Merge "Create new ScanController" into main
diff --git a/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl b/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl
index 34c0c46..1bbf692 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl
@@ -34,5 +34,7 @@
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
void requestMaximumTxDataLength(in BluetoothDevice device);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
- boolean checkPermissionForL2capChannelInfo(in AttributionSource attributionSource);
+ int getL2capLocalChannelId(in ParcelUuid connectionUuid, in AttributionSource attributionSource);
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
+ int getL2capRemoteChannelId(in ParcelUuid connectionUuid, in AttributionSource attributionSource);
}
diff --git a/android/app/jni/com_android_bluetooth_a2dp.cpp b/android/app/jni/com_android_bluetooth_a2dp.cpp
index 7486ccb..12f01d0 100644
--- a/android/app/jni/com_android_bluetooth_a2dp.cpp
+++ b/android/app/jni/com_android_bluetooth_a2dp.cpp
@@ -16,12 +16,12 @@
#define LOG_TAG "BluetoothA2dpServiceJni"
+#include <string.h>
+
+#include <shared_mutex>
+
#include "com_android_bluetooth.h"
#include "hardware/bt_av.h"
-#include "utils/Log.h"
-
-#include <string.h>
-#include <shared_mutex>
namespace android {
static jmethodID method_onConnectionStateChanged;
diff --git a/android/app/jni/com_android_bluetooth_a2dp_sink.cpp b/android/app/jni/com_android_bluetooth_a2dp_sink.cpp
index c4ffb2e..abd8e20 100644
--- a/android/app/jni/com_android_bluetooth_a2dp_sink.cpp
+++ b/android/app/jni/com_android_bluetooth_a2dp_sink.cpp
@@ -23,7 +23,6 @@
#include "com_android_bluetooth.h"
#include "hardware/bt_av.h"
-#include "utils/Log.h"
namespace android {
static jmethodID method_onConnectionStateChanged;
diff --git a/android/app/jni/com_android_bluetooth_avrcp_controller.cpp b/android/app/jni/com_android_bluetooth_avrcp_controller.cpp
index 13c26c1..dcb9fe6 100644
--- a/android/app/jni/com_android_bluetooth_avrcp_controller.cpp
+++ b/android/app/jni/com_android_bluetooth_avrcp_controller.cpp
@@ -16,12 +16,12 @@
#define LOG_TAG "BluetoothAvrcpControllerJni"
+#include <string.h>
+
+#include <shared_mutex>
+
#include "com_android_bluetooth.h"
#include "hardware/bt_rc.h"
-#include "utils/Log.h"
-
-#include <string.h>
-#include <shared_mutex>
namespace android {
static jmethodID method_onConnectionStateChanged;
diff --git a/android/app/jni/com_android_bluetooth_avrcp_target.cpp b/android/app/jni/com_android_bluetooth_avrcp_target.cpp
index 1e9678c..671be39 100644
--- a/android/app/jni/com_android_bluetooth_avrcp_target.cpp
+++ b/android/app/jni/com_android_bluetooth_avrcp_target.cpp
@@ -18,6 +18,7 @@
#include <base/functional/bind.h>
#include <base/functional/callback.h>
+
#include <map>
#include <mutex>
#include <shared_mutex>
@@ -25,7 +26,6 @@
#include "avrcp.h"
#include "com_android_bluetooth.h"
-#include "utils/Log.h"
using namespace bluetooth::avrcp;
diff --git a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
index 6b10df8..f6982c2 100644
--- a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
+++ b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
@@ -32,7 +32,6 @@
#include "com_android_bluetooth.h"
#include "hardware/bt_sock.h"
#include "os/logging/log_adapter.h"
-#include "utils/Log.h"
#include "utils/misc.h"
using bluetooth::Uuid;
@@ -48,6 +47,15 @@
};
} // namespace fmt
+static Uuid from_java_uuid(jlong uuid_msb, jlong uuid_lsb) {
+ std::array<uint8_t, Uuid::kNumBytes128> uu;
+ for (int i = 0; i < 8; i++) {
+ uu[7 - i] = (uuid_msb >> (8 * i)) & 0xFF;
+ uu[15 - i] = (uuid_lsb >> (8 * i)) & 0xFF;
+ }
+ return Uuid::From128BitBE(uu);
+}
+
namespace android {
// Both
@@ -59,6 +67,7 @@
#define BLE_ADDR_RANDOM 0x01
const jint INVALID_FD = -1;
+const jint INVALID_CID = -1;
static jmethodID method_oobDataReceivedCallback;
static jmethodID method_stateChangeCallback;
@@ -2139,6 +2148,42 @@
: JNI_FALSE;
}
+static jint getSocketL2capLocalChannelIdNative(JNIEnv* /* env */,
+ jobject /* obj */,
+ jlong conn_uuid_lsb,
+ jlong conn_uuid_msb) {
+ log::verbose("");
+
+ if (!sBluetoothSocketInterface) {
+ return INVALID_CID;
+ }
+ uint16_t cid;
+ Uuid uuid = from_java_uuid(conn_uuid_msb, conn_uuid_lsb);
+ if (sBluetoothSocketInterface->get_l2cap_local_cid(uuid, &cid) !=
+ BT_STATUS_SUCCESS) {
+ return INVALID_CID;
+ }
+ return (jint)cid;
+}
+
+static jint getSocketL2capRemoteChannelIdNative(JNIEnv* /* env */,
+ jobject /* obj */,
+ jlong conn_uuid_lsb,
+ jlong conn_uuid_msb) {
+ log::verbose("");
+
+ if (!sBluetoothSocketInterface) {
+ return INVALID_CID;
+ }
+ uint16_t cid;
+ Uuid uuid = from_java_uuid(conn_uuid_msb, conn_uuid_lsb);
+ if (sBluetoothSocketInterface->get_l2cap_remote_cid(uuid, &cid) !=
+ BT_STATUS_SUCCESS) {
+ return INVALID_CID;
+ }
+ return (jint)cid;
+}
+
int register_com_android_bluetooth_btservice_AdapterService(JNIEnv* env) {
const JNINativeMethod methods[] = {
{"initNative", "(ZZI[Ljava/lang/String;ZLjava/lang/String;)Z",
@@ -2201,6 +2246,10 @@
(void*)getRemotePbapPceVersionNative},
{"pbapPseDynamicVersionUpgradeIsEnabledNative", "()Z",
(void*)pbapPseDynamicVersionUpgradeIsEnabledNative},
+ {"getSocketL2capLocalChannelIdNative", "(JJ)I",
+ (void*)getSocketL2capLocalChannelIdNative},
+ {"getSocketL2capRemoteChannelIdNative", "(JJ)I",
+ (void*)getSocketL2capRemoteChannelIdNative},
};
const int result = REGISTER_NATIVE_METHODS(
env, "com/android/bluetooth/btservice/AdapterNativeInterface", methods);
diff --git a/android/app/jni/com_android_bluetooth_gatt.cpp b/android/app/jni/com_android_bluetooth_gatt.cpp
index 1622813..a330285 100644
--- a/android/app/jni/com_android_bluetooth_gatt.cpp
+++ b/android/app/jni/com_android_bluetooth_gatt.cpp
@@ -18,7 +18,6 @@
#include <base/functional/bind.h>
#include <base/functional/callback.h>
-#include <cutils/log.h>
#include <string.h>
#include <array>
@@ -32,7 +31,6 @@
#include "rust/cxx.h"
#include "rust/src/gatt/ffi/gatt_shim.h"
#include "src/gatt/ffi.rs.h"
-#include "utils/Log.h"
using bluetooth::Uuid;
diff --git a/android/app/jni/com_android_bluetooth_hid_device.cpp b/android/app/jni/com_android_bluetooth_hid_device.cpp
index e4cff15..fba1cff 100644
--- a/android/app/jni/com_android_bluetooth_hid_device.cpp
+++ b/android/app/jni/com_android_bluetooth_hid_device.cpp
@@ -16,11 +16,10 @@
#define LOG_TAG "BluetoothHidDeviceServiceJni"
+#include <string.h>
+
#include "com_android_bluetooth.h"
#include "hardware/bt_hd.h"
-#include "utils/Log.h"
-
-#include <string.h>
namespace android {
diff --git a/android/app/jni/com_android_bluetooth_pan.cpp b/android/app/jni/com_android_bluetooth_pan.cpp
index 975f18a..28cb632 100644
--- a/android/app/jni/com_android_bluetooth_pan.cpp
+++ b/android/app/jni/com_android_bluetooth_pan.cpp
@@ -16,12 +16,10 @@
#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"
namespace android {
diff --git a/android/app/jni/com_android_bluetooth_sdp.cpp b/android/app/jni/com_android_bluetooth_sdp.cpp
index 206cb44..8b173e5 100644
--- a/android/app/jni/com_android_bluetooth_sdp.cpp
+++ b/android/app/jni/com_android_bluetooth_sdp.cpp
@@ -16,11 +16,10 @@
#define LOG_TAG "BluetoothSdpJni"
+#include <string.h>
+
#include "com_android_bluetooth.h"
#include "hardware/bt_sdp.h"
-#include "utils/Log.h"
-
-#include <string.h>
using bluetooth::Uuid;
diff --git a/android/app/src/com/android/bluetooth/ObexRejectServer.java b/android/app/src/com/android/bluetooth/ObexRejectServer.java
index 415537d..ed50b76 100644
--- a/android/app/src/com/android/bluetooth/ObexRejectServer.java
+++ b/android/app/src/com/android/bluetooth/ObexRejectServer.java
@@ -37,7 +37,6 @@
public class ObexRejectServer extends ServerRequestHandler implements Handler.Callback {
private static final String TAG = "ObexRejectServer";
- private static final boolean V = true;
private final int mResult;
private final HandlerThread mHandlerThread;
private final Handler mMessageHandler;
@@ -64,9 +63,7 @@
// OBEX operation handlers
@Override
public int onConnect(HeaderSet request, HeaderSet reply) {
- if (V) {
- Log.i(TAG, "onConnect() returning error");
- }
+ Log.i(TAG, "onConnect() returning error");
return mResult;
}
@@ -83,9 +80,7 @@
@Override
public boolean handleMessage(Message msg) {
- if (V) {
- Log.i(TAG, "Handling message ID: " + msg.what);
- }
+ Log.i(TAG, "Handling message ID: " + msg.what);
switch (msg.what) {
case MSG_ID_TIMEOUT:
shutdown();
diff --git a/android/app/src/com/android/bluetooth/ObexServerSockets.java b/android/app/src/com/android/bluetooth/ObexServerSockets.java
index e346965..bb4633f 100644
--- a/android/app/src/com/android/bluetooth/ObexServerSockets.java
+++ b/android/app/src/com/android/bluetooth/ObexServerSockets.java
@@ -47,7 +47,6 @@
*/
public class ObexServerSockets {
private static final String TAG = "ObexServerSockets";
- private static final boolean D = true; // TODO: set this to false!
private final IObexConnectionHandler mConHandler;
/* The wrapped sockets */
@@ -108,9 +107,7 @@
@RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
private static ObexServerSockets create(IObexConnectionHandler validator, int rfcommChannel,
int l2capPsm, boolean isSecure) {
- if (D) {
- Log.d(TAG, "create(rfcomm = " + rfcommChannel + ", l2capPsm = " + l2capPsm + ")");
- }
+ Log.d(TAG, "create(rfcomm = " + rfcommChannel + ", l2capPsm = " + l2capPsm + ")");
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
if (bt == null) {
throw new RuntimeException("No bluetooth adapter...");
@@ -154,9 +151,7 @@
break;
}
try {
- if (D) {
- Log.v(TAG, "waiting 300 ms...");
- }
+ Log.v(TAG, "waiting 300 ms...");
Thread.sleep(300);
} catch (InterruptedException e) {
Log.e(TAG, "create() was interrupted");
@@ -167,9 +162,7 @@
}
if (initSocketOK) {
- if (D) {
- Log.d(TAG, "Succeed to create listening sockets ");
- }
+ Log.d(TAG, "Succeed to create listening sockets ");
ObexServerSockets sockets = new ObexServerSockets(validator, rfcommSocket, l2capSocket);
sockets.startAccept();
return sockets;
diff --git a/android/app/src/com/android/bluetooth/Utils.java b/android/app/src/com/android/bluetooth/Utils.java
index 5f9f948..b0f3499 100644
--- a/android/app/src/com/android/bluetooth/Utils.java
+++ b/android/app/src/com/android/bluetooth/Utils.java
@@ -29,6 +29,8 @@
import static android.os.PowerExemptionManager.TEMPORARY_ALLOW_LIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
import static android.permission.PermissionManager.PERMISSION_HARD_DENIED;
+import static com.android.modules.utils.build.SdkLevel.isAtLeastV;
+
import android.Manifest;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -164,6 +166,10 @@
public static boolean isScoManagedByAudioEnabled() {
if (Flags.isScoManagedByAudio()) {
Log.d(TAG, "isScoManagedByAudioEnabled state is: " + isScoManagedByAudioEnabled);
+ if (isScoManagedByAudioEnabled && !isAtLeastV()) {
+ Log.e(TAG, "isScoManagedByAudio should not be enabled before Android V");
+ return false;
+ }
return isScoManagedByAudioEnabled;
}
return false;
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java
index 46896f3..13d1bdd 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java
@@ -36,7 +36,7 @@
* A2DP Codec Configuration setup.
*/
class A2dpCodecConfig {
- private static final String TAG = "A2dpCodecConfig";
+ private static final String TAG = A2dpCodecConfig.class.getSimpleName();
private Context mContext;
private A2dpNativeInterface mA2dpNativeInterface;
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java b/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java
index 6c52b2b..e1c7669 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpNativeInterface.java
@@ -43,8 +43,7 @@
* A2DP Native Interface to/from JNI.
*/
public class A2dpNativeInterface {
- private static final String TAG = "A2dpNativeInterface";
- private static final boolean DBG = true;
+ private static final String TAG = A2dpNativeInterface.class.getSimpleName();
private BluetoothAdapter mAdapter;
private AdapterService mAdapterService;
@@ -200,9 +199,7 @@
event.device = getDevice(address);
event.valueInt = state;
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -211,9 +208,7 @@
event.device = getDevice(address);
event.valueInt = state;
- if (DBG) {
- Log.d(TAG, "onAudioStateChanged: " + event);
- }
+ Log.d(TAG, "onAudioStateChanged: " + event);
sendMessageToService(event);
}
@@ -226,9 +221,7 @@
event.codecStatus = new BluetoothCodecStatus(newCodecConfig,
Arrays.asList(codecsLocalCapabilities),
Arrays.asList(codecsSelectableCapabilities));
- if (DBG) {
- Log.d(TAG, "onCodecConfigChanged: " + event);
- }
+ Log.d(TAG, "onCodecConfigChanged: " + event);
sendMessageToService(event);
}
@@ -236,9 +229,7 @@
A2dpService service = A2dpService.getA2dpService();
if (service != null) {
int enabled = service.getOptionalCodecsEnabled(getDevice(address));
- if (DBG) {
- Log.d(TAG, "isMandatoryCodecPreferred: optional preference " + enabled);
- }
+ Log.d(TAG, "isMandatoryCodecPreferred: optional preference " + enabled);
// Optional codecs are more preferred if possible
return enabled == BluetoothA2dp.OPTIONAL_CODECS_PREF_DISABLED;
} else {
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
index 35c7324..4240f24 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
@@ -82,7 +82,6 @@
*/
public class A2dpService extends ProfileService {
private static final String TAG = A2dpService.class.getSimpleName();
- private static final boolean DBG = true;
// TODO(b/240635097): remove in U
private static final int SOURCE_CODEC_TYPE_OPUS = 6;
@@ -183,9 +182,7 @@
// Step 6: Check if A2DP is in offload mode
mA2dpOffloadEnabled = mAdapterService.isA2dpOffloadEnabled();
- if (DBG) {
- Log.d(TAG, "A2DP offload flag set to " + mA2dpOffloadEnabled);
- }
+ Log.d(TAG, "A2DP offload flag set to " + mA2dpOffloadEnabled);
// Step 7: Register Audio Device callback
mAudioManager.registerAudioDeviceCallback(mAudioManagerAudioDeviceCallback, mHandler);
@@ -265,16 +262,12 @@
}
private static synchronized void setA2dpService(A2dpService instance) {
- if (DBG) {
- Log.d(TAG, "setA2dpService(): set to: " + instance);
- }
+ Log.d(TAG, "setA2dpService(): set to: " + instance);
sA2dpService = instance;
}
public boolean connect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
Log.e(TAG, "Cannot connect to " + device + " : CONNECTION_POLICY_FORBIDDEN");
@@ -323,9 +316,7 @@
* @return true if profile disconnected, false if device not connected over a2dp
*/
public boolean disconnect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
synchronized (mStateMachines) {
A2dpStateMachine sm = mStateMachines.get(device);
@@ -525,9 +516,7 @@
*/
@VisibleForTesting
public boolean setSilenceMode(@NonNull BluetoothDevice device, boolean silence) {
- if (DBG) {
- Log.d(TAG, "setSilenceMode(" + device + "): " + silence);
- }
+ Log.d(TAG, "setSilenceMode(" + device + "): " + silence);
if (silence && Objects.equals(mActiveDevice, device)) {
removeActiveDevice(true);
} else if (!silence && mActiveDevice == null) {
@@ -563,9 +552,7 @@
// returns true since the device is activated even double attempted
return true;
}
- if (DBG) {
- Log.d(TAG, "setActiveDevice(" + device + "): current is " + mActiveDevice);
- }
+ Log.d(TAG, "setActiveDevice(" + device + "): current is " + mActiveDevice);
sm = mStateMachines.get(device);
if (sm == null) {
Log.e(TAG, "setActiveDevice(" + device + "): Cannot set as active: "
@@ -582,9 +569,7 @@
}
// Switch from one A2DP to another A2DP device
- if (DBG) {
- Log.d(TAG, "Switch A2DP devices to " + device + " from " + previousActiveDevice);
- }
+ Log.d(TAG, "Switch A2DP devices to " + device + " from " + previousActiveDevice);
updateLowLatencyAudioSupport(device);
@@ -658,9 +643,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.A2DP,
connectionPolicy)) {
@@ -698,9 +681,7 @@
}
boolean isA2dpPlaying(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "isA2dpPlaying(" + device + ")");
- }
+ Log.d(TAG, "isA2dpPlaying(" + device + ")");
synchronized (mStateMachines) {
A2dpStateMachine sm = mStateMachines.get(device);
if (sm == null) {
@@ -724,9 +705,7 @@
* @return the current codec status
*/
public BluetoothCodecStatus getCodecStatus(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "getCodecStatus(" + device + ")");
- }
+ Log.d(TAG, "getCodecStatus(" + device + ")");
synchronized (mStateMachines) {
if (device == null) {
device = mActiveDevice;
@@ -751,10 +730,8 @@
*/
public void setCodecConfigPreference(BluetoothDevice device,
BluetoothCodecConfig codecConfig) {
- if (DBG) {
- Log.d(TAG, "setCodecConfigPreference(" + device + "): "
- + Objects.toString(codecConfig));
- }
+ Log.d(TAG, "setCodecConfigPreference(" + device + "): "
+ + Objects.toString(codecConfig));
if (device == null) {
device = mActiveDevice;
}
@@ -781,9 +758,7 @@
* active A2DP Bluetooth device.
*/
public void enableOptionalCodecs(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "enableOptionalCodecs(" + device + ")");
- }
+ Log.d(TAG, "enableOptionalCodecs(" + device + ")");
if (device == null) {
device = mActiveDevice;
}
@@ -811,9 +786,7 @@
* active A2DP Bluetooth device.
*/
public void disableOptionalCodecs(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "disableOptionalCodecs(" + device + ")");
- }
+ Log.d(TAG, "disableOptionalCodecs(" + device + ")");
if (device == null) {
device = mActiveDevice;
}
@@ -1021,9 +994,7 @@
+ MAX_A2DP_STATE_MACHINES);
return null;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm =
A2dpStateMachine.make(
device, this, mNativeInterface, mStateMachinesThread.getLooper());
@@ -1055,16 +1026,12 @@
byte[] addressBytes = Utils.getBytesFromAddress(address);
BluetoothDevice device = mAdapterService.getDeviceFromByte(addressBytes);
- if (DBG) {
- Log.d(TAG, " onAudioDevicesAdded: " + device + ", device type: "
- + deviceInfo.getType());
- }
+ Log.d(TAG, " onAudioDevicesAdded: " + device + ", device type: "
+ + deviceInfo.getType());
/* Don't expose already exposed active device */
if (device.equals(mExposedActiveDevice)) {
- if (DBG) {
- Log.d(TAG, " onAudioDevicesAdded: " + device + " is already exposed");
- }
+ Log.d(TAG, " onAudioDevicesAdded: " + device + " is already exposed");
return;
}
@@ -1103,11 +1070,9 @@
mExposedActiveDevice = null;
- if (DBG) {
- Log.d(TAG, " onAudioDevicesRemoved: " + address + ", device type: "
- + deviceInfo.getType()
- + ", mActiveDevice: " + mActiveDevice);
- }
+ Log.d(TAG, " onAudioDevicesRemoved: " + address + ", device type: "
+ + deviceInfo.getType()
+ + ", mActiveDevice: " + mActiveDevice);
}
}
}
@@ -1115,9 +1080,7 @@
@VisibleForTesting
void updateAndBroadcastActiveDevice(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "updateAndBroadcastActiveDevice(" + device + ")");
- }
+ Log.d(TAG, "updateAndBroadcastActiveDevice(" + device + ")");
// Make sure volume has been store before device been remove from active.
if (mFactory.getAvrcpTargetService() != null) {
@@ -1139,9 +1102,7 @@
}
private void broadcastCodecConfig(BluetoothDevice device, BluetoothCodecStatus codecStatus) {
- if (DBG) {
- Log.d(TAG, "broadcastCodecConfig(" + device + "): " + codecStatus);
- }
+ Log.d(TAG, "broadcastCodecConfig(" + device + "): " + codecStatus);
Intent intent = new Intent(BluetoothA2dp.ACTION_CODEC_CONFIG_CHANGED);
intent.putExtra(BluetoothCodecStatus.EXTRA_CODEC_STATUS, codecStatus);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
@@ -1166,9 +1127,7 @@
*/
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
// Remove state machine if the bonding for a device is removed
if (bondState != BluetoothDevice.BOND_NONE) {
return;
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpStateMachine.java b/android/app/src/com/android/bluetooth/a2dp/A2dpStateMachine.java
index 7fc29d1..d170d6d 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpStateMachine.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpStateMachine.java
@@ -74,8 +74,7 @@
import java.util.Scanner;
final class A2dpStateMachine extends StateMachine {
- private static final boolean DBG = true;
- private static final String TAG = "A2dpStateMachine";
+ private static final String TAG = A2dpStateMachine.class.getSimpleName();
static final int CONNECT = 1;
static final int DISCONNECT = 2;
@@ -675,15 +674,17 @@
mCodecStatus = newCodecStatus;
}
- if (DBG) {
+ // The following is a large enough debug operation such that we want to guard it was an
+ // isLoggable check
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "A2DP Codec Config: " + prevCodecConfig + "->"
+ newCodecStatus.getCodecConfig());
for (BluetoothCodecConfig codecConfig :
- newCodecStatus.getCodecsLocalCapabilities()) {
+ newCodecStatus.getCodecsLocalCapabilities()) {
Log.d(TAG, "A2DP Codec Local Capability: " + codecConfig);
}
for (BluetoothCodecConfig codecConfig :
- newCodecStatus.getCodecsSelectableCapabilities()) {
+ newCodecStatus.getCodecsSelectableCapabilities()) {
Log.d(TAG, "A2DP Codec Selectable Capability: " + codecConfig);
}
}
@@ -872,8 +873,6 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java
index 08c1247..944291a 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java
@@ -31,8 +31,7 @@
* A2DP Sink Native Interface to/from JNI.
*/
public class A2dpSinkNativeInterface {
- private static final String TAG = "A2dpSinkNativeInterface";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = A2dpSinkNativeInterface.class.getSimpleName();
private AdapterService mAdapterService;
@GuardedBy("INSTANCE_LOCK")
@@ -171,9 +170,7 @@
public void onConnectionStateChanged(byte[] address, int state) {
StackEvent event =
StackEvent.connectionStateChanged(getDevice(address), state);
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -182,9 +179,7 @@
*/
public void onAudioStateChanged(byte[] address, int state) {
StackEvent event = StackEvent.audioStateChanged(getDevice(address), state);
- if (DBG) {
- Log.d(TAG, "onAudioStateChanged: " + event);
- }
+ Log.d(TAG, "onAudioStateChanged: " + event);
sendMessageToService(event);
}
@@ -194,9 +189,7 @@
public void onAudioConfigChanged(byte[] address, int sampleRate, int channelCount) {
StackEvent event = StackEvent.audioConfigChanged(
getDevice(address), sampleRate, channelCount);
- if (DBG) {
- Log.d(TAG, "onAudioConfigChanged: " + event);
- }
+ Log.d(TAG, "onAudioConfigChanged: " + event);
sendMessageToService(event);
}
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
index c823b76..64c9c9d 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
@@ -49,7 +49,6 @@
*/
public class A2dpSinkService extends ProfileService {
private static final String TAG = A2dpSinkService.class.getSimpleName();
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
private final Map<BluetoothDevice, A2dpSinkStateMachine> mDeviceStateMap =
new ConcurrentHashMap<>(1);
@@ -373,17 +372,12 @@
*/
@RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)
public boolean connect(BluetoothDevice device) {
+ Log.d(TAG, "connect device=" + device);
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
if (device == null) {
throw new IllegalArgumentException("Null device");
}
- if (DBG) {
- StringBuilder sb = new StringBuilder();
- dump(sb);
- Log.d(TAG, " connect device: " + device
- + ", InstanceMap start state: " + sb.toString());
- }
if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
Log.w(TAG, "Connection not allowed: <" + device
+ "> is CONNECTION_POLICY_FORBIDDEN");
@@ -408,13 +402,7 @@
* @return true if disconnect is successful, false otherwise.
*/
public boolean disconnect(BluetoothDevice device) {
- if (DBG) {
- StringBuilder sb = new StringBuilder();
- dump(sb);
- Log.d(TAG, "A2DP disconnect device: " + device
- + ", InstanceMap start state: " + sb.toString());
- }
-
+ Log.d(TAG, "disconnect device=" + device);
if (device == null) {
throw new IllegalArgumentException("Null device");
}
@@ -475,21 +463,21 @@
}
List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
- if (DBG) Log.d(TAG, "getDevicesMatchingConnectionStates" + Arrays.toString(states));
+ Log.d(TAG, "getDevicesMatchingConnectionStates(states=" + Arrays.toString(states) + ")");
List<BluetoothDevice> deviceList = new ArrayList<>();
BluetoothDevice[] bondedDevices = mAdapterService.getBondedDevices();
int connectionState;
for (BluetoothDevice device : bondedDevices) {
connectionState = getConnectionState(device);
- if (DBG) Log.d(TAG, "Device: " + device + "State: " + connectionState);
+ Log.d(TAG, "Device: " + device + "State: " + connectionState);
for (int i = 0; i < states.length; i++) {
if (connectionState == states[i]) {
deviceList.add(device);
}
}
}
- if (DBG) Log.d(TAG, deviceList.toString());
- Log.d(TAG, "GetDevicesDone");
+ Log.d(TAG, "getDevicesMatchingConnectionStates(" + Arrays.toString(states) + "): Found "
+ + deviceList.toString());
return deviceList;
}
@@ -528,9 +516,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.A2DP_SINK,
connectionPolicy)) {
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachine.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachine.java
index d7cc755..a890b34 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachine.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachine.java
@@ -38,7 +38,6 @@
class A2dpSinkStateMachine extends StateMachine {
private static final String TAG = A2dpSinkStateMachine.class.getSimpleName();
- static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
// 0->99 Events from Outside
@VisibleForTesting static final int CONNECT = 1;
@@ -75,7 +74,6 @@
mDeviceAddress = Utils.getByteAddress(mDevice);
mService = service;
mNativeInterface = nativeInterface;
- if (DBG) Log.d(TAG, device.toString());
mDisconnected = new Disconnected();
mConnecting = new Connecting();
@@ -88,6 +86,7 @@
addState(mDisconnecting);
setInitialState(mDisconnected);
+ Log.d(TAG, "[" + mDevice + "] State machine created");
}
/**
@@ -141,13 +140,14 @@
@Override
protected void unhandledMessage(Message msg) {
- Log.w(TAG, "unhandledMessage in state " + getCurrentState() + "msg.what=" + msg.what);
+ Log.w(TAG, "[" + mDevice + "] unhandledMessage state=" + getCurrentState() + ", msg.what="
+ + msg.what);
}
class Disconnected extends State {
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Disconnected");
+ Log.d(TAG, "[" + mDevice + "] Enter Disconnected");
if (mMostRecentState != BluetoothProfile.STATE_DISCONNECTED) {
sendMessage(CLEANUP);
}
@@ -161,7 +161,7 @@
processStackEvent((StackEvent) message.obj);
return true;
case CONNECT:
- if (DBG) Log.d(TAG, "Connect");
+ Log.d(TAG, "[" + mDevice + "] Connect");
transitionTo(mConnecting);
return true;
case CLEANUP:
@@ -179,8 +179,8 @@
case StackEvent.CONNECTION_STATE_CONNECTING:
if (mService.getConnectionPolicy(mDevice)
== BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
- Log.w(TAG, "Ignore incoming connection, profile is"
- + " turned off for " + mDevice);
+ Log.w(TAG, "[" + mDevice + "] Ignore incoming connection, profile"
+ + " is turned off");
mNativeInterface.disconnectA2dpSink(mDevice);
} else {
mConnecting.mIncomingConnection = true;
@@ -203,7 +203,7 @@
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Connecting");
+ Log.d(TAG, "[" + mDevice + "] Enter Connecting");
onConnectionStateChanged(BluetoothProfile.STATE_CONNECTING);
sendMessageDelayed(CONNECT_TIMEOUT, CONNECT_TIMEOUT_MS);
@@ -224,7 +224,8 @@
transitionTo(mDisconnected);
return true;
case DISCONNECT:
- Log.d(TAG, "Received disconnect message while connecting. deferred");
+ Log.d(TAG, "[" + mDevice + "] Received disconnect message while connecting."
+ + "deferred");
deferMessage(message);
return true;
}
@@ -255,7 +256,7 @@
class Connected extends State {
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Connected");
+ Log.d(TAG, "[" + mDevice + "] Enter Connected");
onConnectionStateChanged(BluetoothProfile.STATE_CONNECTED);
}
@@ -296,7 +297,7 @@
protected class Disconnecting extends State {
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Disconnecting");
+ Log.d(TAG, "[" + mDevice + "] Enter Disconnecting");
onConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING);
transitionTo(mDisconnected);
}
@@ -309,10 +310,7 @@
if (currentState == BluetoothProfile.STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.A2DP_SINK);
}
- if (DBG) {
- Log.d(TAG, "Connection state " + mDevice + ": " + mMostRecentState + "->"
- + currentState);
- }
+ Log.d(TAG, "[" + mDevice + "] Connection state: " + mMostRecentState + "->" + currentState);
Intent intent = new Intent(BluetoothA2dpSink.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, mMostRecentState);
intent.putExtra(BluetoothProfile.EXTRA_STATE, currentState);
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandler.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandler.java
index de0d8d1..754ec28 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandler.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkStreamHandler.java
@@ -48,8 +48,7 @@
* restored.
*/
public class A2dpSinkStreamHandler extends Handler {
- private static final String TAG = "A2dpSinkStreamHandler";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = A2dpSinkStreamHandler.class.getSimpleName();
// Configuration Variables
private static final int DEFAULT_DUCK_PERCENT = 25;
@@ -93,9 +92,7 @@
private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
- if (DBG) {
- Log.d(TAG, "onAudioFocusChangeListener focuschange " + focusChange);
- }
+ Log.d(TAG, "onAudioFocusChangeListener(focusChange= " + focusChange + ")");
A2dpSinkStreamHandler.this.obtainMessage(AUDIO_FOCUS_CHANGE, focusChange)
.sendToTarget();
}
@@ -132,10 +129,7 @@
@Override
public void handleMessage(Message message) {
- if (DBG) {
- Log.d(TAG, " process message: " + message.what);
- Log.d(TAG, " current audioFocus state = " + mAudioFocus);
- }
+ Log.d(TAG, "process message: " + message.what + ", audioFocus=" + mAudioFocus);
switch (message.what) {
case SRC_STR_START:
mStreamAvailable = true;
@@ -183,10 +177,8 @@
case AUDIO_FOCUS_CHANGE:
final int focusChangeCode = (int) message.obj;
- if (DBG) {
- Log.d(TAG, "New audioFocus = " + focusChangeCode
- + " Previous audio focus = " + mAudioFocus);
- }
+ Log.d(TAG, "New audioFocus = " + focusChangeCode
+ + " Previous audio focus = " + mAudioFocus);
mAudioFocus = focusChangeCode;
// message.obj is the newly granted audio focus.
switch (mAudioFocus) {
@@ -204,9 +196,7 @@
duckPercent = DEFAULT_DUCK_PERCENT;
}
float duckRatio = (duckPercent / 100.0f);
- if (DBG) {
- Log.d(TAG, "Setting reduce gain on transient loss gain=" + duckRatio);
- }
+ Log.d(TAG, "Setting reduce gain on transient loss gain=" + duckRatio);
setFluorideAudioTrackGain(duckRatio);
break;
@@ -240,14 +230,14 @@
* Utility functions.
*/
private void requestAudioFocusIfNone() {
- if (DBG) Log.d(TAG, "requestAudioFocusIfNone()");
+ Log.d(TAG, "requestAudioFocusIfNone()");
if (mAudioFocus != AudioManager.AUDIOFOCUS_GAIN) {
requestAudioFocus();
}
}
private synchronized int requestAudioFocus() {
- if (DBG) Log.d(TAG, "requestAudioFocus()");
+ Log.d(TAG, "requestAudioFocus()");
// Bluetooth A2DP may carry Music, Audio Books, Navigation, or other sounds so mark content
// type unknown.
AudioAttributes streamAttributes =
@@ -284,8 +274,7 @@
* chosen to use it.
*/
private synchronized void requestMediaKeyFocus() {
- if (DBG) Log.d(TAG, "requestMediaKeyFocus()");
-
+ Log.d(TAG, "requestMediaKeyFocus()");
if (mMediaPlayer == null) {
AudioAttributes attrs = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
@@ -310,7 +299,7 @@
}
private synchronized void abandonAudioFocus() {
- if (DBG) Log.d(TAG, "abandonAudioFocus()");
+ Log.d(TAG, "abandonAudioFocus()");
stopFluorideStreaming();
mAudioManager.abandonAudioFocus(mAudioFocusListener);
mAudioFocus = AudioManager.AUDIOFOCUS_NONE;
@@ -321,7 +310,7 @@
* we're no longer playing audio.
*/
private synchronized void releaseMediaKeyFocus() {
- if (DBG) Log.d(TAG, "releaseMediaKeyFocus()");
+ Log.d(TAG, "releaseMediaKeyFocus()");
if (mMediaPlayer == null) {
return;
}
@@ -359,5 +348,4 @@
return mA2dpSinkService.getResources()
.getBoolean(R.bool.a2dp_sink_automatically_request_audio_focus);
}
-
}
diff --git a/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java b/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java
index bae327d..4e11343 100644
--- a/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java
+++ b/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java
@@ -43,7 +43,6 @@
*/
public class BrowsablePlayerConnector extends Handler {
private static final String TAG = "AvrcpBrowsablePlayerConnector";
- private static final boolean DEBUG = true;
private static final long CONNECT_TIMEOUT_MS = 10000; // Time in ms to wait for a connection
private static final int MSG_GET_FOLDER_ITEMS_CB = 0;
@@ -91,11 +90,9 @@
newConnector.mPendingPlayers.add(player);
player.connect((int status, BrowsedPlayerWrapper wrapper) -> {
// Use the handler to avoid concurrency issues
- if (DEBUG) {
- Log.d(TAG, "Browse player callback called: package="
- + info.serviceInfo.packageName
- + " : status=" + status);
- }
+ Log.d(TAG, "Browse player callback called: package="
+ + info.serviceInfo.packageName
+ + " : status=" + status);
newConnector.obtainMessage(MSG_CONNECT_CB, status, 0, wrapper).sendToTarget();
});
}
@@ -111,7 +108,7 @@
private void removePendingPlayers() {
for (BrowsedPlayerWrapper wrapper : mPendingPlayers) {
- if (DEBUG) Log.d(TAG, "Disconnecting " + wrapper.getPackageName());
+ Log.d(TAG, "Disconnecting " + wrapper.getPackageName());
wrapper.disconnect();
}
mPendingPlayers.clear();
@@ -127,7 +124,7 @@
@Override
public void handleMessage(Message msg) {
- if (DEBUG) Log.d(TAG, "Received a message: msg.what=" + msg.what);
+ Log.d(TAG, "Received a message: msg.what=" + msg.what);
switch(msg.what) {
case MSG_GET_FOLDER_ITEMS_CB: {
int status = msg.arg1;
@@ -163,9 +160,7 @@
}
// Check to see if the root folder has any items
- if (DEBUG) {
- Log.i(TAG, "Checking root contents for " + wrapper.getPackageName());
- }
+ Log.i(TAG, "Checking root contents for " + wrapper.getPackageName());
wrapper.getFolderItems(wrapper.getRootId(),
(int status, String mediaId, List<ListItem> results) -> {
// Send the response as a message so that it is properly
diff --git a/android/app/src/com/android/bluetooth/audio_util/BrowsedPlayerWrapper.java b/android/app/src/com/android/bluetooth/audio_util/BrowsedPlayerWrapper.java
index 8bf62cb..19c6f89 100644
--- a/android/app/src/com/android/bluetooth/audio_util/BrowsedPlayerWrapper.java
+++ b/android/app/src/com/android/bluetooth/audio_util/BrowsedPlayerWrapper.java
@@ -38,8 +38,7 @@
* Right now this is ok because the BrowsablePlayerConnector will handle timeouts.
*/
class BrowsedPlayerWrapper {
- private static final String TAG = "BrowsedPlayerWrapper";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = BrowsedPlayerWrapper.class.getSimpleName();
enum ConnectionState {
DISCONNECTED,
@@ -152,7 +151,7 @@
* currently open.
*/
void disconnect() {
- if (DEBUG) Log.d(TAG, "disconnect: Disconnecting from " + mPackageName);
+ Log.d(TAG, "disconnect: Disconnecting from " + mPackageName);
mWrappedBrowser.disconnect();
clearCallback();
}
@@ -165,7 +164,7 @@
}
mCallback = callback;
}
- if (DEBUG) Log.d(TAG, "Set mCallback, connecting to " + mPackageName);
+ Log.d(TAG, "Set mCallback, connecting to " + mPackageName);
mWrappedBrowser.connect();
return true;
}
@@ -179,7 +178,7 @@
}
callback = mCallback;
}
- if (DEBUG) Log.d(TAG, "Executing callback");
+ Log.d(TAG, "Executing callback");
callback.run(status, player);
}
@@ -187,7 +186,7 @@
synchronized (mCallbackLock) {
mCallback = null;
}
- if (DEBUG) Log.d(TAG, "mCallback = null");
+ Log.d(TAG, "mCallback = null");
}
public String getPackageName() {
@@ -205,9 +204,9 @@
* @return False if any other requests are being serviced, True otherwise
*/
public boolean playItem(String mediaId) {
- if (DEBUG) Log.d(TAG, "playItem: Play item from media ID: " + mediaId);
+ Log.d(TAG, "playItem: Play item from media ID: " + mediaId);
return setCallbackAndConnect((int status, BrowsedPlayerWrapper wrapper) -> {
- if (DEBUG) Log.d(TAG, "playItem: Connected to browsable player " + mPackageName);
+ Log.d(TAG, "playItem: Connected to browsable player " + mPackageName);
MediaController controller = MediaControllerFactory.make(mContext,
wrapper.mWrappedBrowser.getSessionToken());
MediaController.TransportControls ctrl = controller.getTransportControls();
@@ -249,7 +248,7 @@
+ "with null browse callback");
}
- if (DEBUG) Log.d(TAG, "getFolderItems: Connecting to browsable player: " + mPackageName);
+ Log.d(TAG, "getFolderItems: Connecting to browsable player: " + mPackageName);
return setCallbackAndConnect((int status, BrowsedPlayerWrapper wrapper) -> {
Log.i(TAG, "getFolderItems: Connected to browsable player: " + mPackageName);
if (status != STATUS_SUCCESS) {
@@ -390,7 +389,7 @@
@Override
public void onPlaybackStateChanged(@Nullable PlaybackState state) {
- if (DEBUG) Log.d(TAG, "MediaPlayback: " + mPackageName + " -> " + state.toString());
+ Log.d(TAG, "MediaPlayback: " + mPackageName + " -> " + state.toString());
if (state.getState() == PlaybackState.STATE_PLAYING) {
mTimeoutHandler.removeMessages(TimeoutHandler.MSG_TIMEOUT);
mPlaybackCallback.run(STATUS_SUCCESS);
@@ -424,9 +423,7 @@
@Override
public void onChildrenLoaded(String parentId, List<MediaItem> children) {
- if (DEBUG) {
- Log.d(TAG, "onChildrenLoaded: mediaId=" + parentId + " size= " + children.size());
- }
+ Log.d(TAG, "onChildrenLoaded: mediaId=" + parentId + " size= " + children.size());
if (mBrowseCallback == null) {
Log.w(TAG, "onChildrenLoaded: " + mPackageName
@@ -441,10 +438,8 @@
ArrayList<ListItem> return_list = new ArrayList<ListItem>();
for (MediaItem item : children) {
- if (DEBUG) {
- Log.d(TAG, "onChildrenLoaded: Child=\"" + item.toString()
- + "\", ID=\"" + item.getMediaId() + "\"");
- }
+ Log.d(TAG, "onChildrenLoaded: Child=\"" + item.toString()
+ + "\", ID=\"" + item.getMediaId() + "\"");
if (item.isBrowsable()) {
CharSequence titleCharSequence = item.getDescription().getTitle();
diff --git a/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java b/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java
index 102c62f..efb58f5 100644
--- a/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java
+++ b/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java
@@ -28,7 +28,6 @@
*/
class GPMWrapper extends MediaPlayerWrapper {
private static final String TAG = "AvrcpGPMWrapper";
- private static final boolean DEBUG = true;
GPMWrapper(Context context, MediaController controller, Looper looper) {
super(context, controller, looper);
@@ -54,11 +53,9 @@
Metadata qitem = Util.toMetadata(mContext, currItem);
Metadata mdata = Util.toMetadata(mContext, getMetadata());
if (currItem == null || !qitem.equals(mdata)) {
- if (DEBUG) {
- Log.d(TAG, "Metadata currently out of sync for Google Play Music");
- Log.d(TAG, " └ Current queueItem: " + qitem);
- Log.d(TAG, " └ Current metadata : " + mdata);
- }
+ Log.d(TAG, "Metadata currently out of sync for Google Play Music");
+ Log.d(TAG, " └ Current queueItem: " + qitem);
+ Log.d(TAG, " └ Current metadata : " + mdata);
return false;
}
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 4c2ab41..d2c409f 100644
--- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
+++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
@@ -63,8 +63,7 @@
* player would effectively cause player switch by sending a play command to that player.
*/
public class MediaPlayerList {
- private static final String TAG = "MediaPlayerList";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = MediaPlayerList.class.getSimpleName();
static boolean sTesting = false;
private static final String PACKAGE_SCHEME = "package";
@@ -767,7 +766,7 @@
|| action.equals(Intent.ACTION_PACKAGE_CHANGED)) {
String packageName = intent.getData().getSchemeSpecificPart();
if (packageName != null) {
- if (DEBUG) Log.d(TAG, "Name of package changed: " + packageName);
+ Log.d(TAG, "Name of package changed: " + packageName);
// TODO (apanicke): Handle either updating or adding the new package.
// Check if its browsable and send the UIDS changed to update the
// root folder
@@ -968,8 +967,6 @@
}
private static void d(String message) {
- if (DEBUG) {
- Log.d(TAG, message);
- }
+ Log.d(TAG, message);
}
}
diff --git a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java
index 256326d..2dd965d 100644
--- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java
+++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java
@@ -42,7 +42,6 @@
*/
public class MediaPlayerWrapper {
private static final String TAG = "AudioMediaPlayerWrapper";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
static boolean sTesting = false;
private static final int PLAYBACK_STATE_CHANGE_EVENT_LOGGER_SIZE = 5;
private static final String PLAYBACK_STATE_CHANGE_LOGGER_EVENT_TITLE =
@@ -275,11 +274,9 @@
Metadata qitem = Util.toMetadata(mContext, currItem);
Metadata mdata = Util.toMetadata(mContext, getMetadata());
if (currItem == null || !qitem.equals(mdata)) {
- if (DEBUG) {
- Log.d(TAG, "Metadata currently out of sync for " + mPackageName);
- Log.d(TAG, " └ Current queueItem: " + qitem);
- Log.d(TAG, " └ Current metadata : " + mdata);
- }
+ Log.d(TAG, "Metadata currently out of sync for " + mPackageName);
+ Log.d(TAG, " └ Current queueItem: " + qitem);
+ Log.d(TAG, " └ Current metadata : " + mdata);
// Some player do not provide full song info in queue item, allow case
// that only title and artist match.
@@ -469,10 +466,8 @@
return;
}
- if (DEBUG) {
- Log.v(TAG, "onMetadataChanged(): " + mPackageName + " : "
- + Util.toMetadata(mContext, mediaMetadata));
- }
+ Log.v(TAG, "onMetadataChanged(): " + mPackageName + " : "
+ + Util.toMetadata(mContext, mediaMetadata));
if (!Objects.equals(mediaMetadata, getMetadata())) {
e("The callback metadata doesn't match controller metadata");
@@ -549,7 +544,9 @@
return;
}
- if (DEBUG) {
+ // The following is a large enough debug operation such that we want to guard it was an
+ // isLoggable check
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
for (int i = 0; i < current_queue.size(); i++) {
Log.d(TAG, " └ QueueItem(" + i + "): " + current_queue.get(i));
}
@@ -601,7 +598,7 @@
}
private void d(String message) {
- if (DEBUG) Log.d(TAG, mPackageName + ": " + message);
+ Log.d(TAG, mPackageName + ": " + message);
}
@VisibleForTesting
diff --git a/android/app/src/com/android/bluetooth/audio_util/PlayerSettingsManager.java b/android/app/src/com/android/bluetooth/audio_util/PlayerSettingsManager.java
index bbc08cb..1da1364 100644
--- a/android/app/src/com/android/bluetooth/audio_util/PlayerSettingsManager.java
+++ b/android/app/src/com/android/bluetooth/audio_util/PlayerSettingsManager.java
@@ -27,7 +27,7 @@
* Manager class for player apps.
*/
public class PlayerSettingsManager {
- private static final String TAG = "PlayerSettingsManager";
+ private static final String TAG = PlayerSettingsManager.class.getSimpleName();
private final MediaPlayerList mMediaPlayerList;
private final AvrcpTargetService mService;
diff --git a/android/app/src/com/android/bluetooth/audio_util/helpers/Util.java b/android/app/src/com/android/bluetooth/audio_util/helpers/Util.java
index beee390..2612058 100644
--- a/android/app/src/com/android/bluetooth/audio_util/helpers/Util.java
+++ b/android/app/src/com/android/bluetooth/audio_util/helpers/Util.java
@@ -30,7 +30,6 @@
class Util {
public static String TAG = "audio_util.Util";
- public static boolean DEBUG = false;
// TODO (apanicke): Remove this prefix later, for now it makes debugging easier.
public static final String NOW_PLAYING_PREFIX = "NowPlayingId";
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java
index a421e27..e495c4a 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java
@@ -35,8 +35,7 @@
* A class responsible for handling requests from a specific client connection
*/
public class AvrcpBipObexServer extends ServerRequestHandler {
- private static final String TAG = "AvrcpBipObexServer";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpBipObexServer.class.getSimpleName();
private final AvrcpCoverArtService mAvrcpCoverArtService;
@@ -358,8 +357,6 @@
}
private void debug(String msg) {
- if (DEBUG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java
index f043038..867706d 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java
@@ -37,8 +37,7 @@
* BIP OBEX server that handles requests to get AVRCP cover artwork.
*/
public class AvrcpCoverArtService {
- private static final String TAG = "AvrcpCoverArtService";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpCoverArtService.class.getSimpleName();
private static final int COVER_ART_STORAGE_MAX_ITEMS = 32;
@@ -288,9 +287,7 @@
* Print a message to DEBUG if debug output is enabled
*/
private void debug(String msg) {
- if (DEBUG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
/**
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java
index fde4d3b..3348da9 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java
@@ -26,8 +26,7 @@
* A class abstracting the storage method of cover art images
*/
final class AvrcpCoverArtStorage {
- private static final String TAG = "AvrcpCoverArtStorage";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpCoverArtStorage.class.getSimpleName();
private final Object mHandlesLock = new Object();
private int mNextImageHandle = 0;
@@ -198,9 +197,7 @@
* Print a message to DEBUG if debug output is enabled
*/
private void debug(String msg) {
- if (DEBUG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
/**
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpNativeInterface.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpNativeInterface.java
index 3bdaba6..0afdeac 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpNativeInterface.java
@@ -38,8 +38,7 @@
* data.
*/
public class AvrcpNativeInterface {
- private static final String TAG = "AvrcpNativeInterface";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpNativeInterface.class.getSimpleName();
@GuardedBy("INSTANCE_LOCK")
private static AvrcpNativeInterface sInstance;
@@ -399,8 +398,6 @@
private native void sendPlayerSettingsNative(byte[] attributes, byte[] values);
private static void d(String msg) {
- if (DEBUG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
index 1d8ffe3..687aca9 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
@@ -55,8 +55,7 @@
/** Provides Bluetooth AVRCP Target profile as a service in the Bluetooth application. */
public class AvrcpTargetService extends ProfileService {
- private static final String TAG = "AvrcpTargetService";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpTargetService.class.getSimpleName();
private static final int MEDIA_KEY_EVENT_LOGGER_SIZE = 20;
private static final String MEDIA_KEY_EVENT_LOGGER_TITLE = "BTAudio Media Key Events";
@@ -116,10 +115,8 @@
boolean state = !MediaPlayerWrapper.playstateEquals(mCurrentData.state, data.state);
boolean queue = !Objects.equals(mCurrentData.queue, data.queue);
- if (DEBUG) {
- Log.d(TAG, "onMediaUpdated: track_changed=" + metadata
- + " state=" + state + " queue=" + queue);
- }
+ Log.d(TAG, "onMediaUpdated: track_changed=" + metadata
+ + " state=" + state + " queue=" + queue);
mCurrentData = data;
mNativeInterface.sendMediaUpdate(metadata, state, queue);
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java
index c1eaccf..d3bd59e 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java
@@ -36,8 +36,7 @@
import java.util.Objects;
class AvrcpVolumeManager extends AudioDeviceCallback {
- public static final String TAG = "AvrcpVolumeManager";
- public static final boolean DEBUG = true;
+ public static final String TAG = AvrcpVolumeManager.class.getSimpleName();
// All volumes are stored at system volume values, not AVRCP values
private static final String VOLUME_MAP = "bluetooth_volume_map";
@@ -320,8 +319,6 @@
}
static void d(String msg) {
- if (DEBUG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java b/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java
index 0ace6cb..d20da98 100644
--- a/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java
+++ b/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java
@@ -39,8 +39,7 @@
* All return values are ready to use by a BIP server.
*/
public class CoverArt {
- private static final String TAG = "CoverArt";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = CoverArt.class.getSimpleName();
private static final BipPixel PIXEL_THUMBNAIL = BipPixel.createFixed(200, 200);
private String mImageHandle = null;
@@ -204,9 +203,7 @@
* Print a message to DEBUG if debug output is enabled
*/
private void debug(String msg) {
- if (DEBUG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
/**
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java
index 99605c6..3b54b09 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java
@@ -45,8 +45,7 @@
* disconnection has occurred, please create a new client.
*/
public class AvrcpBipClient {
- private static final String TAG = "AvrcpBipClient";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpBipClient.class.getSimpleName();
// AVRCP Controller BIP Image Initiator/Cover Art UUID - AVRCP 1.6 Section 5.14.2.1
private static final byte[] BLUETOOTH_UUID_AVRCP_COVER_ART = new byte[] {
@@ -466,16 +465,14 @@
* Print to debug if debug is enabled for this class
*/
private void debug(String msg) {
- if (DBG) {
- Log.d(TAG, "[" + mDevice + "] " + msg);
- }
+ Log.d(TAG, "[" + mDevice + "] " + msg);
}
/**
* Print to warn
*/
private void warn(String msg) {
- Log.w(TAG, "[" + mDevice+ "] " + msg);
+ Log.w(TAG, "[" + mDevice + "] " + msg);
}
/**
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java
index 38def99..778a7ee 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java
@@ -30,8 +30,6 @@
/** Provides Bluetooth AVRCP Controller native interface for the AVRCP Controller service */
public class AvrcpControllerNativeInterface {
static final String TAG = AvrcpControllerNativeInterface.class.getSimpleName();
- static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
private AvrcpControllerService mAvrcpController;
@@ -123,14 +121,12 @@
void onConnectionStateChanged(
boolean remoteControlConnected, boolean browsingConnected, byte[] address) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(
- TAG,
- "onConnectionStateChanged: "
- + (" remoteControlConnected=" + remoteControlConnected)
- + (" browsingConnected=" + browsingConnected)
- + (" device=" + device));
- }
+ Log.d(
+ TAG,
+ "onConnectionStateChanged: "
+ + (" remoteControlConnected=" + remoteControlConnected)
+ + (" browsingConnected=" + browsingConnected)
+ + (" device=" + device));
mAvrcpController.onConnectionStateChanged(
remoteControlConnected, browsingConnected, device);
@@ -140,9 +136,7 @@
@VisibleForTesting
void getRcPsm(byte[] address, int psm) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "getRcPsm: device=" + device + " psm=" + psm);
- }
+ Log.d(TAG, "getRcPsm: device=" + device + " psm=" + psm);
mAvrcpController.getRcPsm(device, psm);
}
@@ -150,9 +144,7 @@
// Called by JNI to report remote Player's capabilities
void handlePlayerAppSetting(byte[] address, byte[] playerAttribRsp, int rspLen) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handlePlayerAppSetting: device=" + device + " rspLen=" + rspLen);
- }
+ Log.d(TAG, "handlePlayerAppSetting: device=" + device + " rspLen=" + rspLen);
mAvrcpController.handlePlayerAppSetting(device, playerAttribRsp, rspLen);
}
@@ -160,9 +152,7 @@
@VisibleForTesting
void onPlayerAppSettingChanged(byte[] address, byte[] playerAttribRsp, int rspLen) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "onPlayerAppSettingChanged: device=" + device);
- }
+ Log.d(TAG, "onPlayerAppSettingChanged: device=" + device);
mAvrcpController.onPlayerAppSettingChanged(device, playerAttribRsp, rspLen);
}
@@ -170,9 +160,7 @@
// Called by JNI when remote wants to set absolute volume.
void handleSetAbsVolume(byte[] address, byte absVol, byte label) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleSetAbsVolume: device=" + device);
- }
+ Log.d(TAG, "handleSetAbsVolume: device=" + device);
mAvrcpController.handleSetAbsVolume(device, absVol, label);
}
@@ -180,9 +168,7 @@
// Called by JNI when remote wants to receive absolute volume notifications.
void handleRegisterNotificationAbsVol(byte[] address, byte label) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleRegisterNotificationAbsVol: device=" + device);
- }
+ Log.d(TAG, "handleRegisterNotificationAbsVol: device=" + device);
mAvrcpController.handleRegisterNotificationAbsVol(device, label);
}
@@ -190,9 +176,7 @@
// Called by JNI when a track changes and local AvrcpController is registered for updates.
void onTrackChanged(byte[] address, byte numAttributes, int[] attributes, String[] attribVals) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "onTrackChanged: device=" + device);
- }
+ Log.d(TAG, "onTrackChanged: device=" + device);
mAvrcpController.onTrackChanged(device, numAttributes, attributes, attribVals);
}
@@ -200,9 +184,7 @@
// Called by JNI periodically based upon timer to update play position
void onPlayPositionChanged(byte[] address, int songLen, int currSongPosition) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "onPlayPositionChanged: device=" + device + " pos=" + currSongPosition);
- }
+ Log.d(TAG, "onPlayPositionChanged: device=" + device + " pos=" + currSongPosition);
mAvrcpController.onPlayPositionChanged(device, songLen, currSongPosition);
}
@@ -210,9 +192,7 @@
// Called by JNI on changes of play status
void onPlayStatusChanged(byte[] address, byte playStatus) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "onPlayStatusChanged: device=" + device + " playStatus=" + playStatus);
- }
+ Log.d(TAG, "onPlayStatusChanged: device=" + device + " playStatus=" + playStatus);
mAvrcpController.onPlayStatusChanged(device, toPlaybackStateFromJni(playStatus));
}
@@ -220,27 +200,23 @@
// Browsing related JNI callbacks.
void handleGetFolderItemsRsp(byte[] address, int status, AvrcpItem[] items) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(
- TAG,
- "handleGetFolderItemsRsp:"
- + (" device=" + device)
- + (" status=" + status)
- + (" NumberOfItems=" + items.length));
- }
+ Log.d(
+ TAG,
+ "handleGetFolderItemsRsp:"
+ + (" device=" + device)
+ + (" status=" + status)
+ + (" NumberOfItems=" + items.length));
mAvrcpController.handleGetFolderItemsRsp(device, status, items);
}
void handleGetPlayerItemsRsp(byte[] address, AvrcpPlayer[] items) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(
- TAG,
- "handleGetFolderItemsRsp:"
- + (" device=" + device)
- + (" NumberOfItems=" + items.length));
- }
+ Log.d(
+ TAG,
+ "handleGetFolderItemsRsp:"
+ + (" device=" + device)
+ + (" NumberOfItems=" + items.length));
mAvrcpController.handleGetPlayerItemsRsp(device, Arrays.asList(items));
}
@@ -249,17 +225,15 @@
static AvrcpItem createFromNativeMediaItem(
byte[] address, long uid, int type, String name, int[] attrIds, String[] attrVals) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (VDBG) {
- Log.d(
- TAG,
- "createFromNativeMediaItem:"
- + (" device=" + device)
- + (" uid=" + uid)
- + (" type=" + type)
- + (" name=" + name)
- + (" attrids=" + Arrays.toString(attrIds))
- + (" attrVals=" + Arrays.toString(attrVals)));
- }
+ Log.d(
+ TAG,
+ "createFromNativeMediaItem:"
+ + (" device=" + device)
+ + (" uid=" + uid)
+ + (" type=" + type)
+ + (" name=" + name)
+ + (" attrids=" + Arrays.toString(attrIds))
+ + (" attrVals=" + Arrays.toString(attrVals)));
return new AvrcpItem.Builder()
.fromAvrcpAttributeArray(attrIds, attrVals)
@@ -275,16 +249,14 @@
static AvrcpItem createFromNativeFolderItem(
byte[] address, long uid, int type, String name, int playable) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (VDBG) {
- Log.d(
- TAG,
- "createFromNativeFolderItem:"
- + (" device=" + device)
- + (" uid=" + uid)
- + (" type=" + type)
- + (" name=" + name)
- + (" playable=" + playable));
- }
+ Log.d(
+ TAG,
+ "createFromNativeFolderItem:"
+ + (" device=" + device)
+ + (" uid=" + uid)
+ + (" type=" + type)
+ + (" name=" + name)
+ + (" playable=" + playable));
return new AvrcpItem.Builder()
.setDevice(device)
@@ -306,16 +278,14 @@
int playStatus,
int playerType) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (VDBG) {
- Log.d(
- TAG,
- "createFromNativePlayerItem:"
- + (" device=" + device)
- + (" name=" + name)
- + (" transportFlags=" + Arrays.toString(transportFlags))
- + (" playStatus=" + playStatus)
- + (" playerType=" + playerType));
- }
+ Log.d(
+ TAG,
+ "createFromNativePlayerItem:"
+ + (" device=" + device)
+ + (" name=" + name)
+ + (" transportFlags=" + Arrays.toString(transportFlags))
+ + (" playStatus=" + playStatus)
+ + (" playerType=" + playerType));
return new AvrcpPlayer.Builder()
.setDevice(device)
@@ -328,53 +298,41 @@
void handleChangeFolderRsp(byte[] address, int count) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleChangeFolderRsp: device=" + device + " count=" + count);
- }
+ Log.d(TAG, "handleChangeFolderRsp: device=" + device + " count=" + count);
mAvrcpController.handleChangeFolderRsp(device, count);
}
void handleSetBrowsedPlayerRsp(byte[] address, int items, int depth) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleSetBrowsedPlayerRsp: device=" + device + " depth=" + depth);
- }
+ Log.d(TAG, "handleSetBrowsedPlayerRsp: device=" + device + " depth=" + depth);
mAvrcpController.handleSetBrowsedPlayerRsp(device, items, depth);
}
void handleSetAddressedPlayerRsp(byte[] address, int status) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleSetAddressedPlayerRsp device=" + device + " status=" + status);
- }
+ Log.d(TAG, "handleSetAddressedPlayerRsp device=" + device + " status=" + status);
mAvrcpController.handleSetAddressedPlayerRsp(device, status);
}
void handleAddressedPlayerChanged(byte[] address, int id) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleAddressedPlayerChanged: device=" + device + " id=" + id);
- }
+ Log.d(TAG, "handleAddressedPlayerChanged: device=" + device + " id=" + id);
mAvrcpController.handleAddressedPlayerChanged(device, id);
}
void handleNowPlayingContentChanged(byte[] address) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "handleNowPlayingContentChanged: device=" + device);
- }
+ Log.d(TAG, "handleNowPlayingContentChanged: device=" + device);
mAvrcpController.handleNowPlayingContentChanged(device);
}
void onAvailablePlayerChanged(byte[] address) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
- if (DBG) {
- Log.d(TAG, "onAvailablePlayerChanged: device=" + device);
- }
+ Log.d(TAG, "onAvailablePlayerChanged: device=" + device);
mAvrcpController.onAvailablePlayerChanged(device);
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
index 8dd055a..2d4f39c 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
@@ -54,8 +54,6 @@
*/
public class AvrcpControllerService extends ProfileService {
static final String TAG = AvrcpControllerService.class.getSimpleName();
- static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
static final int MAXIMUM_CONNECTED_DEVICES = 5;
@@ -119,10 +117,8 @@
@Override
public void onImageDownloadComplete(BluetoothDevice device,
AvrcpCoverArtManager.DownloadEvent event) {
- if (DBG) {
- Log.d(TAG, "Image downloaded [device: " + device + ", uuid: " + event.getUuid()
- + ", uri: " + event.getUri());
- }
+ Log.d(TAG, "Image downloaded [device: " + device + ", uuid: " + event.getUuid()
+ + ", uri: " + event.getUri());
AvrcpControllerStateMachine stateMachine = getStateMachine(device);
if (stateMachine == null) {
Log.e(TAG, "No state machine found for device " + device);
@@ -207,9 +203,7 @@
*/
@VisibleForTesting
boolean setActiveDevice(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "setActiveDevice(device=" + device + ")");
- }
+ Log.d(TAG, "setActiveDevice(device=" + device + ")");
A2dpSinkService a2dpSinkService = A2dpSinkService.getA2dpSinkService();
if (a2dpSinkService == null) {
Log.w(TAG, "setActiveDevice(device=" + device + "): A2DP Sink not available");
@@ -274,7 +268,7 @@
}
void playItem(String parentMediaId) {
- if (DBG) Log.d(TAG, "playItem(" + parentMediaId + ")");
+ Log.d(TAG, "playItem(" + parentMediaId + ")");
// Check if the requestedNode is a player rather than a song
BrowseTree.BrowseNode requestedNode = sBrowseTree.findBrowseNodeByID(parentMediaId);
if (requestedNode == null) {
@@ -282,7 +276,7 @@
// Check each state machine for the song and then play it
requestedNode = stateMachine.findNode(parentMediaId);
if (requestedNode != null) {
- if (DBG) Log.d(TAG, "Found a node");
+ Log.d(TAG, "Found a node, node=" + requestedNode);
BluetoothDevice device = stateMachine.getDevice();
if (device != null) {
setActiveDevice(device);
@@ -304,7 +298,7 @@
* must be performed.
*/
public synchronized BrowseResult getContents(String parentMediaId) {
- if (DBG) Log.d(TAG, "getContents(" + parentMediaId + ")");
+ Log.d(TAG, "getContents(" + parentMediaId + ")");
BrowseTree.BrowseNode requestedNode = sBrowseTree.findBrowseNodeByID(parentMediaId);
if (requestedNode == null) {
@@ -316,12 +310,10 @@
}
}
- if (DBG) {
- Log.d(TAG, "getContents(" + parentMediaId + "): "
- + (requestedNode == null
- ? "Failed to find node"
- : "node=" + requestedNode + ", device=" + requestedNode.getDevice()));
- }
+ Log.d(TAG, "getContents(" + parentMediaId + "): "
+ + (requestedNode == null
+ ? "Failed to find node"
+ : "node=" + requestedNode + ", device=" + requestedNode.getDevice()));
// If we don't find a node in the tree then do not have any way to browse for the contents.
// Return an empty list instead.
@@ -340,7 +332,7 @@
List<MediaItem> contents = requestedNode.getContents();
if (!requestedNode.isCached()) {
- if (DBG) Log.d(TAG, "getContents(" + parentMediaId + "): node download pending");
+ Log.d(TAG, "getContents(" + parentMediaId + "): node download pending");
refreshContents(requestedNode);
/* Ongoing downloads can have partial results and we want to make sure they get sent
* to the client. If a download gets kicked off as a result of this request, the
@@ -348,10 +340,8 @@
*/
return new BrowseResult(contents, BrowseResult.DOWNLOAD_PENDING);
}
- if (DBG) {
- Log.d(TAG, "getContents(" + parentMediaId + "): return node, contents="
- + requestedNode.getContents());
- }
+ Log.d(TAG, "getContents(" + parentMediaId + "): return node, contents="
+ + requestedNode.getContents());
return new BrowseResult(contents, BrowseResult.SUCCESS);
}
@@ -526,9 +516,7 @@
* player to stop and start playing.
*/
public void onAudioFocusStateChanged(int state) {
- if (DBG) {
- Log.d(TAG, "onAudioFocusStateChanged(state=" + state + ")");
- }
+ Log.d(TAG, "onAudioFocusStateChanged(state=" + state + ")");
// Make sure the active device isn't changed while we're processing the event so play/pause
// commands get routed to the correct device
@@ -639,9 +627,10 @@
// Browsing related JNI callbacks.
void handleGetFolderItemsRsp(BluetoothDevice device, int status, AvrcpItem[] items) {
+ Log.d(TAG, "handleGetFolderItemsRsp(device=" + device + ", status=" + status);
List<AvrcpItem> itemsList = new ArrayList<>();
for (AvrcpItem item : items) {
- if (VDBG) Log.d(TAG, item.toString());
+ Log.v(TAG, "handleGetFolderItemsRsp(device=" + device + "): item=" + item.toString());
if (mCoverArtManager != null) {
String handle = item.getCoverArtHandle();
if (handle != null) {
@@ -718,9 +707,7 @@
* @return true if disconnect is successful, false otherwise.
*/
public synchronized boolean disconnect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "disconnect(device=" + device + ")");
- }
+ Log.d(TAG, "disconnect(device=" + device + ")");
AvrcpControllerStateMachine stateMachine = mDeviceStateMap.get(device);
// a map state machine instance doesn't exist. maybe it is already gone?
if (stateMachine == null) {
@@ -763,7 +750,11 @@
protected AvrcpControllerStateMachine getOrCreateStateMachine(BluetoothDevice device) {
AvrcpControllerStateMachine newStateMachine =
- new AvrcpControllerStateMachine(device, this, mNativeInterface);
+ new AvrcpControllerStateMachine(
+ device,
+ this,
+ mNativeInterface,
+ Utils.isAutomotive(getApplicationContext()));
AvrcpControllerStateMachine existingStateMachine =
mDeviceStateMap.putIfAbsent(device, newStateMachine);
// Given null is not a valid value in our map, ConcurrentHashMap will return null if the
@@ -786,21 +777,20 @@
}
List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
- if (DBG) Log.d(TAG, "getDevicesMatchingConnectionStates" + Arrays.toString(states));
+ Log.d(TAG, "getDevicesMatchingConnectionStates(states=" + Arrays.toString(states) + ")");
List<BluetoothDevice> deviceList = new ArrayList<>();
BluetoothDevice[] bondedDevices = mAdapterService.getBondedDevices();
int connectionState;
for (BluetoothDevice device : bondedDevices) {
connectionState = getConnectionState(device);
- if (DBG) Log.d(TAG, "Device: " + device + "State: " + connectionState);
for (int i = 0; i < states.length; i++) {
if (connectionState == states[i]) {
deviceList.add(device);
}
}
}
- if (DBG) Log.d(TAG, deviceList.toString());
- Log.d(TAG, "GetDevicesDone");
+ Log.d(TAG, "getDevicesMatchingConnectionStates(states=" + Arrays.toString(states)
+ + "): Found " + deviceList.toString());
return deviceList;
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java
index c4461dc..5d07e89 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java
@@ -54,8 +54,7 @@
* and interactions with a remote controlable device.
*/
class AvrcpControllerStateMachine extends StateMachine {
- static final String TAG = "AvrcpControllerStateMachine";
- static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ static final String TAG = AvrcpControllerStateMachine.class.getSimpleName();
//0->99 Events from Outside
public static final int CONNECT = 1;
@@ -148,7 +147,8 @@
AvrcpControllerStateMachine(
BluetoothDevice device,
AvrcpControllerService service,
- AvrcpControllerNativeInterface nativeInterface) {
+ AvrcpControllerNativeInterface nativeInterface,
+ boolean isControllerAbsoluteVolumeEnabled) {
super(TAG);
mDevice = device;
mDeviceAddress = Utils.getByteAddress(mDevice);
@@ -156,7 +156,6 @@
mNativeInterface = requireNonNull(nativeInterface);
mCoverArtPsm = 0;
mCoverArtManager = service.getCoverArtManager();
- logD(device.toString());
mAvailablePlayerList = new SparseArray<AvrcpPlayer>();
mAddressedPlayerId = AvrcpPlayer.DEFAULT_ID;
@@ -186,13 +185,15 @@
mGetFolderList = new GetFolderList();
addState(mGetFolderList, mConnected);
mAudioManager = service.getSystemService(AudioManager.class);
- mIsVolumeFixed = mAudioManager.isVolumeFixed();
+ mIsVolumeFixed = mAudioManager.isVolumeFixed() || isControllerAbsoluteVolumeEnabled;
setInitialState(mDisconnected);
+
+ debug("State machine created");
}
BrowseTree.BrowseNode findNode(String parentMediaId) {
- logD("findNode(device=" + mDevice + ", mediaId=" + parentMediaId + ")");
+ debug("findNode(mediaId=" + parentMediaId + ")");
return mBrowseTree.findBrowseNodeByID(parentMediaId);
}
@@ -293,16 +294,10 @@
@Override
protected void unhandledMessage(Message msg) {
- Log.w(TAG, "Unhandled message in state " + getCurrentState() + "msg.what="
+ warn("Unhandled message, state=" + getCurrentState() + "msg.what="
+ eventToString(msg.what));
}
- private static void logD(String message) {
- if (DBG) {
- Log.d(TAG, message);
- }
- }
-
synchronized void onBrowsingConnected() {
mBrowsingConnected = true;
requestContents(mBrowseTree.mRootNode);
@@ -329,7 +324,7 @@
// Called from "connected" state, which assumes either control or browse is connected
if (mCoverArtManager != null && mCoverArtPsm != 0
&& mCoverArtManager.getState(mDevice) != BluetoothProfile.STATE_CONNECTED) {
- logD("Attempting to connect to AVRCP BIP, psm: " + mCoverArtPsm);
+ debug("Attempting to connect to AVRCP BIP, psm: " + mCoverArtPsm);
mCoverArtManager.connect(mDevice, /* psm */ mCoverArtPsm);
}
}
@@ -337,7 +332,7 @@
synchronized void refreshCoverArt() {
if (mCoverArtManager != null && mCoverArtPsm != 0
&& mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED) {
- logD("Attempting to refresh AVRCP BIP OBEX session, psm: " + mCoverArtPsm);
+ debug("Attempting to refresh AVRCP BIP OBEX session, psm: " + mCoverArtPsm);
mCoverArtManager.refreshSession(mDevice);
}
}
@@ -345,7 +340,7 @@
synchronized void disconnectCoverArt() {
// Safe to call even if we're not connected
if (mCoverArtManager != null) {
- logD("Disconnect BIP cover artwork");
+ debug("Disconnect BIP cover artwork");
mCoverArtManager.disconnect(mDevice);
}
}
@@ -355,7 +350,7 @@
* current track.
*/
synchronized void removeUnusedArtwork(String previousTrackUuid) {
- logD("removeUnusedArtwork(" + previousTrackUuid + ")");
+ debug("removeUnusedArtwork(" + previousTrackUuid + ")");
if (mCoverArtManager == null) return;
AvrcpItem currentTrack = getCurrentTrack();
String currentTrackUuid = currentTrack != null ? currentTrack.getCoverArtUuid() : null;
@@ -372,7 +367,7 @@
* if the uuid is not used by the current track.
*/
synchronized void removeUnusedArtworkFromBrowseTree() {
- logD("removeUnusedArtworkFromBrowseTree()");
+ debug("removeUnusedArtworkFromBrowseTree()");
if (mCoverArtManager == null) return;
AvrcpItem currentTrack = getCurrentTrack();
String currentTrackUuid = currentTrack != null ? currentTrack.getCoverArtUuid() : null;
@@ -403,7 +398,7 @@
void requestContents(BrowseTree.BrowseNode node) {
sendMessage(MESSAGE_GET_FOLDER_ITEMS, node);
- logD("Fetching " + node);
+ debug("requestContents(node=" + node + ")");
}
public void playItem(BrowseTree.BrowseNode node) {
@@ -418,7 +413,7 @@
protected class Disconnected extends State {
@Override
public void enter() {
- logD("Enter Disconnected");
+ debug("Disconnected: Entered");
if (mMostRecentState != BluetoothProfile.STATE_DISCONNECTED) {
sendMessage(CLEANUP);
}
@@ -427,12 +422,13 @@
@Override
public boolean processMessage(Message message) {
+ debug("Disconnected: processMessage " + eventToString(message.what));
switch (message.what) {
case MESSAGE_PROCESS_RECEIVED_COVER_ART_PSM:
mCoverArtPsm = message.arg1;
break;
case CONNECT:
- logD("Connect");
+ debug("Connect");
transitionTo(mConnecting);
break;
case CLEANUP:
@@ -450,7 +446,7 @@
protected class Connecting extends State {
@Override
public void enter() {
- logD("Enter Connecting");
+ debug("Connecting: Enter Connecting");
broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTING);
transitionTo(mConnected);
}
@@ -458,7 +454,6 @@
class Connected extends State {
- private static final String STATE_TAG = "Avrcp.ConnectedAvrcpController";
private int mCurrentlyHeldKey = 0;
@Override
@@ -469,14 +464,14 @@
BluetoothMediaBrowserService.notifyChanged(mService.sBrowseTree.mRootNode);
connectCoverArt(); // only works if we have a valid PSM
} else {
- logD("ReEnteringConnected");
+ debug("Connected: Re-entering Connected ");
}
super.enter();
}
@Override
public boolean processMessage(Message msg) {
- logD(STATE_TAG + " processMessage " + eventToString(msg.what));
+ debug("Connected: processMessage " + eventToString(msg.what));
switch (msg.what) {
case ACTIVE_DEVICE_CHANGE:
int state = msg.arg1;
@@ -505,12 +500,12 @@
case AUDIO_FOCUS_STATE_CHANGE:
int newState = msg.arg1;
- logD("Audio focus changed -> " + newState);
+ debug("Connected: Audio focus changed -> " + newState);
switch (newState) {
case AudioManager.AUDIOFOCUS_GAIN:
// Begin playing audio again if we paused the remote
if (mShouldSendPlayOnFocusRecovery) {
- logD("Regained focus, establishing play status");
+ debug("Connected: Regained focus, establishing play status");
sendMessage(MSG_AVRCP_PASSTHRU,
AvrcpControllerService.PASS_THRU_CMD_ID_PLAY);
}
@@ -522,7 +517,8 @@
// note we should recover
if (mAddressedPlayer.getPlaybackState().getState()
== PlaybackStateCompat.STATE_PLAYING) {
- logD("Transient loss, temporarily pause with intent to recover");
+ debug("Connected: Transient loss, temporarily pause with intent to "
+ + "recover");
sendMessage(MSG_AVRCP_PASSTHRU,
AvrcpControllerService.PASS_THRU_CMD_ID_PAUSE);
mShouldSendPlayOnFocusRecovery = true;
@@ -532,7 +528,7 @@
case AudioManager.AUDIOFOCUS_LOSS:
// Permanent loss of focus probably due to another audio app. Send a
// courtesy pause
- logD("Lost focus, send a courtesy pause");
+ debug("Connected: Lost focus, send a courtesy pause");
if (mAddressedPlayer.getPlaybackState().getState()
== PlaybackStateCompat.STATE_PLAYING) {
sendMessage(MSG_AVRCP_PASSTHRU,
@@ -597,7 +593,8 @@
return true;
case MESSAGE_PROCESS_PLAY_STATUS_CHANGED:
- logd("Playback status changed to " + msg.arg1);
+ debug("Connected: Playback status = "
+ + AvrcpControllerUtils.playbackStateToString(msg.arg1));
mAddressedPlayer.setPlayStatus(msg.arg1);
if (!isActive()) {
sendMessage(MSG_AVRCP_PASSTHRU,
@@ -636,7 +633,7 @@
case MESSAGE_PROCESS_ADDRESSED_PLAYER_CHANGED:
int oldAddressedPlayerId = mAddressedPlayerId;
mAddressedPlayerId = msg.arg1;
- logD("AddressedPlayer changed " + oldAddressedPlayerId + " -> "
+ debug("Connected: AddressedPlayer changed " + oldAddressedPlayerId + " -> "
+ mAddressedPlayerId);
// The now playing list is tied to the addressed player by specification in
@@ -644,7 +641,8 @@
// invalid
mBrowseTree.mNowPlayingNode.setCached(false);
if (isActive()) {
- logD("Addressed player change has invalidated the now playing list");
+ debug("Connected: Addressed player change has invalidated the now playing"
+ + " list");
BluetoothMediaBrowserService.notifyChanged(mBrowseTree.mNowPlayingNode);
}
removeUnusedArtworkFromBrowseTree();
@@ -654,7 +652,8 @@
// isn't there then we need to ensure that a default Addressed AvrcpPlayer is
// created to represent it. It can be updated if/when we do fetch the player.
if (!mAvailablePlayerList.contains(mAddressedPlayerId)) {
- logD("Available player set does not contain the new Addressed Player");
+ debug("Connected: Available player set does not contain the new Addressed"
+ + " Player");
AvrcpPlayer.Builder apb = new AvrcpPlayer.Builder();
apb.setDevice(mDevice);
apb.setPlayerId(mAddressedPlayerId);
@@ -678,7 +677,7 @@
mNativeInterface.getCurrentMetadata(mDeviceAddress);
mNativeInterface.getPlaybackState(mDeviceAddress);
requestContents(mBrowseTree.mNowPlayingNode);
- logD("AddressedPlayer = " + mAddressedPlayer);
+ debug("Connected: AddressedPlayer = " + mAddressedPlayer);
return true;
case MESSAGE_PROCESS_SUPPORTED_APPLICATION_SETTINGS:
@@ -707,7 +706,7 @@
(AvrcpCoverArtManager.DownloadEvent) msg.obj;
String uuid = event.getUuid();
Uri uri = event.getUri();
- logD("Received image for " + uuid + " at " + uri.toString());
+ debug("Connected: Received image for " + uuid + " at " + uri.toString());
// Let the addressed player know we got an image so it can see if the current
// track now has cover artwork
@@ -744,14 +743,15 @@
private void processPlayItem(BrowseTree.BrowseNode node) {
if (node == null) {
- Log.w(TAG, "Invalid item to play");
+ warn("Connected: Invalid item to play");
return;
}
mNativeInterface.playItem(mDeviceAddress, node.getScope(), node.getBluetoothID(), 0);
}
private synchronized void passThru(int cmd) {
- logD("msgPassThru " + cmd);
+ debug("Connected: Send passthrough command, id= " + cmd + ", key="
+ + AvrcpControllerUtils.passThruIdToString(cmd));
// Some keys should be held until the next event.
if (mCurrentlyHeldKey != 0) {
mNativeInterface.sendPassThroughCommand(
@@ -812,7 +812,7 @@
}
private void processAvailablePlayerChanged() {
- logD("processAvailablePlayerChanged");
+ debug("Connected: processAvailablePlayerChanged");
mBrowseTree.mRootNode.setCached(false);
mBrowseTree.mRootNode.setExpectedChildren(BrowseTree.DEFAULT_FOLDER_SIZE);
BluetoothMediaBrowserService.notifyChanged(mBrowseTree.mRootNode);
@@ -825,15 +825,13 @@
// a) Fetch the listing of folders
// b) Once completed return the object listing
class GetFolderList extends State {
- private static final String STATE_TAG = "Avrcp.GetFolderList";
-
boolean mAbort;
BrowseTree.BrowseNode mBrowseNode;
BrowseTree.BrowseNode mNextStep;
@Override
public void enter() {
- logD(STATE_TAG + ": Entering GetFolderList");
+ debug("GetFolderList: Entering GetFolderList");
// Setup the timeouts.
sendMessageDelayed(MESSAGE_INTERNAL_CMD_TIMEOUT, CMD_TIMEOUT_MILLIS);
super.enter();
@@ -841,13 +839,13 @@
Message msg = getCurrentMessage();
if (msg.what == MESSAGE_GET_FOLDER_ITEMS) {
mBrowseNode = (BrowseTree.BrowseNode) msg.obj;
- logD(STATE_TAG + ": new fetch request, node=" + mBrowseNode);
+ debug("GetFolderList: new fetch request, node=" + mBrowseNode);
}
if (mBrowseNode == null) {
transitionTo(mConnected);
} else if (!mBrowsingConnected) {
- Log.w(TAG, "GetFolderItems: Browsing not connected, node=" + mBrowseNode);
+ warn("GetFolderList: Browsing not connected, node=" + mBrowseNode);
transitionTo(mConnected);
} else {
int scope = mBrowseNode.getScope();
@@ -862,12 +860,12 @@
@Override
public boolean processMessage(Message msg) {
- logD(STATE_TAG + " processMessage " + eventToString(msg.what));
+ debug("GetFolderList: processMessage " + eventToString(msg.what));
switch (msg.what) {
case MESSAGE_PROCESS_GET_FOLDER_ITEMS:
ArrayList<AvrcpItem> folderList = (ArrayList<AvrcpItem>) msg.obj;
int endIndicator = mBrowseNode.getExpectedChildren() - 1;
- logD("GetFolderItems: End " + endIndicator
+ debug("GetFolderList: End " + endIndicator
+ " received " + folderList.size());
// Queue up image download if the item has an image and we don't have it yet
@@ -883,7 +881,7 @@
// Always update the node so that the user does not wait forever
// for the list to populate.
int newSize = mBrowseNode.addChildren(folderList);
- logD("Added " + newSize + " items to the browse tree");
+ debug("GetFolderList: Added " + newSize + " items to the browse tree");
notifyChanged(mBrowseNode);
if (mBrowseNode.getChildrenCount() >= endIndicator || folderList.size() == 0
@@ -925,7 +923,7 @@
break;
case MESSAGE_PROCESS_GET_PLAYER_ITEMS:
- logD("Received new available player items");
+ debug("GetFolderList: Received new available player items");
BrowseTree.BrowseNode rootNode = mBrowseTree.mRootNode;
// The specification is not firm on what receiving available player changes
@@ -957,16 +955,18 @@
// will replace it and re-download metadata. If not, we'll re-use the old
// player to save the metadata queries.
if (!mAvailablePlayerList.contains(mAddressedPlayerId)) {
- logD("Available player set doesn't contain the addressed player");
+ debug("GetFolderList: Available player set doesn't contain the"
+ + " addressed player");
mAvailablePlayerList.put(mAddressedPlayerId, mAddressedPlayer);
} else {
- logD("Update addressed player with new available player metadata");
+ debug("GetFolderList: Update addressed player with new available player"
+ + " metadata");
mAddressedPlayer = mAvailablePlayerList.get(mAddressedPlayerId);
mNativeInterface.getCurrentMetadata(mDeviceAddress);
mNativeInterface.getPlaybackState(mDeviceAddress);
requestContents(mBrowseTree.mNowPlayingNode);
}
- logD("AddressedPlayer = " + mAddressedPlayer);
+ debug("GetFolderList: AddressedPlayer = " + mAddressedPlayer);
// Check old cover art UUIDs for deletion
for (String uuid : coverArtUuids) {
@@ -986,7 +986,7 @@
case MESSAGE_INTERNAL_CMD_TIMEOUT:
// We have timed out to execute the request, we should simply send
// whatever listing we have gotten until now.
- Log.w(TAG, "GetFolderItems: Timeout waiting for download, node=" + mBrowseNode);
+ warn("GetFolderList: Timeout waiting for download, node=" + mBrowseNode);
transitionTo(mConnected);
break;
@@ -1004,16 +1004,16 @@
mAbort = true;
}
deferMessage(msg);
- logD("GetFolderItems: Enqueue new request for node=" + requested
+ debug("GetFolderList: Enqueue new request for node=" + requested
+ ", abort=" + mAbort);
} else {
- logD("GetFolderItems: Ignore request, node=" + requested);
+ debug("GetFolderList: Ignore request, node=" + requested);
}
break;
default:
// All of these messages should be handled by parent state immediately.
- logD("GetFolderItems: Passing message to parent state, type="
+ debug("GetFolderList: Passing message to parent state, type="
+ eventToString(msg.what));
return false;
}
@@ -1041,8 +1041,8 @@
int start = target.getChildrenCount();
int end = Math.min(target.getExpectedChildren(), target.getChildrenCount()
+ ITEM_PAGE_SIZE) - 1;
- logD("fetchContents(title=" + target.getID() + ", scope=" + target.getScope()
- + ", start=" + start + ", end=" + end + ", expected="
+ debug("GetFolderList: fetchContents(title=" + target.getID() + ", scope="
+ + target.getScope() + ", start=" + start + ", end=" + end + ", expected="
+ target.getExpectedChildren() + ")");
switch (target.getScope()) {
case AvrcpControllerService.BROWSE_SCOPE_PLAYER_LIST:
@@ -1055,7 +1055,7 @@
mNativeInterface.getFolderList(mDeviceAddress, start, end);
break;
default:
- Log.e(TAG, STATE_TAG + " Scope " + target.getScope()
+ error("GetFolderList: Scope " + target.getScope()
+ " cannot be handled here.");
}
}
@@ -1073,9 +1073,10 @@
*/
private void navigateToFolderOrRetrieve(BrowseTree.BrowseNode target) {
mNextStep = mBrowseTree.getNextStepToFolder(target);
- logD("NAVIGATING From "
- + mBrowseTree.getCurrentBrowsedFolder().toString());
- logD("NAVIGATING Toward " + target.toString());
+ debug("GetFolderList: NAVIGATING From "
+ + mBrowseTree.getCurrentBrowsedFolder().toString()
+ + ", NAVIGATING Toward "
+ + target.toString());
if (mNextStep == null) {
return;
} else if (target.equals(mBrowseTree.mNowPlayingNode)
@@ -1083,17 +1084,17 @@
|| mNextStep.equals(mBrowseTree.getCurrentBrowsedFolder())) {
fetchContents(mNextStep);
} else if (mNextStep.isPlayer()) {
- logD("NAVIGATING Player " + mNextStep.toString());
+ debug("GetFolderList: NAVIGATING Player " + mNextStep.toString());
if (mNextStep.isBrowsable()) {
mNativeInterface.setBrowsedPlayer(
mDeviceAddress, (int) mNextStep.getBluetoothID());
} else {
- logD("Player doesn't support browsing");
+ debug("GetFolderList: Player doesn't support browsing");
mNextStep.setCached(true);
transitionTo(mConnected);
}
} else if (mNextStep.equals(mBrowseTree.mNavigateUpNode)) {
- logD("NAVIGATING UP " + mNextStep.toString());
+ debug("GetFolderList: NAVIGATING UP " + mNextStep.toString());
mNextStep = mBrowseTree.getCurrentBrowsedFolder().getParent();
mBrowseTree.getCurrentBrowsedFolder().setCached(false);
removeUnusedArtworkFromBrowseTree();
@@ -1101,7 +1102,7 @@
mDeviceAddress, AvrcpControllerService.FOLDER_NAVIGATION_DIRECTION_UP, 0);
} else {
- logD("NAVIGATING DOWN " + mNextStep.toString());
+ debug("GetFolderList: NAVIGATING DOWN " + mNextStep.toString());
mNativeInterface.changeFolderPath(
mDeviceAddress,
AvrcpControllerService.FOLDER_NAVIGATION_DIRECTION_DOWN,
@@ -1111,7 +1112,7 @@
@Override
public void exit() {
- logd("GetFolderItems: fetch complete, node=" + mBrowseNode);
+ debug("GetFolderList: fetch complete, node=" + mBrowseNode);
removeMessages(MESSAGE_INTERNAL_CMD_TIMEOUT);
// Whatever we have, notify on it so the UI doesn't hang
@@ -1128,6 +1129,7 @@
protected class Disconnecting extends State {
@Override
public void enter() {
+ debug("Disconnecting: Entered Disconnecting");
disconnectCoverArt();
onBrowsingDisconnected();
if (mService.sBrowseTree != null) {
@@ -1148,9 +1150,9 @@
* @param label Volume notification label
*/
private void handleAbsVolumeRequest(int absVol, int label) {
- logD("handleAbsVolumeRequest: absVol = " + absVol + ", label = " + label);
+ debug("handleAbsVolumeRequest: absVol = " + absVol + ", label = " + label);
if (mIsVolumeFixed) {
- logD("Source volume is assumed to be fixed, responding with max volume");
+ debug("Source volume is assumed to be fixed, responding with max volume");
absVol = ABS_VOL_BASE;
} else {
removeMessages(MESSAGE_INTERNAL_ABS_VOL_TIMEOUT);
@@ -1170,8 +1172,15 @@
int maxLocalVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curLocalVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int reqLocalVolume = (maxLocalVolume * absVol) / ABS_VOL_BASE;
- logD("setAbsVolme: absVol = " + absVol + ", reqLocal = " + reqLocalVolume
- + ", curLocal = " + curLocalVolume + ", maxLocal = " + maxLocalVolume);
+ debug(
+ "setAbsVolume: absVol = "
+ + absVol
+ + ", reqLocal = "
+ + reqLocalVolume
+ + ", curLocal = "
+ + curLocalVolume
+ + ", maxLocal = "
+ + maxLocalVolume);
/*
* In some cases change in percentage is not sufficient enough to warrant
@@ -1225,18 +1234,18 @@
MediaSessionCompat.Callback mSessionCallbacks = new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
- logD("onPlay");
+ debug("onPlay");
onPrepare();
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_PLAY);
}
@Override
public void onPause() {
- logD("onPause");
+ debug("onPause");
// If we receive a local pause/stop request and send it out then we need to signal that
// the intent is to stay paused if we recover focus from a transient loss
if (getFocusState() == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
- logD("Received a pause while in a transient loss. Do not recover anymore.");
+ debug("Received a pause while in a transient loss. Do not recover anymore.");
mShouldSendPlayOnFocusRecovery = false;
}
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_PAUSE);
@@ -1244,21 +1253,21 @@
@Override
public void onSkipToNext() {
- logD("onSkipToNext");
+ debug("onSkipToNext");
onPrepare();
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_FORWARD);
}
@Override
public void onSkipToPrevious() {
- logD("onSkipToPrevious");
+ debug("onSkipToPrevious");
onPrepare();
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_BACKWARD);
}
@Override
public void onSkipToQueueItem(long id) {
- logD("onSkipToQueueItem id=" + id);
+ debug("onSkipToQueueItem(id=" + id + ")");
onPrepare();
BrowseTree.BrowseNode node = mBrowseTree.getTrackFromNowPlayingList((int) id);
if (node != null) {
@@ -1268,11 +1277,11 @@
@Override
public void onStop() {
- logD("onStop");
+ debug("onStop");
// If we receive a local pause/stop request and send it out then we need to signal that
// the intent is to stay paused if we recover focus from a transient loss
if (getFocusState() == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
- logD("Received a stop while in a transient loss. Do not recover anymore.");
+ debug("Received a stop while in a transient loss. Do not recover anymore.");
mShouldSendPlayOnFocusRecovery = false;
}
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_STOP);
@@ -1280,7 +1289,7 @@
@Override
public void onPrepare() {
- logD("onPrepare");
+ debug("onPrepare");
A2dpSinkService a2dpSinkService = A2dpSinkService.getA2dpSinkService();
if (a2dpSinkService != null) {
a2dpSinkService.requestAudioFocus(mDevice, true);
@@ -1289,19 +1298,19 @@
@Override
public void onRewind() {
- logD("onRewind");
+ debug("onRewind");
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_REWIND);
}
@Override
public void onFastForward() {
- logD("onFastForward");
+ debug("onFastForward");
sendMessage(MSG_AVRCP_PASSTHRU, AvrcpControllerService.PASS_THRU_CMD_ID_FF);
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
- logD("onPlayFromMediaId");
+ debug("onPlayFromMediaId(mediaId=" + mediaId + ")");
// Play the item if possible.
onPrepare();
BrowseTree.BrowseNode node = mBrowseTree.findBrowseNodeByID(mediaId);
@@ -1317,13 +1326,13 @@
@Override
public void onSetRepeatMode(int repeatMode) {
- logD("onSetRepeatMode");
+ debug("onSetRepeatMode(repeatMode=" + repeatMode + ")");
sendMessage(MSG_AVRCP_SET_REPEAT, repeatMode);
}
@Override
public void onSetShuffleMode(int shuffleMode) {
- logD("onSetShuffleMode");
+ debug("onSetShuffleMode(shuffleMode=" + shuffleMode + ")");
sendMessage(MSG_AVRCP_SET_SHUFFLE, shuffleMode);
}
@@ -1343,7 +1352,7 @@
mDevice, BluetoothProfile.AVRCP_CONTROLLER, currentState, mMostRecentState);
}
- logD("Connection state " + mDevice + ": " + mMostRecentState + "->" + currentState);
+ debug("Connection state : " + mMostRecentState + "->" + currentState);
Intent intent = new Intent(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, mMostRecentState);
intent.putExtra(BluetoothProfile.EXTRA_STATE, currentState);
@@ -1359,6 +1368,18 @@
.getBoolean(R.bool.a2dp_sink_automatically_request_audio_focus);
}
+ private void debug(String message) {
+ Log.d(TAG, "[" + mDevice + "]: " + message);
+ }
+
+ private void warn(String message) {
+ Log.w(TAG, "[" + mDevice + "]: " + message);
+ }
+
+ private void error(String message) {
+ Log.e(TAG, "[" + mDevice + "]: " + message);
+ }
+
private static String eventToString(int event) {
switch (event) {
case CONNECT:
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java
new file mode 100644
index 0000000..017ecc44
--- /dev/null
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java
@@ -0,0 +1,139 @@
+/*
+ * 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.avrcpcontroller;
+
+import android.support.v4.media.session.PlaybackStateCompat;
+
+/**
+ * A package global set of utilities for the AVRCP Controller implementation to leverage
+ */
+public final class AvrcpControllerUtils {
+
+ /**
+ * Convert an AVRCP Passthrough command id to a human readable version of the key
+ */
+ public static String passThruIdToString(int id) {
+ StringBuilder sb = new StringBuilder();
+ switch (id) {
+ case AvrcpControllerService.PASS_THRU_CMD_ID_PLAY:
+ sb.append("PLAY");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_PAUSE:
+ sb.append("PAUSE");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_VOL_UP:
+ sb.append("VOL_UP");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_VOL_DOWN:
+ sb.append("VOL_DOWN");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_STOP:
+ sb.append("STOP");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_FF:
+ sb.append("FF");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_REWIND:
+ sb.append("REWIND");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_FORWARD:
+ sb.append("FORWARD");
+ break;
+ case AvrcpControllerService.PASS_THRU_CMD_ID_BACKWARD:
+ sb.append("BACKWARD");
+ break;
+ default:
+ sb.append("UNKNOWN_CMD_" + id);
+ break;
+ }
+ sb.append(" (" + id + ")");
+ return sb.toString();
+ }
+
+ /**
+ * Convert an entire PlaybackStateCompat to a string that contains human readable states
+ */
+ public static String playbackStateCompatToString(PlaybackStateCompat playbackState) {
+ if (playbackState == null) {
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder("PlaybackState {");
+ sb.append("state=").append(playbackStateToString(playbackState.getState()));
+ sb.append(", position=").append(playbackState.getPosition());
+ sb.append(", buffered position=").append(playbackState.getBufferedPosition());
+ sb.append(", speed=").append(playbackState.getPlaybackSpeed());
+ sb.append(", updated=").append(playbackState.getLastPositionUpdateTime());
+ sb.append(", actions=").append(playbackState.getActions());
+ sb.append(", error code=").append(playbackState.getErrorCode());
+ sb.append(", error message=").append(playbackState.getErrorMessage());
+ sb.append(", custom actions=").append(playbackState.getCustomActions());
+ sb.append(", active item id=").append(playbackState.getActiveQueueItemId());
+ sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert a playback state constant to a human readable version of the state
+ */
+ public static String playbackStateToString(int playbackState) {
+ StringBuilder sb = new StringBuilder();
+ switch (playbackState) {
+ case PlaybackStateCompat.STATE_NONE:
+ sb.append("STATE_NONE");
+ break;
+ case PlaybackStateCompat.STATE_STOPPED:
+ sb.append("STATE_STOPPED");
+ break;
+ case PlaybackStateCompat.STATE_PAUSED:
+ sb.append("STATE_PAUSED");
+ break;
+ case PlaybackStateCompat.STATE_PLAYING:
+ sb.append("STATE_PLAYING");
+ break;
+ case PlaybackStateCompat.STATE_FAST_FORWARDING:
+ sb.append("STATE_FAST_FORWARDING");
+ break;
+ case PlaybackStateCompat.STATE_REWINDING:
+ sb.append("STATE_REWINDING");
+ break;
+ case PlaybackStateCompat.STATE_BUFFERING:
+ sb.append("STATE_BUFFERING");
+ break;
+ case PlaybackStateCompat.STATE_ERROR:
+ sb.append("STATE_ERROR");
+ break;
+ case PlaybackStateCompat.STATE_CONNECTING:
+ sb.append("STATE_CONNECTING");
+ break;
+ case PlaybackStateCompat.STATE_SKIPPING_TO_PREVIOUS:
+ sb.append("STATE_SKIPPING_TO_PREVIOUS");
+ break;
+ case PlaybackStateCompat.STATE_SKIPPING_TO_NEXT:
+ sb.append("STATE_SKIPPING_TO_NEXT");
+ break;
+ case PlaybackStateCompat.STATE_SKIPPING_TO_QUEUE_ITEM:
+ sb.append("STATE_SKIPPING_TO_QUEUE_ITEM");
+ break;
+ default:
+ sb.append("UNKNOWN_PLAYBACK_STATE");
+ break;
+ }
+ sb.append(" (" + playbackState + ")");
+ return sb.toString();
+ }
+}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java
index 4cf473b..b251ab0 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java
@@ -38,8 +38,7 @@
* properties, download the image, and place it into a Content Provider for others to retrieve from
*/
public class AvrcpCoverArtManager {
- private static final String TAG = "AvrcpCoverArtManager";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpCoverArtManager.class.getSimpleName();
// Image Download Schemes for cover art
public static final String AVRCP_CONTROLLER_COVER_ART_SCHEME =
@@ -484,9 +483,7 @@
* Print to debug if debug is enabled for this class
*/
private void debug(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
/**
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java
index dd59dcb..ea73cf8 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java
@@ -46,8 +46,7 @@
* enable that usage pattern.
*/
public class AvrcpCoverArtProvider extends ContentProvider {
- private static final String TAG = "AvrcpCoverArtProvider";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpCoverArtProvider.class.getSimpleName();
private BluetoothAdapter mAdapter;
@@ -177,8 +176,6 @@
}
private static void debug(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java
index 78e1810..765112f 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java
@@ -29,8 +29,7 @@
* An abstraction of the cover art image storage mechanism.
*/
public class AvrcpCoverArtStorage {
- private static final String TAG = "AvrcpCoverArtStorage";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpCoverArtStorage.class.getSimpleName();
private final Context mContext;
@@ -165,8 +164,6 @@
}
private void debug(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java
index d5bd99c..59fbd60 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java
@@ -33,7 +33,7 @@
* metadata can easily be shared with the system.
*/
public class AvrcpItem {
- private static final String TAG = "AvrcpItem";
+ private static final String TAG = AvrcpItem.class.getSimpleName();
// AVRCP Specification defined item types
public static final int TYPE_PLAYER = 0x1;
@@ -280,7 +280,6 @@
*/
public static class Builder {
private static final String TAG = "AvrcpItem.Builder";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
// Attribute ID Values from AVRCP Specification
private static final int MEDIA_ATTRIBUTE_TITLE = 0x01;
@@ -306,7 +305,7 @@
public Builder fromAvrcpAttributeArray(int[] attrIds, String[] attrMap) {
int attributeCount = Math.max(attrIds.length, attrMap.length);
for (int i = 0; i < attributeCount; i++) {
- if (DBG) Log.d(TAG, attrIds[i] + " = " + attrMap[i]);
+ Log.d(TAG, attrIds[i] + " = " + attrMap[i]);
switch (attrIds[i]) {
case MEDIA_ATTRIBUTE_TITLE:
mAvrcpItem.mTitle = attrMap[i];
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java
index 98605a3..2922f2c 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java
@@ -29,8 +29,7 @@
* Contains information about remote player
*/
class AvrcpPlayer {
- private static final String TAG = "AvrcpPlayer";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = AvrcpPlayer.class.getSimpleName();
public static final int DEFAULT_ID = -1;
@@ -141,7 +140,7 @@
public void setCurrentPlayerApplicationSettings(
PlayerApplicationSettings playerApplicationSettings) {
- Log.d(TAG, "Settings changed");
+ Log.d(TAG, "Play application settings changed, settings=" + playerApplicationSettings);
mCurrentPlayerApplicationSettings = playerApplicationSettings;
MediaSessionCompat session = BluetoothMediaBrowserService.getSession();
session.setRepeatMode(mCurrentPlayerApplicationSettings.getSetting(
@@ -165,9 +164,7 @@
}
public PlaybackStateCompat getPlaybackState() {
- if (DBG) {
- Log.d(TAG, "getPlayBackState state " + mPlayStatus + " time " + mPlayTime);
- }
+ Log.d(TAG, "getPlayBackState state " + mPlayStatus + " time " + mPlayTime);
return mPlaybackStateCompat;
}
@@ -182,11 +179,11 @@
}
public synchronized boolean notifyImageDownload(String uuid, Uri imageUri) {
- if (DBG) Log.d(TAG, "Got an image download -- uuid=" + uuid + ", uri=" + imageUri);
+ Log.d(TAG, "Got an image download -- uuid=" + uuid + ", uri=" + imageUri);
if (uuid == null || imageUri == null || mCurrentTrack == null) return false;
if (uuid.equals(mCurrentTrack.getCoverArtUuid())) {
mCurrentTrack.setCoverArtLocation(imageUri);
- if (DBG) Log.d(TAG, "Image UUID '" + uuid + "' was added to current track.");
+ Log.d(TAG, "Image UUID '" + uuid + "' was added to current track.");
return true;
}
return false;
@@ -230,21 +227,20 @@
mPlaybackStateCompat = new PlaybackStateCompat.Builder(mPlaybackStateCompat)
.setActions(mAvailableActions).build();
- if (DBG) Log.d(TAG, "Supported Actions = " + mAvailableActions);
+ Log.d(TAG, "Supported Actions = " + mAvailableActions);
}
@Override
public String toString() {
return "<AvrcpPlayer id=" + mId + " name=" + mName + " track=" + mCurrentTrack
- + " playState=" + mPlaybackStateCompat + ">";
+ + " playState="
+ + AvrcpControllerUtils.playbackStateCompatToString(mPlaybackStateCompat) + ">";
}
/**
* A Builder object for an AvrcpPlayer
*/
public static class Builder {
- private static final String TAG = "AvrcpPlayer.Builder";
-
private BluetoothDevice mDevice = null;
private int mPlayerId = AvrcpPlayer.DEFAULT_ID;
private String mPlayerName = null;
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java
index aca461f..c4f54f0 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java
@@ -54,8 +54,7 @@
* happens.
*/
public class BluetoothMediaBrowserService extends MediaBrowserServiceCompat {
- private static final String TAG = "BluetoothMediaBrowserService";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = BluetoothMediaBrowserService.class.getSimpleName();
private static BluetoothMediaBrowserService sBluetoothMediaBrowserService;
@@ -86,7 +85,7 @@
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_LOCALE_CHANGED)) {
- if (DBG) Log.d(TAG, "Locale has updated");
+ Log.d(TAG, "Locale has updated");
if (sBluetoothMediaBrowserService == null) return;
MediaSessionCompat session = sBluetoothMediaBrowserService.getSession();
@@ -112,7 +111,7 @@
*/
@Override
public void onCreate() {
- if (DBG) Log.d(TAG, "Service Created");
+ Log.d(TAG, "Service Created");
super.onCreate();
// Create and configure the MediaSessionCompat
@@ -134,7 +133,7 @@
@Override
public void onDestroy() {
- if (DBG) Log.d(TAG, "Service Destroyed");
+ Log.d(TAG, "Service Destroyed");
unregisterReceiver(mReceiver);
mReceiver = null;
}
@@ -235,7 +234,7 @@
@Override
public synchronized void onLoadChildren(final String parentMediaId,
final Result<List<MediaItem>> result) {
- if (DBG) Log.d(TAG, "Request for contents, id= " + parentMediaId);
+ Log.d(TAG, "Request for contents, id= " + parentMediaId);
BrowseResult contents = getContents(parentMediaId);
byte status = contents.getStatus();
List<MediaItem> results = contents.getResults();
@@ -243,10 +242,8 @@
Log.i(TAG, "Download pending - no results, id= " + parentMediaId);
result.detach();
} else {
- if (DBG) {
- Log.d(TAG, "Received Contents, id= " + parentMediaId + ", status= "
- + contents.getStatusString() + ", results=" + results);
- }
+ Log.d(TAG, "Received Contents, id= " + parentMediaId + ", status= "
+ + contents.getStatusString() + ", results=" + results);
result.sendResult(results);
}
}
@@ -271,7 +268,7 @@
} else {
mSession.setQueue(null);
}
- if (DBG) Log.d(TAG, "Now Playing List Changed, queue=" + mMediaQueue);
+ Log.d(TAG, "Now Playing List Changed, queue=" + mMediaQueue);
}
private void clearNowPlayingQueue() {
@@ -284,7 +281,7 @@
if (node.getScope() == AvrcpControllerService.BROWSE_SCOPE_NOW_PLAYING) {
sBluetoothMediaBrowserService.updateNowPlayingQueue(node);
} else {
- if (DBG) Log.d(TAG, "Browse Node contents changed, node=" + node);
+ Log.d(TAG, "Browse Node contents changed, node=" + node);
sBluetoothMediaBrowserService.notifyChildrenChanged(node.getID());
}
}
@@ -303,7 +300,7 @@
}
static synchronized void trackChanged(AvrcpItem track) {
- if (DBG) Log.d(TAG, "Track Changed, track=" + track);
+ Log.d(TAG, "Track Changed, track=" + track);
if (sBluetoothMediaBrowserService != null) {
if (track != null) {
sBluetoothMediaBrowserService.mSession.setMetadata(track.toMediaMetadata());
@@ -317,7 +314,8 @@
}
static synchronized void notifyChanged(PlaybackStateCompat playbackState) {
- if (DBG) Log.d(TAG, "Playback State Changed, state=" + playbackState);
+ Log.d(TAG, "Playback State Changed, state="
+ + AvrcpControllerUtils.playbackStateCompatToString(playbackState));
if (sBluetoothMediaBrowserService != null) {
sBluetoothMediaBrowserService.mSession.setPlaybackState(playbackState);
} else {
@@ -379,7 +377,7 @@
*/
public static synchronized void setActive(boolean active) {
if (sBluetoothMediaBrowserService != null) {
- if (DBG) Log.d(TAG, "Setting the session active state to:" + active);
+ Log.d(TAG, "Setting the session active state to:" + active);
sBluetoothMediaBrowserService.mSession.setActive(active);
} else {
Log.w(TAG, "setActive Unavailable");
@@ -418,7 +416,7 @@
sBluetoothMediaBrowserService.mSession.setMetadata(null);
sBluetoothMediaBrowserService.setErrorPlaybackState();
sBluetoothMediaBrowserService.mSession.setCallback(null);
- if (DBG) Log.d(TAG, "Service state has been reset");
+ Log.d(TAG, "Service state has been reset");
} else {
Log.w(TAG, "reset unavailable");
}
@@ -444,6 +442,8 @@
sb.append(", artist="
+ metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
sb.append(", album=" + metadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM));
+ sb.append(", duration="
+ + metadata.getString(MediaMetadataCompat.METADATA_KEY_DURATION));
sb.append(", track_number="
+ metadata.getLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER));
sb.append(", total_tracks="
@@ -455,7 +455,8 @@
} else {
sb.append("\n track=" + metadata);
}
- sb.append("\n playbackState=" + playbackState);
+ sb.append("\n playbackState="
+ + AvrcpControllerUtils.playbackStateCompatToString(playbackState));
sb.append("\n queue=" + queue);
sb.append("\n internal_queue=" + sBluetoothMediaBrowserService.mMediaQueue);
sb.append("\n session active state=").append(isActive());
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/BrowseTree.java b/android/app/src/com/android/bluetooth/avrcpcontroller/BrowseTree.java
index 612c3cc..df53512 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/BrowseTree.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/BrowseTree.java
@@ -50,9 +50,7 @@
* ....
*/
public class BrowseTree {
- private static final String TAG = "BrowseTree";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
+ private static final String TAG = BrowseTree.class.getSimpleName();
public static final String ROOT = "__ROOT__";
public static final String UP = "__UP__";
@@ -282,7 +280,7 @@
}
synchronized void setCached(boolean cached) {
- if (DBG) Log.d(TAG, "Set Cache" + cached + "Node" + toString());
+ Log.d(TAG, "Set Cache" + cached + "Node" + toString());
mCached = cached;
if (!cached) {
for (BrowseNode child : mChildren) {
@@ -368,9 +366,7 @@
Log.e(TAG, "folder " + parentID + " not found!");
return null;
}
- if (VDBG) {
- Log.d(TAG, "Size" + mBrowseMap.size());
- }
+ Log.d(TAG, "Size" + mBrowseMap.size());
return bn;
}
@@ -419,7 +415,7 @@
synchronized boolean setCurrentAddressedPlayer(String uid) {
BrowseNode bn = mBrowseMap.get(uid);
if (bn == null) {
- if (DBG) Log.d(TAG, "Setting an unknown addressed player, ignoring bn " + uid);
+ Log.w(TAG, "Setting an unknown addressed player, ignoring bn " + uid);
mRootNode.setCached(false);
mRootNode.mChildren.add(mNowPlayingNode);
mBrowseMap.put(NOW_PLAYING_PREFIX, mNowPlayingNode);
@@ -481,7 +477,7 @@
* be notified of the change.
*/
synchronized Set<BrowseNode> notifyImageDownload(String uuid, Uri uri) {
- if (DBG) Log.d(TAG, "Received downloaded image handle to cascade to BrowseNodes using it");
+ Log.d(TAG, "Received downloaded image handle to cascade to BrowseNodes using it");
ArrayList<String> nodes = getNodesUsingCoverArt(uuid);
HashSet<BrowseNode> parents = new HashSet<BrowseNode>();
for (String nodeId : nodes) {
@@ -550,17 +546,15 @@
static BrowseNode getEldestChild(BrowseNode ancestor, BrowseNode target) {
// ancestor is an ancestor of target
BrowseNode descendant = target;
- if (DBG) {
- Log.d(TAG, "NAVIGATING ancestor" + ancestor.toString() + "Target"
- + target.toString());
- }
+ Log.d(TAG, "NAVIGATING ancestor" + ancestor.toString() + "Target"
+ + target.toString());
while (!ancestor.equals(descendant.mParent)) {
descendant = descendant.mParent;
if (descendant == null) {
return null;
}
}
- if (DBG) Log.d(TAG, "NAVIGATING Descendant" + descendant.toString());
+ Log.d(TAG, "NAVIGATING Descendant" + descendant.toString());
return descendant;
}
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java b/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java
index c7dcc97..c4a5d64 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java
@@ -34,10 +34,8 @@
/*
* Values for SetPlayerApplicationSettings from AVRCP Spec V1.6 Appendix F.
*/
- static final byte EQUALIZER_STATUS = 0x01;
static final byte REPEAT_STATUS = 0x02;
static final byte SHUFFLE_STATUS = 0x03;
- static final byte SCAN_STATUS = 0x04;
@VisibleForTesting
static final byte JNI_REPEAT_STATUS_OFF = 0x01;
@@ -177,4 +175,40 @@
}
return JNI_STATUS_INVALID;
}
+
+ public static String repeatStatusToString(int repeatMode) {
+ switch (repeatMode) {
+ case PlaybackStateCompat.REPEAT_MODE_ALL:
+ return "ALL";
+ case PlaybackStateCompat.REPEAT_MODE_GROUP:
+ return "GROUP";
+ case PlaybackStateCompat.REPEAT_MODE_NONE:
+ return "NONE";
+ case PlaybackStateCompat.REPEAT_MODE_ONE:
+ return "ONE";
+ default:
+ return "Unsupported";
+ }
+ }
+
+ public static String shuffleStatusToString(int shuffleMode) {
+ switch (shuffleMode) {
+ case PlaybackStateCompat.SHUFFLE_MODE_NONE:
+ return "NONE";
+ case PlaybackStateCompat.SHUFFLE_MODE_ALL:
+ return "ALL";
+ case PlaybackStateCompat.SHUFFLE_MODE_GROUP:
+ return "GROUP";
+ default:
+ return "Unsupported";
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "<PlayerApplicationSettings"
+ + " repeat=" + repeatStatusToString(getSetting(REPEAT_STATUS))
+ + " shuffle=" + shuffleStatusToString(getSetting(SHUFFLE_STATUS))
+ + ">";
+ }
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java
index 285baaa..82b9fe9 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java
@@ -31,8 +31,7 @@
* This is a base class for implementing AVRCP Controller Basic Image Profile (BIP) requests
*/
abstract class BipRequest {
- private static final String TAG = "avrcpcontroller.BipRequest";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = BipRequest.class.getSimpleName();
// User defined OBEX header identifiers
protected static final byte HEADER_ID_IMG_HANDLE = 0x30;
@@ -162,9 +161,7 @@
* Print to debug if debug is enabled for this class
*/
protected void debug(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
/**
diff --git a/android/app/src/com/android/bluetooth/bas/BatteryService.java b/android/app/src/com/android/bluetooth/bas/BatteryService.java
index e52220d..d33512b 100644
--- a/android/app/src/com/android/bluetooth/bas/BatteryService.java
+++ b/android/app/src/com/android/bluetooth/bas/BatteryService.java
@@ -53,7 +53,6 @@
*/
public class BatteryService extends ProfileService {
private static final String TAG = "BatteryService";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
// Timeout for state machine thread join, to prevent potential ANR.
private static final int SM_THREAD_JOIN_TIMEOUT_MS = 1_000;
@@ -81,9 +80,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sBatteryService != null) {
throw new IllegalStateException("start() called twice");
}
@@ -103,9 +100,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sBatteryService == null) {
Log.w(TAG, "stop() called before start()");
return;
@@ -144,9 +139,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
}
/**
@@ -170,9 +163,7 @@
*/
@VisibleForTesting
public static synchronized void setBatteryService(BatteryService instance) {
- if (DBG) {
- Log.d(TAG, "setBatteryService(): set to: " + instance);
- }
+ Log.d(TAG, "setBatteryService(): set to: " + instance);
sBatteryService = instance;
}
@@ -183,9 +174,7 @@
public boolean connect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (device == null) {
Log.w(TAG, "Ignore connecting to null device");
return false;
@@ -235,9 +224,7 @@
public boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
if (device == null) {
Log.w(TAG, "Ignore disconnecting to null device");
return false;
@@ -314,9 +301,7 @@
if (toState == BluetoothProfile.STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbonded. Remove state machine");
- }
+ Log.d(TAG, device + " is unbonded. Remove state machine");
removeStateMachine(device);
}
}
@@ -403,9 +388,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.BATTERY,
connectionPolicy);
if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
@@ -449,9 +432,7 @@
+ MAX_BATTERY_STATE_MACHINES);
return null;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm = BatteryStateMachine.make(device, this, mStateMachinesThread.getLooper());
mStateMachines.put(device, sm);
return sm;
@@ -473,9 +454,7 @@
*/
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
// Remove state machine if the bonding for a device is removed
if (bondState != BluetoothDevice.BOND_NONE) {
return;
diff --git a/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java b/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java
index a2f1d80..218cff1 100644
--- a/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java
+++ b/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java
@@ -48,7 +48,6 @@
* It manages Battery service of a BLE device
*/
public class BatteryStateMachine extends StateMachine {
- private static final boolean DBG = false;
private static final String TAG = "BatteryStateMachine";
static final UUID GATT_BATTERY_SERVICE_UUID =
@@ -262,15 +261,11 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
static void log(String tag, String msg) {
- if (DBG) {
- Log.d(tag, msg);
- }
+ Log.d(tag, msg);
}
@VisibleForTesting
diff --git a/android/app/src/com/android/bluetooth/bass_client/BaseData.java b/android/app/src/com/android/bluetooth/bass_client/BaseData.java
index cb4702c..a2d75b2 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BaseData.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BaseData.java
@@ -497,8 +497,6 @@
}
static void log(String msg) {
- if (BassConstants.BASS_DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
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 c45059d..b835d91 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
@@ -76,7 +76,6 @@
* Broacast Assistant Scan Service
*/
public class BassClientService extends ProfileService {
- private static final boolean DBG = true;
private static final String TAG = BassClientService.class.getSimpleName();
private static final int MAX_BASS_CLIENT_STATE_MACHINES = 10;
private static final int MAX_ACTIVE_SYNCED_SOURCES_NUM = 4;
@@ -381,9 +380,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sService != null) {
throw new IllegalStateException("start() called twice");
}
@@ -415,9 +412,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
mUnicastSourceStreamStatus = Optional.empty();
@@ -530,9 +525,7 @@
}
private static synchronized void setBassClientService(BassClientService instance) {
- if (DBG) {
- Log.d(TAG, "setBassClientService(): set to: " + instance);
- }
+ Log.d(TAG, "setBassClientService(): set to: " + instance);
sService = instance;
}
@@ -1056,9 +1049,7 @@
* @return true if BAss profile successfully connected, false otherwise
*/
public boolean connect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (device == null) {
Log.e(TAG, "connect: device is null");
return false;
@@ -1086,9 +1077,7 @@
* @return true if Bass client profile successfully disconnected, false otherwise
*/
public boolean disconnect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
if (device == null) {
Log.e(TAG, "disconnect: device is null");
return false;
@@ -1220,9 +1209,7 @@
* @return true if connectionPolicy is set, false on error
*/
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
boolean setSuccessfully =
mDatabaseManager.setProfileConnectionPolicy(device,
BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT, connectionPolicy);
@@ -1858,15 +1845,11 @@
}
static void log(String msg) {
- if (BassConstants.BASS_DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
private void stopSourceReceivers(int broadcastId, boolean store) {
- if (DBG) {
- Log.d(TAG, "stopSourceReceivers(), broadcastId: " + broadcastId + ", store: " + store);
- }
+ Log.d(TAG, "stopSourceReceivers(), broadcastId: " + broadcastId + ", store: " + store);
if (store && !mPausedBroadcastSinks.isEmpty()) {
Log.w(TAG, "stopSourceReceivers(), paused broadcast sinks are replaced");
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 f334264..bda8790 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java
@@ -2241,9 +2241,7 @@
@Override
protected void log(String msg) {
- if (BassConstants.BASS_DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
private static void logByteArray(String prefix, byte[] value, int offset, int count) {
diff --git a/android/app/src/com/android/bluetooth/bass_client/BassConstants.java b/android/app/src/com/android/bluetooth/bass_client/BassConstants.java
index 5edf180..e155d18 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassConstants.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassConstants.java
@@ -24,7 +24,6 @@
* Broadcast Audio Scan Service constants class
*/
public class BassConstants {
- public static final boolean BASS_DBG = true;
public static final ParcelUuid BAAS_UUID =
ParcelUuid.fromString("00001852-0000-1000-8000-00805F9B34FB");
public static final UUID BASS_UUID =
diff --git a/android/app/src/com/android/bluetooth/bass_client/BassUtils.java b/android/app/src/com/android/bluetooth/bass_client/BassUtils.java
index a68a6a6..73dcbb9 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassUtils.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassUtils.java
@@ -47,9 +47,7 @@
}
static void log(String msg) {
- if (BassConstants.BASS_DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
static void printByteArray(byte[] array) {
diff --git a/android/app/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResult.java b/android/app/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResult.java
index 558fadc..8f23446 100644
--- a/android/app/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResult.java
+++ b/android/app/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResult.java
@@ -189,8 +189,6 @@
}
static void log(String msg) {
- if (BassConstants.BASS_DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java b/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java
index 6d308ef..c3dbae2 100644
--- a/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java
+++ b/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java
@@ -127,8 +127,6 @@
}
static void log(String msg) {
- if (BassConstants.BASS_DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
index 71f7ee7..f15b358 100644
--- a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
@@ -101,7 +101,6 @@
*/
public class ActiveDeviceManager implements AdapterService.BluetoothStateCallback {
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;
@@ -220,9 +219,7 @@
}
private void handleAdapterStateChanged(int currentState) {
- if (DBG) {
- Log.d(TAG, "handleAdapterStateChanged: currentState=" + currentState);
- }
+ Log.d(TAG, "handleAdapterStateChanged: currentState=" + currentState);
if (currentState == BluetoothAdapter.STATE_ON) {
resetState();
}
@@ -241,13 +238,9 @@
*/
private void handleA2dpConnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleA2dpConnected: " + device);
- }
+ Log.d(TAG, "handleA2dpConnected: " + device);
if (mA2dpConnectedDevices.contains(device)) {
- if (DBG) {
- Log.d(TAG, "This device is already connected: " + device);
- }
+ Log.d(TAG, "This device is already connected: " + device);
return;
}
mA2dpConnectedDevices.add(device);
@@ -282,10 +275,8 @@
setLeAudioActiveDevice(null, true);
}
} else {
- if (DBG) {
- Log.d(TAG, "A2DP activation is suspended until HFP connected: "
- + device);
- }
+ Log.d(TAG, "A2DP activation is suspended until HFP connected: "
+ + device);
if (mPendingActiveDevice != null) {
mHandler.removeCallbacksAndMessages(mPendingActiveDevice);
}
@@ -316,13 +307,9 @@
*/
private void handleHfpConnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHfpConnected: " + device);
- }
+ Log.d(TAG, "handleHfpConnected: " + device);
if (mHfpConnectedDevices.contains(device)) {
- if (DBG) {
- Log.d(TAG, "This device is already connected: " + device);
- }
+ Log.d(TAG, "This device is already connected: " + device);
return;
}
mHfpConnectedDevices.add(device);
@@ -367,10 +354,8 @@
setLeAudioActiveDevice(null, true);
}
} else {
- if (DBG) {
- Log.d(TAG, "HFP activation is suspended until A2DP connected: "
- + device);
- }
+ Log.d(TAG, "HFP activation is suspended until A2DP connected: "
+ + device);
if (mPendingActiveDevice != null) {
mHandler.removeCallbacksAndMessages(mPendingActiveDevice);
}
@@ -390,13 +375,9 @@
private void handleHearingAidConnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHearingAidConnected: " + device);
- }
+ Log.d(TAG, "handleHearingAidConnected: " + device);
if (mHearingAidConnectedDevices.contains(device)) {
- if (DBG) {
- Log.d(TAG, "This device is already connected: " + device);
- }
+ Log.d(TAG, "This device is already connected: " + device);
return;
}
mHearingAidConnectedDevices.add(device);
@@ -419,9 +400,7 @@
private void handleLeAudioConnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleLeAudioConnected: " + device);
- }
+ Log.d(TAG, "handleLeAudioConnected: " + device);
final LeAudioService leAudioService = mFactory.getLeAudioService();
if (leAudioService == null || device == null) {
@@ -430,9 +409,7 @@
leAudioService.deviceConnected(device);
if (mLeAudioConnectedDevices.contains(device)) {
- if (DBG) {
- Log.d(TAG, "This device is already connected: " + device);
- }
+ Log.d(TAG, "This device is already connected: " + device);
return;
}
@@ -466,13 +443,9 @@
private void handleHapConnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHapConnected: " + device);
- }
+ Log.d(TAG, "handleHapConnected: " + device);
if (mLeHearingAidConnectedDevices.contains(device)) {
- if (DBG) {
- Log.d(TAG, "This device is already connected: " + device);
- }
+ Log.d(TAG, "This device is already connected: " + device);
return;
}
mLeHearingAidConnectedDevices.add(device);
@@ -501,10 +474,8 @@
private void handleA2dpDisconnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleA2dpDisconnected: " + device
- + ", mA2dpActiveDevice=" + mA2dpActiveDevice);
- }
+ Log.d(TAG, "handleA2dpDisconnected: " + device
+ + ", mA2dpActiveDevice=" + mA2dpActiveDevice);
mA2dpConnectedDevices.remove(device);
if (Objects.equals(mA2dpActiveDevice, device)) {
if (!setFallbackDeviceActiveLocked()) {
@@ -516,10 +487,8 @@
private void handleHfpDisconnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHfpDisconnected: " + device
- + ", mHfpActiveDevice=" + mHfpActiveDevice);
- }
+ Log.d(TAG, "handleHfpDisconnected: " + device
+ + ", mHfpActiveDevice=" + mHfpActiveDevice);
mHfpConnectedDevices.remove(device);
if (Objects.equals(mHfpActiveDevice, device)) {
if (mHfpConnectedDevices.isEmpty()) {
@@ -532,10 +501,8 @@
private void handleHearingAidDisconnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHearingAidDisconnected: " + device
- + ", mHearingAidActiveDevices=" + mHearingAidActiveDevices);
- }
+ Log.d(TAG, "handleHearingAidDisconnected: " + device
+ + ", mHearingAidActiveDevices=" + mHearingAidActiveDevices);
mHearingAidConnectedDevices.remove(device);
if (mHearingAidActiveDevices.remove(device) && mHearingAidActiveDevices.isEmpty()) {
if (!setFallbackDeviceActiveLocked()) {
@@ -547,10 +514,8 @@
private void handleLeAudioDisconnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleLeAudioDisconnected: " + device
- + ", mLeAudioActiveDevice=" + mLeAudioActiveDevice);
- }
+ Log.d(TAG, "handleLeAudioDisconnected: " + device
+ + ", mLeAudioActiveDevice=" + mLeAudioActiveDevice);
final LeAudioService leAudioService = mFactory.getLeAudioService();
if (leAudioService == null || device == null) {
@@ -573,10 +538,8 @@
private void handleHapDisconnected(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHapDisconnected: " + device
- + ", mLeHearingAidActiveDevice=" + mLeHearingAidActiveDevice);
- }
+ Log.d(TAG, "handleHapDisconnected: " + device
+ + ", mLeHearingAidActiveDevice=" + mLeHearingAidActiveDevice);
mLeHearingAidConnectedDevices.remove(device);
mPendingLeHearingAidActiveDevice.remove(device);
if (Objects.equals(mLeHearingAidActiveDevice, device)) {
@@ -597,10 +560,8 @@
*/
private void handleA2dpActiveDeviceChanged(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleA2dpActiveDeviceChanged: " + device
- + ", mA2dpActiveDevice=" + mA2dpActiveDevice);
- }
+ Log.d(TAG, "handleA2dpActiveDeviceChanged: " + device
+ + ", mA2dpActiveDevice=" + mA2dpActiveDevice);
if (!Objects.equals(mA2dpActiveDevice, device)) {
if (device != null) {
setHearingAidActiveDevice(null, true);
@@ -663,10 +624,8 @@
*/
private void handleHfpActiveDeviceChanged(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHfpActiveDeviceChanged: " + device
- + ", mHfpActiveDevice=" + mHfpActiveDevice);
- }
+ Log.d(TAG, "handleHfpActiveDeviceChanged: " + device
+ + ", mHfpActiveDevice=" + mHfpActiveDevice);
if (!Objects.equals(mHfpActiveDevice, device)) {
if (device != null) {
setHearingAidActiveDevice(null, true);
@@ -719,10 +678,8 @@
private void handleHearingAidActiveDeviceChanged(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleHearingAidActiveDeviceChanged: " + device
- + ", mHearingAidActiveDevices=" + mHearingAidActiveDevices);
- }
+ Log.d(TAG, "handleHearingAidActiveDeviceChanged: " + device
+ + ", mHearingAidActiveDevices=" + mHearingAidActiveDevices);
// Just assign locally the new value
final HearingAidService hearingAidService = mFactory.getHearingAidService();
if (hearingAidService != null) {
@@ -745,10 +702,8 @@
private void handleLeAudioActiveDeviceChanged(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "handleLeAudioActiveDeviceChanged: " + device
- + ", mLeAudioActiveDevice=" + mLeAudioActiveDevice);
- }
+ Log.d(TAG, "handleLeAudioActiveDeviceChanged: " + device
+ + ", mLeAudioActiveDevice=" + mLeAudioActiveDevice);
if (device != null && !mLeAudioConnectedDevices.contains(device)) {
mLeAudioConnectedDevices.add(device);
}
@@ -786,15 +741,11 @@
@Override
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
- if (DBG) {
- Log.d(TAG, "onAudioDevicesAdded");
- }
+ Log.d(TAG, "onAudioDevicesAdded");
boolean hasAddedWiredDevice = false;
for (AudioDeviceInfo deviceInfo : addedDevices) {
- if (DBG) {
- Log.d(TAG, "Audio device added: " + deviceInfo.getProductName() + " type: "
- + deviceInfo.getType());
- }
+ Log.d(TAG, "Audio device added: " + deviceInfo.getProductName() + " type: "
+ + deviceInfo.getType());
if (isWiredAudioHeadset(deviceInfo)) {
hasAddedWiredDevice = true;
break;
@@ -819,9 +770,7 @@
}
void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
mHandlerThread = new HandlerThread("BluetoothActiveDeviceManager");
BluetoothMethodProxy mp = BluetoothMethodProxy.getInstance();
@@ -833,9 +782,7 @@
}
void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
mAudioManager.unregisterAudioDeviceCallback(mAudioManagerAudioDeviceCallback);
mAdapterService.unregisterBluetoothStateCallback(this);
@@ -866,10 +813,8 @@
private boolean setA2dpActiveDevice(@Nullable BluetoothDevice device,
boolean hasFallbackDevice) {
- if (DBG) {
- Log.d(TAG, "setA2dpActiveDevice(" + device + ")"
- + (device == null ? " hasFallbackDevice=" + hasFallbackDevice : ""));
- }
+ Log.d(TAG, "setA2dpActiveDevice(" + device + ")"
+ + (device == null ? " hasFallbackDevice=" + hasFallbackDevice : ""));
synchronized (mLock) {
if (mPendingActiveDevice != null) {
mHandler.removeCallbacksAndMessages(mPendingActiveDevice);
@@ -902,9 +847,7 @@
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
private boolean setHfpActiveDevice(BluetoothDevice device) {
synchronized (mLock) {
- if (DBG) {
- Log.d(TAG, "setHfpActiveDevice(" + device + ")");
- }
+ Log.d(TAG, "setHfpActiveDevice(" + device + ")");
if (mPendingActiveDevice != null) {
mHandler.removeCallbacksAndMessages(mPendingActiveDevice);
mPendingActiveDevice = null;
@@ -932,10 +875,8 @@
private boolean setHearingAidActiveDevice(@Nullable BluetoothDevice device,
boolean hasFallbackDevice) {
- if (DBG) {
- Log.d(TAG, "setHearingAidActiveDevice(" + device + ")"
- + (device == null ? " hasFallbackDevice=" + hasFallbackDevice : ""));
- }
+ Log.d(TAG, "setHearingAidActiveDevice(" + device + ")"
+ + (device == null ? " hasFallbackDevice=" + hasFallbackDevice : ""));
final HearingAidService hearingAidService = mFactory.getHearingAidService();
if (hearingAidService == null) {
@@ -972,10 +913,8 @@
private boolean setLeAudioActiveDevice(@Nullable BluetoothDevice device,
boolean hasFallbackDevice) {
- if (DBG) {
- Log.d(TAG, "setLeAudioActiveDevice(" + device + ")"
- + (device == null ? " hasFallbackDevice=" + hasFallbackDevice : ""));
- }
+ Log.d(TAG, "setLeAudioActiveDevice(" + device + ")"
+ + (device == null ? " hasFallbackDevice=" + hasFallbackDevice : ""));
synchronized (mLock) {
final LeAudioService leAudioService = mFactory.getLeAudioService();
if (leAudioService == null) {
@@ -989,9 +928,7 @@
if ((mLeAudioActiveDevice != null)
&& (Objects.equals(
mLeAudioActiveDevice, leAudioService.getLeadDevice(device)))) {
- if (DBG) {
- Log.d(TAG, "New LeAudioDevice is a part of an active group");
- }
+ Log.d(TAG, "New LeAudioDevice is a part of an active group");
return true;
}
}
@@ -1042,9 +979,7 @@
*/
@GuardedBy("mLock")
private boolean setFallbackDeviceActiveLocked() {
- if (DBG) {
- Log.d(TAG, "setFallbackDeviceActive");
- }
+ Log.d(TAG, "setFallbackDeviceActive");
mDbManager = mAdapterService.getDatabase();
List<BluetoothDevice> connectedHearingAidDevices = new ArrayList<>();
if (!mHearingAidConnectedDevices.isEmpty()) {
@@ -1058,17 +993,13 @@
mDbManager.getMostRecentlyConnectedDevicesInList(connectedHearingAidDevices);
if (device != null) {
if (mHearingAidConnectedDevices.contains(device)) {
- if (DBG) {
- Log.d(TAG, "Found a hearing aid fallback device: " + device);
- }
+ Log.d(TAG, "Found a hearing aid fallback device: " + device);
setHearingAidActiveDevice(device);
setA2dpActiveDevice(null, true);
setHfpActiveDevice(null);
setLeAudioActiveDevice(null, true);
} else {
- if (DBG) {
- Log.d(TAG, "Found a LE hearing aid fallback device: " + device);
- }
+ Log.d(TAG, "Found a LE hearing aid fallback device: " + device);
setLeHearingAidActiveDevice(device);
setHearingAidActiveDevice(null, true);
setA2dpActiveDevice(null, true);
@@ -1112,9 +1043,7 @@
if (device != null) {
if (mAudioManager.getMode() == AudioManager.MODE_NORMAL) {
if (Objects.equals(a2dpFallbackDevice, device)) {
- if (DBG) {
- Log.d(TAG, "Found an A2DP fallback device: " + device);
- }
+ Log.d(TAG, "Found an A2DP fallback device: " + device);
setA2dpActiveDevice(device);
if (Objects.equals(headsetFallbackDevice, device)) {
setHfpActiveDevice(device);
@@ -1128,9 +1057,7 @@
}
setHearingAidActiveDevice(null, true);
} else {
- if (DBG) {
- Log.d(TAG, "Found a LE audio fallback device: " + device);
- }
+ Log.d(TAG, "Found a LE audio fallback device: " + device);
if (!setLeAudioActiveDevice(device)) {
return false;
}
@@ -1143,9 +1070,7 @@
}
} else {
if (Objects.equals(headsetFallbackDevice, device)) {
- if (DBG) {
- Log.d(TAG, "Found a HFP fallback device: " + device);
- }
+ Log.d(TAG, "Found a HFP fallback device: " + device);
setHfpActiveDevice(device);
if (Objects.equals(a2dpFallbackDevice, device)) {
setA2dpActiveDevice(a2dpFallbackDevice);
@@ -1157,9 +1082,7 @@
}
setHearingAidActiveDevice(null, true);
} else {
- if (DBG) {
- Log.d(TAG, "Found a LE audio fallback device: " + device);
- }
+ Log.d(TAG, "Found a LE audio fallback device: " + device);
setLeAudioActiveDevice(device);
if (!Utils.isDualModeAudioEnabled()) {
setA2dpActiveDevice(null, true);
@@ -1171,9 +1094,7 @@
return true;
}
- if (DBG) {
- Log.d(TAG, "No fallback devices are found");
- }
+ Log.d(TAG, "No fallback devices are found");
return false;
}
@@ -1274,9 +1195,7 @@
@VisibleForTesting
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
void wiredAudioDeviceConnected() {
- if (DBG) {
- Log.d(TAG, "wiredAudioDeviceConnected");
- }
+ Log.d(TAG, "wiredAudioDeviceConnected");
setA2dpActiveDevice(null, true);
setHfpActiveDevice(null);
setHearingAidActiveDevice(null, true);
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterApp.java b/android/app/src/com/android/bluetooth/btservice/AdapterApp.java
index ed873bc..08f69e1 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterApp.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterApp.java
@@ -20,26 +20,21 @@
public class AdapterApp extends Application {
private static final String TAG = "BluetoothAdapterApp";
- private static final boolean DBG = false;
//For Debugging only
private static int sRefCount = 0;
public AdapterApp() {
super();
- if (DBG) {
- synchronized (AdapterApp.class) {
- sRefCount++;
- Log.d(TAG, "REFCOUNT: Constructed " + this + " Instance Count = " + sRefCount);
- }
+ synchronized (AdapterApp.class) {
+ sRefCount++;
+ Log.d(TAG, "REFCOUNT: Constructed " + this + " Instance Count = " + sRefCount);
}
}
@Override
public void onCreate() {
super.onCreate();
- if (DBG) {
- Log.d(TAG, "onCreate");
- }
+ Log.d(TAG, "onCreate");
try {
DataMigration.run(this);
} catch (Exception e) {
@@ -49,11 +44,9 @@
@Override
protected void finalize() {
- if (DBG) {
- synchronized (AdapterApp.class) {
- sRefCount--;
- Log.d(TAG, "REFCOUNT: Finalized: " + this + ", Instance Count = " + sRefCount);
- }
+ synchronized (AdapterApp.class) {
+ sRefCount--;
+ Log.d(TAG, "REFCOUNT: Finalized: " + this + ", Instance Count = " + sRefCount);
}
}
}
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterNativeInterface.java b/android/app/src/com/android/bluetooth/btservice/AdapterNativeInterface.java
index 9f63bc1..9546ab2 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterNativeInterface.java
@@ -17,6 +17,7 @@
package com.android.bluetooth.btservice;
import android.bluetooth.OobData;
+import android.os.ParcelUuid;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -246,6 +247,18 @@
return isLogRedactionEnabledNative();
}
+ int getSocketL2capLocalChannelId(ParcelUuid connectionUuid) {
+ return getSocketL2capLocalChannelIdNative(
+ connectionUuid.getUuid().getLeastSignificantBits(),
+ connectionUuid.getUuid().getMostSignificantBits());
+ }
+
+ int getSocketL2capRemoteChannelId(ParcelUuid connectionUuid) {
+ return getSocketL2capRemoteChannelIdNative(
+ connectionUuid.getUuid().getLeastSignificantBits(),
+ connectionUuid.getUuid().getMostSignificantBits());
+ }
+
/**********************************************************************************************/
/*********************************** callbacks from native ************************************/
/**********************************************************************************************/
@@ -352,4 +365,10 @@
private native boolean pbapPseDynamicVersionUpgradeIsEnabledNative();
private native boolean isLogRedactionEnabledNative();
+
+ private native int getSocketL2capLocalChannelIdNative(
+ long connectionUuidLsb, long connectionUuidMsb);
+
+ private native int getSocketL2capRemoteChannelIdNative(
+ long connectionUuidLsb, long connectionUuidMsb);
}
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java
index 67fb487..61882ca 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java
@@ -75,8 +75,6 @@
import java.util.concurrent.CopyOnWriteArrayList;
class AdapterProperties {
- private static final boolean DBG = true;
- private static final boolean VDBG = false;
private static final String TAG = "AdapterProperties";
private static final String MAX_CONNECTED_AUDIO_DEVICES_PROPERTY =
@@ -763,7 +761,8 @@
if (state == BluetoothProfile.STATE_CONNECTING) {
BluetoothStatsLog.write(BluetoothStatsLog.BLUETOOTH_DEVICE_NAME_REPORTED,
metricId, device.getName());
- MetricsLogger.getInstance().logSanitizedBluetoothDeviceName(metricId, device.getName());
+ MetricsLogger.getInstance()
+ .logAllowlistedDeviceNameHash(metricId, device.getName(), true);
}
BluetoothStatsLog.write(BluetoothStatsLog.BLUETOOTH_CONNECTION_STATE_CHANGED, state,
0 /* deprecated */, profile, mService.obfuscateAddress(device),
@@ -1320,15 +1319,11 @@
}
private static void infoLog(String msg) {
- if (VDBG) {
- Log.i(TAG, msg);
- }
+ Log.i(TAG, msg);
}
private static void debugLog(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
private static void errorLog(String msg) {
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
index 1427c72..8a04ec8 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
@@ -183,8 +183,6 @@
public class AdapterService extends Service {
private static final String TAG = "BluetoothAdapterService";
- private static final boolean DBG = true;
- private static final boolean VERBOSE = false;
private static final int MESSAGE_PROFILE_SERVICE_STATE_CHANGED = 1;
private static final int MESSAGE_PROFILE_SERVICE_REGISTERED = 2;
@@ -348,9 +346,7 @@
};
static {
- if (DBG) {
- Log.d(TAG, "Loading JNI Library");
- }
+ Log.d(TAG, "Loading JNI Library");
if (Utils.isInstrumentationTestMode()) {
Log.w(TAG, "App is instrumented. Skip loading the native");
} else {
@@ -943,7 +939,6 @@
long socketCreationTimeNanos,
boolean isSerialPort,
int appUid) {
-
int metricId = getMetricId(device);
long currentTime = System.nanoTime();
long endToEndLatencyNanos = currentTime - socketCreationTimeNanos;
@@ -1600,12 +1595,10 @@
+ BluetoothProfile.getProfileName(profile) + "): remote device Uuids Empty");
}
- if (VERBOSE) {
- Log.v(TAG, "isProfileSupported(device=" + device + ", profile="
- + BluetoothProfile.getProfileName(profile) + "): local_uuids="
- + Arrays.toString(localDeviceUuids) + ", remote_uuids="
- + Arrays.toString(remoteDeviceUuids));
- }
+ Log.v(TAG, "isProfileSupported(device=" + device + ", profile="
+ + BluetoothProfile.getProfileName(profile) + "): local_uuids="
+ + Arrays.toString(localDeviceUuids) + ", remote_uuids="
+ + Arrays.toString(remoteDeviceUuids));
if (profile == BluetoothProfile.HEADSET) {
return (Utils.arrayContains(localDeviceUuids, BluetoothUuid.HSP_AG)
@@ -7600,15 +7593,11 @@
}
private void debugLog(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
private void verboseLog(String msg) {
- if (VERBOSE) {
- Log.v(TAG, msg);
- }
+ Log.v(TAG, msg);
}
private void errorLog(String msg) {
@@ -7802,9 +7791,12 @@
"screen_off_balanced_interval_millis";
private static final String LE_AUDIO_ALLOW_LIST = "le_audio_allow_list";
- /** Default denylist which matches Eddystone and iBeacon payloads. */
+ /**
+ * Default denylist which matches Eddystone (except for Eddystone-E2EE-EID) and iBeacon
+ * payloads.
+ */
private static final String DEFAULT_LOCATION_DENYLIST_ADVERTISING_DATA =
- "⊆0016AAFE/00FFFFFF,⊆00FF4C0002/00FFFFFFFF";
+ "⊈0016AAFE40/00FFFFFFF0,⊆0016AAFE/00FFFFFF,⊆00FF4C0002/00FFFFFFFF";
private static final int DEFAULT_SCAN_QUOTA_COUNT = 5;
private static final long DEFAULT_SCAN_QUOTA_WINDOW_MILLIS = 30 * SECOND_IN_MILLIS;
@@ -8135,10 +8127,8 @@
return;
}
Log.i(TAG, "sendUuidsInternal: Received service discovery UUIDs for device " + device);
- if (DBG) {
- for (int i = 0; i < uuids.length; i++) {
- Log.d(TAG, "sendUuidsInternal: index=" + i + " uuid=" + uuids[i]);
- }
+ for (int i = 0; i < uuids.length; i++) {
+ Log.d(TAG, "sendUuidsInternal: index=" + i + " uuid=" + uuids[i]);
}
if (mPhonePolicy != null) {
mPhonePolicy.onUuidsDiscovered(device, uuids);
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterState.java b/android/app/src/com/android/bluetooth/btservice/AdapterState.java
index ae395bf..59501ae 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterState.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterState.java
@@ -56,7 +56,6 @@
*/
final class AdapterState extends StateMachine {
- private static final boolean DBG = true;
private static final String TAG = AdapterState.class.getSimpleName();
static final int USER_TURN_ON = 1;
@@ -162,9 +161,7 @@
}
void infoLog(String msg) {
- if (DBG) {
- Log.i(TAG, BluetoothAdapter.nameForState(getStateValue()) + " : " + msg);
- }
+ Log.i(TAG, BluetoothAdapter.nameForState(getStateValue()) + " : " + msg);
}
void errorLog(String msg) {
diff --git a/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java b/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java
index f96f168..12a2d11 100644
--- a/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/AudioRoutingManager.java
@@ -61,7 +61,6 @@
public class AudioRoutingManager extends ActiveDeviceManager {
private static final String TAG = AudioRoutingManager.class.getSimpleName();
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
@VisibleForTesting static final int A2DP_HFP_SYNC_CONNECTION_TIMEOUT_MS = 5_000;
private final AdapterService mAdapterService;
@@ -137,9 +136,7 @@
}
private void handleAdapterStateChanged(int currentState) {
- if (DBG) {
- Log.d(TAG, "handleAdapterStateChanged: currentState=" + currentState);
- }
+ Log.d(TAG, "handleAdapterStateChanged: currentState=" + currentState);
if (currentState == BluetoothAdapter.STATE_ON) {
mHandler.resetState();
}
@@ -157,9 +154,7 @@
@Override
void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
mHandlerThread = new HandlerThread("BluetoothActiveDeviceManager");
BluetoothMethodProxy mp = BluetoothMethodProxy.getInstance();
@@ -173,9 +168,7 @@
@Override
void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
mAudioManager.removeOnModeChangedListener(mHandler);
mAudioManager.unregisterAudioDeviceCallback(mAudioManagerAudioDeviceCallback);
@@ -224,19 +217,15 @@
// Called in mHandler thread. See AudioRoutingManager.start()
@Override
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
- if (DBG) {
- Log.d(TAG, "onAudioDevicesAdded");
- }
+ Log.d(TAG, "onAudioDevicesAdded");
boolean hasAddedWiredDevice = false;
for (AudioDeviceInfo deviceInfo : addedDevices) {
- if (DBG) {
- Log.d(
- TAG,
- "Audio device added: "
- + deviceInfo.getProductName()
- + " type: "
- + deviceInfo.getType());
- }
+ Log.d(
+ TAG,
+ "Audio device added: "
+ + deviceInfo.getProductName()
+ + " type: "
+ + deviceInfo.getType());
if (isWiredAudioHeadset(deviceInfo)) {
hasAddedWiredDevice = true;
break;
@@ -265,20 +254,16 @@
}
public void handleProfileConnected(int profile, BluetoothDevice device) {
- if (DBG) {
- Log.d(
- TAG,
- "handleProfileConnected(device="
- + device
- + ", profile="
- + BluetoothProfile.getProfileName(profile)
- + ")");
- }
+ Log.d(
+ TAG,
+ "handleProfileConnected(device="
+ + device
+ + ", profile="
+ + BluetoothProfile.getProfileName(profile)
+ + ")");
AudioRoutingDevice connectedDevice = getAudioRoutingDevice(device);
if (connectedDevice.connectedProfiles.contains(profile)) {
- if (DBG) {
- Log.d(TAG, "This device is already connected: " + device);
- }
+ Log.d(TAG, "This device is already connected: " + device);
return;
}
connectedDevice.connectedProfiles.add(profile);
@@ -286,9 +271,7 @@
return;
}
if (!connectedDevice.canActivateNow(profile)) {
- if (DBG) {
- Log.d(TAG, "Can not activate now: " + BluetoothProfile.getProfileName(profile));
- }
+ Log.d(TAG, "Can not activate now: " + BluetoothProfile.getProfileName(profile));
mHandler.postDelayed(
() -> activateDeviceProfile(connectedDevice, profile),
connectedDevice,
@@ -299,15 +282,13 @@
}
public void handleProfileDisconnected(int profile, BluetoothDevice device) {
- if (DBG) {
- Log.d(
- TAG,
- "handleProfileDisconnected(device="
- + device
- + ", profile="
- + BluetoothProfile.getProfileName(profile)
- + ")");
- }
+ Log.d(
+ TAG,
+ "handleProfileDisconnected(device="
+ + device
+ + ", profile="
+ + BluetoothProfile.getProfileName(profile)
+ + ")");
AudioRoutingDevice disconnectedDevice = getAudioRoutingDevice(device);
disconnectedDevice.connectedProfiles.remove(profile);
if (disconnectedDevice.connectedProfiles.isEmpty()) {
@@ -338,9 +319,7 @@
@Override
public void onModeChanged(int mode) {
- if (DBG) {
- Log.d(TAG, "onModeChanged: " + mAudioMode + " -> " + mode);
- }
+ Log.d(TAG, "onModeChanged: " + mAudioMode + " -> " + mode);
List<BluetoothDevice> a2dpActiveDevices = getActiveDevices(BluetoothProfile.A2DP);
List<BluetoothDevice> hfpActiveDevices = getActiveDevices(BluetoothProfile.HEADSET);
if (mode == AudioManager.MODE_NORMAL) {
@@ -394,9 +373,7 @@
}
private boolean setFallbackDeviceActive(int profile) {
- if (DBG) {
- Log.d(TAG, "setFallbackDeviceActive: " + BluetoothProfile.getProfileName(profile));
- }
+ Log.d(TAG, "setFallbackDeviceActive: " + BluetoothProfile.getProfileName(profile));
// 1. Activate the lastly activated device among currently activated devices.
Set<AudioRoutingDevice> candidates = new HashSet<>();
for (int i = 0; i < mActiveDevices.size(); ++i) {
@@ -429,9 +406,7 @@
return activateDeviceProfile(fallbackRoutingDevice, profileToActivate);
} catch (NoSuchElementException e) {
// Thrown when no available fallback devices found
- if (DBG) {
- Log.d(TAG, "Found no available BT fallback devices.");
- }
+ Log.d(TAG, "Found no available BT fallback devices.");
return false;
}
}
@@ -488,15 +463,13 @@
public boolean activateDeviceProfile(
@NonNull AudioRoutingDevice routingDevice, int profile) {
mHandler.removeCallbacksAndMessages(routingDevice);
- if (DBG) {
- Log.d(
- TAG,
- "activateDeviceProfile("
- + routingDevice.device
- + ", "
- + BluetoothProfile.getProfileName(profile)
- + ")");
- }
+ Log.d(
+ TAG,
+ "activateDeviceProfile("
+ + routingDevice.device
+ + ", "
+ + BluetoothProfile.getProfileName(profile)
+ + ")");
List<BluetoothDevice> activeDevices = mActiveDevices.get(profile);
if (activeDevices != null && activeDevices.contains(routingDevice.device)) {
@@ -587,15 +560,13 @@
@SuppressLint("MissingPermission")
private boolean setActiveDevice(int profile, BluetoothDevice device) {
- if (DBG) {
- Log.d(
- TAG,
- "setActiveDevice("
- + BluetoothProfile.getProfileName(profile)
- + ", "
- + device
- + ")");
- }
+ Log.d(
+ TAG,
+ "setActiveDevice("
+ + BluetoothProfile.getProfileName(profile)
+ + ", "
+ + device
+ + ")");
boolean activated = switch (profile) {
case BluetoothProfile.A2DP -> {
A2dpService service = mFactory.getA2dpService();
@@ -630,15 +601,13 @@
}
private boolean removeActiveDevice(int profile, boolean hasFallbackDevice) {
- if (DBG) {
- Log.d(
- TAG,
- "removeActiveDevice("
- + BluetoothProfile.getProfileName(profile)
- + ", hadFallbackDevice="
- + hasFallbackDevice
- + ")");
- }
+ Log.d(
+ TAG,
+ "removeActiveDevice("
+ + BluetoothProfile.getProfileName(profile)
+ + ", hadFallbackDevice="
+ + hasFallbackDevice
+ + ")");
mActiveDevices.remove(profile);
return switch (profile) {
case BluetoothProfile.A2DP -> {
@@ -770,9 +739,7 @@
@VisibleForTesting
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
void wiredAudioDeviceConnected() {
- if (DBG) {
- Log.d(TAG, "wiredAudioDeviceConnected");
- }
+ Log.d(TAG, "wiredAudioDeviceConnected");
removeActiveDevice(BluetoothProfile.A2DP, true);
removeActiveDevice(BluetoothProfile.HEADSET, true);
removeActiveDevice(BluetoothProfile.HEARING_AID, true);
diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java b/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java
index e4d5c48..2a5810f 100644
--- a/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java
+++ b/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java
@@ -32,6 +32,8 @@
private static final int INVALID_FD = -1;
+ private static final int INVALID_CID = -1;
+
private AdapterService mService;
BluetoothSocketManagerBinder(AdapterService service) {
@@ -105,18 +107,31 @@
}
@Override
- public boolean checkPermissionForL2capChannelInfo(AttributionSource source) {
+ public int getL2capLocalChannelId(ParcelUuid connectionUuid, AttributionSource source) {
AdapterService service = mService;
if (service == null
|| !Utils.callerIsSystemOrActiveOrManagedUser(
- service, TAG, "checkPermissionForL2capChannelInfo")
+ service, TAG, "getL2capLocalChannelId")
|| !Utils.checkConnectPermissionForDataDelivery(
- service, source,
- "BluetoothSocketManagerBinder checkPermissionForL2capChannelInfo")) {
- return false;
+ service, source, "BluetoothSocketManagerBinder getL2capLocalChannelId")) {
+ return INVALID_CID;
}
Utils.enforceBluetoothPrivilegedPermission(service);
- return true;
+ return service.getNative().getSocketL2capLocalChannelId(connectionUuid);
+ }
+
+ @Override
+ public int getL2capRemoteChannelId(ParcelUuid connectionUuid, AttributionSource source) {
+ AdapterService service = mService;
+ if (service == null
+ || !Utils.callerIsSystemOrActiveOrManagedUser(
+ service, TAG, "getL2capRemoteChannelId")
+ || !Utils.checkConnectPermissionForDataDelivery(
+ service, source, "BluetoothSocketManagerBinder getL2capRemoteChannelId")) {
+ return INVALID_CID;
+ }
+ Utils.enforceBluetoothPrivilegedPermission(service);
+ return service.getNative().getSocketL2capRemoteChannelId(connectionUuid);
}
private void enforceActiveUser() {
diff --git a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java
index 84db24c..5439be2 100644
--- a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java
+++ b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java
@@ -19,21 +19,23 @@
import android.app.AlarmManager;
import android.content.Context;
+import android.os.Build;
import android.os.SystemClock;
import android.util.Log;
+import androidx.annotation.RequiresApi;
+
import com.android.bluetooth.BluetoothMetricsProto.BluetoothLog;
import com.android.bluetooth.BluetoothMetricsProto.ProfileConnectionStats;
import com.android.bluetooth.BluetoothMetricsProto.ProfileId;
import com.android.bluetooth.BluetoothStatsLog;
import com.android.bluetooth.BtRestrictedStatsLog;
import com.android.bluetooth.Utils;
-import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.build.SdkLevel;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
-import com.google.common.hash.Hashing;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -42,7 +44,9 @@
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
/**
* Class of Bluetooth Metrics
@@ -53,8 +57,6 @@
private static final String BLOOMFILTER_FILE = "/devices_for_metrics";
public static final String BLOOMFILTER_FULL_PATH = BLOOMFILTER_PATH + BLOOMFILTER_FILE;
- public static final boolean DEBUG = false;
-
// 6 hours timeout for counter metrics
private static final long BLUETOOTH_COUNTER_METRICS_ACTION_DURATION_MILLIS = 6L * 3600L * 1000L;
private static final int MAX_WORDS_ALLOWED_IN_DEVICE_NAME = 7;
@@ -254,9 +256,7 @@
if (!mInitialized) {
return false;
}
- if (DEBUG) {
- Log.d(TAG, "close()");
- }
+ Log.d(TAG, "close()");
cancelPendingDrain();
drainBufferedCounters();
mAlarmManager = null;
@@ -269,11 +269,10 @@
mAlarmManager.cancel(mOnAlarmListener);
}
- protected boolean logSanitizedBluetoothDeviceName(int metricId, String deviceName) {
- if (!mBloomFilterInitialized || deviceName == null) {
- return false;
+ private List<String> getWordBreakdownList(String deviceName) {
+ if (deviceName == null) {
+ return new ArrayList<String>();
}
-
// remove more than one spaces in a row
deviceName = deviceName.trim().replaceAll(" +", " ");
// remove non alphanumeric characters and spaces, and transform to lower cases.
@@ -282,52 +281,86 @@
if (words.length > MAX_WORDS_ALLOWED_IN_DEVICE_NAME) {
// Validity checking here to avoid excessively long sequences
- return false;
+ return new ArrayList<String>();
}
- // find the longest matched substring
- String matchedString = "";
- byte[] matchedSha256 = null;
+ // collect the word breakdown in an arraylist
+ ArrayList<String> wordBreakdownList = new ArrayList<String>();
for (int start = 0; start < words.length; start++) {
- String toBeMatched = "";
+ StringBuilder deviceNameCombination = new StringBuilder();
for (int end = start; end < words.length; end++) {
- toBeMatched += words[end];
- // TODO(b/280868296): Refactor to log even if bloom filter isn't initialized.
- if (SdkLevel.isAtLeastU()) {
- BtRestrictedStatsLog.write(RESTRICTED_BLUETOOTH_DEVICE_NAME_REPORTED,
- toBeMatched);
- }
- byte[] sha256 = getSha256(toBeMatched);
- if (sha256 == null) {
- continue;
- }
-
- if (mBloomFilter.mightContain(sha256)
- && toBeMatched.length() > matchedString.length()) {
- matchedString = toBeMatched;
- matchedSha256 = sha256;
- }
+ deviceNameCombination.append(words[end]);
+ wordBreakdownList.add(deviceNameCombination.toString());
}
}
- // upload the sha256 of the longest matched string.
- if (matchedSha256 == null) {
- return false;
- }
- statslogBluetoothDeviceNames(
- metricId,
- matchedString,
- Hashing.sha256().hashString(matchedString, StandardCharsets.UTF_8).toString());
- return true;
+ return wordBreakdownList;
}
- protected void statslogBluetoothDeviceNames(int metricId, String matchedString, String sha256) {
+ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ private void uploadRestrictedBluetothDeviceName(List<String> wordBreakdownList) {
+ for (String word : wordBreakdownList) {
+ BtRestrictedStatsLog.write(RESTRICTED_BLUETOOTH_DEVICE_NAME_REPORTED, word);
+ }
+ }
+
+ private String getMatchedString(List<String> wordBreakdownList) {
+ if (!mBloomFilterInitialized || wordBreakdownList.isEmpty()) {
+ return "";
+ }
+
+ String matchedString = "";
+ for (String word : wordBreakdownList) {
+ byte[] sha256 = getSha256(word);
+ if (mBloomFilter.mightContain(sha256) && word.length() > matchedString.length()) {
+ matchedString = word;
+ }
+ }
+ return matchedString;
+ }
+
+ protected String getAllowlistedDeviceNameHash(String deviceName) {
+ List<String> wordBreakdownList = getWordBreakdownList(deviceName);
+ String matchedString = getMatchedString(wordBreakdownList);
+ return getSha256String(matchedString);
+ }
+
+ protected String logAllowlistedDeviceNameHash(
+ int metricId, String deviceName, boolean logRestrictedNames) {
+ List<String> wordBreakdownList = getWordBreakdownList(deviceName);
+ String matchedString = getMatchedString(wordBreakdownList);
+ if (logRestrictedNames) {
+ // Log the restricted bluetooth device name
+ if (SdkLevel.isAtLeastU()) {
+ uploadRestrictedBluetothDeviceName(wordBreakdownList);
+ }
+ }
+ if (!matchedString.isEmpty()) {
+ statslogBluetoothDeviceNames(metricId, matchedString);
+ }
+ return getSha256String(matchedString);
+ }
+
+ protected void statslogBluetoothDeviceNames(int metricId, String matchedString) {
+ String sha256 = getSha256String(matchedString);
Log.d(TAG,
"Uploading sha256 hash of matched bluetooth device name: " + sha256);
BluetoothStatsLog.write(
BluetoothStatsLog.BLUETOOTH_HASHED_DEVICE_NAME_REPORTED, metricId, sha256);
}
+ protected static String getSha256String(String name) {
+ if (name.isEmpty()) {
+ return "";
+ }
+ StringBuilder hexString = new StringBuilder();
+ byte[] hashBytes = getSha256(name);
+ for (byte b : hashBytes) {
+ hexString.append(String.format("%02x", b));
+ }
+ return hexString.toString();
+ }
+
protected static byte[] getSha256(String name) {
MessageDigest digest = null;
try {
diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
index f978c34..080b047 100644
--- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
+++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
@@ -64,7 +64,6 @@
// will try to connect other profiles on the same device. This is to avoid collision if devices
// somehow end up trying to connect at same time or general connection issues.
public class PhonePolicy implements AdapterService.BluetoothStateCallback {
- private static final boolean DBG = true;
private static final String TAG = "BluetoothPhonePolicy";
// Message types for the handler (internal messages generated by intents or timeouts)
@@ -889,9 +888,7 @@
}
private static void debugLog(String msg) {
- if (DBG) {
- Log.i(TAG, msg);
- }
+ Log.d(TAG, msg);
}
private static void warnLog(String msg) {
diff --git a/android/app/src/com/android/bluetooth/btservice/ProfileService.java b/android/app/src/com/android/bluetooth/btservice/ProfileService.java
index f8c43cb..181fa5b 100644
--- a/android/app/src/com/android/bluetooth/btservice/ProfileService.java
+++ b/android/app/src/com/android/bluetooth/btservice/ProfileService.java
@@ -32,7 +32,6 @@
/** Base class for a background service that runs a Bluetooth profile */
public abstract class ProfileService extends ContextWrapper {
- private static final boolean DBG = false;
public static final String BLUETOOTH_PERM =
android.Manifest.permission.BLUETOOTH;
@@ -90,9 +89,7 @@
protected ProfileService(Context ctx) {
super(ctx);
mName = getName();
- if (DBG) {
- Log.d(mName, "Service created");
- }
+ Log.d(mName, "Service created");
mBinder = requireNonNull(initBinder(), "Binder null is not allowed for " + mName);
}
@@ -114,10 +111,8 @@
*/
@RequiresPermission(android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE)
protected void setComponentAvailable(String className, boolean enable) {
- if (DBG) {
- Log.d(mName, "setComponentAvailable(className=" + className + ", enable=" + enable
- + ")");
- }
+ Log.d(mName, "setComponentAvailable(className=" + className + ", enable=" + enable
+ + ")");
if (className == null) {
return;
}
@@ -137,10 +132,8 @@
*/
@RequiresPermission(android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE)
protected void setComponentAvailable(ComponentName component, boolean enable) {
- if (DBG) {
- Log.d(mName, "setComponentAvailable(component=" + component + ", enable=" + enable
- + ")");
- }
+ Log.d(mName, "setComponentAvailable(component=" + component + ", enable=" + enable
+ + ")");
if (component == null) {
return;
}
diff --git a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
index e9995f3..5738ca0 100644
--- a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
+++ b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
@@ -63,7 +63,6 @@
/** Remote device manager. This class is currently mostly used for HF and AG remote devices. */
public class RemoteDevices {
- private static final boolean DBG = false;
private static final String TAG = "BluetoothRemoteDevices";
// Maximum number of device properties to remember
@@ -1552,15 +1551,11 @@
}
private static void debugLog(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
private static void infoLog(String msg) {
- if (DBG) {
- Log.i(TAG, msg);
- }
+ Log.i(TAG, msg);
}
private static void warnLog(String msg) {
diff --git a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java
index 38d306f..196401d 100644
--- a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java
@@ -55,8 +55,7 @@
* 6) If a device is not connected with A2DP or HFP, it cannot enter silence mode.
*/
public class SilenceDeviceManager {
- private static final boolean VERBOSE = false;
- private static final String TAG = "SilenceDeviceManager";
+ private static final String TAG = SilenceDeviceManager.class.getSimpleName();
private final AdapterService mAdapterService;
private final ServiceFactory mFactory;
@@ -125,9 +124,7 @@
@Override
public void handleMessage(Message msg) {
- if (VERBOSE) {
- Log.d(TAG, "handleMessage: " + msg.what);
- }
+ Log.d(TAG, "handleMessage: " + msg.what);
switch (msg.what) {
case MSG_SILENCE_DEVICE_STATE_CHANGED: {
BluetoothDevice device = (BluetoothDevice) msg.obj;
@@ -208,16 +205,12 @@
}
void start() {
- if (VERBOSE) {
- Log.v(TAG, "start()");
- }
+ Log.v(TAG, "start()");
mHandler = new SilenceDeviceManagerHandler(mLooper);
}
void cleanup() {
- if (VERBOSE) {
- Log.v(TAG, "cleanup()");
- }
+ Log.v(TAG, "cleanup()");
mSilenceDevices.clear();
}
@@ -282,10 +275,8 @@
}
void addConnectedDevice(BluetoothDevice device, int profile) {
- if (VERBOSE) {
- Log.d(TAG, "addConnectedDevice: " + device + ", profile:"
- + BluetoothProfile.getProfileName(profile));
- }
+ Log.d(TAG, "addConnectedDevice: " + device + ", profile:"
+ + BluetoothProfile.getProfileName(profile));
switch (profile) {
case BluetoothProfile.A2DP:
if (!mA2dpConnectedDevices.contains(device)) {
@@ -301,10 +292,8 @@
}
void removeConnectedDevice(BluetoothDevice device, int profile) {
- if (VERBOSE) {
- Log.d(TAG, "removeConnectedDevice: " + device + ", profile:"
- + BluetoothProfile.getProfileName(profile));
- }
+ Log.d(TAG, "removeConnectedDevice: " + device + ", profile:"
+ + BluetoothProfile.getProfileName(profile));
switch (profile) {
case BluetoothProfile.A2DP:
if (mA2dpConnectedDevices.contains(device)) {
diff --git a/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java b/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java
index 1eeee08..d9b30db 100644
--- a/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java
+++ b/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java
@@ -61,9 +61,7 @@
* Service used for handling encryption and decryption of the bt_config.conf
*/
public class BluetoothKeystoreService {
- private static final String TAG = "BluetoothKeystoreService";
-
- private static final boolean DBG = false;
+ private static final String TAG = BluetoothKeystoreService.class.getSimpleName();
private static BluetoothKeystoreService sBluetoothKeystoreService;
private boolean mIsCommonCriteriaMode;
@@ -791,9 +789,7 @@
}
private static void infoLog(String msg) {
- if (DBG) {
- Log.i(TAG, msg);
- }
+ Log.i(TAG, msg);
}
private static void debugLog(String msg) {
diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java
index 71ff678..1ffbfe9 100644
--- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java
@@ -32,7 +32,6 @@
*/
public class CsipSetCoordinatorNativeInterface {
private static final String TAG = "CsipSetCoordinatorNativeInterface";
- private static final boolean DBG = false;
private BluetoothAdapter mAdapter;
@GuardedBy("INSTANCE_LOCK")
@@ -146,9 +145,7 @@
event.device = getDevice(address);
event.valueInt1 = state;
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -165,9 +162,7 @@
event.valueInt3 = rank;
event.valueUuid1 = uuid;
- if (DBG) {
- Log.d(TAG, "onDeviceAvailable: " + event);
- }
+ Log.d(TAG, "onDeviceAvailable: " + event);
sendMessageToService(event);
}
@@ -184,9 +179,7 @@
CsipSetCoordinatorStackEvent.EVENT_TYPE_SET_MEMBER_AVAILABLE);
event.device = getDevice(address);
event.valueInt1 = groupId;
- if (DBG) {
- Log.d(TAG, "onSetMemberAvailable: " + event);
- }
+ Log.d(TAG, "onSetMemberAvailable: " + event);
sendMessageToService(event);
}
@@ -205,9 +198,7 @@
event.valueInt1 = groupId;
event.valueInt2 = status;
event.valueBool1 = locked;
- if (DBG) {
- Log.d(TAG, "onGroupLockChanged: " + event);
- }
+ Log.d(TAG, "onGroupLockChanged: " + event);
sendMessageToService(event);
}
diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
index 6ab92a8..c776d76 100644
--- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
+++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
@@ -71,7 +71,6 @@
* Provides Bluetooth CSIP Set Coordinator profile, as a service.
*/
public class CsipSetCoordinatorService extends ProfileService {
- private static final boolean DBG = false;
private static final String TAG = "CsipSetCoordinatorService";
// Timeout for state machine thread join, to prevent potential ANR.
@@ -122,9 +121,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sCsipSetCoordinatorService != null) {
throw new IllegalStateException("start() called twice");
}
@@ -165,9 +162,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sCsipSetCoordinatorService == null) {
Log.w(TAG, "stop() called before start()");
return;
@@ -221,9 +216,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
}
/**
@@ -245,9 +238,7 @@
private static synchronized void setCsipSetCoordinatorService(
CsipSetCoordinatorService instance) {
- if (DBG) {
- Log.d(TAG, "setCsipSetCoordinatorService(): set to: " + instance);
- }
+ Log.d(TAG, "setCsipSetCoordinatorService(): set to: " + instance);
sCsipSetCoordinatorService = instance;
}
@@ -259,9 +250,7 @@
public boolean connect(BluetoothDevice device) {
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (device == null) {
return false;
}
@@ -295,9 +284,7 @@
public boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
if (device == null) {
return false;
}
@@ -467,9 +454,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(
device, BluetoothProfile.CSIP_SET_COORDINATOR, connectionPolicy);
if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
@@ -502,9 +487,7 @@
public @Nullable UUID lockGroup(
int groupId, @NonNull IBluetoothCsipSetCoordinatorLockCallback callback) {
if (callback == null) {
- if (DBG) {
- Log.d(TAG, "lockGroup(): " + groupId + ", callback not provided ");
- }
+ Log.d(TAG, "lockGroup(): " + groupId + ", callback not provided ");
return null;
}
@@ -531,18 +514,14 @@
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
- if (DBG) {
- Log.d(TAG, "lockGroup(): " + groupId + ", ERROR_CSIP_GROUP_LOCKED_BY_OTHER ");
- }
+ Log.d(TAG, "lockGroup(): " + groupId + ", ERROR_CSIP_GROUP_LOCKED_BY_OTHER ");
return null;
}
mLocks.put(groupId, new Pair<>(uuid, callback));
}
- if (DBG) {
- Log.d(TAG, "lockGroup(): locking group: " + groupId);
- }
+ Log.d(TAG, "lockGroup(): locking group: " + groupId);
mCsipSetCoordinatorNativeInterface.groupLockSet(groupId, true);
return uuid;
}
@@ -553,9 +532,7 @@
*/
public void unlockGroup(@NonNull UUID lockUuid) {
if (lockUuid == null) {
- if (DBG) {
- Log.d(TAG, "unlockGroup(): lockUuid is null");
- }
+ Log.d(TAG, "unlockGroup(): lockUuid is null");
return;
}
@@ -564,9 +541,7 @@
mLocks.entrySet()) {
Pair<UUID, IBluetoothCsipSetCoordinatorLockCallback> uuidCbPair = entry.getValue();
if (uuidCbPair.first.equals(lockUuid)) {
- if (DBG) {
- Log.d(TAG, "unlockGroup(): unlocking ... " + lockUuid);
- }
+ Log.d(TAG, "unlockGroup(): unlocking ... " + lockUuid);
mCsipSetCoordinatorNativeInterface.groupLockSet(entry.getKey(), false);
return;
}
@@ -765,9 +740,7 @@
for (Map.Entry<Executor, IBluetoothCsipSetCoordinatorCallback> entry :
mCallbacks.get(uuid).entrySet()) {
- if (DBG) {
- Log.d(TAG, " executing " + uuid + " " + entry.getKey());
- }
+ Log.d(TAG, " executing " + uuid + " " + entry.getKey());
try {
executeCallback(entry.getKey(), entry.getValue(), device, groupId);
} catch (RemoteException e) {
@@ -816,9 +789,7 @@
}
void notifySetMemberAvailable(BluetoothDevice device, int groupId) {
- if (DBG) {
- Log.d(TAG, "notifySetMemberAvailable: " + device + ", " + groupId);
- }
+ Log.d(TAG, "notifySetMemberAvailable: " + device + ", " + groupId);
/* Sent intent as well */
Intent intent = new Intent(BluetoothCsipSetCoordinator.ACTION_CSIS_SET_MEMBER_AVAILABLE);
@@ -916,9 +887,7 @@
+ MAX_CSIS_STATE_MACHINES);
return null;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm = CsipSetCoordinatorStateMachine.make(device, this,
mCsipSetCoordinatorNativeInterface, mStateMachinesThread.getLooper());
mStateMachines.put(device, sm);
@@ -941,9 +910,7 @@
*/
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
if (bondState == BluetoothDevice.BOND_BONDING
&& mFoundSetMemberToGroupId.containsKey(device)) {
mFoundSetMemberToGroupId.remove(device);
@@ -1011,9 +978,7 @@
if (toState == BluetoothProfile.STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
+ Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
}
} else if (toState == BluetoothProfile.STATE_CONNECTED) {
diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java
index 5f2ed95..1013d17 100644
--- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java
+++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java
@@ -41,7 +41,6 @@
* CSIP Set Coordinator role device state machine
*/
public class CsipSetCoordinatorStateMachine extends StateMachine {
- private static final boolean DBG = false;
private static final String TAG = "CsipSetCoordinatorStateMachine";
static final int CONNECT = 1;
@@ -156,9 +155,7 @@
break;
case STACK_EVENT:
CsipSetCoordinatorStackEvent event = (CsipSetCoordinatorStackEvent) message.obj;
- if (DBG) {
- Log.d(TAG, "Disconnected: stack event: " + event);
- }
+ Log.d(TAG, "Disconnected: stack event: " + event);
if (!mDevice.equals(event.device)) {
Log.wtf(TAG, "Device(" + mDevice + "): event mismatch: " + event);
}
@@ -583,8 +580,6 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java b/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java
index 11d112f..9efbd1b 100644
--- a/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java
+++ b/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java
@@ -45,7 +45,6 @@
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public class AdvertiseManager {
- private static final boolean DBG = GattServiceConfig.DBG;
private static final String TAG = GattServiceConfig.TAG_PREFIX + "AdvertiseManager";
private final GattService mService;
@@ -60,9 +59,7 @@
GattService service,
AdvertiseManagerNativeInterface nativeInterface,
AdvertiserMap advertiserMap) {
- if (DBG) {
- Log.d(TAG, "advertise manager created");
- }
+ Log.d(TAG, "advertise manager created");
mService = service;
mNativeInterface = nativeInterface;
mAdvertiserMap = advertiserMap;
@@ -75,9 +72,7 @@
}
void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
mNativeInterface.cleanup();
mAdvertisers.clear();
sTempRegistrationId = -1;
@@ -123,11 +118,9 @@
@Override
public void binderDied() {
- if (DBG) {
- Log.d(
- TAG,
- "Binder is dead - unregistering advertising set (" + mPackageName + ")!");
- }
+ Log.d(
+ TAG,
+ "Binder is dead - unregistering advertising set (" + mPackageName + ")!");
stopAdvertisingSet(callback);
}
}
@@ -145,11 +138,9 @@
void onAdvertisingSetStarted(int regId, int advertiserId, int txPower, int status)
throws Exception {
- if (DBG) {
- Log.d(TAG,
- "onAdvertisingSetStarted() - regId=" + regId + ", advertiserId=" + advertiserId
- + ", status=" + status);
- }
+ Log.d(TAG,
+ "onAdvertisingSetStarted() - regId=" + regId + ", advertiserId=" + advertiserId
+ + ", status=" + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(regId);
@@ -184,10 +175,8 @@
}
void onAdvertisingEnabled(int advertiserId, boolean enable, int status) throws Exception {
- if (DBG) {
- Log.d(TAG, "onAdvertisingSetEnabled() - advertiserId=" + advertiserId + ", enable="
- + enable + ", status=" + status);
- }
+ Log.d(TAG, "onAdvertisingSetEnabled() - advertiserId=" + advertiserId + ", enable="
+ + enable + ", status=" + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -254,9 +243,7 @@
int cbId = --sTempRegistrationId;
mAdvertisers.put(binder, new AdvertiserInfo(cbId, deathRecipient, callback));
- if (DBG) {
- Log.d(TAG, "startAdvertisingSet() - reg_id=" + cbId + ", callback: " + binder);
- }
+ Log.d(TAG, "startAdvertisingSet() - reg_id=" + cbId + ", callback: " + binder);
mAdvertiserMap.add(cbId, callback, mService);
mAdvertiserMap.recordAdvertiseStart(cbId, parameters, advertiseData,
@@ -287,9 +274,7 @@
void onOwnAddressRead(int advertiserId, int addressType, String address)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onOwnAddressRead() advertiserId=" + advertiserId);
- }
+ Log.d(TAG, "onOwnAddressRead() advertiserId=" + advertiserId);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -312,9 +297,7 @@
void stopAdvertisingSet(IAdvertisingSetCallback callback) {
IBinder binder = toBinder(callback);
- if (DBG) {
- Log.d(TAG, "stopAdvertisingSet() " + binder);
- }
+ Log.d(TAG, "stopAdvertisingSet() " + binder);
AdvertiserInfo adv = mAdvertisers.remove(binder);
if (adv == null) {
@@ -453,10 +436,8 @@
}
void onAdvertisingDataSet(int advertiserId, int status) throws Exception {
- if (DBG) {
- Log.d(TAG,
- "onAdvertisingDataSet() advertiserId=" + advertiserId + ", status=" + status);
- }
+ Log.d(TAG,
+ "onAdvertisingDataSet() advertiserId=" + advertiserId + ", status=" + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -469,10 +450,8 @@
}
void onScanResponseDataSet(int advertiserId, int status) throws Exception {
- if (DBG) {
- Log.d(TAG,
- "onScanResponseDataSet() advertiserId=" + advertiserId + ", status=" + status);
- }
+ Log.d(TAG,
+ "onScanResponseDataSet() advertiserId=" + advertiserId + ", status=" + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -486,11 +465,9 @@
void onAdvertisingParametersUpdated(int advertiserId, int txPower, int status)
throws Exception {
- if (DBG) {
- Log.d(TAG,
- "onAdvertisingParametersUpdated() advertiserId=" + advertiserId + ", txPower="
- + txPower + ", status=" + status);
- }
+ Log.d(TAG,
+ "onAdvertisingParametersUpdated() advertiserId=" + advertiserId + ", txPower="
+ + txPower + ", status=" + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -503,10 +480,8 @@
}
void onPeriodicAdvertisingParametersUpdated(int advertiserId, int status) throws Exception {
- if (DBG) {
- Log.d(TAG, "onPeriodicAdvertisingParametersUpdated() advertiserId=" + advertiserId
- + ", status=" + status);
- }
+ Log.d(TAG, "onPeriodicAdvertisingParametersUpdated() advertiserId=" + advertiserId
+ + ", status=" + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -520,10 +495,8 @@
}
void onPeriodicAdvertisingDataSet(int advertiserId, int status) throws Exception {
- if (DBG) {
- Log.d(TAG, "onPeriodicAdvertisingDataSet() advertiserId=" + advertiserId + ", status="
- + status);
- }
+ Log.d(TAG, "onPeriodicAdvertisingDataSet() advertiserId=" + advertiserId + ", status="
+ + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
@@ -537,10 +510,8 @@
void onPeriodicAdvertisingEnabled(int advertiserId, boolean enable, int status)
throws Exception {
- if (DBG) {
- Log.d(TAG, "onPeriodicAdvertisingEnabled() advertiserId=" + advertiserId + ", status="
- + status);
- }
+ Log.d(TAG, "onPeriodicAdvertisingEnabled() advertiserId=" + advertiserId + ", status="
+ + status);
Map.Entry<IBinder, AdvertiserInfo> entry = findAdvertiser(advertiserId);
if (entry == null) {
diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
index 77c3e01..e01f6ab 100644
--- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
+++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
@@ -40,8 +40,7 @@
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public class DistanceMeasurementManager {
- private static final boolean DBG = GattServiceConfig.DBG;
- private static final String TAG = "DistanceMeasurementManager";
+ private static final String TAG = DistanceMeasurementManager.class.getSimpleName();
private static final int RSSI_LOW_FREQUENCY_INTERVAL_MS = 3000;
private static final int RSSI_MEDIUM_FREQUENCY_INTERVAL_MS = 1000;
@@ -85,13 +84,15 @@
IDistanceMeasurementCallback callback) {
Log.i(TAG, "startDistanceMeasurement device:" + params.getDevice().getAnonymizedAddress()
+ ", method: " + params.getMethodId());
- String identityAddress = mAdapterService.getIdentityAddress(
- params.getDevice().getAddress());
- if (identityAddress == null) {
- identityAddress = params.getDevice().getAddress();
+ String address = mAdapterService.getIdentityAddress(params.getDevice().getAddress());
+ if (address == null) {
+ address = params.getDevice().getAddress();
}
- logd("Get identityAddress: " + params.getDevice().getAnonymizedAddress() + " => "
- + BluetoothUtils.toAnonymizedAddress(identityAddress));
+ logd(
+ "Get identityAddress: "
+ + params.getDevice().getAnonymizedAddress()
+ + " => "
+ + BluetoothUtils.toAnonymizedAddress(address));
int interval = getIntervalValue(params.getFrequency(), params.getMethodId());
if (interval == -1) {
@@ -101,8 +102,7 @@
}
DistanceMeasurementTracker tracker =
- new DistanceMeasurementTracker(
- this, params, identityAddress, uuid, interval, callback);
+ new DistanceMeasurementTracker(this, params, address, uuid, interval, callback);
switch (params.getMethodId()) {
case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_AUTO:
@@ -158,19 +158,22 @@
boolean timeout) {
Log.i(TAG, "stopDistanceMeasurement device:" + device.getAnonymizedAddress()
+ ", method: " + method + " timeout " + timeout);
- String identityAddress = mAdapterService.getIdentityAddress(device.getAddress());
- if (identityAddress == null) {
- identityAddress = device.getAddress();
+ String address = mAdapterService.getIdentityAddress(device.getAddress());
+ if (address == null) {
+ address = device.getAddress();
}
- logd("Get identityAddress: " + device.getAnonymizedAddress() + " => "
- + BluetoothUtils.toAnonymizedAddress(identityAddress));
+ logd(
+ "Get identityAddress: "
+ + device.getAnonymizedAddress()
+ + " => "
+ + BluetoothUtils.toAnonymizedAddress(address));
switch (method) {
case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_AUTO:
case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI:
- return stopRssiTracker(uuid, identityAddress, timeout);
+ return stopRssiTracker(uuid, address, timeout);
case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING:
- return stopCsTracker(uuid, identityAddress, timeout);
+ return stopCsTracker(uuid, address, timeout);
default:
Log.w(TAG, "stopDistanceMeasurement with invalid method:" + method);
return BluetoothStatusCodes.ERROR_DISTANCE_MEASUREMENT_INTERNAL;
@@ -468,8 +471,6 @@
/** Logs the message in debug ROM. */
private static void logd(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
+ Log.d(TAG, msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/gatt/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java
index a5476c6..d1402d1 100644
--- a/android/app/src/com/android/bluetooth/gatt/GattService.java
+++ b/android/app/src/com/android/bluetooth/gatt/GattService.java
@@ -101,8 +101,6 @@
* the Bluetooth application.
*/
public class GattService extends ProfileService {
- private static final boolean DBG = GattServiceConfig.DBG;
- private static final boolean VDBG = GattServiceConfig.VDBG;
private static final String TAG = GattServiceConfig.TAG_PREFIX + "GattService";
private static final UUID HID_SERVICE_UUID =
@@ -214,9 +212,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
Settings.Global.putInt(
getContentResolver(), "bluetooth_sanitized_exposure_notification_supported", 1);
@@ -243,9 +239,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
mTransitionalScanHelper.stop();
mAdvertiserMap.clear();
mClientMap.clear();
@@ -260,9 +254,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
if (mNativeInterface != null) {
mNativeInterface.cleanup();
mNativeInterface = null;
@@ -363,15 +355,13 @@
@Override
public void binderDied() {
- if (DBG) {
- Log.d(
- TAG,
- "Binder is dead - unregistering server ("
- + mPackageName
- + " "
- + mAppIf
- + ")!");
- }
+ Log.d(
+ TAG,
+ "Binder is dead - unregistering server ("
+ + mPackageName
+ + " "
+ + mAppIf
+ + ")!");
unregisterServer(mAppIf, getAttributionSource());
}
}
@@ -387,15 +377,13 @@
@Override
public void binderDied() {
- if (DBG) {
- Log.d(
- TAG,
- "Binder is dead - unregistering client ("
- + mPackageName
- + " "
- + mAppIf
- + ")!");
- }
+ Log.d(
+ TAG,
+ "Binder is dead - unregistering client ("
+ + mPackageName
+ + " "
+ + mAppIf
+ + ")!");
unregisterClient(mAppIf, getAttributionSource());
}
}
@@ -1731,9 +1719,7 @@
void onClientRegistered(int status, int clientIf, long uuidLsb, long uuidMsb)
throws RemoteException {
UUID uuid = new UUID(uuidMsb, uuidLsb);
- if (DBG) {
- Log.d(TAG, "onClientRegistered() - UUID=" + uuid + ", clientIf=" + clientIf);
- }
+ Log.d(TAG, "onClientRegistered() - UUID=" + uuid + ", clientIf=" + clientIf);
ClientMap.App app = mClientMap.getByUuid(uuid);
if (app != null) {
if (status == 0) {
@@ -1747,10 +1733,8 @@
}
void onConnected(int clientIf, int connId, int status, String address) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onConnected() - clientIf=" + clientIf + ", connId=" + connId + ", address="
- + address);
- }
+ Log.d(TAG, "onConnected() - clientIf=" + clientIf + ", connId=" + connId + ", address="
+ + address);
int connectionState = BluetoothProtoEnums.CONNECTION_STATE_DISCONNECTED;
if (status == 0) {
mClientMap.addConnection(clientIf, connId, address);
@@ -1775,11 +1759,9 @@
void onDisconnected(int clientIf, int connId, int status, String address)
throws RemoteException {
- if (DBG) {
- Log.d(TAG,
- "onDisconnected() - clientIf=" + clientIf + ", connId=" + connId + ", address="
- + address);
- }
+ Log.d(TAG,
+ "onDisconnected() - clientIf=" + clientIf + ", connId=" + connId + ", address="
+ + address);
mClientMap.removeConnection(clientIf, connId);
ClientMap.App app = mClientMap.getById(clientIf);
@@ -1813,9 +1795,7 @@
}
void onClientPhyUpdate(int connId, int txPhy, int rxPhy, int status) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onClientPhyUpdate() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onClientPhyUpdate() - connId=" + connId + ", status=" + status);
String address = mClientMap.addressByConnId(connId);
if (address == null) {
@@ -1832,11 +1812,9 @@
void onClientPhyRead(int clientIf, String address, int txPhy, int rxPhy, int status)
throws RemoteException {
- if (DBG) {
- Log.d(TAG,
- "onClientPhyRead() - address=" + address + ", status=" + status + ", clientIf="
- + clientIf);
- }
+ Log.d(TAG,
+ "onClientPhyRead() - address=" + address + ", status=" + status + ", clientIf="
+ + clientIf);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
@@ -1854,9 +1832,7 @@
void onClientConnUpdate(int connId, int interval, int latency, int timeout, int status)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onClientConnUpdate() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onClientConnUpdate() - connId=" + connId + ", status=" + status);
String address = mClientMap.addressByConnId(connId);
if (address == null) {
@@ -1872,9 +1848,7 @@
}
void onServiceChanged(int connId) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServiceChanged - connId=" + connId);
- }
+ Log.d(TAG, "onServiceChanged - connId=" + connId);
String address = mClientMap.addressByConnId(connId);
if (address == null) {
@@ -1891,9 +1865,7 @@
void onClientSubrateChange(int connId, int subrateFactor, int latency, int contNum,
int timeout, int status) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onClientSubrateChange() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onClientSubrateChange() - connId=" + connId + ", status=" + status);
String address = mClientMap.addressByConnId(connId);
if (address == null) {
@@ -1909,9 +1881,7 @@
}
void onServerPhyUpdate(int connId, int txPhy, int rxPhy, int status) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServerPhyUpdate() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onServerPhyUpdate() - connId=" + connId + ", status=" + status);
String address = mServerMap.addressByConnId(connId);
if (address == null) {
@@ -1928,9 +1898,7 @@
void onServerPhyRead(int serverIf, String address, int txPhy, int rxPhy, int status)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServerPhyRead() - address=" + address + ", status=" + status);
- }
+ Log.d(TAG, "onServerPhyRead() - address=" + address + ", status=" + status);
Integer connId = mServerMap.connIdByAddress(serverIf, address);
if (connId == null) {
@@ -1948,9 +1916,7 @@
void onServerConnUpdate(int connId, int interval, int latency, int timeout, int status)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServerConnUpdate() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onServerConnUpdate() - connId=" + connId + ", status=" + status);
String address = mServerMap.addressByConnId(connId);
if (address == null) {
@@ -1968,9 +1934,7 @@
void onServerSubrateChange(int connId, int subrateFactor, int latency, int contNum,
int timeout, int status)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServerSubrateChange() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onServerSubrateChange() - connId=" + connId + ", status=" + status);
String address = mServerMap.addressByConnId(connId);
if (address == null) {
@@ -1986,9 +1950,7 @@
}
void onSearchCompleted(int connId, int status) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onSearchCompleted() - connId=" + connId + ", status=" + status);
- }
+ Log.d(TAG, "onSearchCompleted() - connId=" + connId + ", status=" + status);
// Gatt DB is ready!
// This callback was called from the jni_workqueue thread. If we make request to the stack
@@ -2009,9 +1971,7 @@
void onGetGattDb(int connId, ArrayList<GattDbElement> db) throws RemoteException {
String address = mClientMap.addressByConnId(connId);
- if (DBG) {
- Log.d(TAG, "onGetGattDb() - address=" + address);
- }
+ Log.d(TAG, "onGetGattDb() - address=" + address);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app == null || app.callback == null) {
@@ -2032,9 +1992,7 @@
switch (el.type) {
case GattDbElement.TYPE_PRIMARY_SERVICE:
case GattDbElement.TYPE_SECONDARY_SERVICE:
- if (DBG) {
- Log.d(TAG, "got service with UUID=" + el.uuid + " id: " + el.id);
- }
+ Log.d(TAG, "got service with UUID=" + el.uuid + " id: " + el.id);
currSrvc = new BluetoothGattService(el.uuid, el.id, el.type);
dbOut.add(currSrvc);
@@ -2046,9 +2004,7 @@
break;
case GattDbElement.TYPE_CHARACTERISTIC:
- if (DBG) {
- Log.d(TAG, "got characteristic with UUID=" + el.uuid + " id: " + el.id);
- }
+ Log.d(TAG, "got characteristic with UUID=" + el.uuid + " id: " + el.id);
currChar = new BluetoothGattCharacteristic(el.uuid, el.id, el.properties, 0);
currSrvc.addCharacteristic(currChar);
@@ -2059,9 +2015,7 @@
break;
case GattDbElement.TYPE_DESCRIPTOR:
- if (DBG) {
- Log.d(TAG, "got descriptor with UUID=" + el.uuid + " id: " + el.id);
- }
+ Log.d(TAG, "got descriptor with UUID=" + el.uuid + " id: " + el.id);
currChar.addDescriptor(new BluetoothGattDescriptor(el.uuid, el.id, 0));
if (isRestrictedChar) {
@@ -2070,10 +2024,8 @@
break;
case GattDbElement.TYPE_INCLUDED_SERVICE:
- if (DBG) {
- Log.d(TAG, "got included service with UUID=" + el.uuid + " id: " + el.id
- + " startHandle: " + el.startHandle);
- }
+ Log.d(TAG, "got included service with UUID=" + el.uuid + " id: " + el.id
+ + " startHandle: " + el.startHandle);
currSrvc.addIncludedService(
new BluetoothGattService(el.uuid, el.startHandle, el.type));
@@ -2095,19 +2047,15 @@
void onRegisterForNotifications(int connId, int status, int registered, int handle) {
String address = mClientMap.addressByConnId(connId);
- if (DBG) {
- Log.d(TAG, "onRegisterForNotifications() - address=" + address + ", status=" + status
- + ", registered=" + registered + ", handle=" + handle);
- }
+ Log.d(TAG, "onRegisterForNotifications() - address=" + address + ", status=" + status
+ + ", registered=" + registered + ", handle=" + handle);
}
void onNotify(int connId, String address, int handle, boolean isNotify, byte[] data)
throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onNotify() - address=" + address + ", handle=" + handle + ", length="
- + data.length);
- }
+ Log.v(TAG, "onNotify() - address=" + address + ", handle=" + handle + ", length="
+ + data.length);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app != null) {
@@ -2129,10 +2077,8 @@
throws RemoteException {
String address = mClientMap.addressByConnId(connId);
- if (VDBG) {
- Log.d(TAG, "onReadCharacteristic() - address=" + address + ", status=" + status
- + ", length=" + data.length);
- }
+ Log.v(TAG, "onReadCharacteristic() - address=" + address + ", status=" + status
+ + ", length=" + data.length);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app != null) {
@@ -2149,10 +2095,8 @@
mPermits.put(address, -1);
}
- if (VDBG) {
- Log.d(TAG, "onWriteCharacteristic() - address=" + address + ", status=" + status
- + ", length=" + data.length);
- }
+ Log.v(TAG, "onWriteCharacteristic() - address=" + address + ", status=" + status
+ + ", length=" + data.length);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app == null) {
@@ -2175,9 +2119,7 @@
void onExecuteCompleted(int connId, int status) throws RemoteException {
String address = mClientMap.addressByConnId(connId);
- if (VDBG) {
- Log.d(TAG, "onExecuteCompleted() - address=" + address + ", status=" + status);
- }
+ Log.v(TAG, "onExecuteCompleted() - address=" + address + ", status=" + status);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app != null) {
@@ -2188,11 +2130,9 @@
void onReadDescriptor(int connId, int status, int handle, byte[] data) throws RemoteException {
String address = mClientMap.addressByConnId(connId);
- if (VDBG) {
- Log.d(TAG,
- "onReadDescriptor() - address=" + address + ", status=" + status + ", length="
- + data.length);
- }
+ Log.v(TAG,
+ "onReadDescriptor() - address=" + address + ", status=" + status + ", length="
+ + data.length);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app != null) {
@@ -2204,10 +2144,8 @@
throws RemoteException {
String address = mClientMap.addressByConnId(connId);
- if (VDBG) {
- Log.d(TAG, "onWriteDescriptor() - address=" + address + ", status=" + status
- + ", length=" + data.length);
- }
+ Log.v(TAG, "onWriteDescriptor() - address=" + address + ", status=" + status
+ + ", length=" + data.length);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app != null) {
@@ -2217,11 +2155,9 @@
void onReadRemoteRssi(int clientIf, String address, int rssi, int status)
throws RemoteException {
- if (DBG) {
- Log.d(TAG,
- "onReadRemoteRssi() - clientIf=" + clientIf + " address=" + address + ", rssi="
- + rssi + ", status=" + status);
- }
+ Log.d(TAG,
+ "onReadRemoteRssi() - clientIf=" + clientIf + " address=" + address + ", rssi="
+ + rssi + ", status=" + status);
ClientMap.App app = mClientMap.getById(clientIf);
if (app != null) {
@@ -2232,10 +2168,8 @@
void onConfigureMTU(int connId, int status, int mtu) throws RemoteException {
String address = mClientMap.addressByConnId(connId);
- if (DBG) {
- Log.d(TAG,
- "onConfigureMTU() address=" + address + ", status=" + status + ", mtu=" + mtu);
- }
+ Log.d(TAG,
+ "onConfigureMTU() address=" + address + ", status=" + status + ", mtu=" + mtu);
ClientMap.App app = mClientMap.getByConnId(connId);
if (app != null) {
@@ -2244,9 +2178,7 @@
}
void onClientCongestion(int connId, boolean congested) throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onClientCongestion() - connId=" + connId + ", congested=" + congested);
- }
+ Log.v(TAG, "onClientCongestion() - connId=" + connId + ", congested=" + congested);
ClientMap.App app = mClientMap.getByConnId(connId);
@@ -2317,14 +2249,10 @@
@RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
void disconnectAll(AttributionSource attributionSource) {
- if (DBG) {
- Log.d(TAG, "disconnectAll()");
- }
+ Log.d(TAG, "disconnectAll()");
Map<Integer, String> connMap = mClientMap.getConnectedMap();
for (Map.Entry<Integer, String> entry : connMap.entrySet()) {
- if (DBG) {
- Log.d(TAG, "disconnecting addr:" + entry.getValue());
- }
+ Log.d(TAG, "disconnecting addr:" + entry.getValue());
clientDisconnect(entry.getKey(), entry.getValue(), attributionSource);
//clientDisconnect(int clientIf, String address)
}
@@ -2333,9 +2261,7 @@
@RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)
public void unregAll(AttributionSource attributionSource) {
for (Integer appId : mClientMap.getAllAppsIds()) {
- if (DBG) {
- Log.d(TAG, "unreg:" + appId);
- }
+ Log.d(TAG, "unreg:" + appId);
unregisterClient(appId, attributionSource);
}
}
@@ -2493,9 +2419,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "registerClient() - UUID=" + uuid);
- }
+ Log.d(TAG, "registerClient() - UUID=" + uuid);
mClientMap.add(uuid, null, callback, null, this, mTransitionalScanHelper);
mNativeInterface.gattClientRegisterApp(uuid.getLeastSignificantBits(),
uuid.getMostSignificantBits(), eatt_support);
@@ -2508,9 +2432,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "unregisterClient() - clientIf=" + clientIf);
- }
+ Log.d(TAG, "unregisterClient() - clientIf=" + clientIf);
mClientMap.remove(clientIf);
mNativeInterface.gattClientUnregisterApp(clientIf);
}
@@ -2523,11 +2445,9 @@
return;
}
- if (DBG) {
- Log.d(TAG, "clientConnect() - address=" + address + ", addressType="
- + addressType + ", isDirect=" + isDirect + ", opportunistic="
- + opportunistic + ", phy=" + phy);
- }
+ Log.d(TAG, "clientConnect() - address=" + address + ", addressType="
+ + addressType + ", isDirect=" + isDirect + ", opportunistic="
+ + opportunistic + ", phy=" + phy);
statsLogAppPackage(address, attributionSource.getUid(), clientIf);
logClientForegroundInfo(attributionSource.getUid(), isDirect);
@@ -2547,9 +2467,7 @@
}
Integer connId = mClientMap.connIdByAddress(clientIf, address);
- if (DBG) {
- Log.d(TAG, "clientDisconnect() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "clientDisconnect() - address=" + address + ", connId=" + connId);
statsLogGattConnectionStateChange(
BluetoothProfile.GATT, address, clientIf,
BluetoothProtoEnums.CONNECTION_STATE_DISCONNECTING, -1);
@@ -2566,15 +2484,11 @@
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
- if (DBG) {
- Log.d(TAG, "clientSetPreferredPhy() - no connection to " + address);
- }
+ Log.d(TAG, "clientSetPreferredPhy() - no connection to " + address);
return;
}
- if (DBG) {
- Log.d(TAG, "clientSetPreferredPhy() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "clientSetPreferredPhy() - address=" + address + ", connId=" + connId);
mNativeInterface.gattClientSetPreferredPhy(clientIf, address, txPhy, rxPhy, phyOptions);
}
@@ -2587,15 +2501,11 @@
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
- if (DBG) {
- Log.d(TAG, "clientReadPhy() - no connection to " + address);
- }
+ Log.d(TAG, "clientReadPhy() - no connection to " + address);
return;
}
- if (DBG) {
- Log.d(TAG, "clientReadPhy() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "clientReadPhy() - address=" + address + ", connId=" + connId);
mNativeInterface.gattClientReadPhy(clientIf, address);
}
@@ -2633,9 +2543,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "refreshDevice() - address=" + address);
- }
+ Log.d(TAG, "refreshDevice() - address=" + address);
mNativeInterface.gattClientRefresh(clientIf, address);
}
@@ -2647,9 +2555,7 @@
}
Integer connId = mClientMap.connIdByAddress(clientIf, address);
- if (DBG) {
- Log.d(TAG, "discoverServices() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "discoverServices() - address=" + address + ", connId=" + connId);
if (connId != null) {
mNativeInterface.gattClientSearchService(connId, true, 0, 0);
@@ -2683,9 +2589,7 @@
return;
}
- if (VDBG) {
- Log.d(TAG, "readCharacteristic() - address=" + address);
- }
+ Log.v(TAG, "readCharacteristic() - address=" + address);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
@@ -2716,9 +2620,7 @@
return;
}
- if (VDBG) {
- Log.d(TAG, "readUsingCharacteristicUuid() - address=" + address);
- }
+ Log.v(TAG, "readUsingCharacteristicUuid() - address=" + address);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
@@ -2751,9 +2653,7 @@
return BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION;
}
- if (VDBG) {
- Log.d(TAG, "writeCharacteristic() - address=" + address);
- }
+ Log.v(TAG, "writeCharacteristic() - address=" + address);
if (mReliableQueue.contains(address)) {
writeType = 3; // Prepared write
@@ -2795,9 +2695,7 @@
return;
}
- if (VDBG) {
- Log.d(TAG, "readDescriptor() - address=" + address);
- }
+ Log.v(TAG, "readDescriptor() - address=" + address);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
@@ -2827,9 +2725,7 @@
this, attributionSource, "GattService writeDescriptor")) {
return BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION;
}
- if (VDBG) {
- Log.d(TAG, "writeDescriptor() - address=" + address);
- }
+ Log.v(TAG, "writeDescriptor() - address=" + address);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
@@ -2849,9 +2745,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "beginReliableWrite() - address=" + address);
- }
+ Log.d(TAG, "beginReliableWrite() - address=" + address);
mReliableQueue.add(address);
}
@@ -2863,9 +2757,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "endReliableWrite() - address=" + address + " execute: " + execute);
- }
+ Log.d(TAG, "endReliableWrite() - address=" + address + " execute: " + execute);
mReliableQueue.remove(address);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
@@ -2882,9 +2774,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "registerForNotification() - address=" + address + " enable: " + enable);
- }
+ Log.d(TAG, "registerForNotification() - address=" + address + " enable: " + enable);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId == null) {
@@ -2914,9 +2804,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "readRemoteRssi() - address=" + address);
- }
+ Log.d(TAG, "readRemoteRssi() - address=" + address);
mNativeInterface.gattClientReadRemoteRssi(clientIf, address);
}
@@ -2927,9 +2815,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "configureMTU() - address=" + address + " mtu=" + mtu);
- }
+ Log.d(TAG, "configureMTU() - address=" + address + " mtu=" + mtu);
Integer connId = mClientMap.connIdByAddress(clientIf, address);
if (connId != null) {
mNativeInterface.gattClientConfigureMTU(connId, mtu);
@@ -3035,14 +2921,12 @@
break;
}
- if (DBG) {
- Log.d(TAG, "subrateModeRequest() - "
- + "address=" + BluetoothUtils.toAnonymizedAddress(address)
- + ", subrate min/max=" + subrateMin + "/" + subrateMax
- + ", maxLatency=" + maxLatency
- + ", continuation Number=" + contNumber
- + ", timeout=" + supervisionTimeout);
- }
+ Log.d(TAG, "subrateModeRequest() - "
+ + "address=" + BluetoothUtils.toAnonymizedAddress(address)
+ + ", subrate min/max=" + subrateMin + "/" + subrateMax
+ + ", maxLatency=" + maxLatency
+ + ", continuation Number=" + contNumber
+ + ", timeout=" + supervisionTimeout);
mNativeInterface.gattSubrateRequest(clientIf, address, subrateMin, subrateMax, maxLatency,
contNumber, supervisionTimeout);
@@ -3057,14 +2941,12 @@
return;
}
- if (DBG) {
- Log.d(TAG, "leSubrateRequest() - "
- + "address=" + BluetoothUtils.toAnonymizedAddress(address)
- + ", subrate min/max=" + subrateMin + "/" + subrateMax
- + ", maxLatency=" + maxLatency
- + ", continuation Number=" + contNumber
- + ", timeout=" + supervisionTimeout);
- }
+ Log.d(TAG, "leSubrateRequest() - "
+ + "address=" + BluetoothUtils.toAnonymizedAddress(address)
+ + ", subrate min/max=" + subrateMin + "/" + subrateMax
+ + ", maxLatency=" + maxLatency
+ + ", continuation Number=" + contNumber
+ + ", timeout=" + supervisionTimeout);
mNativeInterface.gattSubrateRequest(clientIf, address, subrateMin, subrateMax, maxLatency,
contNumber, supervisionTimeout);
@@ -3078,9 +2960,7 @@
throws RemoteException {
UUID uuid = new UUID(uuidMsb, uuidLsb);
- if (DBG) {
- Log.d(TAG, "onServerRegistered() - UUID=" + uuid + ", serverIf=" + serverIf);
- }
+ Log.d(TAG, "onServerRegistered() - UUID=" + uuid + ", serverIf=" + serverIf);
ServerMap.App app = mServerMap.getByUuid(uuid);
if (app != null) {
app.id = serverIf;
@@ -3091,9 +2971,7 @@
void onServiceAdded(int status, int serverIf, List<GattDbElement> service)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServiceAdded(), status=" + status);
- }
+ Log.d(TAG, "onServiceAdded(), status=" + status);
if (status != 0) {
return;
@@ -3137,9 +3015,7 @@
}
void onServiceStopped(int status, int serverIf, int srvcHandle) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServiceStopped() srvcHandle=" + srvcHandle + ", status=" + status);
- }
+ Log.d(TAG, "onServiceStopped() srvcHandle=" + srvcHandle + ", status=" + status);
if (status == 0) {
mHandleMap.setStarted(serverIf, srvcHandle, false);
}
@@ -3147,20 +3023,16 @@
}
void onServiceDeleted(int status, int serverIf, int srvcHandle) {
- if (DBG) {
- Log.d(TAG, "onServiceDeleted() srvcHandle=" + srvcHandle + ", status=" + status);
- }
+ Log.d(TAG, "onServiceDeleted() srvcHandle=" + srvcHandle + ", status=" + status);
mHandleMap.deleteService(serverIf, srvcHandle);
}
void onClientConnected(String address, boolean connected, int connId, int serverIf)
throws RemoteException {
- if (DBG) {
- Log.d(TAG,
- "onClientConnected() connId=" + connId + ", address=" + address + ", connected="
- + connected);
- }
+ Log.d(TAG,
+ "onClientConnected() connId=" + connId + ", address=" + address + ", connected="
+ + connected);
ServerMap.App app = mServerMap.getById(serverIf);
if (app == null) {
@@ -3192,10 +3064,8 @@
void onServerReadCharacteristic(String address, int connId, int transId, int handle, int offset,
boolean isLong) throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onServerReadCharacteristic() connId=" + connId + ", address=" + address
- + ", handle=" + handle + ", requestId=" + transId + ", offset=" + offset);
- }
+ Log.v(TAG, "onServerReadCharacteristic() connId=" + connId + ", address=" + address
+ + ", handle=" + handle + ", requestId=" + transId + ", offset=" + offset);
HandleMap.Entry entry = mHandleMap.getByHandle(handle);
if (entry == null) {
@@ -3214,10 +3084,8 @@
void onServerReadDescriptor(String address, int connId, int transId, int handle, int offset,
boolean isLong) throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onServerReadDescriptor() connId=" + connId + ", address=" + address
- + ", handle=" + handle + ", requestId=" + transId + ", offset=" + offset);
- }
+ Log.v(TAG, "onServerReadDescriptor() connId=" + connId + ", address=" + address
+ + ", handle=" + handle + ", requestId=" + transId + ", offset=" + offset);
HandleMap.Entry entry = mHandleMap.getByHandle(handle);
if (entry == null) {
@@ -3237,11 +3105,9 @@
void onServerWriteCharacteristic(String address, int connId, int transId, int handle,
int offset, int length, boolean needRsp, boolean isPrep, byte[] data)
throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onServerWriteCharacteristic() connId=" + connId + ", address=" + address
- + ", handle=" + handle + ", requestId=" + transId + ", isPrep=" + isPrep
- + ", offset=" + offset);
- }
+ Log.v(TAG, "onServerWriteCharacteristic() connId=" + connId + ", address=" + address
+ + ", handle=" + handle + ", requestId=" + transId + ", isPrep=" + isPrep
+ + ", offset=" + offset);
HandleMap.Entry entry = mHandleMap.getByHandle(handle);
if (entry == null) {
@@ -3261,11 +3127,9 @@
void onServerWriteDescriptor(String address, int connId, int transId, int handle, int offset,
int length, boolean needRsp, boolean isPrep, byte[] data) throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onAttributeWrite() connId=" + connId + ", address=" + address + ", handle="
- + handle + ", requestId=" + transId + ", isPrep=" + isPrep + ", offset="
- + offset);
- }
+ Log.v(TAG, "onAttributeWrite() connId=" + connId + ", address=" + address + ", handle="
+ + handle + ", requestId=" + transId + ", isPrep=" + isPrep + ", offset="
+ + offset);
HandleMap.Entry entry = mHandleMap.getByHandle(handle);
if (entry == null) {
@@ -3285,10 +3149,8 @@
void onExecuteWrite(String address, int connId, int transId, int execWrite)
throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onExecuteWrite() connId=" + connId + ", address=" + address + ", transId="
- + transId);
- }
+ Log.d(TAG, "onExecuteWrite() connId=" + connId + ", address=" + address + ", transId="
+ + transId);
ServerMap.App app = mServerMap.getByConnId(connId);
if (app == null) {
@@ -3299,15 +3161,11 @@
}
void onResponseSendCompleted(int status, int attrHandle) {
- if (DBG) {
- Log.d(TAG, "onResponseSendCompleted() handle=" + attrHandle);
- }
+ Log.d(TAG, "onResponseSendCompleted() handle=" + attrHandle);
}
void onNotificationSent(int connId, int status) throws RemoteException {
- if (VDBG) {
- Log.d(TAG, "onNotificationSent() connId=" + connId + ", status=" + status);
- }
+ Log.v(TAG, "onNotificationSent() connId=" + connId + ", status=" + status);
String address = mServerMap.addressByConnId(connId);
if (address == null) {
@@ -3330,9 +3188,7 @@
}
void onServerCongestion(int connId, boolean congested) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onServerCongestion() - connId=" + connId + ", congested=" + congested);
- }
+ Log.d(TAG, "onServerCongestion() - connId=" + connId + ", congested=" + congested);
ServerMap.App app = mServerMap.getByConnId(connId);
if (app == null) {
@@ -3350,9 +3206,7 @@
}
void onMtuChanged(int connId, int mtu) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "onMtuChanged() - connId=" + connId + ", mtu=" + mtu);
- }
+ Log.d(TAG, "onMtuChanged() - connId=" + connId + ", mtu=" + mtu);
String address = mServerMap.addressByConnId(connId);
if (address == null) {
@@ -3379,9 +3233,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "registerServer() - UUID=" + uuid);
- }
+ Log.d(TAG, "registerServer() - UUID=" + uuid);
mServerMap.add(uuid, null, callback, null, this, mTransitionalScanHelper);
mNativeInterface.gattServerRegisterApp(uuid.getLeastSignificantBits(),
uuid.getMostSignificantBits(), eatt_support);
@@ -3394,9 +3246,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "unregisterServer() - serverIf=" + serverIf);
- }
+ Log.d(TAG, "unregisterServer() - serverIf=" + serverIf);
deleteServices(serverIf);
@@ -3412,9 +3262,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "serverConnect() - address=" + address);
- }
+ Log.d(TAG, "serverConnect() - address=" + address);
logServerForegroundInfo(attributionSource.getUid(), isDirect);
@@ -3429,9 +3277,7 @@
}
Integer connId = mServerMap.connIdByAddress(serverIf, address);
- if (DBG) {
- Log.d(TAG, "serverDisconnect() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "serverDisconnect() - address=" + address + ", connId=" + connId);
mNativeInterface.gattServerDisconnect(serverIf, address, connId != null ? connId : 0);
}
@@ -3446,15 +3292,11 @@
Integer connId = mServerMap.connIdByAddress(serverIf, address);
if (connId == null) {
- if (DBG) {
- Log.d(TAG, "serverSetPreferredPhy() - no connection to " + address);
- }
+ Log.d(TAG, "serverSetPreferredPhy() - no connection to " + address);
return;
}
- if (DBG) {
- Log.d(TAG, "serverSetPreferredPhy() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "serverSetPreferredPhy() - address=" + address + ", connId=" + connId);
mNativeInterface.gattServerSetPreferredPhy(serverIf, address, txPhy, rxPhy, phyOptions);
}
@@ -3467,15 +3309,11 @@
Integer connId = mServerMap.connIdByAddress(serverIf, address);
if (connId == null) {
- if (DBG) {
- Log.d(TAG, "serverReadPhy() - no connection to " + address);
- }
+ Log.d(TAG, "serverReadPhy() - no connection to " + address);
return;
}
- if (DBG) {
- Log.d(TAG, "serverReadPhy() - address=" + address + ", connId=" + connId);
- }
+ Log.d(TAG, "serverReadPhy() - address=" + address + ", connId=" + connId);
mNativeInterface.gattServerReadPhy(serverIf, address);
}
@@ -3487,9 +3325,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "addService() - uuid=" + service.getUuid());
- }
+ Log.d(TAG, "addService() - uuid=" + service.getUuid());
List<GattDbElement> db = new ArrayList<GattDbElement>();
@@ -3533,9 +3369,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "removeService() - handle=" + handle);
- }
+ Log.d(TAG, "removeService() - handle=" + handle);
mNativeInterface.gattServerDeleteService(serverIf, handle);
}
@@ -3547,9 +3381,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "clearServices()");
- }
+ Log.d(TAG, "clearServices()");
deleteServices(serverIf);
}
@@ -3561,9 +3393,7 @@
return;
}
- if (VDBG) {
- Log.d(TAG, "sendResponse() - address=" + address);
- }
+ Log.v(TAG, "sendResponse() - address=" + address);
int handle = 0;
HandleMap.Entry entry = mHandleMap.getByRequestId(requestId);
@@ -3585,9 +3415,7 @@
return BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION;
}
- if (VDBG) {
- Log.d(TAG, "sendNotification() - address=" + address + " handle=" + handle);
- }
+ Log.v(TAG, "sendNotification() - address=" + address + " handle=" + handle);
Integer connId = mServerMap.connIdByAddress(serverIf, address);
if (connId == null || connId == 0) {
@@ -3646,9 +3474,7 @@
private int getDeviceType(BluetoothDevice device) {
int type = mNativeInterface.gattClientGetDeviceType(device.getAddress());
- if (DBG) {
- Log.d(TAG, "getDeviceType() - device=" + device + ", type=" + type);
- }
+ Log.d(TAG, "getDeviceType() - device=" + device + ", type=" + type);
return type;
}
@@ -3709,9 +3535,7 @@
}
private void stopNextService(int serverIf, int status) throws RemoteException {
- if (DBG) {
- Log.d(TAG, "stopNextService() - serverIf=" + serverIf + ", status=" + status);
- }
+ Log.d(TAG, "stopNextService() - serverIf=" + serverIf + ", status=" + status);
if (status == 0) {
List<HandleMap.Entry> entries = mHandleMap.getEntries();
@@ -3728,9 +3552,7 @@
}
private void deleteServices(int serverIf) {
- if (DBG) {
- Log.d(TAG, "deleteServices() - serverIf=" + serverIf);
- }
+ Log.d(TAG, "deleteServices() - serverIf=" + serverIf);
/*
* Figure out which handles to delete.
@@ -3800,10 +3622,8 @@
BluetoothStatsLog.write(
BluetoothStatsLog.BLUETOOTH_GATT_APP_INFO,
sessionIndex, mAdapterService.getMetricId(device), applicationUid);
- if (DBG) {
- Log.d(TAG, "Gatt Logging: metric_id=" + mAdapterService.getMetricId(device)
- + ", app_uid=" + applicationUid);
- }
+ Log.d(TAG, "Gatt Logging: metric_id=" + mAdapterService.getMetricId(device)
+ + ", app_uid=" + applicationUid);
}
private void statsLogGattConnectionStateChange(
@@ -3814,12 +3634,10 @@
BluetoothStatsLog.BLUETOOTH_CONNECTION_STATE_CHANGED, connectionState,
0 /* deprecated */, profile, new byte[0],
mAdapterService.getMetricId(device), sessionIndex, connectionStatus);
- if (DBG) {
- Log.d(TAG, "Gatt Logging: metric_id=" + mAdapterService.getMetricId(device)
- + ", session_index=" + sessionIndex
- + ", connection state=" + connectionState
- + ", connection status=" + connectionStatus);
- }
+ Log.d(TAG, "Gatt Logging: metric_id=" + mAdapterService.getMetricId(device)
+ + ", session_index=" + sessionIndex
+ + ", connection state=" + connectionState
+ + ", connection status=" + connectionStatus);
}
@Override
diff --git a/android/app/src/com/android/bluetooth/gatt/GattServiceConfig.java b/android/app/src/com/android/bluetooth/gatt/GattServiceConfig.java
index 3855d97..ff60557 100644
--- a/android/app/src/com/android/bluetooth/gatt/GattServiceConfig.java
+++ b/android/app/src/com/android/bluetooth/gatt/GattServiceConfig.java
@@ -16,14 +16,10 @@
package com.android.bluetooth.gatt;
-import android.os.Build;
-
/**
* GattService configuration.
*/
public class GattServiceConfig {
- public static final boolean DBG = Build.TYPE.equals("userdebug") || Build.TYPE.equals("eng");
- public static final boolean VDBG = false;
public static final String TAG_PREFIX = "BtGatt.";
public static final boolean DEBUG_ADMIN = false;
}
diff --git a/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java b/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java
index 263a807..40b6ac3 100644
--- a/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java
@@ -32,7 +32,6 @@
/** Hearing Access Profile Client Native Interface to/from JNI. */
public class HapClientNativeInterface {
private static final String TAG = HapClientNativeInterface.class.getSimpleName();
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
private final BluetoothAdapter mAdapter;
@@ -243,9 +242,7 @@
event.device = getDevice(address);
event.valueInt1 = state;
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -256,9 +253,7 @@
event.device = getDevice(address);
event.valueInt1 = features;
- if (DBG) {
- Log.d(TAG, "onDeviceAvailable: " + event);
- }
+ Log.d(TAG, "onDeviceAvailable: " + event);
sendMessageToService(event);
}
@@ -269,9 +264,7 @@
event.device = getDevice(address);
event.valueInt1 = features;
- if (DBG) {
- Log.d(TAG, "onFeaturesUpdate: " + event);
- }
+ Log.d(TAG, "onFeaturesUpdate: " + event);
sendMessageToService(event);
}
@@ -282,9 +275,7 @@
event.device = getDevice(address);
event.valueInt1 = presetIndex;
- if (DBG) {
- Log.d(TAG, "onActivePresetSelected: " + event);
- }
+ Log.d(TAG, "onActivePresetSelected: " + event);
sendMessageToService(event);
}
@@ -295,9 +286,7 @@
event.valueInt1 = presetIndex;
event.valueInt2 = groupId;
- if (DBG) {
- Log.d(TAG, "onActivePresetGroupSelected: " + event);
- }
+ Log.d(TAG, "onActivePresetGroupSelected: " + event);
sendMessageToService(event);
}
@@ -308,9 +297,7 @@
event.device = getDevice(address);
event.valueInt1 = resultCode;
- if (DBG) {
- Log.d(TAG, "onActivePresetSelectError: " + event);
- }
+ Log.d(TAG, "onActivePresetSelectError: " + event);
sendMessageToService(event);
}
@@ -321,9 +308,7 @@
event.valueInt1 = resultCode;
event.valueInt2 = groupId;
- if (DBG) {
- Log.d(TAG, "onActivePresetGroupSelectError: " + event);
- }
+ Log.d(TAG, "onActivePresetGroupSelectError: " + event);
sendMessageToService(event);
}
@@ -335,9 +320,7 @@
event.valueInt2 = infoReason;
event.valueList = new ArrayList<>(Arrays.asList(presets));
- if (DBG) {
- Log.d(TAG, "onPresetInfo: " + event);
- }
+ Log.d(TAG, "onPresetInfo: " + event);
sendMessageToService(event);
}
@@ -349,9 +332,7 @@
event.valueInt3 = groupId;
event.valueList = new ArrayList<>(Arrays.asList(presets));
- if (DBG) {
- Log.d(TAG, "onGroupPresetInfo: " + event);
- }
+ Log.d(TAG, "onGroupPresetInfo: " + event);
sendMessageToService(event);
}
@@ -363,9 +344,7 @@
event.valueInt1 = resultCode;
event.valueInt2 = presetIndex;
- if (DBG) {
- Log.d(TAG, "onPresetNameSetError: " + event);
- }
+ Log.d(TAG, "onPresetNameSetError: " + event);
sendMessageToService(event);
}
@@ -377,9 +356,7 @@
event.valueInt2 = presetIndex;
event.valueInt3 = groupId;
- if (DBG) {
- Log.d(TAG, "onGroupPresetNameSetError: " + event);
- }
+ Log.d(TAG, "onGroupPresetNameSetError: " + event);
sendMessageToService(event);
}
@@ -391,9 +368,7 @@
event.valueInt1 = resultCode;
event.valueInt2 = presetIndex;
- if (DBG) {
- Log.d(TAG, "onPresetInfoError: " + event);
- }
+ Log.d(TAG, "onPresetInfoError: " + event);
sendMessageToService(event);
}
@@ -405,9 +380,7 @@
event.valueInt2 = presetIndex;
event.valueInt3 = groupId;
- if (DBG) {
- Log.d(TAG, "onGroupPresetInfoError: " + event);
- }
+ Log.d(TAG, "onGroupPresetInfoError: " + event);
sendMessageToService(event);
}
diff --git a/android/app/src/com/android/bluetooth/hap/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java
index 662fe07..1fcb47a 100644
--- a/android/app/src/com/android/bluetooth/hap/HapClientService.java
+++ b/android/app/src/com/android/bluetooth/hap/HapClientService.java
@@ -66,7 +66,6 @@
* Provides Bluetooth Hearing Access profile, as a service.
*/
public class HapClientService extends ProfileService {
- private static final boolean DBG = true;
private static final String TAG = "HapClientService";
// Upper limit of all HearingAccess devices: Bonded or Connected
@@ -99,9 +98,7 @@
@VisibleForTesting
static synchronized void setHapClient(HapClientService instance) {
- if (DBG) {
- Log.d(TAG, "setHapClient(): set to: " + instance);
- }
+ Log.d(TAG, "setHapClient(): set to: " + instance);
sHapClient = instance;
}
@@ -129,9 +126,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
}
@Override
@@ -141,9 +136,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sHapClient != null) {
throw new IllegalStateException("start() called twice");
@@ -176,9 +169,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sHapClient == null) {
Log.w(TAG, "stop() called before start()");
return;
@@ -233,9 +224,7 @@
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
// Remove state machine if the bonding for a device is removed
if (bondState != BluetoothDevice.BOND_NONE) {
@@ -356,9 +345,7 @@
*/
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceBluetoothPrivilegedPermission(this);
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.HAP_CLIENT,
connectionPolicy);
if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
@@ -428,9 +415,7 @@
if (toState == BluetoothProfile.STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
+ Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
}
}
@@ -451,9 +436,7 @@
*/
public boolean connect(BluetoothDevice device) {
enforceBluetoothPrivilegedPermission(this);
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (device == null) {
return false;
}
@@ -487,9 +470,7 @@
*/
public boolean disconnect(BluetoothDevice device) {
enforceBluetoothPrivilegedPermission(this);
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
if (device == null) {
return false;
}
@@ -519,9 +500,7 @@
+ MAX_HEARING_ACCESS_STATE_MACHINES);
return null;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm = HapClientStateMachine.make(device, this,
mHapClientNativeInterface, mStateMachinesThread.getLooper());
mStateMachines.put(device, sm);
diff --git a/android/app/src/com/android/bluetooth/hap/HapClientStateMachine.java b/android/app/src/com/android/bluetooth/hap/HapClientStateMachine.java
index 1dfd45d..e77e086 100644
--- a/android/app/src/com/android/bluetooth/hap/HapClientStateMachine.java
+++ b/android/app/src/com/android/bluetooth/hap/HapClientStateMachine.java
@@ -71,7 +71,6 @@
static final int DISCONNECT = 2;
@VisibleForTesting
static final int STACK_EVENT = 101;
- private static final boolean DBG = true;
private static final String TAG = "HapClientStateMachine";
@VisibleForTesting
static final int CONNECT_TIMEOUT = 201;
@@ -209,9 +208,7 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
@VisibleForTesting
@@ -264,9 +261,7 @@
break;
case STACK_EVENT:
HapClientStackEvent event = (HapClientStackEvent) message.obj;
- if (DBG) {
- Log.d(TAG, "Disconnected: stack event: " + event);
- }
+ Log.d(TAG, "Disconnected: stack event: " + event);
if (!mDevice.equals(event.device)) {
Log.wtf(TAG, "Device(" + mDevice + "): event mismatch: " + event);
}
diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java
index 0ee8dfa..5b32da5 100644
--- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java
@@ -34,7 +34,6 @@
*/
public class HearingAidNativeInterface {
private static final String TAG = "HearingAidNativeInterface";
- private static final boolean DBG = true;
private BluetoothAdapter mAdapter;
@GuardedBy("INSTANCE_LOCK")
@@ -162,9 +161,7 @@
event.device = getDevice(address);
event.valueInt1 = state;
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -176,9 +173,7 @@
event.valueInt1 = capabilities;
event.valueLong2 = hiSyncId;
- if (DBG) {
- Log.d(TAG, "onDeviceAvailable: " + event);
- }
+ Log.d(TAG, "onDeviceAvailable: " + event);
sendMessageToService(event);
}
diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
index 8f7947e..145b1d5 100644
--- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
+++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
@@ -65,7 +65,6 @@
* Provides Bluetooth HearingAid profile, as a service in the Bluetooth application.
*/
public class HearingAidService extends ProfileService {
- private static final boolean DBG = true;
private static final String TAG = "HearingAidService";
// Timeout for state machine thread join, to prevent potential ANR.
@@ -114,9 +113,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sHearingAidService != null) {
throw new IllegalStateException("start() called twice");
}
@@ -150,9 +147,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sHearingAidService == null) {
Log.w(TAG, "stop() called before start()");
return;
@@ -204,9 +199,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
}
/**
@@ -228,9 +221,7 @@
@VisibleForTesting
static synchronized void setHearingAidService(HearingAidService instance) {
- if (DBG) {
- Log.d(TAG, "setHearingAidService(): set to: " + instance);
- }
+ Log.d(TAG, "setHearingAidService(): set to: " + instance);
sHearingAidService = instance;
}
@@ -244,9 +235,7 @@
public boolean connect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (device == null) {
return false;
}
@@ -312,9 +301,7 @@
public boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
if (device == null) {
return false;
}
@@ -497,9 +484,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.HEARING_AID,
connectionPolicy)) {
@@ -584,9 +569,7 @@
* @return true on success, otherwise false
*/
public boolean removeActiveDevice(boolean stopAudio) {
- if (DBG) {
- Log.d(TAG, "removeActiveDevice: stopAudio=" + stopAudio);
- }
+ Log.d(TAG, "removeActiveDevice: stopAudio=" + stopAudio);
synchronized (mStateMachines) {
if (mActiveDeviceHiSyncId != BluetoothHearingAid.HI_SYNC_ID_INVALID) {
reportActiveDevice(null, stopAudio);
@@ -607,15 +590,11 @@
Log.e(TAG, "setActiveDevice: device should not be null!");
return removeActiveDevice(true);
}
- if (DBG) {
- Log.d(TAG, "setActiveDevice: " + device);
- }
+ Log.d(TAG, "setActiveDevice: " + device);
synchronized (mStateMachines) {
/* No action needed since this is the same device as previousely activated */
if (device.equals(mActiveDevice)) {
- if (DBG) {
- Log.d(TAG, "setActiveDevice: The device is already active. Ignoring.");
- }
+ Log.d(TAG, "setActiveDevice: The device is already active. Ignoring.");
return true;
}
@@ -673,10 +652,8 @@
BluetoothDevice device = stackEvent.device;
int capabilities = stackEvent.valueInt1;
long hiSyncId = stackEvent.valueLong2;
- if (DBG) {
- Log.d(TAG, "Device available: device=" + device + " capabilities="
- + capabilities + " hiSyncId=" + hiSyncId);
- }
+ Log.d(TAG, "Device available: device=" + device + " capabilities="
+ + capabilities + " hiSyncId=" + hiSyncId);
mDeviceCapabilitiesMap.put(device, capabilities);
mDeviceHiSyncIdMap.put(device, hiSyncId);
return;
@@ -720,9 +697,7 @@
public void onAudioDevicesRemoved(AudioDeviceInfo[] removedDevices) {
for (AudioDeviceInfo deviceInfo : removedDevices) {
if (deviceInfo.getType() == AudioDeviceInfo.TYPE_HEARING_AID) {
- if (DBG) {
- Log.d(TAG, " onAudioDevicesRemoved: device type: " + deviceInfo.getType());
- }
+ Log.d(TAG, " onAudioDevicesRemoved: device type: " + deviceInfo.getType());
if (mAudioManager != null) {
notifyActiveDeviceChanged();
mAudioManager.unregisterAudioDeviceCallback(this);
@@ -740,9 +715,7 @@
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
for (AudioDeviceInfo deviceInfo : addedDevices) {
if (deviceInfo.getType() == AudioDeviceInfo.TYPE_HEARING_AID) {
- if (DBG) {
- Log.d(TAG, " onAudioDevicesAdded: device type: " + deviceInfo.getType());
- }
+ Log.d(TAG, " onAudioDevicesAdded: device type: " + deviceInfo.getType());
if (mAudioManager != null) {
notifyActiveDeviceChanged();
mAudioManager.unregisterAudioDeviceCallback(this);
@@ -770,9 +743,7 @@
+ MAX_HEARING_AID_STATE_MACHINES);
return null;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm = HearingAidStateMachine.make(device, this,
mHearingAidNativeInterface, mStateMachinesThread.getLooper());
mStateMachines.put(device, sm);
@@ -787,9 +758,7 @@
* @param stopAudio whether to stop audio when device is null.
*/
private void reportActiveDevice(BluetoothDevice device, boolean stopAudio) {
- if (DBG) {
- Log.d(TAG, "reportActiveDevice: device=" + device + " stopAudio=" + stopAudio);
- }
+ Log.d(TAG, "reportActiveDevice: device=" + device + " stopAudio=" + stopAudio);
if (device != null && stopAudio) {
Log.e(TAG, "Illegal arguments: stopAudio should be false when device is not null!");
@@ -812,10 +781,8 @@
BluetoothProfile.HEARING_AID, mAdapterService.obfuscateAddress(device),
mAdapterService.getMetricId(device));
- if (DBG) {
- Log.d(TAG, "Hearing Aid audio: " + previousAudioDevice + " -> " + device
- + ". Stop audio: " + stopAudio);
- }
+ Log.d(TAG, "Hearing Aid audio: " + previousAudioDevice + " -> " + device
+ + ". Stop audio: " + stopAudio);
if (device != null) {
mAudioManager.registerAudioDeviceCallback(mAudioManagerOnAudioDevicesAddedCallback,
@@ -844,9 +811,7 @@
*/
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
// Remove state machine if the bonding for a device is removed
if (bondState != BluetoothDevice.BOND_NONE) {
return;
@@ -921,9 +886,7 @@
if (toState == BluetoothProfile.STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
+ Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
}
}
diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidStateMachine.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidStateMachine.java
index 5682a19..c2a1b00 100644
--- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidStateMachine.java
+++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidStateMachine.java
@@ -67,7 +67,6 @@
import java.util.Scanner;
final class HearingAidStateMachine extends StateMachine {
- private static final boolean DBG = false;
private static final String TAG = "HearingAidStateMachine";
static final int CONNECT = 1;
@@ -179,9 +178,7 @@
break;
case STACK_EVENT:
HearingAidStackEvent event = (HearingAidStackEvent) message.obj;
- if (DBG) {
- Log.d(TAG, "Disconnected: stack event: " + event);
- }
+ Log.d(TAG, "Disconnected: stack event: " + event);
if (!mDevice.equals(event.device)) {
Log.wtf(TAG, "Device(" + mDevice + "): event mismatch: " + event);
}
@@ -584,8 +581,6 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
index 0647bb7..64e7645 100644
--- a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
+++ b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
@@ -47,7 +47,6 @@
*/
public class AtPhonebook {
private static final String TAG = "BluetoothAtPhonebook";
- private static final boolean DBG = false;
/** The projection to use when querying the call log database in response
* to AT+CPBR for the MC, RC, and DC phone books (missed, received, and
@@ -257,9 +256,7 @@
pb = pb.substring(1, pb.length());
}
if (getPhonebookResult(pb, false) == null && !"SM".equals(pb)) {
- if (DBG) {
- Log.d(TAG, "Dont know phonebook: '" + pb + "'");
- }
+ Log.d(TAG, "Dont know phonebook: '" + pb + "'");
atCommandErrorCode = BluetoothCmeError.OPERATION_NOT_ALLOWED;
break;
}
@@ -565,9 +562,7 @@
c.close();
}
if (name == null) {
- if (DBG) {
- Log.d(TAG, "Caller ID lookup failed for " + number);
- }
+ Log.d(TAG, "Caller ID lookup failed for " + number);
}
} else if (pbr.nameColumn != -1) {
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
index 0eef5ea..f1653b3 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
@@ -39,6 +39,7 @@
import android.content.IntentFilter;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
+import android.media.BluetoothProfileConnectionInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Handler;
@@ -107,7 +108,6 @@
*/
public class HeadsetService extends ProfileService {
private static final String TAG = "HeadsetService";
- private static final boolean DBG = false;
/**
* HFP AG owned/managed components
@@ -1198,7 +1198,7 @@
} else {
stateMachine.sendMessage(HeadsetStateMachine.VOICE_RECOGNITION_START, device);
}
- if (Flags.isScoManagedByAudio()) {
+ if (Utils.isScoManagedByAudioEnabled()) {
// when isScoManagedByAudio is on, tell AudioManager to connect SCO
AudioManager am = mSystemInterface.getAudioManager();
BluetoothDevice finalDevice = device;
@@ -1470,6 +1470,15 @@
}
return false;
}
+ if (Utils.isScoManagedByAudioEnabled()) {
+ // tell Audio Framework that active device changed
+ mSystemInterface
+ .getAudioManager()
+ .handleBluetoothActiveDeviceChanged(
+ mActiveDevice,
+ previousActiveDevice,
+ BluetoothProfileConnectionInfo.createHfpInfo());
+ }
broadcastActiveDevice(mActiveDevice);
} else if (shouldPersistAudio()) {
/* If HFP is getting active for a phonecall and there is LeAudio device active,
@@ -1481,8 +1490,20 @@
Log.i(TAG, "Make sure there is no le audio device active.");
leAudioService.setInactiveForHfpHandover(mActiveDevice);
}
-
+ if (Utils.isScoManagedByAudioEnabled()) {
+ // tell Audio Framework that active device changed
+ mSystemInterface
+ .getAudioManager()
+ .handleBluetoothActiveDeviceChanged(
+ mActiveDevice,
+ previousActiveDevice,
+ BluetoothProfileConnectionInfo.createHfpInfo());
+ }
broadcastActiveDevice(mActiveDevice);
+ if (Utils.isScoManagedByAudioEnabled()) {
+ // Audio Framework will handle audio transition
+ return true;
+ }
int connectStatus = connectAudio(mActiveDevice);
if (connectStatus != BluetoothStatusCodes.SUCCESS) {
Log.e(TAG, "setActiveDevice: fail to connectAudio to " + mActiveDevice
@@ -1496,6 +1517,15 @@
return false;
}
} else {
+ if (Utils.isScoManagedByAudioEnabled()) {
+ // tell Audio Framework that active device changed
+ mSystemInterface
+ .getAudioManager()
+ .handleBluetoothActiveDeviceChanged(
+ mActiveDevice,
+ previousActiveDevice,
+ BluetoothProfileConnectionInfo.createHfpInfo());
+ }
broadcastActiveDevice(mActiveDevice);
}
}
@@ -2430,9 +2460,7 @@
}
private static void logD(String message) {
- if (DBG) {
- Log.d(TAG, message);
- }
+ Log.d(TAG, message);
}
private Handler getStateMachinesThreadHandler() {
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
index 5c27109..952d105 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
@@ -86,7 +86,6 @@
@VisibleForTesting
public class HeadsetStateMachine extends StateMachine {
private static final String TAG = "HeadsetStateMachine";
- private static final boolean DBG = true;
static final int CONNECT = 1;
static final int DISCONNECT = 2;
@@ -2584,9 +2583,7 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
@Override
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
index b1a8c5f..ac90f4d 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
@@ -62,8 +62,7 @@
* Bluetooth application.
*/
public class HeadsetClientService extends ProfileService {
- private static final boolean DBG = true;
- private static final String TAG = "HeadsetClientService";
+ private static final String TAG = HeadsetClientService.class.getSimpleName();
// This is also used as a lock for shared data in {@link HeadsetClientService}
@GuardedBy("mStateMachineMap")
@@ -101,9 +100,7 @@
@Override
public void start() {
synchronized (mStartStopLock) {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (getHeadsetClientService() != null) {
throw new IllegalStateException("start() called twice");
}
@@ -202,20 +199,16 @@
// ({@link HeadsetClientStateMachine#SET_SPEAKER_VOLUME} in
// {@link HeadsetClientStateMachine} for details.
if (action.equals(AudioManager.ACTION_VOLUME_CHANGED)) {
- if (DBG) {
- Log.d(TAG, "Volume changed for stream: " + intent.getIntExtra(
- AudioManager.EXTRA_VOLUME_STREAM_TYPE, -1));
- }
+ Log.d(TAG, "Volume changed for stream: " + intent.getIntExtra(
+ AudioManager.EXTRA_VOLUME_STREAM_TYPE, -1));
int streamType = intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, -1);
if (streamType == AudioManager.STREAM_VOICE_CALL) {
int streamValue =
intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_VALUE, -1);
int hfVol = HeadsetClientStateMachine.amToHfVol(streamValue);
- if (DBG) {
- Log.d(TAG,
- "Setting volume to audio manager: " + streamValue + " hands free: "
- + hfVol);
- }
+ Log.d(TAG,
+ "Setting volume to audio manager: " + streamValue + " hands free: "
+ + hfVol);
mAudioManager.setHfpVolume(hfVol);
synchronized (mStateMachineMap) {
for (HeadsetClientStateMachine sm : mStateMachineMap.values()) {
@@ -235,10 +228,8 @@
}
mLastBatteryLevel = batteryLevel;
- if (DBG) {
- Log.d(TAG,
- "Send battery level update BIEV(2," + batteryLevel + ") command");
- }
+ Log.d(TAG,
+ "Send battery level update BIEV(2," + batteryLevel + ") command");
synchronized (mStateMachineMap) {
for (HeadsetClientStateMachine sm : mStateMachineMap.values()) {
@@ -724,16 +715,12 @@
/** Set a {@link HeadsetClientService} instance. */
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
public static synchronized void setHeadsetClientService(HeadsetClientService instance) {
- if (DBG) {
- Log.d(TAG, "setHeadsetClientService(): set to: " + instance);
- }
+ Log.d(TAG, "setHeadsetClientService(): set to: " + instance);
sHeadsetClientService = instance;
}
public boolean connect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "connect " + device);
- }
+ Log.d(TAG, "connect " + device);
if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
Log.w(TAG, "Connection not allowed: <" + device.getAddress()
+ "> is CONNECTION_POLICY_FORBIDDEN");
@@ -837,9 +824,7 @@
* @return true if connectionPolicy is set, false on error
*/
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.HEADSET_CLIENT,
connectionPolicy)) {
@@ -1037,11 +1022,9 @@
continue;
}
int connectionState = entry.getValue().getConnectionState(entry.getKey());
- if (DBG) {
- Log.d(TAG,
- "Accepting a call on device " + device + ". Possibly disconnecting on "
- + entry.getValue());
- }
+ Log.d(TAG,
+ "Accepting a call on device " + device + ". Possibly disconnecting on "
+ + entry.getValue());
if (connectionState == BluetoothProfile.STATE_CONNECTED) {
entry.getValue()
.obtainMessage(HeadsetClientStateMachine.TERMINATE_CALL)
@@ -1306,9 +1289,7 @@
}
if (sm != null) {
- if (DBG) {
- Log.d(TAG, "Found SM for device " + device);
- }
+ Log.d(TAG, "Found SM for device " + device);
} else if (isConnectionEvent) {
// The only time a new state machine should be created when none was found is for
// connection events.
@@ -1338,9 +1319,7 @@
synchronized (mStateMachineMap) {
HeadsetClientStateMachine sm = mStateMachineMap.get(device);
if (sm != null) {
- if (DBG) {
- Log.d(TAG, "allocateStateMachine: SM already exists for device " + device);
- }
+ Log.d(TAG, "allocateStateMachine: SM already exists for device " + device);
return sm;
}
@@ -1369,10 +1348,8 @@
if (entry.getValue() != null) {
int audioState = entry.getValue().getAudioState(entry.getKey());
if (audioState == HeadsetClientHalConstants.AUDIO_STATE_CONNECTED) {
- if (DBG) {
- Log.d(TAG, "Device " + entry.getKey() + " audio state " + audioState
- + " Connected");
- }
+ Log.d(TAG, "Device " + entry.getKey() + " audio state " + audioState
+ + " Connected");
return true;
}
}
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java
index e7afde4..487e482 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java
@@ -88,8 +88,7 @@
import java.util.Set;
public class HeadsetClientStateMachine extends StateMachine {
- private static final String TAG = "HeadsetClientStateMachine";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = HeadsetClientStateMachine.class.getSimpleName();
static final int NO_ACTION = 0;
static final int IN_BAND_RING_ENABLED = 1;
@@ -360,7 +359,7 @@
@VisibleForTesting
HfpClientCall getCall(int... states) {
- logD("getFromCallsWithStates states:" + Arrays.toString(states));
+ debug("getFromCallsWithStates states:" + Arrays.toString(states));
for (HfpClientCall c : mCalls.values()) {
for (int s : states) {
if (c.getState() == s) {
@@ -384,12 +383,12 @@
}
private void sendCallChangedIntent(HfpClientCall c) {
- logD("sendCallChangedIntent " + c);
+ debug("sendCallChangedIntent " + c);
Intent intent = new Intent(BluetoothHeadsetClient.ACTION_CALL_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
if (mService.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
- logD("Send legacy call");
+ debug("Send legacy call");
intent.putExtra(
BluetoothHeadsetClient.EXTRA_CALL, HeadsetClientService.toLegacyCall(c));
} else {
@@ -423,14 +422,14 @@
}
private boolean queryCallsStart() {
- logD("queryCallsStart");
+ debug("queryCallsStart");
mNativeInterface.queryCurrentCalls(mCurrentDevice);
addQueuedAction(QUERY_CURRENT_CALLS, 0);
return true;
}
private void queryCallsDone() {
- logD("queryCallsDone");
+ debug("queryCallsDone");
// mCalls has two types of calls:
// (a) Calls that are received from AG of a previous iteration of queryCallsStart()
// (b) Calls that are outgoing initiated from HF
@@ -477,7 +476,7 @@
callRetainedIds.addAll(currCallIdSet);
callRetainedIds.retainAll(newCallIdSet);
- logD("currCallIdSet " + mCalls.keySet() + " newCallIdSet " + newCallIdSet
+ debug("currCallIdSet " + mCalls.keySet() + " newCallIdSet " + newCallIdSet
+ " callAddedIds " + callAddedIds + " callRemovedIds " + callRemovedIds
+ " callRetainedIds " + callRetainedIds);
@@ -487,7 +486,7 @@
HfpClientCall c = mCalls.get(HF_ORIGINATED_CALL_ID);
long cCreationElapsed = c.getCreationElapsedMilli();
if (callAddedIds.size() > 0) {
- logD("Associating the first call with HF originated call");
+ debug("Associating the first call with HF originated call");
hfOriginatedAssoc = (Integer) callAddedIds.toArray()[0];
mCalls.put(hfOriginatedAssoc, mCalls.get(HF_ORIGINATED_CALL_ID));
mCalls.remove(HF_ORIGINATED_CALL_ID);
@@ -496,7 +495,7 @@
callAddedIds.remove(hfOriginatedAssoc);
callRetainedIds.add(hfOriginatedAssoc);
} else if (SystemClock.elapsedRealtime() - cCreationElapsed > OUTGOING_TIMEOUT_MILLI) {
- Log.w(TAG, "Outgoing call did not see a response, clear the calls and send CHUP");
+ warn("Outgoing call did not see a response, clear the calls and send CHUP");
// We send a terminate because we are in a bad state and trying to
// recover.
terminateCall();
@@ -515,7 +514,7 @@
}
}
- logD("ADJUST: currCallIdSet " + mCalls.keySet() + " newCallIdSet " + newCallIdSet
+ debug("ADJUST: currCallIdSet " + mCalls.keySet() + " newCallIdSet " + newCallIdSet
+ " callAddedIds " + callAddedIds + " callRemovedIds " + callRemovedIds
+ " callRetainedIds " + callRetainedIds);
@@ -565,7 +564,7 @@
R.integer.hfp_clcc_poll_interval_during_call));
} else {
if (getCall(HfpClientCall.CALL_STATE_INCOMING) != null) {
- logD("Still have incoming call; polling");
+ debug("Still have incoming call; polling");
sendMessageDelayed(QUERY_CURRENT_CALLS, QUERY_CURRENT_CALLS_WAIT_MILLIS);
} else {
removeMessages(QUERY_CURRENT_CALLS);
@@ -578,7 +577,7 @@
private void queryCallsUpdate(int id, int state, String number, boolean multiParty,
boolean outgoing) {
- logD("queryCallsUpdate: " + id);
+ debug("queryCallsUpdate: " + id);
mCallsUpdate.put(id,
new HfpClientCall(mCurrentDevice, id, state, number, multiParty,
outgoing, mInBandRing));
@@ -587,7 +586,7 @@
private void acceptCall(int flag) {
int action = -1;
- logD("acceptCall: (" + flag + ")");
+ debug("acceptCall: (" + flag + ")");
HfpClientCall c = getCall(HfpClientCall.CALL_STATE_INCOMING,
HfpClientCall.CALL_STATE_WAITING);
@@ -600,7 +599,7 @@
}
}
- logD("Call to accept: " + c);
+ debug("Call to accept: " + c);
switch (c.getState()) {
case HfpClientCall.CALL_STATE_INCOMING:
if (flag != BluetoothHeadsetClient.CALL_ACCEPT_NONE) {
@@ -622,13 +621,13 @@
// existing call or hold the existing call. We hold the other call by default.
if (flag == BluetoothHeadsetClient.CALL_ACCEPT_HOLD
|| flag == BluetoothHeadsetClient.CALL_ACCEPT_NONE) {
- logD("Accepting call with accept and hold");
+ debug("Accepting call with accept and hold");
action = HeadsetClientHalConstants.CALL_ACTION_CHLD_2;
} else if (flag == BluetoothHeadsetClient.CALL_ACCEPT_TERMINATE) {
- logD("Accepting call with accept and reject");
+ debug("Accepting call with accept and reject");
action = HeadsetClientHalConstants.CALL_ACTION_CHLD_1;
} else {
- Log.e(TAG, "Aceept call with invalid flag: " + flag);
+ error("Accept call with invalid flag: " + flag);
return;
}
break;
@@ -663,21 +662,21 @@
if (mNativeInterface.handleCallAction(mCurrentDevice, action, 0)) {
addQueuedAction(ACCEPT_CALL, action);
} else {
- Log.e(TAG, "ERROR: Couldn't accept a call, action:" + action);
+ error("ERROR: Couldn't accept a call, action:" + action);
}
}
private void rejectCall() {
int action;
- logD("rejectCall");
+ debug("rejectCall");
HfpClientCall c = getCall(HfpClientCall.CALL_STATE_INCOMING,
HfpClientCall.CALL_STATE_WAITING,
HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD,
HfpClientCall.CALL_STATE_HELD);
if (c == null) {
- logD("No call to reject, returning.");
+ debug("No call to reject, returning.");
return;
}
@@ -700,17 +699,17 @@
}
if (mNativeInterface.handleCallAction(mCurrentDevice, action, 0)) {
- logD("Reject call action " + action);
+ debug("Reject call action " + action);
addQueuedAction(REJECT_CALL, action);
} else {
- Log.e(TAG, "ERROR: Couldn't reject a call, action:" + action);
+ error("ERROR: Couldn't reject a call, action:" + action);
}
}
private void holdCall() {
int action;
- logD("holdCall");
+ debug("holdCall");
HfpClientCall c = getCall(HfpClientCall.CALL_STATE_INCOMING);
if (c != null) {
@@ -727,12 +726,12 @@
if (mNativeInterface.handleCallAction(mCurrentDevice, action, 0)) {
addQueuedAction(HOLD_CALL, action);
} else {
- Log.e(TAG, "ERROR: Couldn't hold a call, action:" + action);
+ error("ERROR: Couldn't hold a call, action:" + action);
}
}
private void terminateCall() {
- logD("terminateCall");
+ debug("terminateCall");
int action = HeadsetClientHalConstants.CALL_ACTION_CHUP;
@@ -748,14 +747,14 @@
if (mNativeInterface.handleCallAction(mCurrentDevice, action, 0)) {
addQueuedAction(TERMINATE_CALL, action);
} else {
- Log.e(TAG, "ERROR: Couldn't terminate outgoing call");
+ error("ERROR: Couldn't terminate outgoing call");
}
}
}
@VisibleForTesting
void enterPrivateMode(int idx) {
- logD("enterPrivateMode: " + idx);
+ debug("enterPrivateMode: " + idx);
HfpClientCall c = mCalls.get(idx);
@@ -768,13 +767,13 @@
HeadsetClientHalConstants.CALL_ACTION_CHLD_2X, idx)) {
addQueuedAction(ENTER_PRIVATE_MODE, c);
} else {
- Log.e(TAG, "ERROR: Couldn't enter private " + " id:" + idx);
+ error("ERROR: Couldn't enter private " + " id:" + idx);
}
}
@VisibleForTesting
void explicitCallTransfer() {
- logD("explicitCallTransfer");
+ debug("explicitCallTransfer");
// can't transfer call if there is not enough call parties
if (mCalls.size() < 2) {
@@ -785,7 +784,7 @@
HeadsetClientHalConstants.CALL_ACTION_CHLD_4, -1)) {
addQueuedAction(EXPLICIT_CALL_TRANSFER);
} else {
- Log.e(TAG, "ERROR: Couldn't transfer call");
+ error("ERROR: Couldn't transfer call");
}
}
@@ -940,7 +939,7 @@
static HeadsetClientStateMachine make(HeadsetClientService context,
HeadsetService headsetService,
Looper looper, NativeInterface nativeInterface) {
- logD("make");
+ Log.d(TAG, "make");
HeadsetClientStateMachine hfcsm = new HeadsetClientStateMachine(context, headsetService,
looper, nativeInterface);
hfcsm.start();
@@ -949,10 +948,10 @@
synchronized void routeHfpAudio(boolean enable) {
if (mAudioManager == null) {
- Log.e(TAG, "AudioManager is null!");
+ error("AudioManager is null!");
return;
}
- logD("hfp_enable=" + enable);
+ debug("hfp_enable=" + enable);
if (enable && !sAudioIsRouted) {
mAudioManager.setHfpEnabled(true);
} else if (!enable) {
@@ -973,12 +972,12 @@
int focusRequestStatus = mAudioManager.requestAudioFocus(focusRequest);
String s = (focusRequestStatus == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
? "AudioFocus granted" : "AudioFocus NOT granted";
- logD("AudioManager requestAudioFocus returned: " + s);
+ debug("AudioManager requestAudioFocus returned: " + s);
return focusRequest;
}
public void doQuit() {
- logD("doQuit");
+ debug("doQuit");
if (mCurrentDevice != null) {
mNativeInterface.disconnect(mCurrentDevice);
}
@@ -998,7 +997,7 @@
int hfRange = MAX_HFP_SCO_VOICE_CALL_VOLUME - MIN_HFP_SCO_VOICE_CALL_VOLUME;
int amOffset = (amRange * (hfVol - MIN_HFP_SCO_VOICE_CALL_VOLUME)) / hfRange;
int amVol = sMinAmVcVol + amOffset;
- logD("HF -> AM " + hfVol + " " + amVol);
+ Log.d(TAG, "HF -> AM " + hfVol + " " + amVol);
return amVol;
}
@@ -1007,14 +1006,14 @@
int hfRange = MAX_HFP_SCO_VOICE_CALL_VOLUME - MIN_HFP_SCO_VOICE_CALL_VOLUME;
int hfOffset = (hfRange * (amVol - sMinAmVcVol)) / amRange;
int hfVol = MIN_HFP_SCO_VOICE_CALL_VOLUME + hfOffset;
- logD("AM -> HF " + amVol + " " + hfVol);
+ Log.d(TAG, "AM -> HF " + amVol + " " + hfVol);
return hfVol;
}
class Disconnected extends State {
@Override
public void enter() {
- logD("Enter Disconnected: " + getCurrentMessage().what);
+ debug("Enter Disconnected: " + getCurrentMessage().what);
// cleanup
mIndicatorNetworkState = HeadsetClientHalConstants.NETWORK_STATE_NOT_AVAILABLE;
@@ -1048,7 +1047,7 @@
broadcastConnectionState(mCurrentDevice, BluetoothProfile.STATE_DISCONNECTED,
BluetoothProfile.STATE_CONNECTED);
} else if (mPrevState != null) { // null is the default state before Disconnected
- Log.e(TAG, "Disconnected: Illegal state transition from " + mPrevState.getName()
+ error("Disconnected: Illegal state transition from " + mPrevState.getName()
+ " to Disconnected, mCurrentDevice=" + mCurrentDevice);
}
if (mHeadsetService != null && mCurrentDevice != null) {
@@ -1059,10 +1058,10 @@
@Override
public synchronized boolean processMessage(Message message) {
- logD("Disconnected process message: " + message.what);
+ debug("Disconnected process message: " + message.what);
if (mCurrentDevice != null) {
- Log.e(TAG, "ERROR: current device not null in Disconnected");
+ error("ERROR: current device not null in Disconnected");
return NOT_HANDLED;
}
@@ -1083,15 +1082,15 @@
break;
case StackEvent.STACK_EVENT:
StackEvent event = (StackEvent) message.obj;
- logD("Stack event type: " + event.type);
+ debug("Stack event type: " + event.type);
switch (event.type) {
case StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED:
- logD("Disconnected: Connection " + event.device
+ debug("Disconnected: Connection " + event.device
+ " state changed:" + event.valueInt);
processConnectionEvent(event.valueInt, event.device);
break;
default:
- Log.e(TAG, "Disconnected: Unexpected stack event: " + event.type);
+ error("Disconnected: Unexpected stack event: " + event.type);
break;
}
break;
@@ -1105,13 +1104,13 @@
private void processConnectionEvent(int state, BluetoothDevice device) {
switch (state) {
case HeadsetClientHalConstants.CONNECTION_STATE_CONNECTED:
- Log.w(TAG, "HFPClient Connecting from Disconnected state");
+ warn("HFPClient Connecting from Disconnected state");
if (okToConnect(device)) {
- Log.i(TAG, "Incoming AG accepted");
+ info("Incoming AG accepted");
mCurrentDevice = device;
transitionTo(mConnecting);
} else {
- Log.i(TAG, "Incoming AG rejected. connectionPolicy="
+ info("Incoming AG rejected. connectionPolicy="
+ mService.getConnectionPolicy(device) + " bondState="
+ device.getBondState());
// reject the connection and stay in Disconnected state
@@ -1127,14 +1126,14 @@
case HeadsetClientHalConstants.CONNECTION_STATE_DISCONNECTED:
case HeadsetClientHalConstants.CONNECTION_STATE_DISCONNECTING:
default:
- Log.i(TAG, "ignoring state: " + state);
+ info("ignoring state: " + state);
break;
}
}
@Override
public void exit() {
- logD("Exit Disconnected: " + getCurrentMessage().what);
+ debug("Exit Disconnected: " + getCurrentMessage().what);
mPrevState = this;
}
}
@@ -1142,7 +1141,7 @@
class Connecting extends State {
@Override
public void enter() {
- logD("Enter Connecting: " + getCurrentMessage().what);
+ debug("Enter Connecting: " + getCurrentMessage().what);
// This message is either consumed in processMessage or
// removed in exit. It is safe to send a CONNECTING_TIMEOUT here since
// the only transition is when connection attempt is initiated.
@@ -1152,14 +1151,14 @@
BluetoothProfile.STATE_DISCONNECTED);
} else {
String prevStateName = mPrevState == null ? "null" : mPrevState.getName();
- Log.e(TAG, "Connecting: Illegal state transition from " + prevStateName
- + " to Connecting, mCurrentDevice=" + mCurrentDevice);
+ error("Connecting: Illegal state transition from " + prevStateName
+ + " to Connecting");
}
}
@Override
public synchronized boolean processMessage(Message message) {
- logD("Connecting process message: " + message.what);
+ debug("Connecting process message: " + message.what);
switch (message.what) {
case CONNECT:
@@ -1169,10 +1168,10 @@
break;
case StackEvent.STACK_EVENT:
StackEvent event = (StackEvent) message.obj;
- logD("Connecting: event type: " + event.type);
+ debug("Connecting: event type: " + event.type);
switch (event.type) {
case StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED:
- logD("Connecting: Connection " + event.device + " state changed:"
+ debug("Connecting: Connection " + event.device + " state changed:"
+ event.valueInt);
processConnectionEvent(event.valueInt, event.valueInt2, event.valueInt3,
event.device);
@@ -1193,10 +1192,10 @@
deferMessage(message);
break;
case StackEvent.EVENT_TYPE_CMD_RESULT:
- logD("Connecting: CMD_RESULT valueInt:" + event.valueInt
+ debug("Connecting: CMD_RESULT valueInt:" + event.valueInt
+ " mQueuedActions.size=" + mQueuedActions.size());
if (!mQueuedActions.isEmpty()) {
- logD("queuedAction:" + mQueuedActions.peek().first);
+ debug("queuedAction:" + mQueuedActions.peek().first);
}
Pair<Integer, Object> queuedAction = mQueuedActions.poll();
if (queuedAction == null || queuedAction.first == NO_ACTION) {
@@ -1205,15 +1204,15 @@
switch (queuedAction.first) {
case SEND_ANDROID_AT_COMMAND:
if (event.valueInt == StackEvent.CMD_RESULT_TYPE_OK) {
- Log.w(TAG, "Received OK instead of +ANDROID");
+ warn("Received OK instead of +ANDROID");
} else {
- Log.w(TAG, "Received ERROR instead of +ANDROID");
+ warn("Received ERROR instead of +ANDROID");
}
setAudioPolicyRemoteSupported(false);
transitionTo(mConnected);
break;
default:
- Log.w(TAG, "Ignored CMD Result");
+ warn("Ignored CMD Result");
break;
}
break;
@@ -1223,7 +1222,7 @@
&& processAndroidSlcCommand(event.valueString, event.device)) {
transitionTo(mConnected);
} else {
- Log.e(TAG, "Unknown event :" + event.valueString
+ error("Unknown event :" + event.valueString
+ " for device " + event.device);
}
break;
@@ -1232,18 +1231,18 @@
case StackEvent.EVENT_TYPE_CURRENT_CALLS:
case StackEvent.EVENT_TYPE_OPERATOR_NAME:
default:
- Log.e(TAG, "Connecting: ignoring stack event: " + event.type);
+ error("Connecting: ignoring stack event: " + event.type);
break;
}
break;
case CONNECTING_TIMEOUT:
// We timed out trying to connect, transition to disconnected.
- Log.w(TAG, "Connection timeout for " + mCurrentDevice);
+ warn("Connection timeout for " + mCurrentDevice);
transitionTo(mDisconnected);
break;
default:
- Log.w(TAG, "Message not handled " + message);
+ warn("Message not handled " + message);
return NOT_HANDLED;
}
return HANDLED;
@@ -1258,7 +1257,7 @@
break;
case HeadsetClientHalConstants.CONNECTION_STATE_SLC_CONNECTED:
- logD("HFPClient Connected from Connecting state");
+ debug("HFPClient Connected from Connecting state");
mPeerFeatures = peerFeat;
mChldFeatures = chldFeat;
@@ -1278,7 +1277,7 @@
null)) {
addQueuedAction(DISABLE_NREC);
} else {
- Log.e(TAG, "Failed to send NREC");
+ error("Failed to send NREC");
}
}
@@ -1293,14 +1292,14 @@
deferMessage(obtainMessage(HeadsetClientStateMachine.SUBSCRIBER_INFO));
if (!queryRemoteSupportedFeatures()) {
- Log.w(TAG, "Couldn't query Android AT remote supported!");
+ warn("Couldn't query Android AT remote supported!");
transitionTo(mConnected);
}
break;
case HeadsetClientHalConstants.CONNECTION_STATE_CONNECTED:
if (!mCurrentDevice.equals(device)) {
- Log.w(TAG, "incoming connection event, device: " + device);
+ warn("incoming connection event, device: " + device);
// No state transition is involved, fire broadcast immediately
broadcastConnectionState(mCurrentDevice,
BluetoothProfile.STATE_DISCONNECTED,
@@ -1313,18 +1312,18 @@
break;
case HeadsetClientHalConstants.CONNECTION_STATE_CONNECTING:
/* outgoing connecting started */
- logD("outgoing connection started, ignore");
+ debug("outgoing connection started, ignore");
break;
case HeadsetClientHalConstants.CONNECTION_STATE_DISCONNECTING:
default:
- Log.e(TAG, "Incorrect state: " + state);
+ error("Incorrect state: " + state);
break;
}
}
@Override
public void exit() {
- logD("Exit Connecting: " + getCurrentMessage().what);
+ debug("Exit Connecting: " + getCurrentMessage().what);
removeMessages(CONNECTING_TIMEOUT);
mPrevState = this;
}
@@ -1335,7 +1334,7 @@
@Override
public void enter() {
- logD("Enter Connected: " + getCurrentMessage().what);
+ debug("Enter Connected: " + getCurrentMessage().what);
mAudioWbs = false;
mAudioSWB = false;
mCommandedSpeakerVolume = -1;
@@ -1350,17 +1349,17 @@
BluetoothMetricsProto.ProfileId.HEADSET_CLIENT);
} else if (mPrevState != mAudioOn) {
String prevStateName = mPrevState == null ? "null" : mPrevState.getName();
- Log.e(TAG, "Connected: Illegal state transition from " + prevStateName
- + " to Connected, mCurrentDevice=" + mCurrentDevice);
+ error("Connected: Illegal state transition from " + prevStateName
+ + " to Connected");
}
mService.updateBatteryLevel();
}
@Override
public synchronized boolean processMessage(Message message) {
- logD("Connected process message: " + message.what);
+ debug("Connected process message: " + message.what);
if (mCurrentDevice == null) {
- Log.e(TAG, "ERROR: mCurrentDevice is null in Connected");
+ error("ERROR: mCurrentDevice is null in Connected");
return NOT_HANDLED;
}
@@ -1379,13 +1378,13 @@
break;
}
if (!mNativeInterface.disconnect(dev)) {
- Log.e(TAG, "disconnectNative failed for " + dev);
+ error("disconnectNative failed for " + dev);
}
break;
case CONNECT_AUDIO:
if (!mNativeInterface.connectAudio(mCurrentDevice)) {
- Log.e(TAG, "ERROR: Couldn't connect Audio for device " + mCurrentDevice);
+ error("ERROR: Couldn't connect Audio for device");
// No state transition is involved, fire broadcast immediately
broadcastAudioState(mCurrentDevice,
BluetoothHeadsetClient.STATE_AUDIO_DISCONNECTED,
@@ -1397,7 +1396,7 @@
case DISCONNECT_AUDIO:
if (!mNativeInterface.disconnectAudio(mCurrentDevice)) {
- Log.e(TAG, "ERROR: Couldn't disconnect Audio for device " + mCurrentDevice);
+ error("ERROR: Couldn't disconnect Audio for device");
}
break;
@@ -1406,7 +1405,7 @@
if (mNativeInterface.startVoiceRecognition(mCurrentDevice)) {
addQueuedAction(VOICE_RECOGNITION_START);
} else {
- Log.e(TAG, "ERROR: Couldn't start voice recognition");
+ error("ERROR: Couldn't start voice recognition");
}
}
break;
@@ -1416,7 +1415,7 @@
if (mNativeInterface.stopVoiceRecognition(mCurrentDevice)) {
addQueuedAction(VOICE_RECOGNITION_STOP);
} else {
- Log.e(TAG, "ERROR: Couldn't stop voice recognition");
+ error("ERROR: Couldn't stop voice recognition");
}
}
break;
@@ -1450,7 +1449,7 @@
int amVol = message.arg1;
int hfVol = amToHfVol(amVol);
if (amVol != mCommandedSpeakerVolume) {
- logD("Volume" + amVol + ":" + mCommandedSpeakerVolume);
+ debug("Volume" + amVol + ":" + mCommandedSpeakerVolume);
// Volume was changed by a 3rd party
mCommandedSpeakerVolume = -1;
if (mNativeInterface.setVolume(mCurrentDevice,
@@ -1500,21 +1499,19 @@
(byte) message.arg1)) {
addQueuedAction(SEND_DTMF);
} else {
- Log.e(TAG, "ERROR: Couldn't send DTMF");
+ error("ERROR: Couldn't send DTMF");
}
break;
case SUBSCRIBER_INFO:
if (mNativeInterface.retrieveSubscriberInfo(mCurrentDevice)) {
addQueuedAction(SUBSCRIBER_INFO);
} else {
- Log.e(TAG, "ERROR: Couldn't retrieve subscriber info");
+ error("ERROR: Couldn't retrieve subscriber info");
}
break;
case QUERY_CURRENT_CALLS:
removeMessages(QUERY_CURRENT_CALLS);
- if (DBG) {
- Log.d(TAG, "mClccPollDuringCall=" + mClccPollDuringCall);
- }
+ debug("mClccPollDuringCall=" + mClccPollDuringCall);
// If there are ongoing calls periodically check their status.
if (mCalls.size() > 1
&& mClccPollDuringCall) {
@@ -1530,21 +1527,21 @@
case StackEvent.STACK_EVENT:
Intent intent = null;
StackEvent event = (StackEvent) message.obj;
- logD("Connected: event type: " + event.type);
+ debug("Connected: event type: " + event.type);
switch (event.type) {
case StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED:
- logD("Connected: Connection state changed: " + event.device
+ debug("Connected: Connection state changed: " + event.device
+ ": " + event.valueInt);
processConnectionEvent(event.valueInt, event.device);
break;
case StackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED:
- logD("Connected: Audio state changed: " + event.device + ": "
+ debug("Connected: Audio state changed: " + event.device + ": "
+ event.valueInt);
processAudioEvent(event.valueInt, event.device);
break;
case StackEvent.EVENT_TYPE_NETWORK_STATE:
- logD("Connected: Network state: " + event.valueInt);
+ debug("Connected: Network state: " + event.valueInt);
mIndicatorNetworkState = event.valueInt;
intent = new Intent(BluetoothHeadsetClient.ACTION_AG_EVENT);
@@ -1568,7 +1565,7 @@
if (mNativeInterface.queryCurrentOperatorName(mCurrentDevice)) {
addQueuedAction(QUERY_OPERATOR_NAME);
} else {
- Log.e(TAG, "ERROR: Couldn't querry operator name");
+ error("ERROR: Couldn't querry operator name");
}
}
break;
@@ -1640,7 +1637,7 @@
case StackEvent.EVENT_TYPE_VOLUME_CHANGED:
if (event.valueInt == HeadsetClientHalConstants.VOLUME_TYPE_SPK) {
mCommandedSpeakerVolume = hfToAmVol(event.valueInt2);
- logD("AM volume set to " + mCommandedSpeakerVolume);
+ debug("AM volume set to " + mCommandedSpeakerVolume);
boolean show_volume = SystemProperties
.getBoolean("bluetooth.hfp_volume_control.enabled", true);
mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
@@ -1659,7 +1656,7 @@
break;
}
- logD("Connected: command result: " + event.valueInt
+ debug("Connected: command result: " + event.valueInt
+ " queuedAction: " + queuedAction.first);
switch (queuedAction.first) {
@@ -1685,9 +1682,9 @@
}
break;
case SEND_ANDROID_AT_COMMAND:
- logD("Connected: Received OK for AT+ANDROID");
+ debug("Connected: Received OK for AT+ANDROID");
default:
- Log.w(TAG, "Unhandled AT OK " + event);
+ warn("Unhandled AT OK " + event);
break;
}
@@ -1709,7 +1706,7 @@
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, event.device);
Utils.sendBroadcast(mService, intent, BLUETOOTH_CONNECT,
Utils.getTempAllowlistBroadcastOptions());
- logD(event.device.toString() + "onInBandRing" + event.valueInt);
+ debug(event.device.toString() + "onInBandRing" + event.valueInt);
break;
case StackEvent.EVENT_TYPE_RING_INDICATION:
// Ringing is not handled at this indication and rather should be
@@ -1718,12 +1715,12 @@
break;
case StackEvent.EVENT_TYPE_UNKNOWN_EVENT:
if (!mVendorProcessor.processEvent(event.valueString, event.device)) {
- Log.e(TAG, "Unknown event :" + event.valueString
+ error("Unknown event :" + event.valueString
+ " for device " + event.device);
}
break;
default:
- Log.e(TAG, "Unknown stack event: " + event.type);
+ error("Unknown stack event: " + event.type);
break;
}
@@ -1750,16 +1747,16 @@
private void processConnectionEvent(int state, BluetoothDevice device) {
switch (state) {
case HeadsetClientHalConstants.CONNECTION_STATE_DISCONNECTED:
- logD("Connected disconnects.");
+ debug("Connected disconnects.");
// AG disconnects
if (mCurrentDevice.equals(device)) {
transitionTo(mDisconnected);
} else {
- Log.e(TAG, "Disconnected from unknown device: " + device);
+ error("Disconnected from unknown device: " + device);
}
break;
default:
- Log.e(TAG, "Connection State Device: " + device + " bad state: " + state);
+ error("Connection State Device: " + device + " bad state: " + state);
break;
}
}
@@ -1768,7 +1765,7 @@
private void processAudioEvent(int state, BluetoothDevice device) {
// message from old device
if (!mCurrentDevice.equals(device)) {
- Log.e(TAG, "Audio changed on disconnected device: " + device);
+ error("Audio changed on disconnected device: " + device);
return;
}
@@ -1778,11 +1775,9 @@
HeadsetClientHalConstants.AUDIO_STATE_CONNECTED_MSBC:
mAudioSWB = state == HeadsetClientHalConstants.AUDIO_STATE_CONNECTED_LC3;
mAudioWbs = state == HeadsetClientHalConstants.AUDIO_STATE_CONNECTED_MSBC;
- if (DBG) {
- Log.d(TAG, "mAudioRouteAllowed=" + mAudioRouteAllowed);
- }
+ debug("mAudioRouteAllowed=" + mAudioRouteAllowed);
if (!mAudioRouteAllowed) {
- Log.i(TAG, "Audio is not allowed! Disconnect SCO.");
+ info("Audio is not allowed! Disconnect SCO.");
sendMessage(HeadsetClientStateMachine.DISCONNECT_AUDIO);
// Don't continue connecting!
return;
@@ -1812,20 +1807,20 @@
final int amVol = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
final int hfVol = amToHfVol(amVol);
- logD("hfp_enable=true mAudioSWB is " + mAudioSWB);
- logD("hfp_enable=true mAudioWbs is " + mAudioWbs);
+ debug("hfp_enable=true mAudioSWB is " + mAudioSWB);
+ debug("hfp_enable=true mAudioWbs is " + mAudioWbs);
if (mAudioSWB) {
- logD("Setting sampling rate as 32000");
+ debug("Setting sampling rate as 32000");
mAudioManager.setHfpSamplingRate(32000);
} else if (mAudioWbs) {
- logD("Setting sampling rate as 16000");
+ debug("Setting sampling rate as 16000");
mAudioManager.setHfpSamplingRate(16000);
} else {
- logD("Setting sampling rate as 8000");
+ debug("Setting sampling rate as 8000");
mAudioManager.setHfpSamplingRate(8000);
}
- logD("hf_volume " + hfVol);
+ debug("hf_volume " + hfVol);
routeHfpAudio(true);
mAudioFocusRequest = requestAudioFocus();
mAudioManager.setHfpVolume(hfVol);
@@ -1847,14 +1842,14 @@
break;
default:
- Log.e(TAG, "Audio State Device: " + device + " bad state: " + state);
+ error("Audio State Device: " + device + " bad state: " + state);
break;
}
}
@Override
public void exit() {
- logD("Exit Connected: " + getCurrentMessage().what);
+ debug("Exit Connected: " + getCurrentMessage().what);
mPrevState = this;
}
}
@@ -1862,16 +1857,16 @@
class AudioOn extends State {
@Override
public void enter() {
- logD("Enter AudioOn: " + getCurrentMessage().what);
+ debug("Enter AudioOn: " + getCurrentMessage().what);
broadcastAudioState(mCurrentDevice, BluetoothHeadsetClient.STATE_AUDIO_CONNECTED,
BluetoothHeadsetClient.STATE_AUDIO_CONNECTING);
}
@Override
public synchronized boolean processMessage(Message message) {
- logD("AudioOn process message: " + message.what);
+ debug("AudioOn process message: " + message.what);
if (mCurrentDevice == null) {
- Log.e(TAG, "ERROR: mCurrentDevice is null in Connected");
+ error("ERROR: mCurrentDevice is null in Connected");
return NOT_HANDLED;
}
@@ -1904,15 +1899,15 @@
case StackEvent.STACK_EVENT:
StackEvent event = (StackEvent) message.obj;
- logD("AudioOn: event type: " + event.type);
+ debug("AudioOn: event type: " + event.type);
switch (event.type) {
case StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED:
- logD("AudioOn connection state changed" + event.device + ": "
+ debug("AudioOn connection state changed" + event.device + ": "
+ event.valueInt);
processConnectionEvent(event.valueInt, event.device);
break;
case StackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED:
- logD("AudioOn audio state changed" + event.device + ": "
+ debug("AudioOn audio state changed" + event.device + ": "
+ event.valueInt);
processAudioEvent(event.valueInt, event.device);
break;
@@ -1935,11 +1930,11 @@
device);
transitionTo(mDisconnected);
} else {
- Log.e(TAG, "Disconnected from unknown device: " + device);
+ error("Disconnected from unknown device: " + device);
}
break;
default:
- Log.e(TAG, "Connection State Device: " + device + " bad state: " + state);
+ error("Connection State Device: " + device + " bad state: " + state);
break;
}
}
@@ -1947,7 +1942,7 @@
// in AudioOn state
private void processAudioEvent(int state, BluetoothDevice device) {
if (!mCurrentDevice.equals(device)) {
- Log.e(TAG, "Audio changed on disconnected device: " + device);
+ error("Audio changed on disconnected device: " + device);
return;
}
@@ -1965,14 +1960,14 @@
break;
default:
- Log.e(TAG, "Audio State Device: " + device + " bad state: " + state);
+ error("Audio State Device: " + device + " bad state: " + state);
break;
}
}
@Override
public void exit() {
- logD("Exit AudioOn: " + getCurrentMessage().what);
+ debug("Exit AudioOn: " + getCurrentMessage().what);
mPrevState = this;
broadcastAudioState(mCurrentDevice, BluetoothHeadsetClient.STATE_AUDIO_DISCONNECTED,
BluetoothHeadsetClient.STATE_AUDIO_CONNECTED);
@@ -1993,7 +1988,7 @@
return BluetoothProfile.STATE_CONNECTED;
}
- Log.e(TAG, "Bad currentState: " + currentState);
+ error("Bad currentState: " + currentState);
return BluetoothProfile.STATE_DISCONNECTED;
}
@@ -2022,7 +2017,7 @@
Utils.sendBroadcast(mService, intent, BLUETOOTH_CONNECT,
Utils.getTempAllowlistBroadcastOptions());
- logD("Audio state " + device + ": " + prevState + "->" + newState);
+ debug("Audio state " + device + ": " + prevState + "->" + newState);
HfpClientConnectionService.onAudioStateChanged(device, newState, prevState);
}
@@ -2042,7 +2037,7 @@
break;
}
String feature = atString.substring(indexUpperBucket + 1, indexLowerBucket);
- Log.d(TAG, "processAndroidSlcCommand: feature=[" + feature + "]");
+ debug("processAndroidSlcCommand: feature=[" + feature + "]");
processAndroidAtFeature(feature.split(","));
atString = atString.substring(indexLowerBucket + 1);
@@ -2052,13 +2047,13 @@
private void processAndroidAtFeature(String[] args) {
if (args.length < 1) {
- Log.e(TAG, "processAndroidAtFeature: Invalid feature length");
+ error("processAndroidAtFeature: Invalid feature length");
return;
}
String featureId = args[0];
if (featureId.equals(BluetoothSinkAudioPolicy.HFP_SET_SINK_AUDIO_POLICY_ID)) {
- Log.i(TAG, "processAndroidAtFeature:"
+ info("processAndroidAtFeature:"
+ BluetoothSinkAudioPolicy.HFP_SET_SINK_AUDIO_POLICY_ID + " supported");
setAudioPolicyRemoteSupported(true);
@@ -2075,7 +2070,7 @@
// This method does not check for error condition (newState == prevState)
private void broadcastConnectionState(BluetoothDevice device, int newState, int prevState) {
- logD("Connection state " + device + ": " + prevState + "->" + newState);
+ debug("Connection state " + device + ": " + prevState + "->" + newState);
/*
* Notifying the connection state change of the profile before sending
* the intent for connection state change, as it was causing a race
@@ -2234,12 +2229,25 @@
return BluetoothAdapter.STATE_DISCONNECTED;
}
- private static void logD(String message) {
- if (DBG) {
- Log.d(TAG, message);
- }
+ private void debug(String message) {
+ Log.d(TAG, "[" + mCurrentDevice + "]: " + message);
}
+ private void info(String message) {
+ Log.i(TAG, "[" + mCurrentDevice + "]: " + message);
+ }
+
+ private void warn(String message) {
+
+ Log.w(TAG, "[" + mCurrentDevice + "]: " + message);
+ }
+
+ private void error(String message) {
+
+ Log.e(TAG, "[" + mCurrentDevice + "]: " + message);
+ }
+
+
public void setAudioRouteAllowed(boolean allowed) {
mAudioRouteAllowed = allowed;
@@ -2294,26 +2302,26 @@
* @param policies to be set policies
*/
public void setAudioPolicy(BluetoothSinkAudioPolicy policies) {
- logD("setAudioPolicy: " + policies);
+ debug("setAudioPolicy: " + policies);
mHsClientAudioPolicy = policies;
if (getAudioPolicyRemoteSupported() != BluetoothStatusCodes.FEATURE_SUPPORTED) {
- Log.i(TAG, "Audio Policy feature not supported!");
+ info("Audio Policy feature not supported!");
return;
}
if (!mNativeInterface.sendAndroidAt(mCurrentDevice,
"+ANDROID=" + createMaskString(policies))) {
- Log.e(TAG, "ERROR: Couldn't send call audio policies");
+ error("ERROR: Couldn't send call audio policies");
return;
}
addQueuedAction(SEND_ANDROID_AT_COMMAND);
}
private boolean queryRemoteSupportedFeatures() {
- Log.i(TAG, "queryRemoteSupportedFeatures");
+ info("queryRemoteSupportedFeatures");
if (!mNativeInterface.sendAndroidAt(mCurrentDevice, "+ANDROID=?")) {
- Log.e(TAG, "ERROR: Couldn't send audio policy feature query");
+ error("ERROR: Couldn't send audio policy feature query");
return false;
}
addQueuedAction(SEND_ANDROID_AT_COMMAND);
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java
index 4de8a55..78855e1 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java
@@ -28,8 +28,7 @@
import java.util.UUID;
public class HfpClientConnection extends Connection {
- private static final String TAG = "HfpClientConnection";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = HfpClientConnection.class.getSimpleName();
private static final String EVENT_SCO_CONNECT = "com.android.bluetooth.hfpclient.SCO_CONNECT";
private static final String EVENT_SCO_DISCONNECT =
@@ -69,7 +68,7 @@
mCurrentCall = mServiceInterface.dial(mDevice, number.getSchemeSpecificPart());
if (mCurrentCall == null) {
close(DisconnectCause.ERROR);
- Log.e(TAG, "Failed to create the call, dial failed.");
+ error("Failed to create the call, dial failed.");
return;
}
@@ -117,7 +116,7 @@
public void updateCall(HfpClientCall call) {
if (call == null) {
- Log.e(TAG, "Updating call to a null value.");
+ error("Updating call to a null value.");
return;
}
mCurrentCall = call;
@@ -127,9 +126,7 @@
HfpClientConference conference = (HfpClientConference) getConference();
int state = mCurrentCall.getState();
- if (DBG) {
- Log.d(TAG, "Got call state change to " + state);
- }
+ debug("Got call state change to " + state);
switch (state) {
case HfpClientCall.CALL_STATE_ACTIVE:
setActive();
@@ -163,19 +160,17 @@
}
break;
default:
- Log.wtf(TAG, "Unexpected phone state " + state);
+ Log.wtf(TAG, "[" + mDevice + "]Unexpected phone state " + state);
}
mPreviousCallState = state;
}
public synchronized void close(int cause) {
- if (DBG) {
- Log.d(TAG, "Closing call " + mCurrentCall + "state: " + mClosed);
- }
+ debug("Closing call " + mCurrentCall + "state: " + mClosed);
if (mClosed) {
return;
}
- Log.d(TAG, "Setting " + mCurrentCall + " to disconnected " + getTelecomCallId());
+ debug("Setting " + mCurrentCall + " to disconnected " + getTelecomCallId());
setDisconnected(new DisconnectCause(cause));
mClosed = true;
@@ -194,9 +189,7 @@
@Override
public synchronized void onPlayDtmfTone(char c) {
- if (DBG) {
- Log.d(TAG, "onPlayDtmfTone " + c + " " + mCurrentCall);
- }
+ debug("onPlayDtmfTone " + c + " " + mCurrentCall);
if (!mClosed) {
mServiceInterface.sendDTMF(mDevice, (byte) c);
}
@@ -204,9 +197,7 @@
@Override
public synchronized void onDisconnect() {
- if (DBG) {
- Log.d(TAG, "onDisconnect call: " + mCurrentCall + " state: " + mClosed);
- }
+ debug("onDisconnect call: " + mCurrentCall + " state: " + mClosed);
// The call is not closed so we should send a terminate here.
if (!mClosed) {
mServiceInterface.terminateCall(mDevice, mCurrentCall);
@@ -217,17 +208,13 @@
@Override
public void onAbort() {
- if (DBG) {
- Log.d(TAG, "onAbort " + mCurrentCall);
- }
+ debug("onAbort " + mCurrentCall);
onDisconnect();
}
@Override
public synchronized void onHold() {
- if (DBG) {
- Log.d(TAG, "onHold " + mCurrentCall);
- }
+ debug("onHold " + mCurrentCall);
if (!mClosed) {
mServiceInterface.holdCall(mDevice);
}
@@ -239,9 +226,7 @@
Log.w(TAG, "Ignoring unhold; call hold on the foreground call");
return;
}
- if (DBG) {
- Log.d(TAG, "onUnhold " + mCurrentCall);
- }
+ debug("onUnhold " + mCurrentCall);
if (!mClosed) {
mServiceInterface.acceptCall(mDevice, HeadsetClientServiceInterface.CALL_ACCEPT_HOLD);
}
@@ -249,9 +234,7 @@
@Override
public synchronized void onAnswer() {
- if (DBG) {
- Log.d(TAG, "onAnswer " + mCurrentCall);
- }
+ debug("onAnswer " + mCurrentCall);
if (!mClosed) {
mServiceInterface.acceptCall(mDevice, HeadsetClientServiceInterface.CALL_ACCEPT_NONE);
}
@@ -259,9 +242,7 @@
@Override
public synchronized void onReject() {
- if (DBG) {
- Log.d(TAG, "onReject " + mCurrentCall);
- }
+ debug("onReject " + mCurrentCall);
if (!mClosed) {
mServiceInterface.rejectCall(mDevice);
}
@@ -269,9 +250,7 @@
@Override
public void onCallEvent(String event, Bundle extras) {
- if (DBG) {
- Log.d(TAG, "onCallEvent(" + event + ", " + extras + ")");
- }
+ debug("onCallEvent(" + event + ", " + extras + ")");
if (mClosed) {
return;
}
@@ -299,4 +278,13 @@
return "HfpClientConnection{" + getAddress() + "," + stateToString(getState()) + ","
+ mCurrentCall + "}";
}
+
+ private void debug(String message) {
+ Log.d(TAG, "[" + mDevice + "]: " + message);
+ }
+
+ private void error(String message) {
+
+ Log.e(TAG, "[" + mDevice + "]: " + message);
+ }
}
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java
index 0757c1f..5f079cc 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java
@@ -42,8 +42,7 @@
import java.util.Objects;
public class HfpClientConnectionService extends ConnectionService {
- private static final String TAG = "HfpClientConnService";
- private static final boolean DBG = true;
+ private static final String TAG = HfpClientConnectionService.class.getSimpleName();
public static final String HFP_SCHEME = "hfpc";
@@ -128,18 +127,14 @@
private void onConnectionStateChangedInternal(BluetoothDevice device, int newState,
int oldState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
- if (DBG) {
- Log.d(TAG, "Established connection with " + device);
- }
+ Log.d(TAG, "Established connection with " + device);
HfpClientDeviceBlock block = createBlockForDevice(device);
if (block == null) {
Log.w(TAG, "Block already exists for device= " + device + ", ignoring.");
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
- if (DBG) {
- Log.d(TAG, "Disconnecting from " + device);
- }
+ Log.d(TAG, "Disconnecting from " + device);
// Disconnect any inflight calls from the connection service.
synchronized (HfpClientConnectionService.this) {
@@ -197,9 +192,7 @@
@Override
public void onCreate() {
super.onCreate();
- if (DBG) {
- Log.d(TAG, "onCreate");
- }
+ Log.d(TAG, "onCreate");
mTelecomManager = getSystemService(TelecomManager.class);
if (mTelecomManager != null) mTelecomManager.clearPhoneAccounts();
@@ -215,9 +208,7 @@
@Override
public void onDestroy() {
- if (DBG) {
- Log.d(TAG, "onDestroy called");
- }
+ Log.d(TAG, "onDestroy called");
// Unregister the phone account. This should ideally happen when disconnection ensues but in
// case the service crashes we may need to force clean.
@@ -236,9 +227,7 @@
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
- if (DBG) {
- Log.d(TAG, "onStartCommand " + intent);
- }
+ Log.d(TAG, "onStartCommand " + intent);
// In order to make sure that the service is sticky (recovers from errors when HFP
// connection is still active) and to stop it we need a special intent since stopService
// only recreates it.
@@ -259,10 +248,8 @@
@Override
public Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerAccount,
ConnectionRequest request) {
- if (DBG) {
- Log.d(TAG,
- "onCreateIncomingConnection " + connectionManagerAccount + " req: " + request);
- }
+ Log.d(TAG,
+ "onCreateIncomingConnection " + connectionManagerAccount + " req: " + request);
HfpClientDeviceBlock block = findBlockForHandle(connectionManagerAccount);
if (block == null) {
@@ -282,9 +269,7 @@
@Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerAccount,
ConnectionRequest request) {
- if (DBG) {
- Log.d(TAG, "onCreateOutgoingConnection " + connectionManagerAccount);
- }
+ Log.d(TAG, "onCreateOutgoingConnection " + connectionManagerAccount);
HfpClientDeviceBlock block = findBlockForHandle(connectionManagerAccount);
if (block == null) {
Log.w(TAG, "HfpClient does not support having a connection manager");
@@ -300,9 +285,7 @@
@Override
public Connection onCreateUnknownConnection(PhoneAccountHandle connectionManagerAccount,
ConnectionRequest request) {
- if (DBG) {
- Log.d(TAG, "onCreateUnknownConnection " + connectionManagerAccount);
- }
+ Log.d(TAG, "onCreateUnknownConnection " + connectionManagerAccount);
HfpClientDeviceBlock block = findBlockForHandle(connectionManagerAccount);
if (block == null) {
Log.w(TAG, "HfpClient does not support having a connection manager");
@@ -319,9 +302,7 @@
@Override
public void onConference(Connection connection1, Connection connection2) {
- if (DBG) {
- Log.d(TAG, "onConference " + connection1 + " " + connection2);
- }
+ Log.d(TAG, "onConference " + connection1 + " " + connection2);
BluetoothDevice bd1 = ((HfpClientConnection) connection1).getDevice();
BluetoothDevice bd2 = ((HfpClientConnection) connection2).getDevice();
@@ -395,9 +376,7 @@
.setSupportedUriSchemes(Arrays.asList(PhoneAccount.SCHEME_TEL))
.setCapabilities(capabilities)
.build();
- if (DBG) {
- Log.d(TAG, "phoneaccount: " + account);
- }
+ Log.d(TAG, "phoneaccount: " + account);
return account;
}
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
index f50405f..eba4f0c 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
@@ -38,8 +38,7 @@
// 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 TAG = "HfpClientDeviceBlock";
- private static final boolean DBG = false;
+ private static final String TAG = HfpClientDeviceBlock.class.getSimpleName();
private static final String KEY_SCO_STATE = "com.android.bluetooth.hfpclient.SCO_STATE";
@@ -383,16 +382,14 @@
// Per-Device logging
public void debug(String message) {
- if (DBG) {
- Log.d(TAG, "[device=" + mDevice + "] " + message);
- }
+ Log.d(TAG, "[" + mDevice + "] " + message);
}
public void warn(String message) {
- Log.w(TAG, "[device=" + mDevice + "] " + message);
+ Log.w(TAG, "[" + mDevice + "] " + message);
}
public void error(String message) {
- Log.e(TAG, "[device=" + mDevice + "] " + message);
+ Log.e(TAG, "[" + 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 a152a61..d51acc1 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
@@ -37,8 +37,7 @@
* corresponding CPP file.
*/
public class NativeInterface {
- private static final String TAG = "NativeInterface";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = NativeInterface.class.getSimpleName();
private AdapterService mAdapterService;
@@ -359,9 +358,7 @@
event.device = getDevice(address);
// BluetoothAdapter.getDefaultAdapter().getRemoteDevice(Utils.getAddressStringFromByte
// (address));
- if (DBG) {
- Log.d(TAG, "Device addr " + event.device + " State " + state);
- }
+ Log.d(TAG, "Device addr " + event.device + " State " + state);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -375,9 +372,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_AUDIO_STATE_CHANGED);
event.valueInt = state;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onAudioStateChanged: event " + event);
- }
+ Log.d(TAG, "onAudioStateChanged: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -392,9 +387,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_VR_STATE_CHANGED);
event.valueInt = state;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onVrStateChanged: event " + event);
- }
+ Log.d(TAG, "onVrStateChanged: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
@@ -410,9 +403,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_NETWORK_STATE);
event.valueInt = state;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onNetworkStateChanged: event " + event);
- }
+ Log.d(TAG, "onNetworkStateChanged: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
@@ -429,9 +420,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_ROAMING_STATE);
event.valueInt = state;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onNetworkRoaming: incoming: " + event);
- }
+ Log.d(TAG, "onNetworkRoaming: incoming: " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -446,9 +435,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_NETWORK_SIGNAL);
event.valueInt = signal;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onNetworkSignal: event " + event);
- }
+ Log.d(TAG, "onNetworkSignal: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -462,9 +449,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_BATTERY_LEVEL);
event.valueInt = level;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onBatteryLevel: event " + event);
- }
+ Log.d(TAG, "onBatteryLevel: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -478,9 +463,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_OPERATOR_NAME);
event.valueString = name;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCurrentOperator: event " + event);
- }
+ Log.d(TAG, "onCurrentOperator: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -495,9 +478,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CALL);
event.valueInt = call;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCall: event " + event);
- }
+ Log.d(TAG, "onCall: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -520,10 +501,8 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CALLSETUP);
event.valueInt = callsetup;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCallSetup: device" + event.device);
- Log.d(TAG, "onCallSetup: event " + event);
- }
+ Log.d(TAG, "onCallSetup: device" + event.device);
+ Log.d(TAG, "onCallSetup: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -546,9 +525,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CALLHELD);
event.valueInt = callheld;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCallHeld: event " + event);
- }
+ Log.d(TAG, "onCallHeld: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -562,9 +539,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_RESP_AND_HOLD);
event.valueInt = respAndHold;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onRespAndHold: event " + event);
- }
+ Log.d(TAG, "onRespAndHold: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -578,9 +553,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CLIP);
event.valueString = number;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onClip: event " + event);
- }
+ Log.d(TAG, "onClip: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -594,9 +567,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_CALL_WAITING);
event.valueString = number;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCallWaiting: event " + event);
- }
+ Log.d(TAG, "onCallWaiting: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -615,9 +586,7 @@
event.valueInt4 = mparty;
event.valueString = number;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCurrentCalls: event " + event);
- }
+ Log.d(TAG, "onCurrentCalls: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -632,9 +601,7 @@
event.valueInt = type;
event.valueInt2 = volume;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onVolumeChange: event " + event);
- }
+ Log.d(TAG, "onVolumeChange: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -649,9 +616,7 @@
event.valueInt = type;
event.valueInt2 = cme;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onCmdResult: event " + event);
- }
+ Log.d(TAG, "onCmdResult: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -666,9 +631,7 @@
event.valueInt = type;
event.valueString = number;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onSubscriberInfo: event " + event);
- }
+ Log.d(TAG, "onSubscriberInfo: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -683,9 +646,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_IN_BAND_RINGTONE);
event.valueInt = inBand;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onInBandRing: event " + event);
- }
+ Log.d(TAG, "onInBandRing: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -704,9 +665,7 @@
void onRingIndication(byte[] address) {
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_RING_INDICATION);
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onRingIndication: event " + event);
- }
+ Log.d(TAG, "onRingIndication: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
@@ -721,9 +680,7 @@
StackEvent event = new StackEvent(StackEvent.EVENT_TYPE_UNKNOWN_EVENT);
event.device = getDevice(address);
event.valueString = eventString;
- if (DBG) {
- Log.d(TAG, "onUnknownEvent: event " + event);
- }
+ Log.d(TAG, "onUnknownEvent: event " + event);
HeadsetClientService service = HeadsetClientService.getHeadsetClientService();
if (service != null) {
service.messageFromNative(event);
diff --git a/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java b/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java
index f1a39d2..92f76e0 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java
@@ -36,8 +36,7 @@
class VendorCommandResponseProcessor {
- private static final String TAG = "VendorCommandResponseProcessor";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = VendorCommandResponseProcessor.class.getSimpleName();
private final HeadsetClientService mService;
private final NativeInterface mNativeInterface;
@@ -123,7 +122,7 @@
Log.e(TAG, "Failed to send vendor specific at command");
return false;
}
- logD("Send vendor command: " + atCommand);
+ Log.d(TAG, "Send vendor command: " + atCommand);
return true;
}
@@ -168,7 +167,7 @@
return false;
} else {
broadcastVendorSpecificEventIntent(vendorId, eventCode, atString, device);
- logD("process vendor event " + vendorId + ", " + eventCode + ", "
+ Log.d(TAG, "process vendor event " + vendorId + ", " + eventCode + ", "
+ atString + " for device" + device);
}
return true;
@@ -176,7 +175,7 @@
private void broadcastVendorSpecificEventIntent(int vendorId, String vendorEventCode,
String vendorResponse, BluetoothDevice device) {
- logD("broadcastVendorSpecificEventIntent(" + vendorResponse + ")");
+ Log.d(TAG, "broadcastVendorSpecificEventIntent(" + vendorResponse + ")");
Intent intent = new Intent(BluetoothHeadsetClient
.ACTION_VENDOR_SPECIFIC_HEADSETCLIENT_EVENT);
intent.putExtra(BluetoothHeadsetClient.EXTRA_VENDOR_ID, vendorId);
@@ -186,10 +185,4 @@
Utils.sendBroadcast(mService, intent, BLUETOOTH_CONNECT,
Utils.getTempAllowlistBroadcastOptions());
}
-
- private void logD(String msg) {
- if (DBG) {
- Log.d(TAG, msg);
- }
- }
}
diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
index 1c6742b..b81a8c4 100644
--- a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
+++ b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
@@ -57,7 +57,6 @@
import java.util.Objects;
public class HidDeviceService extends ProfileService {
- private static final boolean DBG = false;
private static final String TAG = HidDeviceService.class.getSimpleName();
private static final int MESSAGE_APPLICATION_STATE_CHANGED = 1;
@@ -102,9 +101,7 @@
@Override
public void handleMessage(Message msg) {
- if (DBG) {
- Log.d(TAG, "handleMessage(): msg.what=" + msg.what);
- }
+ Log.d(TAG, "handleMessage(): msg.what=" + msg.what);
switch (msg.what) {
case MESSAGE_APPLICATION_STATE_CHANGED: {
@@ -332,7 +329,7 @@
BluetoothHidDeviceAppQosSettings inQos, BluetoothHidDeviceAppQosSettings outQos,
IBluetoothHidDeviceCallback callback, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (DBG) Log.d(TAG, "registerApp()");
+ Log.d(TAG, "registerApp()");
try {
HidDeviceService service = getService(source);
boolean defaultValue = false;
@@ -348,7 +345,7 @@
@Override
public void unregisterApp(AttributionSource source, SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "unregisterApp()");
+ Log.d(TAG, "unregisterApp()");
boolean defaultValue = false;
HidDeviceService service = getService(source);
@@ -366,7 +363,7 @@
public void sendReport(BluetoothDevice device, int id, byte[] data,
AttributionSource source, SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "sendReport(): device=" + device + " id=" + id);
+ Log.d(TAG, "sendReport(): device=" + device + " id=" + id);
boolean defaultValue = false ;
HidDeviceService service = getService(source);
@@ -384,7 +381,7 @@
public void replyReport(BluetoothDevice device, byte type, byte id, byte[] data,
AttributionSource source, SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "replyReport(): device=" + device
+ Log.d(TAG, "replyReport(): device=" + device
+ " type=" + type + " id=" + id);
boolean defaultValue = false;
HidDeviceService service = getService(source);
@@ -401,7 +398,7 @@
public void unplug(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "unplug(): device=" + device);
+ Log.d(TAG, "unplug(): device=" + device);
boolean defaultValue = false;
HidDeviceService service = getService(source);
if (service != null) {
@@ -417,7 +414,7 @@
public void connect(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "connect(): device=" + device);
+ Log.d(TAG, "connect(): device=" + device);
HidDeviceService service = getService(source);
boolean defaultValue = false;
if (service != null) {
@@ -434,7 +431,7 @@
public void disconnect(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "disconnect(): device=" + device);
+ Log.d(TAG, "disconnect(): device=" + device);
HidDeviceService service = getService(source);
boolean defaultValue = false;
if (service != null) {
@@ -451,10 +448,8 @@
public void setConnectionPolicy(BluetoothDevice device, int connectionPolicy,
AttributionSource source, SynchronousResultReceiver receiver) {
try {
- if (DBG) {
- Log.d(TAG, "setConnectionPolicy(): device=" + device + " connectionPolicy="
- + connectionPolicy);
- }
+ Log.d(TAG, "setConnectionPolicy(): device=" + device + " connectionPolicy="
+ + connectionPolicy);
HidDeviceService service = getService(source);
boolean defaultValue = false;
if (service != null) {
@@ -471,7 +466,7 @@
public void reportError(BluetoothDevice device, byte error, AttributionSource source,
SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "reportError(): device=" + device + " error=" + error);
+ Log.d(TAG, "reportError(): device=" + device + " error=" + error);
HidDeviceService service = getService(source);
boolean defaultValue = false;
@@ -488,7 +483,7 @@
public void getConnectionState(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
try {
- if (DBG) Log.d(TAG, "getConnectionState(): device=" + device);
+ Log.d(TAG, "getConnectionState(): device=" + device);
HidDeviceService service = getService(source);
int defaultValue = BluetoothHidDevice.STATE_DISCONNECTED;
@@ -504,7 +499,7 @@
@Override
public void getConnectedDevices(AttributionSource source,
SynchronousResultReceiver receiver) {
- if (DBG) Log.d(TAG, "getConnectedDevices()");
+ Log.d(TAG, "getConnectedDevices()");
getDevicesMatchingConnectionStates(new int[] { BluetoothProfile.STATE_CONNECTED },
source, receiver);
@@ -514,10 +509,8 @@
public void getDevicesMatchingConnectionStates(int[] states,
AttributionSource source, SynchronousResultReceiver receiver) {
try {
- if (DBG) {
- Log.d(TAG, "getDevicesMatchingConnectionStates(): states="
- + Arrays.toString(states));
- }
+ Log.d(TAG, "getDevicesMatchingConnectionStates(): states="
+ + Arrays.toString(states));
HidDeviceService service = getService(source);
List<BluetoothDevice> defaultValue = new ArrayList<BluetoothDevice>(0);
if (service != null) {
@@ -575,9 +568,7 @@
}
int callingUid = Binder.getCallingUid();
- if (DBG) {
- Log.d(TAG, "registerApp(): calling uid=" + callingUid);
- }
+ Log.d(TAG, "registerApp(): calling uid=" + callingUid);
if (callingUid >= Process.FIRST_APPLICATION_UID
&& mActivityManager.getUidImportance(callingUid) > FOREGROUND_IMPORTANCE_CUTOFF) {
Log.w(TAG, "registerApp(): failed because the app is not foreground");
@@ -615,51 +606,39 @@
}
synchronized boolean unregisterApp() {
- if (DBG) {
- Log.d(TAG, "unregisterApp()");
- }
+ Log.d(TAG, "unregisterApp()");
int callingUid = Binder.getCallingUid();
return unregisterAppUid(callingUid);
}
private synchronized boolean unregisterAppUid(int uid) {
- if (DBG) {
- Log.d(TAG, "unregisterAppUid(): uid=" + uid);
- }
+ Log.d(TAG, "unregisterAppUid(): uid=" + uid);
if (mUserUid != 0 && (uid == mUserUid || uid < Process.FIRST_APPLICATION_UID)) {
mUserUid = 0;
return mHidDeviceNativeInterface.unregisterApp();
}
- if (DBG) {
- Log.d(TAG, "unregisterAppUid(): caller UID doesn't match user UID");
- }
+ Log.d(TAG, "unregisterAppUid(): caller UID doesn't match user UID");
return false;
}
synchronized boolean sendReport(BluetoothDevice device, int id, byte[] data) {
- if (DBG) {
- Log.d(TAG, "sendReport(): device=" + device + " id=" + id);
- }
+ Log.d(TAG, "sendReport(): device=" + device + " id=" + id);
return checkDevice(device) && checkCallingUid()
&& mHidDeviceNativeInterface.sendReport(id, data);
}
synchronized boolean replyReport(BluetoothDevice device, byte type, byte id, byte[] data) {
- if (DBG) {
- Log.d(TAG, "replyReport(): device=" + device + " type=" + type + " id=" + id);
- }
+ Log.d(TAG, "replyReport(): device=" + device + " type=" + type + " id=" + id);
return checkDevice(device) && checkCallingUid()
&& mHidDeviceNativeInterface.replyReport(type, id, data);
}
synchronized boolean unplug(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "unplug(): device=" + device);
- }
+ Log.d(TAG, "unplug(): device=" + device);
return checkDevice(device) && checkCallingUid()
&& mHidDeviceNativeInterface.unplug();
@@ -672,9 +651,7 @@
* @return true if the connection is successful, false otherwise
*/
public synchronized boolean connect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "connect(): device=" + device);
- }
+ Log.d(TAG, "connect(): device=" + device);
return checkCallingUid() && mHidDeviceNativeInterface.connect(device);
}
@@ -686,9 +663,7 @@
* @return true if the disconnection is successful, false otherwise
*/
public synchronized boolean disconnect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "disconnect(): device=" + device);
- }
+ Log.d(TAG, "disconnect(): device=" + device);
int callingUid = Binder.getCallingUid();
if (callingUid != mUserUid && callingUid >= Process.FIRST_APPLICATION_UID) {
@@ -717,9 +692,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.HID_DEVICE,
connectionPolicy)) {
@@ -754,9 +727,7 @@
}
synchronized boolean reportError(BluetoothDevice device, byte error) {
- if (DBG) {
- Log.d(TAG, "reportError(): device=" + device + " error=" + error);
- }
+ Log.d(TAG, "reportError(): device=" + device + " error=" + error);
return checkDevice(device) && checkCallingUid()
&& mHidDeviceNativeInterface.reportError(error);
@@ -772,9 +743,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
mDatabaseManager = Objects.requireNonNull(AdapterService.getAdapterService().getDatabase(),
"DatabaseManager cannot be null when HidDeviceService starts");
@@ -791,9 +760,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sHidDeviceService == null) {
Log.w(TAG, "stop() called before start()");
@@ -826,9 +793,7 @@
@VisibleForTesting
static synchronized void setHidDeviceService(HidDeviceService instance) {
- if (DBG) {
- Log.d(TAG, "setHidDeviceService(): set to: " + instance);
- }
+ Log.d(TAG, "setHidDeviceService(): set to: " + instance);
sHidDeviceService = instance;
}
@@ -863,9 +828,7 @@
synchronized void onApplicationStateChangedFromNative(BluetoothDevice device,
boolean registered) {
- if (DBG) {
- Log.d(TAG, "onApplicationStateChanged(): registered=" + registered);
- }
+ Log.d(TAG, "onApplicationStateChanged(): registered=" + registered);
Message msg = mHandler.obtainMessage(MESSAGE_APPLICATION_STATE_CHANGED);
msg.obj = device;
@@ -874,10 +837,8 @@
}
synchronized void onConnectStateChangedFromNative(BluetoothDevice device, int state) {
- if (DBG) {
- Log.d(TAG, "onConnectStateChanged(): device="
- + device + " state=" + state);
- }
+ Log.d(TAG, "onConnectStateChanged(): device="
+ + device + " state=" + state);
Message msg = mHandler.obtainMessage(MESSAGE_CONNECT_STATE_CHANGED);
msg.obj = device;
@@ -886,9 +847,7 @@
}
synchronized void onGetReportFromNative(byte type, byte id, short bufferSize) {
- if (DBG) {
- Log.d(TAG, "onGetReport(): type=" + type + " id=" + id + " bufferSize=" + bufferSize);
- }
+ Log.d(TAG, "onGetReport(): type=" + type + " id=" + id + " bufferSize=" + bufferSize);
Message msg = mHandler.obtainMessage(MESSAGE_GET_REPORT);
msg.obj = bufferSize > 0 ? Integer.valueOf(bufferSize) : null;
@@ -898,9 +857,7 @@
}
synchronized void onSetReportFromNative(byte reportType, byte reportId, byte[] data) {
- if (DBG) {
- Log.d(TAG, "onSetReport(): reportType=" + reportType + " reportId=" + reportId);
- }
+ Log.d(TAG, "onSetReport(): reportType=" + reportType + " reportId=" + reportId);
ByteBuffer bb = ByteBuffer.wrap(data);
@@ -912,9 +869,7 @@
}
synchronized void onSetProtocolFromNative(byte protocol) {
- if (DBG) {
- Log.d(TAG, "onSetProtocol(): protocol=" + protocol);
- }
+ Log.d(TAG, "onSetProtocol(): protocol=" + protocol);
Message msg = mHandler.obtainMessage(MESSAGE_SET_PROTOCOL);
msg.arg1 = protocol;
@@ -922,9 +877,7 @@
}
synchronized void onInterruptDataFromNative(byte reportId, byte[] data) {
- if (DBG) {
- Log.d(TAG, "onInterruptData(): reportId=" + reportId);
- }
+ Log.d(TAG, "onInterruptData(): reportId=" + reportId);
ByteBuffer bb = ByteBuffer.wrap(data);
@@ -935,19 +888,15 @@
}
synchronized void onVirtualCableUnplugFromNative() {
- if (DBG) {
- Log.d(TAG, "onVirtualCableUnplug()");
- }
+ Log.d(TAG, "onVirtualCableUnplug()");
Message msg = mHandler.obtainMessage(MESSAGE_VC_UNPLUG);
mHandler.sendMessage(msg);
}
private void setAndBroadcastConnectionState(BluetoothDevice device, int newState) {
- if (DBG) {
- Log.d(TAG, "setAndBroadcastConnectionState(): device=" + device
- + " oldState=" + mHidDeviceState + " newState=" + newState);
- }
+ Log.d(TAG, "setAndBroadcastConnectionState(): device=" + device
+ + " oldState=" + mHidDeviceState + " newState=" + newState);
if (mHidDevice != null && !mHidDevice.equals(device)) {
Log.w(TAG, "Connection state changed for unknown device, ignoring");
diff --git a/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java b/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java
index d537dc8..39a2d39 100644
--- a/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java
@@ -24,7 +24,6 @@
/** Provides Bluetooth Hid Host profile, as a service in the Bluetooth application. */
public class HidHostNativeInterface {
private static final String TAG = HidHostNativeInterface.class.getSimpleName();
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
private HidHostService mHidHostService;
@@ -130,34 +129,34 @@
/**********************************************************************************************/
private void onConnectStateChanged(byte[] address, int addressType, int transport, int state) {
- if (DBG) Log.d(TAG, "onConnectStateChanged: state=" + state);
+ Log.d(TAG, "onConnectStateChanged: state=" + state);
mHidHostService.onConnectStateChanged(
address, addressType, transport, convertHalState(state));
}
private void onGetProtocolMode(byte[] address, int addressType, int transport, int mode) {
- if (DBG) Log.d(TAG, "onGetProtocolMode()");
+ Log.d(TAG, "onGetProtocolMode()");
mHidHostService.onGetProtocolMode(address, addressType, transport, mode);
}
private void onGetReport(
byte[] address, int addressType, int transport, byte[] report, int rptSize) {
- if (DBG) Log.d(TAG, "onGetReport()");
+ Log.d(TAG, "onGetReport()");
mHidHostService.onGetReport(address, addressType, transport, report, rptSize);
}
private void onHandshake(byte[] address, int addressType, int transport, int status) {
- if (DBG) Log.d(TAG, "onHandshake: status=" + status);
+ Log.d(TAG, "onHandshake: status=" + status);
mHidHostService.onHandshake(address, addressType, transport, status);
}
private void onVirtualUnplug(byte[] address, int addressType, int transport, int status) {
- if (DBG) Log.d(TAG, "onVirtualUnplug: status=" + status);
+ Log.d(TAG, "onVirtualUnplug: status=" + status);
mHidHostService.onVirtualUnplug(address, addressType, transport, status);
}
private void onGetIdleTime(byte[] address, int addressType, int transport, int idleTime) {
- if (DBG) Log.d(TAG, "onGetIdleTime()");
+ Log.d(TAG, "onGetIdleTime()");
mHidHostService.onGetIdleTime(address, addressType, transport, idleTime);
}
diff --git a/android/app/src/com/android/bluetooth/hid/HidHostService.java b/android/app/src/com/android/bluetooth/hid/HidHostService.java
index c32d8fb..f94e173 100644
--- a/android/app/src/com/android/bluetooth/hid/HidHostService.java
+++ b/android/app/src/com/android/bluetooth/hid/HidHostService.java
@@ -63,7 +63,6 @@
* the Bluetooth application.
*/
public class HidHostService extends ProfileService {
- private static final boolean DBG = false;
private static final String TAG = "BluetoothHidHostService";
private static class InputDevice {
@@ -167,14 +166,12 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "Stopping Bluetooth HidHostService");
- }
+ Log.d(TAG, "Stopping Bluetooth HidHostService");
}
@Override
public void cleanup() {
- if (DBG) Log.d(TAG, "Stopping Bluetooth HidHostService");
+ Log.d(TAG, "Stopping Bluetooth HidHostService");
if (mNativeAvailable) {
mNativeInterface.cleanup();
mNativeAvailable = false;
@@ -291,9 +288,7 @@
}
private static synchronized void setHidHostService(HidHostService instance) {
- if (DBG) {
- Log.d(TAG, "setHidHostService(): set to: " + instance);
- }
+ Log.d(TAG, "setHidHostService(): set to: " + instance);
sHidHostService = instance;
}
@@ -357,7 +352,8 @@
new Handler() {
@Override
public void handleMessage(Message msg) {
- if (DBG) Log.v(TAG, "handleMessage(): msg.what=" + msg.what);
+ Log.v(TAG, "handleMessage(): msg.what=" + msg.what);
+
switch (msg.what) {
case MESSAGE_CONNECT:
handleMessageConnect(msg);
@@ -390,7 +386,7 @@
handleMessageOnHandshake(msg);
break;
case MESSAGE_SET_REPORT:
- handleMessageSetProtocol(msg);
+ handleMessageSetReport(msg);
break;
case MESSAGE_ON_VIRTUAL_UNPLUG:
handleMessageOnVirtualUnplug(msg);
@@ -492,7 +488,7 @@
broadcastVirtualUnplugStatus(device, status);
}
- private void handleMessageSetProtocol(Message msg) {
+ private void handleMessageSetReport(Message msg) {
BluetoothDevice device = (BluetoothDevice) msg.obj;
Bundle data = msg.getData();
byte reportType = data.getByte(BluetoothHidHost.EXTRA_REPORT_TYPE);
@@ -1068,7 +1064,7 @@
* @return true if connection request is passed down to mHandler.
*/
public boolean connect(BluetoothDevice device) {
- if (DBG) Log.d(TAG, "connect: " + device);
+ Log.d(TAG, "connect: " + device);
int state = getConnectionState(device);
if (state != BluetoothProfile.STATE_DISCONNECTED) {
Log.e(TAG, "Hid Device not disconnected: " + device + ", state: " + state);
@@ -1091,9 +1087,7 @@
* @return true
*/
private boolean disconnect(BluetoothDevice device, int connectionPolicy) {
- if (DBG) {
- Log.d(TAG, "disconnect: " + device + ", connection policy: " + connectionPolicy);
- }
+ Log.d(TAG, "disconnect: " + device + ", connection policy: " + connectionPolicy);
Message msg = mHandler.obtainMessage(MESSAGE_DISCONNECT, device);
msg.arg1 = connectionPolicy;
mHandler.sendMessage(msg);
@@ -1121,7 +1115,7 @@
* {@link BluetoothProfile#STATE_DISCONNECTING} if this profile is being disconnected
*/
public int getConnectionState(BluetoothDevice device) {
- if (DBG) Log.d(TAG, "getConnectionState: " + device);
+ Log.d(TAG, "getConnectionState: " + device);
InputDevice inputDevice = mInputDevices.get(device);
if (inputDevice != null) {
return inputDevice.getState();
@@ -1130,8 +1124,7 @@
}
List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
- if (DBG) Log.d(TAG, "getDevicesMatchingConnectionStates()");
-
+ Log.d(TAG, "getDevicesMatchingConnectionStates()");
return mInputDevices.entrySet().stream()
.filter(entry -> Ints.asList(states).contains(entry.getValue().getState()))
.map(Map.Entry::getKey)
@@ -1154,17 +1147,13 @@
* @return true if connectionPolicy is set, false on error
*/
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
- if (DBG) {
- Log.d(TAG, "setConnectionPolicy: " + device);
- }
+ Log.d(TAG, "setConnectionPolicy: " + device);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.HID_HOST,
connectionPolicy)) {
return false;
}
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
connect(device);
} else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
@@ -1177,9 +1166,7 @@
* @see BluetoothHidHost#setPreferredTransport
*/
boolean setPreferredTransport(BluetoothDevice device, int transport) {
- if (DBG) {
- Log.i(TAG, "setPreferredTransport: " + device + " transport: " + transport);
- }
+ Log.i(TAG, "setPreferredTransport: " + device + " transport: " + transport);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.w(TAG, "Device not bonded" + device);
@@ -1215,9 +1202,7 @@
* @return connection policy of the device
*/
public int getConnectionPolicy(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "getConnectionPolicy: " + device);
- }
+ Log.d(TAG, "getConnectionPolicy: " + device);
return mDatabaseManager
.getProfileConnectionPolicy(device, BluetoothProfile.HID_HOST);
}
@@ -1226,9 +1211,7 @@
* @see BluetoothHidHost#getPreferredTransport
*/
int getPreferredTransport(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "getPreferredTransport: " + device);
- }
+ Log.d(TAG, "getPreferredTransport: " + device);
// TODO: Access to mInputDevices should be protected in binder thread
return getTransport(device);
@@ -1236,9 +1219,7 @@
/* The following APIs regarding test app for compliance */
boolean getProtocolMode(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "getProtocolMode: " + device);
- }
+ Log.d(TAG, "getProtocolMode: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1249,9 +1230,7 @@
}
boolean virtualUnplug(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "virtualUnplug: " + device);
- }
+ Log.d(TAG, "virtualUnplug: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1262,9 +1241,7 @@
}
boolean setProtocolMode(BluetoothDevice device, int protocolMode) {
- if (DBG) {
- Log.d(TAG, "setProtocolMode: " + device);
- }
+ Log.d(TAG, "setProtocolMode: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1277,9 +1254,7 @@
}
boolean getReport(BluetoothDevice device, byte reportType, byte reportId, int bufferSize) {
- if (DBG) {
- Log.d(TAG, "getReport: " + device);
- }
+ Log.d(TAG, "getReport: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1296,9 +1271,7 @@
}
boolean setReport(BluetoothDevice device, byte reportType, String report) {
- if (DBG) {
- Log.d(TAG, "setReport: " + device);
- }
+ Log.d(TAG, "setReport: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1314,9 +1287,7 @@
}
boolean sendData(BluetoothDevice device, String report) {
- if (DBG) {
- Log.d(TAG, "sendData: " + device);
- }
+ Log.d(TAG, "sendData: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1330,7 +1301,7 @@
}
boolean getIdleTime(BluetoothDevice device) {
- if (DBG) Log.d(TAG, "getIdleTime: " + device);
+ Log.d(TAG, "getIdleTime: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1341,7 +1312,7 @@
}
boolean setIdleTime(BluetoothDevice device, byte idleTime) {
- if (DBG) Log.d(TAG, "setIdleTime: " + device);
+ Log.d(TAG, "setIdleTime: " + device);
int state = this.getConnectionState(device);
if (state != BluetoothProfile.STATE_CONNECTED) {
return false;
@@ -1356,7 +1327,7 @@
}
void onGetProtocolMode(byte[] address, int addressType, int transport, int mode) {
- if (DBG) Log.d(TAG, "onGetProtocolMode()");
+ Log.d(TAG, "onGetProtocolMode()");
Message msg = mHandler.obtainMessage(MESSAGE_ON_GET_PROTOCOL_MODE);
msg.obj = address;
msg.arg1 = transport;
@@ -1365,7 +1336,7 @@
}
void onGetIdleTime(byte[] address, int addressType, int transport, int idleTime) {
- if (DBG) Log.d(TAG, "onGetIdleTime()");
+ Log.d(TAG, "onGetIdleTime()");
Message msg = mHandler.obtainMessage(MESSAGE_ON_GET_IDLE_TIME);
msg.obj = address;
msg.arg1 = transport;
@@ -1374,7 +1345,7 @@
}
void onGetReport(byte[] address, int addressType, int transport, byte[] report, int rptSize) {
- if (DBG) Log.d(TAG, "onGetReport()");
+ Log.d(TAG, "onGetReport()");
Message msg = mHandler.obtainMessage(MESSAGE_ON_GET_REPORT);
msg.obj = address;
msg.arg1 = transport;
@@ -1386,7 +1357,7 @@
}
void onHandshake(byte[] address, int addressType, int transport, int status) {
- if (DBG) Log.d(TAG, "onHandshake: status=" + status);
+ Log.d(TAG, "onHandshake: status=" + status);
Message msg = mHandler.obtainMessage(MESSAGE_ON_HANDSHAKE);
msg.obj = address;
msg.arg1 = transport;
@@ -1395,7 +1366,7 @@
}
void onVirtualUnplug(byte[] address, int addressType, int transport, int status) {
- if (DBG) Log.d(TAG, "onVirtualUnplug: status=" + status);
+ Log.d(TAG, "onVirtualUnplug: status=" + status);
Message msg = mHandler.obtainMessage(MESSAGE_ON_VIRTUAL_UNPLUG);
msg.obj = address;
msg.arg1 = transport;
@@ -1404,7 +1375,7 @@
}
void onConnectStateChanged(byte[] address, int addressType, int transport, int state) {
- if (DBG) Log.d(TAG, "onConnectStateChanged: state=" + state);
+ Log.d(TAG, "onConnectStateChanged: state=" + state);
Message msg = mHandler.obtainMessage(MESSAGE_CONNECT_STATE_CHANGED, address);
msg.arg1 = transport;
msg.arg2 = state;
@@ -1534,9 +1505,7 @@
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Utils.sendBroadcast(this, intent, BLUETOOTH_CONNECT,
Utils.getTempAllowlistBroadcastOptions());
- if (DBG) {
- Log.d(TAG, "Protocol Mode (" + device + "): " + protocolMode);
- }
+ Log.d(TAG, "Protocol Mode (" + device + "): " + protocolMode);
}
private void broadcastReport(BluetoothDevice device, byte[] report, int rptSize) {
@@ -1565,9 +1534,7 @@
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Utils.sendBroadcast(this, intent, BLUETOOTH_CONNECT,
Utils.getTempAllowlistBroadcastOptions());
- if (DBG) {
- Log.d(TAG, "Idle time (" + device + "): " + idleTime);
- }
+ Log.d(TAG, "Idle time (" + device + "): " + idleTime);
}
/**
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java
index a76920a..aa05e88 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java
@@ -36,7 +36,6 @@
*/
public class LeAudioBroadcasterNativeInterface {
private static final String TAG = "LeAudioBroadcasterNativeInterface";
- private static final boolean DBG = true;
private BluetoothAdapter mAdapter;
@GuardedBy("INSTANCE_LOCK")
@@ -88,9 +87,7 @@
// Callbacks from the native stack back into the Java framework.
@VisibleForTesting
public void onBroadcastCreated(int broadcastId, boolean success) {
- if (DBG) {
- Log.d(TAG, "onBroadcastCreated: broadcastId=" + broadcastId);
- }
+ Log.d(TAG, "onBroadcastCreated: broadcastId=" + broadcastId);
LeAudioStackEvent event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_CREATED);
@@ -101,9 +98,7 @@
@VisibleForTesting
public void onBroadcastDestroyed(int broadcastId) {
- if (DBG) {
- Log.d(TAG, "onBroadcastDestroyed: broadcastId=" + broadcastId);
- }
+ Log.d(TAG, "onBroadcastDestroyed: broadcastId=" + broadcastId);
LeAudioStackEvent event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_DESTROYED);
@@ -113,9 +108,7 @@
@VisibleForTesting
public void onBroadcastStateChanged(int broadcastId, int state) {
- if (DBG) {
- Log.d(TAG, "onBroadcastStateChanged: broadcastId=" + broadcastId + " state=" + state);
- }
+ Log.d(TAG, "onBroadcastStateChanged: broadcastId=" + broadcastId + " state=" + state);
LeAudioStackEvent event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE);
@@ -133,9 +126,7 @@
@VisibleForTesting
public void onBroadcastMetadataChanged(int broadcastId, BluetoothLeBroadcastMetadata metadata) {
- if (DBG) {
- Log.d(TAG, "onBroadcastMetadataChanged: broadcastId=" + broadcastId);
- }
+ Log.d(TAG, "onBroadcastMetadataChanged: broadcastId=" + broadcastId);
LeAudioStackEvent event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_METADATA_CHANGED);
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java
index f640136..de8a3d6 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java
@@ -25,7 +25,6 @@
* LeAudio Codec Configuration setup.
*/
class LeAudioCodecConfig {
- private static final boolean DBG = true;
private static final String TAG = "LeAudioCodecConfig";
private Context mContext;
@@ -45,13 +44,11 @@
mCodecConfigOffloading = audioManager.getHwOffloadFormatsSupportedForLeAudio()
.toArray(mCodecConfigOffloading);
- if (DBG) {
- Log.i(TAG, "mCodecConfigOffloading size for le -> " + mCodecConfigOffloading.length);
+ Log.i(TAG, "mCodecConfigOffloading size for le -> " + mCodecConfigOffloading.length);
- for (int idx = 0; idx < mCodecConfigOffloading.length; idx++) {
- Log.i(TAG, String.format("mCodecConfigOffloading[%d] -> %s",
- idx, mCodecConfigOffloading[idx].toString()));
- }
+ for (int idx = 0; idx < mCodecConfigOffloading.length; idx++) {
+ Log.i(TAG, String.format("mCodecConfigOffloading[%d] -> %s",
+ idx, mCodecConfigOffloading[idx].toString()));
}
}
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 4c0b7dd..cd28b98 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java
@@ -38,7 +38,6 @@
*/
public class LeAudioNativeInterface {
private static final String TAG = LeAudioNativeInterface.class.getSimpleName();
- private static final boolean DBG = true;
private BluetoothAdapter mAdapter;
@@ -101,9 +100,7 @@
LeAudioStackEvent event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED);
- if (DBG) {
- Log.d(TAG, "onInitialized: " + event);
- }
+ Log.d(TAG, "onInitialized: " + event);
sendMessageToService(event);
}
@@ -114,9 +111,7 @@
event.device = getDevice(address);
event.valueInt1 = state;
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -127,9 +122,7 @@
event.valueInt1 = groupId;
event.valueInt2 = groupStatus;
- if (DBG) {
- Log.d(TAG, "onGroupStatus: " + event);
- }
+ Log.d(TAG, "onGroupStatus: " + event);
sendMessageToService(event);
}
@@ -141,9 +134,7 @@
event.valueInt2 = nodeStatus;
event.device = getDevice(address);
- if (DBG) {
- Log.d(TAG, "onGroupNodeStatus: " + event);
- }
+ Log.d(TAG, "onGroupNodeStatus: " + event);
sendMessageToService(event);
}
@@ -158,9 +149,7 @@
event.valueInt4 = sourceAudioLocation;
event.valueInt5 = availableContexts;
- if (DBG) {
- Log.d(TAG, "onAudioConf: " + event);
- }
+ Log.d(TAG, "onAudioConf: " + event);
sendMessageToService(event);
}
@@ -171,9 +160,7 @@
event.device = getDevice(address);
event.valueInt1 = sinkAudioLocation;
- if (DBG) {
- Log.d(TAG, "onSinkAudioLocationAvailable: " + event);
- }
+ Log.d(TAG, "onSinkAudioLocationAvailable: " + event);
sendMessageToService(event);
}
@@ -188,9 +175,7 @@
event.valueCodecList1 = Arrays.asList(localInputCodecCapabilities);
event.valueCodecList2 = Arrays.asList(localOutputCodecCapabilities);
- if (DBG) {
- Log.d(TAG, "onAudioLocalCodecCapabilities: " + event);
- }
+ Log.d(TAG, "onAudioLocalCodecCapabilities: " + event);
sendMessageToService(event);
}
@@ -207,9 +192,7 @@
event.valueCodec1 = inputCodecConfig;
event.valueCodec2 = outputCodecConfig;
- if (DBG) {
- Log.d(TAG, "onAudioGroupCurrentCodecConf: " + event);
- }
+ Log.d(TAG, "onAudioGroupCurrentCodecConf: " + event);
sendMessageToService(event);
}
@@ -226,9 +209,7 @@
event.valueCodecList1 = Arrays.asList(inputSelectableCodecConfig);
event.valueCodecList2 = Arrays.asList(outputSelectableCodecConfig);
- if (DBG) {
- Log.d(TAG, "onAudioGroupSelectableCodecConf: " + event);
- }
+ Log.d(TAG, "onAudioGroupSelectableCodecConf: " + event);
sendMessageToService(event);
}
@@ -239,9 +220,7 @@
event.device = getDevice(address);
event.valueInt1 = action;
- if (DBG) {
- Log.d(TAG, "onHealthBasedRecommendationAction: " + event);
- }
+ Log.d(TAG, "onHealthBasedRecommendationAction: " + event);
sendMessageToService(event);
}
@@ -253,9 +232,7 @@
event.valueInt1 = groupId;
event.valueInt2 = action;
- if (DBG) {
- Log.d(TAG, "onHealthBasedGroupRecommendationAction: " + event);
- }
+ Log.d(TAG, "onHealthBasedGroupRecommendationAction: " + event);
sendMessageToService(event);
}
@@ -266,9 +243,7 @@
event.valueInt1 = direction;
event.valueInt2 = status;
- if (DBG) {
- Log.d(TAG, "onUnicastMonitorModeStatus: " + event);
- }
+ Log.d(TAG, "onUnicastMonitorModeStatus: " + event);
sendMessageToService(event);
}
@@ -279,9 +254,7 @@
event.valueInt1 = groupId;
event.valueInt2 = groupStreamStatus;
- if (DBG) {
- Log.d(TAG, "onGroupStreamStatus: " + event);
- }
+ Log.d(TAG, "onGroupStreamStatus: " + event);
sendMessageToService(event);
}
@@ -376,9 +349,7 @@
* @param contextType assigned contextType
*/
public void setCcidInformation(int ccid, int contextType) {
- if (DBG) {
- Log.d(TAG, "setCcidInformation ccid: " + ccid + " context type: " + contextType);
- }
+ Log.d(TAG, "setCcidInformation ccid: " + ccid + " context type: " + contextType);
setCcidInformationNative(ccid, contextType);
}
@@ -387,9 +358,7 @@
* @param inCall true when device in call (any state), false otherwise
*/
public void setInCall(boolean inCall) {
- if (DBG) {
- Log.d(TAG, "setInCall inCall: " + inCall);
- }
+ Log.d(TAG, "setInCall inCall: " + inCall);
setInCallNative(inCall);
}
@@ -401,9 +370,7 @@
* on direction stream. false otherwise
*/
public void setUnicastMonitorMode(int direction, boolean enable) {
- if (DBG) {
- Log.d(TAG, "setUnicastMonitorMode enable: " + enable + ", direction : " + direction);
- }
+ Log.d(TAG, "setUnicastMonitorMode enable: " + enable + ", direction : " + direction);
setUnicastMonitorModeNative(direction, enable);
}
@@ -416,11 +383,9 @@
*/
public void sendAudioProfilePreferences(int groupId, boolean isOutputPreferenceLeAudio,
boolean isDuplexPreferenceLeAudio) {
- if (DBG) {
- Log.d(TAG, "sendAudioProfilePreferences groupId=" + groupId
- + ", isOutputPreferenceLeAudio=" + isOutputPreferenceLeAudio
- + ", isDuplexPreferenceLeAudio=" + isDuplexPreferenceLeAudio);
- }
+ Log.d(TAG, "sendAudioProfilePreferences groupId=" + groupId
+ + ", isOutputPreferenceLeAudio=" + isOutputPreferenceLeAudio
+ + ", isDuplexPreferenceLeAudio=" + isDuplexPreferenceLeAudio);
sendAudioProfilePreferencesNative(groupId, isOutputPreferenceLeAudio,
isDuplexPreferenceLeAudio);
}
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 26262d7..1919673 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
@@ -109,7 +109,6 @@
* Provides Bluetooth LeAudio profile, as a service in the Bluetooth application.
*/
public class LeAudioService extends ProfileService {
- private static final boolean DBG = true;
private static final String TAG = "LeAudioService";
// Timeout for state machine thread join, to prevent potential ANR.
@@ -573,9 +572,7 @@
@VisibleForTesting
static synchronized void setLeAudioService(LeAudioService instance) {
- if (DBG) {
- Log.d(TAG, "setLeAudioService(): set to: " + instance);
- }
+ Log.d(TAG, "setLeAudioService(): set to: " + instance);
sLeAudioService = instance;
}
@@ -623,9 +620,7 @@
}
private void setEnabledState(BluetoothDevice device, boolean enabled) {
- if (DBG) {
- Log.d(TAG, "setEnabledState: address:" + device + " enabled: " + enabled);
- }
+ Log.d(TAG, "setEnabledState: address:" + device + " enabled: " + enabled);
if (!mLeAudioNativeIsInitialized) {
Log.e(TAG, "setEnabledState, mLeAudioNativeIsInitialized is not initialized");
return;
@@ -634,9 +629,7 @@
}
public boolean connect(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
Log.e(TAG, "Cannot connect to " + device + " : CONNECTION_POLICY_FORBIDDEN");
@@ -690,9 +683,7 @@
* @return true if profile disconnected, false if device not connected over LE Audio
*/
boolean disconnectV2(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "disconnectV2(): " + device);
- }
+ Log.d(TAG, "disconnectV2(): " + device);
LeAudioStateMachine sm = null;
@@ -729,9 +720,7 @@
return disconnectV2(device);
}
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
mGroupReadLock.lock();
try {
@@ -1101,7 +1090,8 @@
Log.w(TAG, "Native interface not available.");
return;
}
- if (DBG) Log.d(TAG, "startBroadcast");
+
+ Log.d(TAG, "startBroadcast");
/* Start timeout to recover from stucked/error start Broadcast operation */
mDialingOutTimeoutEvent = new DialingOutTimeoutEvent(broadcastId);
@@ -1140,7 +1130,7 @@
BluetoothLeAudioContentMetadata publicMetadata =
broadcastSettings.getPublicBroadcastMetadata();
- if (DBG) Log.d(TAG, "updateBroadcast");
+ Log.d(TAG, "updateBroadcast");
mLeAudioBroadcasterNativeInterface.updateMetadata(broadcastId,
broadcastSettings.getBroadcastName(),
publicMetadata == null ? null : publicMetadata.getRawMetadata(),
@@ -1166,7 +1156,7 @@
return;
}
- if (DBG) Log.d(TAG, "pauseBroadcast");
+ Log.d(TAG, "pauseBroadcast");
mLeAudioBroadcasterNativeInterface.pauseBroadcast(broadcastId);
}
@@ -1188,7 +1178,7 @@
return;
}
- if (DBG) Log.d(TAG, "stopBroadcast");
+ Log.d(TAG, "stopBroadcast");
mLeAudioBroadcasterNativeInterface.stopBroadcast(broadcastId);
}
@@ -1210,7 +1200,7 @@
return;
}
- if (DBG) Log.d(TAG, "destroyBroadcast");
+ Log.d(TAG, "destroyBroadcast");
if (Flags.leaudioBroadcastAudioHandoverPolicies()) {
mLeAudioNativeInterface.setUnicastMonitorMode(LeAudioStackEvent.DIRECTION_SINK, false);
}
@@ -1441,11 +1431,9 @@
if (!Objects.equals(device, previousInDevice)
|| (oldSupportedByDeviceInput != newSupportedByDeviceInput)) {
mActiveAudioInDevice = newSupportedByDeviceInput ? device : null;
- if (DBG) {
- Log.d(TAG, " handleBluetoothActiveDeviceChanged previousInDevice: "
- + previousInDevice + ", mActiveAudioInDevice: " + mActiveAudioInDevice
- + " isLeOutput: false");
- }
+ Log.d(TAG, " handleBluetoothActiveDeviceChanged previousInDevice: "
+ + previousInDevice + ", mActiveAudioInDevice: " + mActiveAudioInDevice
+ + " isLeOutput: false");
return true;
}
@@ -1505,11 +1493,9 @@
if (!Objects.equals(device, previousOutDevice)
|| (oldSupportedByDeviceOutput != newSupportedByDeviceOutput)) {
mActiveAudioOutDevice = newSupportedByDeviceOutput ? device : null;
- if (DBG) {
- Log.d(TAG, " handleBluetoothActiveDeviceChanged previousOutDevice: "
- + previousOutDevice + ", mActiveAudioOutDevice: " + mActiveAudioOutDevice
- + " isLeOutput: true");
- }
+ Log.d(TAG, " handleBluetoothActiveDeviceChanged previousOutDevice: "
+ + previousOutDevice + ", mActiveAudioOutDevice: " + mActiveAudioOutDevice
+ + " isLeOutput: true");
return true;
}
Log.d(TAG, "updateActiveOutDevice: Nothing to do.");
@@ -1521,17 +1507,15 @@
* LeAudioStateMachine.
*/
void notifyConnectionStateChanged(BluetoothDevice device, int newState, int prevState) {
- if (DBG) {
- Log.d(
- TAG,
- "Notify connection state changed."
- + device
- + "("
- + prevState
- + " -> "
- + newState
- + ")");
- }
+ Log.d(
+ TAG,
+ "Notify connection state changed."
+ + device
+ + "("
+ + prevState
+ + " -> "
+ + newState
+ + ")");
mAdapterService.notifyProfileConnectionStateChangeToGatt(
BluetoothProfile.LE_AUDIO, prevState, newState);
@@ -1586,10 +1570,8 @@
*/
@VisibleForTesting
void notifyActiveDeviceChanged(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "Notify Active device changed." + device
- + ". Currently active device is " + mActiveAudioOutDevice);
- }
+ Log.d(TAG, "Notify Active device changed." + device
+ + ". Currently active device is " + mActiveAudioOutDevice);
mAdapterService.handleActiveDeviceChange(BluetoothProfile.LE_AUDIO, device);
sentActiveDeviceChangeIntent(device);
@@ -1599,9 +1581,7 @@
boolean isScannerNeeded() {
if (mDeviceDescriptors.isEmpty() || !mBluetoothEnabled) {
- if (DBG) {
- Log.d(TAG, "isScannerNeeded: false, mBluetoothEnabled: " + mBluetoothEnabled);
- }
+ Log.d(TAG, "isScannerNeeded: false, mBluetoothEnabled: " + mBluetoothEnabled);
return false;
}
@@ -1610,9 +1590,7 @@
return false;
}
- if (DBG) {
- Log.d(TAG, "isScannerNeeded: true");
- }
+ Log.d(TAG, "isScannerNeeded: true");
return true;
}
@@ -1700,17 +1678,13 @@
byte[] addressBytes = Utils.getBytesFromAddress(address);
BluetoothDevice device = mAdapterService.getDeviceFromByte(addressBytes);
- if (DBG) {
- Log.d(TAG, " onAudioDevicesAdded: " + device + ", device type: "
- + deviceInfo.getType() + ", isSink: " + deviceInfo.isSink()
- + " isSource: " + deviceInfo.isSource());
- }
+ Log.d(TAG, " onAudioDevicesAdded: " + device + ", device type: "
+ + deviceInfo.getType() + ", isSink: " + deviceInfo.isSink()
+ + " isSource: " + deviceInfo.isSource());
/* Don't expose already exposed active device */
if (device.equals(mExposedActiveDevice)) {
- if (DBG) {
- Log.d(TAG, " onAudioDevicesAdded: " + device + " is already exposed");
- }
+ Log.d(TAG, " onAudioDevicesAdded: " + device + " is already exposed");
return;
}
@@ -1749,13 +1723,11 @@
byte[] addressBytes = Utils.getBytesFromAddress(address);
BluetoothDevice device = mAdapterService.getDeviceFromByte(addressBytes);
- if (DBG) {
- Log.d(TAG, " onAudioDevicesRemoved: " + address + ", device type: "
- + deviceInfo.getType() + ", isSink: " + deviceInfo.isSink()
- + " isSource: " + deviceInfo.isSource()
- + ", mActiveAudioInDevice: " + mActiveAudioInDevice
- + ", mActiveAudioOutDevice: " + mActiveAudioOutDevice);
- }
+ Log.d(TAG, " onAudioDevicesRemoved: " + address + ", device type: "
+ + deviceInfo.getType() + ", isSink: " + deviceInfo.isSink()
+ + " isSource: " + deviceInfo.isSource()
+ + ", mActiveAudioInDevice: " + mActiveAudioInDevice
+ + ", mActiveAudioOutDevice: " + mActiveAudioOutDevice);
if (device != mExposedActiveDevice) {
continue;
@@ -1779,14 +1751,12 @@
BluetoothDevice previousDevice,
boolean suppressNoisyIntent) {
mActiveBroadcastAudioDevice = newDevice;
- if (DBG) {
- Log.d(
- TAG,
- "updateBroadcastActiveDevice: newDevice: "
- + newDevice
- + ", previousDevice: "
- + previousDevice);
- }
+ Log.d(
+ TAG,
+ "updateBroadcastActiveDevice: newDevice: "
+ + newDevice
+ + ", previousDevice: "
+ + previousDevice);
mAudioManager.handleBluetoothActiveDeviceChanged(
newDevice, previousDevice, getBroadcastProfile(suppressNoisyIntent));
}
@@ -1846,12 +1816,10 @@
boolean isNewActiveInDevice = updateActiveInDevice(newInDevice, groupId,
oldSupportedAudioDirections, newSupportedAudioDirections);
- if (DBG) {
- Log.d(TAG, " isNewActiveOutDevice: " + isNewActiveOutDevice + ", "
- + mActiveAudioOutDevice + ", isNewActiveInDevice: " + isNewActiveInDevice
- + ", " + mActiveAudioInDevice + ", notifyAndUpdateInactiveOutDeviceOnly: "
- + notifyAndUpdateInactiveOutDeviceOnly);
- }
+ Log.d(TAG, " isNewActiveOutDevice: " + isNewActiveOutDevice + ", "
+ + mActiveAudioOutDevice + ", isNewActiveInDevice: " + isNewActiveInDevice
+ + ", " + mActiveAudioInDevice + ", notifyAndUpdateInactiveOutDeviceOnly: "
+ + notifyAndUpdateInactiveOutDeviceOnly);
if (isNewActiveOutDevice) {
int volume = IBluetoothVolumeControl.VOLUME_CONTROL_UNKNOWN_VOLUME;
@@ -1906,9 +1874,7 @@
mGroupDescriptorsView.entrySet()) {
LeAudioGroupDescriptor groupDescriptor = groupEntry.getValue();
if (groupDescriptor.mInactivatedDueToContextType) {
- if (DBG) {
- Log.d(TAG, "clearInactiveDueToContextTypeFlags " + groupEntry.getKey());
- }
+ Log.d(TAG, "clearInactiveDueToContextTypeFlags " + groupEntry.getKey());
groupDescriptor.mInactivatedDueToContextType = false;
}
}
@@ -1938,20 +1904,18 @@
}
int currentlyActiveGroupId = getActiveGroupId();
- if (DBG) {
- Log.d(
- TAG,
- "setActiveGroupWithDevice = "
- + groupId
- + ", currentlyActiveGroupId = "
- + currentlyActiveGroupId
- + ", device: "
- + device
- + ", hasFallbackDevice: "
- + hasFallbackDevice
- + ", mExposedActiveDevice: "
- + mExposedActiveDevice);
- }
+ Log.d(
+ TAG,
+ "setActiveGroupWithDevice = "
+ + groupId
+ + ", currentlyActiveGroupId = "
+ + currentlyActiveGroupId
+ + ", device: "
+ + device
+ + ", hasFallbackDevice: "
+ + hasFallbackDevice
+ + ", mExposedActiveDevice: "
+ + mExposedActiveDevice);
if (isBroadcastActive()
&& currentlyActiveGroupId == LE_AUDIO_GROUP_ID_INVALID
@@ -2011,9 +1975,7 @@
*/
public boolean removeActiveDevice(boolean hasFallbackDevice) {
/* Clear active group */
- if (DBG) {
- Log.d(TAG, "removeActiveDevice, hasFallbackDevice " + hasFallbackDevice);
- }
+ Log.d(TAG, "removeActiveDevice, hasFallbackDevice " + hasFallbackDevice);
setActiveGroupWithDevice(null, hasFallbackDevice);
return true;
}
@@ -2067,9 +2029,7 @@
* @return List of active group members. First element is a Lead device.
*/
public List<BluetoothDevice> getActiveDevices() {
- if (DBG) {
- Log.d(TAG, "getActiveDevices");
- }
+ Log.d(TAG, "getActiveDevices");
ArrayList<BluetoothDevice> activeDevices = new ArrayList<>(2);
activeDevices.add(null);
activeDevices.add(null);
@@ -2108,9 +2068,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "connect() others from group id: " + descriptor.mGroupId);
- }
+ Log.d(TAG, "connect() others from group id: " + descriptor.mGroupId);
Integer setGroupId = descriptor.mGroupId;
@@ -2126,9 +2084,7 @@
continue;
}
- if (DBG) {
- Log.d(TAG, "connect(): " + storedDevice);
- }
+ Log.d(TAG, "connect(): " + storedDevice);
mGroupReadLock.lock();
try {
@@ -2162,9 +2118,7 @@
private void clearLostDevicesWhileStreaming(LeAudioGroupDescriptor descriptor) {
mGroupReadLock.lock();
try {
- if (DBG) {
- Log.d(TAG, "Clearing lost dev: " + descriptor.mLostLeadDeviceWhileStreaming);
- }
+ Log.d(TAG, "Clearing lost dev: " + descriptor.mLostLeadDeviceWhileStreaming);
LeAudioDeviceDescriptor deviceDescriptor =
getDeviceDescriptor(descriptor.mLostLeadDeviceWhileStreaming);
@@ -2190,15 +2144,13 @@
}
private void handleDeviceHealthAction(BluetoothDevice device, int action) {
- if (DBG) {
- Log.d(
- TAG,
- "handleDeviceHealthAction: device: "
- + device
- + " action: "
- + action
- + ", not implemented");
- }
+ Log.d(
+ TAG,
+ "handleDeviceHealthAction: device: "
+ + device
+ + " action: "
+ + action
+ + ", not implemented");
if (action == LeAudioStackEvent.HEALTH_RECOMMENDATION_ACTION_DISABLE) {
MetricsLogger.getInstance()
.count(
@@ -2212,15 +2164,13 @@
}
private void handleGroupHealthAction(int groupId, int action) {
- if (DBG) {
- Log.d(
- TAG,
- "handleGroupHealthAction: groupId: "
- + groupId
- + " action: "
- + action
- + ", not implemented");
- }
+ Log.d(
+ TAG,
+ "handleGroupHealthAction: groupId: "
+ + groupId
+ + " action: "
+ + action
+ + ", not implemented");
BluetoothDevice device = getLeadDeviceForTheGroup(groupId);
switch (action) {
case LeAudioStackEvent.HEALTH_RECOMMENDATION_ACTION_DISABLE:
@@ -2324,7 +2274,7 @@
descriptor.mHasFallbackDeviceWhenGettingInactive,
leaveConnectedInputDevice);
/* Clear lost devices */
- if (DBG) Log.d(TAG, "Clear for group: " + groupId);
+ Log.d(TAG, "Clear for group: " + groupId);
descriptor.mHasFallbackDeviceWhenGettingInactive = false;
clearLostDevicesWhileStreaming(descriptor);
notifyGroupStatusChanged(groupId, LeAudioStackEvent.GROUP_STATUS_INACTIVE);
@@ -2335,9 +2285,7 @@
}
private void handleSinkStreamStatusChange(int status) {
- if (DBG) {
- Log.d(TAG, "status: " + status);
- }
+ Log.d(TAG, "status: " + status);
/* Straming request of Unicast Sink stream should result in pausing broadcast and activating
* Unicast group.
@@ -2403,29 +2351,21 @@
@VisibleForTesting
void handleGroupIdleDuringCall() {
if (mHfpHandoverDevice == null) {
- if (DBG) {
- Log.d(TAG, "There is no HFP handover");
- }
+ Log.d(TAG, "There is no HFP handover");
return;
}
HeadsetService headsetService = mServiceFactory.getHeadsetService();
if (headsetService == null) {
- if (DBG) {
- Log.d(TAG, "There is no HFP service available");
- }
+ Log.d(TAG, "There is no HFP service available");
return;
}
BluetoothDevice activeHfpDevice = headsetService.getActiveDevice();
if (activeHfpDevice == null) {
- if (DBG) {
- Log.d(TAG, "Make " + mHfpHandoverDevice + " active again ");
- }
+ Log.d(TAG, "Make " + mHfpHandoverDevice + " active again ");
headsetService.setActiveDevice(mHfpHandoverDevice);
} else {
- if (DBG) {
- Log.d(TAG, "Connect audio to " + activeHfpDevice);
- }
+ Log.d(TAG, "Connect audio to " + activeHfpDevice);
headsetService.connectAudio();
}
mHfpHandoverDevice = null;
@@ -2433,9 +2373,7 @@
void updateInbandRingtoneForTheGroup(int groupId) {
if (!mLeAudioInbandRingtoneSupportedByPlatform) {
- if (DBG) {
- Log.d(TAG, "Platform does not support inband ringtone");
- }
+ Log.d(TAG, "Platform does not support inband ringtone");
return;
}
@@ -2450,17 +2388,13 @@
boolean ringtoneContextAvailable =
((groupDescriptor.mAvailableContexts
& BluetoothLeAudio.CONTEXT_TYPE_RINGTONE) != 0);
- if (DBG) {
- Log.d(TAG, "groupId active: " + groupDescriptor.mIsActive
- + " ringtone supported: " + ringtoneContextAvailable);
- }
+ Log.d(TAG, "groupId active: " + groupDescriptor.mIsActive
+ + " ringtone supported: " + ringtoneContextAvailable);
boolean isRingtoneEnabled = (groupDescriptor.mIsActive && ringtoneContextAvailable);
- if (DBG) {
- Log.d(TAG, "updateInbandRingtoneForTheGroup old: "
- + groupDescriptor.mInbandRingtoneEnabled + " new: " + isRingtoneEnabled);
- }
+ Log.d(TAG, "updateInbandRingtoneForTheGroup old: "
+ + groupDescriptor.mInbandRingtoneEnabled + " new: " + isRingtoneEnabled);
/* If at least one device from the group removes the Ringtone from available
* context types, the inband ringtone will be removed
@@ -2480,12 +2414,11 @@
Log.i(TAG, "updateInbandRingtoneForTheGroup, setting inband ringtone to: "
+ groupDescriptor.mInbandRingtoneEnabled + " for " + device
+ " " + deviceDescriptor.mDevInbandRingtoneEnabled);
- if (groupDescriptor.mInbandRingtoneEnabled
- == deviceDescriptor.mDevInbandRingtoneEnabled) {
- if (DBG) {
- Log.d(TAG, "Device " + device + " has already set inband ringtone to "
- + groupDescriptor.mInbandRingtoneEnabled);
- }
+ if (Objects.equals(
+ groupDescriptor.mInbandRingtoneEnabled,
+ deviceDescriptor.mDevInbandRingtoneEnabled)) {
+ Log.d(TAG, "Device " + device + " has already set inband ringtone to "
+ + groupDescriptor.mInbandRingtoneEnabled);
continue;
}
@@ -2504,14 +2437,10 @@
}
void stopAudioServersBackgroundScan() {
- if (DBG) {
- Log.d(TAG, "stopAudioServersBackgroundScan");
- }
+ Log.d(TAG, "stopAudioServersBackgroundScan");
if (mAudioServersScanner == null || mScanCallback == null) {
- if (DBG) {
- Log.d(TAG, "stopAudioServersBackgroundScan: already stopped");
- }
+ Log.d(TAG, "stopAudioServersBackgroundScan: already stopped");
return;
}
@@ -2526,9 +2455,7 @@
}
void startAudioServersBackgroundScan(boolean retry) {
- if (DBG) {
- Log.d(TAG, "startAudioServersBackgroundScan, retry: " + retry);
- }
+ Log.d(TAG, "startAudioServersBackgroundScan, retry: " + retry);
if (!isScannerNeeded()) {
return;
@@ -2544,9 +2471,7 @@
if (!retry) {
if (mScanCallback != null) {
- if (DBG) {
- Log.d(TAG, "startAudioServersBackgroundScan: Scanning already enabled");
- }
+ Log.d(TAG, "startAudioServersBackgroundScan: Scanning already enabled");
return;
}
mScanCallback = new AudioServerScanCallback();
@@ -2601,12 +2526,10 @@
return;
}
- if (DBG) {
- Log.d(TAG, "Transitionaing to Unicast stream for group: "
- + mUnicastGroupIdDeactivatedForBroadcastTransition
- + ", with device: "
- + unicastDevice);
- }
+ Log.d(TAG, "Transitionaing to Unicast stream for group: "
+ + mUnicastGroupIdDeactivatedForBroadcastTransition
+ + ", with device: "
+ + unicastDevice);
updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID);
setActiveDevice(unicastDevice);
@@ -2670,7 +2593,7 @@
&& (getConnectedPeerDevices(groupId).size() > 1)
&& !disconnectDueToUnbond) {
- if (DBG) Log.d(TAG, "Adding to lost devices : " + device);
+ Log.d(TAG, "Adding to lost devices : " + device);
descriptor.mLostLeadDeviceWhileStreaming = device;
return;
}
@@ -2682,9 +2605,7 @@
&& Objects.equals(
descriptor.mLostLeadDeviceWhileStreaming,
device)) {
- if (DBG) {
- Log.d(TAG, "Removing from lost devices : " + device);
- }
+ Log.d(TAG, "Removing from lost devices : " + device);
descriptor.mLostLeadDeviceWhileStreaming = null;
/* Try to connect other devices from the group */
connectSet(device);
@@ -2767,12 +2688,10 @@
descriptor.mInputSelectableConfig,
descriptor.mOutputSelectableConfig);
- if (DBG) {
- if (descriptor.mCodecStatus != null) {
- Log.d(TAG, " Replacing codec status for group: " + groupId);
- } else {
- Log.d(TAG, " New codec status for group: " + groupId);
- }
+ if (descriptor.mCodecStatus != null) {
+ Log.d(TAG, " Replacing codec status for group: " + groupId);
+ } else {
+ Log.d(TAG, " New codec status for group: " + groupId);
}
descriptor.mCodecStatus = status;
@@ -2827,10 +2746,8 @@
descriptor.mSinkAudioLocation = sink_audio_location;
- if (DBG) {
- Log.i(TAG, "EVENT_TYPE_SINK_AUDIO_LOCATION_AVAILABLE:" + device
- + " audio location:" + sink_audio_location);
- }
+ Log.i(TAG, "EVENT_TYPE_SINK_AUDIO_LOCATION_AVAILABLE:" + device
+ + " audio location:" + sink_audio_location);
} else if (stackEvent.type == LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED) {
int groupId = stackEvent.valueInt1;
int groupStatus = stackEvent.valueInt2;
@@ -2954,7 +2871,7 @@
switch (descriptor.mState) {
case LeAudioStackEvent.BROADCAST_STATE_STOPPED:
- if (DBG) Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " stopped.");
+ Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " stopped.");
// Playback stopped
notifyPlaybackStopped(broadcastId,
@@ -2979,10 +2896,10 @@
destroyBroadcast(broadcastId);
break;
case LeAudioStackEvent.BROADCAST_STATE_CONFIGURING:
- if (DBG) Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " configuring.");
+ Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " configuring.");
break;
case LeAudioStackEvent.BROADCAST_STATE_PAUSED:
- if (DBG) Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " paused.");
+ Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " paused.");
/* Stop here if Broadcast was not in Streaming state before */
if (previousState != LeAudioStackEvent.BROADCAST_STATE_STREAMING) {
@@ -3014,10 +2931,10 @@
}
break;
case LeAudioStackEvent.BROADCAST_STATE_STOPPING:
- if (DBG) Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " stopping.");
+ Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " stopping.");
break;
case LeAudioStackEvent.BROADCAST_STATE_STREAMING:
- if (DBG) Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " streaming.");
+ Log.d(TAG, "Broadcast broadcastId: " + broadcastId + " streaming.");
// Stream resumed
notifyPlaybackStarted(broadcastId,
@@ -3102,9 +3019,7 @@
return sm;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm =
LeAudioStateMachine.make(
@@ -3128,9 +3043,7 @@
*/
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
// Remove state machine if the bonding for a device is removed
if (bondState != BluetoothDevice.BOND_NONE) {
return;
@@ -3262,9 +3175,7 @@
/** Process a change for disconnection of a device. */
synchronized void deviceDisconnectedV2(BluetoothDevice device, boolean hasFallbackDevice) {
- if (DBG) {
- Log.d(TAG, "deviceDisconnectedV2 " + device);
- }
+ Log.d(TAG, "deviceDisconnectedV2 " + device);
int groupId = LE_AUDIO_GROUP_ID_INVALID;
mGroupReadLock.lock();
@@ -3281,9 +3192,7 @@
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
+ Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
removeAuthorizationInfoForRelatedProfiles(device);
@@ -3353,9 +3262,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "deviceDisconnected " + device);
- }
+ Log.d(TAG, "deviceDisconnected " + device);
mGroupReadLock.lock();
try {
@@ -3367,9 +3274,7 @@
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
+ Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
removeAuthorizationInfoForRelatedProfiles(device);
}
@@ -3580,9 +3485,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO,
connectionPolicy)) {
@@ -3613,10 +3516,8 @@
* @param connectionPolicy is the connection policy we wish to set
*/
private void setLeAudioGattClientProfilesPolicy(BluetoothDevice device, int connectionPolicy) {
- if (DBG) {
- Log.d(TAG, "setLeAudioGattClientProfilesPolicy for device " + device + " to policy="
- + connectionPolicy);
- }
+ Log.d(TAG, "setLeAudioGattClientProfilesPolicy for device " + device + " to policy="
+ + connectionPolicy);
VolumeControlService volumeControlService = getVolumeControlService();
if (volumeControlService != null) {
volumeControlService.setConnectionPolicy(device, connectionPolicy);
@@ -3653,9 +3554,7 @@
public int getConnectionPolicy(BluetoothDevice device) {
int connection_policy = mDatabaseManager
.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO);
- if (DBG) {
- Log.d(TAG, device + " connection policy = " + connection_policy);
- }
+ Log.d(TAG, device + " connection policy = " + connection_policy);
return connection_policy;
}
@@ -3708,9 +3607,7 @@
* @param volume volume to set
*/
public void setVolume(int volume) {
- if (DBG) {
- Log.d(TAG, "SetVolume " + volume);
- }
+ Log.d(TAG, "SetVolume " + volume);
int currentlyActiveGroupId = getActiveGroupId();
if (currentlyActiveGroupId == LE_AUDIO_GROUP_ID_INVALID) {
@@ -3780,9 +3677,7 @@
*/
@VisibleForTesting
void handleBluetoothEnabled() {
- if (DBG) {
- Log.d(TAG, "handleBluetoothEnabled ");
- }
+ Log.d(TAG, "handleBluetoothEnabled ");
mBluetoothEnabled = true;
@@ -3832,9 +3727,7 @@
private void handleGroupNodeAdded(BluetoothDevice device, int groupId) {
mGroupWriteLock.lock();
try {
- if (DBG) {
- Log.d(TAG, "Device " + device + " added to group " + groupId);
- }
+ Log.d(TAG, "Device " + device + " added to group " + groupId);
LeAudioGroupDescriptor groupDescriptor = getGroupDescriptor(groupId);
if (groupDescriptor == null) {
@@ -3899,9 +3792,7 @@
// TODO(b/326295400): Remove SuppressLint
@SuppressLint("GuardedBy")
private void handleGroupNodeRemoved(BluetoothDevice device, int groupId) {
- if (DBG) {
- Log.d(TAG, "Removing device " + device + " grom group " + groupId);
- }
+ Log.d(TAG, "Removing device " + device + " grom group " + groupId);
boolean isGroupEmpty = true;
mGroupReadLock.lock();
@@ -3911,9 +3802,7 @@
Log.e(TAG, "handleGroupNodeRemoved: No valid descriptor for group: " + groupId);
return;
}
- if (DBG) {
- Log.d(TAG, "Lost lead device is " + groupDescriptor.mLostLeadDeviceWhileStreaming);
- }
+ Log.d(TAG, "Lost lead device is " + groupDescriptor.mLostLeadDeviceWhileStreaming);
if (Objects.equals(device, groupDescriptor.mLostLeadDeviceWhileStreaming)) {
clearLostDevicesWhileStreaming(groupDescriptor);
}
@@ -4161,9 +4050,7 @@
* @return the current codec status
*/
public BluetoothLeAudioCodecStatus getCodecStatus(int groupId) {
- if (DBG) {
- Log.d(TAG, "getCodecStatus(" + groupId + ")");
- }
+ Log.d(TAG, "getCodecStatus(" + groupId + ")");
LeAudioGroupDescriptor descriptor = getGroupDescriptor(groupId);
if (descriptor != null) {
return descriptor.mCodecStatus;
@@ -4181,11 +4068,9 @@
public void setCodecConfigPreference(int groupId,
BluetoothLeAudioCodecConfig inputCodecConfig,
BluetoothLeAudioCodecConfig outputCodecConfig) {
- if (DBG) {
- Log.d(TAG, "setCodecConfigPreference(" + groupId + "): "
- + Objects.toString(inputCodecConfig)
- + Objects.toString(outputCodecConfig));
- }
+ Log.d(TAG, "setCodecConfigPreference(" + groupId + "): "
+ + Objects.toString(inputCodecConfig)
+ + Objects.toString(outputCodecConfig));
LeAudioGroupDescriptor descriptor = getGroupDescriptor(groupId);
if (descriptor == null) {
Log.e(TAG, "setCodecConfigPreference: Invalid groupId, " + groupId);
@@ -5054,7 +4939,7 @@
for (Map.Entry<BluetoothDevice, LeAudioDeviceDescriptor> deviceEntry
: mDeviceDescriptors.entrySet()) {
LeAudioDeviceDescriptor deviceDescriptor = deviceEntry.getValue();
- if (deviceDescriptor.mGroupId != groupId) {
+ if (!Objects.equals(deviceDescriptor.mGroupId, groupId)) {
if (deviceDescriptor.mGroupId == LE_AUDIO_GROUP_ID_INVALID) {
numberOfUngroupedDevs++;
}
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java
index f9a240d..1741e9f 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java
@@ -64,7 +64,6 @@
import java.util.Scanner;
final class LeAudioStateMachine extends StateMachine {
- private static final boolean DBG = false;
private static final String TAG = "LeAudioStateMachine";
static final int CONNECT = 1;
@@ -185,9 +184,7 @@
break;
case STACK_EVENT:
LeAudioStackEvent event = (LeAudioStackEvent) message.obj;
- if (DBG) {
- Log.d(TAG, "Disconnected: stack event: " + event);
- }
+ Log.d(TAG, "Disconnected: stack event: " + event);
if (!mDevice.equals(event.device)) {
Log.wtf(TAG, "Device(" + mDevice + "): event mismatch: " + event);
}
@@ -579,8 +576,6 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
}
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java
index 48b3d8d..817d762 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java
@@ -39,7 +39,6 @@
*/
@VisibleForTesting
public class LeAudioTmapGattServer {
- private static final boolean DBG = true;
private static final String TAG = "LeAudioTmapGattServer";
/* Telephony and Media Audio Profile Role Characteristic UUID */
@@ -72,9 +71,7 @@
*/
@VisibleForTesting
public void start(int roleMask) {
- if (DBG) {
- Log.d(TAG, "start(roleMask:" + roleMask + ")");
- }
+ Log.d(TAG, "start(roleMask:" + roleMask + ")");
if (!mBluetoothGattServer.open(mBluetoothGattServerCallback)) {
throw new IllegalStateException("Could not open Gatt server");
@@ -103,9 +100,7 @@
*/
@VisibleForTesting
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (mBluetoothGattServer == null) {
Log.w(TAG, "mBluetoothGattServer should not be null when stop() is called");
return;
@@ -121,11 +116,9 @@
new BluetoothGattServerCallback() {
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
- BluetoothGattCharacteristic characteristic) {
+ BluetoothGattCharacteristic characteristic) {
byte[] value = characteristic.getValue();
- if (DBG) {
- Log.d(TAG, "value " + Arrays.toString(value));
- }
+ Log.d(TAG, "value " + Arrays.toString(value));
if (value != null) {
Log.e(TAG, "value null");
value = Arrays.copyOfRange(value, offset, value.length);
diff --git a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java
index d0c3367..0a0b853 100644
--- a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java
+++ b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java
@@ -41,7 +41,6 @@
*/
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public class PeriodicScanManager {
- private static final boolean DBG = GattServiceConfig.DBG;
private static final String TAG = GattServiceConfig.TAG_PREFIX + "SyncManager";
private final BluetoothAdapter mAdapter;
@@ -52,18 +51,14 @@
/** Constructor of {@link PeriodicScanManager}. */
public PeriodicScanManager(AdapterService adapterService) {
- if (DBG) {
- Log.d(TAG, "periodic scan manager created");
- }
+ Log.d(TAG, "periodic scan manager created");
mAdapter = BluetoothAdapter.getDefaultAdapter();
mNativeInterface = PeriodicScanNativeInterface.getInstance();
mNativeInterface.init(this);
}
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
mNativeInterface.cleanup();
mSyncs.clear();
sTempRegistrationId = -1;
@@ -128,9 +123,7 @@
@Override
public void binderDied() {
- if (DBG) {
- Log.d(TAG, "Binder is dead - unregistering advertising set");
- }
+ Log.d(TAG, "Binder is dead - unregistering advertising set");
stopSync(callback);
}
}
@@ -274,23 +267,19 @@
String address = scanResult.getDevice().getAddress();
int addressType = scanResult.getDevice().getAddressType();
int sid = scanResult.getAdvertisingSid();
- if (DBG) {
- Log.d(
- TAG,
- "startSync for Device: "
- + address
- + " addressType: "
- + addressType
- + " sid: "
- + sid);
- }
+ Log.d(
+ TAG,
+ "startSync for Device: "
+ + address
+ + " addressType: "
+ + addressType
+ + " sid: "
+ + sid);
synchronized (mSyncs) {
Map.Entry<IBinder, SyncInfo> entry = findMatchingSync(sid, address);
if (entry != null) {
//Found matching sync. Copy sync handle
- if (DBG) {
- Log.d(TAG, "startSync: Matching entry found");
- }
+ Log.d(TAG, "startSync: Matching entry found");
mSyncs.put(binder, new SyncInfo(entry.getValue().id, sid, address,
entry.getValue().skip, entry.getValue().timeout, deathRecipient,
callback));
@@ -317,17 +306,13 @@
mSyncs.put(binder, new SyncInfo(cbId, sid, address, skip, timeout,
deathRecipient, callback));
- if (DBG) {
- Log.d(TAG, "startSync() - reg_id=" + cbId + ", callback: " + binder);
- }
+ Log.d(TAG, "startSync() - reg_id=" + cbId + ", callback: " + binder);
mNativeInterface.startSync(sid, address, skip, timeout, cbId);
}
public void stopSync(IPeriodicAdvertisingCallback callback) {
IBinder binder = toBinder(callback);
- if (DBG) {
- Log.d(TAG, "stopSync() " + binder);
- }
+ Log.d(TAG, "stopSync() " + binder);
SyncInfo sync = null;
synchronized (mSyncs) {
sync = mSyncs.remove(binder);
@@ -387,9 +372,7 @@
int advHandle, IPeriodicAdvertisingCallback callback) {
SyncDeathRecipient deathRecipient = new SyncDeathRecipient(callback);
IBinder binder = toBinder(callback);
- if (DBG) {
- Log.d(TAG, "transferSetInfo() " + binder);
- }
+ Log.d(TAG, "transferSetInfo() " + binder);
try {
binder.linkToDeath(deathRecipient, 0);
} catch (RemoteException e) {
diff --git a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanNativeInterface.java b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanNativeInterface.java
index 639e0ee..7372a68 100644
--- a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanNativeInterface.java
@@ -19,14 +19,12 @@
import android.bluetooth.BluetoothDevice;
import android.util.Log;
-import com.android.bluetooth.gatt.GattServiceConfig;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
/** NativeInterface for PeriodicScanManager */
public class PeriodicScanNativeInterface {
private static final String TAG = PeriodicScanNativeInterface.class.getSimpleName();
- private static final boolean DBG = GattServiceConfig.DBG;
private static final int PA_SOURCE_LOCAL = 1;
private static final int PA_SOURCE_REMOTE = 2;
@@ -100,47 +98,37 @@
int interval,
int status)
throws Exception {
- if (DBG) {
- Log.d(
- TAG,
- "onSyncStarted(): "
- + (" regId=" + regId)
- + (" syncHandle=" + syncHandle)
- + (" status=" + status));
- }
+ Log.d(
+ TAG,
+ "onSyncStarted(): "
+ + (" regId=" + regId)
+ + (" syncHandle=" + syncHandle)
+ + (" status=" + status));
mManager.onSyncStarted(regId, syncHandle, sid, addressType, address, phy, interval, status);
}
void onSyncReport(int syncHandle, int txPower, int rssi, int dataStatus, byte[] data)
throws Exception {
- if (DBG) {
- Log.d(TAG, "onSyncReport(): syncHandle=" + syncHandle);
- }
+ Log.d(TAG, "onSyncReport(): syncHandle=" + syncHandle);
mManager.onSyncReport(syncHandle, txPower, rssi, dataStatus, data);
}
void onSyncLost(int syncHandle) throws Exception {
- if (DBG) {
- Log.d(TAG, "onSyncLost(): syncHandle=" + syncHandle);
- }
+ Log.d(TAG, "onSyncLost(): syncHandle=" + syncHandle);
mManager.onSyncLost(syncHandle);
}
void onSyncTransferredCallback(int paSource, int status, String bda) {
- if (DBG) {
- Log.d(TAG, "onSyncTransferredCallback()");
- }
+ Log.d(TAG, "onSyncTransferredCallback()");
mManager.onSyncTransferredCallback(paSource, status, bda);
}
void onBigInfoReport(int syncHandle, boolean encrypted) throws Exception {
- if (DBG) {
- Log.d(
- TAG,
- "onBigInfoReport():"
- + (" syncHandle=" + syncHandle)
- + (" encrypted=" + encrypted));
- }
+ Log.d(
+ TAG,
+ "onBigInfoReport():"
+ + (" syncHandle=" + syncHandle)
+ + (" encrypted=" + encrypted));
mManager.onBigInfoReport(syncHandle, encrypted);
}
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 77397aa..55658ea 100644
--- a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java
+++ b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java
@@ -69,7 +69,6 @@
* Class that handles Bluetooth LE scan related operations.
*/
public class ScanManager {
- private static final boolean DBG = GattServiceConfig.DBG;
private static final String TAG = GattServiceConfig.TAG_PREFIX + "ScanManager";
/**
@@ -289,9 +288,7 @@
}
public void startScan(ScanClient client) {
- if (DBG) {
- Log.d(TAG, "startScan() " + client);
- }
+ Log.d(TAG, "startScan() " + client);
sendMessage(MSG_START_BLE_SCAN, client);
}
@@ -393,9 +390,7 @@
}
void handleStartScan(ScanClient client) {
- if (DBG) {
- Log.d(TAG, "handling starting scan");
- }
+ Log.d(TAG, "handling starting scan");
fetchAppForegroundState(client);
if (!isScanSupported(client)) {
@@ -457,11 +452,9 @@
removeMessages(MSG_SCAN_TIMEOUT, client);
}
sendMessageDelayed(msg, mAdapterService.getScanTimeoutMillis());
- if (DBG) {
- Log.d(TAG,
- "apply scan timeout (" + mAdapterService.getScanTimeoutMillis()
- + ")" + "to scannerId " + client.scannerId);
- }
+ Log.d(TAG,
+ "apply scan timeout (" + mAdapterService.getScanTimeoutMillis()
+ + ")" + "to scannerId " + client.scannerId);
}
}
}
@@ -499,9 +492,7 @@
if (client == null) {
return;
}
- if (DBG) {
- Log.d(TAG, "handling stopping scan " + client);
- }
+ Log.d(TAG, "handling stopping scan " + client);
if (mSuspendedScanClients.contains(client)) {
mSuspendedScanClients.remove(client);
@@ -521,21 +512,15 @@
mScanNative.stopBatchScan(client);
}
if (client.appDied) {
- if (DBG) {
- Log.d(TAG, "app died, unregister scanner - " + client.scannerId);
- }
+ Log.d(TAG, "app died, unregister scanner - " + client.scannerId);
mScanHelper.unregisterScanner(client.scannerId, mContext.getAttributionSource());
}
}
void handleFlushBatchResults(ScanClient client) {
- if (DBG) {
- Log.d(TAG, "handleFlushBatchResults() " + client);
- }
+ Log.d(TAG, "handleFlushBatchResults() " + client);
if (!mBatchClients.contains(client)) {
- if (DBG) {
- Log.d(TAG, "There is no batch scan client to flush " + client);
- }
+ Log.d(TAG, "There is no batch scan client to flush " + client);
return;
}
mScanNative.flushBatchResults(client.scannerId);
@@ -568,9 +553,7 @@
return;
}
mScreenOn = false;
- if (DBG) {
- Log.d(TAG, "handleScreenOff()");
- }
+ Log.d(TAG, "handleScreenOff()");
handleSuspendScans();
updateRegularScanClientsScreenOff();
updateRegularScanToBatchScanClients();
@@ -582,15 +565,11 @@
}
boolean updatedScanParams = false;
mIsConnecting = true;
- if (DBG) {
- Log.d(TAG, "handleConnectingState()");
- }
+ Log.d(TAG, "handleConnectingState()");
for (ScanClient client : mRegularScanClients) {
if (downgradeScanModeFromMaxDuty(client)) {
updatedScanParams = true;
- if (DBG) {
- Log.d(TAG, "scanMode is downgraded by connecting for " + client);
- }
+ Log.d(TAG, "scanMode is downgraded by connecting for " + client);
}
}
if (updatedScanParams) {
@@ -606,16 +585,12 @@
Log.e(TAG, "handleClearConnectingState() - not connecting state");
return;
}
- if (DBG) {
- Log.d(TAG, "handleClearConnectingState()");
- }
+ Log.d(TAG, "handleClearConnectingState()");
boolean updatedScanParams = false;
for (ScanClient client : mRegularScanClients) {
if (revertDowngradeScanModeFromMaxDuty(client)) {
updatedScanParams = true;
- if (DBG) {
- Log.d(TAG, "downgraded scanMode is reverted for " + client);
- }
+ Log.d(TAG, "downgraded scanMode is reverted for " + client);
}
}
if (updatedScanParams) {
@@ -634,9 +609,7 @@
if (client.stats != null) {
client.stats.recordScanSuspend(client.scannerId);
}
- if (DBG) {
- Log.d(TAG, "suspend scan " + client);
- }
+ Log.d(TAG, "suspend scan " + client);
handleStopScan(client);
mSuspendedScanClients.add(client);
}
@@ -647,9 +620,7 @@
boolean updatedScanParams = false;
for (ScanClient client : mRegularScanClients) {
if (!mScanNative.isExemptFromAutoBatchScanUpdate(client)) {
- if (DBG) {
- Log.d(TAG, "Updating regular scan to batch scan" + client);
- }
+ Log.d(TAG, "Updating regular scan to batch scan" + client);
handleStopScan(client);
setAutoBatchScanClient(client);
handleStartScan(client);
@@ -665,9 +636,7 @@
boolean updatedScanParams = false;
for (ScanClient client : mBatchClients) {
if (!mScanNative.isExemptFromAutoBatchScanUpdate(client)) {
- if (DBG) {
- Log.d(TAG, "Updating batch scan to regular scan" + client);
- }
+ Log.d(TAG, "Updating batch scan to regular scan" + client);
handleStopScan(client);
clearAutoBatchScanClient(client);
handleStartScan(client);
@@ -704,9 +673,7 @@
for (ScanClient client : mRegularScanClients) {
if (updateScanModeScreenOff(client)) {
updatedScanParams = true;
- if (DBG) {
- Log.d(TAG, "Scan mode update during screen off" + client);
- }
+ Log.d(TAG, "Scan mode update during screen off" + client);
}
}
if (updatedScanParams) {
@@ -794,9 +761,7 @@
if (upgradeScanModeByOneLevel(client)) {
Message msg = obtainMessage(MSG_REVERT_SCAN_MODE_UPGRADE);
msg.obj = client;
- if (DBG) {
- Log.d(TAG, "scanMode is upgraded for " + client);
- }
+ Log.d(TAG, "scanMode is upgraded for " + client);
sendMessageDelayed(msg, mAdapterService.getScanUpgradeDurationMillis());
return true;
}
@@ -823,9 +788,7 @@
return;
}
if (client.updateScanMode(client.scanModeApp)) {
- if (DBG) {
- Log.d(TAG, "scanMode upgrade is reverted for " + client);
- }
+ Log.d(TAG, "scanMode upgrade is reverted for " + client);
mScanNative.configureRegularScanParams();
}
}
@@ -851,9 +814,7 @@
int maxScanMode = SCAN_MODE_MAX_IN_CONCURRENCY;
if (client.updateScanMode(getMinScanMode(scanMode, maxScanMode))) {
client.stats.setScanDowngrade(client.scannerId, true);
- if (DBG) {
- Log.d(TAG, "downgradeScanModeFromMaxDuty() for " + client);
- }
+ Log.d(TAG, "downgradeScanModeFromMaxDuty() for " + client);
return true;
}
return false;
@@ -864,9 +825,7 @@
return false;
}
client.stats.setScanDowngrade(client.scannerId, false);
- if (DBG) {
- Log.d(TAG, "revertDowngradeScanModeFromMaxDuty() for " + client);
- }
+ Log.d(TAG, "revertDowngradeScanModeFromMaxDuty() for " + client);
if (mScreenOn) {
return updateScanModeScreenOn(client);
} else {
@@ -880,9 +839,7 @@
return;
}
mScreenOn = true;
- if (DBG) {
- Log.d(TAG, "handleScreenOn()");
- }
+ Log.d(TAG, "handleScreenOn()");
updateBatchScanToRegularScanClients();
handleResumeScans();
updateRegularScanClientsScreenOn();
@@ -897,9 +854,7 @@
if (client.stats != null) {
client.stats.recordScanResume(client.scannerId);
}
- if (DBG) {
- Log.d(TAG, "resume scan " + client);
- }
+ Log.d(TAG, "resume scan " + client);
handleStartScan(client);
iterator.remove();
}
@@ -923,15 +878,13 @@
int profile = ((Integer) msg.obj).intValue();
boolean updatedConnectingState =
updateCountersAndCheckForConnectingState(toState, fromState);
- if (DBG) {
- Log.d(
- TAG,
- "PROFILE_CONNECTION_STATE_CHANGE:"
- + (" profile=" + BluetoothProfile.getProfileName(profile))
- + (" prevState=" + fromState)
- + (" state=" + toState)
- + (" updatedConnectingState = " + updatedConnectingState));
- }
+ Log.d(
+ TAG,
+ "PROFILE_CONNECTION_STATE_CHANGE:"
+ + (" profile=" + BluetoothProfile.getProfileName(profile))
+ + (" prevState=" + fromState)
+ + (" state=" + toState)
+ + (" updatedConnectingState = " + updatedConnectingState));
if (updatedConnectingState) {
if (!mIsConnecting) {
handleConnectingState();
@@ -1056,9 +1009,7 @@
}
private void callbackDone(int scannerId, int status) {
- if (DBG) {
- Log.d(TAG, "callback done for scannerId - " + scannerId + " status - " + status);
- }
+ Log.d(TAG, "callback done for scannerId - " + scannerId + " status - " + status);
if (status == 0) {
mNativeInterface.callbackDone();
}
@@ -1074,9 +1025,7 @@
}
void configureRegularScanParams() {
- if (DBG) {
- Log.d(TAG, "configureRegularScanParams() - queue=" + mRegularScanClients.size());
- }
+ Log.d(TAG, "configureRegularScanParams() - queue=" + mRegularScanClients.size());
int curScanSetting = Integer.MIN_VALUE;
ScanClient client = getAggressiveClient(mRegularScanClients);
if (client != null) {
@@ -1097,14 +1046,12 @@
if (!AppScanStats.recordScanRadioStop()) {
Log.w(TAG, "There is no scan radio to stop");
}
- if (DBG) {
- Log.d(TAG, "Start gattClientScanNative with"
- + " old scanMode " + mLastConfiguredScanSetting
- + " new scanMode " + curScanSetting
- + " ( in MS: " + scanIntervalMs + " / " + scanWindowMs
- + ", in scan unit: " + scanInterval + " / " + scanWindow + " )"
- + client);
- }
+ Log.d(TAG, "Start gattClientScanNative with"
+ + " old scanMode " + mLastConfiguredScanSetting
+ + " new scanMode " + curScanSetting
+ + " ( in MS: " + scanIntervalMs + " / " + scanWindowMs
+ + ", in scan unit: " + scanInterval + " / " + scanWindow + " )"
+ + client);
mNativeInterface.gattSetScanParameters(
client.scannerId, scanInterval, scanWindow, scanPhy);
mNativeInterface.gattClientScan(true);
@@ -1115,9 +1062,7 @@
}
} else {
mLastConfiguredScanSetting = curScanSetting;
- if (DBG) {
- Log.d(TAG, "configureRegularScanParams() - queue empty, scan stopped");
- }
+ Log.d(TAG, "configureRegularScanParams() - queue empty, scan stopped");
}
}
@@ -1146,9 +1091,7 @@
if (numRegularScanClients() == 1
&& client.settings != null
&& client.settings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) {
- if (DBG) {
- Log.d(TAG, "start gattClientScanNative from startRegularScan()");
- }
+ Log.d(TAG, "start gattClientScanNative from startRegularScan()");
mNativeInterface.gattClientScan(true);
if (!AppScanStats.recordScanRadioStart(client.settings.getScanMode())) {
Log.w(TAG, "Scan radio already started");
@@ -1221,9 +1164,7 @@
BatchScanParams batchScanParams = getBatchScanParams();
// Stop batch if batch scan params changed and previous params is not null.
if (mBatchScanParms != null && (!mBatchScanParms.equals(batchScanParams))) {
- if (DBG) {
- Log.d(TAG, "stopping BLe Batch");
- }
+ Log.d(TAG, "stopping BLe Batch");
resetCountDownLatch();
mNativeInterface.gattClientStopBatchScan(scannerId);
waitForCallback();
@@ -1234,15 +1175,11 @@
// Start batch if batchScanParams changed and current params is not null.
if (batchScanParams != null && (!batchScanParams.equals(mBatchScanParms))) {
int notifyThreshold = 95;
- if (DBG) {
- Log.d(TAG, "Starting BLE batch scan");
- }
+ Log.d(TAG, "Starting BLE batch scan");
int resultType = getResultType(batchScanParams);
int fullScanPercent = getFullScanStoragePercent(resultType);
resetCountDownLatch();
- if (DBG) {
- Log.d(TAG, "configuring batch scan storage, appIf " + client.scannerId);
- }
+ Log.d(TAG, "configuring batch scan storage, appIf " + client.scannerId);
mNativeInterface.gattClientConfigBatchScanStorage(client.scannerId, fullScanPercent,
100 - fullScanPercent, notifyThreshold);
waitForCallback();
@@ -1375,9 +1312,7 @@
}
mRegularScanClients.remove(client);
if (numRegularScanClients() == 0) {
- if (DBG) {
- Log.d(TAG, "stop gattClientScanNative");
- }
+ Log.d(TAG, "stop gattClientScanNative");
mNativeInterface.gattClientScan(false);
if (!AppScanStats.recordScanRadioStop()) {
Log.w(TAG, "There is no scan radio to stop");
@@ -1388,9 +1323,7 @@
void regularScanTimeout(ScanClient client) {
if (!isExemptFromScanTimeout(client) && client.stats.isScanningTooLong()) {
- if (DBG) {
- Log.d(TAG, "regularScanTimeout - client scan time was too long");
- }
+ Log.d(TAG, "regularScanTimeout - client scan time was too long");
if (client.filters == null || client.filters.isEmpty()) {
Log.w(TAG,
"Moving unfiltered scan client to opportunistic scan (scannerId "
@@ -1415,9 +1348,7 @@
// The scan should continue for background scans
configureRegularScanParams();
if (numRegularScanClients() == 0) {
- if (DBG) {
- Log.d(TAG, "stop gattClientScanNative");
- }
+ Log.d(TAG, "stop gattClientScanNative");
mNativeInterface.gattClientScan(false);
if (!AppScanStats.recordScanRadioStop()) {
Log.w(TAG, "There is no scan radio to stop");
@@ -1466,9 +1397,7 @@
}
void flushBatchResults(int scannerId) {
- if (DBG) {
- Log.d(TAG, "flushPendingBatchResults - scannerId = " + scannerId);
- }
+ Log.d(TAG, "flushPendingBatchResults - scannerId = " + scannerId);
if (mBatchScanParms.fullScanscannerId != -1) {
resetCountDownLatch();
mNativeInterface.gattClientReadScanReports(mBatchScanParms.fullScanscannerId,
@@ -1532,7 +1461,7 @@
: ALL_PASS_FILTER_INDEX_REGULAR_SCAN;
resetCountDownLatch();
// Don't allow Onfound/onlost with all pass
- configureFilterParamter(scannerId, client, ALL_PASS_FILTER_SELECTION, filterIndex,
+ configureFilterParameter(scannerId, client, ALL_PASS_FILTER_SELECTION, filterIndex,
0);
waitForCallback();
} else {
@@ -1565,7 +1494,7 @@
}
}
}
- configureFilterParamter(scannerId, client, featureSelection, filterIndex,
+ configureFilterParameter(scannerId, client, featureSelection, filterIndex,
trackEntries);
waitForCallback();
clientFilterIndices.add(filterIndex);
@@ -1675,18 +1604,16 @@
}
// Configure filter parameters.
- private void configureFilterParamter(int scannerId, ScanClient client, int featureSelection,
- int filterIndex, int numOfTrackingEntries) {
+ private void configureFilterParameter(int scannerId, ScanClient client,
+ int featureSelection, int filterIndex, int numOfTrackingEntries) {
int deliveryMode = getDeliveryMode(client);
int rssiThreshold = Byte.MIN_VALUE;
ScanSettings settings = client.settings;
int onFoundTimeout = getOnFoundOnLostTimeoutMillis(settings, true);
int onFoundCount = getOnFoundOnLostSightings(settings);
int onLostTimeout = 10000;
- if (DBG) {
- Log.d(TAG, "configureFilterParamter " + onFoundTimeout + " " + onLostTimeout + " "
- + onFoundCount + " " + numOfTrackingEntries);
- }
+ Log.d(TAG, "configureFilterParameter " + onFoundTimeout + " " + onLostTimeout + " "
+ + onFoundCount + " " + numOfTrackingEntries);
FilterParams filtValue =
new FilterParams(scannerId, filterIndex, featureSelection, LIST_LOGIC_TYPE,
FILTER_LOGIC_TYPE, rssiThreshold, rssiThreshold, deliveryMode,
@@ -1847,10 +1774,8 @@
break;
default:
val = 1;
- if (DBG) {
- Log.d(TAG, "Invalid setting for getNumOfMatches() "
- + settings.getNumOfMatches());
- }
+ Log.d(TAG, "Invalid setting for getNumOfMatches() "
+ + settings.getNumOfMatches());
}
return val;
}
@@ -2006,10 +1931,8 @@
break;
default:
}
- if (DBG) {
- Log.d(TAG, "mProfilesConnecting " + mProfilesConnecting + ", mProfilesConnected "
- + mProfilesConnected + ", mProfilesDisconnecting " + mProfilesDisconnecting);
- }
+ Log.d(TAG, "mProfilesConnecting " + mProfilesConnecting + ", mProfilesConnected "
+ + mProfilesConnected + ", mProfilesDisconnecting " + mProfilesDisconnecting);
return (mProfilesConnecting > 0);
}
@@ -2048,10 +1971,8 @@
updatedScanParams = true;
}
}
- if (DBG) {
- Log.d(TAG, "uid " + uid + " isForeground " + isForeground
- + " scanMode " + client.settings.getScanMode());
- }
+ Log.d(TAG, "uid " + uid + " isForeground " + isForeground
+ + " scanMode " + client.settings.getScanMode());
}
if (updatedScanParams) {
diff --git a/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java b/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java
index ba80f2d..025c994 100644
--- a/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java
+++ b/android/app/src/com/android/bluetooth/le_scan/TransitionalScanHelper.java
@@ -80,8 +80,6 @@
* {@link com.android.bluetooth.btservice.ProfileService} when introduced.
*/
public class TransitionalScanHelper {
- private static final boolean DBG = GattServiceConfig.DBG;
- private static final boolean VDBG = GattServiceConfig.VDBG;
private static final String TAG = GattServiceConfig.TAG_PREFIX + "ScanHelper";
// Batch scan related constants.
@@ -341,41 +339,37 @@
int periodicAdvInt,
byte[] advData,
String originalAddress) {
- if (VDBG) {
- Log.d(
- TAG,
- "onScanResult() - eventType=0x"
- + Integer.toHexString(eventType)
- + ", addressType="
- + addressType
- + ", address="
- + address
- + ", primaryPhy="
- + primaryPhy
- + ", secondaryPhy="
- + secondaryPhy
- + ", advertisingSid=0x"
- + Integer.toHexString(advertisingSid)
- + ", txPower="
- + txPower
- + ", rssi="
- + rssi
- + ", periodicAdvInt=0x"
- + Integer.toHexString(periodicAdvInt)
- + ", originalAddress="
- + originalAddress);
- }
+ Log.v(
+ TAG,
+ "onScanResult() - eventType=0x"
+ + Integer.toHexString(eventType)
+ + ", addressType="
+ + addressType
+ + ", address="
+ + address
+ + ", primaryPhy="
+ + primaryPhy
+ + ", secondaryPhy="
+ + secondaryPhy
+ + ", advertisingSid=0x"
+ + Integer.toHexString(advertisingSid)
+ + ", txPower="
+ + txPower
+ + ", rssi="
+ + rssi
+ + ", periodicAdvInt=0x"
+ + Integer.toHexString(periodicAdvInt)
+ + ", originalAddress="
+ + originalAddress);
String identityAddress = mAdapterService.getIdentityAddress(address);
if (!address.equals(identityAddress)) {
- if (VDBG) {
- Log.d(
- TAG,
- "found identityAddress of "
- + address
- + ", replace originalAddress as "
- + identityAddress);
- }
+ Log.v(
+ TAG,
+ "found identityAddress of "
+ + address
+ + ", replace originalAddress as "
+ + identityAddress);
originalAddress = identityAddress;
}
@@ -384,9 +378,7 @@
for (ScanClient client : mScanManager.getRegularScanQueue()) {
ScannerMap.App app = mScannerMap.getById(client.scannerId);
if (app == null) {
- if (VDBG) {
- Log.d(TAG, "App is null; skip.");
- }
+ Log.v(TAG, "App is null; skip.");
continue;
}
@@ -399,9 +391,7 @@
if (settings.getLegacy()) {
if ((eventType & ET_LEGACY_MASK) == 0) {
// If this is legacy scan, but nonlegacy result - skip.
- if (VDBG) {
- Log.d(TAG, "Legacy scan, non legacy result; skip.");
- }
+ Log.v(TAG, "Legacy scan, non legacy result; skip.");
continue;
} else {
// Some apps are used to fixed-size advertise data.
@@ -450,23 +440,19 @@
}
boolean matchResult = matchesFilters(client, result, originalAddress);
if (!hasPermission || !matchResult) {
- if (VDBG) {
- Log.d(
- TAG,
- "Skipping client: permission="
- + hasPermission
- + " matches="
- + matchResult);
- }
+ Log.v(
+ TAG,
+ "Skipping client: permission="
+ + hasPermission
+ + " matches="
+ + matchResult);
continue;
}
int callbackType = settings.getCallbackType();
if (!(callbackType == ScanSettings.CALLBACK_TYPE_ALL_MATCHES
|| callbackType == ScanSettings.CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH)) {
- if (VDBG) {
- Log.d(TAG, "Skipping client: CALLBACK_TYPE_ALL_MATCHES");
- }
+ Log.v(TAG, "Skipping client: CALLBACK_TYPE_ALL_MATCHES");
continue;
}
@@ -531,16 +517,14 @@
public void onScannerRegistered(int status, int scannerId, long uuidLsb, long uuidMsb)
throws RemoteException {
UUID uuid = new UUID(uuidMsb, uuidLsb);
- if (DBG) {
- Log.d(
- TAG,
- "onScannerRegistered() - UUID="
- + uuid
- + ", scannerId="
- + scannerId
- + ", status="
- + status);
- }
+ Log.d(
+ TAG,
+ "onScannerRegistered() - UUID="
+ + uuid
+ + ", scannerId="
+ + scannerId
+ + ", status="
+ + status);
// First check the callback map
ScannerMap.App cbApp = mScannerMap.getByUuid(uuid);
@@ -613,81 +597,71 @@
/** Callback method for scan filter enablement/disablement. */
public void onScanFilterEnableDisabled(int action, int status, int clientIf) {
- if (DBG) {
- Log.d(
- TAG,
- "onScanFilterEnableDisabled() - clientIf="
- + clientIf
- + ", status="
- + status
- + ", action="
- + action);
- }
+ Log.d(
+ TAG,
+ "onScanFilterEnableDisabled() - clientIf="
+ + clientIf
+ + ", status="
+ + status
+ + ", action="
+ + action);
mScanManager.callbackDone(clientIf, status);
}
/** Callback method for configuration of scan filter params. */
public void onScanFilterParamsConfigured(
int action, int status, int clientIf, int availableSpace) {
- if (DBG) {
- Log.d(
- TAG,
- "onScanFilterParamsConfigured() - clientIf="
- + clientIf
- + ", status="
- + status
- + ", action="
- + action
- + ", availableSpace="
- + availableSpace);
- }
+ Log.d(
+ TAG,
+ "onScanFilterParamsConfigured() - clientIf="
+ + clientIf
+ + ", status="
+ + status
+ + ", action="
+ + action
+ + ", availableSpace="
+ + availableSpace);
mScanManager.callbackDone(clientIf, status);
}
/** Callback method for configuration of scan filter. */
public void onScanFilterConfig(
int action, int status, int clientIf, int filterType, int availableSpace) {
- if (DBG) {
- Log.d(
- TAG,
- "onScanFilterConfig() - clientIf="
- + clientIf
- + ", action = "
- + action
- + " status = "
- + status
- + ", filterType="
- + filterType
- + ", availableSpace="
- + availableSpace);
- }
+ Log.d(
+ TAG,
+ "onScanFilterConfig() - clientIf="
+ + clientIf
+ + ", action = "
+ + action
+ + " status = "
+ + status
+ + ", filterType="
+ + filterType
+ + ", availableSpace="
+ + availableSpace);
mScanManager.callbackDone(clientIf, status);
}
/** Callback method for configuration of batch scan storage. */
public void onBatchScanStorageConfigured(int status, int clientIf) {
- if (DBG) {
- Log.d(
- TAG,
- "onBatchScanStorageConfigured() - clientIf=" + clientIf + ", status=" + status);
- }
+ Log.d(
+ TAG,
+ "onBatchScanStorageConfigured() - clientIf=" + clientIf + ", status=" + status);
mScanManager.callbackDone(clientIf, status);
}
/** Callback method for start/stop of batch scan. */
// TODO: split into two different callbacks : onBatchScanStarted and onBatchScanStopped.
public void onBatchScanStartStopped(int startStopAction, int status, int clientIf) {
- if (DBG) {
- Log.d(
- TAG,
- "onBatchScanStartStopped() - clientIf="
- + clientIf
- + ", status="
- + status
- + ", startStopAction="
- + startStopAction);
- }
+ Log.d(
+ TAG,
+ "onBatchScanStartStopped() - clientIf="
+ + clientIf
+ + ", status="
+ + status
+ + ", startStopAction="
+ + startStopAction);
mScanManager.callbackDone(clientIf, status);
}
@@ -715,18 +689,16 @@
void onBatchScanReportsInternal(
int status, int scannerId, int reportType, int numRecords, byte[] recordData)
throws RemoteException {
- if (DBG) {
- Log.d(
- TAG,
- "onBatchScanReports() - scannerId="
- + scannerId
- + ", status="
- + status
- + ", reportType="
- + reportType
- + ", numRecords="
- + numRecords);
- }
+ Log.d(
+ TAG,
+ "onBatchScanReports() - scannerId="
+ + scannerId
+ + ", status="
+ + status
+ + ", reportType="
+ + reportType
+ + ", numRecords="
+ + numRecords);
Set<ScanResult> results = parseBatchScanResults(numRecords, reportType, recordData);
if (reportType == ScanManager.SCAN_RESULT_TYPE_TRUNCATED) {
@@ -787,17 +759,13 @@
try {
if (app.callback != null) {
if (mScanManager.isAutoBatchScanClientEnabled(client)) {
- if (DBG) {
- Log.d(TAG, "sendBatchScanResults() to onScanResult()" + client);
- }
+ Log.d(TAG, "sendBatchScanResults() to onScanResult()" + client);
for (ScanResult result : results) {
app.appScanStats.addResult(client.scannerId);
app.callback.onScanResult(result);
}
} else {
- if (DBG) {
- Log.d(TAG, "sendBatchScanResults() to onBatchScanResults()" + client);
- }
+ Log.d(TAG, "sendBatchScanResults() to onBatchScanResults()" + client);
app.callback.onBatchScanResults(results);
}
} else {
@@ -859,9 +827,7 @@
if (numRecords == 0) {
return Collections.emptySet();
}
- if (DBG) {
- Log.d(TAG, "current time is " + SystemClock.elapsedRealtimeNanos());
- }
+ Log.d(TAG, "current time is " + SystemClock.elapsedRealtimeNanos());
if (reportType == ScanManager.SCAN_RESULT_TYPE_TRUNCATED) {
return parseTruncatedResults(numRecords, batchRecord);
} else {
@@ -870,9 +836,7 @@
}
private Set<ScanResult> parseTruncatedResults(int numRecords, byte[] batchRecord) {
- if (DBG) {
- Log.d(TAG, "batch record " + Arrays.toString(batchRecord));
- }
+ Log.d(TAG, "batch record " + Arrays.toString(batchRecord));
Set<ScanResult> results = new HashSet<ScanResult>(numRecords);
long now = SystemClock.elapsedRealtimeNanos();
for (int i = 0; i < numRecords; ++i) {
@@ -898,9 +862,7 @@
}
private Set<ScanResult> parseFullResults(int numRecords, byte[] batchRecord) {
- if (DBG) {
- Log.d(TAG, "Batch record : " + Arrays.toString(batchRecord));
- }
+ Log.d(TAG, "Batch record : " + Arrays.toString(batchRecord));
Set<ScanResult> results = new HashSet<ScanResult>(numRecords);
int position = 0;
long now = SystemClock.elapsedRealtimeNanos();
@@ -929,9 +891,7 @@
System.arraycopy(advertiseBytes, 0, scanRecord, 0, advertisePacketLen);
System.arraycopy(
scanResponseBytes, 0, scanRecord, advertisePacketLen, scanResponsePacketLen);
- if (DBG) {
- Log.d(TAG, "ScanRecord : " + Arrays.toString(scanRecord));
- }
+ Log.d(TAG, "ScanRecord : " + Arrays.toString(scanRecord));
results.add(
new ScanResult(
device, ScanRecord.parseFromBytes(scanRecord), rssi, timestampNanos));
@@ -958,9 +918,7 @@
@RequiresPermission(android.Manifest.permission.BLUETOOTH_SCAN)
public void onBatchScanThresholdCrossed(int clientIf) {
- if (DBG) {
- Log.d(TAG, "onBatchScanThresholdCrossed() - clientIf=" + clientIf);
- }
+ Log.d(TAG, "onBatchScanThresholdCrossed() - clientIf=" + clientIf);
flushPendingBatchResults(clientIf, mContext.getAttributionSource());
}
@@ -997,16 +955,14 @@
public void onTrackAdvFoundLost(AdvtFilterOnFoundOnLostInfo trackingInfo)
throws RemoteException {
- if (DBG) {
- Log.d(
- TAG,
- "onTrackAdvFoundLost() - scannerId= "
- + trackingInfo.getClientIf()
- + " address = "
- + trackingInfo.getAddress()
- + " adv_state = "
- + trackingInfo.getAdvState());
- }
+ Log.d(
+ TAG,
+ "onTrackAdvFoundLost() - scannerId= "
+ + trackingInfo.getClientIf()
+ + " address = "
+ + trackingInfo.getAddress()
+ + " adv_state = "
+ + trackingInfo.getAdvState());
ScannerMap.App app = mScannerMap.getById(trackingInfo.getClientIf());
if (app == null || (app.callback == null && app.info == null)) {
@@ -1046,16 +1002,14 @@
app.info, result, ScanSettings.CALLBACK_TYPE_MATCH_LOST, client);
}
} else {
- if (DBG) {
- Log.d(
- TAG,
- "Not reporting onlost/onfound : "
- + advertiserState
- + " scannerId = "
- + client.scannerId
- + " callbackType "
- + settings.getCallbackType());
- }
+ Log.d(
+ TAG,
+ "Not reporting onlost/onfound : "
+ + advertiserState
+ + " scannerId = "
+ + client.scannerId
+ + " callbackType "
+ + settings.getCallbackType());
}
}
}
@@ -1067,9 +1021,7 @@
Log.e(TAG, "Advertise app or callback is null");
return;
}
- if (DBG) {
- Log.d(TAG, "onScanParamSetupCompleted : " + status);
- }
+ Log.d(TAG, "onScanParamSetupCompleted : " + status);
}
// callback from ScanManager for dispatch of errors apps.
@@ -1103,9 +1055,7 @@
}
UUID uuid = UUID.randomUUID();
- if (DBG) {
- Log.d(TAG, "registerScanner() - UUID=" + uuid);
- }
+ Log.d(TAG, "registerScanner() - UUID=" + uuid);
enforceImpersonatationPermissionIfNeeded(workSource);
@@ -1133,9 +1083,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "unregisterScanner() - scannerId=" + scannerId);
- }
+ Log.d(TAG, "unregisterScanner() - scannerId=" + scannerId);
mScannerMap.remove(scannerId);
mScanManager.unregisterScanner(scannerId);
}
@@ -1172,9 +1120,7 @@
ScanSettings settings,
List<ScanFilter> filters,
AttributionSource attributionSource) {
- if (DBG) {
- Log.d(TAG, "start scan with filters");
- }
+ Log.d(TAG, "start scan with filters");
if (!Utils.checkScanPermissionForDataDelivery(
mContext, attributionSource, "Starting GATT scan.")) {
@@ -1236,9 +1182,7 @@
ScanSettings settings,
List<ScanFilter> filters,
AttributionSource attributionSource) {
- if (DBG) {
- Log.d(TAG, "start scan with filters, for PendingIntent");
- }
+ Log.d(TAG, "start scan with filters, for PendingIntent");
if (!Utils.checkScanPermissionForDataDelivery(
mContext, attributionSource, "Starting GATT scan.")) {
@@ -1256,14 +1200,12 @@
piInfo.filters = filters;
piInfo.callingPackage = callingPackage;
piInfo.callingUid = callingUid;
- if (DBG) {
- Log.d(
- TAG,
- "startScan(PI) -"
- + (" UUID=" + uuid)
- + (" Package=" + callingPackage)
- + (" UID=" + callingUid));
- }
+ Log.d(
+ TAG,
+ "startScan(PI) -"
+ + (" UUID=" + uuid)
+ + (" Package=" + callingPackage)
+ + (" UID=" + callingUid));
// Don't start scan if the Pi scan already in mScannerMap.
if (mScannerMap.getByContextInfo(piInfo) != null) {
@@ -1345,9 +1287,7 @@
mContext, attributionSource, "ScanHelper flushPendingBatchResults")) {
return;
}
- if (DBG) {
- Log.d(TAG, "flushPendingBatchResults - scannerId=" + scannerId);
- }
+ Log.d(TAG, "flushPendingBatchResults - scannerId=" + scannerId);
mScanManager.flushBatchScanResults(new ScanClient(scannerId));
}
@@ -1359,9 +1299,7 @@
}
int scanQueueSize =
mScanManager.getBatchScanQueue().size() + mScanManager.getRegularScanQueue().size();
- if (DBG) {
- Log.d(TAG, "stopScan() - queue size =" + scanQueueSize);
- }
+ Log.d(TAG, "stopScan() - queue size =" + scanQueueSize);
AppScanStats app = mScannerMap.getAppScanStatsById(scannerId);
if (app != null) {
@@ -1380,9 +1318,7 @@
PendingIntentInfo pii = new PendingIntentInfo();
pii.intent = intent;
ContextMap.App app = mScannerMap.getByContextInfo(pii);
- if (VDBG) {
- Log.d(TAG, "stopScan(PendingIntent): app found = " + app);
- }
+ Log.v(TAG, "stopScan(PendingIntent): app found = " + app);
if (app != null) {
intent.removeCancelListener(mScanIntentCancelListener);
final int scannerId = app.id;
@@ -1469,15 +1405,13 @@
@Override
public void binderDied() {
- if (DBG) {
- Log.d(
- TAG,
- "Binder is dead - unregistering scanner ("
- + mPackageName
- + " "
- + mScannerId
- + ")!");
- }
+ Log.d(
+ TAG,
+ "Binder is dead - unregistering scanner ("
+ + mPackageName
+ + " "
+ + mScannerId
+ + ")!");
ScanClient client = getScanClient(mScannerId);
if (client != null) {
@@ -1536,9 +1470,7 @@
*/
@SuppressLint("AndroidFrameworkRequiresPermission")
private void enforcePrivilegedPermissionIfNeeded(List<ScanFilter> filters) {
- if (DBG) {
- Log.d(TAG, "enforcePrivilegedPermissionIfNeeded(" + filters + ")");
- }
+ Log.d(TAG, "enforcePrivilegedPermissionIfNeeded(" + filters + ")");
// Some 3p API cases may have null filters, need to allow
if (filters != null) {
for (ScanFilter filter : filters) {
diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java
index 769f39a..c2e2ef9 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java
@@ -57,9 +57,9 @@
import java.util.Set;
class MapClientContent {
+ private static final String TAG = MapClientContent.class.getSimpleName();
private static final String INBOX_PATH = "telecom/msg/inbox";
- private static final String TAG = "MapClientContent";
private static final int DEFAULT_CHARSET = 106;
private static final int ORIGINATOR_ADDRESS_TYPE = 137;
private static final int RECIPIENT_ADDRESS_TYPE = 151;
@@ -135,13 +135,13 @@
@Override
public void onChange(boolean selfChange) {
- logV("onChange(self=" + selfChange + ")");
+ verbose("onChange(self=" + selfChange + ")");
findChangeInDatabase();
}
@Override
public void onChange(boolean selfChange, Uri uri) {
- logV("onChange(self=" + selfChange + ", uri=" + uri.toString() + ")");
+ verbose("onChange(self=" + selfChange + ", uri=" + uri.toString() + ")");
findChangeInDatabase();
}
};
@@ -157,7 +157,7 @@
context.getSystemService(SubscriptionManager.class);
List<SubscriptionInfo> subscriptions = subscriptionManager.getActiveSubscriptionInfoList();
if (subscriptions == null) {
- Log.w(TAG, "Active subscription list is missing");
+ Log.w(TAG, "[AllDevices] Active subscription list is missing");
return;
}
for (SubscriptionInfo info : subscriptions) {
@@ -167,26 +167,34 @@
subscriptionManager.removeSubscriptionInfoRecord(info.getIccId(),
SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM);
} catch (Exception e) {
- Log.w(TAG, "cleanUp failed: " + e.toString());
+ Log.w(TAG, "[AllDevices] cleanUp failed: " + e.toString());
}
}
}
}
- private static void logI(String message) {
- Log.i(TAG, message);
+ private void error(String message) {
+ Log.e(TAG, "[" + mDevice + "] " + message);
}
- private static void logD(String message) {
- if (MapClientService.DBG) {
- Log.d(TAG, message);
- }
+ private void warn(String message) {
+ Log.w(TAG, "[" + mDevice + "] " + message);
}
- private static void logV(String message) {
- if (MapClientService.VDBG) {
- Log.v(TAG, message);
- }
+ private void warn(String message, Exception e) {
+ Log.w(TAG, "[" + mDevice + "] " + message, e);
+ }
+
+ private void info(String message) {
+ Log.i(TAG, "[" + mDevice + "] " + message);
+ }
+
+ private void debug(String message) {
+ Log.d(TAG, "[" + mDevice + "] " + message);
+ }
+
+ private void verbose(String message) {
+ Log.v(TAG, "[" + mDevice + "] " + message);
}
/**
@@ -195,7 +203,7 @@
*/
void setRemoteDeviceOwnNumber(String phoneNumber) {
mPhoneNumber = phoneNumber;
- logV("Remote device " + mDevice.getAddress() + " phone number set to: " + mPhoneNumber);
+ verbose("Remote device " + mDevice.getAddress() + " phone number set to: " + mPhoneNumber);
}
/**
@@ -205,10 +213,8 @@
* The handle is used to associate the local message with the remote message.
*/
void storeMessage(Bmessage message, String handle, Long timestamp, boolean seen) {
- logI(
- "storeMessage(device="
- + Utils.getLoggableAddress(mDevice)
- + ", time="
+ info(
+ "storeMessage(time="
+ timestamp
+ "["
+ toDatetimeString(timestamp)
@@ -229,24 +235,24 @@
storeSms(message, handle, timestamp, seen);
return;
default:
- logD("Request to store unsupported message type: " + message.getType());
+ debug("Request to store unsupported message type: " + message.getType());
}
}
private void storeSms(Bmessage message, String handle, Long timestamp, boolean seen) {
- logD("storeSms");
- logV(message.toString());
+ debug("storeSms");
+ verbose(message.toString());
String recipients;
if (INBOX_PATH.equals(message.getFolder())) {
recipients = getOriginatorNumber(message);
} else {
recipients = getFirstRecipientNumber(message);
if (recipients == null) {
- logD("invalid recipients");
+ debug("invalid recipients");
return;
}
}
- logV("Received SMS from Number " + recipients);
+ verbose("Received SMS from Number " + recipients);
Uri contentUri = INBOX_PATH.equalsIgnoreCase(message.getFolder()) ? Sms.Inbox.CONTENT_URI
: Sms.Sent.CONTENT_URI;
@@ -265,7 +271,7 @@
Uri results = mResolver.insert(contentUri, values);
mHandleToUriMap.put(handle, results);
mUriToHandleMap.put(results, new MessageStatus(handle, readStatus));
- logD("Map InsertedThread" + results);
+ debug("Map InsertedThread" + results);
}
/**
@@ -273,7 +279,7 @@
* remove a message from the local provider based on a remote change
*/
void deleteMessage(String handle) {
- logD("deleting handle" + handle);
+ debug("deleting handle" + handle);
Uri messageToChange = mHandleToUriMap.get(handle);
if (messageToChange != null) {
mResolver.delete(messageToChange, null);
@@ -286,7 +292,7 @@
* mark a message read in the local provider based on a remote change
*/
void markRead(String handle) {
- logD("marking read " + handle);
+ debug("marking read " + handle);
Uri messageToChange = mHandleToUriMap.get(handle);
if (messageToChange != null) {
ContentValues values = new ContentValues();
@@ -315,7 +321,7 @@
int readStatus = cursor.getInt(cursor.getColumnIndex(Sms.READ));
MessageStatus currentMessage = duplicateUriToHandleMap.remove(index);
if (currentMessage != null && currentMessage.mRead != readStatus) {
- logV(currentMessage.mHandle);
+ verbose(currentMessage.mHandle);
currentMessage.mRead = readStatus;
mCallbacks.onMessageStatusChanged(
currentMessage.mHandle, BluetoothMapClient.READ);
@@ -324,7 +330,7 @@
}
}
for (HashMap.Entry record : duplicateUriToHandleMap.entrySet()) {
- logV("Deleted " + ((MessageStatus) record.getValue()).mHandle);
+ verbose("Deleted " + ((MessageStatus) record.getValue()).mHandle);
originalUriToHandleMap.remove(record.getKey());
mCallbacks.onMessageStatusChanged(((MessageStatus) record.getValue()).mHandle,
BluetoothMapClient.DELETED);
@@ -332,8 +338,8 @@
}
private void storeMms(Bmessage message, String handle, Long timestamp, boolean seen) {
- logD("storeMms");
- logV(message.toString());
+ debug("storeMms");
+ verbose(message.toString());
try {
ContentValues values = new ContentValues();
long threadId = getThreadId(message);
@@ -349,7 +355,7 @@
contentUri = Mms.Sent.CONTENT_URI;
messageBox = Mms.MESSAGE_BOX_SENT;
}
- logD("Parsed");
+ debug("Parsed");
values.put(Mms.SUBSCRIPTION_ID, mSubscriptionId);
values.put(Mms.THREAD_ID, threadId);
values.put(Mms.DATE, timestamp / 1000L);
@@ -372,7 +378,7 @@
mHandleToUriMap.put(handle, results);
mUriToHandleMap.put(results, new MessageStatus(handle, read));
- logD("Map InsertedThread" + results);
+ debug("Map InsertedThread" + results);
for (MimePart part : mmsBmessage.getMimeParts()) {
storeMmsPart(part, results);
@@ -383,7 +389,7 @@
values.put(Mms.Part.CONTENT_TYPE, "plain/text");
values.put(Mms.SUBSCRIPTION_ID, mSubscriptionId);
} catch (Exception e) {
- Log.e(TAG, e.toString());
+ error("Error while storing MMS: " + e.toString());
throw e;
}
}
@@ -400,7 +406,7 @@
Uri contentUri = Uri.parse(messageUri.toString() + "/part");
Uri results = mResolver.insert(contentUri, values);
- logD("Inserted" + results);
+ debug("Inserted" + results);
return results;
}
@@ -428,7 +434,7 @@
* clear the subscription info and content on shutdown
*/
void cleanUp() {
- logD("cleanUp(device=" + Utils.getLoggableAddress(mDevice)
+ debug("cleanUp(device=" + Utils.getLoggableAddress(mDevice)
+ "subscriptionId=" + mSubscriptionId);
mResolver.unregisterContentObserver(mContentObserver);
clearMessages(mContext, mSubscriptionId);
@@ -437,7 +443,7 @@
SubscriptionManager.SUBSCRIPTION_TYPE_REMOTE_SIM);
mSubscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
} catch (Exception e) {
- Log.w(TAG, "cleanUp failed: " + e.toString());
+ warn("cleanUp failed: " + e.toString());
}
}
@@ -446,7 +452,7 @@
* clean up the content provider on startup
*/
private static void clearMessages(Context context, int subscriptionId) {
- logD("clearMessages(subscriptionId=" + subscriptionId);
+ Log.d(TAG, "[AllDevices] clearMessages(subscriptionId=" + subscriptionId);
ContentResolver resolver = context.getContentResolver();
String threads = new String();
@@ -485,13 +491,13 @@
return Telephony.Threads.COMMON_THREAD;
} else if (messageContacts.size() > 1) {
if (mPhoneNumber == null) {
- Log.w(TAG, "getThreadId called, mPhoneNumber never found.");
+ warn("getThreadId called, mPhoneNumber never found.");
}
messageContacts.removeIf(number -> (PhoneNumberUtils.areSamePhoneNumber(number,
mPhoneNumber, mTelephonyManager.getNetworkCountryIso())));
}
- logV("Contacts = " + messageContacts.toString());
+ verbose("Contacts = " + messageContacts.toString());
return Telephony.Threads.getOrCreateThreadId(mContext, messageContacts);
}
@@ -541,8 +547,8 @@
boolean addThreadContactsToEntries(Bmessage bmsg, String thread) {
String threadId = Uri.parse(thread).getLastPathSegment();
- logD("MATCHING THREAD" + threadId);
- logD(MmsSms.CONTENT_CONVERSATIONS_URI + threadId + "/recipients");
+ debug("MATCHING THREAD" + threadId);
+ debug(MmsSms.CONTENT_CONVERSATIONS_URI + threadId + "/recipients");
try (Cursor cursor =
mResolver.query(
@@ -554,13 +560,14 @@
null)) {
if (cursor.moveToNext()) {
- logD("Columns" + Arrays.toString(cursor.getColumnNames()));
- logV("CONTACT LIST: " + cursor.getString(cursor.getColumnIndex("recipient_ids")));
+ debug("Columns" + Arrays.toString(cursor.getColumnNames()));
+ verbose("CONTACT LIST: "
+ + cursor.getString(cursor.getColumnIndex("recipient_ids")));
addRecipientsToEntries(
bmsg, cursor.getString(cursor.getColumnIndex("recipient_ids")).split(" "));
return true;
} else {
- Log.w(TAG, "Thread Not Found");
+ warn("Thread Not Found");
return false;
}
}
@@ -568,7 +575,7 @@
private void addRecipientsToEntries(Bmessage bmsg, String[] recipients) {
- logV("CONTACT LIST: " + Arrays.toString(recipients));
+ verbose("CONTACT LIST: " + Arrays.toString(recipients));
for (String recipient : recipients) {
try (Cursor cursor =
mResolver.query(
@@ -579,7 +586,7 @@
null)) {
while (cursor.moveToNext()) {
String number = cursor.getString(cursor.getColumnIndex(Mms.Addr.ADDRESS));
- logV("CONTACT number: " + number);
+ verbose("CONTACT number: " + number);
VCardEntry destEntry = new VCardEntry();
VCardProperty destEntryPhone = new VCardProperty();
destEntryPhone.setName(VCardConstants.PROPERTY_TEL);
@@ -597,7 +604,7 @@
*/
private int getStoredMessagesCount(Uri uri) {
if (mSubscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
- logV("getStoredMessagesCount(uri=" + uri + "): Failed, no subscription ID");
+ verbose("getStoredMessagesCount(uri=" + uri + "): Failed, no subscription ID");
return 0;
}
@@ -636,7 +643,7 @@
smsUri = Sms.Sent.CONTENT_URI;
mmsUri = Mms.Sent.CONTENT_URI;
} else {
- Log.w(TAG, "getRecentMessagesFromFolder: Failed, unsupported folder=" + folder);
+ warn("getRecentMessagesFromFolder: Failed, unsupported folder=" + folder);
return null;
}
@@ -644,7 +651,7 @@
for (Uri uri : new Uri[] {smsUri, mmsUri}) {
messages.addAll(getMessagesFromUri(uri));
}
- logV(
+ verbose(
"getRecentMessagesFromFolder: "
+ folder
+ ", "
@@ -659,17 +666,17 @@
}
private List<MessageDumpElement> getMessagesFromUri(Uri uri) {
- logD("getMessagesFromUri: uri=" + uri);
+ debug("getMessagesFromUri: uri=" + uri);
ArrayList<MessageDumpElement> messages = new ArrayList<MessageDumpElement>();
if (mSubscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
- Log.w(TAG, "getMessagesFromUri: Failed, no subscription ID");
+ warn("getMessagesFromUri: Failed, no subscription ID");
return messages;
}
Type type = getMessageTypeFromUri(uri);
if (type == Type.UNKNOWN) {
- Log.w(TAG, "getMessagesFromUri: unknown message type");
+ warn("getMessagesFromUri: unknown message type");
return messages;
}
@@ -702,10 +709,10 @@
try {
if (cursor == null) {
- Log.w(TAG, "getMessagesFromUri: null cursor for uri=" + uri);
+ warn("getMessagesFromUri: null cursor for uri=" + uri);
return messages;
}
- logV("Number of rows in cursor = " + cursor.getCount() + ", for uri=" + uri);
+ verbose("Number of rows in cursor = " + cursor.getCount() + ", for uri=" + uri);
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
@@ -724,7 +731,7 @@
MessageStatus handleAndStatus = mUriToHandleMap.get(messageUri);
String messageHandle = "<unknown>";
if (handleAndStatus == null) {
- Log.w(TAG, "getMessagesFromUri: no entry for message uri=" + messageUri);
+ warn("getMessagesFromUri: no entry for message uri=" + messageUri);
} else {
messageHandle = handleAndStatus.mHandle;
}
@@ -745,7 +752,7 @@
type));
}
} catch (Exception e) {
- Log.w(TAG, "Exception when querying db for dumpsys", e);
+ warn("Exception when querying db for dumpsys", e);
} finally {
cursor.close();
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
index cf6e1e6..7b85fec 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
@@ -51,10 +51,7 @@
import java.util.concurrent.ConcurrentHashMap;
public class MapClientService extends ProfileService {
- private static final String TAG = "MapClientService";
-
- static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
+ private static final String TAG = MapClientService.class.getSimpleName();
static final int MAXIMUM_CONNECTED_DEVICES = 4;
@@ -99,9 +96,7 @@
@VisibleForTesting
static synchronized void setMapClientService(MapClientService instance) {
- if (DBG) {
- Log.d(TAG, "setMapClientService(): set to: " + instance);
- }
+ Log.d(TAG, "setMapClientService(): set to: " + instance);
sMapClientService = instance;
}
@@ -123,9 +118,7 @@
if (device == null) {
throw new IllegalArgumentException("Null device");
}
- if (DBG) {
- Log.d(TAG, "connect(device= " + device + "): devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "connect(device= " + device + "): devices=" + mMapInstanceMap.keySet());
if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
Log.w(TAG, "Connection not allowed: <" + device.getAddress()
+ "> is CONNECTION_POLICY_FORBIDDEN");
@@ -162,16 +155,12 @@
// Statemachine exists but not in connecting or connected state! it should
// have been removed form the map. lets get rid of it and add a new one.
- if (DBG) {
- Log.d(TAG, "Statemachine exists for a device in unexpected state: " + state);
- }
+ Log.d(TAG, "Statemachine exists for a device in unexpected state: " + state);
mMapInstanceMap.remove(device);
mapStateMachine.doQuit();
addDeviceToMapAndConnect(device);
- if (DBG) {
- Log.d(TAG, "connect(device= " + device + "): end devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "connect(device= " + device + "): end devices=" + mMapInstanceMap.keySet());
return true;
}
@@ -188,9 +177,7 @@
public synchronized boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "disconnect(device= " + device + "): devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "disconnect(device= " + device + "): devices=" + mMapInstanceMap.keySet());
MceStateMachine mapStateMachine = mMapInstanceMap.get(device);
// a map state machine instance doesn't exist. maybe it is already gone?
if (mapStateMachine == null) {
@@ -202,10 +189,8 @@
return false;
}
mapStateMachine.disconnect();
- if (DBG) {
- Log.d(TAG, "disconnect(device= " + device + "): end devices="
- + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "disconnect(device= " + device + "): end devices="
+ + mMapInstanceMap.keySet());
return true;
}
@@ -218,20 +203,20 @@
}
public synchronized List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
- if (DBG) Log.d(TAG, "getDevicesMatchingConnectionStates" + Arrays.toString(states));
+ Log.d(TAG, "getDevicesMatchingConnectionStates" + Arrays.toString(states));
List<BluetoothDevice> deviceList = new ArrayList<>();
BluetoothDevice[] bondedDevices = mAdapterService.getBondedDevices();
int connectionState;
for (BluetoothDevice device : bondedDevices) {
connectionState = getConnectionState(device);
- if (DBG) Log.d(TAG, "Device: " + device + "State: " + connectionState);
+ Log.d(TAG, "Device: " + device + "State: " + connectionState);
for (int i = 0; i < states.length; i++) {
if (connectionState == states[i]) {
deviceList.add(device);
}
}
}
- if (DBG) Log.d(TAG, deviceList.toString());
+ Log.d(TAG, deviceList.toString());
return deviceList;
}
@@ -259,9 +244,7 @@
*/
@RequiresPermission(android.Manifest.permission.BLUETOOTH_PRIVILEGED)
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
- if (VDBG) {
- Log.v(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.v(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
@@ -310,7 +293,7 @@
@Override
public synchronized void start() {
- Log.e(TAG, "start()");
+ Log.d(TAG, "start()");
mAdapterService = AdapterService.getAdapterService();
mDatabaseManager = Objects.requireNonNull(AdapterService.getAdapterService().getDatabase(),
@@ -329,9 +312,7 @@
@Override
public synchronized void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (mMnsServer != null) {
mMnsServer.stop();
@@ -353,9 +334,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "in Cleanup");
- }
+ Log.d(TAG, "cleanup");
removeUncleanAccounts();
// TODO(b/72948646): should be moved to stop()
setMapClientService(null);
@@ -369,9 +348,7 @@
*/
@VisibleForTesting
public void cleanupDevice(BluetoothDevice device, MceStateMachine sm) {
- if (DBG) {
- Log.d(TAG, "cleanup(device= " + device + "): devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "cleanup(device= " + device + "): devices=" + mMapInstanceMap.keySet());
synchronized (mMapInstanceMap) {
MceStateMachine stateMachine = mMapInstanceMap.get(device);
if (stateMachine != null) {
@@ -383,16 +360,12 @@
}
}
}
- if (DBG) {
- Log.d(TAG, "cleanup(device= " + device + "): end devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "cleanup(device= " + device + "): end devices=" + mMapInstanceMap.keySet());
}
@VisibleForTesting
void removeUncleanAccounts() {
- if (DBG) {
- Log.d(TAG, "removeUncleanAccounts(): devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "removeUncleanAccounts(): devices=" + mMapInstanceMap.keySet());
Iterator iterator = mMapInstanceMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<BluetoothDevice, MceStateMachine> profileConnection =
@@ -401,9 +374,7 @@
iterator.remove();
}
}
- if (DBG) {
- Log.d(TAG, "removeUncleanAccounts(): end devices=" + mMapInstanceMap.keySet());
- }
+ Log.d(TAG, "removeUncleanAccounts(): end devices=" + mMapInstanceMap.keySet());
}
public synchronized boolean getUnreadMessages(BluetoothDevice device) {
@@ -422,7 +393,7 @@
public synchronized int getSupportedFeatures(BluetoothDevice device) {
MceStateMachine mapStateMachine = mMapInstanceMap.get(device);
if (mapStateMachine == null) {
- if (DBG) Log.d(TAG, "in getSupportedFeatures, returning 0");
+ Log.d(TAG, "in getSupportedFeatures, returning 0");
return 0;
}
return mapStateMachine.getSupportedFeatures();
@@ -455,9 +426,7 @@
private MapClientService mService;
Binder(MapClientService service) {
- if (VDBG) {
- Log.v(TAG, "Binder()");
- }
+ Log.v(TAG, "Binder()");
mService = service;
}
@@ -483,9 +452,7 @@
@Override
public void isConnected(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "isConnected()");
- }
+ Log.v(TAG, "isConnected()");
try {
MapClientService service = getService(source);
boolean result = false;
@@ -501,9 +468,7 @@
@Override
public void connect(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "connect()");
- }
+ Log.v(TAG, "connect()");
try {
MapClientService service = getService(source);
boolean result = false;
@@ -519,9 +484,7 @@
@Override
public void disconnect(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "disconnect()");
- }
+ Log.v(TAG, "disconnect()");
try {
MapClientService service = getService(source);
boolean result = false;
@@ -537,9 +500,7 @@
@Override
public void getConnectedDevices(AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "getConnectedDevices()");
- }
+ Log.v(TAG, "getConnectedDevices()");
try {
MapClientService service = getService(source);
List<BluetoothDevice> connectedDevices = new ArrayList<BluetoothDevice>(0);
@@ -555,9 +516,7 @@
@Override
public void getDevicesMatchingConnectionStates(int[] states,
AttributionSource source, SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "getDevicesMatchingConnectionStates()");
- }
+ Log.v(TAG, "getDevicesMatchingConnectionStates()");
try {
MapClientService service = getService(source);
List<BluetoothDevice> devices = new ArrayList<BluetoothDevice>(0);
@@ -573,9 +532,7 @@
@Override
public void getConnectionState(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "getConnectionState()");
- }
+ Log.v(TAG, "getConnectionState()");
try {
MapClientService service = getService(source);
int state = BluetoothProfile.STATE_DISCONNECTED;
@@ -591,9 +548,7 @@
@Override
public void setConnectionPolicy(BluetoothDevice device, int connectionPolicy,
AttributionSource source, SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "setConnectionPolicy()");
- }
+ Log.v(TAG, "setConnectionPolicy()");
try {
MapClientService service = getService(source);
boolean result = false;
@@ -609,9 +564,7 @@
@Override
public void getConnectionPolicy(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "getConnectionPolicy()");
- }
+ Log.v(TAG, "getConnectionPolicy()");
try {
MapClientService service = getService(source);
int policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
@@ -628,14 +581,12 @@
public void sendMessage(BluetoothDevice device, Uri[] contacts, String message,
PendingIntent sentIntent, PendingIntent deliveredIntent, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "sendMessage()");
- }
+ Log.v(TAG, "sendMessage()");
try {
MapClientService service = getService(source);
boolean result = false;
if (service != null) {
- if (DBG) Log.d(TAG, "Checking Permission of sendMessage");
+ Log.d(TAG, "Checking Permission of sendMessage");
service.enforceCallingOrSelfPermission(Manifest.permission.SEND_SMS,
"Need SEND_SMS permission");
result = service.sendMessage(device, contacts, message, sentIntent,
@@ -650,9 +601,7 @@
@Override
public void getUnreadMessages(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "getUnreadMessages()");
- }
+ Log.v(TAG, "getUnreadMessages()");
try {
MapClientService service = getService(source);
boolean result = false;
@@ -670,15 +619,13 @@
@Override
public void getSupportedFeatures(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "getSupportedFeatures()");
- }
+ Log.v(TAG, "getSupportedFeatures()");
try {
MapClientService service = getService(source);
int feature = 0;
if (service != null) {
feature = service.getSupportedFeatures(device);
- } else if (DBG) {
+ } else {
Log.d(TAG, "in MapClientService getSupportedFeatures stub, returning 0");
}
receiver.send(feature);
@@ -690,9 +637,7 @@
@Override
public void setMessageStatus(BluetoothDevice device, String handle, int status,
AttributionSource source, SynchronousResultReceiver receiver) {
- if (VDBG) {
- Log.v(TAG, "setMessageStatus()");
- }
+ Log.v(TAG, "setMessageStatus()");
try {
MapClientService service = getService(source);
boolean result = false;
@@ -739,9 +684,7 @@
private void handleSdpSearchRecordReceived(
BluetoothDevice device, int status, Parcelable record, ParcelUuid uuid) {
MceStateMachine stateMachine = mMapInstanceMap.get(device);
- if (DBG) {
- Log.d(TAG, "Received SDP Record, device=" + device.toString() + ", uuid=" + uuid);
- }
+ Log.d(TAG, "Received SDP Record, device=" + device.toString() + ", uuid=" + uuid);
if (stateMachine == null) {
Log.e(TAG, "No Statemachine found for the device=" + device.toString());
return;
@@ -749,9 +692,7 @@
if (uuid.equals(BluetoothUuid.MAS)) {
// Check if we have a valid SDP record.
SdpMasRecord masRecord = (SdpMasRecord) record;
- if (DBG) {
- Log.d(TAG, "SDP complete, status: " + status + ", record:" + masRecord);
- }
+ Log.d(TAG, "SDP complete, status: " + status + ", record:" + masRecord);
stateMachine.sendSdpResult(status, masRecord);
}
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MasClient.java b/android/app/src/com/android/bluetooth/mapclient/MasClient.java
index fcbf764..b0a2c42 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MasClient.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MasClient.java
@@ -39,11 +39,11 @@
* construction. After use shutdown() must be called to properly clean up.
*/
public class MasClient {
+ private static final String TAG = MasClient.class.getSimpleName();
+
private static final int CONNECT = 0;
private static final int DISCONNECT = 1;
private static final int REQUEST = 2;
- private static final String TAG = "MasClient";
- private static final boolean DBG = MapClientService.DBG;
private static final byte[] BLUETOOTH_UUID_OBEX_MAS = new byte[]{
(byte) 0xbb,
0x58,
@@ -107,18 +107,14 @@
int l2capSocket = mSdpMasRecord.getL2capPsm();
if (l2capSocket != L2CAP_INVALID_PSM) {
- if (DBG) {
- Log.d(TAG, "Connecting to OBEX on L2CAP channel " + l2capSocket);
- }
+ Log.d(TAG, "Connecting to OBEX on L2CAP channel " + l2capSocket);
mSocket = mRemoteDevice.createL2capSocket(l2capSocket);
} else {
- if (DBG) {
- Log.d(TAG, "Connecting to OBEX on RFCOM channel "
- + mSdpMasRecord.getRfcommCannelNumber());
- }
+ Log.d(TAG, "Connecting to OBEX on RFCOM channel "
+ + mSdpMasRecord.getRfcommCannelNumber());
mSocket = mRemoteDevice.createRfcommSocket(mSdpMasRecord.getRfcommCannelNumber());
}
- if (DBG) Log.d(TAG, mRemoteDevice.toString() + "Socket: " + mSocket.toString());
+ Log.d(TAG, mRemoteDevice.toString() + "Socket: " + mSocket.toString());
mSocket.connect();
mTransport = new BluetoothObexTransport(mSocket);
@@ -132,12 +128,10 @@
oap.addToHeaderSet(headerset);
headerset = mSession.connect(headerset);
- if (DBG) Log.d(TAG, "Connection results" + headerset.getResponseCode());
+ Log.d(TAG, "Connection results" + headerset.getResponseCode());
if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK) {
- if (DBG) {
- Log.d(TAG, "Connection Successful");
- }
+ Log.d(TAG, "Connection Successful");
mConnected = true;
mCallback.sendMessage(MceStateMachine.MSG_MAS_CONNECTED);
} else {
@@ -174,18 +168,14 @@
request.execute(mSession);
mCallback.sendMessage(MceStateMachine.MSG_MAS_REQUEST_COMPLETED, request);
} catch (IOException e) {
- if (DBG) {
- Log.d(TAG, "Request failed: " + request);
- }
+ Log.d(TAG, "Request failed: " + request);
// Disconnect to cleanup.
disconnect();
}
}
public boolean makeRequest(Request request) {
- if (DBG) {
- Log.d(TAG, "makeRequest called with: " + request);
- }
+ Log.d(TAG, "makeRequest called with: " + request);
boolean status = mHandler.sendMessage(mHandler.obtainMessage(REQUEST, request));
if (!status) {
@@ -201,9 +191,7 @@
* @param request The {@link Request} to abort.
*/
public void abortRequest(Request request) {
- if (DBG) {
- Log.d(TAG, "abortRequest called with: " + request);
- }
+ Log.d(TAG, "abortRequest called with: " + request);
request.abort();
mHandler.removeMessages(REQUEST, request);
diff --git a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
index 4beab6a..0f99928 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
@@ -90,6 +90,8 @@
* messages is sent.
*/
class MceStateMachine extends StateMachine {
+ private static final String TAG = MceStateMachine.class.getSimpleName();
+
// Messages for events handled by the StateMachine
static final int MSG_MAS_CONNECTED = 1001;
static final int MSG_MAS_DISCONNECTED = 1002;
@@ -106,9 +108,6 @@
static final int MSG_SET_MESSAGE_STATUS = 2006;
static final int MSG_SEARCH_OWN_NUMBER_TIMEOUT = 2007;
- private static final String TAG = "MceStateMachine";
- private static final Boolean DBG = MapClientService.DBG;
- private static final Boolean VDBG = MapClientService.VDBG;
// SAVE_OUTBOUND_MESSAGES defaults to true to place the responsibility of managing content on
// Bluetooth, to work with the default Car Messenger. This may need to be set to false if the
// messaging app takes that responsibility.
@@ -295,10 +294,8 @@
if (mDevice == null) {
return;
}
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + ": Connection state changed, prev="
- + prevState + ", new=" + state);
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + ": Connection state changed, prev="
+ + prevState + ", new=" + state);
if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.MAP_CLIENT);
}
@@ -332,9 +329,7 @@
* Notify of SDP completion.
*/
public void sendSdpResult(int status, SdpMasRecord record) {
- if (DBG) {
- Log.d(TAG, "Received SDP Result, status=" + status + ", record=" + record);
- }
+ Log.d(TAG, "Received SDP Result, status=" + status + ", record=" + record);
if (status != SDP_SUCCESS || record == null) {
Log.w(TAG, "SDP unsuccessful, status: " + status + ", record: " + record);
sendMessage(MceStateMachine.MSG_MAS_SDP_UNSUCCESSFUL, status);
@@ -344,18 +339,14 @@
}
public boolean disconnect() {
- if (DBG) {
- Log.d(TAG, "Disconnect Request " + mDevice);
- }
+ Log.d(TAG, "Disconnect Request " + mDevice);
sendMessage(MSG_DISCONNECT, mDevice);
return true;
}
public synchronized boolean sendMapMessage(Uri[] contacts, String message,
PendingIntent sentIntent, PendingIntent deliveredIntent) {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + ": Send, message=" + message);
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + ": Send, message=" + message);
if (contacts == null || contacts.length <= 0) {
return false;
}
@@ -367,9 +358,7 @@
for (Uri contact : contacts) {
// Who to send the message to.
- if (VDBG) {
- Log.d(TAG, "Scheme " + contact.getScheme());
- }
+ Log.v(TAG, "Scheme " + contact.getScheme());
if (PhoneAccount.SCHEME_TEL.equals(contact.getScheme())) {
String path = contact.getPath();
if (path != null && path.contains(Telephony.Threads.CONTENT_URI.toString())) {
@@ -381,9 +370,7 @@
destEntryPhone.addValues(contact.getSchemeSpecificPart());
destEntry.addProperty(destEntryPhone);
bmsg.addRecipient(destEntry);
- if (VDBG) {
- Log.d(TAG, "Sending to phone numbers " + destEntryPhone.getValueList());
- }
+ Log.v(TAG, "Sending to phone numbers " + destEntryPhone.getValueList());
}
} else if (SCHEME_MAILTO.equals(contact.getScheme())) {
VCardEntry destEntry = new VCardEntry();
@@ -393,10 +380,8 @@
destEntry.addProperty(destEntryContact);
bmsg.addRecipient(destEntry);
Log.d(TAG, "SPECIFIC: " + contact.getSchemeSpecificPart());
- if (DBG) {
- Log.d(TAG, "Sending to emails "
- + destEntryContact.getValueList());
- }
+ Log.d(TAG, "Sending to emails "
+ + destEntryContact.getValueList());
} else {
Log.w(TAG, "Scheme " + contact.getScheme() + " not supported.");
return false;
@@ -418,9 +403,7 @@
}
synchronized boolean getMessage(String handle) {
- if (DBG) {
- Log.d(TAG, "getMessage" + handle);
- }
+ Log.d(TAG, "getMessage" + handle);
if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
sendMessage(MSG_INBOUND_MESSAGE, handle);
return true;
@@ -429,9 +412,7 @@
}
synchronized boolean getUnreadMessages() {
- if (DBG) {
- Log.d(TAG, "getMessage");
- }
+ Log.d(TAG, "getMessage");
if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
sendMessage(MSG_GET_MESSAGE_LISTING, FOLDER_INBOX);
return true;
@@ -441,17 +422,15 @@
synchronized int getSupportedFeatures() {
if (mMostRecentState == BluetoothProfile.STATE_CONNECTED && mMasClient != null) {
- if (DBG) Log.d(TAG, "returning getSupportedFeatures from SDP record");
+ Log.d(TAG, "returning getSupportedFeatures from SDP record");
return mMasClient.getSdpMasRecord().getSupportedFeatures();
}
- if (DBG) Log.d(TAG, "in getSupportedFeatures, returning 0");
+ Log.d(TAG, "getSupportedFeatures: no connection, returning 0");
return 0;
}
synchronized boolean setMessageStatus(String handle, int status) {
- if (DBG) {
- Log.d(TAG, "setMessageStatus(" + handle + ", " + status + ")");
- }
+ Log.d(TAG, "setMessageStatus(" + handle + ", " + status + ")");
if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
RequestSetMessageStatus.StatusIndicator statusIndicator;
byte value;
@@ -534,10 +513,8 @@
class Disconnected extends State {
@Override
public void enter() {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Disconnected]: Entered, message="
- + getMessageName(getCurrentMessage().what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Disconnected]: Entered, message="
+ + getMessageName(getCurrentMessage().what));
onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTED);
mPreviousState = BluetoothProfile.STATE_DISCONNECTED;
quit();
@@ -552,10 +529,8 @@
class Connecting extends State {
@Override
public void enter() {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connecting]: Entered, message="
- + getMessageName(getCurrentMessage().what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connecting]: Entered, message="
+ + getMessageName(getCurrentMessage().what));
onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTING);
// When commanded to connect begin SDP to find the MAS server.
@@ -566,10 +541,8 @@
@Override
public boolean processMessage(Message message) {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connecting]: Received "
- + getMessageName(message.what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connecting]: Received "
+ + getMessageName(message.what));
switch (message.what) {
case MSG_MAS_SDP_DONE:
@@ -591,19 +564,15 @@
Log.i(TAG, Utils.getLoggableAddress(mDevice)
+ " [Connecting]: SDP unsuccessful, status=" + sdpStatus);
if (sdpStatus == SDP_BUSY) {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice)
- + " [Connecting]: SDP was busy, try again");
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice)
+ + " [Connecting]: SDP was busy, try again");
mDevice.sdpSearch(BluetoothUuid.MAS);
} else {
// This means the status is 0 (success, but no record) or 1 (organic
// failure). We historically have never retried SDP in failure cases, so we
// don't need to wait for the timeout anymore.
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice)
- + " [Connecting]: SDP failed completely, disconnecting");
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice)
+ + " [Connecting]: SDP failed completely, disconnecting");
transitionTo(mDisconnecting);
}
break;
@@ -646,10 +615,8 @@
class Connected extends State {
@Override
public void enter() {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connected]: Entered, message="
- + getMessageName(getCurrentMessage().what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connected]: Entered, message="
+ + getMessageName(getCurrentMessage().what));
MapClientContent.Callbacks callbacks = new MapClientContent.Callbacks(){
@Override
@@ -687,10 +654,8 @@
@Override
public boolean processMessage(Message message) {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connected]: Received "
- + getMessageName(message.what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Connected]: Received "
+ + getMessageName(message.what));
switch (message.what) {
case MSG_DISCONNECT:
if (mDevice.equals(message.obj)) {
@@ -883,9 +848,7 @@
mDatabase.deleteMessage(event.getHandle());
break;
default:
- if (DBG) {
- Log.d(TAG, "processNotification: ignoring event type=" + event.getType());
- }
+ Log.d(TAG, "processNotification: ignoring event type=" + event.getType());
}
}
@@ -909,10 +872,8 @@
// oldest first. Iterate in reverse order so we initiate requests oldest first.
for (int i = messageListing.size() - 1; i >= 0; i--) {
com.android.bluetooth.mapclient.Message msg = messageListing.get(i);
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice)
- + " [Connected]: fetch message content, handle=" + msg.getHandle());
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice)
+ + " [Connected]: fetch message content, handle=" + msg.getHandle());
// A message listing coming from the server should always have up to date data
if (msg.getDateTime() == null) {
Log.w(TAG, "message with handle " + msg.getHandle()
@@ -940,15 +901,11 @@
RequestGetMessagesListingForOwnNumber request) {
if (request.isSearchCompleted()) {
- if (DBG) {
- Log.d(TAG, "processMessageListingForOwnNumber: search completed");
- }
+ Log.d(TAG, "processMessageListingForOwnNumber: search completed");
if (request.getOwnNumber() != null) {
// A phone number was found (should be the remote device's).
- if (DBG) {
- Log.d(TAG, "processMessageListingForOwnNumber: number found = "
- + request.getOwnNumber());
- }
+ Log.d(TAG, "processMessageListingForOwnNumber: number found = "
+ + request.getOwnNumber());
mDatabase.setRemoteDeviceOwnNumber(request.getOwnNumber());
}
// Remove any outstanding timeouts from state machine queue
@@ -959,9 +916,7 @@
} else {
// A phone number wasn't found, but there are still additional messages that can
// be requested and searched.
- if (DBG) {
- Log.d(TAG, "processMessageListingForOwnNumber: continuing search");
- }
+ Log.d(TAG, "processMessageListingForOwnNumber: continuing search");
mMasClient.makeRequest(request);
}
}
@@ -978,9 +933,7 @@
}
private void processSetMessageStatus(RequestSetMessageStatus request) {
- if (DBG) {
- Log.d(TAG, "processSetMessageStatus");
- }
+ Log.d(TAG, "processSetMessageStatus");
int result = BluetoothMapClient.RESULT_SUCCESS;
if (!request.isSuccess()) {
Log.e(TAG, "Set message status failed");
@@ -1026,9 +979,7 @@
*/
private void processInboundMessage(RequestGetMessage request) {
Bmessage message = request.getMessage();
- if (DBG) {
- Log.d(TAG, "Notify inbound Message" + message);
- }
+ Log.d(TAG, "Notify inbound Message" + message);
if (message == null) {
return;
@@ -1037,20 +988,16 @@
mMessages.get(request.getHandle()).getTimestamp(),
mMessages.get(request.getHandle()).getSeen());
if (!INBOX_PATH.equalsIgnoreCase(message.getFolder())) {
- if (DBG) {
- Log.d(TAG, "Ignoring message received in " + message.getFolder() + ".");
- }
+ Log.d(TAG, "Ignoring message received in " + message.getFolder() + ".");
return;
}
switch (message.getType()) {
case SMS_CDMA:
case SMS_GSM:
case MMS:
- if (DBG) {
- Log.d(TAG, "Body: " + message.getBodyContent());
- Log.d(TAG, message.toString());
- Log.d(TAG, "Recipients" + message.getRecipients().toString());
- }
+ Log.d(TAG, "Body: " + message.getBodyContent());
+ Log.d(TAG, message.toString());
+ Log.d(TAG, "Recipients" + message.getRecipients().toString());
// Grab the message metadata and update the cached read status from the bMessage
MessageMetadata metadata = mMessages.get(request.getHandle());
@@ -1067,23 +1014,17 @@
intent.putExtra(android.content.Intent.EXTRA_TEXT, message.getBodyContent());
VCardEntry originator = message.getOriginator();
if (originator != null) {
- if (DBG) {
- Log.d(TAG, originator.toString());
- }
+ Log.d(TAG, originator.toString());
List<VCardEntry.PhoneData> phoneData = originator.getPhoneList();
List<VCardEntry.EmailData> emailData = originator.getEmailList();
if (phoneData != null && phoneData.size() > 0) {
String phoneNumber = phoneData.get(0).getNumber();
- if (DBG) {
- Log.d(TAG, "Originator number: " + phoneNumber);
- }
+ Log.d(TAG, "Originator number: " + phoneNumber);
intent.putExtra(BluetoothMapClient.EXTRA_SENDER_CONTACT_URI,
getContactURIFromPhone(phoneNumber));
} else if (emailData != null && emailData.size() > 0) {
String email = emailData.get(0).getAddress();
- if (DBG) {
- Log.d(TAG, "Originator email: " + email);
- }
+ Log.d(TAG, "Originator email: " + email);
intent.putExtra(BluetoothMapClient.EXTRA_SENDER_CONTACT_URI,
getContactURIFromEmail(email));
}
@@ -1143,9 +1084,7 @@
List<VCardEntry.PhoneData> phoneData = recipient.getPhoneList();
if (phoneData != null && phoneData.size() > 0) {
String phoneNumber = phoneData.get(0).getNumber();
- if (DBG) {
- Log.d(TAG, "CC Recipient number: " + phoneNumber);
- }
+ Log.d(TAG, "CC Recipient number: " + phoneNumber);
uris.add(getContactURIFromPhone(phoneNumber));
}
}
@@ -1154,9 +1093,7 @@
}
private void notifySentMessageStatus(String handle, EventReport.Type status) {
- if (DBG) {
- Log.d(TAG, "got a status for " + handle + " Status = " + status);
- }
+ Log.d(TAG, "got a status for " + handle + " Status = " + status);
// some test devices don't populate messageHandle field.
// in such cases, ignore such messages.
if (handle == null || handle.length() <= 2) return;
@@ -1173,9 +1110,7 @@
if (intentToSend != null) {
try {
- if (DBG) {
- Log.d(TAG, "*******Sending " + intentToSend);
- }
+ Log.d(TAG, "*******Sending " + intentToSend);
int result = Activity.RESULT_OK;
if (status == EventReport.Type.SENDING_FAILURE
|| status == EventReport.Type.DELIVERY_FAILURE) {
@@ -1195,10 +1130,8 @@
class Disconnecting extends State {
@Override
public void enter() {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Disconnecting]: Entered, message="
- + getMessageName(getCurrentMessage().what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Disconnecting]: Entered, message="
+ + getMessageName(getCurrentMessage().what));
onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTING);
@@ -1214,10 +1147,8 @@
@Override
public boolean processMessage(Message message) {
- if (DBG) {
- Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Disconnecting]: Received "
- + getMessageName(message.what));
- }
+ Log.d(TAG, Utils.getLoggableAddress(mDevice) + " [Disconnecting]: Received "
+ + getMessageName(message.what));
switch (message.what) {
case MSG_DISCONNECTING_TIMEOUT:
case MSG_MAS_DISCONNECTED:
@@ -1247,10 +1178,8 @@
}
void receiveEvent(EventReport ev) {
- if (DBG) {
- Log.d(TAG, "Message Type = " + ev.getType()
- + ", Message handle = " + ev.getHandle());
- }
+ Log.d(TAG, "Message Type = " + ev.getType()
+ + ", Message handle = " + ev.getHandle());
sendMessage(MSG_NOTIFICATION, ev);
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java b/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java
index 34088ab..3018bf0 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java
@@ -30,9 +30,7 @@
import java.util.Arrays;
class MnsObexServer extends ServerRequestHandler {
-
- private static final String TAG = "MnsObexServer";
- private static final boolean VDBG = MapClientService.VDBG;
+ private static final String TAG = MnsObexServer.class.getSimpleName();
@VisibleForTesting
static final byte[] MNS_TARGET = new byte[]{
@@ -66,9 +64,7 @@
@Override
public int onConnect(final HeaderSet request, HeaderSet reply) {
- if (VDBG) {
- Log.v(TAG, "onConnect");
- }
+ Log.v(TAG, "onConnect");
try {
byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
@@ -87,9 +83,7 @@
@Override
public void onDisconnect(final HeaderSet request, HeaderSet reply) {
- if (VDBG) {
- Log.v(TAG, "onDisconnect");
- }
+ Log.v(TAG, "onDisconnect");
MceStateMachine currentStateMachine = mStateMachineReference.get();
if (currentStateMachine != null) {
currentStateMachine.disconnect();
@@ -98,17 +92,13 @@
@Override
public int onGet(final Operation op) {
- if (VDBG) {
- Log.v(TAG, "onGet");
- }
+ Log.v(TAG, "onGet");
return ResponseCodes.OBEX_HTTP_BAD_REQUEST;
}
@Override
public int onPut(final Operation op) {
- if (VDBG) {
- Log.v(TAG, "onPut");
- }
+ Log.v(TAG, "onPut");
try {
HeaderSet headerset;
@@ -136,25 +126,19 @@
@Override
public int onAbort(final HeaderSet request, HeaderSet reply) {
- if (VDBG) {
- Log.v(TAG, "onAbort");
- }
+ Log.v(TAG, "onAbort");
return ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED;
}
@Override
public int onSetPath(final HeaderSet request, HeaderSet reply, final boolean backup,
final boolean create) {
- if (VDBG) {
- Log.v(TAG, "onSetPath");
- }
+ Log.v(TAG, "onSetPath");
return ResponseCodes.OBEX_HTTP_BAD_REQUEST;
}
@Override
public void onClose() {
- if (VDBG) {
- Log.v(TAG, "onClose");
- }
+ Log.v(TAG, "onClose");
}
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MnsService.java b/android/app/src/com/android/bluetooth/mapclient/MnsService.java
index 9739b71..afebd7c 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MnsService.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MnsService.java
@@ -34,12 +34,11 @@
* Message Notification Server implementation
*/
public class MnsService {
+ private static final String TAG = MnsService.class.getSimpleName();
+
static final int MSG_EVENT = 1;
/* for Client */
static final int EVENT_REPORT = 1001;
- private static final String TAG = "MnsService";
- private static final Boolean DBG = MapClientService.DBG;
- private static final Boolean VDBG = MapClientService.VDBG;
/* MAP version 1.4 */
private static final int MNS_VERSION = 0x0104;
/* these are shared across instances */
@@ -51,9 +50,7 @@
private int mSdpHandle = -1;
MnsService(MapClientService context) {
- if (VDBG) {
- Log.v(TAG, "MnsService()");
- }
+ Log.v(TAG, "MnsService()");
sContext = context;
sAcceptThread = new SocketAcceptor();
sServerSockets = ObexServerSockets.create(sAcceptThread);
@@ -72,9 +69,7 @@
}
void stop() {
- if (VDBG) {
- Log.v(TAG, "stop()");
- }
+ Log.v(TAG, "stop()");
mShutdown = true;
cleanUpSdpRecord();
if (sServerSockets != null) {
@@ -117,15 +112,13 @@
Log.e(TAG, "OnAcceptFailed");
sServerSockets = null; // Will cause a new to be created when calling start.
if (mShutdown) {
- Log.e(TAG, "Failed to accept incomming connection - " + "shutdown");
+ Log.e(TAG, "Failed to accept incoming connection - shutdown");
}
}
@Override
public synchronized boolean onConnect(BluetoothDevice device, BluetoothSocket socket) {
- if (DBG) {
- Log.d(TAG, "onConnect" + device + " SOCKET: " + socket);
- }
+ Log.d(TAG, "onConnect" + device + " SOCKET: " + socket);
/* Signal to the service that we have received an incoming connection.*/
MceStateMachine stateMachine = sContext.getMceStateMachineForDevice(device);
if (stateMachine == null) {
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 0c5ef67..70a18f2 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageParser.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageParser.java
@@ -35,8 +35,7 @@
/* BMessage as defined by MAP_SPEC_V101 Section 3.1.3 Message format (x-bt/message) */
class BmessageParser {
- private static final String TAG = "BmessageParser";
- private static final boolean DBG = MapClientService.DBG;
+ private static final String TAG = BmessageParser.class.getSimpleName();
private static final String CRLF = "\r\n";
@@ -72,9 +71,7 @@
public static Bmessage createBmessage(String str) {
BmessageParser p = new BmessageParser();
- if (DBG) {
- Log.d(TAG, "actual wired contents: " + str);
- }
+ Log.d(TAG, "actual wired contents: " + str);
try {
p.parse(str);
@@ -291,12 +288,10 @@
* UTF-8 as the MCE is not obliged to support native charset.
*
* 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.
+ * not always UTF-8, downgrading log message from ERROR to INFO.
*/
if (!"UTF-8".equals(mBmsg.mBbodyCharset)) {
- if (DBG) {
- Log.d(TAG, "The charset was not set to charset UTF-8: " + mBmsg.mBbodyCharset);
- }
+ Log.i(TAG, "The charset was not set to charset UTF-8: " + mBmsg.mBbodyCharset);
}
/*
diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/BmsgTokenizer.java b/android/app/src/com/android/bluetooth/mapclient/obex/BmsgTokenizer.java
index b0ef434..2c4cd7a 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/BmsgTokenizer.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/BmsgTokenizer.java
@@ -23,8 +23,7 @@
import java.util.regex.Pattern;
public final class BmsgTokenizer {
- private static final String TAG = "BmsgTokenizer";
- private static final boolean VDBG = MapClientService.VDBG;
+ private static final String TAG = BmsgTokenizer.class.getSimpleName();
private final String mStr;
@@ -91,9 +90,7 @@
this.name = name;
this.value = value;
- if (VDBG) {
- Log.v(TAG, toString());
- }
+ Log.v(TAG, toString());
}
@Override
diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java
index 8452be3..aa15fd6 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java
@@ -293,8 +293,6 @@
}
private static void logD(String message) {
- if (MapClientService.DBG) {
- Log.d(TAG, message);
- }
+ Log.d(TAG, message);
}
}
diff --git a/android/app/src/com/android/bluetooth/mcp/McpService.java b/android/app/src/com/android/bluetooth/mcp/McpService.java
index 7b54864..84832e2 100644
--- a/android/app/src/com/android/bluetooth/mcp/McpService.java
+++ b/android/app/src/com/android/bluetooth/mcp/McpService.java
@@ -43,8 +43,6 @@
* Provides Media Control Profile, as a service in the Bluetooth application.
*/
public class McpService extends ProfileService {
- private static final boolean DBG = true;
- private static final boolean VDBG = false;
private static final String TAG = "BluetoothMcpService";
private static McpService sMcpService;
@@ -65,9 +63,7 @@
}
private static synchronized void setMcpService(McpService instance) {
- if (VDBG) {
- Log.d(TAG, "setMcpService(): set to: " + instance);
- }
+ Log.d(TAG, "setMcpService(): set to: " + instance);
sMcpService = instance;
}
@@ -101,9 +97,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sMcpService != null) {
throw new IllegalStateException("start() called twice");
@@ -133,9 +127,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sMcpService == null) {
Log.w(TAG, "stop() called before start()");
@@ -161,9 +153,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
}
@Override
@@ -244,9 +234,7 @@
if (leAudioService.getConnectionPolicy(device)
> BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
- if (DBG) {
- Log.d(TAG, "MCS authorization allowed based on supported LeAudio service");
- }
+ Log.d(TAG, "MCS authorization allowed based on supported LeAudio service");
setDeviceAuthorized(device, true);
return BluetoothDevice.ACCESS_ALLOWED;
}
diff --git a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java
index afb5a2d..a610716 100644
--- a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java
+++ b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java
@@ -73,8 +73,6 @@
*/
public class MediaControlGattService implements MediaControlGattServiceInterface {
private static final String TAG = "MediaControlGattService";
- private static final boolean DBG = Log.isLoggable(TAG, Log.INFO);
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
/* MCS assigned UUIDs */
public static final UUID UUID_PLAYER_NAME =
@@ -254,9 +252,7 @@
private final Map<UUID, CharacteristicWriteHandler> mCharWriteCallback = Map.of(
UUID_TRACK_POSITION,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "TRACK_POSITION write request");
- }
+ Log.d(TAG, "TRACK_POSITION write request");
int status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
if (value.length == 4) {
status = BluetoothGatt.GATT_SUCCESS;
@@ -269,9 +265,7 @@
},
UUID_PLAYBACK_SPEED,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "PLAYBACK_SPEED write request");
- }
+ Log.d(TAG, "PLAYBACK_SPEED write request");
int status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
if (value.length == 1) {
status = BluetoothGatt.GATT_SUCCESS;
@@ -291,9 +285,7 @@
},
UUID_CURRENT_TRACK_OBJ_ID,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "CURRENT_TRACK_OBJ_ID write request");
- }
+ Log.d(TAG, "CURRENT_TRACK_OBJ_ID write request");
int status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
if (value.length == 6) {
status = BluetoothGatt.GATT_SUCCESS;
@@ -306,9 +298,7 @@
},
UUID_NEXT_TRACK_OBJ_ID,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "NEXT_TRACK_OBJ_ID write request");
- }
+ Log.d(TAG, "NEXT_TRACK_OBJ_ID write request");
int status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
if (value.length == 6) {
status = BluetoothGatt.GATT_SUCCESS;
@@ -320,9 +310,7 @@
},
UUID_CURRENT_GROUP_OBJ_ID,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "CURRENT_GROUP_OBJ_ID write request");
- }
+ Log.d(TAG, "CURRENT_GROUP_OBJ_ID write request");
int status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
if (value.length == 6) {
status = BluetoothGatt.GATT_SUCCESS;
@@ -335,9 +323,7 @@
},
UUID_PLAYING_ORDER,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "PLAYING_ORDER write request");
- }
+ Log.d(TAG, "PLAYING_ORDER write request");
int status = BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH;
Integer currentPlayingOrder = null;
@@ -365,9 +351,7 @@
},
UUID_MEDIA_CONTROL_POINT,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "MEDIA_CONTROL_POINT write request");
- }
+ Log.d(TAG, "MEDIA_CONTROL_POINT write request");
int status = handleMediaControlPointRequest(device, value);
if (responseNeeded) {
mBluetoothGattServer.sendResponse(device, requestId, status, offset, value);
@@ -375,9 +359,7 @@
},
UUID_SEARCH_CONTROL_POINT,
(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value) -> {
- if (VDBG) {
- Log.d(TAG, "SEARCH_CONTROL_POINT write request");
- }
+ Log.d(TAG, "SEARCH_CONTROL_POINT write request");
// TODO: There is no Object Trasfer Service implementation.
if (responseNeeded) {
mBluetoothGattServer.sendResponse(device, requestId, 0, offset, value);
@@ -763,9 +745,7 @@
}
private void ClearUnauthorizedGattOperations(BluetoothDevice device) {
- if (VDBG) {
- Log.d(TAG, "ClearUnauthorizedGattOperations: device= " + device);
- }
+ Log.d(TAG, "ClearUnauthorizedGattOperations: device= " + device);
synchronized (mPendingGattOperations) {
mPendingGattOperations.remove(device);
@@ -773,9 +753,7 @@
}
private void ProcessPendingGattOperations(BluetoothDevice device) {
- if (VDBG) {
- Log.d(TAG, "ProcessPendingGattOperations: device= " + device);
- }
+ Log.d(TAG, "ProcessPendingGattOperations: device= " + device);
synchronized (mPendingGattOperations) {
if (mPendingGattOperations.containsKey(device)) {
@@ -817,12 +795,10 @@
private final AdapterService.BluetoothStateCallback mBluetoothStateChangeCallback =
new AdapterService.BluetoothStateCallback() {
public void onBluetoothStateChange(int prevState, int newState) {
- if (DBG) {
- Log.d(
- TAG,
- "onBluetoothStateChange: state="
- + BluetoothAdapter.nameForState(newState));
- }
+ Log.d(
+ TAG,
+ "onBluetoothStateChange: state="
+ + BluetoothAdapter.nameForState(newState));
if (newState == BluetoothAdapter.STATE_ON) {
restoreCccValuesForStoredDevices();
}
@@ -834,9 +810,7 @@
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
- if (VDBG) {
- Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange");
- }
+ Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange");
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
ClearUnauthorizedGattOperations(device);
}
@@ -845,9 +819,7 @@
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
- if (VDBG) {
- Log.d(TAG, "BluetoothGattServerCallback: onServiceAdded");
- }
+ Log.d(TAG, "BluetoothGattServerCallback: onServiceAdded");
if (mCallbacks != null) {
mCallbacks.onServiceInstanceRegistered((status != BluetoothGatt.GATT_SUCCESS)
@@ -867,10 +839,8 @@
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
- if (VDBG) {
- Log.d(TAG, "BluetoothGattServerCallback: onCharacteristicReadRequest offset= "
- + offset + " entire value= " + Arrays.toString(characteristic.getValue()));
- }
+ Log.d(TAG, "BluetoothGattServerCallback: onCharacteristicReadRequest offset= "
+ + offset + " entire value= " + Arrays.toString(characteristic.getValue()));
if ((characteristic.getProperties() & PROPERTY_READ) == 0) {
mBluetoothGattServer.sendResponse(device, requestId,
@@ -899,11 +869,9 @@
boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite,
responseNeeded, offset, value);
- if (VDBG) {
- Log.d(TAG,
- "BluetoothGattServerCallback: "
- + "onCharacteristicWriteRequest");
- }
+ Log.d(TAG,
+ "BluetoothGattServerCallback: "
+ + "onCharacteristicWriteRequest");
if ((characteristic.getProperties() & PROPERTY_WRITE)
== 0) {
@@ -931,11 +899,9 @@
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset,
BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
- if (VDBG) {
- Log.d(TAG,
- "BluetoothGattServerCallback: "
- + "onDescriptorReadRequest");
- }
+ Log.d(TAG,
+ "BluetoothGattServerCallback: "
+ + "onDescriptorReadRequest");
if ((descriptor.getPermissions() & BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED)
== 0) {
@@ -965,11 +931,9 @@
int offset, byte[] value) {
super.onDescriptorWriteRequest(
device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
- if (VDBG) {
- Log.d(TAG,
- "BluetoothGattServerCallback: "
- + "onDescriptorWriteRequest");
- }
+ Log.d(TAG,
+ "BluetoothGattServerCallback: "
+ + "onDescriptorWriteRequest");
if ((descriptor.getPermissions() & BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED)
== 0) {
@@ -1277,9 +1241,7 @@
for (Pair<UUID, CharacteristicData> entry : getUuidCharacteristicList()) {
CharacteristicData desc = entry.second;
UUID uuid = entry.first;
- if (VDBG) {
- Log.d(TAG, "Checking uuid: " + uuid);
- }
+ Log.d(TAG, "Checking uuid: " + uuid);
if ((mFeatures & desc.featureFlag) != 0) {
int notifyProp = (((mFeatures & desc.ntfFeatureFlag) != 0)
? PROPERTY_NOTIFY
@@ -1293,22 +1255,16 @@
BluetoothGattDescriptor cccDesc = new BluetoothGattDescriptor(UUID_CCCD,
BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED
| BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED);
- if (VDBG) {
- Log.d(TAG, "Adding descriptor: " + cccDesc);
- }
+ Log.d(TAG, "Adding descriptor: " + cccDesc);
myChar.addDescriptor(cccDesc);
}
- if (VDBG) {
- Log.d(TAG, "Adding char: " + myChar);
- }
+ Log.d(TAG, "Adding char: " + myChar);
mCharacteristics.put(desc.id, myChar);
mGattService.addCharacteristic(myChar);
}
}
- if (VDBG) {
- Log.d(TAG, "Adding service: " + mGattService);
- }
+ Log.d(TAG, "Adding service: " + mGattService);
return mBluetoothGattServer.addService(mGattService);
}
@@ -1353,9 +1309,7 @@
@Override
public void updatePlaybackState(MediaState state) {
- if (DBG) {
- Log.d(TAG, "updatePlaybackState");
- }
+ Log.d(TAG, "updatePlaybackState");
if ((state.getValue() <= MediaState.STATE_MAX.getValue())
&& (state.getValue() >= MediaState.STATE_MIN.getValue())) {
@@ -1379,9 +1333,7 @@
@VisibleForTesting
void updateMediaStateChar(int state) {
- if (DBG) {
- Log.d(TAG, "updateMediaStateChar: state= " + MediaState.toString(state));
- }
+ Log.d(TAG, "updateMediaStateChar: state= " + MediaState.toString(state));
if (!isFeatureSupported(ServiceFeature.MEDIA_STATE)) return;
@@ -1394,9 +1346,7 @@
}
private void updateObjectID(int objectIdField, long objectIdValue, boolean notify) {
- if (DBG) {
- Log.d(TAG, "updateObjectID");
- }
+ Log.d(TAG, "updateObjectID");
int feature = ObjectIds.GetMatchingServiceFeature(objectIdField);
if (!isFeatureSupported(feature)) return;
@@ -1419,9 +1369,7 @@
@Override
public void setMediaControlRequestResult(Request request,
Request.Results resultStatus) {
- if (DBG) {
- Log.d(TAG, "setMediaControlRequestResult");
- }
+ Log.d(TAG, "setMediaControlRequestResult");
if (getMediaStateChar() == MediaState.INACTIVE.getValue()) {
resultStatus = Request.Results.MEDIA_PLAYER_INACTIVE;
@@ -1440,9 +1388,7 @@
@Override
public void setSearchRequestResult(SearchRequest request,
SearchRequest.Results resultStatus, long resultObjectId) {
- if (DBG) {
- Log.d(TAG, "setSearchRequestResult");
- }
+ Log.d(TAG, "setSearchRequestResult");
// TODO: There is no Object Trasfer Service implementation.
BluetoothGattCharacteristic characteristic =
@@ -1460,11 +1406,9 @@
if (stateFields.containsKey(PlayerStateField.PLAYBACK_STATE)) {
MediaState playbackState =
(MediaState) stateFields.get(PlayerStateField.PLAYBACK_STATE);
- if (DBG) {
- Log.d(TAG,
- "updatePlayerState: playbackState= "
- + stateFields.get(PlayerStateField.PLAYBACK_STATE));
- }
+ Log.d(TAG,
+ "updatePlayerState: playbackState= "
+ + stateFields.get(PlayerStateField.PLAYBACK_STATE));
if (playbackState == MediaState.INACTIVE) {
setInitialCharacteristicValues();
@@ -1638,9 +1582,7 @@
@Override
public void destroy() {
- if (DBG) {
- Log.d(TAG, "Destroy");
- }
+ Log.d(TAG, "Destroy");
mAdapterService.unregisterBluetoothStateCallback(mBluetoothStateChangeCallback);
@@ -1659,9 +1601,7 @@
@VisibleForTesting
void updatePlayingOrderChar(PlayingOrder order, boolean notify) {
- if (VDBG) {
- Log.d(TAG, "updatePlayingOrderChar: order= " + order);
- }
+ Log.d(TAG, "updatePlayingOrderChar: order= " + order);
if (!isFeatureSupported(ServiceFeature.PLAYING_ORDER)) return;
BluetoothGattCharacteristic orderChar = mCharacteristics.get(CharId.PLAYING_ORDER);
@@ -1689,17 +1629,15 @@
if (charCccMap == null) return;
byte[] ccc = getCccBytes(device, characteristic.getUuid());
- if (VDBG) {
- Log.d(
- TAG,
- "notifyCharacteristic: char= "
- + characteristic.getUuid().toString()
- + " cccVal= "
- + ByteBuffer.wrap(ccc).order(ByteOrder.LITTLE_ENDIAN).getShort());
- }
+ Log.d(
+ TAG,
+ "notifyCharacteristic: char= "
+ + characteristic.getUuid().toString()
+ + " cccVal= "
+ + ByteBuffer.wrap(ccc).order(ByteOrder.LITTLE_ENDIAN).getShort());
if (!Arrays.equals(ccc, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) return;
- if (VDBG) Log.d(TAG, "notifyCharacteristic: sending notification");
+ Log.d(TAG, "notifyCharacteristic: sending notification");
mBluetoothGattServer.notifyCharacteristicChanged(device, characteristic, false);
}
@@ -1753,9 +1691,7 @@
@VisibleForTesting
void updateSeekingSpeedChar(float speed, boolean notify) {
- if (VDBG) {
- Log.d(TAG, "updateSeekingSpeedChar: speed= " + speed);
- }
+ Log.d(TAG, "updateSeekingSpeedChar: speed= " + speed);
if (isFeatureSupported(ServiceFeature.SEEKING_SPEED)) {
if ((getSeekingSpeedChar() == null) || (getSeekingSpeedChar() != speed)) {
BluetoothGattCharacteristic characteristic =
@@ -1790,9 +1726,7 @@
@VisibleForTesting
void updatePlaybackSpeedChar(float speed, boolean notify) {
- if (VDBG) {
- Log.d(TAG, "updatePlaybackSpeedChar: " + speed);
- }
+ Log.d(TAG, "updatePlaybackSpeedChar: " + speed);
if (!isFeatureSupported(ServiceFeature.PLAYBACK_SPEED)) return;
@@ -1813,9 +1747,7 @@
@VisibleForTesting
void updateTrackPositionChar(long positionMs, boolean forceNotify) {
- if (VDBG) {
- Log.d(TAG, "updateTrackPositionChar: " + positionMs);
- }
+ Log.d(TAG, "updateTrackPositionChar: " + positionMs);
if (!isFeatureSupported(ServiceFeature.TRACK_POSITION)) return;
final int position =
@@ -1856,9 +1788,7 @@
@VisibleForTesting
void updateTrackDurationChar(long durationMs, boolean notify) {
- if (VDBG) {
- Log.d(TAG, "updateTrackDurationChar: " + durationMs);
- }
+ Log.d(TAG, "updateTrackDurationChar: " + durationMs);
if (isFeatureSupported(ServiceFeature.TRACK_DURATION)) {
final int duration =
(durationMs != TRACK_DURATION_UNAVAILABLE)
@@ -1894,9 +1824,7 @@
@VisibleForTesting
void updateTrackTitleChar(String title, boolean notify) {
- if (VDBG) {
- Log.d(TAG, "updateTrackTitleChar: " + title);
- }
+ Log.d(TAG, "updateTrackTitleChar: " + title);
if (isFeatureSupported(ServiceFeature.TRACK_TITLE)) {
BluetoothGattCharacteristic characteristic =
mCharacteristics.get(CharId.TRACK_TITLE);
@@ -1910,12 +1838,10 @@
@VisibleForTesting
void updateSupportedOpcodesChar(int opcodes, boolean notify) {
- if (VDBG) {
- Log.d(
- TAG,
- "updateSupportedOpcodesChar: opcodes= "
- + Request.SupportedOpcodes.toString(opcodes));
- }
+ Log.d(
+ TAG,
+ "updateSupportedOpcodesChar: opcodes= "
+ + Request.SupportedOpcodes.toString(opcodes));
if (!isFeatureSupported(ServiceFeature.MEDIA_CONTROL_POINT_OPCODES_SUPPORTED)) return;
BluetoothGattCharacteristic characteristic = mCharacteristics.get(
@@ -1940,9 +1866,7 @@
@VisibleForTesting
void updatePlayingOrderSupportedChar(int supportedOrder) {
- if (VDBG) {
- Log.d(TAG, "updatePlayingOrderSupportedChar: " + supportedOrder);
- }
+ Log.d(TAG, "updatePlayingOrderSupportedChar: " + supportedOrder);
if (isFeatureSupported(ServiceFeature.PLAYING_ORDER_SUPPORTED)) {
mCharacteristics.get(CharId.PLAYING_ORDER_SUPPORTED)
.setValue(supportedOrder, BluetoothGattCharacteristic.FORMAT_UINT16, 0);
@@ -1997,9 +1921,7 @@
}
private void updatePlayerIconUrlChar(String url) {
- if (VDBG) {
- Log.d(TAG, "updatePlayerIconUrlChar: " + url);
- }
+ Log.d(TAG, "updatePlayerIconUrlChar: " + url);
if (isFeatureSupported(ServiceFeature.PLAYER_ICON_URL)) {
mCharacteristics.get(CharId.PLAYER_ICON_URL).setValue(url);
mEventLogger.logd(TAG, "updatePlayerIconUrlChar: " + url);
@@ -2018,9 +1940,7 @@
@VisibleForTesting
void updatePlayerNameChar(String name, boolean notify) {
- if (VDBG) {
- Log.d(TAG, "updatePlayerNameChar: " + name);
- }
+ Log.d(TAG, "updatePlayerNameChar: " + name);
if (!isFeatureSupported(ServiceFeature.PLAYER_NAME)) return;
@@ -2034,10 +1954,8 @@
}
private boolean isFeatureSupported(long featureBit) {
- if (DBG) {
- Log.w(TAG, "Feature " + ServiceFeature.toString(featureBit) + " support: "
- + ((mFeatures & featureBit) != 0));
- }
+ Log.w(TAG, "Feature " + ServiceFeature.toString(featureBit) + " support: "
+ + ((mFeatures & featureBit) != 0));
return (mFeatures & featureBit) != 0;
}
diff --git a/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java b/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java
index 6c7219e..e646162 100644
--- a/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java
+++ b/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java
@@ -62,7 +62,6 @@
*/
public class MediaControlProfile implements MediaControlServiceCallbacks {
private static final String TAG = "MediaControlProfile";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
private final Context mContext;
private static final int LOG_NB_EVENTS = 100;
@@ -152,7 +151,7 @@
}
private void onCurrentPlayerQueueUpdated() {
- if (DBG) Log.d(TAG, "onCurrentPlayerQueueUpdated: not implemented");
+ Log.d(TAG, "onCurrentPlayerQueueUpdated: not implemented");
/* TODO: Implement once we have the Object Transfer Service */
if (mCurrentData.queue == null) return;
@@ -577,7 +576,7 @@
}
private void processPendingPlayerStateRequest() {
- if (DBG) Log.d(TAG, "GMCS processPendingPlayerStateRequest");
+ Log.d(TAG, "GMCS processPendingPlayerStateRequest");
Map<PlayerStateField, Object> handled_request_map = new HashMap<>();
@@ -666,13 +665,11 @@
}
}
- if (DBG) {
- synchronized (this) {
- if (mPendingStateRequest != null && !mPendingStateRequest.isEmpty()) {
- Log.w(TAG, "MCS service state fields left unhandled: ");
- for (PlayerStateField item : mPendingStateRequest) {
- Log.w(TAG, " > " + item);
- }
+ synchronized (this) {
+ if (mPendingStateRequest != null && !mPendingStateRequest.isEmpty()) {
+ Log.w(TAG, "MCS service state fields left unhandled: ");
+ for (PlayerStateField item : mPendingStateRequest) {
+ Log.w(TAG, " > " + item);
}
}
}
diff --git a/android/app/src/com/android/bluetooth/pan/PanService.java b/android/app/src/com/android/bluetooth/pan/PanService.java
index 9476359..a4dbc1c 100644
--- a/android/app/src/com/android/bluetooth/pan/PanService.java
+++ b/android/app/src/com/android/bluetooth/pan/PanService.java
@@ -63,8 +63,7 @@
* the Bluetooth application.
*/
public class PanService extends ProfileService {
- private static final String TAG = "PanService";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = PanService.class.getSimpleName();
private static PanService sPanService;
private static final int BLUETOOTH_MAX_PAN_CONNECTIONS = 5;
@@ -138,9 +137,7 @@
}
private static synchronized void setPanService(PanService instance) {
- if (DBG) {
- Log.d(TAG, "setPanService(): set to: " + instance);
- }
+ Log.d(TAG, "setPanService(): set to: " + instance);
sPanService = instance;
}
@@ -265,14 +262,12 @@
final BluetoothDevice device =
mAdapterService.getDeviceFromByte(cs.addr);
// TBD get iface from the msg
- if (DBG) {
- Log.d(
- TAG,
- "MESSAGE_CONNECT_STATE_CHANGED: "
- + device
- + " state: "
- + cs.state);
- }
+ Log.d(
+ TAG,
+ "MESSAGE_CONNECT_STATE_CHANGED: "
+ + device
+ + " state: "
+ + cs.state);
// It could be null if the connection up is coming when the
// Bluetooth is turning off.
if (device == null) {
@@ -486,9 +481,7 @@
})
void setBluetoothTethering(IBluetoothPanCallback callback, int id, int callerUid,
boolean value) {
- if (DBG) {
- Log.d(TAG, "setBluetoothTethering: " + value + ", mTetherOn: " + mTetherOn);
- }
+ Log.d(TAG, "setBluetoothTethering: " + value + ", mTetherOn: " + mTetherOn);
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
enforceCallingOrSelfPermission(
@@ -550,9 +543,7 @@
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
enforceCallingOrSelfPermission(
BLUETOOTH_PRIVILEGED, "Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.PAN,
connectionPolicy)) {
@@ -625,10 +616,8 @@
void onConnectStateChanged(byte[] address, int state, int error, int localRole,
int remoteRole) {
- if (DBG) {
- Log.d(TAG, "onConnectStateChanged: " + state + ", local role:" + localRole
- + ", remoteRole: " + remoteRole);
- }
+ Log.d(TAG, "onConnectStateChanged: " + state + ", local role:" + localRole
+ + ", remoteRole: " + remoteRole);
Message msg = mHandler.obtainMessage(MESSAGE_CONNECT_STATE_CHANGED);
msg.obj = new ConnectState(address, state, error, localRole, remoteRole);
mHandler.sendMessage(msg);
@@ -636,10 +625,8 @@
@VisibleForTesting
void onControlStateChanged(int localRole, int state, int error, String ifname) {
- if (DBG) {
- Log.d(TAG, "onControlStateChanged: " + state + ", error: " + error + ", ifname: "
- + ifname);
- }
+ Log.d(TAG, "onControlStateChanged: " + state + ", error: " + error + ", ifname: "
+ + ifname);
if (error == 0) {
mPanIfName = ifname;
}
@@ -648,11 +635,9 @@
void handlePanDeviceStateChange(BluetoothDevice device, String iface, int state,
@LocalPanRole int localRole, @RemotePanRole int remoteRole) {
- if (DBG) {
- Log.d(TAG, "handlePanDeviceStateChange: device: " + device + ", iface: " + iface
- + ", state: " + state + ", localRole:" + localRole + ", remoteRole:"
- + remoteRole);
- }
+ Log.d(TAG, "handlePanDeviceStateChange: device: " + device + ", iface: " + iface
+ + ", state: " + state + ", localRole:" + localRole + ", remoteRole:"
+ + remoteRole);
int prevState;
BluetoothPanDevice panDevice = mPanDevices.get(device);
diff --git a/android/app/src/com/android/bluetooth/pbapclient/Authenticator.java b/android/app/src/com/android/bluetooth/pbapclient/Authenticator.java
index 71d3d2c..ee06984 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/Authenticator.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/Authenticator.java
@@ -26,7 +26,6 @@
public class Authenticator extends AbstractAccountAuthenticator {
private static final String TAG = "PbapClientAuthenticator";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
public Authenticator(Context context) {
super(context);
@@ -35,7 +34,7 @@
// Editing properties is not supported
@Override
public Bundle editProperties(AccountAuthenticatorResponse r, String s) {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
throw new UnsupportedOperationException();
}
@@ -43,7 +42,7 @@
@Override
public Bundle addAccount(AccountAuthenticatorResponse r, String s, String s2, String[] strings,
Bundle bundle) throws NetworkErrorException {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
// Don't allow accounts to be added.
throw new UnsupportedOperationException();
}
@@ -52,7 +51,7 @@
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse r, Account account, Bundle bundle)
throws NetworkErrorException {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
return null;
}
@@ -60,14 +59,14 @@
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse r, Account account, String s,
Bundle bundle) throws NetworkErrorException {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
throw new UnsupportedOperationException();
}
// Getting a label for the auth token is not supported
@Override
public String getAuthTokenLabel(String s) {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
return null;
}
@@ -75,7 +74,7 @@
@Override
public Bundle updateCredentials(AccountAuthenticatorResponse r, Account account, String s,
Bundle bundle) throws NetworkErrorException {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
return null;
}
@@ -83,7 +82,7 @@
@Override
public Bundle hasFeatures(AccountAuthenticatorResponse r, Account account, String[] strings)
throws NetworkErrorException {
- if (DBG) Log.d(TAG, "got call", new Exception());
+ Log.d(TAG, "got call", new Exception());
final Bundle result = new Bundle();
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
diff --git a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticator.java b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticator.java
index b191705..920a724 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticator.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapObexAuthenticator.java
@@ -29,10 +29,7 @@
* authentication is implementation defined.
*/
class BluetoothPbapObexAuthenticator implements Authenticator {
-
private static final String TAG = "PbapClientObexAuth";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
//Default session key for legacy devices is 0000
@VisibleForTesting
@@ -42,16 +39,14 @@
public PasswordAuthentication onAuthenticationChallenge(String description,
boolean isUserIdRequired, boolean isFullAccess) {
PasswordAuthentication pa = null;
- if (DBG) Log.d(TAG, "onAuthenticationChallenge: starting");
+ Log.d(TAG, "onAuthenticationChallenge: starting");
if (mSessionKey != null && mSessionKey.length() != 0) {
- if (DBG) Log.d(TAG, "onAuthenticationChallenge: mSessionKey=" + mSessionKey);
+ Log.d(TAG, "onAuthenticationChallenge: mSessionKey=" + mSessionKey);
pa = new PasswordAuthentication(null, mSessionKey.getBytes());
} else {
- if (DBG) {
- Log.d(TAG,
- "onAuthenticationChallenge: mSessionKey is empty, timeout/cancel occured");
- }
+ Log.d(TAG,
+ "onAuthenticationChallenge: mSessionKey is empty, timeout/cancel occurred");
}
return pa;
@@ -59,7 +54,7 @@
@Override
public byte[] onAuthenticationResponse(byte[] userName) {
- if (VDBG) Log.v(TAG, "onAuthenticationResponse: " + Arrays.toString(userName));
+ Log.v(TAG, "onAuthenticationResponse: " + Arrays.toString(userName));
/* required only in case PCE challenges PSE which we don't do now */
return null;
}
diff --git a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequest.java b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequest.java
index adc5e69..dd0dee2 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequest.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequest.java
@@ -27,9 +27,7 @@
import java.io.InputStream;
abstract class BluetoothPbapRequest {
-
static final String TAG = "PbapClient.BaseRequest";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
protected static final byte OAP_TAGID_ORDER = 0x01;
protected static final byte OAP_TAGID_SEARCH_VALUE = 0x02;
@@ -59,7 +57,7 @@
}
public void execute(ClientSession session) throws IOException {
- if (DBG) Log.v(TAG, "execute");
+ Log.v(TAG, "execute");
/* in case request is aborted before can be executed */
if (mAborted) {
@@ -89,7 +87,7 @@
mResponseCode = mOp.getResponseCode();
- if (DBG) Log.d(TAG, "mResponseCode=" + mResponseCode);
+ Log.d(TAG, "mResponseCode=" + mResponseCode);
checkResponseCode(mResponseCode);
} catch (IOException e) {
@@ -113,19 +111,19 @@
}
protected void readResponse(InputStream stream) throws IOException {
- if (DBG) Log.v(TAG, "readResponse");
+ Log.v(TAG, "readResponse");
/* nothing here by default */
}
protected void readResponseHeaders(HeaderSet headerset) {
- if (DBG) Log.v(TAG, "readResponseHeaders");
+ Log.v(TAG, "readResponseHeaders");
/* nothing here by dafault */
}
protected void checkResponseCode(int responseCode) throws IOException {
- if (DBG) Log.v(TAG, "checkResponseCode");
+ Log.v(TAG, "checkResponseCode");
/* nothing here by dafault */
}
diff --git a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBook.java b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBook.java
index b6b2d96..5b46c30 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBook.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBook.java
@@ -29,7 +29,6 @@
final class BluetoothPbapRequestPullPhoneBook extends BluetoothPbapRequest {
private static final String TAG = "PbapClient.PullPb";
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
private static final String TYPE = "x-bt/phonebook";
@@ -91,17 +90,15 @@
@Override
protected void readResponse(InputStream stream) throws IOException {
- if (VDBG) Log.v(TAG, "readResponse");
+ Log.v(TAG, "readResponse");
mResponse = new BluetoothPbapVcardList(mAccount, stream, mFormat);
- if (VDBG) {
- Log.d(TAG, "Read " + mResponse.getCount() + " entries.");
- }
+ Log.d(TAG, "Read " + mResponse.getCount() + " entries");
}
@Override
protected void readResponseHeaders(HeaderSet headerset) {
- if (VDBG) Log.v(TAG, "readResponseHeaders");
+ Log.v(TAG, "readResponseHeaders");
ObexAppParameters oap = ObexAppParameters.fromHeaderSet(headerset);
diff --git a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSize.java b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSize.java
index 92ae463..9432881 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSize.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/BluetoothPbapRequestPullPhoneBookSize.java
@@ -23,7 +23,6 @@
final class BluetoothPbapRequestPullPhoneBookSize extends BluetoothPbapRequest {
private static final String TAG = "PbapClient.PullPbSize";
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
private static final String TYPE = "x-bt/phonebook";
@@ -48,9 +47,7 @@
@Override
protected void readResponseHeaders(HeaderSet headerset) {
- if (VDBG) {
- Log.v(TAG, "readResponseHeaders");
- }
+ Log.v(TAG, "readResponseHeaders");
ObexAppParameters oap = ObexAppParameters.fromHeaderSet(headerset);
diff --git a/android/app/src/com/android/bluetooth/pbapclient/CallLogPullRequest.java b/android/app/src/com/android/bluetooth/pbapclient/CallLogPullRequest.java
index e6c8249..d2a3202 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/CallLogPullRequest.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/CallLogPullRequest.java
@@ -42,8 +42,6 @@
public class CallLogPullRequest extends PullRequest {
private static final String TAG = "CallLogPullRequest";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
@VisibleForTesting
static final String TIMESTAMP_PROPERTY = "X-IRMC-CALL-DATETIME";
@@ -68,12 +66,7 @@
return;
}
- if (DBG) {
- Log.d(TAG, "onPullComplete");
- if (VDBG) {
- Log.d(TAG, " with " + mEntries.size() + " count.");
- }
- }
+ Log.d(TAG, "onPullComplete with " + mEntries.size() + " entries");
int type;
try {
if (path.equals(PbapClientConnectionHandler.ICH_PATH)) {
@@ -115,10 +108,7 @@
try {
values.put(CallLog.Calls.DATE, parser.parse(pair.second).getTime());
} catch (ParseException e) {
- Log.d(TAG, "Failed to parse date ");
- if (VDBG) {
- Log.d(TAG, pair.second);
- }
+ Log.d(TAG, "Failed to parse date, value=" + pair.second);
}
}
}
@@ -156,18 +146,14 @@
c.moveToNext();
String contactId = c.getString(c.getColumnIndex(
ContactsContract.PhoneLookup.CONTACT_ID));
- if (VDBG) {
- Log.d(TAG, "onPullComplete: ID " + contactId + " key : " + key);
- }
+ Log.d(TAG, "onPullComplete: ID " + contactId + " key : " + key);
String where = ContactsContract.RawContacts.CONTACT_ID + "=" + contactId;
mContext.getContentResolver().update(
ContactsContract.RawContacts.CONTENT_URI, values, where, null);
}
}
}
- if (DBG) {
- Log.d(TAG, "Updated TIMES_CONTACTED");
- }
+ Log.d(TAG, "Updated TIMES_CONTACTED");
}
}
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandler.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandler.java
index 9e34fa4..ce6d17a 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandler.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandler.java
@@ -48,6 +48,8 @@
* controlling state machine.
*/
class PbapClientConnectionHandler extends Handler {
+ private static final String TAG = "PbapClientConnHandler";
+
// Tradeoff: larger BATCH_SIZE leads to faster download rates, while smaller
// BATCH_SIZE is less prone to IO Exceptions if there is a download in
// progress when Bluetooth stack is torn down.
@@ -57,9 +59,6 @@
// i.e., valid indices are [0, 1, ... , UPPER_LIMIT]
private static final int UPPER_LIMIT = 65535;
- static final String TAG = "PbapClientConnHandler";
- static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
static final int MSG_CONNECT = 1;
static final int MSG_DISCONNECT = 2;
static final int MSG_DOWNLOAD = 3;
@@ -189,17 +188,13 @@
@Override
public void handleMessage(Message msg) {
- if (DBG) {
- Log.d(TAG, "Handling Message = " + msg.what);
- }
+ Log.d(TAG, "Handling Message = " + msg.what);
switch (msg.what) {
case MSG_CONNECT:
mPseRec = (SdpPseRecord) msg.obj;
/* To establish a connection, first open a socket and then create an OBEX session */
if (connectSocket()) {
- if (DBG) {
- Log.d(TAG, "Socket connected");
- }
+ Log.d(TAG, "Socket connected");
} else {
Log.w(TAG, "Socket CONNECT Failure ");
mPbapClientStateMachine.sendMessage(
@@ -217,28 +212,20 @@
break;
case MSG_DISCONNECT:
- if (DBG) {
- Log.d(TAG, "Starting Disconnect");
- }
+ Log.d(TAG, "Starting Disconnect");
try {
if (mObexSession != null) {
- if (DBG) {
- Log.d(TAG, "obexSessionDisconnect" + mObexSession);
- }
+ Log.d(TAG, "obexSessionDisconnect" + mObexSession);
mObexSession.disconnect(null);
mObexSession.close();
}
} catch (IOException e) {
Log.w(TAG, "DISCONNECT Failure ", e);
} finally {
- if (DBG) {
- Log.d(TAG, "Closing Socket");
- }
+ Log.d(TAG, "Closing Socket");
closeSocket();
}
- if (DBG) {
- Log.d(TAG, "Completing Disconnect");
- }
+ Log.d(TAG, "Completing Disconnect");
removeAccount();
removeCallLog();
@@ -291,14 +278,14 @@
/* Use BluetoothSocket to connect */
if (mPseRec == null) {
// BackWardCompatability: Fall back to create RFCOMM through UUID.
- if (VDBG) Log.v(TAG, "connectSocket: UUID: " + BluetoothUuid.PBAP_PSE.getUuid());
+ Log.v(TAG, "connectSocket: UUID: " + BluetoothUuid.PBAP_PSE.getUuid());
mSocket =
mDevice.createRfcommSocketToServiceRecord(BluetoothUuid.PBAP_PSE.getUuid());
} else if (mPseRec.getL2capPsm() != L2CAP_INVALID_PSM) {
- if (VDBG) Log.v(TAG, "connectSocket: PSM: " + mPseRec.getL2capPsm());
+ Log.v(TAG, "connectSocket: PSM: " + mPseRec.getL2capPsm());
mSocket = mDevice.createL2capSocket(mPseRec.getL2capPsm());
} else {
- if (VDBG) Log.v(TAG, "connectSocket: channel: " + mPseRec.getRfcommChannelNumber());
+ Log.v(TAG, "connectSocket: channel: " + mPseRec.getRfcommChannelNumber());
mSocket = mDevice.createRfcommSocket(mPseRec.getRfcommChannelNumber());
}
@@ -321,9 +308,7 @@
boolean connectionSuccessful = false;
try {
- if (VDBG) {
- Log.v(TAG, "Start Obex Client Session");
- }
+ Log.v(TAG, "Start Obex Client Session");
BluetoothObexTransport transport = new BluetoothObexTransport(mSocket);
mObexSession = new ClientSession(transport);
mObexSession.setAuthenticator(mAuth);
@@ -332,9 +317,7 @@
connectionRequest.setHeader(HeaderSet.TARGET, PBAP_TARGET);
if (mPseRec != null) {
- if (DBG) {
- Log.d(TAG, "Remote PbapSupportedFeatures " + mPseRec.getSupportedFeatures());
- }
+ Log.d(TAG, "Remote PbapSupportedFeatures " + mPseRec.getSupportedFeatures());
ObexAppParameters oap = new ObexAppParameters();
@@ -349,9 +332,7 @@
connectionSuccessful =
(connectionResponse.getResponseCode() == ResponseCodes.OBEX_HTTP_OK);
- if (DBG) {
- Log.d(TAG, "Success = " + Boolean.toString(connectionSuccessful));
- }
+ Log.d(TAG, "Success = " + Boolean.toString(connectionSuccessful));
} catch (IOException | NullPointerException e) {
// Will get NPE if a null mSocket is passed to BluetoothObexTransport.
// mSocket can be set to null if an abort() --> closeSocket() was called between
@@ -372,9 +353,7 @@
private synchronized void closeSocket() {
try {
if (mSocket != null) {
- if (DBG) {
- Log.d(TAG, "Closing socket" + mSocket);
- }
+ Log.d(TAG, "Closing socket" + mSocket);
mSocket.close();
mSocket = null;
}
@@ -460,9 +439,7 @@
@VisibleForTesting
boolean addAccount() {
if (mAccountManager.addAccountExplicitly(mAccount, null, null)) {
- if (DBG) {
- Log.d(TAG, "Added account " + mAccount);
- }
+ Log.d(TAG, "Added account " + mAccount);
return true;
}
return false;
@@ -471,9 +448,7 @@
@VisibleForTesting
void removeAccount() {
if (mAccountManager.removeAccountExplicitly(mAccount)) {
- if (DBG) {
- Log.d(TAG, "Removed account " + mAccount);
- }
+ Log.d(TAG, "Removed account " + mAccount);
} else {
Log.e(TAG, "Failed to remove account " + mAccount);
}
@@ -484,9 +459,7 @@
try {
// need to check call table is exist ?
if (mContext.getContentResolver() == null) {
- if (DBG) {
- Log.d(TAG, "CallLog ContentResolver is not found");
- }
+ Log.d(TAG, "CallLog ContentResolver is not found");
return;
}
mContext.getContentResolver().delete(CallLog.Calls.CONTENT_URI,
@@ -499,7 +472,7 @@
@VisibleForTesting
boolean isRepositorySupported(int mask) {
if (mPseRec == null) {
- if (VDBG) Log.v(TAG, "No PBAP Server SDP Record");
+ Log.v(TAG, "No PBAP Server SDP Record");
return false;
}
return (mask & mPseRec.getSupportedRepositories()) != 0;
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
index 91ce765..03f1155 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
@@ -56,9 +56,7 @@
/** Provides Bluetooth Phone Book Access Profile Client profile. */
public class PbapClientService extends ProfileService {
- private static final String TAG = "PbapClientService";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
+ private static final String TAG = PbapClientService.class.getSimpleName();
private static final String SERVICE_NAME = "Phonebook Access PCE";
@@ -131,9 +129,7 @@
@Override
public void start() {
- if (VDBG) {
- Log.v(TAG, "onStart");
- }
+ Log.v(TAG, "onStart");
mDatabaseManager =
Objects.requireNonNull(
@@ -183,7 +179,7 @@
}
void cleanupDevice(BluetoothDevice device) {
- if (DBG) Log.d(TAG, "Cleanup device: " + device);
+ Log.d(TAG, "Cleanup device: " + device);
synchronized (mPbapClientStateMachineMap) {
PbapClientStateMachine pbapClientStateMachine = mPbapClientStateMachineMap.get(device);
if (pbapClientStateMachine != null) {
@@ -212,16 +208,14 @@
* our account type is ready to use.
*
* Make a placeholder device account and determine our visibility relative to it. Note that this
- * function uses the same restrictions are the other add and remove functions, but is *also*
+ * function uses the same restrictions as the other add and remove functions, but is *also*
* available to all system apps instead of throwing a runtime SecurityException.
*/
protected boolean isAuthenticationServiceReady() {
Account account = new Account("00:00:00:00:00:00", getString(R.string.pbap_account_type));
AccountManager accountManager = AccountManager.get(this);
int visibility = accountManager.getAccountVisibility(account, getPackageName());
- if (DBG) {
- Log.d(TAG, "Checking visibility, visibility=" + visibility);
- }
+ Log.d(TAG, "Checking visibility, visibility=" + visibility);
return visibility == AccountManager.VISIBILITY_VISIBLE
|| visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
}
@@ -236,7 +230,7 @@
AccountManager accountManager = AccountManager.get(this);
Account[] accounts =
accountManager.getAccountsByType(getString(R.string.pbap_account_type));
- if (VDBG) Log.v(TAG, "Found " + accounts.length + " unclean accounts");
+ Log.v(TAG, "Found " + accounts.length + " unclean accounts");
for (Account acc : accounts) {
Log.w(TAG, "Deleting " + acc);
try {
@@ -251,7 +245,7 @@
}
private void removeHfpCallLog(String accountName, Context context) {
- if (DBG) Log.d(TAG, "Removing call logs from " + accountName);
+ Log.d(TAG, "Removing call logs from " + accountName);
// Delete call logs belonging to accountName==BD_ADDR that also match
// component name "hfpclient".
ComponentName componentName = new ComponentName(context, HfpClientConnectionService.class);
@@ -304,7 +298,7 @@
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
- if (DBG) Log.v(TAG, "onReceive" + action);
+ Log.v(TAG, "onReceive" + action);
if (action.equals(Intent.ACTION_USER_UNLOCKED)) {
for (PbapClientStateMachine stateMachine : mPbapClientStateMachineMap.values()) {
stateMachine.tryDownloadIfConnected();
@@ -342,9 +336,7 @@
public void handleHeadsetClientConnectionStateChanged(
BluetoothDevice device, int oldState, int newState) {
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
- if (DBG) {
- Log.d(TAG, "Received intent to disconnect HFP with " + device);
- }
+ Log.d(TAG, "Received intent to disconnect HFP with " + device);
// HFP client stores entries in calllog.db by BD_ADDR and component name
// Using the current Service as the context.
removeHfpCallLog(device.getAddress(), this);
@@ -384,7 +376,7 @@
@Override
public void connect(BluetoothDevice device, AttributionSource source,
SynchronousResultReceiver receiver) {
- if (DBG) Log.d(TAG, "PbapClient Binder connect ");
+ Log.d(TAG, "PbapClient Binder connect");
try {
PbapClientService service = getService(source);
boolean defaultValue = false;
@@ -507,9 +499,7 @@
@VisibleForTesting
static synchronized void setPbapClientService(PbapClientService instance) {
- if (VDBG) {
- Log.v(TAG, "setPbapClientService(): set to: " + instance);
- }
+ Log.v(TAG, "setPbapClientService(): set to: " + instance);
sPbapClientService = instance;
}
@@ -520,7 +510,7 @@
}
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) Log.d(TAG, "Received request to ConnectPBAPPhonebook " + device.getAddress());
+ Log.d(TAG, "Received request to ConnectPBAPPhonebook " + device.getAddress());
if (getConnectionPolicy(device) <= BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
return false;
}
@@ -591,10 +581,8 @@
Log.e(TAG, "No Statemachine found for the device=" + device.toString());
return;
}
- if (DBG) {
- Log.v(TAG, "Received UUID: " + uuid.toString());
- Log.v(TAG, "expected UUID: " + BluetoothUuid.PBAP_PSE.toString());
- }
+ Log.v(TAG, "Received SDP record for UUID=" + uuid.toString() + " (expected UUID="
+ + BluetoothUuid.PBAP_PSE.toString() + ")");
if (uuid.equals(BluetoothUuid.PBAP_PSE)) {
stateMachine
.obtainMessage(PbapClientStateMachine.MSG_SDP_COMPLETE, record)
@@ -645,9 +633,7 @@
}
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
if (!mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.PBAP_CLIENT,
connectionPolicy)) {
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java
index 272382e..f4a1ef6 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java
@@ -71,8 +71,7 @@
import java.util.List;
class PbapClientStateMachine extends StateMachine {
- private static final String TAG = "PbapClientStateMachine";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
+ private static final String TAG = PbapClientStateMachine.class.getSimpleName();
// Messages for handling connect/disconnect requests.
private static final int MSG_DISCONNECT = 2;
@@ -137,7 +136,7 @@
class Disconnected extends State {
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Disconnected: " + getCurrentMessage().what);
+ Log.d(TAG, "Enter Disconnected: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_DISCONNECTED);
mMostRecentState = BluetoothProfile.STATE_DISCONNECTED;
@@ -149,9 +148,7 @@
@Override
public void enter() {
- if (DBG) {
- Log.d(TAG, "Enter Connecting: " + getCurrentMessage().what);
- }
+ Log.d(TAG, "Enter Connecting: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_CONNECTING);
mCurrentDevice.sdpSearch(BluetoothUuid.PBAP_PSE);
@@ -180,9 +177,7 @@
@Override
public boolean processMessage(Message message) {
- if (DBG) {
- Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
- }
+ Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
switch (message.what) {
case MSG_DISCONNECT:
if (message.obj instanceof BluetoothDevice && message.obj.equals(
@@ -223,7 +218,7 @@
class Disconnecting extends State {
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Disconnecting: " + getCurrentMessage().what);
+ Log.d(TAG, "Enter Disconnecting: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_DISCONNECTING);
mMostRecentState = BluetoothProfile.STATE_DISCONNECTING;
@@ -238,9 +233,7 @@
@Override
public boolean processMessage(Message message) {
- if (DBG) {
- Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
- }
+ Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
PbapClientConnectionHandler connectionHandler = mConnectionHandler;
HandlerThread handlerThread = mHandlerThread;
@@ -283,7 +276,7 @@
class Connected extends State {
@Override
public void enter() {
- if (DBG) Log.d(TAG, "Enter Connected: " + getCurrentMessage().what);
+ Log.d(TAG, "Enter Connected: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_CONNECTED);
mMostRecentState = BluetoothProfile.STATE_CONNECTED;
@@ -292,9 +285,7 @@
@Override
public boolean processMessage(Message message) {
- if (DBG) {
- Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
- }
+ Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
switch (message.what) {
case MSG_DISCONNECT:
if ((message.obj instanceof BluetoothDevice)
@@ -359,7 +350,7 @@
}
public void disconnect(BluetoothDevice device) {
- if (DBG) Log.d(TAG, "Disconnect Request " + device);
+ Log.d(TAG, "Disconnect Request " + device);
sendMessage(MSG_DISCONNECT, device);
}
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PhonebookPullRequest.java b/android/app/src/com/android/bluetooth/pbapclient/PhonebookPullRequest.java
index 58551cb..5496f7a 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PhonebookPullRequest.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PhonebookPullRequest.java
@@ -30,7 +30,6 @@
public class PhonebookPullRequest extends PullRequest {
private static final String TAG = "PhonebookPullRequest";
- private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
@VisibleForTesting
static final int MAX_OPS = 250;
@@ -50,9 +49,7 @@
Log.e(TAG, "onPullComplete entries is null.");
return;
}
- if (VDBG) {
- Log.d(TAG, "onPullComplete with " + mEntries.size() + " count.");
- }
+ Log.v(TAG, "onPullComplete with " + mEntries.size() + " count.");
try {
ContentResolver contactsProvider = mContext.getContentResolver();
@@ -84,11 +81,9 @@
contactsProvider.applyBatch(ContactsContract.AUTHORITY, insertOperations);
insertOperations.clear();
}
- if (VDBG) {
- Log.d(TAG, "Sync complete: add=" + mEntries.size());
- }
+ Log.v(TAG, "Sync complete: add=" + mEntries.size());
} catch (OperationApplicationException | RemoteException | NumberFormatException e) {
- Log.e(TAG, "Got exception: ", e);
+ Log.e(TAG, "Exception occurred while processing phonebook pull: ", e);
} finally {
complete = true;
}
diff --git a/android/app/src/com/android/bluetooth/sdp/SdpManager.java b/android/app/src/com/android/bluetooth/sdp/SdpManager.java
index edebcca..38f4204 100644
--- a/android/app/src/com/android/bluetooth/sdp/SdpManager.java
+++ b/android/app/src/com/android/bluetooth/sdp/SdpManager.java
@@ -42,8 +42,6 @@
public class SdpManager {
private static final String TAG = SdpManager.class.getSimpleName();
- private static final boolean D = true;
-
// TODO: When changing PBAP to use this new API.
// Move the defines to the profile (PBAP already have the feature bits)
/* PBAP repositories */
@@ -227,12 +225,8 @@
sdpRecord = new SdpMasRecord(masInstanceId, l2capPsm, rfcommCannelNumber,
profileVersion, supportedFeatures, supportedMessageTypes, serviceName);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, moreResults);
}
}
@@ -253,12 +247,8 @@
sdpRecord = new SdpMnsRecord(l2capPsm, rfcommCannelNumber, profileVersion,
supportedFeatures, serviceName);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, moreResults);
}
}
@@ -278,12 +268,8 @@
sdpRecord = new SdpPseRecord(l2capPsm, rfcommCannelNumber, profileVersion,
supportedFeatures, supportedRepositories, serviceName);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, moreResults);
}
}
@@ -305,12 +291,8 @@
sdpRecord = new SdpOppOpsRecord(serviceName, rfcommCannelNumber, l2capPsm,
profileVersion, formatsList);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, moreResults);
}
}
@@ -329,12 +311,8 @@
if (status == AbstractionLayer.BT_STATUS_SUCCESS) {
sdpRecord = new SdpSapsRecord(rfcommCannelNumber, profileVersion, serviceName);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, moreResults);
}
}
@@ -353,21 +331,15 @@
return;
}
inst.setStatus(status);
- if (D) {
- Log.d(TAG, "sdpDipRecordFoundCallback: status " + status);
- }
+ Log.d(TAG, "sdpDipRecordFoundCallback: status " + status);
if (status == AbstractionLayer.BT_STATUS_SUCCESS) {
sdpRecord = new SdpDipRecord(specificationId,
vendorId, vendorIdSource,
productId, version,
primaryRecord);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, moreResults);
}
}
@@ -385,20 +357,12 @@
}
inst.setStatus(status);
if (status == AbstractionLayer.BT_STATUS_SUCCESS) {
- if (D) {
- Log.d(TAG, "sdpRecordFoundCallback: found a sdp record of size " + sizeRecord);
- }
- if (D) {
- Log.d(TAG, "Record:" + Arrays.toString(record));
- }
+ Log.d(TAG, "sdpRecordFoundCallback: found a sdp record of size " + sizeRecord);
+ Log.d(TAG, "Record:" + Arrays.toString(record));
sdpRecord = new SdpRecord(sizeRecord, record);
}
- if (D) {
- Log.d(TAG, "UUID: " + Arrays.toString(uuid));
- }
- if (D) {
- Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
- }
+ Log.d(TAG, "UUID: " + Arrays.toString(uuid));
+ Log.d(TAG, "UUID in parcel: " + ((Utils.byteArrayToUuid(uuid))[0]).toString());
sendSdpIntent(inst, sdpRecord, false);
}
}
@@ -428,9 +392,7 @@
SdpSearchInstance inst = sSdpSearchTracker.getNext();
if ((inst != null) && (!sSearchInProgress)) {
- if (D) {
- Log.d(TAG, "Starting search for UUID: " + inst.getUuid());
- }
+ Log.d(TAG, "Starting search for UUID: " + inst.getUuid());
sSearchInProgress = true;
inst.startSearch(); // Trigger timeout message
@@ -441,10 +403,8 @@
: sAdapterService.getByteIdentityAddress(inst.getDevice()),
Utils.uuidToByteArray(inst.getUuid()));
} else { // Else queue is empty.
- if (D) {
- Log.d(TAG, "startSearch(): nextInst = " + inst + " mSearchInProgress = "
- + sSearchInProgress + " - search busy or queue empty.");
- }
+ Log.d(TAG, "startSearch(): nextInst = " + inst + " mSearchInProgress = "
+ + sSearchInProgress + " - search busy or queue empty.");
}
}
diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java
index 9ecefaf..ac23e52 100644
--- a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java
+++ b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java
@@ -53,7 +53,6 @@
public class TbsGatt {
private static final String TAG = "TbsGatt";
- private static final boolean DBG = true;
private static final String UUID_PREFIX = "0000";
private static final String UUID_SUFFIX = "-0000-1000-8000-00805f9b34fb";
@@ -714,9 +713,7 @@
}
public boolean setCallState(Map<Integer, TbsCall> callsList) {
- if (DBG) {
- Log.d(TAG, "setCallState: callsList=" + callsList);
- }
+ Log.d(TAG, "setCallState: callsList=" + callsList);
int i = 0;
byte[] value = new byte[callsList.size() * 3];
for (Map.Entry<Integer, TbsCall> entry : callsList.entrySet()) {
@@ -730,9 +727,7 @@
}
public boolean setBearerListCurrentCalls(Map<Integer, TbsCall> callsList) {
- if (DBG) {
- Log.d(TAG, "setBearerListCurrentCalls: callsList=" + callsList);
- }
+ Log.d(TAG, "setBearerListCurrentCalls: callsList=" + callsList);
final int listItemLengthMax = Byte.MAX_VALUE;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
@@ -860,10 +855,8 @@
}
public boolean setTerminationReason(int callIndex, int terminationReason) {
- if (DBG) {
- Log.d(TAG, "setTerminationReason: callIndex=" + callIndex + " terminationReason="
- + terminationReason);
- }
+ Log.d(TAG, "setTerminationReason: callIndex=" + callIndex + " terminationReason="
+ + terminationReason);
byte[] value = new byte[2];
value[0] = (byte) (callIndex & 0xff);
value[1] = (byte) (terminationReason & 0xff);
@@ -881,9 +874,7 @@
}
public boolean setIncomingCall(int callIndex, String uri) {
- if (DBG) {
- Log.d(TAG, "setIncomingCall: callIndex=" + callIndex + " uri=" + uri);
- }
+ Log.d(TAG, "setIncomingCall: callIndex=" + callIndex + " uri=" + uri);
int uri_len = 0;
if (uri != null) {
uri_len = uri.length();
@@ -900,17 +891,13 @@
}
public boolean clearIncomingCall() {
- if (DBG) {
- Log.d(TAG, "clearIncomingCall");
- }
+ Log.d(TAG, "clearIncomingCall");
return mIncomingCallCharacteristic.clearValue(false);
}
public boolean setCallFriendlyName(int callIndex, String callFriendlyName) {
- if (DBG) {
- Log.d(TAG, "setCallFriendlyName: callIndex=" + callIndex + "callFriendlyName="
- + callFriendlyName);
- }
+ Log.d(TAG, "setCallFriendlyName: callIndex=" + callIndex + "callFriendlyName="
+ + callFriendlyName);
byte[] value = new byte[callFriendlyName.length() + 1];
value[0] = (byte) (callIndex & 0xff);
System.arraycopy(callFriendlyName.getBytes(), 0, value, 1, callFriendlyName.length());
@@ -928,20 +915,16 @@
}
public boolean clearFriendlyName() {
- if (DBG) {
- Log.d(TAG, "clearFriendlyName");
- }
+ Log.d(TAG, "clearFriendlyName");
return mCallFriendlyNameCharacteristic.clearValue(false);
}
public void setCallControlPointResult(BluetoothDevice device, int requestedOpcode,
int callIndex, int requestResult) {
- if (DBG) {
- Log.d(TAG,
- "setCallControlPointResult: device=" + device + " requestedOpcode="
- + requestedOpcode + " callIndex=" + callIndex + " requesuResult="
- + requestResult);
- }
+ Log.d(TAG,
+ "setCallControlPointResult: device=" + device + " requestedOpcode="
+ + requestedOpcode + " callIndex=" + callIndex + " requesuResult="
+ + requestResult);
mCallControlPointCharacteristic.setResult(device, requestedOpcode, callIndex,
requestResult);
}
@@ -986,12 +969,10 @@
private final AdapterService.BluetoothStateCallback mBluetoothStateChangeCallback =
new AdapterService.BluetoothStateCallback() {
public void onBluetoothStateChange(int prevState, int newState) {
- if (DBG) {
- Log.d(
- TAG,
- "onBluetoothStateChange: state="
- + BluetoothAdapter.nameForState(newState));
- }
+ Log.d(
+ TAG,
+ "onBluetoothStateChange: state="
+ + BluetoothAdapter.nameForState(newState));
if (newState == BluetoothAdapter.STATE_ON) {
restoreCccValuesForStoredDevices();
}
@@ -1204,9 +1185,7 @@
switch (op.mOperation) {
case READ_CHARACTERISTIC:
- if (DBG) {
- Log.d(TAG, "onCharacteristicReadRequest: device=" + device);
- }
+ Log.d(TAG, "onCharacteristicReadRequest: device=" + device);
if (getDeviceAuthorization(device) != BluetoothDevice.ACCESS_ALLOWED) {
onRejectedAuthorizationGattOperation(device, op);
@@ -1242,9 +1221,7 @@
break;
case WRITE_CHARACTERISTIC:
- if (DBG) {
- Log.d(TAG, "onCharacteristicWriteRequest: device=" + device);
- }
+ Log.d(TAG, "onCharacteristicWriteRequest: device=" + device);
if (getDeviceAuthorization(device) != BluetoothDevice.ACCESS_ALLOWED) {
onRejectedAuthorizationGattOperation(device, op);
@@ -1269,9 +1246,7 @@
break;
case READ_DESCRIPTOR:
- if (DBG) {
- Log.d(TAG, "onDescriptorReadRequest: device=" + device);
- }
+ Log.d(TAG, "onDescriptorReadRequest: device=" + device);
if (getDeviceAuthorization(device) != BluetoothDevice.ACCESS_ALLOWED) {
onRejectedAuthorizationGattOperation(device, op);
@@ -1291,9 +1266,7 @@
break;
case WRITE_DESCRIPTOR:
- if (DBG) {
- Log.d(TAG, "onDescriptorWriteRequest: device=" + device);
- }
+ Log.d(TAG, "onDescriptorWriteRequest: device=" + device);
if (getDeviceAuthorization(device) != BluetoothDevice.ACCESS_ALLOWED) {
onRejectedAuthorizationGattOperation(device, op);
@@ -1394,9 +1367,7 @@
}
private void clearUnauthorizedGattOperationss(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "clearUnauthorizedGattOperationss device: " + device);
- }
+ Log.d(TAG, "clearUnauthorizedGattOperationss device: " + device);
synchronized (mPendingGattOperationsLock) {
mPendingGattOperations.remove(device);
@@ -1404,9 +1375,7 @@
}
private void processPendingGattOperations(BluetoothDevice device) {
- if (DBG) {
- Log.d(TAG, "processPendingGattOperations device: " + device);
- }
+ Log.d(TAG, "processPendingGattOperations device: " + device);
synchronized (mPendingGattOperationsLock) {
if (mPendingGattOperations.containsKey(device)) {
@@ -1433,9 +1402,7 @@
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
- if (DBG) {
- Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange");
- }
+ Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange");
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
clearUnauthorizedGattOperationss(device);
}
@@ -1443,9 +1410,7 @@
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
- if (DBG) {
- Log.d(TAG, "onServiceAdded: status=" + status);
- }
+ Log.d(TAG, "onServiceAdded: status=" + status);
if (mCallback != null) {
mCallback.onServiceAdded(status == BluetoothGatt.GATT_SUCCESS);
}
@@ -1457,10 +1422,8 @@
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
- if (DBG) {
- Log.d(TAG, "BluetoothGattServerCallback: onCharacteristicReadRequest offset= "
- + offset + " entire value= " + Arrays.toString(characteristic.getValue()));
- }
+ Log.d(TAG, "BluetoothGattServerCallback: onCharacteristicReadRequest offset= "
+ + offset + " entire value= " + Arrays.toString(characteristic.getValue()));
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) == 0) {
mBluetoothGattServer.sendResponse(device, requestId,
@@ -1489,11 +1452,9 @@
boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite,
responseNeeded, offset, value);
- if (DBG) {
- Log.d(TAG,
- "BluetoothGattServerCallback: "
- + "onCharacteristicWriteRequest");
- }
+ Log.d(TAG,
+ "BluetoothGattServerCallback: "
+ + "onCharacteristicWriteRequest");
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE)
== 0) {
@@ -1521,11 +1482,9 @@
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset,
BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
- if (DBG) {
- Log.d(TAG,
- "BluetoothGattServerCallback: "
- + "onDescriptorReadRequest");
- }
+ Log.d(TAG,
+ "BluetoothGattServerCallback: "
+ + "onDescriptorReadRequest");
if ((descriptor.getPermissions() & BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED)
== 0) {
@@ -1555,11 +1514,9 @@
int offset, byte[] value) {
super.onDescriptorWriteRequest(
device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
- if (DBG) {
- Log.d(TAG,
- "BluetoothGattServerCallback: "
- + "onDescriptorWriteRequest");
- }
+ Log.d(TAG,
+ "BluetoothGattServerCallback: "
+ + "onDescriptorWriteRequest");
if ((descriptor.getPermissions() & BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED)
== 0) {
diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java b/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java
index a5364f8..3c116fd 100644
--- a/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java
+++ b/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java
@@ -51,7 +51,6 @@
public class TbsGeneric {
private static final String TAG = "TbsGeneric";
- private static final boolean DBG = true;
private static final String UCI = "GTBS";
private static final String DEFAULT_PROVIDER_NAME = "none";
@@ -159,9 +158,7 @@
};
public synchronized boolean init(TbsGatt tbsGatt) {
- if (DBG) {
- Log.d(TAG, "init");
- }
+ Log.d(TAG, "init");
mTbsGatt = tbsGatt;
int ccid = ContentControlIdKeeper.acquireCcid(new ParcelUuid(TbsGatt.UUID_GTBS),
@@ -205,9 +202,7 @@
}
public synchronized void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup");
- }
+ Log.d(TAG, "cleanup");
if (mTbsGatt != null) {
if (mReceiver != null) {
@@ -307,12 +302,10 @@
public synchronized boolean addBearer(String token, IBluetoothLeCallControlCallback callback,
String uci, List<String> uriSchemes, int capabilities, String providerName,
int technology) {
- if (DBG) {
- Log.d(TAG,
- "addBearer: token=" + token + " uci=" + uci + " uriSchemes=" + uriSchemes
- + " capabilities=" + capabilities + " providerName=" + providerName
- + " technology=" + technology);
- }
+ Log.d(TAG,
+ "addBearer: token=" + token + " uci=" + uci + " uriSchemes=" + uriSchemes
+ + " capabilities=" + capabilities + " providerName=" + providerName
+ + " technology=" + technology);
if (!mIsInitialized) {
Log.w(TAG, "addBearer called while not initialized.");
return false;
@@ -359,9 +352,7 @@
}
public synchronized void removeBearer(String token) {
- if (DBG) {
- Log.d(TAG, "removeBearer: token=" + token);
- }
+ Log.d(TAG, "removeBearer: token=" + token);
if (!mIsInitialized) {
Log.w(TAG, "removeBearer called while not initialized.");
@@ -405,9 +396,7 @@
}
if (requestEntry == null) {
- if (DBG) {
- Log.d(TAG, "requestEntry is null");
- }
+ Log.d(TAG, "requestEntry is null");
return;
}
@@ -491,10 +480,8 @@
}
public synchronized void requestResult(int ccid, int requestId, int result) {
- if (DBG) {
- Log.d(TAG, "requestResult: ccid=" + ccid + " requestId=" + requestId + " result="
- + result);
- }
+ Log.d(TAG, "requestResult: ccid=" + ccid + " requestId=" + requestId + " result="
+ + result);
if (!mIsInitialized) {
Log.w(TAG, "requestResult called while not initialized.");
@@ -525,9 +512,7 @@
}
public synchronized void callAdded(int ccid, BluetoothLeCall call) {
- if (DBG) {
- Log.d(TAG, "callAdded: ccid=" + ccid + " call=" + call);
- }
+ Log.d(TAG, "callAdded: ccid=" + ccid + " call=" + call);
if (!mIsInitialized) {
Log.w(TAG, "callAdded called while not initialized.");
@@ -574,9 +559,7 @@
}
public synchronized void callRemoved(int ccid, UUID callId, int reason) {
- if (DBG) {
- Log.d(TAG, "callRemoved: ccid=" + ccid + "reason=" + reason);
- }
+ Log.d(TAG, "callRemoved: ccid=" + ccid + "reason=" + reason);
if (!mIsInitialized) {
Log.w(TAG, "callRemoved called while not initialized.");
@@ -619,9 +602,7 @@
}
public synchronized void callStateChanged(int ccid, UUID callId, int state) {
- if (DBG) {
- Log.d(TAG, "callStateChanged: ccid=" + ccid + " callId=" + callId + " state=" + state);
- }
+ Log.d(TAG, "callStateChanged: ccid=" + ccid + " callId=" + callId + " state=" + state);
if (!mIsInitialized) {
Log.w(TAG, "callStateChanged called while not initialized.");
@@ -658,9 +639,7 @@
}
public synchronized void currentCallsList(int ccid, List<BluetoothLeCall> calls) {
- if (DBG) {
- Log.d(TAG, "currentCallsList: ccid=" + ccid + " callsNum=" + calls.size());
- }
+ Log.d(TAG, "currentCallsList: ccid=" + ccid + " callsNum=" + calls.size());
if (!mIsInitialized) {
Log.w(TAG, "currentCallsList called while not initialized.");
@@ -714,10 +693,8 @@
}
public synchronized void networkStateChanged(int ccid, String providerName, int technology) {
- if (DBG) {
- Log.d(TAG, "networkStateChanged: ccid=" + ccid + " providerName=" + providerName
- + " technology=" + technology);
- }
+ Log.d(TAG, "networkStateChanged: ccid=" + ccid + " providerName=" + providerName
+ + " technology=" + technology);
if (!mIsInitialized) {
Log.w(TAG, "networkStateChanged called while not initialized.");
@@ -794,9 +771,7 @@
@Override
public void onServiceAdded(boolean success) {
synchronized (TbsGeneric.this) {
- if (DBG) {
- Log.d(TAG, "onServiceAdded: success=" + success);
- }
+ Log.d(TAG, "onServiceAdded: success=" + success);
}
}
@@ -813,11 +788,9 @@
@Override
public void onCallControlPointRequest(BluetoothDevice device, int opcode, byte[] args) {
synchronized (TbsGeneric.this) {
- if (DBG) {
- Log.d(TAG, "onCallControlPointRequest: device=" + device + " opcode="
- + callControlRequestOpcodeStr(opcode) + "(" + opcode + ")"
- + " argsLen=" + args.length);
- }
+ Log.d(TAG, "onCallControlPointRequest: device=" + device + " opcode="
+ + callControlRequestOpcodeStr(opcode) + "(" + opcode + ")"
+ + " argsLen=" + args.length);
if (!mIsInitialized) {
Log.w(TAG, "onCallControlPointRequest called while not initialized.");
@@ -1068,9 +1041,7 @@
}
private synchronized void setForegroundBearer(Bearer bearer) {
- if (DBG) {
- Log.d(TAG, "setForegroundBearer: bearer=" + bearer);
- }
+ Log.d(TAG, "setForegroundBearer: bearer=" + bearer);
if (bearer == null) {
mTbsGatt.setBearerProviderName(DEFAULT_PROVIDER_NAME);
@@ -1111,9 +1082,7 @@
}
private synchronized void notifyCclc() {
- if (DBG) {
- Log.d(TAG, "notifyCclc");
- }
+ Log.d(TAG, "notifyCclc");
if (isLeAudioServiceAvailable()) {
if (mCurrentCallsList.size() > 0) {
diff --git a/android/app/src/com/android/bluetooth/tbs/TbsService.java b/android/app/src/com/android/bluetooth/tbs/TbsService.java
index b5342b9..77dc1ca 100644
--- a/android/app/src/com/android/bluetooth/tbs/TbsService.java
+++ b/android/app/src/com/android/bluetooth/tbs/TbsService.java
@@ -44,7 +44,6 @@
public class TbsService extends ProfileService {
private static final String TAG = "TbsService";
- private static final boolean DBG = true;
private static TbsService sTbsService;
private Map<BluetoothDevice, Integer> mDeviceAuthorizations = new HashMap<>();
@@ -67,9 +66,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sTbsService != null) {
throw new IllegalStateException("start() called twice");
}
@@ -82,9 +79,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sTbsService == null) {
Log.w(TAG, "stop() called before start()");
return;
@@ -100,9 +95,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
mDeviceAuthorizations.clear();
}
@@ -126,9 +119,7 @@
}
private static synchronized void setTbsService(TbsService instance) {
- if (DBG) {
- Log.d(TAG, "setTbsService: set to=" + instance);
- }
+ Log.d(TAG, "setTbsService: set to=" + instance);
sTbsService = instance;
}
@@ -200,9 +191,7 @@
if (leAudioService.getConnectionPolicy(device)
> BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
- if (DBG) {
- Log.d(TAG, "TBS authorization allowed based on supported LeAudio service");
- }
+ Log.d(TAG, "TBS authorization allowed based on supported LeAudio service");
setDeviceAuthorized(device, true);
return BluetoothDevice.ACCESS_ALLOWED;
}
@@ -254,9 +243,7 @@
}
if (mService != null) {
- if (DBG) {
- Log.d(TAG, "Service available");
- }
+ Log.d(TAG, "Service available");
enforceBluetoothPrivilegedPermission(mService);
return mService;
@@ -368,9 +355,7 @@
@VisibleForTesting
void registerBearer(String token, IBluetoothLeCallControlCallback callback, String uci,
List<String> uriSchemes, int capabilities, String providerName, int technology) {
- if (DBG) {
- Log.d(TAG, "registerBearer: token=" + token);
- }
+ Log.d(TAG, "registerBearer: token=" + token);
boolean success = mTbsGeneric.addBearer(token, callback, uci, uriSchemes, capabilities,
providerName, technology);
@@ -385,72 +370,56 @@
}
}
- if (DBG) {
- Log.d(TAG, "registerBearer: token=" + token + " success=" + success);
- }
+ Log.d(TAG, "registerBearer: token=" + token + " success=" + success);
}
@VisibleForTesting
void unregisterBearer(String token) {
- if (DBG) {
- Log.d(TAG, "unregisterBearer: token=" + token);
- }
+ Log.d(TAG, "unregisterBearer: token=" + token);
mTbsGeneric.removeBearer(token);
}
@VisibleForTesting
public void requestResult(int ccid, int requestId, int result) {
- if (DBG) {
- Log.d(TAG, "requestResult: ccid=" + ccid + " requestId=" + requestId + " result="
- + result);
- }
+ Log.d(TAG, "requestResult: ccid=" + ccid + " requestId=" + requestId + " result="
+ + result);
mTbsGeneric.requestResult(ccid, requestId, result);
}
@VisibleForTesting
void callAdded(int ccid, BluetoothLeCall call) {
- if (DBG) {
- Log.d(TAG, "callAdded: ccid=" + ccid + " call=" + call);
- }
+ Log.d(TAG, "callAdded: ccid=" + ccid + " call=" + call);
mTbsGeneric.callAdded(ccid, call);
}
@VisibleForTesting
void callRemoved(int ccid, UUID callId, int reason) {
- if (DBG) {
- Log.d(TAG, "callRemoved: ccid=" + ccid + " callId=" + callId + " reason=" + reason);
- }
+ Log.d(TAG, "callRemoved: ccid=" + ccid + " callId=" + callId + " reason=" + reason);
mTbsGeneric.callRemoved(ccid, callId, reason);
}
@VisibleForTesting
void callStateChanged(int ccid, UUID callId, int state) {
- if (DBG) {
- Log.d(TAG, "callStateChanged: ccid=" + ccid + " callId=" + callId + " state=" + state);
- }
+ Log.d(TAG, "callStateChanged: ccid=" + ccid + " callId=" + callId + " state=" + state);
mTbsGeneric.callStateChanged(ccid, callId, state);
}
@VisibleForTesting
void currentCallsList(int ccid, List<BluetoothLeCall> calls) {
- if (DBG) {
- Log.d(TAG, "currentCallsList: ccid=" + ccid + " calls=" + calls);
- }
+ Log.d(TAG, "currentCallsList: ccid=" + ccid + " calls=" + calls);
mTbsGeneric.currentCallsList(ccid, calls);
}
@VisibleForTesting
void networkStateChanged(int ccid, String providerName, int technology) {
- if (DBG) {
- Log.d(TAG, "networkStateChanged: ccid=" + ccid + " providerName=" + providerName
- + " technology=" + technology);
- }
+ Log.d(TAG, "networkStateChanged: ccid=" + ccid + " providerName=" + providerName
+ + " technology=" + technology);
mTbsGeneric.networkStateChanged(ccid, providerName, technology);
}
diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java
index e76d8ad..818d18d 100644
--- a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java
@@ -27,7 +27,6 @@
public class VolumeControlNativeInterface {
private static final String TAG = "VolumeControlNativeInterface";
- private static final boolean DBG = true;
private BluetoothAdapter mAdapter;
@GuardedBy("INSTANCE_LOCK")
@@ -273,9 +272,7 @@
event.device = getDevice(address);
event.valueInt1 = state;
- if (DBG) {
- Log.d(TAG, "onConnectionStateChanged: " + event);
- }
+ Log.d(TAG, "onConnectionStateChanged: " + event);
sendMessageToService(event);
}
@@ -291,9 +288,7 @@
event.valueBool1 = mute;
event.valueBool2 = isAutonomous;
- if (DBG) {
- Log.d(TAG, "onVolumeStateChanged: " + event);
- }
+ Log.d(TAG, "onVolumeStateChanged: " + event);
sendMessageToService(event);
}
@@ -309,9 +304,7 @@
event.valueBool1 = mute;
event.valueBool2 = isAutonomous;
- if (DBG) {
- Log.d(TAG, "onGroupVolumeStateChanged: " + event);
- }
+ Log.d(TAG, "onGroupVolumeStateChanged: " + event);
sendMessageToService(event);
}
@@ -324,9 +317,7 @@
event.device = getDevice(address);
event.valueInt1 = numOfExternalOutputs;
- if (DBG) {
- Log.d(TAG, "onDeviceAvailable: " + event);
- }
+ Log.d(TAG, "onDeviceAvailable: " + event);
sendMessageToService(event);
}
@@ -340,9 +331,7 @@
event.valueInt1 = externalOutputId;
event.valueInt2 = offset;
- if (DBG) {
- Log.d(TAG, "onExtAudioOutVolumeOffsetChanged: " + event);
- }
+ Log.d(TAG, "onExtAudioOutVolumeOffsetChanged: " + event);
sendMessageToService(event);
}
@@ -356,9 +345,7 @@
event.valueInt1 = externalOutputId;
event.valueInt2 = location;
- if (DBG) {
- Log.d(TAG, "onExtAudioOutLocationChanged: " + event);
- }
+ Log.d(TAG, "onExtAudioOutLocationChanged: " + event);
sendMessageToService(event);
}
@@ -372,9 +359,7 @@
event.valueInt1 = externalOutputId;
event.valueString1 = descr;
- if (DBG) {
- Log.d(TAG, "onExtAudioOutLocationChanged: " + event);
- }
+ Log.d(TAG, "onExtAudioOutLocationChanged: " + event);
sendMessageToService(event);
}
diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
index f7f926f..2e0e455 100644
--- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
+++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
@@ -63,7 +63,6 @@
public class VolumeControlService extends ProfileService {
private static final String TAG = "VolumeControlService";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
// Timeout for state machine thread join, to prevent potential ANR.
private static final int SM_THREAD_JOIN_TIMEOUT_MS = 1000;
@@ -211,9 +210,7 @@
@Override
public void start() {
- if (DBG) {
- Log.d(TAG, "start()");
- }
+ Log.d(TAG, "start()");
if (sVolumeControlService != null) {
throw new IllegalStateException("start() called twice");
}
@@ -252,9 +249,7 @@
@Override
public void stop() {
- if (DBG) {
- Log.d(TAG, "stop()");
- }
+ Log.d(TAG, "stop()");
if (sVolumeControlService == null) {
Log.w(TAG, "stop() called before start()");
return;
@@ -310,9 +305,7 @@
@Override
public void cleanup() {
- if (DBG) {
- Log.d(TAG, "cleanup()");
- }
+ Log.d(TAG, "cleanup()");
}
/**
@@ -334,9 +327,7 @@
@VisibleForTesting
static synchronized void setVolumeControlService(VolumeControlService instance) {
- if (DBG) {
- Log.d(TAG, "setVolumeControlService(): set to: " + instance);
- }
+ Log.d(TAG, "setVolumeControlService(): set to: " + instance);
sVolumeControlService = instance;
}
@@ -344,9 +335,7 @@
public boolean connect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "connect(): " + device);
- }
+ Log.d(TAG, "connect(): " + device);
if (device == null) {
return false;
}
@@ -377,9 +366,7 @@
public boolean disconnect(BluetoothDevice device) {
enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED,
"Need BLUETOOTH_PRIVILEGED permission");
- if (DBG) {
- Log.d(TAG, "disconnect(): " + device);
- }
+ Log.d(TAG, "disconnect(): " + device);
if (device == null) {
return false;
}
@@ -520,9 +507,7 @@
* @return true on success, otherwise false
*/
public boolean setConnectionPolicy(BluetoothDevice device, int connectionPolicy) {
- if (DBG) {
- Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
- }
+ Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(device, BluetoothProfile.VOLUME_CONTROL,
connectionPolicy);
if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
@@ -593,16 +578,14 @@
if (!Flags.leaudioBroadcastVolumeControlForConnectedDevices()) {
return;
}
- if (DBG) {
- Log.d(
- TAG,
- "setDeviceVolume: "
- + device
- + ", volume: "
- + volume
- + ", isGroupOp: "
- + isGroupOp);
- }
+ Log.d(
+ TAG,
+ "setDeviceVolume: "
+ + device
+ + ", volume: "
+ + volume
+ + ", isGroupOp: "
+ + isGroupOp);
LeAudioService leAudioService = mFactory.getLeAudioService();
if (leAudioService == null) {
@@ -684,9 +667,7 @@
* @param active indicator if group is active or not
*/
public void setGroupActive(int groupId, boolean active) {
- if (DBG) {
- Log.d(TAG, "setGroupActive: " + groupId + ", active: " + active);
- }
+ Log.d(TAG, "setGroupActive: " + groupId + ", active: " + active);
if (!active) {
/* For now we don't need to handle group inactivation */
return;
@@ -727,9 +708,7 @@
}
void notifyNewCallbackOfKnownVolumeInfo(IBluetoothVolumeControlCallback callback) {
- if (DBG) {
- Log.d(TAG, "notifyNewCallbackOfKnownVolumeInfo");
- }
+ Log.d(TAG, "notifyNewCallbackOfKnownVolumeInfo");
RemoteCallbackList<IBluetoothVolumeControlCallback> tempCallbackList =
new RemoteCallbackList<>();
@@ -759,20 +738,18 @@
int location = descriptor.getLocation(id);
String description = descriptor.getDescription(id);
- if (DBG) {
- Log.d(
- TAG,
- "notifyNewCallbackOfKnownVolumeInfo, device: "
- + device
- + ", id: "
- + id
- + ", offset: "
- + offset
- + ", location: "
- + location
- + ", description: "
- + description);
- }
+ Log.d(
+ TAG,
+ "notifyNewCallbackOfKnownVolumeInfo, device: "
+ + device
+ + ", id: "
+ + id
+ + ", offset: "
+ + offset
+ + ", location: "
+ + location
+ + ", description: "
+ + description);
try {
tempCallbackList
@@ -812,9 +789,7 @@
}
void registerCallback(IBluetoothVolumeControlCallback callback) {
- if (DBG) {
- Log.d(TAG, "registerCallback: " + callback);
- }
+ Log.d(TAG, "registerCallback: " + callback);
/* Here we keep all the user callbacks */
mCallbacks.register(callback);
@@ -822,9 +797,7 @@
}
void notifyNewRegisteredCallback(IBluetoothVolumeControlCallback callback) {
- if (DBG) {
- Log.d(TAG, "notifyNewRegisteredCallback: " + callback);
- }
+ Log.d(TAG, "notifyNewRegisteredCallback: " + callback);
notifyNewCallbackOfKnownVolumeInfo(callback);
}
@@ -1038,9 +1011,7 @@
int getBluetoothContextualVolumeStream() {
int mode = mAudioManager.getMode();
- if (DBG) {
- Log.d(TAG, "Volume mode: " + mode + "0: normal, 1: ring, 2,3: call");
- }
+ Log.d(TAG, "Volume mode: " + mode + "0: normal, 1: ring, 2,3: call");
switch (mode) {
case AudioManager.MODE_IN_COMMUNICATION:
@@ -1048,9 +1019,7 @@
return AudioManager.STREAM_VOICE_CALL;
case AudioManager.MODE_RINGTONE:
if (Flags.leaudioVolumeChangeOnRingtoneFix()) {
- if (DBG) {
- Log.d(TAG, " Update during ringtone applied to voice call");
- }
+ Log.d(TAG, " Update during ringtone applied to voice call");
return AudioManager.STREAM_VOICE_CALL;
}
// fall through
@@ -1088,9 +1057,7 @@
}
void handleDeviceExtAudioOffsetChanged(BluetoothDevice device, int id, int value) {
- if (DBG) {
- Log.d(TAG, " device: " + device + " offset_id: " + id + " value: " + value);
- }
+ Log.d(TAG, " device: " + device + " offset_id: " + id + " value: " + value);
VolumeControlOffsetDescriptor offsets = mAudioOffsets.get(device);
if (offsets == null) {
Log.e(TAG, " Offsets not found for device: " + device);
@@ -1114,10 +1081,8 @@
}
void handleDeviceExtAudioLocationChanged(BluetoothDevice device, int id, int location) {
- if (DBG) {
- Log.d(TAG, " device: " + device + " offset_id: "
- + id + " location: " + location);
- }
+ Log.d(TAG, " device: " + device + " offset_id: "
+ + id + " location: " + location);
VolumeControlOffsetDescriptor offsets = mAudioOffsets.get(device);
if (offsets == null) {
@@ -1147,10 +1112,8 @@
void handleDeviceExtAudioDescriptionChanged(
BluetoothDevice device, int id, String description) {
- if (DBG) {
- Log.d(TAG, " device: " + device + " offset_id: "
- + id + " description: " + description);
- }
+ Log.d(TAG, " device: " + device + " offset_id: "
+ + id + " description: " + description);
VolumeControlOffsetDescriptor offsets = mAudioOffsets.get(device);
if (offsets == null) {
@@ -1179,9 +1142,7 @@
}
void messageFromNative(VolumeControlStackEvent stackEvent) {
- if (DBG) {
- Log.d(TAG, "messageFromNative: " + stackEvent);
- }
+ Log.d(TAG, "messageFromNative: " + stackEvent);
if (stackEvent.type == VolumeControlStackEvent.EVENT_TYPE_VOLUME_STATE_CHANGED) {
handleVolumeControlChanged(stackEvent.device, stackEvent.valueInt1,
@@ -1267,9 +1228,7 @@
+ MAX_VC_STATE_MACHINES);
return null;
}
- if (DBG) {
- Log.d(TAG, "Creating a new state machine for " + device);
- }
+ Log.d(TAG, "Creating a new state machine for " + device);
sm = VolumeControlStateMachine.make(device, this,
mVolumeControlNativeInterface, mStateMachinesThread.getLooper());
mStateMachines.put(device, sm);
@@ -1350,9 +1309,7 @@
*/
@VisibleForTesting
void bondStateChanged(BluetoothDevice device, int bondState) {
- if (DBG) {
- Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
- }
+ Log.d(TAG, "Bond state changed for device: " + device + " state: " + bondState);
// Remove state machine if the bonding for a device is removed
if (bondState != BluetoothDevice.BOND_NONE) {
return;
@@ -1409,9 +1366,7 @@
if (toState == BluetoothProfile.STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
- if (DBG) {
- Log.d(TAG, device + " is unbond. Remove state machine");
- }
+ Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
}
} else if (toState == BluetoothProfile.STATE_CONNECTED) {
diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java b/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java
index 10ddb8a..1fa26e8 100644
--- a/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java
+++ b/android/app/src/com/android/bluetooth/vc/VolumeControlStateMachine.java
@@ -39,7 +39,6 @@
public class VolumeControlStateMachine extends StateMachine {
- private static final boolean DBG = false;
private static final String TAG = "VolumeControlStateMachine";
static final int CONNECT = 1;
@@ -151,9 +150,7 @@
break;
case STACK_EVENT:
VolumeControlStackEvent event = (VolumeControlStackEvent) message.obj;
- if (DBG) {
- Log.d(TAG, "Disconnected: stack event: " + event);
- }
+ Log.d(TAG, "Disconnected: stack event: " + event);
if (!mDevice.equals(event.device)) {
Log.wtf(TAG, "Device(" + mDevice + "): event mismatch: " + event);
}
@@ -568,8 +565,6 @@
@Override
protected void log(String msg) {
- if (DBG) {
- super.log(msg);
- }
+ super.log(msg);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java
index d245b81..ae9965b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java
@@ -152,7 +152,8 @@
*/
private AvrcpControllerStateMachine makeStateMachine(BluetoothDevice device) {
AvrcpControllerStateMachine sm =
- new AvrcpControllerStateMachine(device, mAvrcpControllerService, mNativeInterface);
+ new AvrcpControllerStateMachine(
+ device, mAvrcpControllerService, mNativeInterface, false);
sm.start();
return sm;
}
@@ -1119,6 +1120,55 @@
.sendRegisterAbsVolRsp(any(), anyByte(), eq(127), eq((int) label));
}
+ /** Test that set absolute volume is working */
+ @Test
+ public void testSetAbsoluteVolume_volumeIsFixed_setsAbsVolumeBase() {
+ byte label = 42;
+ setUpConnectedState(true, true);
+ mAvrcpStateMachine.sendMessage(
+ AvrcpControllerStateMachine.MESSAGE_PROCESS_SET_ABS_VOL_CMD, 20, label);
+ verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS))
+ .sendAbsVolRsp(any(), eq(127), eq((int) label));
+ }
+
+ /** Test that set absolute volume is working */
+ @Test
+ public void testSetAbsoluteVolume_volumeIsNotFixed_setsAbsVolumeBase() {
+ doReturn(false).when(mAudioManager).isVolumeFixed();
+ mAvrcpStateMachine =
+ new AvrcpControllerStateMachine(
+ mTestDevice, mAvrcpControllerService, mNativeInterface, false);
+ mAvrcpStateMachine.start();
+ byte label = 42;
+ setUpConnectedState(true, true);
+ doReturn(100).when(mAudioManager).getStreamMaxVolume(eq(AudioManager.STREAM_MUSIC));
+ doReturn(25).when(mAudioManager).getStreamVolume(eq(AudioManager.STREAM_MUSIC));
+ mAvrcpStateMachine.sendMessage(
+ AvrcpControllerStateMachine.MESSAGE_PROCESS_SET_ABS_VOL_CMD, 20, label);
+ verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS))
+ .sendAbsVolRsp(any(), eq(20), eq((int) label));
+ verify(mAudioManager, timeout(ASYNC_CALL_TIMEOUT_MILLIS))
+ .setStreamVolume(
+ eq(AudioManager.STREAM_MUSIC), eq(15), eq(AudioManager.FLAG_SHOW_UI));
+ }
+
+ /** Test that set absolute volume is working */
+ @Test
+ public void
+ testSetAbsoluteVolume_volumeIsNotFixedSinkAbsoluteVolumeEnabled_setsAbsVolumeBase() {
+ doReturn(false).when(mAudioManager).isVolumeFixed();
+ mAvrcpStateMachine =
+ new AvrcpControllerStateMachine(
+ mTestDevice, mAvrcpControllerService, mNativeInterface, true);
+ mAvrcpStateMachine.start();
+ byte label = 42;
+ setUpConnectedState(true, true);
+ mAvrcpStateMachine.sendMessage(
+ AvrcpControllerStateMachine.MESSAGE_PROCESS_SET_ABS_VOL_CMD, 20, label);
+ verify(mNativeInterface, timeout(ASYNC_CALL_TIMEOUT_MILLIS))
+ .sendAbsVolRsp(any(), eq(127), eq((int) label));
+ }
+
/**
* Test playback does not request focus when another app is playing music.
*/
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java
index f556f19..5740a80 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java
@@ -158,9 +158,7 @@
AvrcpPlayer avrcpPlayer = new AvrcpPlayer.Builder().setPlayerId(TEST_PLAYER_ID).setName(
TEST_NAME).setCurrentTrack(mAvrcpItem).build();
- assertThat(avrcpPlayer.toString()).isEqualTo(
- "<AvrcpPlayer id=" + TEST_PLAYER_ID + " name=" + TEST_NAME + " track="
- + mAvrcpItem + " playState=" + avrcpPlayer.getPlaybackState() + ">");
+ assertThat(avrcpPlayer.toString()).isNotNull();
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java
index 273ac96..ebc870c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/MetricsLoggerTest.java
@@ -42,15 +42,48 @@
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
+import java.util.Map;
-/**
- * Unit tests for {@link MetricsLogger}
- */
+/** Unit tests for {@link MetricsLogger} */
@MediumTest
@RunWith(AndroidJUnit4.class)
public class MetricsLoggerTest {
private static final String TEST_BLOOMFILTER_NAME = "TestBloomfilter";
+ private static final HashMap<String, String> SANITIZED_DEVICE_NAME_MAP = new HashMap<>();
+
+ static {
+ SANITIZED_DEVICE_NAME_MAP.put("AirpoDspro", "airpodspro");
+ SANITIZED_DEVICE_NAME_MAP.put("AirpoDs-pro", "airpodspro");
+ SANITIZED_DEVICE_NAME_MAP.put("Someone's AirpoDs", "airpods");
+ SANITIZED_DEVICE_NAME_MAP.put("Galaxy Buds pro", "galaxybudspro");
+ SANITIZED_DEVICE_NAME_MAP.put("Someone's AirpoDs", "airpods");
+ SANITIZED_DEVICE_NAME_MAP.put("Who's Pixel 7", "pixel7");
+ SANITIZED_DEVICE_NAME_MAP.put("陈的pixel 7手机", "pixel7");
+ SANITIZED_DEVICE_NAME_MAP.put("pixel 7 pro", "pixel7pro");
+ SANITIZED_DEVICE_NAME_MAP.put("My Pixel 7 Pro", "pixel7pro");
+ SANITIZED_DEVICE_NAME_MAP.put("My Pixel 7 PRO", "pixel7pro");
+ SANITIZED_DEVICE_NAME_MAP.put("My Pixel 7 - PRO", "pixel7pro");
+ SANITIZED_DEVICE_NAME_MAP.put("My BMW X5", "bmwx5");
+ SANITIZED_DEVICE_NAME_MAP.put("Jane Doe's Tesla Model--X", "teslamodelx");
+ SANITIZED_DEVICE_NAME_MAP.put("TESLA of Jane DOE", "tesla");
+ SANITIZED_DEVICE_NAME_MAP.put("SONY WH-1000XM noise cancelling headsets", "sonywh1000xm");
+ SANITIZED_DEVICE_NAME_MAP.put("Amazon Echo Dot in Kitchen", "amazonechodot");
+ SANITIZED_DEVICE_NAME_MAP.put("斯巴鲁 Starlink", "starlink");
+ SANITIZED_DEVICE_NAME_MAP.put("大黄蜂MyLink", "mylink");
+ SANITIZED_DEVICE_NAME_MAP.put("Dad's Fitbit Charge 3", "fitbitcharge3");
+ SANITIZED_DEVICE_NAME_MAP.put("Mike's new Galaxy Buds 2", "galaxybuds2");
+ SANITIZED_DEVICE_NAME_MAP.put("My third Ford F-150", "fordf150");
+ SANITIZED_DEVICE_NAME_MAP.put("BOSE QC_35 Noise Cancelling Headsets", "boseqc35");
+ SANITIZED_DEVICE_NAME_MAP.put("Fitbit versa 3 band", "fitbitversa3");
+ SANITIZED_DEVICE_NAME_MAP.put("vw atlas", "vwatlas");
+ SANITIZED_DEVICE_NAME_MAP.put("My volkswagen tiguan", "volkswagentiguan");
+ SANITIZED_DEVICE_NAME_MAP.put("SomeDevice1", "");
+ SANITIZED_DEVICE_NAME_MAP.put("Some Device-2", "");
+ SANITIZED_DEVICE_NAME_MAP.put("abcgfDG gdfg", "");
+ SANITIZED_DEVICE_NAME_MAP.put("Bluetooth headset", "");
+ }
+
private TestableMetricsLogger mTestableMetricsLogger;
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
@@ -64,20 +97,17 @@
@Override
public boolean count(int key, long count) {
mTestableCounters.put(key, count);
- return true;
+ return true;
}
@Override
- protected void scheduleDrains() {
- }
+ protected void scheduleDrains() {}
@Override
- protected void cancelPendingDrain() {
- }
+ protected void cancelPendingDrain() {}
@Override
- protected void statslogBluetoothDeviceNames(
- int metricId, String matchedString, String sha256) {
+ protected void statslogBluetoothDeviceNames(int metricId, String matchedString) {
mTestableDeviceNames.merge(matchedString, 1, Integer::sum);
}
}
@@ -88,8 +118,7 @@
MetricsLogger.dumpProto(BluetoothLog.newBuilder());
mTestableMetricsLogger = new TestableMetricsLogger();
mTestableMetricsLogger.mBloomFilterInitialized = true;
- doReturn(null)
- .when(mMockAdapterService).registerReceiver(any(), any());
+ doReturn(null).when(mMockAdapterService).registerReceiver(any(), any());
}
@After
@@ -99,9 +128,7 @@
mTestableMetricsLogger.close();
}
- /**
- * Simple test to verify that profile connection event can be logged, dumped, and cleaned
- */
+ /** Simple test to verify that profile connection event can be logged, dumped, and cleaned */
@Test
public void testLogProfileConnectionEvent() {
MetricsLogger.logProfileConnectionEvent(ProfileId.AVRCP);
@@ -119,9 +146,7 @@
Assert.assertEquals(0, metricsProtoAfterDump.getProfileConnectionStatsCount());
}
- /**
- * Test whether multiple profile's connection events can be logged interleaving
- */
+ /** Test whether multiple profile's connection events can be logged interleaving */
@Test
public void testLogProfileConnectionEventMultipleProfile() {
MetricsLogger.logProfileConnectionEvent(ProfileId.AVRCP);
@@ -134,11 +159,11 @@
HashMap<ProfileId, ProfileConnectionStats> profileConnectionCountMap =
getProfileUsageStatsMap(metricsProto.getProfileConnectionStatsList());
Assert.assertTrue(profileConnectionCountMap.containsKey(ProfileId.AVRCP));
- Assert.assertEquals(2,
- profileConnectionCountMap.get(ProfileId.AVRCP).getNumTimesConnected());
+ Assert.assertEquals(
+ 2, profileConnectionCountMap.get(ProfileId.AVRCP).getNumTimesConnected());
Assert.assertTrue(profileConnectionCountMap.containsKey(ProfileId.HEADSET));
- Assert.assertEquals(1,
- profileConnectionCountMap.get(ProfileId.HEADSET).getNumTimesConnected());
+ Assert.assertEquals(
+ 1, profileConnectionCountMap.get(ProfileId.HEADSET).getNumTimesConnected());
// Verify that MetricsLogger's internal state is cleared after a dump
BluetoothLog.Builder metricsBuilderAfterDump = BluetoothLog.newBuilder();
MetricsLogger.dumpProto(metricsBuilderAfterDump);
@@ -153,9 +178,7 @@
return profileUsageStatsMap;
}
- /**
- * Test add counters and send them to statsd
- */
+ /** Test add counters and send them to statsd */
@Test
public void testAddAndSendCountersNormalCases() {
mTestableMetricsLogger.init(mMockAdapterService);
@@ -172,12 +195,9 @@
mTestableMetricsLogger.cacheCount(2, 5);
mTestableMetricsLogger.cacheCount(3, 1);
mTestableMetricsLogger.drainBufferedCounters();
- Assert.assertEquals(
- 3L, mTestableMetricsLogger.mTestableCounters.get(1).longValue());
- Assert.assertEquals(
- 10L, mTestableMetricsLogger.mTestableCounters.get(2).longValue());
- Assert.assertEquals(
- 1L, mTestableMetricsLogger.mTestableCounters.get(3).longValue());
+ Assert.assertEquals(3L, mTestableMetricsLogger.mTestableCounters.get(1).longValue());
+ Assert.assertEquals(10L, mTestableMetricsLogger.mTestableCounters.get(2).longValue());
+ Assert.assertEquals(1L, mTestableMetricsLogger.mTestableCounters.get(3).longValue());
}
@Test
@@ -204,8 +224,7 @@
mTestableMetricsLogger.cacheCount(2, Long.MAX_VALUE);
mTestableMetricsLogger.close();
- Assert.assertEquals(
- 1, mTestableMetricsLogger.mTestableCounters.get(1).longValue());
+ Assert.assertEquals(1, mTestableMetricsLogger.mTestableCounters.get(1).longValue());
Assert.assertEquals(
Long.MAX_VALUE, mTestableMetricsLogger.mTestableCounters.get(2).longValue());
}
@@ -226,173 +245,27 @@
}
@Test
- public void testDeviceNameUploadingDeviceSet1() {
- initTestingBloomfitler();
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "a b c d e f g h pixel 7");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "AirpoDspro");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("airpodspro").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "AirpoDs-pro");
- Assert.assertEquals(2,
- mTestableMetricsLogger.mTestableDeviceNames.get("airpodspro").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "Someone's AirpoDs");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("airpods").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "Who's Pixel 7");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("pixel7").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "陈的pixel 7手机");
- Assert.assertEquals(2,
- mTestableMetricsLogger.mTestableDeviceNames.get("pixel7").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(2, "pixel 7 pro");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("pixel7pro").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "My Pixel 7 PRO");
- Assert.assertEquals(2,
- mTestableMetricsLogger.mTestableDeviceNames.get("pixel7pro").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "My Pixel 7 PRO");
- Assert.assertEquals(3,
- mTestableMetricsLogger.mTestableDeviceNames.get("pixel7pro").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "My Pixel 7 - PRO");
- Assert.assertEquals(4,
- mTestableMetricsLogger.mTestableDeviceNames.get("pixel7pro").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "My BMW X5");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("bmwx5").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "Jane Doe's Tesla Model--X");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("teslamodelx").intValue());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "TESLA of Jane DOE");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("tesla").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "SONY WH-1000XM noise cancelling headsets");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("sonywh1000xm").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "SONY WH-1000XM4 noise cancelling headsets");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("sonywh1000xm4").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "Amazon Echo Dot in Kitchen");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("amazonechodot").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "斯巴鲁 Starlink");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("starlink").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "大黄蜂MyLink");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("mylink").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "Dad's Fitbit Charge 3");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("fitbitcharge3").intValue());
-
- mTestableMetricsLogger.mTestableDeviceNames.clear();
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, " ");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "SomeDevice1");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "Bluetooth headset");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(3, "Some Device-2");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(5, "abcgfDG gdfg");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
+ public void testDeviceNameToSha() {
+ initTestingBloomfilter();
+ for (Map.Entry<String, String> entry : SANITIZED_DEVICE_NAME_MAP.entrySet()) {
+ String deviceName = entry.getKey();
+ String sha256 = MetricsLogger.getSha256String(entry.getValue());
+ Assert.assertEquals(
+ sha256,
+ mTestableMetricsLogger.logAllowlistedDeviceNameHash(1, deviceName, true));
+ }
}
@Test
- public void testDeviceNameUploadingDeviceSet2() {
- initTestingBloomfitler();
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "Galaxy Buds pro");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("galaxybudspro").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "Mike's new Galaxy Buds 2");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("galaxybuds2").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(877, "My third Ford F-150");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("fordf150").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "BOSE QC_35 Noise Cancelling Headsets");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("boseqc35").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "BOSE Quiet Comfort 35 Headsets");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("bosequietcomfort35").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "Fitbit versa 3 band");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("fitbitversa3").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "vw atlas");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("vwatlas").intValue());
-
- mTestableMetricsLogger
- .logSanitizedBluetoothDeviceName(1, "My volkswagen tiguan");
- Assert.assertEquals(1,
- mTestableMetricsLogger.mTestableDeviceNames.get("volkswagentiguan").intValue());
-
- mTestableMetricsLogger.mTestableDeviceNames.clear();
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, " ");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, "weirddevice");
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
- mTestableMetricsLogger.logSanitizedBluetoothDeviceName(1, ""
- + "My BOSE Quiet Comfort 35 Noise Cancelling Headsets");
- // Too long, won't process
- Assert.assertTrue(mTestableMetricsLogger.mTestableDeviceNames.isEmpty());
-
+ public void uploadEmptyDeviceName() {
+ initTestingBloomfilter();
+ Assert.assertEquals("", mTestableMetricsLogger.logAllowlistedDeviceNameHash(1, "", true));
}
- private void initTestingBloomfitler() {
- byte[] bloomfilterData = DeviceBloomfilterGenerator.hexStringToByteArray(
- DeviceBloomfilterGenerator.BLOOM_FILTER_DEFAULT);
+
+ private void initTestingBloomfilter() {
+ byte[] bloomfilterData =
+ DeviceBloomfilterGenerator.hexStringToByteArray(
+ DeviceBloomfilterGenerator.BLOOM_FILTER_DEFAULT);
try {
mTestableMetricsLogger.setBloomfilter(
BloomFilter.readFrom(
diff --git a/flags/gap.aconfig b/flags/gap.aconfig
index a1d3619..8c60694 100644
--- a/flags/gap.aconfig
+++ b/flags/gap.aconfig
@@ -149,3 +149,13 @@
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ name: "update_inquiry_result_on_flag_change"
+ namespace: "bluetooth"
+ description: "Update ADV flag in inquiry result as soon as updated flag received"
+ bug: "329872838"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
diff --git a/framework/java/android/bluetooth/BluetoothSocket.java b/framework/java/android/bluetooth/BluetoothSocket.java
index e9e23b1..af89bf4 100644
--- a/framework/java/android/bluetooth/BluetoothSocket.java
+++ b/framework/java/android/bluetooth/BluetoothSocket.java
@@ -156,13 +156,12 @@
@UnsupportedAppUsage private int mPort; /* RFCOMM channel or L2CAP psm */
private String mServiceName;
- private static final int SOCK_SIGNAL_SIZE = 24;
+ private static final int SOCK_SIGNAL_SIZE = 36;
private ByteBuffer mL2capBuffer = null;
private int mMaxTxPacketSize = 0; // The l2cap maximum packet size supported by the peer.
private int mMaxRxPacketSize = 0; // The l2cap maximum packet size that can be received.
- private int mL2capLocalCid = 0;
- private int mL2capRemoteCid = 0;
+ private ParcelUuid mConnectionUuid;
private long mSocketCreationTimeNanos = 0;
private long mSocketCreationLatencyNanos = 0;
@@ -299,8 +298,7 @@
mOutputStream = new BluetoothOutputStream(this);
mMaxRxPacketSize = s.mMaxRxPacketSize;
mMaxTxPacketSize = s.mMaxTxPacketSize;
- mL2capLocalCid = s.mL2capLocalCid;
- mL2capRemoteCid = s.mL2capRemoteCid;
+ mConnectionUuid = s.mConnectionUuid;
mServiceName = s.mServiceName;
mExcludeSdp = s.mExcludeSdp;
@@ -743,6 +741,7 @@
mPfd.close();
mPfd = null;
}
+ mConnectionUuid = null;
}
}
}
@@ -856,6 +855,13 @@
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
public int getL2capLocalChannelId() throws IOException {
+ if (mType != TYPE_L2CAP_LE) {
+ throw new BluetoothSocketException(BluetoothSocketException.L2CAP_UNKNOWN);
+ }
+ if (mSocketState != SocketState.CONNECTED || mConnectionUuid == null) {
+ throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
+ }
+ int cid;
IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
if (bluetoothProxy == null) {
throw new BluetoothSocketException(BluetoothSocketException.BLUETOOTH_OFF_FAILURE);
@@ -865,22 +871,17 @@
if (socketManager == null) {
throw new BluetoothSocketException(BluetoothSocketException.SOCKET_MANAGER_FAILURE);
}
- if (!socketManager.checkPermissionForL2capChannelInfo(
- AttributionSource.myAttributionSource())) {
- throw new SecurityException(
- "Need BLUETOOTH_CONNECT and BLUETOOTH_PRIVILEGED Permission");
- }
+ cid =
+ socketManager.getL2capLocalChannelId(
+ mConnectionUuid, AttributionSource.myAttributionSource());
} catch (RemoteException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
throw new IOException("unable to send RPC: " + e.getMessage());
}
- if (mType != TYPE_L2CAP_LE) {
- throw new BluetoothSocketException(BluetoothSocketException.L2CAP_UNKNOWN);
- }
- if (mSocketState != SocketState.CONNECTED) {
+ if (cid == -1) {
throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
}
- return mL2capLocalCid;
+ return cid;
}
/**
@@ -898,6 +899,13 @@
android.Manifest.permission.BLUETOOTH_PRIVILEGED,
})
public int getL2capRemoteChannelId() throws IOException {
+ if (mType != TYPE_L2CAP_LE) {
+ throw new BluetoothSocketException(BluetoothSocketException.L2CAP_UNKNOWN);
+ }
+ if (mSocketState != SocketState.CONNECTED || mConnectionUuid == null) {
+ throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
+ }
+ int cid;
IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
if (bluetoothProxy == null) {
throw new BluetoothSocketException(BluetoothSocketException.BLUETOOTH_OFF_FAILURE);
@@ -907,22 +915,17 @@
if (socketManager == null) {
throw new BluetoothSocketException(BluetoothSocketException.SOCKET_MANAGER_FAILURE);
}
- if (!socketManager.checkPermissionForL2capChannelInfo(
- AttributionSource.myAttributionSource())) {
- throw new SecurityException(
- "Need BLUETOOTH_CONNECT and BLUETOOTH_PRIVILEGED Permission");
- }
+ cid =
+ socketManager.getL2capRemoteChannelId(
+ mConnectionUuid, AttributionSource.myAttributionSource());
} catch (RemoteException e) {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
throw new IOException("unable to send RPC: " + e.getMessage());
}
- if (mType != TYPE_L2CAP_LE) {
- throw new BluetoothSocketException(BluetoothSocketException.L2CAP_UNKNOWN);
- }
- if (mSocketState != SocketState.CONNECTED) {
+ if (cid == -1) {
throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
}
- return mL2capRemoteCid;
+ return cid;
}
/** @hide */
@@ -961,8 +964,9 @@
int status = bb.getInt();
mMaxTxPacketSize = (bb.getShort() & 0xffff); // Convert to unsigned value
mMaxRxPacketSize = (bb.getShort() & 0xffff); // Convert to unsigned value
- mL2capLocalCid = (bb.getShort() & 0xffff); // Convert to unsigned value
- mL2capRemoteCid = (bb.getShort() & 0xffff); // Convert to unsigned value
+ long uuidLsb = bb.getLong();
+ long uuidMsb = bb.getLong();
+ mConnectionUuid = new ParcelUuid(new UUID(uuidMsb, uuidLsb));
String RemoteAddr = convertAddr(addr);
if (VDBG) {
Log.d(
@@ -979,10 +983,8 @@
+ mMaxRxPacketSize
+ " MaxTxPktSize: "
+ mMaxTxPacketSize
- + " mL2capLocalCid: "
- + String.format("0x%04x", mL2capLocalCid)
- + " mL2capRemoteCid: "
- + String.format("0x%04x", mL2capRemoteCid));
+ + " mConnectionUuid: "
+ + mConnectionUuid.toString());
}
if (status != 0) {
throw new IOException("Connection failure, status: " + status);
diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java
index ac34efb..50f439b 100644
--- a/framework/java/android/bluetooth/BluetoothVolumeControl.java
+++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java
@@ -294,22 +294,17 @@
mService = IBluetoothVolumeControl.Stub.asInterface(service);
// re-register the service-to-app callback
synchronized (mCallbackExecutorMap) {
- if (!mCallbackExecutorMap.isEmpty()) {
- try {
- if (service != null) {
- final SynchronousResultReceiver<Integer> recv =
- SynchronousResultReceiver.get();
- mService.registerCallback(mCallback, mAttributionSource, recv);
- recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(null);
- }
- } catch (RemoteException e) {
- Log.e(
- TAG,
- "onBluetoothServiceUp: Failed to register" + "Volume Control callback",
- e);
- } catch (TimeoutException e) {
- Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
- }
+ if (mCallbackExecutorMap.isEmpty()) {
+ return;
+ }
+ try {
+ final SynchronousResultReceiver<Void> recv = SynchronousResultReceiver.get();
+ mService.registerCallback(mCallback, mAttributionSource, recv);
+ recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(null);
+ } catch (RemoteException e) {
+ Log.e(TAG, "onBluetoothServiceUp: Failed to register VolumeControl callback", e);
+ } catch (TimeoutException e) {
+ Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
}
diff --git a/framework/tests/bumble/src/android/bluetooth/LeLegacyAdvertisingTest.java b/framework/tests/bumble/src/android/bluetooth/LeLegacyAdvertisingTest.java
new file mode 100644
index 0000000..d56ec08
--- /dev/null
+++ b/framework/tests/bumble/src/android/bluetooth/LeLegacyAdvertisingTest.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.bluetooth;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.bluetooth.le.AdvertiseData;
+import android.bluetooth.le.AdvertisingSet;
+import android.bluetooth.le.AdvertisingSetCallback;
+import android.bluetooth.le.AdvertisingSetParameters;
+import android.bluetooth.le.BluetoothLeAdvertiser;
+import android.os.ParcelUuid;
+import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.bluetooth.flags.Flags;
+import com.android.compatibility.common.util.AdoptShellPermissionsRule;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(AndroidJUnit4.class)
+public class LeLegacyAdvertisingTest {
+ private static final int TIMEOUT_MS = 1_000;
+
+ @Rule public final AdoptShellPermissionsRule mPermissionRule = new AdoptShellPermissionsRule();
+
+ @Rule
+ public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
+
+ @RequiresFlagsEnabled(Flags.FLAG_BLE_CHECK_DATA_LENGTH_ON_LEGACY_ADVERTISING)
+ @Test
+ public void setAdvertisingDataOver31Bytes() throws Exception {
+ final BluetoothLeAdvertiser advertiser =
+ BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
+
+ // Set legacy scan mode
+ AdvertisingSetParameters params =
+ new AdvertisingSetParameters.Builder()
+ .setLegacyMode(true)
+ .setScannable(true)
+ .setInterval(AdvertisingSetParameters.INTERVAL_HIGH)
+ .setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
+ .build();
+
+ AdvertiseData advertiseData =
+ new AdvertiseData.Builder()
+ .addServiceUuid(new ParcelUuid(UUID.randomUUID()))
+ .build();
+
+ final CompletableFuture<Integer> future = new CompletableFuture<>();
+
+ AdvertisingSetCallback callback =
+ new AdvertisingSetCallback() {
+ @Override
+ public void onAdvertisingSetStarted(
+ AdvertisingSet advertisingSet, int txPower, int status) {
+ // Should be greater than 31
+ int advertisingDataLengthWhichExceedsLimit = 50;
+ advertisingSet.setAdvertisingData(
+ createAdvertiseData(advertisingDataLengthWhichExceedsLimit));
+ }
+
+ @Override
+ public void onAdvertisingDataSet(AdvertisingSet advertisingSet, int status) {
+ future.complete(status);
+ }
+ };
+
+ try {
+ advertiser.startAdvertisingSet(params, advertiseData, null, null, null, callback);
+ future.completeOnTimeout(null, TIMEOUT_MS, TimeUnit.MILLISECONDS).join();
+
+ Integer setAdvertingDataResult = future.get();
+ assertThat(setAdvertingDataResult).isNotNull();
+ assertThat(setAdvertingDataResult)
+ .isEqualTo(AdvertisingSetCallback.ADVERTISE_FAILED_DATA_TOO_LARGE);
+ } finally {
+ advertiser.stopAdvertisingSet(callback);
+ }
+ }
+
+ @RequiresFlagsEnabled(Flags.FLAG_BLE_CHECK_DATA_LENGTH_ON_LEGACY_ADVERTISING)
+ @Test
+ public void setScanResponseDataOver31Bytes() throws Exception {
+ final BluetoothLeAdvertiser advertiser =
+ BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
+
+ // Set legacy scan mode
+ AdvertisingSetParameters params =
+ new AdvertisingSetParameters.Builder()
+ .setLegacyMode(true)
+ .setScannable(true)
+ .setInterval(AdvertisingSetParameters.INTERVAL_HIGH)
+ .setTxPowerLevel(AdvertisingSetParameters.TX_POWER_MEDIUM)
+ .build();
+
+ AdvertiseData advertiseData =
+ new AdvertiseData.Builder()
+ .addServiceUuid(new ParcelUuid(UUID.randomUUID()))
+ .build();
+
+ final CompletableFuture<Integer> future = new CompletableFuture<>();
+
+ AdvertisingSetCallback callback =
+ new AdvertisingSetCallback() {
+ @Override
+ public void onAdvertisingSetStarted(
+ AdvertisingSet advertisingSet, int txPower, int status) {
+ // Should be greater than 31
+ int scanResponseDataLengthWhichExceedsLimit = 50;
+ advertisingSet.setScanResponseData(
+ createAdvertiseData(scanResponseDataLengthWhichExceedsLimit));
+ }
+
+ @Override
+ public void onScanResponseDataSet(AdvertisingSet advertisingSet, int status) {
+ future.complete(status);
+ }
+ };
+
+ try {
+ advertiser.startAdvertisingSet(params, advertiseData, null, null, null, callback);
+ future.completeOnTimeout(null, TIMEOUT_MS, TimeUnit.MILLISECONDS).join();
+
+ Integer setScanResponseResult = future.get();
+ assertThat(setScanResponseResult).isNotNull();
+ assertThat(setScanResponseResult)
+ .isEqualTo(AdvertisingSetCallback.ADVERTISE_FAILED_DATA_TOO_LARGE);
+ } finally {
+ advertiser.stopAdvertisingSet(callback);
+ }
+ }
+
+ private AdvertiseData createAdvertiseData(int length) {
+ if (length <= 4) {
+ return null;
+ }
+
+ // Create an arbitrary manufacturer specific data
+ int manufacturerId = BluetoothAssignedNumbers.GOOGLE;
+ byte[] manufacturerSpecificData = new byte[length - 4];
+ for (int i = 0; i < manufacturerSpecificData.length; i++) {
+ manufacturerSpecificData[i] = (byte) i;
+ }
+
+ return new AdvertiseData.Builder()
+ .addManufacturerData(manufacturerId, manufacturerSpecificData)
+ .build();
+ }
+}
diff --git a/service/src/AutoOnFeature.kt b/service/src/AutoOnFeature.kt
index fe76114..e7b6d8c 100644
--- a/service/src/AutoOnFeature.kt
+++ b/service/src/AutoOnFeature.kt
@@ -18,6 +18,7 @@
package com.android.server.bluetooth
+import android.app.AlarmManager
import android.bluetooth.BluetoothAdapter.ACTION_AUTO_ON_STATE_CHANGED
import android.bluetooth.BluetoothAdapter.AUTO_ON_STATE_DISABLED
import android.bluetooth.BluetoothAdapter.AUTO_ON_STATE_ENABLED
@@ -157,24 +158,23 @@
looper: Looper,
private val context: Context,
private val receiver: BroadcastReceiver,
- callback_on: () -> Unit,
+ private val callback_on: () -> Unit,
private val now: LocalDateTime,
private val target: LocalDateTime,
private val timeToSleep: Duration
-) {
+) : AlarmManager.OnAlarmListener {
+ private val alarmManager: AlarmManager = context.getSystemService(AlarmManager::class.java)!!
+
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
+ alarmManager.set(
+ AlarmManager.ELAPSED_REALTIME,
+ timeToSleep.inWholeMilliseconds,
+ "Bluetooth AutoOnFeature",
+ this,
+ handler
)
Log.i(TAG, "[${this}]: Scheduling next Bluetooth restart")
@@ -190,6 +190,13 @@
)
}
+ override fun onAlarm() {
+ Log.i(TAG, "[${this}]: Bluetooth restarting now")
+ callback_on()
+ cancel()
+ timer = null
+ }
+
companion object {
@VisibleForTesting internal val STORAGE_KEY = "bluetooth_internal_automatic_turn_on_timer"
@@ -236,6 +243,7 @@
internal fun pause() {
Log.i(TAG, "[${this}]: Pausing timer")
context.unregisterReceiver(receiver)
+ alarmManager.cancel(this)
handler.removeCallbacksAndMessages(null)
}
@@ -244,11 +252,13 @@
internal fun cancel() {
Log.i(TAG, "[${this}]: Cancelling timer")
context.unregisterReceiver(receiver)
+ alarmManager.cancel(this)
handler.removeCallbacksAndMessages(null)
resetStorage(context.contentResolver)
}
- override fun toString() = "Timer scheduled ${now} for target=${target} (=${timeToSleep} delay)."
+ override fun toString() =
+ "Timer was scheduled at ${now} and should expire at ${target}. (sleep for ${timeToSleep})."
}
@VisibleForTesting internal val USER_SETTINGS_KEY = "bluetooth_automatic_turn_on"
diff --git a/service/src/AutoOnFeatureTest.kt b/service/src/AutoOnFeatureTest.kt
index 73ea861..7f8082d 100644
--- a/service/src/AutoOnFeatureTest.kt
+++ b/service/src/AutoOnFeatureTest.kt
@@ -15,6 +15,7 @@
*/
package com.android.server.bluetooth.test
+import android.app.AlarmManager
import android.app.Application
import android.bluetooth.BluetoothAdapter
import android.content.Context
@@ -165,7 +166,11 @@
fun setupTimer_whenBtOffAndUserEnabled_triggerCallback() {
setupTimer()
- shadowOf(looper).runToEndOfTasks()
+ val shadowAlarmManager = shadowOf(context.getSystemService(AlarmManager::class.java))
+ shadowAlarmManager.fireAlarm(shadowAlarmManager.peekNextScheduledAlarm())
+
+ shadowOf(looper).runOneTask()
+
expect.that(callback_count).isEqualTo(1)
expect.that(timer).isNull()
}
@@ -176,7 +181,11 @@
setupTimer()
setupTimer()
- shadowOf(looper).runToEndOfTasks()
+ val shadowAlarmManager = shadowOf(context.getSystemService(AlarmManager::class.java))
+ shadowAlarmManager.fireAlarm(shadowAlarmManager.peekNextScheduledAlarm())
+
+ shadowOf(looper).runOneTask()
+
expect.that(callback_count).isEqualTo(1)
expect.that(timer).isNull()
}
diff --git a/system/Android.mk b/system/Android.mk
index c4d9180..a6c5ad0 100644
--- a/system/Android.mk
+++ b/system/Android.mk
@@ -24,9 +24,6 @@
LOCAL_host_python_smp_packets_library := \
$(SOONG_OUT_DIR)/.intermediates/packages/modules/Bluetooth/system/pdl/security/gd_smp_packets_python3_gen/gen/smp_packets.py
-LOCAL_host_python_extension_libraries := \
- $(HOST_OUT_SHARED_LIBRARIES)/bluetooth_packets_python3.so
-
LOCAL_host_libraries := \
$(HOST_OUT_SHARED_LIBRARIES)/libbase.so \
$(HOST_OUT_SHARED_LIBRARIES)/libbinder.so \
@@ -98,14 +95,12 @@
$(bluetooth_cert_src_and_bin_zip): PRIVATE_cert_test_sources := $(LOCAL_cert_test_sources)
$(bluetooth_cert_src_and_bin_zip): PRIVATE_host_executables := $(LOCAL_host_executables)
$(bluetooth_cert_src_and_bin_zip): PRIVATE_host_libraries := $(LOCAL_host_libraries)
-$(bluetooth_cert_src_and_bin_zip): PRIVATE_host_python_extension_libraries := $(LOCAL_host_python_extension_libraries)
$(bluetooth_cert_src_and_bin_zip): PRIVATE_host_python_hci_packets_library := $(LOCAL_host_python_hci_packets_library)
$(bluetooth_cert_src_and_bin_zip): PRIVATE_host_python_smp_packets_library := $(LOCAL_host_python_smp_packets_library)
$(bluetooth_cert_src_and_bin_zip): PRIVATE_target_executables := $(LOCAL_target_executables)
$(bluetooth_cert_src_and_bin_zip): PRIVATE_target_libraries := $(LOCAL_target_libraries)
$(bluetooth_cert_src_and_bin_zip): $(SOONG_ZIP) $(LOCAL_cert_test_sources) \
$(LOCAL_host_executables) $(LOCAL_host_libraries) $(LOCAL_host_python_libraries) \
- $(LOCAL_host_python_extension_libraries) \
$(LOCAL_host_python_hci_packets_library) \
$(LOCAL_host_python_smp_packets_library) \
$(LOCAL_target_executables) $(LOCAL_target_libraries)
@@ -114,7 +109,6 @@
-C $(dir $(PRIVATE_host_python_hci_packets_library)) -f $(PRIVATE_host_python_hci_packets_library) \
-C $(dir $(PRIVATE_host_python_smp_packets_library)) -f $(PRIVATE_host_python_smp_packets_library) \
-C $(HOST_OUT_EXECUTABLES) $(addprefix -f ,$(PRIVATE_host_executables)) \
- -C $(HOST_OUT_SHARED_LIBRARIES) $(addprefix -f ,$(PRIVATE_host_python_extension_libraries)) \
-P lib64 \
-C $(HOST_OUT_SHARED_LIBRARIES) $(addprefix -f ,$(PRIVATE_host_libraries)) \
-P target \
@@ -125,7 +119,7 @@
SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD SPDX-license-identifier-MIT legacy_unencumbered,\
notice, $(LOCAL_PATH)/../NOTICE,,packages/modules/Bluetooth)
$(call declare-container-license-deps,$(bluetooth_cert_src_and_bin_zip),\
- $(LOCAL_host_python_extension_libraries) $(LOCAL_target_executables) $(LOCAL_target_libraries),$(bluetooth_cert_src_and_bin_zip):)
+ $(LOCAL_target_executables) $(LOCAL_target_libraries),$(bluetooth_cert_src_and_bin_zip):)
# TODO: Find a better way to locate output from SOONG genrule()
LOCAL_facade_generated_py_zip := \
diff --git a/system/audio/Android.bp b/system/audio/Android.bp
index 9eb0883..f41e44c 100644
--- a/system/audio/Android.bp
+++ b/system/audio/Android.bp
@@ -28,6 +28,7 @@
],
shared_libs: [
"libchrome",
+ "liblog",
],
static_libs: [
"libbase",
@@ -64,6 +65,7 @@
"libbluetooth_headers",
],
static_libs: [
+ "libbase",
"libbluetooth_hci_pdl",
"libbluetooth_log",
"libbt-common",
@@ -72,6 +74,7 @@
"libevent",
"libflatbuffers-cpp",
"libgmock",
+ "liblog",
],
stl: "libc++_static",
generated_headers: [
diff --git a/system/audio/asrc/asrc_resampler.cc b/system/audio/asrc/asrc_resampler.cc
index 7b3a325..12c906b 100644
--- a/system/audio/asrc/asrc_resampler.cc
+++ b/system/audio/asrc/asrc_resampler.cc
@@ -18,6 +18,7 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <algorithm>
#include <cmath>
@@ -439,11 +440,11 @@
!check_bounds(interval_us, 1 * 1000, 100 * 1000) ||
!check_bounds(num_burst_buffers, 0, 10) ||
!check_bounds(burst_delay_ms, 0, 1000)) {
- LOG(ERROR) << "Bad parameters:"
- << " channels: " << channels << " sample_rate: " << sample_rate
- << " bit_depth: " << bit_depth << " interval_us: " << interval_us
- << " num_burst_buffers: " << num_burst_buffers
- << " burst_delay_ms: " << burst_delay_ms << std::endl;
+ log::error(
+ "Bad parameters: channels: {} sample_rate: {} bit_depth: {} "
+ "interval_us: {} num_burst_buffers: {} burst_delay_ms: {}",
+ channels, sample_rate, bit_depth, interval_us, num_burst_buffers,
+ burst_delay_ms);
return;
}
@@ -561,8 +562,8 @@
std::vector<const std::vector<uint8_t>*> out;
if (in.size() != buffers_size_) {
- LOG(ERROR) << "Inconsistent input buffer size: " << in.size() << " ("
- << buffers_size_ << " expected)" << std::endl;
+ log::error("Inconsistent input buffer size: {} ({} expected)", in.size(),
+ buffers_size_);
return out;
}
@@ -611,11 +612,9 @@
int(output_us - local_us));
if (0)
- LOG(INFO) << base::StringPrintf(
- "[%6u.%06u] Fs: %.2f Hz drift: %d us",
- output_us / (1000 * 1000), output_us % (1000 * 1000),
- ratio * sample_rate_, int(output_us - local_us))
- << std::endl;
+ log::info("[{:6}.{:06}] Fs: {:.2f} Hz drift: {} us",
+ output_us / (1000 * 1000), output_us % (1000 * 1000),
+ ratio * sample_rate_, int(output_us - local_us));
return out;
}
diff --git a/system/audio_bluetooth_hw/Android.bp b/system/audio_bluetooth_hw/Android.bp
index 01763dc..8587c62 100644
--- a/system/audio_bluetooth_hw/Android.bp
+++ b/system/audio_bluetooth_hw/Android.bp
@@ -51,6 +51,9 @@
"libhidlbase",
],
cflags: ["-Wno-unused-parameter"],
+ visibility: [
+ "//device/generic/goldfish/audio",
+ ],
}
cc_test {
diff --git a/system/audio_bluetooth_hw/audio_bluetooth_hw.cc b/system/audio_bluetooth_hw/audio_bluetooth_hw.cc
index f85cbb8..4b66644 100644
--- a/system/audio_bluetooth_hw/audio_bluetooth_hw.cc
+++ b/system/audio_bluetooth_hw/audio_bluetooth_hw.cc
@@ -18,7 +18,6 @@
#include <android-base/logging.h>
#include <hardware/hardware.h>
-#include <log/log.h>
#include <malloc.h>
#include <string.h>
#include <system/audio.h>
diff --git a/system/audio_bluetooth_hw/device_port_proxy.cc b/system/audio_bluetooth_hw/device_port_proxy.cc
index 8505420..4f4acd1 100644
--- a/system/audio_bluetooth_hw/device_port_proxy.cc
+++ b/system/audio_bluetooth_hw/device_port_proxy.cc
@@ -21,7 +21,6 @@
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <audio_utils/primitives.h>
-#include <log/log.h>
#include <stdlib.h>
#include <vector>
diff --git a/system/audio_bluetooth_hw/device_port_proxy_hidl.cc b/system/audio_bluetooth_hw/device_port_proxy_hidl.cc
index 3aa3a9c..f90bf7b 100644
--- a/system/audio_bluetooth_hw/device_port_proxy_hidl.cc
+++ b/system/audio_bluetooth_hw/device_port_proxy_hidl.cc
@@ -22,7 +22,6 @@
#include <android-base/stringprintf.h>
#include <audio_utils/primitives.h>
#include <inttypes.h>
-#include <log/log.h>
#include <stdlib.h>
#include "BluetoothAudioSessionControl_2_1.h"
@@ -618,4 +617,4 @@
} // namespace hidl
} // namespace audio
} // namespace bluetooth
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/system/audio_bluetooth_hw/stream_apis.cc b/system/audio_bluetooth_hw/stream_apis.cc
index 1a10803..c82f2e2 100644
--- a/system/audio_bluetooth_hw/stream_apis.cc
+++ b/system/audio_bluetooth_hw/stream_apis.cc
@@ -21,7 +21,6 @@
#include <android-base/stringprintf.h>
#include <cutils/properties.h>
#include <inttypes.h>
-#include <log/log.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
diff --git a/system/audio_bluetooth_hw/utils.cc b/system/audio_bluetooth_hw/utils.cc
index f864fd5..a74a83b 100644
--- a/system/audio_bluetooth_hw/utils.cc
+++ b/system/audio_bluetooth_hw/utils.cc
@@ -20,8 +20,8 @@
#include <android-base/logging.h>
#include <android-base/strings.h>
-#include <log/log.h>
#include <stdlib.h>
+
#include <sstream>
#include <vector>
diff --git a/system/audio_hal_interface/Android.bp b/system/audio_hal_interface/Android.bp
index 0a4814e..f0b5ef3 100644
--- a/system/audio_hal_interface/Android.bp
+++ b/system/audio_hal_interface/Android.bp
@@ -146,18 +146,6 @@
"packages/modules/Bluetooth/system/gd",
"packages/modules/Bluetooth/system/stack/include",
],
- target: {
- host: {
- srcs: [
- ":BluetoothHostTestingLogCapture",
- ],
- },
- android: {
- srcs: [
- ":BluetoothAndroidTestingLogCapture",
- ],
- },
- },
sanitize: {
cfi: true,
scs: true,
diff --git a/system/audio_hal_interface/a2dp_encoding_host.cc b/system/audio_hal_interface/a2dp_encoding_host.cc
index 6b596e5..b449ef3 100644
--- a/system/audio_hal_interface/a2dp_encoding_host.cc
+++ b/system/audio_hal_interface/a2dp_encoding_host.cc
@@ -16,6 +16,7 @@
#include "a2dp_encoding_host.h"
+#include <bluetooth/log.h>
#include <grp.h>
#include <sys/stat.h>
@@ -36,14 +37,21 @@
// TODO(b/198260375): Make A2DP data owner group configurable.
#define A2DP_HOST_DATA_GROUP "bluetooth-audio"
+namespace fmt {
+template <>
+struct formatter<tUIPC_EVENT> : enum_formatter<tUIPC_EVENT> {};
+template <>
+struct formatter<tA2DP_CTRL_CMD> : enum_formatter<tA2DP_CTRL_CMD> {};
+} // namespace fmt
+
namespace {
std::unique_ptr<tUIPC_STATE> a2dp_uipc = nullptr;
static void btif_a2dp_data_cb([[maybe_unused]] tUIPC_CH_ID ch_id,
tUIPC_EVENT event) {
- LOG_WARN("%s: BTIF MEDIA (A2DP-DATA) EVENT %s", __func__,
- dump_uipc_event(event));
+ bluetooth::log::warn("BTIF MEDIA (A2DP-DATA) EVENT {}",
+ dump_uipc_event(event));
switch (event) {
case UIPC_OPEN_EVT:
@@ -67,7 +75,7 @@
break;
default:
- LOG_ERROR("%s: ### A2DP-DATA EVENT %d NOT HANDLED ###", __func__, event);
+ bluetooth::log::error("### A2DP-DATA EVENT {} NOT HANDLED ###", event);
break;
}
}
@@ -84,7 +92,7 @@
if (grp) {
int res = chown(A2DP_HOST_DATA_PATH, -1, grp->gr_gid);
if (res == -1) {
- LOG_ERROR("%s failed: %s", __func__, strerror(errno));
+ bluetooth::log::error("failed: {}", strerror(errno));
}
}
}
@@ -119,16 +127,16 @@
// Check if a previous request is not finished
if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_START) {
- LOG_INFO("%s: A2DP_CTRL_CMD_START in progress", __func__);
+ log::info("A2DP_CTRL_CMD_START in progress");
return false;
} else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
- LOG_WARN("%s: busy in pending_cmd=%u", __func__, a2dp_pending_cmd_);
+ log::warn("busy in pending_cmd={}", a2dp_pending_cmd_);
return false;
}
// Don't send START request to stack while we are in a call
if (!bluetooth::headset::IsCallIdle()) {
- LOG_ERROR("%s: call state is busy", __func__);
+ log::error("call state is busy");
return false;
}
@@ -147,13 +155,13 @@
a2dp_pending_cmd_ = A2DP_CTRL_CMD_START;
btif_av_stream_start(A2dpType::kSource);
if (btif_av_get_peer_sep(A2dpType::kSource) != AVDT_TSEP_SRC) {
- LOG_INFO("%s: accepted", __func__);
+ log::info("accepted");
return true; // NOTE: The request is placed, but could still fail.
}
a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
return true;
}
- LOG_ERROR("%s: AV stream is not ready to start", __func__);
+ log::error("AV stream is not ready to start");
return false;
}
@@ -164,7 +172,7 @@
btif_av_clear_remote_suspend_flag(A2dpType::kSource);
return true;
}
- LOG_INFO("%s: handling", __func__);
+ log::info("handling");
a2dp_pending_cmd_ = A2DP_CTRL_CMD_STOP;
btif_av_stream_stop(RawAddress::kEmpty);
return true;
@@ -172,14 +180,14 @@
bool SuspendRequest() {
if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
- LOG_WARN("%s: busy in pending_cmd=%u", __func__, a2dp_pending_cmd_);
+ log::warn("busy in pending_cmd={}", a2dp_pending_cmd_);
return false;
}
if (!btif_av_stream_started_ready(A2dpType::kSource)) {
- LOG_WARN("%s: AV stream is not started", __func__);
+ log::warn("AV stream is not started");
return false;
}
- LOG_INFO("%s: handling", __func__);
+ log::info("handling");
a2dp_pending_cmd_ = A2DP_CTRL_CMD_SUSPEND;
btif_av_stream_suspend();
return true;
diff --git a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc
index ccf21ff..a8fc262 100644
--- a/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc
+++ b/system/audio_hal_interface/aidl/a2dp_encoding_aidl.cc
@@ -17,6 +17,8 @@
#include "a2dp_encoding_aidl.h"
+#include <bluetooth/log.h>
+
#include <vector>
#include "a2dp_provider_info.h"
@@ -27,6 +29,16 @@
#include "codec_status_aidl.h"
#include "transport_instance.h"
+namespace fmt {
+template <>
+struct formatter<tA2DP_CTRL_CMD> : enum_formatter<tA2DP_CTRL_CMD> {};
+template <>
+struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
+template <>
+struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {
+};
+} // namespace fmt
+
namespace bluetooth {
namespace audio {
namespace aidl {
@@ -72,16 +84,16 @@
BluetoothAudioCtrlAck A2dpTransport::StartRequest(bool is_low_latency) {
// Check if a previous request is not finished
if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_START) {
- LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_START in progress";
+ log::info("A2DP_CTRL_CMD_START in progress");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
} else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
- LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
+ log::warn("busy in pending_cmd={}", a2dp_pending_cmd_);
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
}
// Don't send START request to stack while we are in a call
if (!bluetooth::headset::IsCallIdle()) {
- LOG(ERROR) << __func__ << ": call state is busy";
+ log::error("call state is busy");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_INCALL_FAILURE);
}
@@ -100,28 +112,28 @@
a2dp_pending_cmd_ = A2DP_CTRL_CMD_START;
btif_av_stream_start_with_latency(is_low_latency);
if (btif_av_get_peer_sep(A2dpType::kSource) != AVDT_TSEP_SRC) {
- LOG(INFO) << __func__ << ": accepted";
+ log::info("accepted");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
}
a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_SUCCESS);
}
- LOG(ERROR) << __func__ << ": AV stream is not ready to start";
+ log::error("AV stream is not ready to start");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
}
BluetoothAudioCtrlAck A2dpTransport::SuspendRequest() {
// Previous request is not finished
if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_SUSPEND) {
- LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_SUSPEND in progress";
+ log::info("A2DP_CTRL_CMD_SUSPEND in progress");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
} else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
- LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
+ log::warn("busy in pending_cmd={}", a2dp_pending_cmd_);
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
}
// Local suspend
if (btif_av_stream_started_ready(A2dpType::kSource)) {
- LOG(INFO) << __func__ << ": accepted";
+ log::info("accepted");
a2dp_pending_cmd_ = A2DP_CTRL_CMD_SUSPEND;
btif_av_stream_suspend();
return BluetoothAudioCtrlAck::PENDING;
@@ -140,7 +152,7 @@
btif_av_clear_remote_suspend_flag(A2dpType::kSource);
return;
}
- LOG(INFO) << __func__ << ": handling";
+ log::info("handling");
a2dp_pending_cmd_ = A2DP_CTRL_CMD_STOP;
btif_av_stream_stop(RawAddress::kEmpty);
}
@@ -156,10 +168,9 @@
*remote_delay_report_ns = remote_delay_report_ * 100000u;
*total_bytes_read = total_bytes_read_;
*data_position = data_position_;
- VLOG(2) << __func__ << ": delay=" << remote_delay_report_
- << "/10ms, data=" << total_bytes_read_
- << " byte(s), timestamp=" << data_position_.tv_sec << "."
- << data_position_.tv_nsec << "s";
+ log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s",
+ remote_delay_report_, total_bytes_read_, data_position_.tv_sec,
+ data_position_.tv_nsec);
return true;
}
@@ -167,11 +178,10 @@
const source_metadata_v7_t& source_metadata) {
auto track_count = source_metadata.track_count;
auto tracks = source_metadata.tracks;
- VLOG(1) << __func__ << ": " << track_count << " track(s) received";
+ log::verbose("{} track(s) received", track_count);
while (track_count) {
- VLOG(2) << __func__ << ": usage=" << tracks->base.usage
- << ", content_type=" << tracks->base.content_type
- << ", gain=" << tracks->base.gain;
+ log::verbose("usage={}, content_type={}, gain={}", tracks->base.usage,
+ tracks->base.content_type, tracks->base.gain);
--track_count;
++tracks;
}
@@ -284,7 +294,7 @@
bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) {
A2dpCodecConfig* a2dp_config = bta_av_get_a2dp_current_codec();
if (a2dp_config == nullptr) {
- LOG(WARNING) << __func__ << ": failure to get A2DP codec config";
+ log::warn("failure to get A2DP codec config");
return false;
}
btav_a2dp_codec_config_t current_codec = a2dp_config->getCodecConfig();
@@ -328,8 +338,7 @@
case BTAV_A2DP_CODEC_INDEX_MAX:
[[fallthrough]];
default:
- LOG(ERROR) << __func__
- << ": Unknown codec_type=" << current_codec.codec_type;
+ log::error("Unknown codec_type={}", current_codec.codec_type);
return false;
}
codec_config->encodedAudioBitrate = a2dp_config->getTrackBitRate();
@@ -350,7 +359,7 @@
} else if (codec_config->peerMtu > MAX_3MBPS_AVDTP_MTU) {
codec_config->peerMtu = MAX_3MBPS_AVDTP_MTU;
}
- LOG(INFO) << __func__ << ": CodecConfiguration=" << codec_config->toString();
+ log::info("CodecConfiguration={}", codec_config->toString());
return true;
}
@@ -358,7 +367,7 @@
if (pcm_config == nullptr) return false;
A2dpCodecConfig* a2dp_codec_configs = bta_av_get_a2dp_current_codec();
if (a2dp_codec_configs == nullptr) {
- LOG(WARNING) << __func__ << ": failure to get A2DP codec config";
+ log::warn("failure to get A2DP codec config");
*pcm_config = BluetoothAudioSinkClientInterface::kInvalidPcmConfiguration;
return false;
}
@@ -415,7 +424,7 @@
if (hal_interface->IsValid()) {
return hal_interface;
} else {
- LOG(ERROR) << __func__ << "BluetoothAudio HAL for a2dp is invalid";
+ log::error("BluetoothAudio HAL for a2dp is invalid");
delete a2dp_transport;
delete hal_interface;
return nullptr;
@@ -436,20 +445,19 @@
// Initialize BluetoothAudio HAL: openProvider
bool init(bluetooth::common::MessageLoopThread* /*message_loop*/) {
- LOG(INFO) << __func__;
+ log::info("");
if (software_hal_interface != nullptr) {
return true;
}
if (is_hal_force_disabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
+ log::error("BluetoothAudio HAL is disabled");
return false;
}
if (!BluetoothAudioClientInterface::is_aidl_available()) {
- LOG(ERROR) << __func__
- << ": BluetoothAudio AIDL implementation does not exist";
+ log::error("BluetoothAudio AIDL implementation does not exist");
return false;
}
@@ -475,8 +483,7 @@
: software_hal_interface);
if (remote_delay != 0) {
- LOG(INFO) << __func__ << ": restore DELAY "
- << static_cast<float>(remote_delay / 10.0) << " ms";
+ log::info("restore DELAY {} ms", static_cast<float>(remote_delay / 10.0));
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
->SetRemoteDelay(remote_delay);
remote_delay = 0;
@@ -511,13 +518,13 @@
// Set up the codec into BluetoothAudio HAL
bool setup_codec() {
if (!is_hal_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return false;
}
A2dpCodecConfig* a2dp_config = bta_av_get_a2dp_current_codec();
if (a2dp_config == nullptr) {
- LOG(ERROR) << __func__ << ": the current codec is not configured";
+ log::error("the current codec is not configured");
return false;
}
@@ -554,7 +561,7 @@
codec_info + parameters_start, codec_info + parameters_end);
if (!is_hal_offloading()) {
- LOG(WARNING) << __func__ << ": Switching BluetoothAudio HAL to Hardware";
+ log::warn("Switching BluetoothAudio HAL to Hardware");
end_session();
active_hal_interface = offloading_hal_interface;
}
@@ -567,18 +574,18 @@
CodecConfiguration codec_config{};
if (!a2dp_get_selected_hal_codec_config(&codec_config)) {
- LOG(ERROR) << __func__ << ": Failed to get CodecConfiguration";
+ log::error("Failed to get CodecConfiguration");
return false;
}
bool should_codec_offloading =
bluetooth::audio::aidl::codec::IsCodecOffloadingEnabled(codec_config);
if (should_codec_offloading && !is_hal_offloading()) {
- LOG(WARNING) << __func__ << ": Switching BluetoothAudio HAL to Hardware";
+ log::warn("Switching BluetoothAudio HAL to Hardware");
end_session();
active_hal_interface = offloading_hal_interface;
} else if (!should_codec_offloading && is_hal_offloading()) {
- LOG(WARNING) << __func__ << ": Switching BluetoothAudio HAL to Software";
+ log::warn("Switching BluetoothAudio HAL to Software");
end_session();
active_hal_interface = software_hal_interface;
}
@@ -590,7 +597,7 @@
} else {
PcmConfiguration pcm_config{};
if (!a2dp_get_selected_hal_pcm_config(&pcm_config)) {
- LOG(ERROR) << __func__ << ": Failed to get PcmConfiguration";
+ log::error("Failed to get PcmConfiguration");
return false;
}
audio_config.set<AudioConfiguration::pcmConfig>(pcm_config);
@@ -601,7 +608,7 @@
void start_session() {
if (!is_hal_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return;
}
std::vector<LatencyMode> latency_modes = {LatencyMode::FREE};
@@ -614,7 +621,7 @@
void end_session() {
if (!is_hal_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return;
}
active_hal_interface->EndSession();
@@ -626,15 +633,14 @@
void ack_stream_started(const tA2DP_CTRL_ACK& ack) {
auto ctrl_ack = a2dp_ack_to_bt_audio_ctrl_ack(ack);
- LOG(INFO) << __func__ << ": result=" << ctrl_ack;
+ log::info("result={}", ctrl_ack);
auto a2dp_sink =
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance());
auto pending_cmd = a2dp_sink->GetPendingCmd();
if (pending_cmd == A2DP_CTRL_CMD_START) {
active_hal_interface->StreamStarted(ctrl_ack);
} else {
- LOG(WARNING) << __func__ << ": pending=" << pending_cmd
- << " ignore result=" << ctrl_ack;
+ log::warn("pending={} ignore result={}", pending_cmd, ctrl_ack);
return;
}
if (ctrl_ack != BluetoothAudioCtrlAck::PENDING) {
@@ -644,17 +650,16 @@
void ack_stream_suspended(const tA2DP_CTRL_ACK& ack) {
auto ctrl_ack = a2dp_ack_to_bt_audio_ctrl_ack(ack);
- LOG(INFO) << __func__ << ": result=" << ctrl_ack;
+ log::info("result={}", ctrl_ack);
auto a2dp_sink =
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance());
auto pending_cmd = a2dp_sink->GetPendingCmd();
if (pending_cmd == A2DP_CTRL_CMD_SUSPEND) {
active_hal_interface->StreamSuspended(ctrl_ack);
} else if (pending_cmd == A2DP_CTRL_CMD_STOP) {
- LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_STOP result=" << ctrl_ack;
+ log::info("A2DP_CTRL_CMD_STOP result={}", ctrl_ack);
} else {
- LOG(WARNING) << __func__ << ": pending=" << pending_cmd
- << " ignore result=" << ctrl_ack;
+ log::warn("pending={} ignore result={}", pending_cmd, ctrl_ack);
return;
}
if (ctrl_ack != BluetoothAudioCtrlAck::PENDING) {
@@ -665,13 +670,13 @@
// Read from the FMQ of BluetoothAudio HAL
size_t read(uint8_t* p_buf, uint32_t len) {
if (!is_hal_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return 0;
} else if (is_hal_offloading()) {
- LOG(ERROR) << __func__ << ": session_type="
- << toString(active_hal_interface->GetTransportInstance()
- ->GetSessionType())
- << " is not A2DP_SOFTWARE_ENCODING_DATAPATH";
+ log::error(
+ "session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH",
+ toString(
+ active_hal_interface->GetTransportInstance()->GetSessionType()));
return 0;
}
return active_hal_interface->ReadAudioData(p_buf, len);
@@ -680,13 +685,12 @@
// Update A2DP delay report to BluetoothAudio HAL
void set_remote_delay(uint16_t delay_report) {
if (!is_hal_enabled()) {
- LOG(INFO) << __func__ << ": not ready for DelayReport "
- << static_cast<float>(delay_report / 10.0) << " ms";
+ log::info("not ready for DelayReport {} ms",
+ static_cast<float>(delay_report / 10.0));
remote_delay = delay_report;
return;
}
- VLOG(1) << __func__ << ": DELAY " << static_cast<float>(delay_report / 10.0)
- << " ms";
+ log::verbose("DELAY {} ms", static_cast<float>(delay_report / 10.0));
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
->SetRemoteDelay(delay_report);
}
@@ -695,7 +699,7 @@
void set_low_latency_mode_allowed(bool allowed) {
is_low_latency_mode_allowed = allowed;
if (!is_hal_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return;
}
std::vector<LatencyMode> latency_modes = {LatencyMode::FREE};
@@ -764,7 +768,7 @@
case ChannelMode::STEREO:
return BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO;
default:
- LOG(ERROR) << "unknown channel mode";
+ log::error("unknown channel mode");
break;
}
return BTAV_A2DP_CODEC_CHANNEL_MODE_NONE;
@@ -790,7 +794,7 @@
case 24000:
return BTAV_A2DP_CODEC_SAMPLE_RATE_24000;
default:
- LOG(ERROR) << "unknown sampling frequency " << sampling_frequency_hz;
+ log::error("unknown sampling frequency {}", sampling_frequency_hz);
break;
}
return BTAV_A2DP_CODEC_SAMPLE_RATE_NONE;
@@ -805,7 +809,7 @@
case 32:
return BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32;
default:
- LOG(ERROR) << "unknown bit depth " << bitdepth;
+ log::error("unknown bit depth {}", bitdepth);
break;
}
return BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE;
@@ -928,17 +932,16 @@
break;
}
- LOG(INFO) << __func__;
- LOG(INFO) << "remote capabilities:";
+ log::info("remote capabilities:");
for (auto const& sep : a2dp_remote_capabilities) {
- LOG(INFO) << " - " << sep.toString();
+ log::info("- {}", sep.toString());
}
- LOG(INFO) << "hint: " << hint.toString();
+ log::info("hint: {}", hint.toString());
if (offloading_hal_interface == nullptr &&
(offloading_hal_interface = new_hal_interface(
SessionType::A2DP_HARDWARE_OFFLOAD_ENCODING_DATAPATH)) == nullptr) {
- LOG(ERROR) << __func__ << "the offloading HAL interface cannot be opened";
+ log::error("the offloading HAL interface cannot be opened");
return std::nullopt;
}
@@ -949,11 +952,11 @@
// Convert the result configuration back to the stack's format.
if (!result.has_value()) {
- LOG(INFO) << __func__ << ": provider cannot resolve the a2dp configuration";
+ log::info("provider cannot resolve the a2dp configuration");
return std::nullopt;
}
- LOG(INFO) << __func__ << ": provider selected " << result->toString();
+ log::info("provider selected {}", result->toString());
::bluetooth::audio::a2dp::provider::a2dp_configuration a2dp_configuration;
a2dp_configuration.remote_seid = result->remoteSeid;
@@ -987,13 +990,13 @@
CodecParameters codec_parameters_aidl;
if (provider_info == nullptr) {
- LOG(ERROR) << __func__ << "provider_info is null";
+ log::error("provider_info is null");
return A2DP_FAIL;
}
auto codec = provider_info->GetCodec(codec_index);
if (!codec.has_value()) {
- LOG(ERROR) << __func__ << ": codec index not recognized by provider";
+ log::error("codec index not recognized by provider");
return A2DP_FAIL;
}
@@ -1004,7 +1007,7 @@
codec.value()->id, configuration, &codec_parameters_aidl);
if (!a2dp_status.has_value()) {
- LOG(ERROR) << __func__ << ": provider failed to parse configuration";
+ log::error("provider failed to parse configuration");
return A2DP_FAIL;
}
diff --git a/system/audio_hal_interface/aidl/a2dp_provider_info.cc b/system/audio_hal_interface/aidl/a2dp_provider_info.cc
index f7ecca8..2ee0391 100644
--- a/system/audio_hal_interface/aidl/a2dp_provider_info.cc
+++ b/system/audio_hal_interface/aidl/a2dp_provider_info.cc
@@ -20,6 +20,7 @@
#include <android/binder_manager.h>
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
#include <optional>
#include <vector>
@@ -52,14 +53,16 @@
std::unique_ptr<ProviderInfo> ProviderInfo::GetProviderInfo(
bool supports_a2dp_hw_offload_v2) {
if (!IS_FLAG_ENABLED(a2dp_offload_codec_extensibility)) {
- LOG(INFO) << "a2dp offload codec extensibility is disabled;"
- << " not going to load the ProviderInfo";
+ log::info(
+ "a2dp offload codec extensibility is disabled,"
+ " not going to load the ProviderInfo");
return nullptr;
}
if (!supports_a2dp_hw_offload_v2) {
- LOG(INFO) << "a2dp hw offload v2 is not supported by the controller;"
- << " not going to load the ProviderInfo";
+ log::info(
+ "a2dp hw offload v2 is not supported by the controller,"
+ " not going to load the ProviderInfo");
return nullptr;
}
@@ -70,8 +73,9 @@
SessionType::A2DP_HARDWARE_OFFLOAD_DECODING_DATAPATH, nullptr);
if (!source_provider_info.has_value() && !sink_provider_info.has_value()) {
- LOG(INFO) << "a2dp offload codec extensibility is enabled;"
- << " but the provider info is empty";
+ log::info(
+ "a2dp offload codec extensibility is enabled,"
+ " but the provider info is empty");
return nullptr;
}
@@ -86,7 +90,7 @@
sink_codecs = std::move(sink_provider_info->codecInfos);
}
- LOG(INFO) << "successfully loaded provider info";
+ log::info("successfully loaded provider info");
return std::make_unique<ProviderInfo>(std::move(source_codecs),
std::move(sink_codecs));
}
@@ -145,8 +149,9 @@
/* out of extension codec indexes */
if (*ext_index >= BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MAX) {
- LOG(ERROR) << "unable to assign a source codec index for vendorId="
- << vendor_id << ", codecId=" << codec_id;
+ log::error(
+ "unable to assign a source codec index for vendorId={}, codecId={}",
+ vendor_id, codec_id);
}
/* assign a new codec index for the
@@ -191,8 +196,9 @@
/* out of extension codec indexes */
if (*ext_index >= BTAV_A2DP_CODEC_INDEX_SINK_EXT_MAX) {
- LOG(ERROR) << "unable to assign a sink codec index for vendorId="
- << vendor_id << ", codecId=" << codec_id;
+ log::error(
+ "unable to assign a sink codec index for vendorId={}, codecId={}",
+ vendor_id, codec_id);
}
/* assign a new codec index for the
@@ -210,7 +216,7 @@
BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN;
for (size_t i = 0; i < this->source_codecs.size(); i++) {
auto& codec = this->source_codecs[i];
- LOG(INFO) << "supported source codec " << codec.name;
+ log::info("supported source codec {}", codec.name);
auto index = assignSourceCodecIndex(codec, &ext_source_index);
if (index.has_value()) {
assigned_codec_indexes[index.value()] = &codec;
@@ -220,7 +226,7 @@
btav_a2dp_codec_index_t ext_sink_index = BTAV_A2DP_CODEC_INDEX_SINK_EXT_MIN;
for (size_t i = 0; i < this->sink_codecs.size(); i++) {
auto& codec = this->sink_codecs[i];
- LOG(INFO) << "supports sink codec " << codec.name;
+ log::info("supports sink codec {}", codec.name);
auto index = assignSinkCodecIndex(codec, &ext_sink_index);
if (index.has_value()) {
assigned_codec_indexes[index.value()] = &codec;
diff --git a/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc b/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc
index 5a61a63..fbc2658 100644
--- a/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc
+++ b/system/audio_hal_interface/aidl/a2dp_provider_info_unittest.cc
@@ -18,6 +18,7 @@
#include "a2dp_provider_info.h"
+#include <bluetooth/log.h>
#include <com_android_bluetooth_flags.h>
#include <flag_macros.h>
#include <gmock/gmock.h>
@@ -42,6 +43,8 @@
using ::testing::Return;
using ::testing::Test;
+using namespace bluetooth;
+
tA2DP_CODEC_TYPE A2DP_GetCodecType(const uint8_t* p_codec_info) {
return (tA2DP_CODEC_TYPE)(p_codec_info[AVDT_CODEC_TYPE_INDEX]);
}
@@ -268,8 +271,8 @@
provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_SBC);
ASSERT_TRUE(received_codec_info_sbc.has_value());
auto codec_info = received_codec_info_sbc.value();
- LOG(ERROR) << codec_info->toString();
- LOG(ERROR) << test_source_provider_info.codecInfos[0].toString();
+ log::error("{}", codec_info->toString());
+ log::error("{}", test_source_provider_info.codecInfos[0].toString());
ASSERT_EQ(*codec_info, test_source_provider_info.codecInfos[0]);
}
@@ -282,8 +285,8 @@
provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_AAC);
ASSERT_TRUE(received_codec_info_aac.has_value());
auto codec_info = received_codec_info_aac.value();
- LOG(ERROR) << codec_info->toString();
- LOG(ERROR) << test_source_provider_info.codecInfos[1].toString();
+ log::error("{}", codec_info->toString());
+ log::error("{}", test_source_provider_info.codecInfos[1].toString());
ASSERT_EQ(*codec_info, test_source_provider_info.codecInfos[1]);
}
@@ -296,8 +299,8 @@
provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS);
ASSERT_TRUE(received_codec_info_opus.has_value());
auto codec_info = received_codec_info_opus.value();
- LOG(ERROR) << codec_info->toString();
- LOG(ERROR) << test_source_provider_info.codecInfos[2].toString();
+ log::error("{}", codec_info->toString());
+ log::error("{}", test_source_provider_info.codecInfos[2].toString());
ASSERT_EQ(*codec_info, test_source_provider_info.codecInfos[2]);
}
@@ -310,8 +313,8 @@
provider_info->GetCodec(BTAV_A2DP_CODEC_INDEX_SOURCE_EXT_MIN);
ASSERT_TRUE(received_codec_info_foobar.has_value());
auto codec_info = received_codec_info_foobar.value();
- LOG(ERROR) << codec_info->toString();
- LOG(ERROR) << test_source_provider_info.codecInfos[3].toString();
+ log::error("{}", codec_info->toString());
+ log::error("{}", test_source_provider_info.codecInfos[3].toString());
ASSERT_EQ(*codec_info, test_source_provider_info.codecInfos[3]);
}
@@ -770,4 +773,4 @@
(BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16 |
BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24 |
BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32));
-}
\ No newline at end of file
+}
diff --git a/system/audio_hal_interface/aidl/audio_ctrl_ack.h b/system/audio_hal_interface/aidl/audio_ctrl_ack.h
index 82c9c18..befe3eb 100644
--- a/system/audio_hal_interface/aidl/audio_ctrl_ack.h
+++ b/system/audio_hal_interface/aidl/audio_ctrl_ack.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
namespace bluetooth {
namespace audio {
namespace aidl {
@@ -57,3 +59,9 @@
} // namespace aidl
} // namespace audio
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::audio::aidl::BluetoothAudioCtrlAck>
+ : ostream_formatter {};
+} // namespace fmt
diff --git a/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc b/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc
index 9cc829f..95695d0 100644
--- a/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc
+++ b/system/audio_hal_interface/aidl/bluetooth_audio_port_impl.cc
@@ -16,6 +16,8 @@
#include "bluetooth_audio_port_impl.h"
+#include <bluetooth/log.h>
+
#include <vector>
#include "btif/include/btif_common.h"
@@ -41,8 +43,7 @@
auto aidl_retval =
provider_->streamStarted(BluetoothAudioCtrlAckToHalStatus(ack));
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
}
}
return ndk::ScopedAStatus::ok();
@@ -55,8 +56,7 @@
auto aidl_retval =
provider_->streamSuspended(BluetoothAudioCtrlAckToHalStatus(ack));
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
}
}
return ndk::ScopedAStatus::ok();
@@ -85,10 +85,9 @@
total_bytes_read = 0;
transmittedOctetsTimeStamp = {};
}
- VLOG(2) << __func__ << ": result=" << retval
- << ", delay=" << remote_delay_report_ns
- << ", data=" << total_bytes_read
- << " byte(s), timestamp=" << transmittedOctetsTimeStamp.toString();
+ log::verbose("result={}, delay={}, data={} byte(s), timestamp={}", retval,
+ remote_delay_report_ns, total_bytes_read,
+ transmittedOctetsTimeStamp.toString());
_aidl_return->remoteDeviceAudioDelayNanos =
static_cast<int64_t>(remote_delay_report_ns);
_aidl_return->transmittedOctets = static_cast<int64_t>(total_bytes_read);
@@ -99,13 +98,13 @@
ndk::ScopedAStatus BluetoothAudioPortImpl::updateSourceMetadata(
const SourceMetadata& source_metadata) {
StopWatchLegacy stop_watch(__func__);
- LOG(INFO) << __func__ << ": " << source_metadata.tracks.size() << " track(s)";
+ log::info("{} track(s)", source_metadata.tracks.size());
std::vector<playback_track_metadata_v7> tracks_vec;
tracks_vec.reserve(source_metadata.tracks.size());
for (const auto& track : source_metadata.tracks) {
auto num_of_tags = track.tags.size();
- LOG(INFO) << __func__ << " metadata tags size: " << num_of_tags;
+ log::info("metadata tags size: {}", num_of_tags);
playback_track_metadata_v7 desc_track = {
.base = {.usage = static_cast<audio_usage_t>(track.usage),
@@ -123,8 +122,7 @@
if ((copied_size >= max_tags_size) ||
(copied_size + string_len >= max_tags_size)) {
- LOG(ERROR) << __func__
- << "Too many tags, copied size: " << copied_size;
+ log::error("Too many tags, copied size: {}", copied_size);
break;
}
@@ -137,7 +135,7 @@
int string_len = track.tags[num_of_tags - 1].length();
if ((copied_size >= max_tags_size) ||
(copied_size + string_len >= max_tags_size)) {
- LOG(ERROR) << __func__ << "Too many tags, copied size: " << copied_size;
+ log::error("Too many tags, copied size: {}", copied_size);
} else {
track.tags[num_of_tags - 1].copy(desc_track.tags + copied_size,
string_len, 0);
@@ -158,13 +156,13 @@
ndk::ScopedAStatus BluetoothAudioPortImpl::updateSinkMetadata(
const SinkMetadata& sink_metadata) {
StopWatchLegacy stop_watch(__func__);
- LOG(INFO) << __func__ << ": " << sink_metadata.tracks.size() << " track(s)";
+ log::info("{} track(s)", sink_metadata.tracks.size());
std::vector<record_track_metadata_v7> tracks_vec;
tracks_vec.reserve(sink_metadata.tracks.size());
for (const auto& track : sink_metadata.tracks) {
auto num_of_tags = track.tags.size();
- LOG(INFO) << __func__ << " metadata tags size: " << num_of_tags;
+ log::info("metadata tags size: {}", num_of_tags);
record_track_metadata_v7 desc_track = {
.base =
@@ -183,8 +181,7 @@
if ((copied_size >= max_tags_size) ||
(copied_size + string_len >= max_tags_size)) {
- LOG(ERROR) << __func__
- << "Too many tags, copied size: " << copied_size;
+ log::error("Too many tags, copied size: {}", copied_size);
break;
}
@@ -197,7 +194,7 @@
int string_len = track.tags[num_of_tags - 1].length();
if ((copied_size >= max_tags_size) ||
(copied_size + string_len >= max_tags_size)) {
- LOG(ERROR) << __func__ << "Too many tags, copied size: " << copied_size;
+ log::error("Too many tags, copied size: {}", copied_size);
} else {
track.tags[num_of_tags - 1].copy(desc_track.tags + copied_size,
string_len, 0);
diff --git a/system/audio_hal_interface/aidl/client_interface_aidl.cc b/system/audio_hal_interface/aidl/client_interface_aidl.cc
index 7f290ea..58b0593 100644
--- a/system/audio_hal_interface/aidl/client_interface_aidl.cc
+++ b/system/audio_hal_interface/aidl/client_interface_aidl.cc
@@ -20,6 +20,7 @@
#include <android/binder_manager.h>
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
#include <thread>
#include <vector>
@@ -83,16 +84,15 @@
kDefaultAudioProviderFactoryInterface.c_str())));
if (provider_factory == nullptr) {
- LOG(ERROR) << __func__ << ", can't get capability from unknown factory";
+ log::error("can't get capability from unknown factory");
return capabilities;
}
auto aidl_retval =
provider_factory->getProviderCapabilities(session_type, &capabilities);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getProviderCapabilities failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}",
+ aidl_retval.getDescription());
}
return capabilities;
}
@@ -113,7 +113,7 @@
}
if (provider_factory == nullptr) {
- LOG(ERROR) << __func__ << ", can't get provider info from unknown factory";
+ log::error("can't get provider info from unknown factory");
return std::nullopt;
}
@@ -123,8 +123,8 @@
provider_factory->getProviderInfo(session_type, &provider_info);
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal::getProviderInfo failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal::getProviderInfo failure: {}",
+ aidl_retval.getDescription());
return std::nullopt;
}
@@ -141,8 +141,7 @@
}
if (provider_ == nullptr) {
- LOG(ERROR) << __func__
- << ", can't get a2dp configuration from unknown provider";
+ log::error("can't get a2dp configuration from unknown provider");
return std::nullopt;
}
@@ -151,8 +150,8 @@
&configuration);
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ", getA2dpConfiguration failure: "
- << aidl_retval.getDescription();
+ log::error("getA2dpConfiguration failure: {}",
+ aidl_retval.getDescription());
return std::nullopt;
}
@@ -165,9 +164,7 @@
A2dpStatus a2dp_status;
if (provider_ == nullptr) {
- LOG(ERROR)
- << __func__
- << ", can not parse A2DP configuration because of unknown provider";
+ log::error("can not parse A2DP configuration because of unknown provider");
return std::nullopt;
}
@@ -175,8 +172,8 @@
codec_id, configuration, codec_parameters, &a2dp_status);
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ", parseA2dpConfiguration failure: "
- << aidl_retval.getDescription();
+ log::error("parseA2dpConfiguration failure: {}",
+ aidl_retval.getDescription());
return std::nullopt;
}
@@ -185,18 +182,18 @@
void BluetoothAudioClientInterface::FetchAudioProvider() {
if (!is_aidl_available()) {
- LOG(ERROR) << __func__ << ": aidl is not supported on this platform.";
+ log::error("aidl is not supported on this platform.");
return;
}
if (provider_ != nullptr) {
- LOG(WARNING) << __func__ << ": refetch";
+ log::warn("refetch");
}
auto provider_factory = IBluetoothAudioProviderFactory::fromBinder(
::ndk::SpAIBinder(AServiceManager_waitForService(
kDefaultAudioProviderFactoryInterface.c_str())));
if (provider_factory == nullptr) {
- LOG(ERROR) << __func__ << ", can't get capability from unknown factory";
+ log::error("can't get capability from unknown factory");
return;
}
@@ -204,39 +201,36 @@
auto aidl_retval = provider_factory->getProviderCapabilities(
transport_->GetSessionType(), &capabilities_);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getProviderCapabilities failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}",
+ aidl_retval.getDescription());
return;
}
if (capabilities_.empty()) {
- LOG(WARNING) << __func__
- << ": SessionType=" << toString(transport_->GetSessionType())
- << " Not supported by BluetoothAudioHal";
+ log::warn("SessionType={} Not supported by BluetoothAudioHal",
+ toString(transport_->GetSessionType()));
return;
}
- LOG(INFO) << __func__ << ": BluetoothAudioHal SessionType="
- << toString(transport_->GetSessionType()) << " has "
- << capabilities_.size() << " AudioCapabilities";
+ log::info("BluetoothAudioHal SessionType={} has {} AudioCapabilities",
+ toString(transport_->GetSessionType()), capabilities_.size());
aidl_retval =
provider_factory->openProvider(transport_->GetSessionType(), &provider_);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioHal::openProvider failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::openProvider failure: {}",
+ aidl_retval.getDescription());
}
CHECK(provider_ != nullptr);
binder_status_t binder_status = AIBinder_linkToDeath(
provider_factory->asBinder().get(), death_recipient_.get(), this);
if (binder_status != STATUS_OK) {
- LOG(ERROR) << "Failed to linkToDeath " << static_cast<int>(binder_status);
+ log::error("Failed to linkToDeath {}", static_cast<int>(binder_status));
}
provider_factory_ = std::move(provider_factory);
- LOG(INFO) << "IBluetoothAudioProvidersFactory::openProvider() returned "
- << provider_.get()
- << (provider_->isRemote() ? " (remote)" : " (local)");
+ log::info("IBluetoothAudioProvidersFactory::openProvider() returned {}{}",
+ fmt::ptr(provider_.get()),
+ (provider_->isRemote() ? " (remote)" : " (local)"));
}
BluetoothAudioSinkClientInterface::BluetoothAudioSinkClientInterface(
@@ -266,10 +260,10 @@
}
void BluetoothAudioClientInterface::binderDiedCallbackAidl(void* ptr) {
- LOG(WARNING) << __func__ << ": restarting connection with new Audio Hal";
+ log::warn("restarting connection with new Audio Hal");
auto client = static_cast<BluetoothAudioClientInterface*>(ptr);
if (client == nullptr) {
- LOG(ERROR) << __func__ << ": null audio HAL died!";
+ log::error("null audio HAL died!");
return;
}
client->RenewAudioProviderAndSession();
@@ -332,15 +326,13 @@
transport_->UpdateAudioConfiguration(audio_config);
if (provider_ == nullptr) {
- LOG(INFO) << __func__
- << ": BluetoothAudioHal nullptr, update it as session started";
+ log::info("BluetoothAudioHal nullptr, update it as session started");
return true;
}
auto aidl_retval = provider_->updateAudioConfiguration(audio_config);
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
}
return true;
}
@@ -348,7 +340,7 @@
bool BluetoothAudioClientInterface::SetAllowedLatencyModes(
std::vector<LatencyMode> latency_modes) {
if (provider_ == nullptr) {
- LOG(INFO) << __func__ << ": BluetoothAudioHal nullptr";
+ log::info("BluetoothAudioHal nullptr");
return false;
}
@@ -364,19 +356,20 @@
}
for (auto latency_mode : latency_modes) {
- LOG(INFO) << "Latency mode allowed: "
- << ::aidl::android::hardware::bluetooth::audio::toString(
- latency_mode);
+ log::info(
+ "Latency mode allowed: {}",
+ ::aidl::android::hardware::bluetooth::audio::toString(latency_mode));
}
/* Low latency mode is used if modes other than FREE are present */
bool allowed = (latency_modes_.size() > 1);
- LOG(INFO) << __func__ << ": Latency mode allowed: " << allowed;
+ log::info("Latency mode allowed: {}", allowed);
auto aidl_retval = provider_->setLowLatencyModeAllowed(allowed);
if (!aidl_retval.isOk()) {
- LOG(WARNING) << __func__ << ": BluetoothAudioHal is not ready: "
- << aidl_retval.getDescription() << ". latency_modes_ is saved "
- << "and it will be sent to BluetoothAudioHal at StartSession.";
+ log::warn(
+ "BluetoothAudioHal is not ready: {}. latency_modes_ is saved and it "
+ "will be sent to BluetoothAudioHal at StartSession.",
+ aidl_retval.getDescription());
}
return true;
}
@@ -384,12 +377,12 @@
int BluetoothAudioClientInterface::StartSession() {
std::lock_guard<std::mutex> guard(internal_mutex_);
if (provider_ == nullptr) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
session_started_ = false;
return -EINVAL;
}
if (session_started_) {
- LOG(ERROR) << __func__ << ": session started already";
+ log::error("session started already");
return -EBUSY;
}
@@ -403,12 +396,11 @@
stack_if, transport_->GetAudioConfiguration(), latency_modes_, &mq_desc);
if (!aidl_retval.isOk()) {
if (aidl_retval.getExceptionCode() == EX_ILLEGAL_ARGUMENT) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal Error: "
- << aidl_retval.getDescription() << ", audioConfig="
- << transport_->GetAudioConfiguration().toString();
+ log::error("BluetoothAudioHal Error: {}, audioConfig={}",
+ aidl_retval.getDescription(),
+ transport_->GetAudioConfiguration().toString());
} else {
- LOG(FATAL) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
}
return -EPROTO;
}
@@ -438,10 +430,10 @@
return 0;
} else {
if (!data_mq_) {
- LOG(ERROR) << __func__ << "Failed to obtain audio data path";
+ log::error("Failed to obtain audio data path");
}
if (data_mq_ && !data_mq_->isValid()) {
- LOG(ERROR) << __func__ << "Audio data path is invalid";
+ log::error("Audio data path is invalid");
}
session_started_ = false;
return -EIO;
@@ -451,11 +443,11 @@
void BluetoothAudioClientInterface::StreamStarted(
const BluetoothAudioCtrlAck& ack) {
if (provider_ == nullptr) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
return;
}
if (ack == BluetoothAudioCtrlAck::PENDING) {
- LOG(INFO) << __func__ << ": " << ack << " ignored";
+ log::info("{} ignored", ack);
return;
}
BluetoothAudioStatus status = BluetoothAudioCtrlAckToHalStatus(ack);
@@ -463,19 +455,18 @@
auto aidl_retval = provider_->streamStarted(status);
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
}
}
void BluetoothAudioClientInterface::StreamSuspended(
const BluetoothAudioCtrlAck& ack) {
if (provider_ == nullptr) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
return;
}
if (ack == BluetoothAudioCtrlAck::PENDING) {
- LOG(INFO) << __func__ << ": " << ack << " ignored";
+ log::info("{} ignored", ack);
return;
}
BluetoothAudioStatus status = BluetoothAudioCtrlAckToHalStatus(ack);
@@ -483,21 +474,20 @@
auto aidl_retval = provider_->streamSuspended(status);
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
}
}
int BluetoothAudioClientInterface::EndSession() {
std::lock_guard<std::mutex> guard(internal_mutex_);
if (!session_started_) {
- LOG(INFO) << __func__ << ": session ended already";
+ log::info("session ended already");
return 0;
}
session_started_ = false;
if (provider_ == nullptr) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
return -EINVAL;
}
data_mq_ = nullptr;
@@ -505,8 +495,7 @@
auto aidl_retval = provider_->endSession();
if (!aidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << aidl_retval.getDescription();
+ log::error("BluetoothAudioHal failure: {}", aidl_retval.getDescription());
return -EPROTO;
}
return 0;
@@ -526,21 +515,21 @@
}
if (data_mq_ == nullptr || !data_mq_->isValid()) {
- LOG(WARNING) << __func__ << ", data_mq_ invalid";
+ log::warn("data_mq_ invalid");
return;
}
size_t size = data_mq_->availableToRead();
std::vector<MqDataType> buffer(size);
if (data_mq_->read(buffer.data(), size) != size) {
- LOG(WARNING) << __func__ << ", failed to flush data queue!";
+ log::warn("failed to flush data queue!");
}
}
size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf,
uint32_t len) {
if (!IsValid()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal is not valid";
+ log::error("BluetoothAudioHal is not valid");
return 0;
}
if (p_buf == nullptr || len == 0) return 0;
@@ -558,8 +547,7 @@
avail_to_read = len - total_read;
}
if (data_mq_->read((MqDataType*)p_buf + total_read, avail_to_read) == 0) {
- LOG(WARNING) << __func__ << ": len=" << len
- << " total_read=" << total_read << " failed";
+ log::warn("len={} total_read={} failed", len, total_read);
break;
}
total_read += avail_to_read;
@@ -569,9 +557,8 @@
timeout_ms -= kDefaultDataReadPollIntervalMs;
continue;
} else {
- LOG(WARNING) << __func__ << ": " << (len - total_read) << "/" << len
- << " no data " << (kDefaultDataReadTimeoutMs - timeout_ms)
- << " ms";
+ log::warn("{}/{} no data {} ms", (len - total_read), len,
+ (kDefaultDataReadTimeoutMs - timeout_ms));
break;
}
} while (total_read < len);
@@ -579,10 +566,10 @@
if (timeout_ms <
(kDefaultDataReadTimeoutMs - kDefaultDataReadPollIntervalMs) &&
timeout_ms >= kDefaultDataReadPollIntervalMs) {
- VLOG(1) << __func__ << ": underflow " << len << " -> " << total_read
- << " read " << (kDefaultDataReadTimeoutMs - timeout_ms) << " ms";
+ log::verbose("underflow {} -> {} read {} ms", len, total_read,
+ (kDefaultDataReadTimeoutMs - timeout_ms));
} else {
- VLOG(2) << __func__ << ": " << len << " -> " << total_read << " read";
+ log::verbose("{} -> {} read", len, total_read);
}
sink_->LogBytesRead(total_read);
@@ -595,8 +582,7 @@
FetchAudioProvider();
if (session_started_) {
- LOG(INFO) << __func__
- << ": Restart the session while audio HAL recovering ";
+ log::info("Restart the session while audio HAL recovering");
session_started_ = false;
StartSession();
@@ -606,7 +592,7 @@
size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf,
uint32_t len) {
if (!IsValid()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal is not valid";
+ log::error("BluetoothAudioHal is not valid");
return 0;
}
if (p_buf == nullptr || len == 0) return 0;
@@ -625,8 +611,7 @@
}
if (data_mq_->write((const MqDataType*)p_buf + total_written,
avail_to_write) == 0) {
- LOG(WARNING) << __func__ << ": len=" << len
- << " total_written=" << total_written << " failed";
+ log::warn("len={} total_written={} failed", len, total_written);
break;
}
total_written += avail_to_write;
@@ -636,9 +621,8 @@
timeout_ms -= kDefaultDataWritePollIntervalMs;
continue;
} else {
- LOG(WARNING) << __func__ << ": " << (len - total_written) << "/" << len
- << " no data " << (kDefaultDataWriteTimeoutMs - timeout_ms)
- << " ms";
+ log::warn("{}/{} no data {} ms", (len - total_written), len,
+ (kDefaultDataWriteTimeoutMs - timeout_ms));
break;
}
} while (total_written < len);
@@ -646,11 +630,10 @@
if (timeout_ms <
(kDefaultDataWriteTimeoutMs - kDefaultDataWritePollIntervalMs) &&
timeout_ms >= kDefaultDataWritePollIntervalMs) {
- VLOG(1) << __func__ << ": underflow " << len << " -> " << total_written
- << " read " << (kDefaultDataWriteTimeoutMs - timeout_ms) << " ms ";
+ log::verbose("underflow {} -> {} read {} ms", len, total_written,
+ (kDefaultDataWriteTimeoutMs - timeout_ms));
} else {
- VLOG(2) << __func__ << ": " << len << " -> " << total_written
- << " written ";
+ log::verbose("{} -> {} written", len, total_written);
}
source_->LogBytesWritten(total_written);
@@ -662,8 +645,8 @@
CHECK(provider_ != nullptr);
auto aidl_retval = provider_->setCodecPriority(codec_id, priority);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioHal::setCodecPriority failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::setCodecPriority failure: {}",
+ aidl_retval.getDescription());
}
}
@@ -686,14 +669,14 @@
&configurations);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getLeAudioAseConfiguration failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::getLeAudioAseConfiguration failure: {}",
+ aidl_retval.getDescription());
}
- LOG(INFO) << __func__
- << ": BluetoothAudioHal::getLeAudioAseConfiguration returned "
- << configurations.size() << " configurations.";
+ log::info(
+ "BluetoothAudioHal::getLeAudioAseConfiguration returned {} "
+ "configurations.",
+ configurations.size());
return configurations;
}
@@ -708,9 +691,8 @@
qosRequirement, &qos_configuration);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getLeAudioAseQosConfiguration failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::getLeAudioAseQosConfiguration failure: {}",
+ aidl_retval.getDescription());
}
return qos_configuration;
}
@@ -724,9 +706,8 @@
provider_->onSinkAseMetadataChanged(state, cigId, cisId, metadata);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::onSinkAseMetadataChanged failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::onSinkAseMetadataChanged failure: {}",
+ aidl_retval.getDescription());
}
}
@@ -739,9 +720,8 @@
provider_->onSourceAseMetadataChanged(state, cigId, cisId, metadata);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::onSinkAseMetadataChanged failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::onSinkAseMetadataChanged failure: {}",
+ aidl_retval.getDescription());
}
}
@@ -759,9 +739,8 @@
remoteSinkAudioCapabilities, requirement, &setting);
if (!aidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::onSinkAseMetadataChanged failure: "
- << aidl_retval.getDescription();
+ log::fatal("BluetoothAudioHal::onSinkAseMetadataChanged failure: {}",
+ aidl_retval.getDescription());
}
return setting;
diff --git a/system/audio_hal_interface/aidl/codec_status_aidl.cc b/system/audio_hal_interface/aidl/codec_status_aidl.cc
index 55297bb..506ab0d 100644
--- a/system/audio_hal_interface/aidl/codec_status_aidl.cc
+++ b/system/audio_hal_interface/aidl/codec_status_aidl.cc
@@ -18,6 +18,8 @@
#include "codec_status_aidl.h"
+#include <bluetooth/log.h>
+
#include <unordered_set>
#include <vector>
@@ -86,12 +88,12 @@
(sbc_config.minBitpool < sbc_capability.minBitpool ||
sbc_config.maxBitpool < sbc_config.minBitpool ||
sbc_capability.maxBitpool < sbc_config.maxBitpool)) {
- LOG(WARNING) << __func__ << ": software codec=" << sbc_config.toString()
- << " capability=" << sbc_capability.toString();
+ log::warn("software codec={} capability={}", sbc_config.toString(),
+ sbc_capability.toString());
return false;
}
- LOG(INFO) << __func__ << ": offload codec=" << sbc_config.toString()
- << " capability=" << sbc_capability.toString();
+ log::info("offload codec={} capability={}", sbc_config.toString(),
+ sbc_capability.toString());
return true;
}
@@ -105,12 +107,12 @@
aac_config.sampleRateHz) ||
(!aac_capability.variableBitRateSupported &&
aac_config.variableBitRateEnabled)) {
- LOG(WARNING) << __func__ << ": software codec=" << aac_config.toString()
- << " capability=" << aac_capability.toString();
+ log::warn("software codec={} capability={}", aac_config.toString(),
+ aac_capability.toString());
return false;
}
- LOG(INFO) << __func__ << ": offloading codec=" << aac_config.toString()
- << " capability=" << aac_capability.toString();
+ log::info("offloading codec={} capability={}", aac_config.toString(),
+ aac_capability.toString());
return true;
}
@@ -122,12 +124,12 @@
aptx_config.bitsPerSample) ||
!ContainedInVector(aptx_capability.sampleRateHz,
aptx_config.sampleRateHz)) {
- LOG(WARNING) << __func__ << ": software codec=" << aptx_config.toString()
- << " capability=" << aptx_capability.toString();
+ log::warn("software codec={} capability={}", aptx_config.toString(),
+ aptx_capability.toString());
return false;
}
- LOG(INFO) << __func__ << ": offloading codec=" << aptx_config.toString()
- << " capability=" << aptx_capability.toString();
+ log::info("offloading codec={} capability={}", aptx_config.toString(),
+ aptx_capability.toString());
return true;
}
@@ -139,12 +141,12 @@
ldac_config.bitsPerSample) ||
!ContainedInVector(ldac_capability.sampleRateHz,
ldac_config.sampleRateHz)) {
- LOG(WARNING) << __func__ << ": software codec=" << ldac_config.toString()
- << " capability=" << ldac_capability.toString();
+ log::warn("software codec={} capability={}", ldac_config.toString(),
+ ldac_capability.toString());
return false;
}
- LOG(INFO) << __func__ << ": offloading codec=" << ldac_config.toString()
- << " capability=" << ldac_capability.toString();
+ log::info("offloading codec={} capability={}", ldac_config.toString(),
+ ldac_capability.toString());
return true;
}
@@ -157,12 +159,12 @@
opus_config->frameDurationUs) ||
!ContainedInVector(opus_capability->samplingFrequencyHz,
opus_config->samplingFrequencyHz)) {
- LOG(WARNING) << __func__ << ": software codec=" << opus_config->toString()
- << " capability=" << opus_capability->toString();
+ log::warn("software codec={} capability={}", opus_config->toString(),
+ opus_capability->toString());
return false;
}
- LOG(INFO) << __func__ << ": offloading codec=" << opus_config->toString()
- << " capability=" << opus_capability->toString();
+ log::info("offloading codec={} capability={}", opus_config->toString(),
+ opus_capability->toString());
return true;
}
@@ -233,8 +235,7 @@
SbcConfiguration sbc_config = {};
sbc_config.sampleRateHz = A2dpCodecToHalSampleRate(current_codec);
if (sbc_config.sampleRateHz <= 0) {
- LOG(ERROR) << __func__
- << ": Unknown SBC sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown SBC sample_rate={}", current_codec.sample_rate);
return false;
}
uint8_t channel_mode = a2dp_offload.codec_info[3] & A2DP_SBC_IE_CH_MD_MSK;
@@ -252,7 +253,7 @@
sbc_config.channelMode = SbcChannelMode::MONO;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC channel_mode=" << channel_mode;
+ log::error("Unknown SBC channel_mode={}", channel_mode);
sbc_config.channelMode = SbcChannelMode::UNKNOWN;
return false;
}
@@ -271,7 +272,7 @@
sbc_config.blockLength = 16;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC block_length=" << block_length;
+ log::error("Unknown SBC block_length={}", block_length);
return false;
}
uint8_t sub_bands = a2dp_offload.codec_info[0] & A2DP_SBC_IE_SUBBAND_MSK;
@@ -283,7 +284,7 @@
sbc_config.numSubbands = 8;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC Subbands=" << sub_bands;
+ log::error("Unknown SBC Subbands={}", sub_bands);
return false;
}
uint8_t alloc_method = a2dp_offload.codec_info[0] & A2DP_SBC_IE_ALLOC_MD_MSK;
@@ -295,15 +296,14 @@
sbc_config.allocMethod = SbcAllocMethod::ALLOC_MD_L;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC alloc_method=" << alloc_method;
+ log::error("Unknown SBC alloc_method={}", alloc_method);
return false;
}
sbc_config.minBitpool = a2dp_offload.codec_info[1];
sbc_config.maxBitpool = a2dp_offload.codec_info[2];
sbc_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (sbc_config.bitsPerSample <= 0) {
- LOG(ERROR) << __func__ << ": Unknown SBC bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown SBC bits_per_sample={}", current_codec.bits_per_sample);
return false;
}
codec_config->config.set<CodecConfiguration::CodecSpecific::sbcConfig>(
@@ -337,19 +337,17 @@
aac_config.objectType = AacObjectType::MPEG4_SCALABLE;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown AAC object_type=" << +object_type;
+ log::error("Unknown AAC object_type={}", object_type);
return false;
}
aac_config.sampleRateHz = A2dpCodecToHalSampleRate(current_codec);
if (aac_config.sampleRateHz <= 0) {
- LOG(ERROR) << __func__
- << ": Unknown AAC sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown AAC sample_rate={}", current_codec.sample_rate);
return false;
}
aac_config.channelMode = A2dpCodecToHalChannelMode(current_codec);
if (aac_config.channelMode == ChannelMode::UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown AAC channel_mode=" << current_codec.channel_mode;
+ log::error("Unknown AAC channel_mode={}", current_codec.channel_mode);
return false;
}
uint8_t vbr_enabled =
@@ -362,13 +360,12 @@
aac_config.variableBitRateEnabled = false;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown AAC VBR=" << +vbr_enabled;
+ log::error("Unknown AAC VBR={}", vbr_enabled);
return false;
}
aac_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (aac_config.bitsPerSample <= 0) {
- LOG(ERROR) << __func__ << ": Unknown AAC bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown AAC bits_per_sample={}", current_codec.bits_per_sample);
return false;
}
codec_config->config.set<CodecConfiguration::CodecSpecific::aacConfig>(
@@ -393,20 +390,18 @@
AptxConfiguration aptx_config = {};
aptx_config.sampleRateHz = A2dpCodecToHalSampleRate(current_codec);
if (aptx_config.sampleRateHz <= 0) {
- LOG(ERROR) << __func__
- << ": Unknown aptX sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown aptX sample_rate={}", current_codec.sample_rate);
return false;
}
aptx_config.channelMode = A2dpCodecToHalChannelMode(current_codec);
if (aptx_config.channelMode == ChannelMode::UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown aptX channel_mode=" << current_codec.channel_mode;
+ log::error("Unknown aptX channel_mode={}", current_codec.channel_mode);
return false;
}
aptx_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (aptx_config.bitsPerSample <= 0) {
- LOG(ERROR) << __func__ << ": Unknown aptX bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown aptX bits_per_sample={}",
+ current_codec.bits_per_sample);
return false;
}
codec_config->config.set<CodecConfiguration::CodecSpecific::aptxConfig>(
@@ -426,8 +421,7 @@
LdacConfiguration ldac_config = {};
ldac_config.sampleRateHz = A2dpCodecToHalSampleRate(current_codec);
if (ldac_config.sampleRateHz <= 0) {
- LOG(ERROR) << __func__
- << ": Unknown LDAC sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown LDAC sample_rate={}", current_codec.sample_rate);
return false;
}
switch (a2dp_offload.codec_info[7]) {
@@ -441,8 +435,7 @@
ldac_config.channelMode = LdacChannelMode::MONO;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown LDAC channel_mode="
- << a2dp_offload.codec_info[7];
+ log::error("Unknown LDAC channel_mode={}", a2dp_offload.codec_info[7]);
ldac_config.channelMode = LdacChannelMode::UNKNOWN;
return false;
}
@@ -460,14 +453,13 @@
ldac_config.qualityIndex = LdacQualityIndex::ABR;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown LDAC QualityIndex="
- << a2dp_offload.codec_info[6];
+ log::error("Unknown LDAC QualityIndex={}", a2dp_offload.codec_info[6]);
return false;
}
ldac_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (ldac_config.bitsPerSample <= 0) {
- LOG(ERROR) << __func__ << ": Unknown LDAC bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown LDAC bits_per_sample={}",
+ current_codec.bits_per_sample);
return false;
}
codec_config->config.set<CodecConfiguration::CodecSpecific::ldacConfig>(
@@ -489,20 +481,18 @@
opus_config.pcmBitDepth = A2dpCodecToHalBitsPerSample(current_codec);
if (opus_config.pcmBitDepth <= 0) {
- LOG(ERROR) << __func__ << ": Unknown Opus bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown Opus bits_per_sample={}",
+ current_codec.bits_per_sample);
return false;
}
opus_config.samplingFrequencyHz = A2dpCodecToHalSampleRate(current_codec);
if (opus_config.samplingFrequencyHz <= 0) {
- LOG(ERROR) << __func__
- << ": Unknown Opus sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown Opus sample_rate={}", current_codec.sample_rate);
return false;
}
opus_config.channelMode = A2dpCodecToHalChannelMode(current_codec);
if (opus_config.channelMode == ChannelMode::UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown Opus channel_mode=" << current_codec.channel_mode;
+ log::error("Unknown Opus channel_mode={}", current_codec.channel_mode);
return false;
}
@@ -543,9 +533,8 @@
codec_type_set.insert(CodecType::LDAC);
break;
case BTAV_A2DP_CODEC_INDEX_SOURCE_LC3:
- LOG(WARNING) << __func__
- << ": Ignore source codec_type=" << preference.codec_type
- << ", not implemented";
+ log::warn("Ignore source codec_type={}, not implemented",
+ preference.codec_type);
break;
case BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS:
codec_type_set.insert(CodecType::OPUS);
@@ -557,14 +546,12 @@
case BTAV_A2DP_CODEC_INDEX_SINK_LDAC:
[[fallthrough]];
case BTAV_A2DP_CODEC_INDEX_SINK_OPUS:
- LOG(WARNING) << __func__
- << ": Ignore sink codec_type=" << preference.codec_type;
+ log::warn("Ignore sink codec_type={}", preference.codec_type);
break;
case BTAV_A2DP_CODEC_INDEX_MAX:
[[fallthrough]];
default:
- LOG(ERROR) << __func__
- << ": Unknown codec_type=" << preference.codec_type;
+ log::error("Unknown codec_type={}", preference.codec_type);
return false;
}
}
@@ -573,12 +560,10 @@
auto codec_type =
capability.get<AudioCapabilities::a2dpCapabilities>().codecType;
if (codec_type_set.find(codec_type) != codec_type_set.end()) {
- LOG(INFO) << __func__
- << ": enabled offloading capability=" << capability.toString();
+ log::info("enabled offloading capability={}", capability.toString());
offloading_preference.push_back(capability);
} else {
- LOG(INFO) << __func__
- << ": disabled offloading capability=" << capability.toString();
+ log::info("disabled offloading capability={}", capability.toString());
}
}
@@ -649,12 +634,12 @@
case CodecType::UNKNOWN:
[[fallthrough]];
default:
- LOG(ERROR) << __func__ << ": Unknown codecType="
- << toString(codec_capability.codecType);
+ log::error("Unknown codecType={}",
+ toString(codec_capability.codecType));
return false;
}
}
- LOG(INFO) << __func__ << ": software codec=" << codec_config.toString();
+ log::info("software codec={}", codec_config.toString());
return false;
}
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 e6fbd16..82127d9 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
@@ -18,11 +18,21 @@
#include "hearing_aid_software_encoding_aidl.h"
+#include <bluetooth/log.h>
+
#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h"
#include "client_interface_aidl.h"
#include "os/log.h"
#include "osi/include/properties.h"
+namespace fmt {
+template <>
+struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
+template <>
+struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {
+};
+} // namespace fmt
+
namespace {
using ::aidl::android::hardware::bluetooth::audio::ChannelMode;
@@ -33,6 +43,7 @@
using ::bluetooth::audio::aidl::PcmConfiguration;
using ::bluetooth::audio::aidl::SessionType;
using ::bluetooth::audio::aidl::hearing_aid::StreamCallbacks;
+using namespace bluetooth;
// Transport implementation for Hearing Aids
class HearingAidTransport
@@ -48,7 +59,7 @@
data_position_({}){};
BluetoothAudioCtrlAck StartRequest(bool is_low_latency) override {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_resume_(true)) {
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
}
@@ -56,7 +67,7 @@
}
BluetoothAudioCtrlAck SuspendRequest() override {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
::bluetooth::audio::aidl::hearing_aid::read(p_buf, sizeof(p_buf));
@@ -67,7 +78,7 @@
}
void StopRequest() override {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
// flush
uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
@@ -80,10 +91,9 @@
bool GetPresentationPosition(uint64_t* remote_delay_report_ns,
uint64_t* total_bytes_read,
timespec* data_position) override {
- VLOG(2) << __func__ << ": data=" << total_bytes_read_
- << " byte(s), timestamp=" << data_position_.tv_sec << "."
- << data_position_.tv_nsec
- << "s, delay report=" << remote_delay_report_ms_ << " msec.";
+ log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.",
+ total_bytes_read_, data_position_.tv_sec,
+ data_position_.tv_nsec, remote_delay_report_ms_);
if (remote_delay_report_ns != nullptr) {
*remote_delay_report_ns = remote_delay_report_ms_ * 1000000u;
}
@@ -101,11 +111,10 @@
const source_metadata_v7_t& source_metadata) override {
auto track_count = source_metadata.track_count;
auto tracks = source_metadata.tracks;
- LOG(INFO) << __func__ << ": " << track_count << " track(s) received";
+ log::info("{} track(s) received", track_count);
while (track_count) {
- VLOG(1) << __func__ << ": usage=" << tracks->base.usage
- << ", content_type=" << tracks->base.content_type
- << ", gain=" << tracks->base.gain;
+ log::verbose("usage={}, content_type={}, gain={}", tracks->base.usage,
+ tracks->base.content_type, tracks->base.gain);
--track_count;
++tracks;
}
@@ -114,7 +123,7 @@
void SinkMetadataChanged(const sink_metadata_v7_t&) override {}
void ResetPresentationPosition() override {
- VLOG(2) << __func__ << ": called.";
+ log::verbose("called.");
remote_delay_report_ms_ = 0;
total_bytes_read_ = 0;
data_position_ = {};
@@ -128,7 +137,7 @@
}
void SetRemoteDelay(uint16_t delay_report_ms) {
- LOG(INFO) << __func__ << ": delay_report=" << delay_report_ms << " msec";
+ log::info("delay_report={} msec", delay_report_ms);
remote_delay_report_ms_ = delay_report_ms;
}
@@ -180,16 +189,15 @@
bool init(StreamCallbacks stream_cb,
bluetooth::common::MessageLoopThread* /*message_loop*/) {
- LOG(INFO) << __func__;
+ log::info("");
if (is_hal_force_disabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
+ log::error("BluetoothAudio HAL is disabled");
return false;
}
if (!BluetoothAudioClientInterface::is_aidl_available()) {
- LOG(ERROR) << __func__
- << ": BluetoothAudio AIDL implementation does not exist";
+ log::error("BluetoothAudio AIDL implementation does not exist");
return false;
}
@@ -198,8 +206,7 @@
new bluetooth::audio::aidl::BluetoothAudioSinkClientInterface(
hearing_aid_sink);
if (!hearing_aid_hal_clientinterface->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Hearing Aid is invalid?!";
+ log::warn("BluetoothAudio HAL for Hearing Aid is invalid?!");
delete hearing_aid_hal_clientinterface;
hearing_aid_hal_clientinterface = nullptr;
delete hearing_aid_sink;
@@ -208,7 +215,7 @@
}
if (remote_delay_ms != 0) {
- LOG(INFO) << __func__ << ": restore DELAY " << remote_delay_ms << " ms";
+ log::info("restore DELAY {} ms", remote_delay_ms);
hearing_aid_sink->SetRemoteDelay(remote_delay_ms);
remote_delay_ms = 0;
}
@@ -217,7 +224,7 @@
}
void cleanup() {
- LOG(INFO) << __func__;
+ log::info("");
if (!is_hal_enabled()) return;
end_session();
delete hearing_aid_hal_clientinterface;
@@ -228,24 +235,24 @@
}
void start_session() {
- LOG(INFO) << __func__;
+ log::info("");
if (!is_hal_enabled()) return;
AudioConfiguration audio_config;
PcmConfiguration pcm_config{};
if (!HearingAidGetSelectedHalPcmConfig(&pcm_config)) {
- LOG(ERROR) << __func__ << ": cannot get PCM config";
+ log::error("cannot get PCM config");
return;
}
audio_config.set<AudioConfiguration::pcmConfig>(pcm_config);
if (!hearing_aid_hal_clientinterface->UpdateAudioConfig(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
hearing_aid_hal_clientinterface->StartSession();
}
void end_session() {
- LOG(INFO) << __func__;
+ log::info("");
if (!is_hal_enabled()) return;
hearing_aid_hal_clientinterface->EndSession();
}
@@ -258,12 +265,11 @@
// Update Hearing Aids delay report to BluetoothAudio HAL
void set_remote_delay(uint16_t delay_report_ms) {
if (!is_hal_enabled()) {
- LOG(INFO) << __func__ << ": not ready for DelayReport " << delay_report_ms
- << " ms";
+ log::info("not ready for DelayReport {} ms", delay_report_ms);
remote_delay_ms = delay_report_ms;
return;
}
- LOG(INFO) << __func__ << ": delay_report_ms=" << delay_report_ms << " ms";
+ log::info("delay_report_ms={} ms", delay_report_ms);
hearing_aid_sink->SetRemoteDelay(delay_report_ms);
}
diff --git a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc
index f5df063..2d3d3da 100644
--- a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc
+++ b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.cc
@@ -17,6 +17,8 @@
#include "hfp_client_interface_aidl.h"
+#include <bluetooth/log.h>
+
#include <map>
#include "aidl/android/hardware/bluetooth/audio/AudioConfiguration.h"
@@ -46,17 +48,17 @@
tBTA_AG_SCB* get_hfp_active_device_callback() {
const RawAddress& addr = bta_ag_get_active_device();
if (addr.IsEmpty()) {
- LOG(ERROR) << __func__ << ": No active device found";
+ log::error("No active device found");
return nullptr;
}
auto idx = bta_ag_idx_by_bdaddr(&addr);
if (idx == 0) {
- LOG(ERROR) << __func__ << ": No index found for active device";
+ log::error("No index found for active device");
return nullptr;
}
auto cb = bta_ag_scb_by_idx(idx);
if (cb == nullptr) {
- LOG(ERROR) << __func__ << ": No callback for the active device";
+ log::error("No callback for the active device");
return nullptr;
}
return cb;
@@ -73,10 +75,10 @@
BluetoothAudioCtrlAck HfpTransport::StartRequest() {
if (hfp_pending_cmd_ == HFP_CTRL_CMD_START) {
- LOG(INFO) << __func__ << ": HFP_CTRL_CMD_START in progress";
+ log::info("HFP_CTRL_CMD_START in progress");
return BluetoothAudioCtrlAck::PENDING;
} else if (hfp_pending_cmd_ != HFP_CTRL_CMD_NONE) {
- LOG(WARNING) << __func__ << ": busy in pending_cmd=" << hfp_pending_cmd_;
+ log::warn("busy in pending_cmd={}", hfp_pending_cmd_);
return BluetoothAudioCtrlAck::FAILURE_BUSY;
}
@@ -94,11 +96,10 @@
// status
auto status =
bluetooth::headset::GetInterface()->ConnectAudio(&cb->peer_addr, 0);
- LOG(INFO) << __func__ << ": ConnectAudio status = " << status << " - "
- << bt_status_text(status).c_str();
+ log::info("ConnectAudio status = {} - {}", status, bt_status_text(status));
auto ctrl_ack = status_to_ack_map.find(status);
if (ctrl_ack == status_to_ack_map.end()) {
- LOG_WARN("Unmapped status=%d", status);
+ log::warn("Unmapped status={}", status);
return BluetoothAudioCtrlAck::FAILURE;
}
if (ctrl_ack->second != BluetoothAudioCtrlAck::SUCCESS_FINISHED) {
@@ -108,16 +109,15 @@
}
void HfpTransport::StopRequest() {
- LOG(INFO) << __func__ << ": handling";
+ log::info("handling");
RawAddress addr = bta_ag_get_active_device();
if (addr.IsEmpty()) {
- LOG(ERROR) << __func__ << ": No active device found";
+ log::error("No active device found");
return;
}
hfp_pending_cmd_ = HFP_CTRL_CMD_STOP;
auto status = bluetooth::headset::GetInterface()->DisconnectAudio(&addr);
- LOG(INFO) << __func__ << ": DisconnectAudio status = " << status << " - "
- << bt_status_text(status).c_str();
+ log::info("DisconnectAudio status = {} - {}", status, bt_status_text(status));
hfp_pending_cmd_ = HFP_CTRL_CMD_NONE;
return;
}
diff --git a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h
index 2e11ee0..e2767d3 100644
--- a/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h
+++ b/system/audio_hal_interface/aidl/hfp_client_interface_aidl.h
@@ -16,6 +16,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <cstdint>
#include <unordered_map>
@@ -168,3 +170,9 @@
} // namespace aidl
} // namespace audio
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::audio::aidl::hfp::tHFP_CTRL_CMD>
+ : enum_formatter<bluetooth::audio::aidl::hfp::tHFP_CTRL_CMD> {};
+} // namespace fmt
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 b7d1491..e370049 100644
--- a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
+++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
@@ -19,6 +19,8 @@
#include "le_audio_software_aidl.h"
+#include <bluetooth/log.h>
+
#include <atomic>
#include <unordered_map>
#include <vector>
@@ -80,7 +82,7 @@
BluetoothAudioCtrlAck LeAudioTransport::StartRequest(bool is_low_latency) {
// Check if operation is pending already
if (GetStartRequestState() == StartRequestState::PENDING_AFTER_RESUME) {
- LOG_INFO("Start request is already pending. Ignore the request");
+ log::info("Start request is already pending. Ignore the request");
return BluetoothAudioCtrlAck::PENDING;
}
@@ -89,14 +91,14 @@
auto expected = StartRequestState::CONFIRMED;
if (std::atomic_compare_exchange_strong(&start_request_state_, &expected,
StartRequestState::IDLE)) {
- LOG_INFO("Start completed.");
+ log::info("Start completed.");
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
}
expected = StartRequestState::CANCELED;
if (std::atomic_compare_exchange_strong(&start_request_state_, &expected,
StartRequestState::IDLE)) {
- LOG_INFO("Start request failed.");
+ log::info("Start request failed.");
return BluetoothAudioCtrlAck::FAILURE;
}
@@ -104,12 +106,12 @@
if (std::atomic_compare_exchange_strong(
&start_request_state_, &expected,
StartRequestState::PENDING_AFTER_RESUME)) {
- LOG_INFO("Start pending.");
+ log::info("Start pending.");
return BluetoothAudioCtrlAck::PENDING;
}
}
- LOG_ERROR("Start request failed.");
+ log::error("Start request failed.");
auto expected = StartRequestState::PENDING_BEFORE_RESUME;
std::atomic_compare_exchange_strong(&start_request_state_, &expected,
StartRequestState::IDLE);
@@ -119,7 +121,7 @@
BluetoothAudioCtrlAck LeAudioTransport::StartRequestV2(bool is_low_latency) {
// Check if operation is pending already
if (GetStartRequestState() == StartRequestState::PENDING_AFTER_RESUME) {
- LOG_INFO("Start request is already pending. Ignore the request");
+ log::info("Start request is already pending. Ignore the request");
return BluetoothAudioCtrlAck::PENDING;
}
@@ -129,32 +131,32 @@
switch (start_request_state_) {
case StartRequestState::CONFIRMED:
- LOG_INFO("Start completed.");
+ log::info("Start completed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
case StartRequestState::CANCELED:
- LOG_INFO("Start request failed.");
+ log::info("Start request failed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::FAILURE;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Start pending.");
+ log::info("Start pending.");
SetStartRequestState(StartRequestState::PENDING_AFTER_RESUME);
return BluetoothAudioCtrlAck::PENDING;
default:
SetStartRequestState(StartRequestState::IDLE);
- LOG_ERROR("Unexpected state %d",
- static_cast<int>(start_request_state_.load()));
+ log::error("Unexpected state {}",
+ static_cast<int>(start_request_state_.load()));
return BluetoothAudioCtrlAck::FAILURE;
}
}
SetStartRequestState(StartRequestState::IDLE);
- LOG_INFO("On resume failed.");
+ log::info("On resume failed.");
return BluetoothAudioCtrlAck::FAILURE;
}
BluetoothAudioCtrlAck LeAudioTransport::SuspendRequest() {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
flush_();
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
@@ -164,16 +166,16 @@
}
void LeAudioTransport::StopRequest() {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
flush_();
}
}
void LeAudioTransport::SetLatencyMode(LatencyMode latency_mode) {
- LOG_DEBUG("Latency mode: %s",
- ::aidl::android::hardware::bluetooth::audio::toString(latency_mode)
- .c_str());
+ log::debug(
+ "Latency mode: {}",
+ ::aidl::android::hardware::bluetooth::audio::toString(latency_mode));
DsaMode prev_dsa_mode = dsa_mode_;
@@ -191,7 +193,7 @@
dsa_mode_ = DsaMode::ISO_HW;
break;
default:
- LOG(WARNING) << ", invalid latency mode: " << (int)latency_mode;
+ log::warn(", invalid latency mode: {}", (int)latency_mode);
return;
}
@@ -199,7 +201,7 @@
if (dsa_mode_ != prev_dsa_mode &&
cached_source_metadata_.tracks != nullptr &&
cached_source_metadata_.tracks != 0) {
- LOG(INFO) << ", latency mode changed, update source metadata";
+ log::info(", latency mode changed, update source metadata");
stream_cb_.on_metadata_update_(cached_source_metadata_, dsa_mode_);
}
}
@@ -208,10 +210,9 @@
bool LeAudioTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns,
uint64_t* total_bytes_processed,
timespec* data_position) {
- VLOG(2) << __func__ << ": data=" << total_bytes_processed_
- << " byte(s), timestamp=" << data_position_.tv_sec << "."
- << data_position_.tv_nsec
- << "s, delay report=" << remote_delay_report_ms_ << " msec.";
+ log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.",
+ total_bytes_processed_, data_position_.tv_sec,
+ data_position_.tv_nsec, remote_delay_report_ms_);
if (remote_delay_report_ns != nullptr) {
*remote_delay_report_ns = remote_delay_report_ms_ * 1000000u;
}
@@ -227,7 +228,7 @@
auto track_count = source_metadata.track_count;
if (track_count == 0) {
- LOG(WARNING) << ", invalid number of metadata changed tracks";
+ log::warn(", invalid number of metadata changed tracks");
return;
}
@@ -237,7 +238,7 @@
cached_source_metadata_.tracks = nullptr;
}
- LOG(INFO) << ", caching source metadata";
+ log::info(", caching source metadata");
playback_track_metadata_v7* tracks;
tracks = (playback_track_metadata_v7*)malloc(sizeof(*tracks) * track_count);
@@ -255,7 +256,7 @@
auto track_count = sink_metadata.track_count;
if (track_count == 0) {
- LOG(WARNING) << ", invalid number of metadata changed tracks";
+ log::warn(", invalid number of metadata changed tracks");
return;
}
@@ -264,7 +265,7 @@
}
void LeAudioTransport::ResetPresentationPosition() {
- VLOG(2) << __func__ << ": called.";
+ log::verbose("called.");
remote_delay_report_ms_ = 0;
total_bytes_processed_ = 0;
data_position_ = {};
@@ -278,7 +279,7 @@
}
void LeAudioTransport::SetRemoteDelay(uint16_t delay_report_ms) {
- LOG(INFO) << __func__ << ": delay_report=" << delay_report_ms << " msec";
+ log::info("delay_report={} msec", delay_report_ms);
remote_delay_report_ms_ = delay_report_ms;
}
@@ -332,8 +333,8 @@
}
auto ret = std::get<1>(result);
- LOG_VERBOSE(" new state: %d, return %s", (int)(start_request_state_.load()),
- ret ? "true" : "false");
+ log::verbose("new state: {}, return {}", (int)(start_request_state_.load()),
+ ret ? "true" : "false");
return ret;
}
@@ -607,13 +608,12 @@
const UnicastCapability& hal_capability,
CodecConfigSetting& stack_capability) {
if (hal_capability.codecType != CodecType::LC3) {
- LOG(WARNING) << "Unsupported codecType: "
- << toString(hal_capability.codecType);
+ log::warn("Unsupported codecType: {}", toString(hal_capability.codecType));
return false;
}
if (hal_capability.leAudioCodecCapabilities.getTag() !=
UnicastCapability::LeAudioCodecCapabilities::lc3Capabilities) {
- LOG(WARNING) << "Unknown LE Audio capabilities(vendor proprietary?)";
+ log::warn("Unknown LE Audio capabilities(vendor proprietary?)");
return false;
}
@@ -631,13 +631,12 @@
octets_per_frame_map.find(octets_per_frame) ==
octets_per_frame_map.end() ||
audio_location_map.find(supported_channel) == audio_location_map.end()) {
- LOG(ERROR) << __func__ << ": Failed to convert HAL format to stack format"
- << "\nsample rate hz = " << sample_rate_hz
- << "\nframe duration us = " << frame_duration_us
- << "\noctets per frame= " << octets_per_frame
- << "\nsupported channel = " << toString(supported_channel)
- << "\nchannel count per device = " << channel_count
- << "\ndevice count = " << hal_capability.deviceCount;
+ log::error(
+ "Failed to convert HAL format to stack format\nsample rate hz = "
+ "{}\nframe duration us = {}\noctets per frame= {}\nsupported channel = "
+ "{}\nchannel count per device = {}\ndevice count = {}",
+ sample_rate_hz, frame_duration_us, octets_per_frame,
+ toString(supported_channel), channel_count, hal_capability.deviceCount);
return false;
}
@@ -665,13 +664,13 @@
const BroadcastCapability& hal_bcast_capability,
CodecConfigSetting& stack_capability) {
if (hal_bcast_capability.codecType != CodecType::LC3) {
- LOG(WARNING) << "Unsupported codecType: "
- << toString(hal_bcast_capability.codecType);
+ log::warn("Unsupported codecType: {}",
+ toString(hal_bcast_capability.codecType));
return false;
}
if (hal_bcast_capability.leAudioCodecCapabilities.getTag() !=
BroadcastCapability::LeAudioCodecCapabilities::lc3Capabilities) {
- LOG(WARNING) << "Unknown LE Audio capabilities(vendor proprietary?)";
+ log::warn("Unknown LE Audio capabilities(vendor proprietary?)");
return false;
}
@@ -680,7 +679,7 @@
BroadcastCapability::LeAudioCodecCapabilities::lc3Capabilities>();
if (hal_lc3_capabilities->size() != 1) {
- LOG(WARNING) << __func__ << ": The number of config is not supported yet.";
+ log::warn("The number of config is not supported yet.");
}
auto supported_channel = hal_bcast_capability.supportedChannel;
@@ -694,13 +693,12 @@
octets_per_frame_map.find(octets_per_frame) ==
octets_per_frame_map.end() ||
audio_location_map.find(supported_channel) == audio_location_map.end()) {
- LOG(WARNING) << __func__
- << " : Failed to convert HAL format to stack format"
- << "\nsample rate hz = " << sample_rate_hz
- << "\nframe duration us = " << frame_duration_us
- << "\noctets per frame= " << octets_per_frame
- << "\nsupported channel = " << toString(supported_channel)
- << "\nchannel count per stream = " << channel_count;
+ log::warn(
+ "Failed to convert HAL format to stack format\nsample rate hz = "
+ "{}\nframe duration us = {}\noctets per frame= {}\nsupported channel = "
+ "{}\nchannel count per stream = {}",
+ sample_rate_hz, frame_duration_us, octets_per_frame,
+ toString(supported_channel), channel_count);
return false;
}
@@ -725,7 +723,7 @@
}
std::vector<AudioSetConfiguration> get_offload_capabilities() {
- LOG(INFO) << __func__;
+ log::info("");
std::vector<AudioSetConfiguration> offload_capabilities;
std::vector<AudioCapabilities> le_audio_hal_capabilities =
BluetoothAudioSinkClientInterface::GetAudioCapabilities(
@@ -779,12 +777,10 @@
if (!audio_set_config.confs.sink.empty() ||
!audio_set_config.confs.source.empty()) {
offload_capabilities.push_back(audio_set_config);
- LOG(INFO) << __func__
- << ": Supported codec capability =" << str_capability_log;
+ log::info("Supported codec capability ={}", str_capability_log);
} else {
- LOG(INFO) << __func__
- << ": Unknown codec capability =" << hal_cap.toString();
+ log::info("Unknown codec capability ={}", hal_cap.toString());
}
}
diff --git a/system/audio_hal_interface/audio_linux.h b/system/audio_hal_interface/audio_linux.h
index 1c723f7..87537ba 100644
--- a/system/audio_hal_interface/audio_linux.h
+++ b/system/audio_hal_interface/audio_linux.h
@@ -299,4 +299,4 @@
size_t track_count;
/** Array of metadata of each track connected to this sink. */
struct record_track_metadata_v7* tracks;
-} sink_metadata_v7_t;
\ No newline at end of file
+} sink_metadata_v7_t;
diff --git a/system/audio_hal_interface/hal_version_manager.cc b/system/audio_hal_interface/hal_version_manager.cc
index 36672cb..1401531 100644
--- a/system/audio_hal_interface/hal_version_manager.cc
+++ b/system/audio_hal_interface/hal_version_manager.cc
@@ -19,6 +19,7 @@
#include <android/binder_manager.h>
#include <android/hidl/manager/1.2/IServiceManager.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <hidl/ServiceManagement.h>
#include <memory>
@@ -79,15 +80,15 @@
kDefaultAudioProviderFactoryInterface.c_str())));
if (provider_factory == nullptr) {
- LOG_ERROR(
+ log::error(
"getInterfaceVersion: Can't get aidl version from unknown factory");
return BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
}
auto aidl_retval = provider_factory->getInterfaceVersion(&version);
if (!aidl_retval.isOk()) {
- LOG_ERROR("BluetoothAudioHal::getInterfaceVersion failure: %s",
- aidl_retval.getDescription().c_str());
+ log::error("BluetoothAudioHal::getInterfaceVersion failure: {}",
+ aidl_retval.getDescription());
return BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
}
@@ -118,9 +119,9 @@
CHECK(providers_factory)
<< "V2_1::IBluetoothAudioProvidersFactory::getService() failed";
- LOG(INFO) << "V2_1::IBluetoothAudioProvidersFactory::getService() returned "
- << providers_factory.get()
- << (providers_factory->isRemote() ? " (remote)" : " (local)");
+ log::info("V2_1::IBluetoothAudioProvidersFactory::getService() returned {}{}",
+ fmt::ptr(providers_factory.get()),
+ (providers_factory->isRemote() ? " (remote)" : " (local)"));
return providers_factory;
}
@@ -136,9 +137,9 @@
CHECK(providers_factory)
<< "V2_0::IBluetoothAudioProvidersFactory::getService() failed";
- LOG(INFO) << "V2_0::IBluetoothAudioProvidersFactory::getService() returned "
- << providers_factory.get()
- << (providers_factory->isRemote() ? " (remote)" : " (local)");
+ log::info("V2_0::IBluetoothAudioProvidersFactory::getService() returned {}{}",
+ fmt::ptr(providers_factory.get()),
+ (providers_factory->isRemote() ? " (remote)" : " (local)"));
guard.unlock();
return providers_factory;
}
@@ -163,8 +164,8 @@
auto hidl_retval = service_manager->listManifestByInterface(
kFullyQualifiedInterfaceName_2_1, listManifestByInterface_cb);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": IServiceManager::listByInterface failure: "
- << hidl_retval.description();
+ log::fatal("IServiceManager::listByInterface failure: {}",
+ hidl_retval.description());
return;
}
@@ -177,8 +178,8 @@
hidl_retval = service_manager->listManifestByInterface(
kFullyQualifiedInterfaceName_2_0, listManifestByInterface_cb);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": IServiceManager::listByInterface failure: "
- << hidl_retval.description();
+ log::fatal("IServiceManager::listByInterface failure: {}",
+ hidl_retval.description());
return;
}
@@ -189,7 +190,7 @@
}
hal_version_ = BluetoothAudioHalVersion::VERSION_UNAVAILABLE;
- LOG(ERROR) << __func__ << " No supported HAL version";
+ log::error("No supported HAL version");
}
} // namespace audio
diff --git a/system/audio_hal_interface/hfp_client_interface.cc b/system/audio_hal_interface/hfp_client_interface.cc
index 5a42fa2..f6ad94c 100644
--- a/system/audio_hal_interface/hfp_client_interface.cc
+++ b/system/audio_hal_interface/hfp_client_interface.cc
@@ -18,6 +18,8 @@
#define LOG_TAG "BTAudioClientHfpStub"
+#include <bluetooth/log.h>
+
#include "aidl/client_interface_aidl.h"
#include "aidl/hfp_client_interface_aidl.h"
#include "hal_version_manager.h"
@@ -110,11 +112,11 @@
HfpClientInterface* HfpClientInterface::interface = nullptr;
HfpClientInterface* HfpClientInterface::Get() {
if (!is_hal_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
+ log::error("BluetoothAudio HAL is disabled");
return nullptr;
}
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return nullptr;
}
if (HfpClientInterface::interface == nullptr) {
@@ -125,7 +127,7 @@
// Decode client implementation
void HfpClientInterface::Decode::Cleanup() {
- LOG(INFO) << __func__ << " decode";
+ log::info("decode");
StopSession();
if (HfpDecodingTransport::instance_) {
delete HfpDecodingTransport::software_hal_interface;
@@ -137,15 +139,15 @@
void HfpClientInterface::Decode::StartSession() {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " decode";
+ log::info("decode");
AudioConfiguration audio_config;
audio_config.set<AudioConfiguration::pcmConfig>(
get_default_pcm_configuration());
if (!get_decode_client_interface()->UpdateAudioConfig(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
get_decode_client_interface()->StartSession();
@@ -153,10 +155,10 @@
void HfpClientInterface::Decode::StopSession() {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " decode";
+ log::info("decode");
get_decode_client_interface()->EndSession();
if (get_decode_transport_instance()) {
get_decode_transport_instance()->ResetPendingCmd();
@@ -167,22 +169,20 @@
void HfpClientInterface::Decode::UpdateAudioConfigToHal(
const ::hfp::offload_config& offload_config) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(WARNING)
- << __func__
- << " decode - Unsupported update audio config for software session";
+ log::warn("decode - Unsupported update audio config for software session");
return;
}
size_t HfpClientInterface::Decode::Read(uint8_t* p_buf, uint32_t len) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return 0;
}
- LOG(INFO) << __func__ << " decode";
+ log::info("decode");
return get_decode_client_interface()->ReadAudioData(p_buf, len);
}
@@ -196,10 +196,10 @@
instance->ResetPendingCmd();
return;
case aidl::hfp::HFP_CTRL_CMD_NONE:
- LOG_WARN("no pending start stream request");
+ log::warn("no pending start stream request");
return;
default:
- LOG_WARN("Invalid state, %d", pending_cmd);
+ log::warn("Invalid state, {}", pending_cmd);
}
}
@@ -213,28 +213,28 @@
instance->ResetPendingCmd();
return;
case aidl::hfp::HFP_CTRL_CMD_NONE:
- LOG_WARN("no pending start stream request");
+ log::warn("no pending start stream request");
return;
default:
- LOG_WARN("Invalid state, %d", pending_cmd);
+ log::warn("Invalid state, {}", pending_cmd);
}
}
HfpClientInterface::Decode* HfpClientInterface::GetDecode(
bluetooth::common::MessageLoopThread* /*message_loop*/) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return nullptr;
}
if (decode_ == nullptr) {
decode_ = new Decode();
} else {
- LOG(WARNING) << __func__ << ": Decode is already acquired";
+ log::warn("Decode is already acquired");
return nullptr;
}
- LOG(INFO) << __func__ << " decode";
+ log::info("decode");
HfpDecodingTransport::instance_ = new HfpDecodingTransport(
aidl::SessionType::HFP_SOFTWARE_DECODING_DATAPATH);
@@ -242,7 +242,7 @@
new aidl::BluetoothAudioSinkClientInterface(
HfpDecodingTransport::instance_);
if (!HfpDecodingTransport::software_hal_interface->IsValid()) {
- LOG(WARNING) << __func__ << ": BluetoothAudio HAL for HFP is invalid";
+ log::warn("BluetoothAudio HAL for HFP is invalid");
delete HfpDecodingTransport::software_hal_interface;
HfpDecodingTransport::software_hal_interface = nullptr;
delete HfpDecodingTransport::instance_;
@@ -258,11 +258,11 @@
bool HfpClientInterface::ReleaseDecode(HfpClientInterface::Decode* decode) {
if (decode != decode_) {
- LOG(WARNING) << __func__ << ", can't release not acquired decode";
+ log::warn("can't release not acquired decode");
return false;
}
- LOG(INFO) << __func__ << " decode";
+ log::info("decode");
if (get_decode_client_interface()) decode->Cleanup();
delete decode_;
@@ -273,7 +273,7 @@
// Encoding client implementation
void HfpClientInterface::Encode::Cleanup() {
- LOG(INFO) << __func__ << " encode";
+ log::info("encode");
StopSession();
if (HfpEncodingTransport::instance_) {
delete HfpEncodingTransport::software_hal_interface;
@@ -285,15 +285,15 @@
void HfpClientInterface::Encode::StartSession() {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " encode";
+ log::info("encode");
AudioConfiguration audio_config;
audio_config.set<AudioConfiguration::pcmConfig>(
get_default_pcm_configuration());
if (!get_encode_client_interface()->UpdateAudioConfig(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
get_encode_client_interface()->StartSession();
@@ -301,10 +301,10 @@
void HfpClientInterface::Encode::StopSession() {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " encode";
+ log::info("encode");
get_encode_client_interface()->EndSession();
if (get_encode_transport_instance()) {
get_encode_transport_instance()->ResetPendingCmd();
@@ -315,22 +315,20 @@
void HfpClientInterface::Encode::UpdateAudioConfigToHal(
const ::hfp::offload_config& offload_config) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(WARNING)
- << __func__
- << " encode - Unsupported update audio config for software session";
+ log::warn("encode - Unsupported update audio config for software session");
return;
}
size_t HfpClientInterface::Encode::Write(const uint8_t* p_buf, uint32_t len) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return 0;
}
- LOG(INFO) << __func__ << " encode";
+ log::info("encode");
return get_encode_client_interface()->WriteAudioData(p_buf, len);
}
@@ -344,10 +342,10 @@
instance->ResetPendingCmd();
return;
case aidl::hfp::HFP_CTRL_CMD_NONE:
- LOG_WARN("no pending start stream request");
+ log::warn("no pending start stream request");
return;
default:
- LOG_WARN("Invalid state, %d", pending_cmd);
+ log::warn("Invalid state, {}", pending_cmd);
}
}
@@ -361,28 +359,28 @@
instance->ResetPendingCmd();
return;
case aidl::hfp::HFP_CTRL_CMD_NONE:
- LOG_WARN("no pending start stream request");
+ log::warn("no pending start stream request");
return;
default:
- LOG_WARN("Invalid state, %d", pending_cmd);
+ log::warn("Invalid state, {}", pending_cmd);
}
}
HfpClientInterface::Encode* HfpClientInterface::GetEncode(
bluetooth::common::MessageLoopThread* /*message_loop*/) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return nullptr;
}
if (encode_ == nullptr) {
encode_ = new Encode();
} else {
- LOG(WARNING) << __func__ << ": Encoding is already acquired";
+ log::warn("Encoding is already acquired");
return nullptr;
}
- LOG(INFO) << __func__ << " encode";
+ log::info("encode");
HfpEncodingTransport::instance_ = new HfpEncodingTransport(
aidl::SessionType::HFP_SOFTWARE_ENCODING_DATAPATH);
@@ -390,7 +388,7 @@
new aidl::BluetoothAudioSourceClientInterface(
HfpEncodingTransport::instance_);
if (!HfpEncodingTransport::software_hal_interface->IsValid()) {
- LOG(WARNING) << __func__ << ": BluetoothAudio HAL for HFP is invalid";
+ log::warn("BluetoothAudio HAL for HFP is invalid");
delete HfpEncodingTransport::software_hal_interface;
HfpEncodingTransport::software_hal_interface = nullptr;
delete HfpEncodingTransport::instance_;
@@ -406,7 +404,7 @@
bool HfpClientInterface::ReleaseEncode(HfpClientInterface::Encode* encode) {
if (encode != encode_) {
- LOG(WARNING) << __func__ << ", can't release not acquired encode";
+ log::warn("can't release not acquired encode");
return false;
}
@@ -421,7 +419,7 @@
// Offload client implementation
// Based on HfpEncodingTransport
void HfpClientInterface::Offload::Cleanup() {
- LOG(INFO) << __func__ << " offload";
+ log::info("offload");
StopSession();
if (HfpEncodingTransport::instance_) {
delete HfpEncodingTransport::offloading_hal_interface;
@@ -433,15 +431,15 @@
void HfpClientInterface::Offload::StartSession() {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " offload";
+ log::info("offload");
AudioConfiguration audio_config;
audio_config.set<AudioConfiguration::hfpConfig>(
get_default_hfp_configuration());
if (!get_encode_client_interface()->UpdateAudioConfig(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
get_encode_client_interface()->StartSession();
@@ -449,10 +447,10 @@
void HfpClientInterface::Offload::StopSession() {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " offload";
+ log::info("offload");
get_encode_client_interface()->EndSession();
if (get_encode_transport_instance()) {
get_encode_transport_instance()->ResetPendingCmd();
@@ -463,11 +461,11 @@
void HfpClientInterface::Offload::UpdateAudioConfigToHal(
const ::hfp::offload_config& offload_config) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return;
}
- LOG(INFO) << __func__ << " offload";
+ log::info("offload");
get_encode_client_interface()->UpdateAudioConfig(
offload_config_to_hal_audio_config(offload_config));
}
@@ -482,10 +480,10 @@
instance->ResetPendingCmd();
return;
case aidl::hfp::HFP_CTRL_CMD_NONE:
- LOG_WARN("no pending start stream request");
+ log::warn("no pending start stream request");
return;
default:
- LOG_WARN("Invalid state, %d", pending_cmd);
+ log::warn("Invalid state, {}", pending_cmd);
}
}
@@ -499,10 +497,10 @@
instance->ResetPendingCmd();
return;
case aidl::hfp::HFP_CTRL_CMD_NONE:
- LOG_WARN("no pending start stream request");
+ log::warn("no pending start stream request");
return;
default:
- LOG_WARN("Invalid state, %d", pending_cmd);
+ log::warn("Invalid state, {}", pending_cmd);
}
}
@@ -515,18 +513,18 @@
HfpClientInterface::Offload* HfpClientInterface::GetOffload(
bluetooth::common::MessageLoopThread* /*message_loop*/) {
if (!is_aidl_support_hfp()) {
- LOG(WARNING) << __func__ << ": Unsupported HIDL or AIDL version";
+ log::warn("Unsupported HIDL or AIDL version");
return nullptr;
}
if (offload_ == nullptr) {
offload_ = new Offload();
} else {
- LOG(WARNING) << __func__ << ": Offload is already acquired";
+ log::warn("Offload is already acquired");
return nullptr;
}
- LOG(INFO) << __func__ << " offload";
+ log::info("offload");
// Prepare offload hal interface.
if (bta_ag_get_sco_offload_enabled()) {
@@ -536,8 +534,7 @@
new aidl::BluetoothAudioSourceClientInterface(
HfpEncodingTransport::instance_);
if (!HfpEncodingTransport::offloading_hal_interface->IsValid()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudio HAL for HFP offloading is invalid";
+ log::fatal("BluetoothAudio HAL for HFP offloading is invalid");
delete HfpEncodingTransport::offloading_hal_interface;
HfpEncodingTransport::offloading_hal_interface = nullptr;
delete HfpEncodingTransport::instance_;
@@ -558,7 +555,7 @@
bool HfpClientInterface::ReleaseOffload(HfpClientInterface::Offload* offload) {
if (offload != offload_) {
- LOG(WARNING) << __func__ << ", can't release not acquired offload";
+ log::warn("can't release not acquired offload");
return false;
}
diff --git a/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc b/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc
index 6cd71ea..ce4e3a0 100644
--- a/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc
+++ b/system/audio_hal_interface/hidl/a2dp_encoding_hidl.cc
@@ -17,6 +17,8 @@
#include "a2dp_encoding_hidl.h"
+#include <bluetooth/log.h>
+
#include <vector>
#include "a2dp_sbc_constants.h"
@@ -29,6 +31,16 @@
#include "osi/include/properties.h"
#include "types/raw_address.h"
+namespace fmt {
+template <>
+struct formatter<tA2DP_CTRL_CMD> : enum_formatter<tA2DP_CTRL_CMD> {};
+template <>
+struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
+template <>
+struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {
+};
+} // namespace fmt
+
namespace {
using ::bluetooth::audio::hidl::AudioCapabilities;
@@ -50,6 +62,8 @@
using ::bluetooth::audio::hidl::codec::A2dpSbcToHalConfig;
using ::bluetooth::audio::hidl::codec::CodecConfiguration;
+using namespace bluetooth;
+
BluetoothAudioCtrlAck a2dp_ack_to_bt_audio_ctrl_ack(tA2DP_CTRL_ACK ack);
// Provide call-in APIs for the Bluetooth Audio HAL
@@ -67,16 +81,16 @@
BluetoothAudioCtrlAck StartRequest() override {
// Check if a previous request is not finished
if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_START) {
- LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_START in progress";
+ log::info("A2DP_CTRL_CMD_START in progress");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
} else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
- LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
+ log::warn("busy in pending_cmd={}", a2dp_pending_cmd_);
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
}
// Don't send START request to stack while we are in a call
if (!bluetooth::headset::IsCallIdle()) {
- LOG(ERROR) << __func__ << ": call state is busy";
+ log::error("call state is busy");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_INCALL_FAILURE);
}
@@ -93,28 +107,28 @@
a2dp_pending_cmd_ = A2DP_CTRL_CMD_START;
btif_av_stream_start(A2dpType::kSource);
if (btif_av_get_peer_sep(A2dpType::kSource) != AVDT_TSEP_SRC) {
- LOG(INFO) << __func__ << ": accepted";
+ log::info("accepted");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
}
a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_SUCCESS);
}
- LOG(ERROR) << __func__ << ": AV stream is not ready to start";
+ log::error("AV stream is not ready to start");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
}
BluetoothAudioCtrlAck SuspendRequest() override {
// Previous request is not finished
if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_SUSPEND) {
- LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_SUSPEND in progress";
+ log::info("A2DP_CTRL_CMD_SUSPEND in progress");
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_PENDING);
} else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
- LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
+ log::warn("busy in pending_cmd={}", a2dp_pending_cmd_);
return a2dp_ack_to_bt_audio_ctrl_ack(A2DP_CTRL_ACK_FAILURE);
}
// Local suspend
if (btif_av_stream_started_ready(A2dpType::kSource)) {
- LOG(INFO) << __func__ << ": accepted";
+ log::info("accepted");
a2dp_pending_cmd_ = A2DP_CTRL_CMD_SUSPEND;
btif_av_stream_suspend();
return BluetoothAudioCtrlAck::PENDING;
@@ -133,7 +147,7 @@
btif_av_clear_remote_suspend_flag(A2dpType::kSource);
return;
}
- LOG(INFO) << __func__ << ": handling";
+ log::info("handling");
a2dp_pending_cmd_ = A2DP_CTRL_CMD_STOP;
btif_av_stream_stop(RawAddress::kEmpty);
}
@@ -144,21 +158,19 @@
*remote_delay_report_ns = remote_delay_report_ * 100000u;
*total_bytes_read = total_bytes_read_;
*data_position = data_position_;
- VLOG(2) << __func__ << ": delay=" << remote_delay_report_
- << "/10ms, data=" << total_bytes_read_
- << " byte(s), timestamp=" << data_position_.tv_sec << "."
- << data_position_.tv_nsec << "s";
+ log::verbose("delay={}/10ms, data={} byte(s), timestamp={}.{}s",
+ remote_delay_report_, total_bytes_read_, data_position_.tv_sec,
+ data_position_.tv_nsec);
return true;
}
void MetadataChanged(const source_metadata_t& source_metadata) override {
auto track_count = source_metadata.track_count;
auto tracks = source_metadata.tracks;
- VLOG(1) << __func__ << ": " << track_count << " track(s) received";
+ log::verbose("{} track(s) received", track_count);
while (track_count) {
- VLOG(2) << __func__ << ": usage=" << tracks->usage
- << ", content_type=" << tracks->content_type
- << ", gain=" << tracks->gain;
+ log::verbose("usage={}, content_type={}, gain={}", tracks->usage,
+ tracks->content_type, tracks->gain);
--track_count;
++tracks;
}
@@ -230,7 +242,7 @@
bool a2dp_get_selected_hal_codec_config(CodecConfiguration* codec_config) {
A2dpCodecConfig* a2dp_config = bta_av_get_a2dp_current_codec();
if (a2dp_config == nullptr) {
- LOG(WARNING) << __func__ << ": failure to get A2DP codec config";
+ log::warn("failure to get A2DP codec config");
*codec_config = ::bluetooth::audio::hidl::codec::kInvalidCodecConfiguration;
return false;
}
@@ -269,8 +281,7 @@
case BTAV_A2DP_CODEC_INDEX_MAX:
[[fallthrough]];
default:
- LOG(ERROR) << __func__
- << ": Unknown codec_type=" << current_codec.codec_type;
+ log::error("Unknown codec_type={}", current_codec.codec_type);
*codec_config =
::bluetooth::audio::hidl::codec::kInvalidCodecConfiguration;
return false;
@@ -293,7 +304,7 @@
} else if (codec_config->peerMtu > MAX_3MBPS_AVDTP_MTU) {
codec_config->peerMtu = MAX_3MBPS_AVDTP_MTU;
}
- LOG(INFO) << __func__ << ": CodecConfiguration=" << toString(*codec_config);
+ log::info("CodecConfiguration={}", toString(*codec_config));
return true;
}
@@ -301,7 +312,7 @@
if (pcm_config == nullptr) return false;
A2dpCodecConfig* a2dp_codec_configs = bta_av_get_a2dp_current_codec();
if (a2dp_codec_configs == nullptr) {
- LOG(WARNING) << __func__ << ": failure to get A2DP codec config";
+ log::warn("failure to get A2DP codec config");
*pcm_config = BluetoothAudioSinkClientInterface::kInvalidPcmConfiguration;
return false;
}
@@ -351,10 +362,10 @@
// Initialize BluetoothAudio HAL: openProvider
bool init(bluetooth::common::MessageLoopThread* message_loop) {
- LOG(INFO) << __func__;
+ log::info("");
if (is_hal_2_0_force_disabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
+ log::error("BluetoothAudio HAL is disabled");
return false;
}
@@ -363,7 +374,7 @@
software_hal_interface =
new BluetoothAudioSinkClientInterface(a2dp_sink, message_loop);
if (!software_hal_interface->IsValid()) {
- LOG(WARNING) << __func__ << ": BluetoothAudio HAL for A2DP is invalid?!";
+ log::warn("BluetoothAudio HAL for A2DP is invalid?!");
delete software_hal_interface;
software_hal_interface = nullptr;
delete a2dp_sink;
@@ -375,8 +386,7 @@
offloading_hal_interface =
new BluetoothAudioSinkClientInterface(a2dp_sink, message_loop);
if (!offloading_hal_interface->IsValid()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudio HAL for A2DP offloading is invalid?!";
+ log::fatal("BluetoothAudio HAL for A2DP offloading is invalid?!");
delete offloading_hal_interface;
offloading_hal_interface = nullptr;
delete a2dp_sink;
@@ -394,8 +404,7 @@
: software_hal_interface);
if (remote_delay != 0) {
- LOG(INFO) << __func__ << ": restore DELAY "
- << static_cast<float>(remote_delay / 10.0) << " ms";
+ log::info("restore DELAY {} ms", static_cast<float>(remote_delay / 10.0));
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
->SetRemoteDelay(remote_delay);
remote_delay = 0;
@@ -430,22 +439,22 @@
// Set up the codec into BluetoothAudio HAL
bool setup_codec() {
if (!is_hal_2_0_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return false;
}
CodecConfiguration codec_config{};
if (!a2dp_get_selected_hal_codec_config(&codec_config)) {
- LOG(ERROR) << __func__ << ": Failed to get CodecConfiguration";
+ log::error("Failed to get CodecConfiguration");
return false;
}
bool should_codec_offloading =
bluetooth::audio::hidl::codec::IsCodecOffloadingEnabled(codec_config);
if (should_codec_offloading && !is_hal_2_0_offloading()) {
- LOG(WARNING) << __func__ << ": Switching BluetoothAudio HAL to Hardware";
+ log::warn("Switching BluetoothAudio HAL to Hardware");
end_session();
active_hal_interface = offloading_hal_interface;
} else if (!should_codec_offloading && is_hal_2_0_offloading()) {
- LOG(WARNING) << __func__ << ": Switching BluetoothAudio HAL to Software";
+ log::warn("Switching BluetoothAudio HAL to Software");
end_session();
active_hal_interface = software_hal_interface;
}
@@ -457,7 +466,7 @@
} else {
PcmParameters pcm_config{};
if (!a2dp_get_selected_hal_pcm_config(&pcm_config)) {
- LOG(ERROR) << __func__ << ": Failed to get PcmConfiguration";
+ log::error("Failed to get PcmConfiguration");
return false;
}
audio_config.pcmConfig(pcm_config);
@@ -467,7 +476,7 @@
void start_session() {
if (!is_hal_2_0_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return;
}
active_hal_interface->StartSession();
@@ -475,7 +484,7 @@
void end_session() {
if (!is_hal_2_0_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return;
}
active_hal_interface->EndSession();
@@ -487,15 +496,14 @@
void ack_stream_started(const tA2DP_CTRL_ACK& ack) {
auto ctrl_ack = a2dp_ack_to_bt_audio_ctrl_ack(ack);
- LOG(INFO) << __func__ << ": result=" << ctrl_ack;
+ log::info("result={}", ctrl_ack);
auto a2dp_sink =
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance());
auto pending_cmd = a2dp_sink->GetPendingCmd();
if (pending_cmd == A2DP_CTRL_CMD_START) {
active_hal_interface->StreamStarted(ctrl_ack);
} else {
- LOG(WARNING) << __func__ << ": pending=" << pending_cmd
- << " ignore result=" << ctrl_ack;
+ log::warn("pending={} ignore result={}", pending_cmd, ctrl_ack);
return;
}
if (ctrl_ack != bluetooth::audio::hidl::BluetoothAudioCtrlAck::PENDING) {
@@ -505,17 +513,16 @@
void ack_stream_suspended(const tA2DP_CTRL_ACK& ack) {
auto ctrl_ack = a2dp_ack_to_bt_audio_ctrl_ack(ack);
- LOG(INFO) << __func__ << ": result=" << ctrl_ack;
+ log::info("result={}", ctrl_ack);
auto a2dp_sink =
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance());
auto pending_cmd = a2dp_sink->GetPendingCmd();
if (pending_cmd == A2DP_CTRL_CMD_SUSPEND) {
active_hal_interface->StreamSuspended(ctrl_ack);
} else if (pending_cmd == A2DP_CTRL_CMD_STOP) {
- LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_STOP result=" << ctrl_ack;
+ log::info("A2DP_CTRL_CMD_STOP result={}", ctrl_ack);
} else {
- LOG(WARNING) << __func__ << ": pending=" << pending_cmd
- << " ignore result=" << ctrl_ack;
+ log::warn("pending={} ignore result={}", pending_cmd, ctrl_ack);
return;
}
if (ctrl_ack != bluetooth::audio::hidl::BluetoothAudioCtrlAck::PENDING) {
@@ -526,13 +533,13 @@
// Read from the FMQ of BluetoothAudio HAL
size_t read(uint8_t* p_buf, uint32_t len) {
if (!is_hal_2_0_enabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is not enabled";
+ log::error("BluetoothAudio HAL is not enabled");
return 0;
} else if (is_hal_2_0_offloading()) {
- LOG(ERROR) << __func__ << ": session_type="
- << toString(active_hal_interface->GetTransportInstance()
- ->GetSessionType())
- << " is not A2DP_SOFTWARE_ENCODING_DATAPATH";
+ log::error(
+ "session_type={} is not A2DP_SOFTWARE_ENCODING_DATAPATH",
+ toString(
+ active_hal_interface->GetTransportInstance()->GetSessionType()));
return 0;
}
return active_hal_interface->ReadAudioData(p_buf, len);
@@ -541,13 +548,12 @@
// Update A2DP delay report to BluetoothAudio HAL
void set_remote_delay(uint16_t delay_report) {
if (!is_hal_2_0_enabled()) {
- LOG(INFO) << __func__ << ": not ready for DelayReport "
- << static_cast<float>(delay_report / 10.0) << " ms";
+ log::info("not ready for DelayReport {} ms",
+ static_cast<float>(delay_report / 10.0));
remote_delay = delay_report;
return;
}
- VLOG(1) << __func__ << ": DELAY " << static_cast<float>(delay_report / 10.0)
- << " ms";
+ log::verbose("DELAY {} ms", static_cast<float>(delay_report / 10.0));
static_cast<A2dpTransport*>(active_hal_interface->GetTransportInstance())
->SetRemoteDelay(delay_report);
}
diff --git a/system/audio_hal_interface/hidl/client_interface_hidl.cc b/system/audio_hal_interface/hidl/client_interface_hidl.cc
index 6c51091..4c230e8 100644
--- a/system/audio_hal_interface/hidl/client_interface_hidl.cc
+++ b/system/audio_hal_interface/hidl/client_interface_hidl.cc
@@ -20,6 +20,7 @@
#include <android/hardware/bluetooth/audio/2.0/IBluetoothAudioPort.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <hidl/MQDescriptor.h>
#include <future>
@@ -80,8 +81,7 @@
auto hidl_retval =
provider_->streamStarted(BluetoothAudioCtrlAckToHalStatus(ack));
if (!hidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << hidl_retval.description();
+ log::error("BluetoothAudioHal failure: {}", hidl_retval.description());
}
}
return Void();
@@ -94,8 +94,7 @@
auto hidl_retval =
provider_->streamSuspended(BluetoothAudioCtrlAckToHalStatus(ack));
if (!hidl_retval.isOk()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal failure: "
- << hidl_retval.description();
+ log::error("BluetoothAudioHal failure: {}", hidl_retval.description());
}
}
return Void();
@@ -124,10 +123,9 @@
total_bytes_read = 0;
transmittedOctetsTimeStamp = {};
}
- VLOG(2) << __func__ << ": result=" << retval
- << ", delay=" << remote_delay_report_ns
- << ", data=" << total_bytes_read
- << " byte(s), timestamp=" << toString(transmittedOctetsTimeStamp);
+ log::verbose("result={}, delay={}, data={} byte(s), timestamp={}", retval,
+ remote_delay_report_ns, total_bytes_read,
+ toString(transmittedOctetsTimeStamp));
_hidl_cb((retval ? BluetoothAudioStatus::SUCCESS
: BluetoothAudioStatus::FAILURE),
remote_delay_report_ns, total_bytes_read,
@@ -137,8 +135,7 @@
Return<void> updateMetadata(const SourceMetadata& sourceMetadata) override {
StopWatchLegacy stop_watch(__func__);
- LOG(INFO) << __func__ << ": " << sourceMetadata.tracks.size()
- << " track(s)";
+ log::info("{} track(s)", sourceMetadata.tracks.size());
// refer to StreamOut.impl.h within Audio HAL (AUDIO_HAL_VERSION_5_0)
std::vector<playback_track_metadata> metadata_vec;
metadata_vec.reserve(sourceMetadata.tracks.size());
@@ -176,7 +173,7 @@
uint64_t /*cookie*/,
const ::android::wp<::android::hidl::base::V1_0::IBase>& /*who*/)
override {
- LOG(WARNING) << __func__ << ": restarting connection with new Audio Hal";
+ log::warn("restarting connection with new Audio Hal");
if (bluetooth_audio_clientif_ != nullptr && message_loop_ != nullptr) {
// restart the session on the correct thread
message_loop_->DoInThread(
@@ -185,7 +182,7 @@
&BluetoothAudioClientInterface::RenewAudioProviderAndSession,
base::Unretained(bluetooth_audio_clientif_)));
} else {
- LOG(ERROR) << __func__ << ": BluetoothAudioClientInterface corrupted";
+ log::error("BluetoothAudioClientInterface corrupted");
}
}
@@ -224,7 +221,7 @@
if (HalVersionManager::GetHalVersion() ==
BluetoothAudioHalVersion::VERSION_UNAVAILABLE) {
- LOG(ERROR) << __func__ << ", can't get capability from unknown factory";
+ log::error("can't get capability from unknown factory");
return capabilities;
}
@@ -242,9 +239,8 @@
auto hidl_retval = providersFactory->getProviderCapabilities(
session_type, getProviderCapabilities_cb);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getProviderCapabilities failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}",
+ hidl_retval.description());
}
return capabilities;
}
@@ -255,7 +251,7 @@
std::vector<AudioCapabilities_2_1> capabilities_2_1(0);
if (HalVersionManager::GetHalVersion() !=
BluetoothAudioHalVersion::VERSION_2_1) {
- LOG(ERROR) << __func__ << ", can't get capability for HAL 2.1";
+ log::error("can't get capability for HAL 2.1");
return capabilities_2_1;
}
@@ -274,16 +270,15 @@
auto hidl_retval = providersFactory->getProviderCapabilities_2_1(
session_type_2_1, getProviderCapabilities_cb);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getProviderCapabilities failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}",
+ hidl_retval.description());
}
return capabilities_2_1;
}
void BluetoothAudioClientInterface::FetchAudioProvider() {
if (provider_ != nullptr) {
- LOG(WARNING) << __func__ << ": reflash";
+ log::warn("reflash");
}
android::sp<IBluetoothAudioProvidersFactory_2_0> providersFactory =
@@ -302,20 +297,17 @@
auto hidl_retval = providersFactory->getProviderCapabilities(
transport_->GetSessionType(), getProviderCapabilities_cb);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getProviderCapabilities failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}",
+ hidl_retval.description());
return;
}
if (capabilities_.empty()) {
- LOG(WARNING) << __func__
- << ": SessionType=" << toString(transport_->GetSessionType())
- << " Not supported by BluetoothAudioHal";
+ log::warn("SessionType={} Not supported by BluetoothAudioHal",
+ toString(transport_->GetSessionType()));
return;
}
- LOG(INFO) << __func__ << ": BluetoothAudioHal SessionType="
- << toString(transport_->GetSessionType()) << " has "
- << capabilities_.size() << " AudioCapabilities";
+ log::info("BluetoothAudioHal SessionType={} has {} AudioCapabilities",
+ toString(transport_->GetSessionType()), capabilities_.size());
std::promise<void> openProvider_promise;
auto openProvider_future = openProvider_promise.get_future();
@@ -323,35 +315,37 @@
[&provider_ = this->provider_, &openProvider_promise](
BluetoothAudioStatus status,
const android::sp<IBluetoothAudioProvider>& provider) {
- LOG(INFO) << "openProvider_cb(" << toString(status) << ")";
+ log::info("openProvider_cb({})", toString(status));
if (status == BluetoothAudioStatus::SUCCESS) {
provider_ = provider;
}
- ALOGE_IF(!provider_, "Failed to open BluetoothAudio provider");
+ if (!provider_) {
+ log::error("Failed to open BluetoothAudio provider");
+ }
openProvider_promise.set_value();
};
hidl_retval = providersFactory->openProvider(transport_->GetSessionType(),
openProvider_cb);
openProvider_future.get();
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioHal::openProvider failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioHal::openProvider failure: {}",
+ hidl_retval.description());
}
CHECK(provider_ != nullptr);
if (!provider_->linkToDeath(death_recipient_, 0).isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioDeathRecipient failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioDeathRecipient failure: {}",
+ hidl_retval.description());
}
- LOG(INFO) << "IBluetoothAudioProvidersFactory::openProvider() returned "
- << provider_.get()
- << (provider_->isRemote() ? " (remote)" : " (local)");
+ log::info("IBluetoothAudioProvidersFactory::openProvider() returned {}{}",
+ fmt::ptr(provider_.get()),
+ (provider_->isRemote() ? " (remote)" : " (local)"));
}
void BluetoothAudioClientInterface::FetchAudioProvider_2_1() {
if (provider_2_1_ != nullptr) {
- LOG(WARNING) << __func__ << ": reflash";
+ log::warn("reflash");
}
android::sp<IBluetoothAudioProvidersFactory_2_1> providersFactory =
@@ -370,20 +364,18 @@
auto hidl_retval = providersFactory->getProviderCapabilities_2_1(
transport_->GetSessionType_2_1(), getProviderCapabilities_cb);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal::getProviderCapabilities failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioHal::getProviderCapabilities failure: {}",
+ hidl_retval.description());
return;
}
if (capabilities_2_1_.empty()) {
- LOG(WARNING) << __func__ << ": SessionType="
- << toString(transport_->GetSessionType_2_1())
- << " Not supported by BluetoothAudioHal";
+ log::warn("SessionType={} Not supported by BluetoothAudioHal",
+ toString(transport_->GetSessionType_2_1()));
return;
}
- LOG(INFO) << __func__ << ": BluetoothAudioHal SessionType="
- << toString(transport_->GetSessionType_2_1()) << " has "
- << capabilities_2_1_.size() << " AudioCapabilities";
+ log::info("BluetoothAudioHal SessionType={} has {} AudioCapabilities",
+ toString(transport_->GetSessionType_2_1()),
+ capabilities_2_1_.size());
std::promise<void> openProvider_promise;
auto openProvider_future = openProvider_promise.get_future();
@@ -391,30 +383,32 @@
[&provider_2_1_ = this->provider_2_1_, &openProvider_promise](
BluetoothAudioStatus status,
const android::sp<IBluetoothAudioProvider_2_1>& provider_2_1) {
- LOG(INFO) << "openProvider_cb(" << toString(status) << ")";
+ log::info("openProvider_cb({})", toString(status));
if (status == BluetoothAudioStatus::SUCCESS) {
provider_2_1_ = provider_2_1;
}
- ALOGE_IF(!provider_2_1_, "Failed to open BluetoothAudio provider_2_1");
+ if (!provider_2_1_) {
+ log::error("Failed to open BluetoothAudio provider_2_1");
+ }
openProvider_promise.set_value();
};
hidl_retval = providersFactory->openProvider_2_1(
transport_->GetSessionType_2_1(), openProvider_cb);
openProvider_future.get();
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioHal::openProvider failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioHal::openProvider failure: {}",
+ hidl_retval.description());
}
CHECK(provider_2_1_ != nullptr);
if (!provider_2_1_->linkToDeath(death_recipient_, 0).isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioDeathRecipient failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioDeathRecipient failure: {}",
+ hidl_retval.description());
}
- LOG(INFO) << "IBluetoothAudioProvidersFactory::openProvider() returned "
- << provider_2_1_.get()
- << (provider_2_1_->isRemote() ? " (remote)" : " (local)");
+ log::info("IBluetoothAudioProvidersFactory::openProvider() returned {}{}",
+ fmt::ptr(provider_2_1_.get()),
+ (provider_2_1_->isRemote() ? " (remote)" : " (local)"));
}
BluetoothAudioSinkClientInterface::BluetoothAudioSinkClientInterface(
@@ -442,15 +436,15 @@
if (provider_ != nullptr) {
auto hidl_retval = provider_->unlinkToDeath(death_recipient_);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioDeathRecipient failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioDeathRecipient failure: {}",
+ hidl_retval.description());
}
}
if (provider_2_1_ != nullptr) {
auto hidl_retval = provider_2_1_->unlinkToDeath(death_recipient_);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioDeathRecipient failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioDeathRecipient failure: {}",
+ hidl_retval.description());
}
}
}
@@ -480,15 +474,15 @@
if (provider_ != nullptr) {
auto hidl_retval = provider_->unlinkToDeath(death_recipient_);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioDeathRecipient failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioDeathRecipient failure: {}",
+ hidl_retval.description());
}
}
if (provider_2_1_ != nullptr) {
auto hidl_retval = provider_2_1_->unlinkToDeath(death_recipient_);
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__ << ": BluetoothAudioDeathRecipient failure: "
- << hidl_retval.description();
+ log::fatal("BluetoothAudioDeathRecipient failure: {}",
+ hidl_retval.description());
}
}
}
@@ -550,12 +544,12 @@
int BluetoothAudioClientInterface::StartSession() {
std::lock_guard<std::mutex> guard(internal_mutex_);
if (provider_ == nullptr) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
session_started_ = false;
return -EINVAL;
}
if (session_started_) {
- LOG(ERROR) << __func__ << ": session started already";
+ log::error("session started already");
return -EBUSY;
}
@@ -570,7 +564,7 @@
auto hidl_cb = [&session_status, &tempDataMQ, &hidl_startSession_promise](
BluetoothAudioStatus status,
const DataMQ::Descriptor& dataMQ) {
- LOG(INFO) << "startSession_cb(" << toString(status) << ")";
+ log::info("startSession_cb({})", toString(status));
session_status = status;
if (status == BluetoothAudioStatus::SUCCESS && dataMQ.isHandleValid()) {
tempDataMQ.reset(new DataMQ(dataMQ));
@@ -581,8 +575,7 @@
stack_if, transport_->GetAudioConfiguration(), hidl_cb);
hidl_startSession_future.get();
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal failure: " << hidl_retval.description();
+ log::fatal("BluetoothAudioHal failure: {}", hidl_retval.description());
return -EPROTO;
}
@@ -599,23 +592,25 @@
transport_->ResetPresentationPosition();
session_started_ = true;
return 0;
- } else {
- ALOGE_IF(!mDataMQ, "Failed to obtain audio data path");
- ALOGE_IF(mDataMQ && !mDataMQ->isValid(), "Audio data path is invalid");
- session_started_ = false;
- return -EIO;
}
+ if (!mDataMQ) {
+ log::error("Failed to obtain audio data path");
+ } else {
+ log::error("Audio data path is invalid");
+ }
+ session_started_ = false;
+ return -EIO;
}
int BluetoothAudioClientInterface::StartSession_2_1() {
std::lock_guard<std::mutex> guard(internal_mutex_);
if (provider_2_1_ == nullptr) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
session_started_ = false;
return -EINVAL;
}
if (session_started_) {
- LOG(ERROR) << __func__ << ": session started already";
+ log::error("session started already");
return -EBUSY;
}
@@ -630,7 +625,7 @@
auto hidl_cb = [&session_status, &tempDataMQ, &hidl_startSession_promise](
BluetoothAudioStatus status,
const DataMQ::Descriptor& dataMQ) {
- LOG(INFO) << "startSession_cb(" << toString(status) << ")";
+ log::info("startSession_cb({})", toString(status));
session_status = status;
if (status == BluetoothAudioStatus::SUCCESS && dataMQ.isHandleValid()) {
tempDataMQ.reset(new DataMQ(dataMQ));
@@ -641,8 +636,7 @@
stack_if, transport_->GetAudioConfiguration_2_1(), hidl_cb);
hidl_startSession_future.get();
if (!hidl_retval.isOk()) {
- LOG(FATAL) << __func__
- << ": BluetoothAudioHal failure: " << hidl_retval.description();
+ log::fatal("BluetoothAudioHal failure: {}", hidl_retval.description());
return -EPROTO;
}
@@ -659,18 +653,20 @@
transport_->ResetPresentationPosition();
session_started_ = true;
return 0;
- } else {
- ALOGE_IF(!mDataMQ, "Failed to obtain audio data path");
- ALOGE_IF(mDataMQ && !mDataMQ->isValid(), "Audio data path is invalid");
- session_started_ = false;
- return -EIO;
}
+ if (!mDataMQ) {
+ log::error("Failed to obtain audio data path");
+ } else {
+ log::error("Audio data path is invalid");
+ }
+ session_started_ = false;
+ return -EIO;
}
void BluetoothAudioClientInterface::StreamStarted(
const BluetoothAudioCtrlAck& ack) {
if (ack == BluetoothAudioCtrlAck::PENDING) {
- LOG(INFO) << __func__ << ": " << ack << " ignored";
+ log::info("{} ignored", ack);
return;
}
BluetoothAudioStatus status = BluetoothAudioCtrlAckToHalStatus(ack);
@@ -681,20 +677,19 @@
} else if (provider_ != nullptr) {
hidl_retval = provider_->streamStarted(status);
} else {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
return;
}
if (!hidl_retval.isOk()) {
- LOG(ERROR) << __func__
- << ": BluetoothAudioHal failure: " << hidl_retval.description();
+ log::error("BluetoothAudioHal failure: {}", hidl_retval.description());
}
}
void BluetoothAudioClientInterface::StreamSuspended(
const BluetoothAudioCtrlAck& ack) {
if (ack == BluetoothAudioCtrlAck::PENDING) {
- LOG(INFO) << __func__ << ": " << ack << " ignored";
+ log::info("{} ignored", ack);
return;
}
BluetoothAudioStatus status = BluetoothAudioCtrlAckToHalStatus(ack);
@@ -705,20 +700,19 @@
} else if (provider_ != nullptr) {
hidl_retval = provider_->streamSuspended(status);
} else {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
return;
}
if (!hidl_retval.isOk()) {
- LOG(ERROR) << __func__
- << ": BluetoothAudioHal failure: " << hidl_retval.description();
+ log::error("BluetoothAudioHal failure: {}", hidl_retval.description());
}
}
int BluetoothAudioClientInterface::EndSession() {
std::lock_guard<std::mutex> guard(internal_mutex_);
if (!session_started_) {
- LOG(INFO) << __func__ << ": session ended already";
+ log::info("session ended already");
return 0;
}
@@ -731,13 +725,12 @@
} else if (provider_ != nullptr) {
hidl_retval = provider_->endSession();
} else {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal nullptr";
+ log::error("BluetoothAudioHal nullptr");
return -EINVAL;
}
if (!hidl_retval.isOk()) {
- LOG(ERROR) << __func__
- << ": BluetoothAudioHal failure: " << hidl_retval.description();
+ log::error("BluetoothAudioHal failure: {}", hidl_retval.description());
return -EPROTO;
}
return 0;
@@ -751,20 +744,20 @@
return;
if (mDataMQ == nullptr || !mDataMQ->isValid()) {
- LOG(WARNING) << __func__ << ", mDataMQ invalid";
+ log::warn("mDataMQ invalid");
return;
}
size_t size = mDataMQ->availableToRead();
uint8_t p_buf[size];
if (mDataMQ->read(p_buf, size) != size)
- LOG(WARNING) << __func__ << ", failed to flush data queue!";
+ log::warn("failed to flush data queue!");
}
size_t BluetoothAudioSinkClientInterface::ReadAudioData(uint8_t* p_buf,
uint32_t len) {
if (!IsValid()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal is not valid";
+ log::error("BluetoothAudioHal is not valid");
return 0;
}
if (p_buf == nullptr || len == 0) return 0;
@@ -782,8 +775,7 @@
avail_to_read = len - total_read;
}
if (mDataMQ->read(p_buf + total_read, avail_to_read) == 0) {
- LOG(WARNING) << __func__ << ": len=" << len
- << " total_read=" << total_read << " failed";
+ log::warn("len={} total_read={} failed", len, total_read);
break;
}
total_read += avail_to_read;
@@ -793,9 +785,8 @@
timeout_ms -= kDefaultDataReadPollIntervalMs;
continue;
} else {
- LOG(WARNING) << __func__ << ": " << (len - total_read) << "/" << len
- << " no data " << (kDefaultDataReadTimeoutMs - timeout_ms)
- << " ms";
+ log::warn("{}/{} no data {} ms", (len - total_read), len,
+ (kDefaultDataReadTimeoutMs - timeout_ms));
break;
}
} while (total_read < len);
@@ -803,10 +794,10 @@
if (timeout_ms <
(kDefaultDataReadTimeoutMs - kDefaultDataReadPollIntervalMs) &&
timeout_ms >= kDefaultDataReadPollIntervalMs) {
- VLOG(1) << __func__ << ": underflow " << len << " -> " << total_read
- << " read " << (kDefaultDataReadTimeoutMs - timeout_ms) << " ms";
+ log::verbose("underflow {} -> {} read {} ms", len, total_read,
+ (kDefaultDataReadTimeoutMs - timeout_ms));
} else {
- VLOG(2) << __func__ << ": " << len << " -> " << total_read << " read";
+ log::verbose("{} -> {} read", len, total_read);
}
sink_->LogBytesRead(total_read);
@@ -823,12 +814,12 @@
} else if (transport_->GetSessionType() != SessionType::UNKNOWN) {
FetchAudioProvider();
} else {
- LOG(FATAL) << __func__ << ", cannot renew audio provider";
+ log::fatal("cannot renew audio provider");
return;
}
if (session_started_) {
- LOG(INFO) << __func__ << ": Restart the session while audio HAL recovering";
+ log::info("Restart the session while audio HAL recovering");
session_started_ = false;
if (provider_2_1_ != nullptr)
@@ -841,7 +832,7 @@
size_t BluetoothAudioSourceClientInterface::WriteAudioData(const uint8_t* p_buf,
uint32_t len) {
if (!IsValid()) {
- LOG(ERROR) << __func__ << ": BluetoothAudioHal is not valid";
+ log::error("BluetoothAudioHal is not valid");
return 0;
}
if (p_buf == nullptr || len == 0) return 0;
@@ -859,8 +850,7 @@
avail_to_write = len - total_written;
}
if (mDataMQ->write(p_buf + total_written, avail_to_write) == 0) {
- LOG(WARNING) << __func__ << ": len=" << len
- << " total_written=" << total_written << " failed";
+ log::warn("len={} total_written={} failed", len, total_written);
break;
}
total_written += avail_to_write;
@@ -870,9 +860,8 @@
timeout_ms -= kDefaultDataWritePollIntervalMs;
continue;
} else {
- LOG(WARNING) << __func__ << ": " << (len - total_written) << "/" << len
- << " no data " << (kDefaultDataWriteTimeoutMs - timeout_ms)
- << " ms";
+ log::warn("{}/{} no data {} ms", (len - total_written), len,
+ (kDefaultDataWriteTimeoutMs - timeout_ms));
break;
}
} while (total_written < len);
@@ -880,10 +869,10 @@
if (timeout_ms <
(kDefaultDataWriteTimeoutMs - kDefaultDataWritePollIntervalMs) &&
timeout_ms >= kDefaultDataWritePollIntervalMs) {
- VLOG(1) << __func__ << ": underflow " << len << " -> " << total_written
- << " read " << (kDefaultDataWriteTimeoutMs - timeout_ms) << " ms";
+ log::verbose("underflow {} -> {} read {} ms", len, total_written,
+ (kDefaultDataWriteTimeoutMs - timeout_ms));
} else {
- VLOG(2) << __func__ << ": " << len << " -> " << total_written << " written";
+ log::verbose("{} -> {} written", len, total_written);
}
source_->LogBytesWritten(total_written);
diff --git a/system/audio_hal_interface/hidl/client_interface_hidl.h b/system/audio_hal_interface/hidl/client_interface_hidl.h
index 2ca53e2..04e0e9b 100644
--- a/system/audio_hal_interface/hidl/client_interface_hidl.h
+++ b/system/audio_hal_interface/hidl/client_interface_hidl.h
@@ -18,6 +18,7 @@
#include <android/hardware/bluetooth/audio/2.1/IBluetoothAudioProvider.h>
#include <android/hardware/bluetooth/audio/2.1/types.h>
+#include <bluetooth/log.h>
#include <fmq/MessageQueue.h>
#include <hardware/audio.h>
#include <time.h>
@@ -294,3 +295,9 @@
} // namespace hidl
} // namespace audio
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::audio::hidl::BluetoothAudioCtrlAck>
+ : enum_formatter<bluetooth::audio::hidl::BluetoothAudioCtrlAck> {};
+} // namespace fmt
diff --git a/system/audio_hal_interface/hidl/codec_status_hidl.cc b/system/audio_hal_interface/hidl/codec_status_hidl.cc
index b79e9ff..ebc81dd 100644
--- a/system/audio_hal_interface/hidl/codec_status_hidl.cc
+++ b/system/audio_hal_interface/hidl/codec_status_hidl.cc
@@ -18,6 +18,8 @@
#include "codec_status_hidl.h"
+#include <bluetooth/log.h>
+
#include <vector>
#include "a2dp_aac_constants.h"
@@ -48,6 +50,8 @@
using ::android::hardware::bluetooth::audio::V2_0::SbcNumSubbands;
using ::android::hardware::bluetooth::audio::V2_0::SbcParameters;
+using namespace bluetooth;
+
// capabilities from BluetoothAudioSinkClientInterface::GetAudioCapabilities()
std::vector<AudioCapabilities> audio_hal_capabilities(0);
// capabilities that audio HAL supports and frameworks / Bluetooth SoC / runtime
@@ -77,12 +81,12 @@
(sbc_config.minBitpool < sbc_capability.minBitpool ||
sbc_config.maxBitpool < sbc_config.minBitpool ||
sbc_capability.maxBitpool < sbc_config.maxBitpool)) {
- LOG(WARNING) << __func__ << ": software codec=" << toString(sbc_config)
- << " capability=" << toString(sbc_capability);
+ log::warn("software codec={} capability={}", toString(sbc_config),
+ toString(sbc_capability));
return false;
}
- VLOG(1) << __func__ << ": offloading codec=" << toString(sbc_config)
- << " capability=" << toString(sbc_capability);
+ log::verbose("offloading codec={} capability={}", toString(sbc_config),
+ toString(sbc_capability));
return true;
}
@@ -102,12 +106,12 @@
(static_cast<BitsPerSample>(aac_capability.bitsPerSample &
aac_config.bitsPerSample) ==
BitsPerSample::BITS_UNKNOWN)) {
- LOG(WARNING) << __func__ << ": software codec=" << toString(aac_config)
- << " capability=" << toString(aac_capability);
+ log::warn("software codec={} capability={}", toString(aac_config),
+ toString(aac_capability));
return false;
}
- VLOG(1) << __func__ << ": offloading codec=" << toString(aac_config)
- << " capability=" << toString(aac_capability);
+ log::verbose("offloading codec={} capability={}", toString(aac_config),
+ toString(aac_capability));
return true;
}
@@ -122,12 +126,12 @@
(static_cast<BitsPerSample>(aptx_capability.bitsPerSample &
aptx_config.bitsPerSample) ==
BitsPerSample::BITS_UNKNOWN)) {
- LOG(WARNING) << __func__ << ": software codec=" << toString(aptx_config)
- << " capability=" << toString(aptx_capability);
+ log::warn("software codec={} capability={}", toString(aptx_config),
+ toString(aptx_capability));
return false;
}
- VLOG(1) << __func__ << ": offloading codec=" << toString(aptx_config)
- << " capability=" << toString(aptx_capability);
+ log::verbose("offloading codec={} capability={}", toString(aptx_config),
+ toString(aptx_capability));
return true;
}
@@ -142,12 +146,12 @@
(static_cast<BitsPerSample>(ldac_capability.bitsPerSample &
ldac_config.bitsPerSample) ==
BitsPerSample::BITS_UNKNOWN)) {
- LOG(WARNING) << __func__ << ": software codec=" << toString(ldac_config)
- << " capability=" << toString(ldac_capability);
+ log::warn("software codec={} capability={}", toString(ldac_config),
+ toString(ldac_capability));
return false;
}
- VLOG(1) << __func__ << ": offloading codec=" << toString(ldac_config)
- << " capability=" << toString(ldac_capability);
+ log::verbose("offloading codec={} capability={}", toString(ldac_config),
+ toString(ldac_capability));
return true;
}
} // namespace
@@ -229,8 +233,7 @@
auto sbc_config = codec_config->config.sbcConfig();
sbc_config.sampleRate = A2dpCodecToHalSampleRate(current_codec);
if (sbc_config.sampleRate == SampleRate::RATE_UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown SBC sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown SBC sample_rate={}", current_codec.sample_rate);
return false;
}
uint8_t channel_mode = a2dp_offload.codec_info[3] & A2DP_SBC_IE_CH_MD_MSK;
@@ -248,7 +251,7 @@
sbc_config.channelMode = SbcChannelMode::MONO;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC channel_mode=" << channel_mode;
+ log::error("Unknown SBC channel_mode={}", channel_mode);
sbc_config.channelMode = SbcChannelMode::UNKNOWN;
return false;
}
@@ -267,7 +270,7 @@
sbc_config.blockLength = SbcBlockLength::BLOCKS_16;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC block_length=" << block_length;
+ log::error("Unknown SBC block_length={}", block_length);
return false;
}
uint8_t sub_bands = a2dp_offload.codec_info[0] & A2DP_SBC_IE_SUBBAND_MSK;
@@ -279,7 +282,7 @@
sbc_config.numSubbands = SbcNumSubbands::SUBBAND_8;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC Subbands=" << sub_bands;
+ log::error("Unknown SBC Subbands={}", sub_bands);
return false;
}
uint8_t alloc_method = a2dp_offload.codec_info[0] & A2DP_SBC_IE_ALLOC_MD_MSK;
@@ -291,15 +294,14 @@
sbc_config.allocMethod = SbcAllocMethod::ALLOC_MD_L;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown SBC alloc_method=" << alloc_method;
+ log::error("Unknown SBC alloc_method={}", alloc_method);
return false;
}
sbc_config.minBitpool = a2dp_offload.codec_info[1];
sbc_config.maxBitpool = a2dp_offload.codec_info[2];
sbc_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (sbc_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
- LOG(ERROR) << __func__ << ": Unknown SBC bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown SBC bits_per_sample={}", current_codec.bits_per_sample);
return false;
}
codec_config->config.sbcConfig(sbc_config);
@@ -334,19 +336,17 @@
aac_config.objectType = AacObjectType::MPEG4_SCALABLE;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown AAC object_type=" << +object_type;
+ log::error("Unknown AAC object_type={}", object_type);
return false;
}
aac_config.sampleRate = A2dpCodecToHalSampleRate(current_codec);
if (aac_config.sampleRate == SampleRate::RATE_UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown AAC sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown AAC sample_rate={}", current_codec.sample_rate);
return false;
}
aac_config.channelMode = A2dpCodecToHalChannelMode(current_codec);
if (aac_config.channelMode == ChannelMode::UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown AAC channel_mode=" << current_codec.channel_mode;
+ log::error("Unknown AAC channel_mode={}", current_codec.channel_mode);
return false;
}
uint8_t vbr_enabled =
@@ -359,13 +359,12 @@
aac_config.variableBitRateEnabled = AacVariableBitRate::DISABLED;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown AAC VBR=" << +vbr_enabled;
+ log::error("Unknown AAC VBR={}", vbr_enabled);
return false;
}
aac_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (aac_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
- LOG(ERROR) << __func__ << ": Unknown AAC bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown AAC bits_per_sample={}", current_codec.bits_per_sample);
return false;
}
codec_config->config.aacConfig(aac_config);
@@ -391,20 +390,18 @@
auto aptx_config = codec_config->config.aptxConfig();
aptx_config.sampleRate = A2dpCodecToHalSampleRate(current_codec);
if (aptx_config.sampleRate == SampleRate::RATE_UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown aptX sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown aptX sample_rate={}", current_codec.sample_rate);
return false;
}
aptx_config.channelMode = A2dpCodecToHalChannelMode(current_codec);
if (aptx_config.channelMode == ChannelMode::UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown aptX channel_mode=" << current_codec.channel_mode;
+ log::error("Unknown aptX channel_mode={}", current_codec.channel_mode);
return false;
}
aptx_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (aptx_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
- LOG(ERROR) << __func__ << ": Unknown aptX bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown aptX bits_per_sample={}",
+ current_codec.bits_per_sample);
return false;
}
codec_config->config.aptxConfig(aptx_config);
@@ -425,8 +422,7 @@
auto ldac_config = codec_config->config.ldacConfig();
ldac_config.sampleRate = A2dpCodecToHalSampleRate(current_codec);
if (ldac_config.sampleRate == SampleRate::RATE_UNKNOWN) {
- LOG(ERROR) << __func__
- << ": Unknown LDAC sample_rate=" << current_codec.sample_rate;
+ log::error("Unknown LDAC sample_rate={}", current_codec.sample_rate);
return false;
}
switch (a2dp_offload.codec_info[7]) {
@@ -440,8 +436,7 @@
ldac_config.channelMode = LdacChannelMode::MONO;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown LDAC channel_mode="
- << a2dp_offload.codec_info[7];
+ log::error("Unknown LDAC channel_mode={}", a2dp_offload.codec_info[7]);
ldac_config.channelMode = LdacChannelMode::UNKNOWN;
return false;
}
@@ -459,14 +454,13 @@
ldac_config.qualityIndex = LdacQualityIndex::QUALITY_ABR;
break;
default:
- LOG(ERROR) << __func__ << ": Unknown LDAC QualityIndex="
- << a2dp_offload.codec_info[6];
+ log::error("Unknown LDAC QualityIndex={}", a2dp_offload.codec_info[6]);
return false;
}
ldac_config.bitsPerSample = A2dpCodecToHalBitsPerSample(current_codec);
if (ldac_config.bitsPerSample == BitsPerSample::BITS_UNKNOWN) {
- LOG(ERROR) << __func__ << ": Unknown LDAC bits_per_sample="
- << current_codec.bits_per_sample;
+ log::error("Unknown LDAC bits_per_sample={}",
+ current_codec.bits_per_sample);
return false;
}
codec_config->config.ldacConfig(ldac_config);
@@ -497,14 +491,12 @@
codec_type_masks |= CodecType::LDAC;
break;
case BTAV_A2DP_CODEC_INDEX_SOURCE_LC3:
- LOG(WARNING) << __func__
- << ": Ignore source codec_type=" << preference.codec_type
- << ", not supported";
+ log::warn("Ignore source codec_type={}, not supported",
+ preference.codec_type);
break;
case BTAV_A2DP_CODEC_INDEX_SOURCE_OPUS:
- LOG(WARNING) << __func__
- << ": Ignore source codec_type=" << preference.codec_type
- << ", not supported on HIDL";
+ log::warn("Ignore source codec_type={}, not supported on HIDL",
+ preference.codec_type);
break;
case BTAV_A2DP_CODEC_INDEX_SINK_SBC:
[[fallthrough]];
@@ -513,14 +505,12 @@
case BTAV_A2DP_CODEC_INDEX_SINK_LDAC:
[[fallthrough]];
case BTAV_A2DP_CODEC_INDEX_SINK_OPUS:
- LOG(WARNING) << __func__
- << ": Ignore sink codec_type=" << preference.codec_type;
+ log::warn("Ignore sink codec_type={}", preference.codec_type);
break;
case BTAV_A2DP_CODEC_INDEX_MAX:
[[fallthrough]];
default:
- LOG(ERROR) << __func__
- << ": Unknown codec_type=" << preference.codec_type;
+ log::error("Unknown codec_type={}", preference.codec_type);
return false;
}
}
@@ -528,12 +518,10 @@
for (auto capability : audio_hal_capabilities) {
if (static_cast<CodecType>(capability.codecCapabilities().codecType &
codec_type_masks) != CodecType::UNKNOWN) {
- LOG(INFO) << __func__
- << ": enabled offloading capability=" << toString(capability);
+ log::info("enabled offloading capability={}", toString(capability));
offloading_preference.push_back(capability);
} else {
- LOG(INFO) << __func__
- << ": disabled offloading capability=" << toString(capability);
+ log::info("disabled offloading capability={}", toString(capability));
}
}
// TODO: Bluetooth SoC and runtime property
@@ -573,12 +561,12 @@
case CodecType::UNKNOWN:
[[fallthrough]];
default:
- LOG(ERROR) << __func__ << ": Unknown codecType="
- << toString(codec_capability.codecType);
+ log::error("Unknown codecType={}",
+ toString(codec_capability.codecType));
return false;
}
}
- LOG(INFO) << __func__ << ": software codec=" << toString(codec_config);
+ log::info("software codec={}", toString(codec_config));
return false;
}
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 48abb4a..e093574 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
@@ -18,11 +18,21 @@
#include "hidl/hearing_aid_software_encoding_hidl.h"
+#include <bluetooth/log.h>
+
#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h"
#include "client_interface_hidl.h"
#include "os/log.h"
#include "osi/include/properties.h"
+namespace fmt {
+template <>
+struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
+template <>
+struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {
+};
+} // namespace fmt
+
namespace {
using ::android::hardware::bluetooth::audio::V2_0::CodecType;
@@ -36,6 +46,8 @@
using ::bluetooth::audio::hidl::SessionType_2_1;
using ::bluetooth::audio::hidl::hearing_aid::StreamCallbacks;
+using namespace bluetooth;
+
// Transport implementation for Hearing Aids
class HearingAidTransport
: public bluetooth::audio::hidl::IBluetoothSinkTransportInstance {
@@ -50,7 +62,7 @@
data_position_({}){};
BluetoothAudioCtrlAck StartRequest() override {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_resume_(true)) {
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
}
@@ -58,7 +70,7 @@
}
BluetoothAudioCtrlAck SuspendRequest() override {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
::bluetooth::audio::hidl::hearing_aid::read(p_buf, sizeof(p_buf));
@@ -69,7 +81,7 @@
}
void StopRequest() override {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
// flush
uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
@@ -80,10 +92,9 @@
bool GetPresentationPosition(uint64_t* remote_delay_report_ns,
uint64_t* total_bytes_read,
timespec* data_position) override {
- VLOG(2) << __func__ << ": data=" << total_bytes_read_
- << " byte(s), timestamp=" << data_position_.tv_sec << "."
- << data_position_.tv_nsec
- << "s, delay report=" << remote_delay_report_ms_ << " msec.";
+ log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.",
+ total_bytes_read_, data_position_.tv_sec,
+ data_position_.tv_nsec, remote_delay_report_ms_);
if (remote_delay_report_ns != nullptr) {
*remote_delay_report_ns = remote_delay_report_ms_ * 1000000u;
}
@@ -96,18 +107,17 @@
void MetadataChanged(const source_metadata_t& source_metadata) override {
auto track_count = source_metadata.track_count;
auto tracks = source_metadata.tracks;
- LOG(INFO) << __func__ << ": " << track_count << " track(s) received";
+ log::info("{} track(s) received", track_count);
while (track_count) {
- VLOG(1) << __func__ << ": usage=" << tracks->usage
- << ", content_type=" << tracks->content_type
- << ", gain=" << tracks->gain;
+ log::verbose("usage={}, content_type={}, gain={}", tracks->usage,
+ tracks->content_type, tracks->gain);
--track_count;
++tracks;
}
}
void ResetPresentationPosition() override {
- VLOG(2) << __func__ << ": called.";
+ log::verbose("called.");
remote_delay_report_ms_ = 0;
total_bytes_read_ = 0;
data_position_ = {};
@@ -121,7 +131,7 @@
}
void SetRemoteDelay(uint16_t delay_report_ms) {
- LOG(INFO) << __func__ << ": delay_report=" << delay_report_ms << " msec";
+ log::info("delay_report={} msec", delay_report_ms);
remote_delay_report_ms_ = delay_report_ms;
}
@@ -173,10 +183,10 @@
bool init(StreamCallbacks stream_cb,
bluetooth::common::MessageLoopThread* message_loop) {
- LOG(INFO) << __func__;
+ log::info("");
if (is_hal_2_0_force_disabled()) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
+ log::error("BluetoothAudio HAL is disabled");
return false;
}
@@ -185,8 +195,7 @@
new bluetooth::audio::hidl::BluetoothAudioSinkClientInterface(
hearing_aid_sink, message_loop);
if (!hearing_aid_hal_clientinterface->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Hearing Aid is invalid?!";
+ log::warn("BluetoothAudio HAL for Hearing Aid is invalid?!");
delete hearing_aid_hal_clientinterface;
hearing_aid_hal_clientinterface = nullptr;
delete hearing_aid_sink;
@@ -195,7 +204,7 @@
}
if (remote_delay_ms != 0) {
- LOG(INFO) << __func__ << ": restore DELAY " << remote_delay_ms << " ms";
+ log::info("restore DELAY {} ms", remote_delay_ms);
hearing_aid_sink->SetRemoteDelay(remote_delay_ms);
remote_delay_ms = 0;
}
@@ -204,7 +213,7 @@
}
void cleanup() {
- LOG(INFO) << __func__;
+ log::info("");
if (!is_hal_2_0_enabled()) return;
end_session();
delete hearing_aid_hal_clientinterface;
@@ -215,24 +224,24 @@
}
void start_session() {
- LOG(INFO) << __func__;
+ log::info("");
if (!is_hal_2_0_enabled()) return;
AudioConfiguration audio_config;
PcmParameters pcm_config{};
if (!HearingAidGetSelectedHalPcmConfig(&pcm_config)) {
- LOG(ERROR) << __func__ << ": cannot get PCM config";
+ log::error("cannot get PCM config");
return;
}
audio_config.pcmConfig(pcm_config);
if (!hearing_aid_hal_clientinterface->UpdateAudioConfig(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
hearing_aid_hal_clientinterface->StartSession();
}
void end_session() {
- LOG(INFO) << __func__;
+ log::info("");
if (!is_hal_2_0_enabled()) return;
hearing_aid_hal_clientinterface->EndSession();
}
@@ -245,12 +254,11 @@
// Update Hearing Aids delay report to BluetoothAudio HAL
void set_remote_delay(uint16_t delay_report_ms) {
if (!is_hal_2_0_enabled()) {
- LOG(INFO) << __func__ << ": not ready for DelayReport " << delay_report_ms
- << " ms";
+ log::info("not ready for DelayReport {} ms", delay_report_ms);
remote_delay_ms = delay_report_ms;
return;
}
- LOG(INFO) << __func__ << ": delay_report_ms=" << delay_report_ms << " ms";
+ log::info("delay_report_ms={} ms", delay_report_ms);
hearing_aid_sink->SetRemoteDelay(delay_report_ms);
}
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 f4f1c29..a03bcaf 100644
--- a/system/audio_hal_interface/hidl/le_audio_software_hidl.cc
+++ b/system/audio_hal_interface/hidl/le_audio_software_hidl.cc
@@ -19,6 +19,8 @@
#include "le_audio_software_hidl.h"
+#include <bluetooth/log.h>
+
#include "os/log.h"
namespace bluetooth {
@@ -113,23 +115,23 @@
SetStartRequestState(StartRequestState::PENDING_BEFORE_RESUME);
if (stream_cb_.on_resume_(true)) {
if (start_request_state_ == StartRequestState::CONFIRMED) {
- LOG_INFO("Start completed.");
+ log::info("Start completed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
}
if (start_request_state_ == StartRequestState::CANCELED) {
- LOG_INFO("Start request failed.");
+ log::info("Start request failed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::FAILURE;
}
- LOG_INFO("Start pending.");
+ log::info("Start pending.");
SetStartRequestState(StartRequestState::PENDING_AFTER_RESUME);
return BluetoothAudioCtrlAck::PENDING;
}
- LOG_ERROR("Start request failed.");
+ log::error("Start request failed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::FAILURE;
}
@@ -139,29 +141,29 @@
if (stream_cb_.on_resume_(true)) {
std::lock_guard<std::mutex> guard(start_request_state_mutex_);
if (start_request_state_ == StartRequestState::CONFIRMED) {
- LOG_INFO("Start completed.");
+ log::info("Start completed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
}
if (start_request_state_ == StartRequestState::CANCELED) {
- LOG_INFO("Start request failed.");
+ log::info("Start request failed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::FAILURE;
}
- LOG_INFO("Start pending.");
+ log::info("Start pending.");
SetStartRequestState(StartRequestState::PENDING_AFTER_RESUME);
return BluetoothAudioCtrlAck::PENDING;
}
- LOG_ERROR("Start request failed.");
+ log::error("Start request failed.");
SetStartRequestState(StartRequestState::IDLE);
return BluetoothAudioCtrlAck::FAILURE;
}
BluetoothAudioCtrlAck LeAudioTransport::SuspendRequest() {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
flush_();
return BluetoothAudioCtrlAck::SUCCESS_FINISHED;
@@ -171,7 +173,7 @@
}
void LeAudioTransport::StopRequest() {
- LOG(INFO) << __func__;
+ log::info("");
if (stream_cb_.on_suspend_()) {
flush_();
}
@@ -180,10 +182,9 @@
bool LeAudioTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns,
uint64_t* total_bytes_processed,
timespec* data_position) {
- VLOG(2) << __func__ << ": data=" << total_bytes_processed_
- << " byte(s), timestamp=" << data_position_.tv_sec << "."
- << data_position_.tv_nsec
- << "s, delay report=" << remote_delay_report_ms_ << " msec.";
+ log::verbose("data={} byte(s), timestamp={}.{}s, delay report={} msec.",
+ total_bytes_processed_, data_position_.tv_sec,
+ data_position_.tv_nsec, remote_delay_report_ms_);
if (remote_delay_report_ns != nullptr) {
*remote_delay_report_ns = remote_delay_report_ms_ * 1000000u;
}
@@ -199,7 +200,7 @@
auto track_count = source_metadata.track_count;
if (track_count == 0) {
- LOG(WARNING) << ", invalid number of metadata changed tracks";
+ log::warn(", invalid number of metadata changed tracks");
return;
}
std::vector<playback_track_metadata_v7> tracks_vec;
@@ -221,7 +222,7 @@
}
void LeAudioTransport::ResetPresentationPosition() {
- VLOG(2) << __func__ << ": called.";
+ log::verbose("called.");
remote_delay_report_ms_ = 0;
total_bytes_processed_ = 0;
data_position_ = {};
@@ -235,7 +236,7 @@
}
void LeAudioTransport::SetRemoteDelay(uint16_t delay_report_ms) {
- LOG(INFO) << __func__ << ": delay_report=" << delay_report_ms << " msec";
+ log::info("delay_report={} msec", delay_report_ms);
remote_delay_report_ms_ = delay_report_ms;
}
@@ -264,9 +265,9 @@
}
auto ret = std::get<1>(result);
- LOG_VERBOSE("new state: %d, return: %s",
- static_cast<int>(start_request_state_.load()),
- ret ? "true" : "false");
+ log::verbose("new state: {}, return: {}",
+ static_cast<int>(start_request_state_.load()),
+ ret ? "true" : "false");
return ret;
}
diff --git a/system/audio_hal_interface/le_audio_software.cc b/system/audio_hal_interface/le_audio_software.cc
index d801600..98e8fce 100644
--- a/system/audio_hal_interface/le_audio_software.cc
+++ b/system/audio_hal_interface/le_audio_software.cc
@@ -20,6 +20,7 @@
#include "le_audio_software.h"
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
#include <unordered_map>
#include <vector>
@@ -89,7 +90,7 @@
LeAudioClientInterface* LeAudioClientInterface::interface = nullptr;
LeAudioClientInterface* LeAudioClientInterface::Get() {
if (osi_property_get_bool(BLUETOOTH_AUDIO_HAL_PROP_DISABLED, false)) {
- LOG(ERROR) << __func__ << ": BluetoothAudio HAL is disabled";
+ log::error("BluetoothAudio HAL is disabled");
return nullptr;
}
@@ -100,7 +101,7 @@
}
void LeAudioClientInterface::Sink::Cleanup() {
- LOG_INFO("HAL transport: 0x%02x, is broadcast: %d",
+ log::info("HAL transport: 0x{:02x}, is broadcast: {}",
static_cast<int>(HalVersionManager::GetHalTransport()),
is_broadcaster_);
@@ -139,8 +140,8 @@
}
}
} else {
- LOG_ERROR("Invalid HAL transport: 0x%02x",
- static_cast<int>(HalVersionManager::GetHalTransport()));
+ log::error("Invalid HAL transport: 0x{:02x}",
+ static_cast<int>(HalVersionManager::GetHalTransport()));
}
}
@@ -161,7 +162,7 @@
// Update Le Audio delay report to BluetoothAudio HAL
void LeAudioClientInterface::Sink::SetRemoteDelay(uint16_t delay_report_ms) {
- LOG(INFO) << __func__ << ": delay_report_ms=" << delay_report_ms << " ms";
+ log::info("delay_report_ms={} ms", delay_report_ms);
if (HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
hidl::le_audio::LeAudioSinkTransport::instance->SetRemoteDelay(
@@ -172,7 +173,7 @@
}
void LeAudioClientInterface::Sink::StartSession() {
- LOG(INFO) << __func__;
+ log::info("");
if (HalVersionManager::GetHalVersion() ==
BluetoothAudioHalVersion::VERSION_2_1) {
AudioConfiguration_2_1 audio_config;
@@ -180,7 +181,7 @@
->LeAudioGetSelectedHalPcmConfig());
if (!hidl::le_audio::LeAudioSinkTransport::interface->UpdateAudioConfig_2_1(
audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
hidl::le_audio::LeAudioSinkTransport::interface->StartSession_2_1();
@@ -205,7 +206,7 @@
}
if (!get_aidl_client_interface(is_broadcaster_)
->UpdateAudioConfig(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
get_aidl_client_interface(is_broadcaster_)->StartSession();
@@ -220,21 +221,21 @@
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
hidl_instance->SetStartRequestState(StartRequestState::CONFIRMED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
hidl_instance->ClearStartRequestState();
hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted(
hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return;
}
}
@@ -243,21 +244,21 @@
auto start_request_state = aidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
aidl_instance->SetStartRequestState(StartRequestState::CONFIRMED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
aidl_instance->ClearStartRequestState();
get_aidl_client_interface(is_broadcaster_)
->StreamStarted(aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return;
}
}
@@ -267,17 +268,17 @@
-> std::pair<StartRequestState, bool> {
switch (currect_start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return std::make_pair(StartRequestState::IDLE, false);
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
return std::make_pair(StartRequestState::CONFIRMED, false);
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
return std::make_pair(StartRequestState::IDLE, true);
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return std::make_pair(currect_start_request_state, false);
}
};
@@ -307,21 +308,21 @@
auto start_request_state = hidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
hidl_instance->SetStartRequestState(StartRequestState::CANCELED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
hidl_instance->ClearStartRequestState();
hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted(
hidl::BluetoothAudioCtrlAck::FAILURE);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
break;
}
}
@@ -330,21 +331,21 @@
auto start_request_state = aidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
aidl_instance->SetStartRequestState(StartRequestState::CANCELED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
aidl_instance->ClearStartRequestState();
get_aidl_client_interface(is_broadcaster_)
->StreamStarted(aidl::BluetoothAudioCtrlAck::FAILURE);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
break;
}
}
@@ -356,21 +357,21 @@
auto start_request_state = hidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
hidl_instance->SetStartRequestState(StartRequestState::CANCELED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
hidl_instance->ClearStartRequestState();
hidl::le_audio::LeAudioSinkTransport::interface->StreamStarted(
hidl::BluetoothAudioCtrlAck::FAILURE);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
break;
}
}
@@ -379,27 +380,27 @@
auto start_request_state = aidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
aidl_instance->SetStartRequestState(StartRequestState::CANCELED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
aidl_instance->ClearStartRequestState();
get_aidl_client_interface(is_broadcaster_)
->StreamStarted(aidl::BluetoothAudioCtrlAck::FAILURE);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
break;
}
}
void LeAudioClientInterface::Sink::StopSession() {
- LOG(INFO) << __func__ << " sink";
+ log::info("sink");
if (HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
hidl::le_audio::LeAudioSinkTransport::instance->ClearStartRequestState();
@@ -475,7 +476,7 @@
}
void LeAudioClientInterface::Source::Cleanup() {
- LOG(INFO) << __func__ << " source";
+ log::info("source");
StopSession();
if (hidl::le_audio::LeAudioSourceTransport::interface) {
delete hidl::le_audio::LeAudioSourceTransport::interface;
@@ -512,7 +513,7 @@
}
void LeAudioClientInterface::Source::SetRemoteDelay(uint16_t delay_report_ms) {
- LOG(INFO) << __func__ << ": delay_report_ms=" << delay_report_ms << " ms";
+ log::info("delay_report_ms={} ms", delay_report_ms);
if (HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
hidl::le_audio::LeAudioSourceTransport::instance->SetRemoteDelay(
@@ -524,7 +525,7 @@
}
void LeAudioClientInterface::Source::StartSession() {
- LOG(INFO) << __func__;
+ log::info("");
if (HalVersionManager::GetHalVersion() ==
BluetoothAudioHalVersion::VERSION_2_1) {
AudioConfiguration_2_1 audio_config;
@@ -532,7 +533,7 @@
->LeAudioGetSelectedHalPcmConfig());
if (!hidl::le_audio::LeAudioSourceTransport::
interface->UpdateAudioConfig_2_1(audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
hidl::le_audio::LeAudioSourceTransport::interface->StartSession_2_1();
@@ -555,7 +556,7 @@
if (!aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig(
audio_config)) {
- LOG(ERROR) << __func__ << ": cannot update audio config to HAL";
+ log::error("cannot update audio config to HAL");
return;
}
aidl::le_audio::LeAudioSourceTransport::interface->StartSession();
@@ -594,21 +595,21 @@
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
hidl_instance->SetStartRequestState(StartRequestState::CONFIRMED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
hidl_instance->ClearStartRequestState();
hidl::le_audio::LeAudioSourceTransport::interface->StreamStarted(
hidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return;
}
}
@@ -617,21 +618,21 @@
auto start_request_state = aidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
aidl_instance->SetStartRequestState(StartRequestState::CONFIRMED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
aidl_instance->ClearStartRequestState();
aidl::le_audio::LeAudioSourceTransport::interface->StreamStarted(
aidl::BluetoothAudioCtrlAck::SUCCESS_FINISHED);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return;
}
}
@@ -641,17 +642,17 @@
-> std::pair<StartRequestState, bool> {
switch (currect_start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return std::make_pair(StartRequestState::IDLE, false);
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
return std::make_pair(StartRequestState::CONFIRMED, false);
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
return std::make_pair(StartRequestState::IDLE, true);
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return std::make_pair(currect_start_request_state, false);
}
};
@@ -681,21 +682,21 @@
auto start_request_state = hidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
hidl_instance->SetStartRequestState(StartRequestState::CANCELED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
hidl_instance->ClearStartRequestState();
hidl::le_audio::LeAudioSourceTransport::interface->StreamStarted(
hidl::BluetoothAudioCtrlAck::FAILURE);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
break;
}
}
@@ -704,21 +705,21 @@
auto start_request_state = aidl_instance->GetStartRequestState();
switch (start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return;
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
aidl_instance->SetStartRequestState(StartRequestState::CANCELED);
return;
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
aidl_instance->ClearStartRequestState();
aidl::le_audio::LeAudioSourceTransport::interface->StreamStarted(
aidl::BluetoothAudioCtrlAck::FAILURE);
return;
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
break;
}
}
@@ -728,17 +729,17 @@
-> std::pair<StartRequestState, bool> {
switch (currect_start_request_state) {
case StartRequestState::IDLE:
- LOG_WARN(", no pending start stream request");
+ log::warn(", no pending start stream request");
return std::make_pair(StartRequestState::IDLE, false);
case StartRequestState::PENDING_BEFORE_RESUME:
- LOG_INFO("Response before sending PENDING to audio HAL");
+ log::info("Response before sending PENDING to audio HAL");
return std::make_pair(StartRequestState::CANCELED, false);
case StartRequestState::PENDING_AFTER_RESUME:
- LOG_INFO("Response after sending PENDING to audio HAL");
+ log::info("Response after sending PENDING to audio HAL");
return std::make_pair(StartRequestState::IDLE, true);
case StartRequestState::CONFIRMED:
case StartRequestState::CANCELED:
- LOG_ERROR("Invalid state, start stream already confirmed");
+ log::error("Invalid state, start stream already confirmed");
return std::make_pair(currect_start_request_state, false);
}
};
@@ -761,7 +762,7 @@
}
void LeAudioClientInterface::Source::StopSession() {
- LOG(INFO) << __func__ << " source";
+ log::info("source");
if (HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
hidl::le_audio::LeAudioSourceTransport::instance->ClearStartRequestState();
@@ -805,8 +806,7 @@
bool is_broadcasting_session_type) {
if (is_broadcasting_session_type && HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
- LOG(WARNING) << __func__
- << ", No support for broadcasting Le Audio on HIDL";
+ log::warn("No support for broadcasting Le Audio on HIDL");
return nullptr;
}
@@ -814,11 +814,11 @@
if (sink == nullptr) {
sink = new Sink(is_broadcasting_session_type);
} else {
- LOG(WARNING) << __func__ << ", Sink is already acquired";
+ log::warn("Sink is already acquired");
return nullptr;
}
- LOG(INFO) << __func__;
+ log::info("");
if (HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
@@ -832,8 +832,7 @@
new hidl::BluetoothAudioSinkClientInterface(
hidl::le_audio::LeAudioSinkTransport::instance, message_loop);
if (!hidl::le_audio::LeAudioSinkTransport::interface->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Le Audio is invalid?!";
+ log::warn("BluetoothAudio HAL for Le Audio is invalid?!");
delete hidl::le_audio::LeAudioSinkTransport::interface;
hidl::le_audio::LeAudioSinkTransport::interface = nullptr;
delete hidl::le_audio::LeAudioSinkTransport::instance;
@@ -869,8 +868,7 @@
aidl::le_audio::LeAudioSinkTransport::instance_unicast_);
if (!aidl::le_audio::LeAudioSinkTransport::interface_unicast_
->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Le Audio is invalid?!";
+ log::warn("BluetoothAudio HAL for Le Audio is invalid?!");
delete aidl::le_audio::LeAudioSinkTransport::interface_unicast_;
aidl::le_audio::LeAudioSinkTransport::interface_unicast_ = nullptr;
delete aidl::le_audio::LeAudioSinkTransport::instance_unicast_;
@@ -889,8 +887,7 @@
aidl::le_audio::LeAudioSinkTransport::instance_broadcast_);
if (!aidl::le_audio::LeAudioSinkTransport::interface_broadcast_
->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Le Audio is invalid?!";
+ log::warn("BluetoothAudio HAL for Le Audio is invalid?!");
delete aidl::le_audio::LeAudioSinkTransport::interface_broadcast_;
aidl::le_audio::LeAudioSinkTransport::interface_broadcast_ = nullptr;
delete aidl::le_audio::LeAudioSinkTransport::instance_broadcast_;
@@ -915,7 +912,7 @@
bool LeAudioClientInterface::ReleaseSink(LeAudioClientInterface::Sink* sink) {
if (sink != unicast_sink_ && sink != broadcast_sink_) {
- LOG(WARNING) << __func__ << ", can't release not acquired sink";
+ log::warn("can't release not acquired sink");
return false;
}
@@ -944,11 +941,11 @@
if (source_ == nullptr) {
source_ = new Source();
} else {
- LOG(WARNING) << __func__ << ", Source is already acquired";
+ log::warn("Source is already acquired");
return nullptr;
}
- LOG(INFO) << __func__;
+ log::info("");
if (HalVersionManager::GetHalTransport() ==
BluetoothAudioHalTransport::HIDL) {
@@ -967,8 +964,7 @@
new hidl::BluetoothAudioSourceClientInterface(
hidl::le_audio::LeAudioSourceTransport::instance, message_loop);
if (!hidl::le_audio::LeAudioSourceTransport::interface->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Le Audio is invalid?!";
+ log::warn("BluetoothAudio HAL for Le Audio is invalid?!");
delete hidl::le_audio::LeAudioSourceTransport::interface;
hidl::le_audio::LeAudioSourceTransport::interface = nullptr;
delete hidl::le_audio::LeAudioSourceTransport::instance;
@@ -994,8 +990,7 @@
new aidl::BluetoothAudioSourceClientInterface(
aidl::le_audio::LeAudioSourceTransport::instance);
if (!aidl::le_audio::LeAudioSourceTransport::interface->IsValid()) {
- LOG(WARNING) << __func__
- << ": BluetoothAudio HAL for Le Audio is invalid?!";
+ log::warn("BluetoothAudio HAL for Le Audio is invalid?!");
delete aidl::le_audio::LeAudioSourceTransport::interface;
aidl::le_audio::LeAudioSourceTransport::interface = nullptr;
delete aidl::le_audio::LeAudioSourceTransport::instance;
@@ -1015,7 +1010,7 @@
bool LeAudioClientInterface::ReleaseSource(
LeAudioClientInterface::Source* source) {
if (source != source_) {
- LOG(WARNING) << __func__ << ", can't release not acquired source";
+ log::warn("can't release not acquired source");
return false;
}
@@ -1040,7 +1035,7 @@
BluetoothAudioHalTransport::AIDL) {
if (aidl::le_audio::LeAudioSinkTransport::interface_unicast_ == nullptr ||
aidl::le_audio::LeAudioSinkTransport::instance_unicast_ == nullptr) {
- LOG(WARNING) << __func__ << ": LeAudioSourceTransport::interface is null";
+ log::warn("LeAudioSourceTransport::interface is null");
return;
}
@@ -1060,7 +1055,7 @@
latency_modes.push_back(LatencyMode::DYNAMIC_SPATIAL_AUDIO_HARDWARE);
break;
default:
- LOG(WARNING) << "Unsupported latency mode ignored: " << (int)dsa_mode;
+ log::warn("Unsupported latency mode ignored: {}", (int)dsa_mode);
break;
}
}
diff --git a/system/blueberry/tests/gd/cert/captures.py b/system/blueberry/tests/gd/cert/captures.py
index 94e5b9d..104f8df 100644
--- a/system/blueberry/tests/gd/cert/captures.py
+++ b/system/blueberry/tests/gd/cert/captures.py
@@ -14,12 +14,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import bluetooth_packets_python3 as bt_packets
-from bluetooth_packets_python3 import l2cap_packets
-from bluetooth_packets_python3.l2cap_packets import CommandCode, LeCommandCode
from blueberry.tests.gd.cert.capture import Capture
from blueberry.tests.gd.cert.matchers import HciMatchers
-from blueberry.tests.gd.cert.matchers import L2capMatchers
from blueberry.tests.gd.cert.matchers import SecurityMatchers
from blueberry.facade.security.facade_pb2 import UiMsgType
import hci_packets as hci
@@ -99,64 +95,6 @@
lambda packet: hci.Event.parse_all(packet.payload))
-class L2capCaptures(object):
-
- @staticmethod
- def ConnectionRequest(psm):
- return Capture(L2capMatchers.ConnectionRequest(psm), L2capCaptures._extract_connection_request)
-
- @staticmethod
- def _extract_connection_request(packet):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_REQUEST)
- return l2cap_packets.ConnectionRequestView(frame)
-
- @staticmethod
- def ConnectionResponse(scid):
- return Capture(L2capMatchers.ConnectionResponse(scid), L2capCaptures._extract_connection_response)
-
- @staticmethod
- def _extract_connection_response(packet):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_RESPONSE)
- return l2cap_packets.ConnectionResponseView(frame)
-
- @staticmethod
- def ConfigurationRequest(cid=None):
- return Capture(L2capMatchers.ConfigurationRequest(cid), L2capCaptures._extract_configuration_request)
-
- @staticmethod
- def _extract_configuration_request(packet):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_REQUEST)
- return l2cap_packets.ConfigurationRequestView(frame)
-
- @staticmethod
- def CreditBasedConnectionRequest(psm):
- return Capture(L2capMatchers.CreditBasedConnectionRequest(psm),
- L2capCaptures._extract_credit_based_connection_request)
-
- @staticmethod
- def _extract_credit_based_connection_request(packet):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_REQUEST)
- return l2cap_packets.LeCreditBasedConnectionRequestView(frame)
-
- @staticmethod
- def CreditBasedConnectionResponse():
- return Capture(L2capMatchers.CreditBasedConnectionResponse(),
- L2capCaptures._extract_credit_based_connection_response)
-
- @staticmethod
- def _extract_credit_based_connection_response(packet):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_RESPONSE)
- return l2cap_packets.LeCreditBasedConnectionResponseView(frame)
-
- @staticmethod
- def LinkSecurityInterfaceCallbackEvent(type):
- return Capture(L2capMatchers.LinkSecurityInterfaceCallbackEvent(type), L2capCaptures._extract_address)
-
- @staticmethod
- def _extract_address(packet):
- return packet.address
-
-
class SecurityCaptures(object):
@staticmethod
diff --git a/system/blueberry/tests/gd/cert/cert_self_test.py b/system/blueberry/tests/gd/cert/cert_self_test.py
index 1ff40c7..5ccd8f9 100644
--- a/system/blueberry/tests/gd/cert/cert_self_test.py
+++ b/system/blueberry/tests/gd/cert/cert_self_test.py
@@ -28,7 +28,6 @@
from blueberry.tests.gd.cert.event_stream import EventStream, FilteringEventStream
from blueberry.tests.gd.cert.metadata import metadata
from blueberry.tests.gd.cert.truth import assertThat
-from bluetooth_packets_python3 import l2cap_packets
import hci_packets as hci
from mobly import asserts
@@ -192,25 +191,6 @@
logging.debug(outside.serialize())
logging.debug("Done!")
- def test_l2cap_config_options(self):
- mtu_opt = l2cap_packets.MtuConfigurationOption()
- mtu_opt.mtu = 123
- fcs_opt = l2cap_packets.FrameCheckSequenceOption()
- fcs_opt.fcs_type = l2cap_packets.FcsType.DEFAULT
- request = l2cap_packets.ConfigurationRequestBuilder(
- 0x1d, # Command ID
- 0xc1d, # Channel ID
- l2cap_packets.Continuation.END,
- [mtu_opt, fcs_opt])
- request_b_frame = l2cap_packets.BasicFrameBuilder(0x01, request)
- handle = 123
- wrapped = hci.Acl(handle=handle,
- packet_boundary_flag=hci.PacketBoundaryFlag.FIRST_NON_AUTOMATICALLY_FLUSHABLE,
- broadcast_flag=hci.BroadcastFlag.POINT_TO_POINT,
- payload=bytes(request_b_frame.Serialize()))
- # Size is ACL (4) + L2CAP (4) + Configure (8) + MTU (4) + FCS (3)
- asserts.assert_true(len(wrapped.serialize()) == 23, "Packet serialized incorrectly")
-
def test_assertThat_boolean_success(self):
assertThat(True).isTrue()
assertThat(False).isFalse()
diff --git a/system/blueberry/tests/gd/cert/matchers.py b/system/blueberry/tests/gd/cert/matchers.py
index e438b7b..780fe2b 100644
--- a/system/blueberry/tests/gd/cert/matchers.py
+++ b/system/blueberry/tests/gd/cert/matchers.py
@@ -14,17 +14,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import bluetooth_packets_python3 as bt_packets
import logging
import sys
-from bluetooth_packets_python3 import l2cap_packets
-from bluetooth_packets_python3.l2cap_packets import CommandCode, LeCommandCode
-from bluetooth_packets_python3.l2cap_packets import ConfigurationResponseResult
-from bluetooth_packets_python3.l2cap_packets import ConnectionResponseResult
-from bluetooth_packets_python3.l2cap_packets import InformationRequestInfoType
-from bluetooth_packets_python3.l2cap_packets import LeCreditBasedConnectionResponseResult
-
from blueberry.utils import bluetooth
import hci_packets as hci
@@ -274,454 +266,6 @@
return bluetooth.Address(address) == event.address
-class L2capMatchers(object):
-
- @staticmethod
- def ConnectionRequest(psm):
- return lambda packet: L2capMatchers._is_matching_connection_request(packet, psm)
-
- @staticmethod
- def ConnectionResponse(scid):
- return lambda packet: L2capMatchers._is_matching_connection_response(packet, scid)
-
- @staticmethod
- def ConfigurationResponse(result=ConfigurationResponseResult.SUCCESS):
- return lambda packet: L2capMatchers._is_matching_configuration_response(packet, result)
-
- @staticmethod
- def ConfigurationRequest(cid=None):
- return lambda packet: L2capMatchers._is_matching_configuration_request_with_cid(packet, cid)
-
- @staticmethod
- def ConfigurationRequestWithErtm():
- return lambda packet: L2capMatchers._is_matching_configuration_request_with_ertm(packet)
-
- @staticmethod
- def ConfigurationRequestView(dcid):
- return lambda request_view: request_view.GetDestinationCid() == dcid
-
- @staticmethod
- def DisconnectionRequest(scid, dcid):
- return lambda packet: L2capMatchers._is_matching_disconnection_request(packet, scid, dcid)
-
- @staticmethod
- def DisconnectionResponse(scid, dcid):
- return lambda packet: L2capMatchers._is_matching_disconnection_response(packet, scid, dcid)
-
- @staticmethod
- def EchoResponse():
- return lambda packet: L2capMatchers._is_control_frame_with_code(packet, CommandCode.ECHO_RESPONSE)
-
- @staticmethod
- def CommandReject():
- return lambda packet: L2capMatchers._is_control_frame_with_code(packet, CommandCode.COMMAND_REJECT)
-
- @staticmethod
- def LeCommandReject():
- return lambda packet: L2capMatchers._is_le_control_frame_with_code(packet, LeCommandCode.COMMAND_REJECT)
-
- @staticmethod
- def LeConnectionParameterUpdateRequest():
- return lambda packet: L2capMatchers._is_le_control_frame_with_code(
- packet, LeCommandCode.CONNECTION_PARAMETER_UPDATE_REQUEST)
-
- @staticmethod
- def LeConnectionParameterUpdateResponse(result=l2cap_packets.ConnectionParameterUpdateResponseResult.ACCEPTED):
- return lambda packet: L2capMatchers._is_matching_connection_parameter_update_response(packet, result)
-
- @staticmethod
- def CreditBasedConnectionRequest(psm):
- return lambda packet: L2capMatchers._is_matching_credit_based_connection_request(packet, psm)
-
- @staticmethod
- def CreditBasedConnectionResponse(result=LeCreditBasedConnectionResponseResult.SUCCESS):
- return lambda packet: L2capMatchers._is_matching_credit_based_connection_response(packet, result)
-
- @staticmethod
- def CreditBasedConnectionResponseUsedCid():
- return lambda packet: L2capMatchers._is_matching_credit_based_connection_response(
- packet, LeCreditBasedConnectionResponseResult.SOURCE_CID_ALREADY_ALLOCATED
- ) or L2capMatchers._is_le_control_frame_with_code(packet, LeCommandCode.COMMAND_REJECT)
-
- @staticmethod
- def LeDisconnectionRequest(scid, dcid):
- return lambda packet: L2capMatchers._is_matching_le_disconnection_request(packet, scid, dcid)
-
- @staticmethod
- def LeDisconnectionResponse(scid, dcid):
- return lambda packet: L2capMatchers._is_matching_le_disconnection_response(packet, scid, dcid)
-
- @staticmethod
- def LeFlowControlCredit(cid):
- return lambda packet: L2capMatchers._is_matching_le_flow_control_credit(packet, cid)
-
- @staticmethod
- def SFrame(req_seq=None, f=None, s=None, p=None):
- return lambda packet: L2capMatchers._is_matching_supervisory_frame(packet, req_seq, f, s, p)
-
- @staticmethod
- def IFrame(tx_seq=None, payload=None, f=None):
- return lambda packet: L2capMatchers._is_matching_information_frame(packet, tx_seq, payload, f, fcs=False)
-
- @staticmethod
- def IFrameWithFcs(tx_seq=None, payload=None, f=None):
- return lambda packet: L2capMatchers._is_matching_information_frame(packet, tx_seq, payload, f, fcs=True)
-
- @staticmethod
- def IFrameStart(tx_seq=None, payload=None, f=None):
- return lambda packet: L2capMatchers._is_matching_information_start_frame(packet, tx_seq, payload, f, fcs=False)
-
- @staticmethod
- def Data(payload):
- return lambda packet: packet.GetPayload().GetBytes() == payload
-
- @staticmethod
- def FirstLeIFrame(payload, sdu_size):
- return lambda packet: L2capMatchers._is_matching_first_le_i_frame(packet, payload, sdu_size)
-
- # this is a hack - should be removed
- @staticmethod
- def PartialData(payload):
- return lambda packet: payload in packet.GetPayload().GetBytes()
-
- # this is a hack - should be removed
- @staticmethod
- def PacketPayloadRawData(payload):
- return lambda packet: payload in packet.payload
-
- # this is a hack - should be removed
- @staticmethod
- def PacketPayloadWithMatchingPsm(psm):
- return lambda packet: None if psm != packet.psm else packet
-
- # this is a hack - should be removed
- @staticmethod
- def PacketPayloadWithMatchingCid(cid):
- return lambda packet: None if cid != packet.fixed_cid else packet
-
- @staticmethod
- def ExtractBasicFrame(scid):
- return lambda packet: L2capMatchers._basic_frame_for(packet, scid)
-
- @staticmethod
- def ExtractBasicFrameWithFcs(scid):
- return lambda packet: L2capMatchers._basic_frame_with_fcs_for(packet, scid)
-
- @staticmethod
- def InformationRequestWithType(info_type):
- return lambda packet: L2capMatchers._information_request_with_type(packet, info_type)
-
- @staticmethod
- def InformationResponseExtendedFeatures(supports_ertm=None,
- supports_streaming=None,
- supports_fcs=None,
- supports_fixed_channels=None):
- return lambda packet: L2capMatchers._is_matching_information_response_extended_features(
- packet, supports_ertm, supports_streaming, supports_fcs, supports_fixed_channels)
-
- @staticmethod
- def _basic_frame(packet):
- if packet is None:
- return None
- return l2cap_packets.BasicFrameView(bt_packets.PacketViewLittleEndian(list(packet.payload)))
-
- @staticmethod
- def _basic_frame_with_fcs(packet):
- if packet is None:
- return None
- return l2cap_packets.BasicFrameWithFcsView(bt_packets.PacketViewLittleEndian(list(packet.payload)))
-
- @staticmethod
- def _basic_frame_for(packet, scid):
- frame = L2capMatchers._basic_frame(packet)
- if frame.GetChannelId() != scid:
- return None
- return frame
-
- @staticmethod
- def _basic_frame_with_fcs_for(packet, scid):
- frame = L2capMatchers._basic_frame(packet)
- if frame.GetChannelId() != scid:
- return None
- frame = L2capMatchers._basic_frame_with_fcs(packet)
- if frame is None:
- return None
- return frame
-
- @staticmethod
- def _information_frame(packet):
- standard_frame = l2cap_packets.StandardFrameView(packet)
- if standard_frame.GetFrameType() != l2cap_packets.FrameType.I_FRAME:
- return None
- return l2cap_packets.EnhancedInformationFrameView(standard_frame)
-
- @staticmethod
- def _information_frame_with_fcs(packet):
- standard_frame = l2cap_packets.StandardFrameWithFcsView(packet)
- if standard_frame is None:
- return None
- if standard_frame.GetFrameType() != l2cap_packets.FrameType.I_FRAME:
- return None
- return l2cap_packets.EnhancedInformationFrameWithFcsView(standard_frame)
-
- @staticmethod
- def _information_start_frame(packet):
- start_frame = L2capMatchers._information_frame(packet)
- if start_frame is None:
- return None
- return l2cap_packets.EnhancedInformationStartFrameView(start_frame)
-
- @staticmethod
- def _information_start_frame_with_fcs(packet):
- start_frame = L2capMatchers._information_frame_with_fcs(packet)
- if start_frame is None:
- return None
- return l2cap_packets.EnhancedInformationStartFrameWithFcsView(start_frame)
-
- @staticmethod
- def _supervisory_frame(packet):
- standard_frame = l2cap_packets.StandardFrameView(packet)
- if standard_frame.GetFrameType() != l2cap_packets.FrameType.S_FRAME:
- return None
- return l2cap_packets.EnhancedSupervisoryFrameView(standard_frame)
-
- @staticmethod
- def _is_matching_information_frame(packet, tx_seq, payload, f, fcs=False):
- if fcs:
- frame = L2capMatchers._information_frame_with_fcs(packet)
- else:
- frame = L2capMatchers._information_frame(packet)
- if frame is None:
- return False
- if tx_seq is not None and frame.GetTxSeq() != tx_seq:
- return False
- if payload is not None and frame.GetPayload().GetBytes() != payload:
- return False
- if f is not None and frame.GetF() != f:
- return False
- return True
-
- @staticmethod
- def _is_matching_information_start_frame(packet, tx_seq, payload, f, fcs=False):
- if fcs:
- frame = L2capMatchers._information_start_frame_with_fcs(packet)
- else:
- frame = L2capMatchers._information_start_frame(packet)
- if frame is None:
- return False
- if tx_seq is not None and frame.GetTxSeq() != tx_seq:
- return False
- if payload is not None and frame.GetPayload().GetBytes() != payload:
- return False
- if f is not None and frame.GetF() != f:
- return False
- return True
-
- @staticmethod
- def _is_matching_supervisory_frame(packet, req_seq, f, s, p):
- frame = L2capMatchers._supervisory_frame(packet)
- if frame is None:
- return False
- if req_seq is not None and frame.GetReqSeq() != req_seq:
- return False
- if f is not None and frame.GetF() != f:
- return False
- if s is not None and frame.GetS() != s:
- return False
- if p is not None and frame.GetP() != p:
- return False
- return True
-
- @staticmethod
- def _is_matching_first_le_i_frame(packet, payload, sdu_size):
- first_le_i_frame = l2cap_packets.FirstLeInformationFrameView(packet)
- return first_le_i_frame.GetPayload().GetBytes() == payload and first_le_i_frame.GetL2capSduLength() == sdu_size
-
- @staticmethod
- def _control_frame(packet):
- if packet.GetChannelId() != 1:
- return None
- return l2cap_packets.ControlView(packet.GetPayload())
-
- @staticmethod
- def _le_control_frame(packet):
- if packet.GetChannelId() != 5:
- return None
- return l2cap_packets.LeControlView(packet.GetPayload())
-
- @staticmethod
- def control_frame_with_code(packet, code):
- frame = L2capMatchers._control_frame(packet)
- if frame is None or frame.GetCode() != code:
- return None
- return frame
-
- @staticmethod
- def le_control_frame_with_code(packet, code):
- frame = L2capMatchers._le_control_frame(packet)
- if frame is None or frame.GetCode() != code:
- return None
- return frame
-
- @staticmethod
- def _is_control_frame_with_code(packet, code):
- return L2capMatchers.control_frame_with_code(packet, code) is not None
-
- @staticmethod
- def _is_le_control_frame_with_code(packet, code):
- return L2capMatchers.le_control_frame_with_code(packet, code) is not None
-
- @staticmethod
- def _is_matching_connection_request(packet, psm):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_REQUEST)
- if frame is None:
- return False
- request = l2cap_packets.ConnectionRequestView(frame)
- return request.GetPsm() == psm
-
- @staticmethod
- def _is_matching_connection_response(packet, scid):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONNECTION_RESPONSE)
- if frame is None:
- return False
- response = l2cap_packets.ConnectionResponseView(frame)
- return response.GetSourceCid() == scid and response.GetResult(
- ) == ConnectionResponseResult.SUCCESS and response.GetDestinationCid() != 0
-
- @staticmethod
- def _is_matching_configuration_request_with_cid(packet, cid=None):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_REQUEST)
- if frame is None:
- return False
- request = l2cap_packets.ConfigurationRequestView(frame)
- dcid = request.GetDestinationCid()
- return cid is None or cid == dcid
-
- @staticmethod
- def _is_matching_configuration_request_with_ertm(packet):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_REQUEST)
- if frame is None:
- return False
- request = l2cap_packets.ConfigurationRequestView(frame)
- config_bytes = request.GetBytes()
- # TODO(b/153189503): Use packet struct parser.
- return b"\x04\x09\x03" in config_bytes
-
- @staticmethod
- def _is_matching_configuration_response(packet, result=ConfigurationResponseResult.SUCCESS):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.CONFIGURATION_RESPONSE)
- if frame is None:
- return False
- response = l2cap_packets.ConfigurationResponseView(frame)
- return response.GetResult() == result
-
- @staticmethod
- def _is_matching_disconnection_request(packet, scid, dcid):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.DISCONNECTION_REQUEST)
- if frame is None:
- return False
- request = l2cap_packets.DisconnectionRequestView(frame)
- return request.GetSourceCid() == scid and request.GetDestinationCid() == dcid
-
- @staticmethod
- def _is_matching_disconnection_response(packet, scid, dcid):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.DISCONNECTION_RESPONSE)
- if frame is None:
- return False
- response = l2cap_packets.DisconnectionResponseView(frame)
- return response.GetSourceCid() == scid and response.GetDestinationCid() == dcid
-
- @staticmethod
- def _is_matching_le_disconnection_response(packet, scid, dcid):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.DISCONNECTION_RESPONSE)
- if frame is None:
- return False
- response = l2cap_packets.LeDisconnectionResponseView(frame)
- return response.GetSourceCid() == scid and response.GetDestinationCid() == dcid
-
- @staticmethod
- def _is_matching_le_disconnection_request(packet, scid, dcid):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.DISCONNECTION_REQUEST)
- if frame is None:
- return False
- request = l2cap_packets.LeDisconnectionRequestView(frame)
- return request.GetSourceCid() == scid and request.GetDestinationCid() == dcid
-
- @staticmethod
- def _is_matching_le_flow_control_credit(packet, cid):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_FLOW_CONTROL_CREDIT)
- if frame is None:
- return False
- request = l2cap_packets.LeFlowControlCreditView(frame)
- return request.GetCid() == cid
-
- @staticmethod
- def _information_request_with_type(packet, info_type):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.INFORMATION_REQUEST)
- if frame is None:
- return None
- request = l2cap_packets.InformationRequestView(frame)
- if request.GetInfoType() != info_type:
- return None
- return request
-
- @staticmethod
- def _information_response_with_type(packet, info_type):
- frame = L2capMatchers.control_frame_with_code(packet, CommandCode.INFORMATION_RESPONSE)
- if frame is None:
- return None
- response = l2cap_packets.InformationResponseView(frame)
- if response.GetInfoType() != info_type:
- return None
- return response
-
- @staticmethod
- def _is_matching_information_response_extended_features(packet, supports_ertm, supports_streaming, supports_fcs,
- supports_fixed_channels):
- frame = L2capMatchers._information_response_with_type(packet,
- InformationRequestInfoType.EXTENDED_FEATURES_SUPPORTED)
- if frame is None:
- return False
- features = l2cap_packets.InformationResponseExtendedFeaturesView(frame)
- if supports_ertm is not None and features.GetEnhancedRetransmissionMode() != supports_ertm:
- return False
- if supports_streaming is not None and features.GetStreamingMode != supports_streaming:
- return False
- if supports_fcs is not None and features.GetFcsOption() != supports_fcs:
- return False
- if supports_fixed_channels is not None and features.GetFixedChannels() != supports_fixed_channels:
- return False
- return True
-
- @staticmethod
- def _is_matching_connection_parameter_update_response(packet, result):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.CONNECTION_PARAMETER_UPDATE_RESPONSE)
- if frame is None:
- return False
- return l2cap_packets.ConnectionParameterUpdateResponseView(frame).GetResult() == result
-
- @staticmethod
- def _is_matching_credit_based_connection_request(packet, psm):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_REQUEST)
- if frame is None:
- return False
- request = l2cap_packets.LeCreditBasedConnectionRequestView(frame)
- return request.GetLePsm() == psm
-
- @staticmethod
- def _is_matching_credit_based_connection_response(packet, result):
- frame = L2capMatchers.le_control_frame_with_code(packet, LeCommandCode.LE_CREDIT_BASED_CONNECTION_RESPONSE)
- if frame is None:
- return False
- response = l2cap_packets.LeCreditBasedConnectionResponseView(frame)
- return response.GetResult() == result and (result != LeCreditBasedConnectionResponseResult.SUCCESS or
- response.GetDestinationCid() != 0)
-
- @staticmethod
- def LinkSecurityInterfaceCallbackEvent(type):
- return lambda event: True if event.event_type == type else False
-
-
class SecurityMatchers(object):
@staticmethod
diff --git a/system/blueberry/tests/gd/cert/py_l2cap.py b/system/blueberry/tests/gd/cert/py_l2cap.py
deleted file mode 100644
index 60a852b..0000000
--- a/system/blueberry/tests/gd/cert/py_l2cap.py
+++ /dev/null
@@ -1,264 +0,0 @@
-#!/usr/bin/env python3
-#
-# 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.
-
-from google.protobuf import empty_pb2 as empty_proto
-
-from blueberry.facade.l2cap.classic import facade_pb2 as l2cap_facade_pb2
-from blueberry.facade.l2cap.classic.facade_pb2 import LinkSecurityInterfaceCallbackEventType
-from blueberry.facade.l2cap.le import facade_pb2 as l2cap_le_facade_pb2
-from blueberry.facade.l2cap.le.facade_pb2 import SecurityLevel
-from bluetooth_packets_python3 import l2cap_packets
-from blueberry.tests.gd.cert.event_stream import FilteringEventStream
-from blueberry.tests.gd.cert.event_stream import EventStream, IEventStream
-from blueberry.tests.gd.cert.closable import Closable, safeClose
-from blueberry.tests.gd.cert.py_hci import PyHci
-from blueberry.tests.gd.cert.matchers import HciMatchers
-from blueberry.tests.gd.cert.matchers import L2capMatchers
-from blueberry.tests.gd.cert.truth import assertThat
-import hci_packets as hci
-
-
-class PyL2capChannel(IEventStream):
-
- def __init__(self, device, psm, l2cap_stream):
- self._device = device
- self._psm = psm
- self._le_l2cap_stream = l2cap_stream
- self._our_le_l2cap_view = FilteringEventStream(self._le_l2cap_stream,
- L2capMatchers.PacketPayloadWithMatchingPsm(self._psm))
-
- def get_event_queue(self):
- return self._our_le_l2cap_view.get_event_queue()
-
- def send(self, payload):
- self._device.l2cap.SendDynamicChannelPacket(
- l2cap_facade_pb2.DynamicChannelPacket(psm=self._psm, payload=payload))
-
- def close_channel(self):
- self._device.l2cap.CloseChannel(l2cap_facade_pb2.CloseChannelRequest(psm=self._psm))
-
- def set_traffic_paused(self, paused):
- self._device.l2cap.SetTrafficPaused(l2cap_facade_pb2.SetTrafficPausedRequest(psm=self._psm, paused=paused))
-
-
-class _ClassicConnectionResponseFutureWrapper(object):
- """
- The future object returned when we send a connection request from DUT. Can be used to get connection status and
- create the corresponding PyL2capDynamicChannel object later
- """
-
- def __init__(self, grpc_response_future, device, psm, l2cap_stream):
- self._grpc_response_future = grpc_response_future
- self._device = device
- self._psm = psm
- self._l2cap_stream = l2cap_stream
-
- def get_channel(self):
- return PyL2capChannel(self._device, self._psm, self._l2cap_stream)
-
-
-class PyL2cap(Closable):
-
- def __init__(self, device, cert_address, has_security=False):
- self._device = device
- self._cert_address = cert_address
- self._hci = PyHci(device)
- self._l2cap_stream = EventStream(self._device.l2cap.FetchL2capData(empty_proto.Empty()))
- self._security_connection_event_stream = EventStream(
- self._device.l2cap.FetchSecurityConnectionEvents(empty_proto.Empty()))
- if has_security == False:
- self._hci.register_for_events(hci.EventCode.LINK_KEY_REQUEST)
-
- def close(self):
- safeClose(self._l2cap_stream)
- safeClose(self._security_connection_event_stream)
- safeClose(self._hci)
-
- def register_dynamic_channel(self, psm=0x33, mode=l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC):
- self._device.l2cap.SetDynamicChannel(
- l2cap_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, retransmission_mode=mode))
- return PyL2capChannel(self._device, psm, self._l2cap_stream)
-
- def connect_dynamic_channel_to_cert(self, psm=0x33, mode=l2cap_facade_pb2.RetransmissionFlowControlMode.BASIC):
- """
- Send open Dynamic channel request to CERT.
- Get a future for connection result, to be used after CERT accepts request
- """
- self.register_dynamic_channel(psm, mode)
- response_future = self._device.l2cap.OpenChannel.future(
- l2cap_facade_pb2.OpenChannelRequest(psm=psm, remote=self._cert_address, mode=mode))
-
- return _ClassicConnectionResponseFutureWrapper(response_future, self._device, psm, self._l2cap_stream)
-
- def get_channel_queue_buffer_size(self):
- return self._device.l2cap.GetChannelQueueDepth(empty_proto.Empty()).size
-
- def initiate_connection_for_security(self):
- """
- Establish an ACL for the specific purpose of pairing devices
- """
- self._device.l2cap.InitiateConnectionForSecurity(self._cert_address)
-
- def get_security_connection_event_stream(self):
- """
- Stream of Link related events. Events are returned with an address.
- Events map to the LinkSecurityInterfaceListener callbacks
- """
- return self._security_connection_event_stream
-
- def security_link_hold(self):
- """
- Holds open the ACL indefinitely allowing for the security handshake
- to take place
- """
- self._device.l2cap.SecurityLinkHold(self._cert_address)
-
- def security_link_ensure_authenticated(self):
- """
- Triggers authentication process by sending HCI event AUTHENTICATION_REQUESTED
- """
- self._device.l2cap.SecurityLinkEnsureAuthenticated(self._cert_address)
-
- def security_link_release(self):
- """
- Releases a Held open ACL allowing for the ACL to time out after the default time
- """
- self._device.l2cap.SecurityLinkRelease(self._cert_address)
-
- def security_link_disconnect(self):
- """
- Immediately release and disconnect ACL
- """
- self._device.l2cap.SecurityLinkDisconnect(self._cert_address)
-
- def verify_security_connection(self):
- """
- Verify that we get a connection and a link key request
- """
- assertThat(self.get_security_connection_event_stream()).emits(
- lambda event: event.event_type == LinkSecurityInterfaceCallbackEventType.ON_CONNECTED)
- assertThat(self._hci.get_event_stream()).emits(HciMatchers.LinkKeyRequest())
-
-
-class PyLeL2capFixedChannel(IEventStream):
-
- def __init__(self, device, cid, l2cap_stream):
- self._device = device
- self._cid = cid
- self._le_l2cap_stream = l2cap_stream
- self._our_le_l2cap_view = FilteringEventStream(self._le_l2cap_stream,
- L2capMatchers.PacketPayloadWithMatchingCid(self._cid))
-
- def get_event_queue(self):
- return self._our_le_l2cap_view.get_event_queue()
-
- def send(self, payload):
- self._device.l2cap_le.SendFixedChannelPacket(
- l2cap_le_facade_pb2.FixedChannelPacket(cid=self._cid, payload=payload))
-
- def close_channel(self):
- self._device.l2cap_le.SetFixedChannel(
- l2cap_le_facade_pb2.SetEnableFixedChannelRequest(cid=self._cid, enable=False))
-
-
-class PyLeL2capDynamicChannel(IEventStream):
-
- def __init__(self, device, cert_address, psm, l2cap_stream):
- self._device = device
- self._cert_address = cert_address
- self._psm = psm
- self._le_l2cap_stream = l2cap_stream
- self._our_le_l2cap_view = FilteringEventStream(self._le_l2cap_stream,
- L2capMatchers.PacketPayloadWithMatchingPsm(self._psm))
-
- def get_event_queue(self):
- return self._our_le_l2cap_view.get_event_queue()
-
- def send(self, payload):
- self._device.l2cap_le.SendDynamicChannelPacket(
- l2cap_le_facade_pb2.DynamicChannelPacket(psm=self._psm, payload=payload))
-
- def close_channel(self):
- self._device.l2cap_le.CloseDynamicChannel(
- l2cap_le_facade_pb2.CloseDynamicChannelRequest(remote=self._cert_address, psm=self._psm))
-
-
-class _CreditBasedConnectionResponseFutureWrapper(object):
- """
- The future object returned when we send a connection request from DUT. Can be used to get connection status and
- create the corresponding PyLeL2capDynamicChannel object later
- """
-
- def __init__(self, grpc_response_future, device, cert_address, psm, le_l2cap_stream):
- self._grpc_response_future = grpc_response_future
- self._device = device
- self._cert_address = cert_address
- self._psm = psm
- self._le_l2cap_stream = le_l2cap_stream
-
- def get_status(self):
- return l2cap_packets.LeCreditBasedConnectionResponseResult(self._grpc_response_future.result().status)
-
- def get_channel(self):
- assertThat(self.get_status()).isEqualTo(l2cap_packets.LeCreditBasedConnectionResponseResult.SUCCESS)
- return PyLeL2capDynamicChannel(self._device, self._cert_address, self._psm, self._le_l2cap_stream)
-
-
-class PyLeL2cap(Closable):
-
- def __init__(self, device):
- self._device = device
- self._le_l2cap_stream = EventStream(self._device.l2cap_le.FetchL2capData(empty_proto.Empty()))
-
- def close(self):
- safeClose(self._le_l2cap_stream)
-
- def enable_fixed_channel(self, cid=4):
- self._device.l2cap_le.SetFixedChannel(l2cap_le_facade_pb2.SetEnableFixedChannelRequest(cid=cid, enable=True))
-
- def get_fixed_channel(self, cid=4):
- return PyLeL2capFixedChannel(self._device, cid, self._le_l2cap_stream)
-
- def register_coc(self, cert_address, psm=0x33, security_level=SecurityLevel.NO_SECURITY):
- self._device.l2cap_le.SetDynamicChannel(
- l2cap_le_facade_pb2.SetEnableDynamicChannelRequest(psm=psm, enable=True, security_level=security_level))
- return PyLeL2capDynamicChannel(self._device, cert_address, psm, self._le_l2cap_stream)
-
- def connect_coc_to_cert(self, cert_address, psm=0x33):
- """
- Send open LE COC request to CERT. Get a future for connection result, to be used after CERT accepts request
- """
- self.register_coc(cert_address, psm)
- response_future = self._device.l2cap_le.OpenDynamicChannel.future(
- l2cap_le_facade_pb2.OpenDynamicChannelRequest(psm=psm, remote=cert_address))
-
- return _CreditBasedConnectionResponseFutureWrapper(response_future, self._device, cert_address, psm,
- self._le_l2cap_stream)
-
- def update_connection_parameter(self,
- conn_interval_min=0x10,
- conn_interval_max=0x10,
- conn_latency=0x0a,
- supervision_timeout=0x64,
- min_ce_length=12,
- max_ce_length=12):
- self._device.l2cap_le.SendConnectionParameterUpdate(
- l2cap_le_facade_pb2.ConnectionParameter(conn_interval_min=conn_interval_min,
- conn_interval_max=conn_interval_max,
- conn_latency=conn_latency,
- supervision_timeout=supervision_timeout,
- min_ce_length=min_ce_length,
- max_ce_length=max_ce_length))
diff --git a/system/blueberry/tests/gd/hci/le_acl_manager_test.py b/system/blueberry/tests/gd/hci/le_acl_manager_test.py
index deecaea..51c01a5 100644
--- a/system/blueberry/tests/gd/hci/le_acl_manager_test.py
+++ b/system/blueberry/tests/gd/hci/le_acl_manager_test.py
@@ -24,7 +24,6 @@
from blueberry.facade.hci import le_advertising_manager_facade_pb2 as le_advertising_facade
from blueberry.facade.hci import le_initiator_address_facade_pb2 as le_initiator_address_facade
from blueberry.facade.hci import hci_facade_pb2 as hci_facade
-from bluetooth_packets_python3 import RawBuilder
from mobly import test_runner
import hci_packets as hci
diff --git a/system/blueberry/tests/gd/l2cap/le/cert_le_l2cap.py b/system/blueberry/tests/gd/l2cap/le/cert_le_l2cap.py
deleted file mode 100644
index 36139f6..0000000
--- a/system/blueberry/tests/gd/l2cap/le/cert_le_l2cap.py
+++ /dev/null
@@ -1,200 +0,0 @@
-#!/usr/bin/env python3
-#
-# 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.
-
-from blueberry.tests.gd.cert.captures import L2capCaptures
-from blueberry.tests.gd.cert.closable import Closable
-from blueberry.tests.gd.cert.closable import safeClose
-from blueberry.tests.gd.cert.event_stream import FilteringEventStream
-from blueberry.tests.gd.cert.event_stream import IEventStream
-from blueberry.tests.gd.cert.matchers import L2capMatchers
-from blueberry.tests.gd.cert.py_le_acl_manager import PyLeAclManager
-from blueberry.tests.gd.cert.truth import assertThat
-import bluetooth_packets_python3 as bt_packets
-from bluetooth_packets_python3 import l2cap_packets
-from bluetooth_packets_python3.l2cap_packets import LeCommandCode
-from bluetooth_packets_python3.l2cap_packets import LeCreditBasedConnectionResponseResult
-
-
-class CertLeL2capChannel(IEventStream):
-
- def __init__(self, device, scid, dcid, acl_stream, acl, control_channel, initial_credits=0):
- self._device = device
- self._scid = scid
- self._dcid = dcid
- self._acl_stream = acl_stream
- self._acl = acl
- self._control_channel = control_channel
- self._our_acl_view = FilteringEventStream(acl_stream, L2capMatchers.ExtractBasicFrame(scid))
- self._credits_left = initial_credits
-
- def get_event_queue(self):
- return self._our_acl_view.get_event_queue()
-
- def send(self, packet):
- frame = l2cap_packets.BasicFrameBuilder(self._dcid, packet)
- self._acl.send(frame.Serialize())
- self._credits_left -= 1
-
- def send_first_le_i_frame(self, sdu_size, packet):
- frame = l2cap_packets.FirstLeInformationFrameBuilder(self._dcid, sdu_size, packet)
- self._acl.send(frame.Serialize())
- self._credits_left -= 1
-
- def disconnect_and_verify(self):
- assertThat(self._scid).isNotEqualTo(1)
- self._control_channel.send(l2cap_packets.LeDisconnectionRequestBuilder(1, self._dcid, self._scid))
-
- assertThat(self._control_channel).emits(L2capMatchers.LeDisconnectionResponse(self._scid, self._dcid))
-
- def verify_disconnect_request(self):
- assertThat(self._control_channel).emits(L2capMatchers.LeDisconnectionRequest(self._dcid, self._scid))
-
- def send_credits(self, num_credits):
- self._control_channel.send(l2cap_packets.LeFlowControlCreditBuilder(2, self._scid, num_credits))
-
- def credits_left(self):
- return self._credits_left
-
-
-class CertLeL2cap(Closable):
-
- def __init__(self, device):
- self._device = device
- self._le_acl_manager = PyLeAclManager(device)
- self._le_acl = None
-
- self.control_table = {
- LeCommandCode.DISCONNECTION_REQUEST: self._on_disconnection_request_default,
- LeCommandCode.DISCONNECTION_RESPONSE: self._on_disconnection_response_default,
- LeCommandCode.LE_FLOW_CONTROL_CREDIT: self._on_credit,
- }
-
- self._cid_to_cert_channels = {}
-
- def close(self):
- self._le_acl_manager.close()
- safeClose(self._le_acl)
-
- def connect_le_acl(self, remote_addr):
- self._le_acl = self._le_acl_manager.connect_to_remote(remote_addr)
- self.control_channel = CertLeL2capChannel(
- self._device, 5, 5, self._get_acl_stream(), self._le_acl, control_channel=None)
- self._get_acl_stream().register_callback(self._handle_control_packet)
-
- def wait_for_connection(self):
- self._le_acl = self._le_acl_manager.wait_for_connection()
- self.control_channel = CertLeL2capChannel(
- self._device, 5, 5, self._get_acl_stream(), self._le_acl, control_channel=None)
- self._get_acl_stream().register_callback(self._handle_control_packet)
-
- def open_fixed_channel(self, cid=4):
- channel = CertLeL2capChannel(self._device, cid, cid, self._get_acl_stream(), self._le_acl, None, 0)
- return channel
-
- def open_channel(self, signal_id, psm, scid, mtu=1000, mps=100, initial_credit=6):
- self.control_channel.send(
- l2cap_packets.LeCreditBasedConnectionRequestBuilder(signal_id, psm, scid, mtu, mps, initial_credit))
-
- response = L2capCaptures.CreditBasedConnectionResponse()
- assertThat(self.control_channel).emits(response)
- channel = CertLeL2capChannel(self._device, scid,
- response.get().GetDestinationCid(), self._get_acl_stream(), self._le_acl,
- self.control_channel,
- response.get().GetInitialCredits())
- self._cid_to_cert_channels[scid] = channel
- return channel
-
- def open_channel_with_expected_result(self, psm=0x33, result=LeCreditBasedConnectionResponseResult.SUCCESS):
- self.control_channel.send(l2cap_packets.LeCreditBasedConnectionRequestBuilder(1, psm, 0x40, 1000, 100, 6))
-
- response = L2capMatchers.CreditBasedConnectionResponse(result)
- assertThat(self.control_channel).emits(response)
-
- def verify_and_respond_open_channel_from_remote(self,
- psm=0x33,
- result=LeCreditBasedConnectionResponseResult.SUCCESS,
- our_scid=None):
- request = L2capCaptures.CreditBasedConnectionRequest(psm)
- assertThat(self.control_channel).emits(request)
- (scid, dcid) = self._respond_connection_request_default(request.get(), result, our_scid)
- channel = CertLeL2capChannel(self._device, scid, dcid, self._get_acl_stream(), self._le_acl,
- self.control_channel,
- request.get().GetInitialCredits())
- self._cid_to_cert_channels[scid] = channel
- return channel
-
- def verify_and_reject_open_channel_from_remote(self, psm=0x33):
- request = L2capCaptures.CreditBasedConnectionRequest(psm)
- assertThat(self.control_channel).emits(request)
- sid = request.get().GetIdentifier()
- reject = l2cap_packets.LeCommandRejectNotUnderstoodBuilder(sid)
- self.control_channel.send(reject)
-
- def verify_le_flow_control_credit(self, channel):
- assertThat(self.control_channel).emits(L2capMatchers.LeFlowControlCredit(channel._dcid))
-
- def _respond_connection_request_default(self,
- request,
- result=LeCreditBasedConnectionResponseResult.SUCCESS,
- our_scid=None):
- sid = request.GetIdentifier()
- their_scid = request.GetSourceCid()
- mtu = request.GetMtu()
- mps = request.GetMps()
- initial_credits = request.GetInitialCredits()
- # If our_scid is not specified, we use the same value - their scid as their scid
- if our_scid is None:
- our_scid = their_scid
- our_dcid = their_scid
- response = l2cap_packets.LeCreditBasedConnectionResponseBuilder(sid, our_scid, mtu, mps, initial_credits,
- result)
- self.control_channel.send(response)
- return (our_scid, our_dcid)
-
- def get_control_channel(self):
- return self.control_channel
-
- def _get_acl_stream(self):
- return self._le_acl.acl_stream
-
- def _on_disconnection_request_default(self, request):
- disconnection_request = l2cap_packets.LeDisconnectionRequestView(request)
- sid = disconnection_request.GetIdentifier()
- scid = disconnection_request.GetSourceCid()
- dcid = disconnection_request.GetDestinationCid()
- response = l2cap_packets.LeDisconnectionResponseBuilder(sid, dcid, scid)
- self.control_channel.send(response)
-
- def _on_disconnection_response_default(self, request):
- disconnection_response = l2cap_packets.LeDisconnectionResponseView(request)
-
- def _on_credit(self, l2cap_le_control_view):
- credit_view = l2cap_packets.LeFlowControlCreditView(l2cap_le_control_view)
- cid = credit_view.GetCid()
- if cid not in self._cid_to_cert_channels:
- return
- self._cid_to_cert_channels[cid]._credits_left += credit_view.GetCredits()
-
- def _handle_control_packet(self, l2cap_packet):
- packet_bytes = l2cap_packet.payload
- l2cap_view = l2cap_packets.BasicFrameView(bt_packets.PacketViewLittleEndian(list(packet_bytes)))
- if l2cap_view.GetChannelId() != 5:
- return
- request = l2cap_packets.LeControlView(l2cap_view.GetPayload())
- fn = self.control_table.get(request.GetCode())
- if fn is not None:
- fn(request)
- return
diff --git a/system/bta/Android.bp b/system/bta/Android.bp
index 1402876..5b26e24 100644
--- a/system/bta/Android.bp
+++ b/system/bta/Android.bp
@@ -788,7 +788,6 @@
"le_audio/le_audio_set_configuration_provider_json.cc",
"le_audio/le_audio_types.cc",
"le_audio/le_audio_utils.cc",
- "test/common/mock_controller.cc",
],
data: [
":audio_set_configurations_bfbs",
@@ -801,6 +800,7 @@
"LeAudioSetConfigSchemas_h",
],
shared_libs: [
+ "libbase",
"libcrypto",
"libhidlbase",
"liblog", // __android_log_print
@@ -893,7 +893,6 @@
"test/common/bta_gatt_queue_mock.cc",
"test/common/btif_storage_mock.cc",
"test/common/btm_api_mock.cc",
- "test/common/mock_controller.cc",
"test/common/mock_csis_client.cc",
],
data: [
@@ -988,7 +987,6 @@
"test/common/bta_gatt_queue_mock.cc",
"test/common/btif_storage_mock.cc",
"test/common/btm_api_mock.cc",
- "test/common/mock_controller.cc",
"test/common/mock_csis_client.cc",
"test/common/mock_device_groups.cc",
],
@@ -1087,6 +1085,7 @@
"le_audio/mock_codec_manager.cc",
],
shared_libs: [
+ "libbase",
"libcrypto",
"liblog",
],
@@ -1153,9 +1152,9 @@
"le_audio/metrics_collector_linux.cc",
"le_audio/mock_codec_interface.cc",
"le_audio/mock_codec_manager.cc",
- "test/common/mock_controller.cc",
],
shared_libs: [
+ "libbase",
"libbinder_ndk",
"libcrypto",
"libfmq",
@@ -1224,7 +1223,6 @@
"test/common/bta_gatt_queue_mock.cc",
"test/common/btif_storage_mock.cc",
"test/common/btm_api_mock.cc",
- "test/common/mock_controller.cc",
"test/common/mock_csis_client.cc",
],
shared_libs: [
diff --git a/system/bta/csis/csis_client.cc b/system/bta/csis/csis_client.cc
index 090f34f..6fcee05 100644
--- a/system/bta/csis/csis_client.cc
+++ b/system/bta/csis/csis_client.cc
@@ -1411,11 +1411,12 @@
*/
if (instance == nullptr) return;
- if (event == BTA_DM_INQ_CMPL_EVT) {
+ if (event == BTA_DM_OBSERVE_CMPL_EVT) {
power_telemetry::GetInstance().LogBleScan(
- static_cast<int>(p_data->inq_cmpl.num_resps));
+ static_cast<int>(
+ p_data->observe_cmpl.num_resps));
log::info("BLE observe complete. Num Resp: {}",
- p_data->inq_cmpl.num_resps);
+ p_data->observe_cmpl.num_resps);
csis_ad_type_filter_set(false);
instance->OnCsisObserveCompleted();
instance->CsisObserverSetBackground(true);
@@ -1535,11 +1536,12 @@
*/
if (instance == nullptr) return;
- if (event == BTA_DM_INQ_CMPL_EVT) {
+ if (event == BTA_DM_OBSERVE_CMPL_EVT) {
power_telemetry::GetInstance().LogBleScan(
- static_cast<int>(p_data->inq_cmpl.num_resps));
+ static_cast<int>(
+ p_data->observe_cmpl.num_resps));
log::verbose("BLE observe complete. Num Resp: {}",
- p_data->inq_cmpl.num_resps);
+ p_data->observe_cmpl.num_resps);
return;
}
diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc
index 0eb29a4..18cf0b6 100644
--- a/system/bta/csis/csis_client_test.cc
+++ b/system/bta/csis/csis_client_test.cc
@@ -1206,9 +1206,9 @@
ASSERT_NE(p_results_cb, nullptr);
tBTA_DM_SEARCH result;
- result.inq_cmpl.num_resps = 80;
+ result.observe_cmpl.num_resps = 80;
- p_results_cb(BTA_DM_INQ_CMPL_EVT, &result);
+ p_results_cb(BTA_DM_OBSERVE_CMPL_EVT, &result);
/* Verify that scanner has been called to stop filtering */
ASSERT_EQ(2, get_func_call_count("set_empty_filter"));
diff --git a/system/bta/dm/bta_dm_act.cc b/system/bta/dm/bta_dm_act.cc
index 72dce00..b954823 100644
--- a/system/bta/dm/bta_dm_act.cc
+++ b/system/bta/dm/bta_dm_act.cc
@@ -45,7 +45,6 @@
#include "bta/sys/bta_sys.h"
#include "btif/include/btif_dm.h"
#include "btif/include/stack_manager_t.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "include/bind_helpers.h"
#include "include/check.h"
@@ -1471,8 +1470,9 @@
/** This function set the maximum transmission packet size */
void bta_dm_ble_set_data_length(const RawAddress& bd_addr) {
- const controller_t* controller = controller_get_interface();
- uint16_t max_len = controller->get_ble_maximum_tx_data_length();
+ uint16_t max_len = bluetooth::shim::GetController()
+ ->GetLeMaximumDataLength()
+ .supported_max_tx_octets_;
if (BTM_SetBleDataLength(bd_addr, max_len) != BTM_SUCCESS) {
log::info("Unable to set ble data length:{}", max_len);
diff --git a/system/bta/dm/bta_dm_api.cc b/system/bta/dm/bta_dm_api.cc
index e7ae385..b32588e 100644
--- a/system/bta/dm/bta_dm_api.cc
+++ b/system/bta/dm/bta_dm_api.cc
@@ -327,32 +327,9 @@
/*******************************************************************************
*
- * Function BTA_DmBleObserve
- *
- * Description This procedure keep the device listening for advertising
- * events from a broadcast device.
- *
- * Parameters start: start or stop observe.
- *
- * Returns void
-
- *
- * Returns void.
- *
- ******************************************************************************/
-void BTA_DmBleObserve(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_results_cb) {
- log::verbose("start = {}", start);
- do_in_main_thread(FROM_HERE, base::BindOnce(bta_dm_ble_observe, start,
- duration, p_results_cb));
-}
-
-/*******************************************************************************
- *
* Function BTA_DmBleScan
*
- * Description Start or stop the scan procedure if it's not already started
- * with BTA_DmBleObserve().
+ * Description Start or stop the scan procedure.
*
* Parameters start: start or stop the scan procedure,
* duration_sec: Duration of the scan. Continuous scan if 0 is
diff --git a/system/bta/dm/bta_dm_disc.cc b/system/bta/dm/bta_dm_disc.cc
index ac94ef4..d97737e 100644
--- a/system/bta/dm/bta_dm_disc.cc
+++ b/system/bta/dm/bta_dm_disc.cc
@@ -25,6 +25,7 @@
#include <stddef.h>
#include <cstdint>
+#include <string>
#include <vector>
#include "android_bluetooth_flags.h"
@@ -80,7 +81,7 @@
static void bta_dm_gatt_disc_complete(uint16_t conn_id, tGATT_STATUS status);
static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
uint16_t eir_len);
-static void bta_dm_inq_cmpl(uint8_t num);
+static void bta_dm_inq_cmpl();
static void bta_dm_inq_cmpl_cb(void* p_result);
static void bta_dm_service_search_remname_cback(const RawAddress& bd_addr,
DEV_CLASS dc, BD_NAME bd_name);
@@ -287,7 +288,7 @@
log::warn("Unable to start device discovery search btm_status:{}",
btm_status_text(btm_status));
// Not started so completion callback is executed now
- bta_dm_inq_cmpl(0);
+ bta_dm_inq_cmpl();
break;
}
}
@@ -320,7 +321,7 @@
}
#endif
} else {
- bta_dm_inq_cmpl(0);
+ bta_dm_inq_cmpl();
}
}
@@ -436,7 +437,7 @@
* Returns void
*
******************************************************************************/
-static void bta_dm_inq_cmpl(uint8_t num) {
+static void bta_dm_inq_cmpl() {
if (bta_dm_search_get_state() == BTA_DM_SEARCH_CANCELLING) {
bta_dm_search_set_state(BTA_DM_SEARCH_IDLE);
bta_dm_execute_queued_request();
@@ -447,13 +448,8 @@
return;
}
- tBTA_DM_SEARCH data;
-
log::verbose("bta_dm_inq_cmpl");
- data.inq_cmpl.num_resps = num;
- bta_dm_search_cb.p_search_cback(BTA_DM_INQ_CMPL_EVT, &data);
-
bta_dm_search_cb.p_btm_inq_info =
get_btm_client_interface().db.BTM_InqDbFirst();
if (bta_dm_search_cb.p_btm_inq_info != NULL) {
@@ -1535,10 +1531,10 @@
* Returns void
*
******************************************************************************/
-static void bta_dm_inq_cmpl_cb(void* p_result) {
+static void bta_dm_inq_cmpl_cb(void* /* p_result */) {
log::verbose("");
- bta_dm_inq_cmpl(((tBTM_INQUIRY_CMPL*)p_result)->num_resp);
+ bta_dm_inq_cmpl();
}
/*******************************************************************************
@@ -1561,10 +1557,7 @@
/* if this is what we are looking for */
if (bta_dm_search_cb.peer_bdaddr == bd_addr) {
rem_name.bd_addr = bd_addr;
- rem_name.length = bd_name_copy(rem_name.remote_bd_name, bd_name);
- if (rem_name.length > BD_NAME_LEN) {
- rem_name.length = BD_NAME_LEN;
- }
+ bd_name_copy(rem_name.remote_bd_name, bd_name);
rem_name.status = BTM_SUCCESS;
rem_name.hci_status = HCI_SUCCESS;
bta_dm_remname_cback(&rem_name);
@@ -1583,7 +1576,6 @@
// needed so our response is not ignored, since this corresponds to the
// actual peer_bdaddr
rem_name.bd_addr = bta_dm_search_cb.peer_bdaddr;
- rem_name.length = 0;
rem_name.remote_bd_name[0] = 0;
rem_name.status = btm_status;
rem_name.hci_status = HCI_SUCCESS;
@@ -1610,7 +1602,8 @@
ADDRESS_TO_LOGGABLE_CSTR(p_remote_name->bd_addr),
btm_status_text(p_remote_name->status),
hci_error_code_text(p_remote_name->hci_status),
- p_remote_name->remote_bd_name[0], p_remote_name->length);
+ p_remote_name->remote_bd_name[0],
+ strnlen((const char*)p_remote_name->remote_bd_name, BD_NAME_LEN));
if (bta_dm_search_cb.peer_bdaddr == p_remote_name->bd_addr) {
get_btm_client_interface().security.BTM_SecDeleteRmtNameNotifyCallback(
@@ -1728,9 +1721,6 @@
result.inq_res.remt_name_not_required = false;
}
- if (bta_dm_search_cb.p_scan_cback)
- bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_RES_EVT, &result);
-
if (p_inq_info) {
/* application indicates if it knows the remote name, inside the callback
copy that to the inquiry data base*/
@@ -1802,16 +1792,12 @@
*
******************************************************************************/
static void bta_dm_observe_cmpl_cb(void* p_result) {
- tBTA_DM_SEARCH data;
-
log::verbose("bta_dm_observe_cmpl_cb");
- data.inq_cmpl.num_resps = ((tBTM_INQUIRY_CMPL*)p_result)->num_resp;
- if (bta_dm_search_cb.p_scan_cback) {
- bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
- }
if (bta_dm_search_cb.p_csis_scan_cback) {
- bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
+ auto num_resps = ((tBTM_INQUIRY_CMPL*)p_result)->num_resp;
+ tBTA_DM_SEARCH data{.observe_cmpl{.num_resps = num_resps}};
+ bta_dm_search_cb.p_csis_scan_cback(BTA_DM_OBSERVE_CMPL_EVT, &data);
}
}
@@ -1822,40 +1808,16 @@
low_latency_scan);
if (status != BTM_CMD_STARTED) {
- tBTA_DM_SEARCH data = {
- .inq_cmpl =
- {
- .num_resps = 0,
- },
- };
log::warn("BTM_BleObserve failed. status {}", status);
- if (bta_dm_search_cb.p_scan_cback) {
- bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
- }
if (bta_dm_search_cb.p_csis_scan_cback) {
- bta_dm_search_cb.p_csis_scan_cback(BTA_DM_INQ_CMPL_EVT, &data);
+ tBTA_DM_SEARCH data{.observe_cmpl = {.num_resps = 0}};
+ bta_dm_search_cb.p_csis_scan_cback(BTA_DM_OBSERVE_CMPL_EVT, &data);
}
}
}
-void bta_dm_ble_observe(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_cback) {
- if (!start) {
- bta_dm_search_cb.p_scan_cback = NULL;
- get_btm_client_interface().ble.BTM_BleObserve(false, 0, NULL, NULL, false);
- return;
- }
-
- /*Save the callback to be called when a scan results are available */
- bta_dm_search_cb.p_scan_cback = p_cback;
- bta_dm_start_scan(duration);
-}
-
void bta_dm_ble_scan(bool start, uint8_t duration_sec,
bool low_latency_scan = false) {
- /* Start or stop only if there is no active main scanner */
- if (bta_dm_search_cb.p_scan_cback != NULL) return;
-
if (!start) {
get_btm_client_interface().ble.BTM_BleObserve(false, 0, NULL, NULL, false);
return;
@@ -2482,7 +2444,7 @@
void bta_dm_find_services(const RawAddress& bd_addr) {
::bta_dm_find_services(bd_addr);
}
-void bta_dm_inq_cmpl(uint8_t num) { ::bta_dm_inq_cmpl(num); }
+void bta_dm_inq_cmpl() { ::bta_dm_inq_cmpl(); }
void bta_dm_inq_cmpl_cb(void* p_result) { ::bta_dm_inq_cmpl_cb(p_result); }
void bta_dm_observe_cmpl_cb(void* p_result) {
::bta_dm_observe_cmpl_cb(p_result);
diff --git a/system/bta/dm/bta_dm_disc.h b/system/bta/dm/bta_dm_disc.h
index e010efd..02c2089 100644
--- a/system/bta/dm/bta_dm_disc.h
+++ b/system/bta/dm/bta_dm_disc.h
@@ -48,8 +48,6 @@
const char* bta_dm_get_remname(void);
// LE observe and scan interface
-void bta_dm_ble_observe(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_cback);
void bta_dm_ble_scan(bool start, uint8_t duration_sec, bool low_latency_scan);
void bta_dm_ble_csis_observe(bool observe, tBTA_DM_SEARCH_CBACK* p_cback);
diff --git a/system/bta/dm/bta_dm_disc_int.h b/system/bta/dm/bta_dm_disc_int.h
index f24c97b..d5df5ae 100644
--- a/system/bta/dm/bta_dm_disc_int.h
+++ b/system/bta/dm/bta_dm_disc_int.h
@@ -173,7 +173,6 @@
bluetooth::Uuid uuid;
uint8_t peer_scn;
tBT_TRANSPORT transport;
- tBTA_DM_SEARCH_CBACK* p_scan_cback;
tBTA_DM_SEARCH_CBACK* p_csis_scan_cback;
tGATT_IF client_if;
uint8_t uuid_to_search;
diff --git a/system/bta/dm/bta_dm_sec.cc b/system/bta/dm/bta_dm_sec.cc
index bc1d3b9..9e989bb 100644
--- a/system/bta/dm/bta_dm_sec.cc
+++ b/system/bta/dm/bta_dm_sec.cc
@@ -127,32 +127,6 @@
}
}
-/*******************************************************************************
- *
- * Function bta_dm_add_device
- *
- * Description This function adds a Link Key to an security database entry.
- * It is normally called during host startup to restore all
- * required information stored in the NVRAM.
- ******************************************************************************/
-void bta_dm_add_device(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg) {
- DEV_CLASS dc = kDevClassEmpty;
- LinkKey* p_lc = NULL;
-
- /* If not all zeros, the device class has been specified */
- if (msg->dc_known) dc = msg->dc;
-
- if (msg->link_key_known) p_lc = &msg->link_key;
-
- auto add_result = get_btm_client_interface().security.BTM_SecAddDevice(
- msg->bd_addr, dc, msg->bd_name, nullptr, p_lc, msg->key_type,
- msg->pin_length);
- if (!add_result) {
- log::error("Error adding device:{}",
- ADDRESS_TO_LOGGABLE_CSTR(msg->bd_addr));
- }
-}
-
/** Bonds with peer device */
void bta_dm_bond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type,
tBT_TRANSPORT transport, tBT_DEVICE_TYPE device_type) {
@@ -161,7 +135,6 @@
bt_transport_text(transport), DeviceTypeText(device_type));
tBTA_DM_SEC sec_event;
- const char* p_name;
tBTM_STATUS status = get_btm_client_interface().security.BTM_SecBond(
bd_addr, addr_type, transport, device_type);
@@ -169,11 +142,9 @@
if (bta_dm_sec_cb.p_sec_cback && (status != BTM_CMD_STARTED)) {
memset(&sec_event, 0, sizeof(tBTA_DM_SEC));
sec_event.auth_cmpl.bd_addr = bd_addr;
- p_name = get_btm_client_interface().security.BTM_SecReadDevName(bd_addr);
- if (p_name != NULL) {
- memcpy(sec_event.auth_cmpl.bd_name, p_name, BD_NAME_LEN);
- sec_event.auth_cmpl.bd_name[BD_NAME_LEN] = 0;
- }
+ bd_name_from_char_pointer(
+ sec_event.auth_cmpl.bd_name,
+ get_btm_client_interface().security.BTM_SecReadDevName(bd_addr));
/* taken care of by memset [above]
sec_event.auth_cmpl.key_present = false;
@@ -243,7 +214,6 @@
static void bta_dm_pinname_cback(const tBTM_REMOTE_DEV_NAME* p_data) {
tBTM_REMOTE_DEV_NAME* p_result = (tBTM_REMOTE_DEV_NAME*)p_data;
tBTA_DM_SEC sec_event;
- uint32_t bytes_to_copy;
tBTA_DM_SEC_EVT event = bta_dm_sec_cb.pin_evt;
if (BTA_DM_SP_CFM_REQ_EVT == event) {
@@ -252,11 +222,7 @@
sec_event.cfm_req.dev_class = bta_dm_sec_cb.pin_dev_class;
if (p_result && p_result->status == BTM_SUCCESS) {
- bytes_to_copy =
- (p_result->length < BD_NAME_LEN) ? p_result->length : BD_NAME_LEN;
- memcpy(sec_event.cfm_req.bd_name, p_result->remote_bd_name,
- bytes_to_copy);
- sec_event.pin_req.bd_name[BD_NAME_LEN] = 0;
+ bd_name_copy(sec_event.cfm_req.bd_name, p_result->remote_bd_name);
} else /* No name found */
sec_event.cfm_req.bd_name[0] = 0;
@@ -277,11 +243,7 @@
sec_event.pin_req.dev_class = bta_dm_sec_cb.pin_dev_class;
if (p_result && p_result->status == BTM_SUCCESS) {
- bytes_to_copy = (p_result->length < BD_NAME_LEN) ? p_result->length
- : (BD_NAME_LEN - 1);
- memcpy(sec_event.pin_req.bd_name, p_result->remote_bd_name,
- bytes_to_copy);
- sec_event.pin_req.bd_name[BD_NAME_LEN] = 0;
+ bd_name_copy(sec_event.pin_req.bd_name, p_result->remote_bd_name);
} else /* No name found */
sec_event.pin_req.bd_name[0] = 0;
@@ -356,8 +318,7 @@
p_auth_cmpl->bd_addr = bd_addr;
- memcpy(p_auth_cmpl->bd_name, bd_name, BD_NAME_LEN);
- p_auth_cmpl->bd_name[BD_NAME_LEN] = 0;
+ bd_name_copy(p_auth_cmpl->bd_name, bd_name);
p_auth_cmpl->key_present = true;
p_auth_cmpl->key_type = key_type;
p_auth_cmpl->success = true;
@@ -402,8 +363,7 @@
.bd_addr = bd_addr,
},
};
- memcpy(sec_event.auth_cmpl.bd_name, bd_name, BD_NAME_LEN);
- sec_event.auth_cmpl.bd_name[BD_NAME_LEN] = 0;
+ bd_name_copy(sec_event.auth_cmpl.bd_name, bd_name);
// Report the BR link key based on the BR/EDR address and type
get_btm_client_interface().peer.BTM_ReadDevInfo(
diff --git a/system/bta/dm/bta_dm_sec_api.cc b/system/bta/dm/bta_dm_sec_api.cc
index bf346ae..dae4791 100644
--- a/system/bta/dm/bta_dm_sec_api.cc
+++ b/system/bta/dm/bta_dm_sec_api.cc
@@ -30,6 +30,7 @@
#include "stack/btm/btm_sec.h"
#include "stack/include/bt_octets.h"
#include "stack/include/btm_ble_sec_api.h"
+#include "stack/include/btm_client_interface.h"
#include "stack/include/main_thread.h"
#include "types/raw_address.h"
@@ -134,35 +135,19 @@
* Description This function adds a device to the security database list of
* peer device
*
- *
* Returns void
*
******************************************************************************/
-void BTA_DmAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class,
- const LinkKey& link_key, uint8_t key_type,
- uint8_t pin_length) {
- std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg =
- std::make_unique<tBTA_DM_API_ADD_DEVICE>();
-
- msg->bd_addr = bd_addr;
- msg->link_key_known = true;
- msg->key_type = key_type;
- msg->link_key = link_key;
-
- /* Load device class if specified */
- if (dev_class != kDevClassEmpty) {
- msg->dc_known = true;
- msg->dc = dev_class;
- }
-
- memset(msg->bd_name, 0, BD_NAME_LEN + 1);
- msg->pin_length = pin_length;
+void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key,
+ uint8_t key_type, uint8_t pin_length) {
+ auto closure =
+ base::Bind(get_btm_client_interface().security.BTM_SecAddDevice, bd_addr,
+ dev_class, link_key, key_type, pin_length);
if (IS_FLAG_ENABLED(synchronous_bta_sec)) {
- bta_dm_add_device(std::move(msg));
+ closure.Run();
} else {
- do_in_main_thread(FROM_HERE,
- base::Bind(bta_dm_add_device, base::Passed(&msg)));
+ do_in_main_thread(FROM_HERE, closure);
}
}
diff --git a/system/bta/dm/bta_dm_sec_int.h b/system/bta/dm/bta_dm_sec_int.h
index 1b17655..699ac41 100644
--- a/system/bta/dm/bta_dm_sec_int.h
+++ b/system/bta/dm/bta_dm_sec_int.h
@@ -45,17 +45,6 @@
} tBTA_DM_CI_RMT_OOB;
typedef struct {
- RawAddress bd_addr;
- DEV_CLASS dc;
- LinkKey link_key;
- uint8_t key_type;
- bool link_key_known;
- bool dc_known;
- BD_NAME bd_name;
- uint8_t pin_length;
-} tBTA_DM_API_ADD_DEVICE;
-
-typedef struct {
tBTA_DM_SEC_CBACK* p_sec_cback;
tBTA_DM_SEC_CBACK* p_sec_sirk_cback;
/* Storage for pin code request parameters */
@@ -80,7 +69,6 @@
tBT_DEVICE_TYPE dev_type);
void bta_dm_add_blekey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE blekey,
tBTM_LE_KEY_TYPE key_type);
-void bta_dm_add_device(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg);
void bta_dm_ble_config_local_privacy(bool privacy_enable);
void bta_dm_ble_confirm_reply(const RawAddress& bd_addr, bool accept);
void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept,
diff --git a/system/bta/gatt/bta_gattc_act.cc b/system/bta/gatt/bta_gattc_act.cc
index 0e7cc6b..b2a4d23 100644
--- a/system/bta/gatt/bta_gattc_act.cc
+++ b/system/bta/gatt/bta_gattc_act.cc
@@ -34,7 +34,6 @@
#include "bta/gatt/bta_gattc_int.h"
#include "bta/include/bta_api.h"
#include "btif/include/btif_debug_conn.h"
-#include "device/include/controller.h"
#include "hardware/bt_gatt_types.h"
#include "hci/controller_interface.h"
#include "include/check.h"
@@ -229,7 +228,8 @@
void bta_gattc_deregister(tBTA_GATTC_RCB* p_clreg) {
uint8_t accept_list_size = 0;
if (bluetooth::shim::GetController()->SupportsBle()) {
- accept_list_size = controller_get_interface()->get_ble_acceptlist_size();
+ accept_list_size =
+ bluetooth::shim::GetController()->GetLeFilterAcceptListSize();
}
/* remove bg connection associated with this rcb */
diff --git a/system/bta/gatt/bta_gattc_api.cc b/system/bta/gatt/bta_gattc_api.cc
index ea5d42d..048bc14 100644
--- a/system/bta/gatt/bta_gattc_api.cc
+++ b/system/bta/gatt/bta_gattc_api.cc
@@ -33,8 +33,6 @@
#include <vector>
#include "bta/gatt/bta_gattc_int.h"
-#include "device/include/controller.h"
-#include "internal_include/bt_target.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
@@ -136,7 +134,8 @@
******************************************************************************/
void BTA_GATTC_Open(tGATT_IF client_if, const RawAddress& remote_bda,
tBTM_BLE_CONN_TYPE connection_type, bool opportunistic) {
- uint8_t phy = controller_get_interface()->get_le_all_initiating_phys();
+ constexpr uint8_t kPhyLe1M = 0x01; // From the old controller shim.
+ uint8_t phy = kPhyLe1M;
BTA_GATTC_Open(client_if, remote_bda, connection_type, BT_TRANSPORT_LE,
opportunistic, phy);
}
diff --git a/system/bta/gatt/bta_gattc_utils.cc b/system/bta/gatt/bta_gattc_utils.cc
index 0db0f41..b10cea7 100644
--- a/system/bta/gatt/bta_gattc_utils.cc
+++ b/system/bta/gatt/bta_gattc_utils.cc
@@ -31,7 +31,6 @@
#include "bta/gatt/bta_gattc_int.h"
#include "common/init_flags.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
@@ -45,11 +44,10 @@
using namespace bluetooth;
static uint8_t ble_acceptlist_size() {
- const controller_t* controller = controller_get_interface();
if (!bluetooth::shim::GetController()->SupportsBle()) {
return 0;
}
- return controller->get_ble_acceptlist_size();
+ return bluetooth::shim::GetController()->GetLeFilterAcceptListSize();
}
/*******************************************************************************
diff --git a/system/bta/has/has_client_test.cc b/system/bta/has/has_client_test.cc
index 2f550aa..78ee07c 100644
--- a/system/bta/has/has_client_test.cc
+++ b/system/bta/has/has_client_test.cc
@@ -36,7 +36,6 @@
#include "gatt/database_builder.h"
#include "hardware/bt_gatt_types.h"
#include "has_types.h"
-#include "mock_controller.h"
#include "mock_csis_client.h"
#include "stack/include/bt_uuid16.h"
#include "test/common/mock_functions.h"
@@ -656,7 +655,6 @@
void SetUp(void) override {
reset_mock_function_count_map();
- controller::SetMockControllerInterface(&controller_interface_);
bluetooth::manager::SetMockBtmInterface(&btm_interface);
bluetooth::storage::SetMockBtifStorageInterface(&btif_storage_interface_);
gatt::SetMockBtaGattInterface(&gatt_interface);
@@ -761,7 +759,6 @@
gatt::SetMockBtaGattInterface(nullptr);
bluetooth::storage::SetMockBtifStorageInterface(nullptr);
bluetooth::manager::SetMockBtmInterface(nullptr);
- controller::SetMockControllerInterface(nullptr);
callbacks.reset();
current_peer_active_preset_idx_.clear();
@@ -1172,7 +1169,6 @@
std::unique_ptr<MockHasCallbacks> callbacks;
bluetooth::manager::MockBtmInterface btm_interface;
bluetooth::storage::MockBtifStorageInterface btif_storage_interface_;
- controller::MockControllerInterface controller_interface_;
gatt::MockBtaGattInterface gatt_interface;
gatt::MockBtaGattQueue gatt_queue;
MockCsisClient mock_csis_client_module_;
diff --git a/system/bta/hh/bta_hh_le.cc b/system/bta/hh/bta_hh_le.cc
index 39022d6..f3f8efd 100644
--- a/system/bta/hh/bta_hh_le.cc
+++ b/system/bta/hh/bta_hh_le.cc
@@ -2306,7 +2306,7 @@
uint16_t cis_conn_hdl, uint8_t* data,
uint16_t size, uint32_t timestamp) {
if (!IS_FLAG_ENABLED(leaudio_dynamic_spatial_audio)) {
- LOG_WARN("DSA not supported");
+ log::warn("DSA not supported");
return false;
}
@@ -2316,7 +2316,7 @@
tBTA_HH_DEV_CB* p_dev_cb = bta_hh_le_find_dev_cb_by_bda(link_spec);
if (p_dev_cb == nullptr) {
- LOG_WARN("Device not connected: %s", ADDRESS_TO_LOGGABLE_CSTR(link_spec));
+ log::warn("Device not connected: {}", ADDRESS_TO_LOGGABLE_CSTR(link_spec));
return false;
}
diff --git a/system/bta/include/bta_api.h b/system/bta/include/bta_api.h
index af4f433..57148f2 100644
--- a/system/bta/include/bta_api.h
+++ b/system/bta/include/bta_api.h
@@ -224,6 +224,7 @@
BTA_DM_DID_RES_EVT = 6, /* Vendor/Product ID search result */
BTA_DM_GATT_OVER_SDP_RES_EVT = 7, /* GATT services over SDP discovered */
BTA_DM_NAME_READ_EVT = 8, /* Name read complete. */
+ BTA_DM_OBSERVE_CMPL_EVT = 9, /* Observe complete. */
} tBTA_DM_SEARCH_EVT;
inline std::string bta_dm_search_evt_text(const tBTA_DM_SEARCH_EVT& event) {
@@ -237,6 +238,7 @@
CASE_RETURN_TEXT(BTA_DM_DID_RES_EVT);
CASE_RETURN_TEXT(BTA_DM_GATT_OVER_SDP_RES_EVT);
CASE_RETURN_TEXT(BTA_DM_NAME_READ_EVT);
+ CASE_RETURN_TEXT(BTA_DM_OBSERVE_CMPL_EVT);
default:
return base::StringPrintf("UNKNOWN[%hhu]", event);
}
@@ -270,10 +272,10 @@
uint16_t clock_offset;
} tBTA_DM_INQ_RES;
-/* Structure associated with BTA_DM_INQ_CMPL_EVT */
+/* Structure associated with BTA_DM_OBSERVE_CMPL_EVT */
typedef struct {
- uint8_t num_resps; /* Number of inquiry responses. */
-} tBTA_DM_INQ_CMPL;
+ uint8_t num_resps; /* Number of responses. */
+} tBTA_DM_OBSERVE_CMPL;
/* Structure associated with BTA_DM_DISC_RES_EVT */
typedef struct {
@@ -307,11 +309,11 @@
/* Union of all search callback structures */
typedef union {
tBTA_DM_INQ_RES inq_res; /* Inquiry result for a peer device. */
- tBTA_DM_INQ_CMPL inq_cmpl; /* Inquiry complete. */
tBTA_DM_DISC_RES disc_res; /* Discovery result for a peer device. */
tBTA_DM_DISC_BLE_RES
disc_ble_res; /* discovery result for GATT based service */
tBTA_DM_DID_RES did_res; /* Vendor and Product ID of peer device */
+ tBTA_DM_OBSERVE_CMPL observe_cmpl; /* Observe complete. */
} tBTA_DM_SEARCH;
/* Search callback */
@@ -677,28 +679,9 @@
/*******************************************************************************
*
- * Function BTA_DmBleObserve
- *
- * Description This procedure keep the device listening for advertising
- * events from a broadcast device.
- *
- * Parameters start: start or stop observe.
- * duration : Duration of the scan. Continuous scan if 0 is
- * passed
- * p_results_cb: Callback to be called with scan results
- *
- * Returns void
- *
- ******************************************************************************/
-void BTA_DmBleObserve(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_results_cb);
-
-/*******************************************************************************
- *
* Function BTA_DmBleScan
*
- * Description Start or stop the scan procedure if it's not already started
- * with BTA_DmBleObserve().
+ * Description Start or stop the scan procedure.
*
* Parameters start: start or stop the scan procedure,
* duration_sec: Duration of the scan. Continuous scan if 0 is
diff --git a/system/bta/include/bta_sec_api.h b/system/bta/include/bta_sec_api.h
index 9b3ae1f..6123aed 100644
--- a/system/bta/include/bta_sec_api.h
+++ b/system/bta/include/bta_sec_api.h
@@ -337,9 +337,8 @@
* Returns void
*
******************************************************************************/
-void BTA_DmAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class,
- const LinkKey& link_key, uint8_t key_type,
- uint8_t pin_length);
+void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key,
+ uint8_t key_type, uint8_t pin_length);
/*******************************************************************************
*
diff --git a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc
index ac6098e..134e1c1 100644
--- a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc
+++ b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc
@@ -18,6 +18,7 @@
#include "audio_hal_client.h"
+#include <bluetooth/log.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -48,6 +49,8 @@
using bluetooth::le_audio::LeAudioSinkAudioHalClient;
using bluetooth::le_audio::LeAudioSourceAudioHalClient;
+using namespace bluetooth;
+
bluetooth::common::MessageLoopThread message_loop_thread("test message loop");
bluetooth::common::MessageLoopThread* get_main_thread() {
return &message_loop_thread;
@@ -55,7 +58,7 @@
bt_status_t do_in_main_thread(const base::Location& from_here,
base::OnceClosure task) {
if (!message_loop_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;
@@ -71,7 +74,7 @@
}
if (!message_loop_thread.EnableRealTimeScheduling())
- LOG(ERROR) << "Unable to set real time scheduling";
+ log::error("Unable to set real time scheduling");
message_loop_ = message_loop_thread.message_loop();
if (message_loop_ == nullptr) FAIL() << "unable to get message loop.";
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 a6a67bb..4b8ad5a 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
@@ -18,6 +18,8 @@
*
******************************************************************************/
+#include <bluetooth/log.h>
+
#include "audio_hal_client.h"
#include "audio_hal_interface/le_audio_software.h"
#include "bta/le_audio/codec_manager.h"
@@ -79,7 +81,7 @@
auto halInterface = audio::le_audio::LeAudioClientInterface::Get();
if (halInterface == nullptr) {
- LOG_ERROR("Can't get LE Audio HAL interface");
+ log::error("Can't get LE Audio HAL interface");
return false;
}
@@ -87,7 +89,7 @@
halInterface->GetSource(source_stream_cb, get_main_thread());
if (halSourceInterface_ == nullptr) {
- LOG_ERROR("Can't get Audio HAL Audio source interface");
+ log::error("Can't get Audio HAL Audio source interface");
return false;
}
@@ -98,7 +100,7 @@
void SinkImpl::Release() {
if (le_audio_source_hal_state == HAL_UNINITIALIZED) {
- LOG_WARN("Audio HAL Audio source is not running");
+ log::warn("Audio HAL Audio source is not running");
return;
}
@@ -110,7 +112,7 @@
if (halInterface != nullptr) {
halInterface->ReleaseSource(halSourceInterface_);
} else {
- LOG_ERROR("Can't get LE Audio HAL interface");
+ log::error("Can't get LE Audio HAL interface");
}
le_audio_source_hal_state = HAL_UNINITIALIZED;
@@ -120,7 +122,7 @@
bool SinkImpl::OnResumeReq(bool start_media_task) {
if (audioSinkCallbacks_ == nullptr) {
- LOG_ERROR("audioSinkCallbacks_ not set");
+ log::error("audioSinkCallbacks_ not set");
return false;
}
@@ -132,13 +134,13 @@
return true;
}
- LOG_ERROR("do_in_main_thread err=%d", status);
+ log::error("do_in_main_thread err={}", status);
return false;
}
bool SinkImpl::OnSuspendReq() {
if (audioSinkCallbacks_ == nullptr) {
- LOG_ERROR("audioSinkCallbacks_ not set");
+ log::error("audioSinkCallbacks_ not set");
return false;
}
@@ -150,13 +152,13 @@
return true;
}
- LOG_ERROR("do_in_main_thread err=%d", status);
+ log::error("do_in_main_thread err={}", status);
return false;
}
bool SinkImpl::OnMetadataUpdateReq(const sink_metadata_v7_t& sink_metadata) {
if (audioSinkCallbacks_ == nullptr) {
- LOG_ERROR("audioSinkCallbacks_ not set");
+ log::error("audioSinkCallbacks_ not set");
return false;
}
@@ -169,7 +171,7 @@
return true;
}
- LOG_ERROR("do_in_main_thread err=%d", status);
+ log::error("do_in_main_thread err={}", status);
return false;
}
@@ -177,19 +179,19 @@
LeAudioSinkAudioHalClient::Callbacks* audioReceiver,
DsaModes dsa_modes) {
if (!halSourceInterface_) {
- LOG_ERROR("Audio HAL Audio source interface not acquired");
+ log::error("Audio HAL Audio source interface not acquired");
return false;
}
if (le_audio_source_hal_state == HAL_STARTED) {
- LOG_ERROR("Audio HAL Audio source is already in use");
+ log::error("Audio HAL Audio source is already in use");
return false;
}
- LOG_INFO("bit rate: %d, num channels: %d, sample rate: %d, data interval: %d",
- codec_configuration.bits_per_sample,
- codec_configuration.num_channels, codec_configuration.sample_rate,
- codec_configuration.data_interval_us);
+ log::info(
+ "bit rate: {}, num channels: {}, sample rate: {}, data interval: {}",
+ codec_configuration.bits_per_sample, codec_configuration.num_channels,
+ codec_configuration.sample_rate, codec_configuration.data_interval_us);
audio::le_audio::LeAudioClientInterface::PcmParameters pcmParameters = {
.data_interval_us = codec_configuration.data_interval_us,
@@ -208,12 +210,12 @@
void SinkImpl::Stop() {
if (!halSourceInterface_) {
- LOG_ERROR("Audio HAL Audio source interface already stopped");
+ log::error("Audio HAL Audio source interface already stopped");
return;
}
if (le_audio_source_hal_state != HAL_STARTED) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -227,20 +229,20 @@
size_t SinkImpl::SendData(uint8_t* data, uint16_t size) {
size_t bytes_written;
if (!halSourceInterface_) {
- LOG_ERROR("Audio HAL Audio source interface not initialized");
+ log::error("Audio HAL Audio source interface not initialized");
return 0;
}
if (le_audio_source_hal_state != HAL_STARTED) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return 0;
}
/* TODO: What to do if not all data is written ? */
bytes_written = halSourceInterface_->Write(data, size);
if (bytes_written != size) {
- LOG_ERROR(
- "Not all data is written to source HAL. Bytes written: %zu, total: %d",
+ log::error(
+ "Not all data is written to source HAL. Bytes written: {}, total: {}",
bytes_written, size);
}
@@ -250,7 +252,7 @@
void SinkImpl::ConfirmStreamingRequest() {
if ((halSourceInterface_ == nullptr) ||
(le_audio_source_hal_state != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -265,7 +267,7 @@
void SinkImpl::SuspendedForReconfiguration() {
if ((halSourceInterface_ == nullptr) ||
(le_audio_source_hal_state != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -276,7 +278,7 @@
void SinkImpl::ReconfigurationComplete() {
if ((halSourceInterface_ == nullptr) ||
(le_audio_source_hal_state != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -287,7 +289,7 @@
void SinkImpl::CancelStreamingRequest() {
if ((halSourceInterface_ == nullptr) ||
(le_audio_source_hal_state != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -302,7 +304,7 @@
void SinkImpl::UpdateRemoteDelay(uint16_t remote_delay_ms) {
if ((halSourceInterface_ == nullptr) ||
(le_audio_source_hal_state != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -314,7 +316,7 @@
const ::bluetooth::le_audio::offload_config& config) {
if ((halSourceInterface_ == nullptr) ||
(le_audio_source_hal_state != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio source was not started!");
+ log::error("Audio HAL Audio source was not started!");
return;
}
@@ -327,7 +329,7 @@
LeAudioSinkAudioHalClient::AcquireUnicast() {
std::unique_ptr<SinkImpl> impl(new SinkImpl());
if (!impl->Acquire()) {
- LOG_ERROR("Could not acquire Unicast Sink on LE Audio HAL enpoint");
+ log::error("Could not acquire Unicast Sink on LE Audio HAL enpoint");
impl.reset();
return nullptr;
}
diff --git a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc
index 25ffd1c..d9398da 100644
--- a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc
+++ b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc
@@ -20,6 +20,7 @@
#include <android_bluetooth_flags.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "audio/asrc/asrc_resampler.h"
#include "audio_hal_client.h"
@@ -121,7 +122,7 @@
/* Get pointer to singleton LE audio client interface */
auto halInterface = audio::le_audio::LeAudioClientInterface::Get();
if (halInterface == nullptr) {
- LOG_ERROR("Can't get LE Audio HAL interface");
+ log::error("Can't get LE Audio HAL interface");
return false;
}
@@ -129,7 +130,7 @@
halInterface->GetSink(sink_stream_cb, get_main_thread(), is_broadcaster_);
if (halSinkInterface_ == nullptr) {
- LOG_ERROR("Can't get Audio HAL Audio sink interface");
+ log::error("Can't get Audio HAL Audio sink interface");
return false;
}
@@ -140,7 +141,7 @@
void SourceImpl::Release() {
if (le_audio_sink_hal_state_ == HAL_UNINITIALIZED) {
- LOG_WARN("Audio HAL Audio sink is not running");
+ log::warn("Audio HAL Audio sink is not running");
return;
}
@@ -154,7 +155,7 @@
if (halInterface != nullptr) {
halInterface->ReleaseSink(halSinkInterface_);
} else {
- LOG_ERROR("Can't get LE Audio HAL interface");
+ log::error("Can't get LE Audio HAL interface");
}
le_audio_sink_hal_state_ = HAL_UNINITIALIZED;
@@ -165,7 +166,7 @@
bool SourceImpl::OnResumeReq(bool start_media_task) {
std::lock_guard<std::mutex> guard(audioSourceCallbacksMutex_);
if (audioSourceCallbacks_ == nullptr) {
- LOG_ERROR("audioSourceCallbacks_ not set");
+ log::error("audioSourceCallbacks_ not set");
return false;
}
bt_status_t status = do_in_main_thread(
@@ -176,13 +177,13 @@
return true;
}
- LOG_ERROR("do_in_main_thread err=%d", status);
+ log::error("do_in_main_thread err={}", status);
return false;
}
void SourceImpl::SendAudioData() {
if (halSinkInterface_ == nullptr) {
- LOG_ERROR("Audio HAL Audio sink interface not acquired - aborting");
+ log::error("Audio HAL Audio sink interface not acquired - aborting");
return;
}
@@ -229,14 +230,14 @@
worker_thread_->StartUp();
if (!worker_thread_->IsRunning()) {
- LOG_ERROR("Unable to start up the BLE audio sink worker thread");
+ log::error("Unable to start up the BLE audio sink worker thread");
return false;
}
/* Schedule the rest of the operations */
if (!worker_thread_->EnableRealTimeScheduling()) {
#if defined(__ANDROID__)
- LOG(FATAL) << __func__ << ", Failed to increase media thread priority";
+ log::fatal("Failed to increase media thread priority");
#endif
}
@@ -277,7 +278,7 @@
}
if (audioSourceCallbacks_ == nullptr) {
- LOG_ERROR("audioSourceCallbacks_ not set");
+ log::error("audioSourceCallbacks_ not set");
return false;
}
@@ -289,7 +290,7 @@
return true;
}
- LOG_ERROR("do_in_main_thread err=%d", status);
+ log::error("do_in_main_thread err={}", status);
return false;
}
@@ -297,7 +298,7 @@
const source_metadata_v7_t& source_metadata, DsaMode dsa_mode) {
std::lock_guard<std::mutex> guard(audioSourceCallbacksMutex_);
if (audioSourceCallbacks_ == nullptr) {
- LOG(ERROR) << __func__ << ", audio receiver not started";
+ log::error("audio receiver not started");
return false;
}
@@ -311,7 +312,7 @@
return true;
}
- LOG_ERROR("do_in_main_thread err=%d", status);
+ log::error("do_in_main_thread err={}", status);
return false;
}
@@ -319,19 +320,19 @@
LeAudioSourceAudioHalClient::Callbacks* audioReceiver,
DsaModes dsa_modes) {
if (!halSinkInterface_) {
- LOG_ERROR("Audio HAL Audio sink interface not acquired");
+ log::error("Audio HAL Audio sink interface not acquired");
return false;
}
if (le_audio_sink_hal_state_ == HAL_STARTED) {
- LOG_ERROR("Audio HAL Audio sink is already in use");
+ log::error("Audio HAL Audio sink is already in use");
return false;
}
- LOG_INFO("bit rate: %d, num channels: %d, sample rate: %d, data interval: %d",
- codec_configuration.bits_per_sample,
- codec_configuration.num_channels, codec_configuration.sample_rate,
- codec_configuration.data_interval_us);
+ log::info(
+ "bit rate: {}, num channels: {}, sample rate: {}, data interval: {}",
+ codec_configuration.bits_per_sample, codec_configuration.num_channels,
+ codec_configuration.sample_rate, codec_configuration.data_interval_us);
sStats.Reset();
@@ -355,12 +356,12 @@
void SourceImpl::Stop() {
if (!halSinkInterface_) {
- LOG_ERROR("Audio HAL Audio sink interface already stopped");
+ log::error("Audio HAL Audio sink interface already stopped");
return;
}
if (le_audio_sink_hal_state_ != HAL_STARTED) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -387,7 +388,7 @@
void SourceImpl::ConfirmStreamingRequest() {
if ((halSinkInterface_ == nullptr) ||
(le_audio_sink_hal_state_ != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -413,7 +414,7 @@
void SourceImpl::SuspendedForReconfiguration() {
if ((halSinkInterface_ == nullptr) ||
(le_audio_sink_hal_state_ != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -424,7 +425,7 @@
void SourceImpl::ReconfigurationComplete() {
if ((halSinkInterface_ == nullptr) ||
(le_audio_sink_hal_state_ != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -435,7 +436,7 @@
void SourceImpl::CancelStreamingRequest() {
if ((halSinkInterface_ == nullptr) ||
(le_audio_sink_hal_state_ != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -450,7 +451,7 @@
void SourceImpl::UpdateRemoteDelay(uint16_t remote_delay_ms) {
if ((halSinkInterface_ == nullptr) ||
(le_audio_sink_hal_state_ != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -462,7 +463,7 @@
const ::bluetooth::le_audio::offload_config& config) {
if ((halSinkInterface_ == nullptr) ||
(le_audio_sink_hal_state_ != HAL_STARTED)) {
- LOG_ERROR("Audio HAL Audio sink was not started!");
+ log::error("Audio HAL Audio sink was not started!");
return;
}
@@ -473,7 +474,7 @@
void SourceImpl::UpdateBroadcastAudioConfigToHal(
const ::bluetooth::le_audio::broadcast_offload_config& config) {
if (halSinkInterface_ == nullptr) {
- LOG_ERROR("Audio HAL Audio sink interface not acquired");
+ log::error("Audio HAL Audio sink interface not acquired");
return;
}
@@ -486,7 +487,7 @@
LeAudioSourceAudioHalClient::AcquireUnicast() {
std::unique_ptr<SourceImpl> impl(new SourceImpl(false));
if (!impl->Acquire()) {
- LOG_ERROR("Could not acquire Unicast Source on LE Audio HAL enpoint");
+ log::error("Could not acquire Unicast Source on LE Audio HAL enpoint");
impl.reset();
return nullptr;
}
@@ -499,7 +500,7 @@
LeAudioSourceAudioHalClient::AcquireBroadcast() {
std::unique_ptr<SourceImpl> impl(new SourceImpl(true));
if (!impl->Acquire()) {
- LOG_ERROR("Could not acquire Broadcast Source on LE Audio HAL enpoint");
+ log::error("Could not acquire Broadcast Source on LE Audio HAL enpoint");
impl.reset();
return nullptr;
}
diff --git a/system/bta/le_audio/broadcaster/broadcaster.cc b/system/bta/le_audio/broadcaster/broadcaster.cc
index dfbd212..02a8554 100644
--- a/system/bta/le_audio/broadcaster/broadcaster.cc
+++ b/system/bta/le_audio/broadcaster/broadcaster.cc
@@ -17,6 +17,7 @@
#include <base/functional/bind.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include <mutex>
@@ -68,6 +69,8 @@
using bluetooth::le_audio::types::LeAudioLtvMap;
using bluetooth::le_audio::utils::GetAudioContextsFromSourceMetadata;
+using namespace bluetooth;
+
namespace {
class LeAudioBroadcasterImpl;
LeAudioBroadcasterImpl* instance;
@@ -121,13 +124,13 @@
}
if (instance->available_broadcast_ids_.empty()) {
- LOG_ALWAYS_FATAL("Unable to generate proper broadcast identifiers.");
+ log::fatal("Unable to generate proper broadcast identifiers.");
}
}));
}
void CleanUp() {
- LOG_INFO("Broadcaster");
+ log::info("Broadcaster");
broadcasts_.clear();
callbacks_ = nullptr;
is_iso_running_ = false;
@@ -145,7 +148,7 @@
}
void Stop() {
- LOG_INFO("Broadcaster");
+ log::info("Broadcaster");
for (auto& sm_pair : broadcasts_) {
StopAudioBroadcast(sm_pair.first);
@@ -249,12 +252,12 @@
}
void UpdateStreamingContextTypeOnAllSubgroups(const AudioContexts& contexts) {
- LOG_DEBUG("%s context_type_map=%s", __func__, contexts.to_string().c_str());
+ log::debug("context_type_map={}", contexts.to_string());
auto ccids = ContentControlIdKeeper::GetInstance()->GetAllCcids(contexts);
if (ccids.empty()) {
- LOG_WARN("%s No content providers available for context_type_map=%s.",
- __func__, contexts.to_string().c_str());
+ log::warn("No content providers available for context_type_map={}.",
+ contexts.to_string());
}
std::vector<uint8_t> stream_context_vec(2);
@@ -332,18 +335,18 @@
std::vector<LeAudioLtvMap> subgroup_ltvs;
if (broadcasts_.count(broadcast_id) == 0) {
- LOG_ERROR("No such broadcast_id=%d", broadcast_id);
+ log::error("No such broadcast_id={}", broadcast_id);
return;
}
- LOG_INFO("For broadcast_id=%d", broadcast_id);
+ log::info("For broadcast_id={}", broadcast_id);
for (const std::vector<uint8_t>& metadata : subgroup_metadata) {
/* Prepare the announcement format */
bool is_metadata_valid;
auto ltv = LeAudioLtvMap::Parse(metadata.data(), metadata.size(), is_metadata_valid);
if (!is_metadata_valid) {
- LOG_ERROR("Invalid metadata provided.");
+ log::error("Invalid metadata provided.");
return;
}
@@ -364,7 +367,7 @@
if (stream_context_vec) {
auto pp = stream_context_vec.value().data();
if (stream_context_vec.value().size() < 2) {
- LOG_ERROR("stream_context_vec.value() size < 2");
+ log::error("stream_context_vec.value() size < 2");
return;
}
UINT16_TO_STREAM(pp, context_type.value());
@@ -377,7 +380,7 @@
if (stream_context_vec) {
auto pp = stream_context_vec.value().data();
if (stream_context_vec.value().size() < 2) {
- LOG_ERROR("stream_context_vec.value() size < 2");
+ log::error("stream_context_vec.value() size < 2");
return;
}
STREAM_TO_UINT16(context_type.value_ref(), pp);
@@ -403,7 +406,7 @@
LeAudioLtvMap::Parse(public_metadata.data(), public_metadata.size(),
is_public_metadata_valid);
if (!is_public_metadata_valid) {
- LOG_ERROR("Invalid public metadata provided.");
+ log::error("Invalid public metadata provided.");
return;
}
PublicBroadcastAnnouncementData pb_announcement =
@@ -464,7 +467,7 @@
std::vector<LeAudioLtvMap> subgroup_ltvs;
if (queued_create_broadcast_request_) {
- LOG_ERROR("Not processed yet queued broadcast");
+ log::error("Not processed yet queued broadcast");
callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
false);
return;
@@ -476,7 +479,7 @@
public_ltv = LeAudioLtvMap::Parse(
public_metadata.data(), public_metadata.size(), is_metadata_valid);
if (!is_metadata_valid) {
- LOG_ERROR("Invalid metadata provided.");
+ log::error("Invalid metadata provided.");
callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
false);
return;
@@ -519,7 +522,7 @@
bool is_metadata_valid;
auto ltv = LeAudioLtvMap::Parse(metadata.data(), metadata.size(), is_metadata_valid);
if (!is_metadata_valid) {
- LOG_ERROR("Invalid metadata provided.");
+ log::error("Invalid metadata provided.");
callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
false);
return;
@@ -532,7 +535,7 @@
kLeAudioMetadataTypeStreamingAudioContext);
if (stream_context_vec) {
if (stream_context_vec.value().size() < 2) {
- LOG_ERROR("kLeAudioMetadataTypeStreamingAudioContext size < 2");
+ log::error("kLeAudioMetadataTypeStreamingAudioContext size < 2");
callbacks_->OnBroadcastCreated(
bluetooth::le_audio::kBroadcastIdInvalid, false);
return;
@@ -547,7 +550,7 @@
kLeAudioMetadataTypeStreamingAudioContext);
if (stream_context_vec) {
if (stream_context_vec.value().size() < 2) {
- LOG_ERROR("kLeAudioMetadataTypeStreamingAudioContext size < 2");
+ log::error("kLeAudioMetadataTypeStreamingAudioContext size < 2");
callbacks_->OnBroadcastCreated(
bluetooth::le_audio::kBroadcastIdInvalid, false);
return;
@@ -584,7 +587,7 @@
subgroup_requirements, std::nullopt);
if (!config) {
- LOG_ERROR("No valid broadcast offload config");
+ log::error("No valid broadcast offload config");
callbacks_->OnBroadcastCreated(bluetooth::le_audio::kBroadcastIdInvalid,
false);
return;
@@ -615,9 +618,9 @@
// 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.");
+ log::info("Iso is still active. Queueing broadcast creation for later.");
if (queued_create_broadcast_request_) {
- LOG_WARN(
+ log::warn(
"Already queued. Updating queued broadcast creation with the new "
"configuration.");
}
@@ -629,7 +632,7 @@
}
void InstantiateBroadcast(BroadcastStateMachineConfig msg) {
- LOG_INFO("CreateAudioBroadcast");
+ log::info("CreateAudioBroadcast");
/* Put the new broadcast on the initialization queue, notify the error and
* drop the pending broadcast data if init fails.
@@ -644,16 +647,16 @@
}
void SuspendAudioBroadcast(uint32_t broadcast_id) override {
- LOG_INFO("broadcast_id=%d", broadcast_id);
+ log::info("broadcast_id={}", broadcast_id);
if (broadcasts_.count(broadcast_id) != 0) {
- LOG_INFO("Stopping AudioHalClient");
+ log::info("Stopping AudioHalClient");
if (le_audio_source_hal_client_) le_audio_source_hal_client_->Stop();
broadcasts_[broadcast_id]->SetMuted(true);
broadcasts_[broadcast_id]->ProcessMessage(
BroadcastStateMachine::Message::SUSPEND, nullptr);
} else {
- LOG_ERROR("No such broadcast_id=%d", broadcast_id);
+ log::error("No such broadcast_id={}", broadcast_id);
}
}
@@ -670,10 +673,10 @@
}
void StartAudioBroadcast(uint32_t broadcast_id) override {
- LOG_INFO("Starting broadcast_id=%d", broadcast_id);
+ log::info("Starting broadcast_id={}", broadcast_id);
if (queued_start_broadcast_request_) {
- LOG_ERROR("Not processed yet start broadcast request");
+ log::error("Not processed yet start broadcast request");
return;
}
@@ -683,7 +686,7 @@
}
if (IsAnyoneStreaming()) {
- LOG_ERROR("Stop the other broadcast first!");
+ log::error("Stop the other broadcast first!");
return;
}
@@ -692,7 +695,7 @@
le_audio_source_hal_client_ =
LeAudioSourceAudioHalClient::AcquireBroadcast();
if (!le_audio_source_hal_client_) {
- LOG_ERROR("Could not acquire le audio");
+ log::error("Could not acquire le audio");
return;
}
}
@@ -702,17 +705,17 @@
bluetooth::le_audio::MetricsCollector::Get()->OnBroadcastStateChanged(
true);
} else {
- LOG_ERROR("No such broadcast_id=%d", broadcast_id);
+ log::error("No such broadcast_id={}", broadcast_id);
}
}
void StopAudioBroadcast(uint32_t broadcast_id) override {
if (broadcasts_.count(broadcast_id) == 0) {
- LOG_ERROR("no such broadcast_id=%d", broadcast_id);
+ log::error("no such broadcast_id={}", broadcast_id);
return;
}
- LOG_INFO("Stopping AudioHalClient, broadcast_id=%d", broadcast_id);
+ log::info("Stopping AudioHalClient, broadcast_id={}", broadcast_id);
if (le_audio_source_hal_client_) le_audio_source_hal_client_->Stop();
broadcasts_[broadcast_id]->SetMuted(true);
@@ -723,7 +726,7 @@
}
void DestroyAudioBroadcast(uint32_t broadcast_id) override {
- LOG_INFO("Destroying broadcast_id=%d", broadcast_id);
+ log::info("Destroying broadcast_id={}", broadcast_id);
broadcasts_.erase(broadcast_id);
}
@@ -752,13 +755,13 @@
void GetBroadcastMetadata(uint32_t broadcast_id) override {
if (broadcasts_.count(broadcast_id) == 0) {
- LOG_ERROR("No such broadcast_id=%d", broadcast_id);
+ log::error("No such broadcast_id={}", broadcast_id);
return;
}
auto meta = GetBroadcastMetadataOpt(broadcast_id);
if (!meta) {
- LOG_ERROR("No metadata for broadcast_id=%d", broadcast_id);
+ log::error("No metadata for broadcast_id={}", broadcast_id);
return;
}
callbacks_->OnBroadcastMetadataChanged(broadcast_id,
@@ -780,7 +783,7 @@
RawAddress /* addr */, bool /* is_local */)>
cb) override {
if (broadcasts_.count(broadcast_id) == 0) {
- LOG_ERROR("No such broadcast_id=%d", broadcast_id);
+ log::error("No such broadcast_id={}", broadcast_id);
std::move(cb).Run(broadcast_id, addr_type, addr, false);
return;
}
@@ -850,26 +853,26 @@
le_audio_source_hal_client_.reset();
} break;
default:
- LOG_ERROR("Invalid event=%d", event);
+ log::error("Invalid event={}", event);
}
}
void IsoTrafficEventCb(bool is_active) {
is_iso_running_ = is_active;
- LOG_INFO("is_iso_running: %d", is_iso_running_);
+ log::info("is_iso_running: {}", is_iso_running_);
if (!is_iso_running_) {
if (queued_start_broadcast_request_) {
auto broadcast_id = *queued_start_broadcast_request_;
queued_start_broadcast_request_ = std::nullopt;
- LOG_INFO("Start queued broadcast.");
+ 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.");
+ log::info("Create queued broadcast.");
InstantiateBroadcast(std::move(broadcast_msg));
}
}
@@ -902,12 +905,12 @@
if (initialized) {
const uint32_t broadcast_id = (*pending_broadcast)->GetBroadcastId();
- LOG_INFO("broadcast_id=%d state=%s", broadcast_id,
- ToString((*pending_broadcast)->GetState()).c_str());
+ log::info("broadcast_id={} state={}", broadcast_id,
+ ToString((*pending_broadcast)->GetState()));
instance->broadcasts_[broadcast_id] = std::move(*pending_broadcast);
} else {
- LOG_ERROR("Failed creating broadcast!");
+ log::error("Failed creating broadcast!");
}
instance->pending_broadcasts_.erase(pending_broadcast);
instance->callbacks_->OnBroadcastCreated(broadcast_id, initialized);
@@ -925,10 +928,9 @@
static int getStreamerCount() {
return std::count_if(instance->broadcasts_.begin(),
instance->broadcasts_.end(), [](auto const& sm) {
- LOG_VERBOSE(
- "broadcast_id=%d, state=%s",
- sm.second->GetBroadcastId(),
- ToString(sm.second->GetState()).c_str());
+ log::verbose("broadcast_id={}, state={}",
+ sm.second->GetBroadcastId(),
+ ToString(sm.second->GetState()));
return sm.second->GetState() ==
BroadcastStateMachine::State::STREAMING;
});
@@ -937,8 +939,7 @@
void OnStateMachineEvent(uint32_t broadcast_id,
BroadcastStateMachine::State state,
const void* data) override {
- LOG_INFO("broadcast_id=%d state=%s", broadcast_id,
- ToString(state).c_str());
+ log::info("broadcast_id={} state={}", broadcast_id, ToString(state));
switch (state) {
case BroadcastStateMachine::State::STOPPED:
@@ -952,7 +953,7 @@
break;
case BroadcastStateMachine::State::STREAMING:
if (getStreamerCount() == 1) {
- LOG_INFO("Starting AudioHalClient");
+ log::info("Starting AudioHalClient");
if (instance->broadcasts_.count(broadcast_id) != 0) {
const auto& broadcast = instance->broadcasts_.at(broadcast_id);
@@ -1006,9 +1007,9 @@
instance->pending_broadcasts_.back()->OnCreateAnnouncement(
advertiser_id, tx_power, status);
} else {
- LOG_WARN(
- "Ignored OnAdvertisingSetStarted callback reg_id:%d "
- "advertiser_id:%d",
+ log::warn(
+ "Ignored OnAdvertisingSetStarted callback reg_id:{} "
+ "advertiser_id:{}",
reg_id, advertiser_id);
}
}
@@ -1025,60 +1026,60 @@
if (iter != instance->broadcasts_.cend()) {
iter->second->OnEnableAnnouncement(enable, status);
} else {
- LOG_WARN("Ignored OnAdvertisingEnabled callback advertiser_id:%d",
- advertiser_id);
+ log::warn("Ignored OnAdvertisingEnabled callback advertiser_id:{}",
+ advertiser_id);
}
}
void OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) {
- LOG_WARN(
+ log::warn(
"Not being used, ignored OnAdvertisingDataSet callback "
- "advertiser_id:%d",
+ "advertiser_id:{}",
advertiser_id);
}
void OnScanResponseDataSet(uint8_t advertiser_id, uint8_t status) {
- LOG_WARN(
+ log::warn(
"Not being used, ignored OnScanResponseDataSet callback "
- "advertiser_id:%d",
+ "advertiser_id:{}",
advertiser_id);
}
void OnAdvertisingParametersUpdated(uint8_t advertiser_id, int8_t tx_power,
uint8_t status) {
- LOG_WARN(
+ log::warn(
"Not being used, ignored OnAdvertisingParametersUpdated callback "
- "advertiser_id:%d",
+ "advertiser_id:{}",
advertiser_id);
}
void OnPeriodicAdvertisingParametersUpdated(uint8_t advertiser_id,
uint8_t status) {
- LOG_WARN(
+ log::warn(
"Not being used, ignored OnPeriodicAdvertisingParametersUpdated "
- "callback advertiser_id:%d",
+ "callback advertiser_id:{}",
advertiser_id);
}
void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) {
- LOG_WARN(
+ log::warn(
"Not being used, ignored OnPeriodicAdvertisingDataSet callback "
- "advertiser_id:%d",
+ "advertiser_id:{}",
advertiser_id);
}
void OnPeriodicAdvertisingEnabled(uint8_t advertiser_id, bool enable,
uint8_t status) {
- LOG_WARN(
+ log::warn(
"Not being used, ignored OnPeriodicAdvertisingEnabled callback "
- "advertiser_id:%d",
+ "advertiser_id:{}",
advertiser_id);
}
void OnOwnAddressRead(uint8_t advertiser_id, uint8_t address_type,
RawAddress address) {
- LOG_WARN(
- "Not being used, ignored OnOwnAddressRead callback advertiser_id:%d",
+ log::warn(
+ "Not being used, ignored OnOwnAddressRead callback advertiser_id:{}",
advertiser_id);
}
} state_machine_adv_callbacks_;
@@ -1113,8 +1114,8 @@
auto codec_status = codec->InitEncoder(codec_config, codec_config);
if (codec_status !=
bluetooth::le_audio::CodecInterface::Status::STATUS_OK) {
- LOG_ERROR("Channel %d codec setup failed with err: %d",
- (uint32_t)sw_enc_.size(), codec_status);
+ log::error("Channel {} codec setup failed with err: {}",
+ (uint32_t)sw_enc_.size(), codec_status);
return;
}
@@ -1130,16 +1131,15 @@
encoders) {
auto const& config = broadcast->GetBigConfig();
if (config == std::nullopt) {
- LOG_ERROR(
- "Broadcast broadcast_id=%d has no valid BIS configurations in "
- "state=%s",
- broadcast->GetBroadcastId(),
- ToString(broadcast->GetState()).c_str());
+ log::error(
+ "Broadcast broadcast_id={} has no valid BIS configurations in "
+ "state={}",
+ broadcast->GetBroadcastId(), ToString(broadcast->GetState()));
return;
}
if (config->connection_handles.size() < encoders.size()) {
- LOG_ERROR("Not enough BIS'es to broadcast all channels!");
+ log::error("Not enough BIS'es to broadcast all channels!");
return;
}
@@ -1154,7 +1154,7 @@
virtual void OnAudioDataReady(const std::vector<uint8_t>& data) override {
if (!instance) return;
- LOG_VERBOSE("Received %zu bytes.", data.size());
+ log::verbose("Received {} bytes.", data.size());
if (!broadcast_config_.has_value() ||
(broadcast_config_->subgroups.size() == 0)) {
@@ -1191,7 +1191,7 @@
!broadcast->IsMuted())
sendBroadcastData(broadcast, sw_enc_);
}
- LOG_VERBOSE("All data sent.");
+ log::verbose("All data sent.");
}
virtual void OnAudioSuspend(void) override {
@@ -1270,18 +1270,18 @@
std::scoped_lock<std::mutex> lock(instance_mutex);
LOG_INFO();
if (instance) {
- LOG_ERROR("Already initialized");
+ log::error("Already initialized");
return;
}
if (!bluetooth::shim::GetController()->SupportsBleIsochronousBroadcaster() &&
!osi_property_get_bool("persist.bluetooth.fake_iso_support", false)) {
- LOG_WARN("Isochronous Broadcast not supported by the controller!");
+ log::warn("Isochronous Broadcast not supported by the controller!");
return;
}
if (!std::move(audio_hal_verifier).Run()) {
- LOG_ALWAYS_FATAL("HAL requirements not met. Init aborted.");
+ log::fatal("HAL requirements not met. Init aborted.");
}
IsoManager::GetInstance()->Start();
diff --git a/system/bta/le_audio/broadcaster/broadcaster_test.cc b/system/bta/le_audio/broadcaster/broadcaster_test.cc
index 767aeb7..40e05b4 100644
--- a/system/bta/le_audio/broadcaster/broadcaster_test.cc
+++ b/system/bta/le_audio/broadcaster/broadcaster_test.cc
@@ -15,6 +15,7 @@
* limitations under the License.
*/
+#include <bluetooth/log.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <hardware/audio.h>
@@ -29,7 +30,6 @@
#include "bta/le_audio/content_control_id_keeper.h"
#include "bta/le_audio/le_audio_types.h"
#include "bta/le_audio/mock_codec_manager.h"
-#include "bta/test/common/mock_controller.h"
#include "hci/controller_interface_mock.h"
#include "stack/include/btm_iso_api.h"
#include "test/common/mock_functions.h"
@@ -54,6 +54,7 @@
using testing::Test;
using namespace bluetooth::le_audio;
+using namespace bluetooth;
using bluetooth::le_audio::DsaMode;
using bluetooth::le_audio::LeAudioCodecConfiguration;
@@ -91,7 +92,7 @@
num_async_tasks--;
},
std::move(task), std::ref(num_async_tasks)))) {
- LOG(ERROR) << __func__ << ": failed from " << from_here.ToString();
+ log::error("failed from {}", from_here.ToString());
return BT_STATUS_FAIL;
}
num_async_tasks++;
@@ -109,7 +110,7 @@
}
if (!message_loop_thread.EnableRealTimeScheduling())
- LOG(ERROR) << "Unable to set real time scheduling";
+ log::error("Unable to set real time scheduling");
message_loop_ = message_loop_thread.message_loop();
if (message_loop_ == nullptr) FAIL() << "unable to get message loop.";
diff --git a/system/bta/le_audio/broadcaster/broadcaster_types.h b/system/bta/le_audio/broadcaster/broadcaster_types.h
index d67e04a..1b9a445 100644
--- a/system/bta/le_audio/broadcaster/broadcaster_types.h
+++ b/system/bta/le_audio/broadcaster/broadcaster_types.h
@@ -18,6 +18,7 @@
#pragma once
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <optional>
diff --git a/system/bta/le_audio/broadcaster/state_machine.cc b/system/bta/le_audio/broadcaster/state_machine.cc
index 1208753..de5bf78 100644
--- a/system/bta/le_audio/broadcaster/state_machine.cc
+++ b/system/bta/le_audio/broadcaster/state_machine.cc
@@ -18,6 +18,7 @@
#include "bta/le_audio/broadcaster/state_machine.h"
#include <bind_helpers.h>
+#include <bluetooth/log.h>
#include <functional>
#include <iostream>
@@ -43,6 +44,7 @@
using bluetooth::le_audio::types::CodecLocation;
using namespace bluetooth::le_audio::broadcaster;
+using namespace bluetooth;
namespace {
@@ -71,9 +73,9 @@
static constexpr uint8_t sNumBisMax = 31;
if (sm_config_.config.GetNumBisTotal() > sNumBisMax) {
- LOG_ERROR(
- "Channel count of %d exceeds the maximum number of possible BISes, "
- "which is %d",
+ log::error(
+ "Channel count of {} exceeds the maximum number of possible BISes, "
+ "which is {}",
sm_config_.config.GetNumBisTotal(), sNumBisMax);
return false;
}
@@ -145,8 +147,8 @@
void OnCreateAnnouncement(uint8_t advertising_sid, int8_t tx_power,
uint8_t status) {
- LOG_INFO("advertising_sid=%d tx_power=%d status=%d", advertising_sid,
- tx_power, status);
+ log::info("advertising_sid={} tx_power={} status={}", advertising_sid,
+ tx_power, status);
/* If this callback gets called the advertising_sid is valid even though the
* status can be other than SUCCESS.
@@ -155,7 +157,7 @@
if (status !=
bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) {
- LOG_ERROR("Creating Announcement failed");
+ log::error("Creating Announcement failed");
callbacks_->OnStateMachineCreateStatus(GetBroadcastId(), false);
return;
}
@@ -173,8 +175,8 @@
}
void OnEnableAnnouncement(bool enable, uint8_t status) {
- LOG_INFO("operation=%s, broadcast_id=%d, status=%d",
- (enable ? "enable" : "disable"), GetBroadcastId(), status);
+ log::info("operation={}, broadcast_id={}, status={}",
+ (enable ? "enable" : "disable"), GetBroadcastId(), status);
if (status ==
bluetooth::hci::AdvertisingCallback::AdvertisingStatus::SUCCESS) {
@@ -226,8 +228,8 @@
}
void ProcessMessage(Message msg, const void* data = nullptr) override {
- LOG_INFO("broadcast_id=%d, state=%s, message=%s", GetBroadcastId(),
- ToString(GetState()).c_str(), ToString(msg).c_str());
+ log::info("broadcast_id={}, state={}, message={}", GetBroadcastId(),
+ ToString(GetState()), ToString(msg));
switch (msg) {
case Message::START:
start_msg_handlers[StateMachine::GetState()](data);
@@ -323,7 +325,8 @@
[](const void*) { /* Already streaming */ }};
void OnAddressResponse(uint8_t addr_type, RawAddress addr) {
- LOG_INFO("own address=%s, type=%d", ADDRESS_TO_LOGGABLE_CSTR(addr), addr_type);
+ log::info("own address={}, type={}", ADDRESS_TO_LOGGABLE_CSTR(addr),
+ addr_type);
addr_ = addr;
addr_type_ = addr_type;
}
@@ -335,9 +338,9 @@
public_announcement,
const bluetooth::le_audio::BasicAudioAnnouncementData& announcement,
uint8_t streaming_phy) {
- LOG_INFO("is_public=%s, broadcast_name=%s, public_features=%d",
- (is_public ? "public" : "non-public"), broadcast_name.c_str(),
- public_announcement.features);
+ log::info("is_public={}, broadcast_name={}, public_features={}",
+ (is_public ? "public" : "non-public"), broadcast_name,
+ public_announcement.features);
if (advertiser_if_ != nullptr) {
AdvertiseParameters adv_params;
PeriodicAdvertisingParameters periodic_params;
@@ -380,7 +383,7 @@
}
void EnableAnnouncement() {
- LOG_INFO("broadcast_id=%d", GetBroadcastId());
+ log::info("broadcast_id={}", GetBroadcastId());
// Callback is handled by OnAdvertisingEnabled() which returns the status
advertiser_if_->Enable(GetAdvertisingSid(), true, base::DoNothing(), 0,
0, /* Enable until stopped */
@@ -388,7 +391,7 @@
}
void CreateBig(void) {
- LOG_INFO("broadcast_id=%d", GetBroadcastId());
+ log::info("broadcast_id={}", GetBroadcastId());
/* TODO: Figure out how to decide on the currently hard-codded params. */
struct bluetooth::hci::iso_manager::big_create_params big_params = {
.adv_handle = GetAdvertisingSid(),
@@ -410,14 +413,14 @@
}
void DisableAnnouncement(void) {
- LOG_INFO("broadcast_id=%d", GetBroadcastId());
+ log::info("broadcast_id={}", GetBroadcastId());
// Callback is handled by OnAdvertisingEnabled() which returns the status
advertiser_if_->Enable(GetAdvertisingSid(), false, base::DoNothing(), 0, 0,
base::DoNothing());
}
void TerminateBig() {
- LOG_INFO("suspending=%d", suspending_);
+ log::info("suspending={}", suspending_);
/* Terminate with reason: Connection Terminated By Local Host */
IsoManager::GetInstance()->TerminateBig(GetAdvertisingSid(), 0x16);
}
@@ -426,7 +429,7 @@
LOG_ASSERT(active_config_ != std::nullopt);
if (status != 0) {
- LOG_ERROR("Failure creating data path. Tearing down the BIG now.");
+ log::error("Failure creating data path. Tearing down the BIG now.");
suspending_ = true;
TerminateBig();
return;
@@ -447,7 +450,7 @@
} else {
/* Note: We would feed a watchdog here if we had one */
/* There are more BISes to set up data path for */
- LOG_INFO("There is more data paths to set up.");
+ log::info("There is more data paths to set up.");
TriggerIsoDatapathSetup(*handle_it);
}
}
@@ -456,7 +459,7 @@
LOG_ASSERT(active_config_ != std::nullopt);
if (status != 0) {
- LOG_ERROR("Failure removing data path. Tearing down the BIG now.");
+ log::error("Failure removing data path. Tearing down the BIG now.");
TerminateBig();
return;
}
@@ -475,13 +478,13 @@
} else {
/* Note: We would feed a watchdog here if we had one */
/* There are more BISes to tear down data path for */
- LOG_INFO("There is more data paths to tear down.");
+ log::info("There is more data paths to tear down.");
TriggerIsoDatapathTeardown(*handle_it);
}
}
void TriggerIsoDatapathSetup(uint16_t conn_handle) {
- LOG_INFO("conn_hdl=%d", conn_handle);
+ log::info("conn_hdl={}", conn_handle);
LOG_ASSERT(active_config_ != std::nullopt);
/* Note: If coding format is transparent, 'codec_id_company' and
@@ -511,7 +514,7 @@
}
void TriggerIsoDatapathTeardown(uint16_t conn_handle) {
- LOG_INFO("conn_hdl=%d", conn_handle);
+ log::info("conn_hdl={}", conn_handle);
LOG_ASSERT(active_config_ != std::nullopt);
SetMuted(true);
@@ -526,13 +529,13 @@
auto* evt = static_cast<big_create_cmpl_evt*>(data);
if (evt->big_id != GetAdvertisingSid()) {
- LOG_ERROR("State=%s, Event=%d, Unknown big, big_id=%d",
- ToString(GetState()).c_str(), event, evt->big_id);
+ log::error("State={}, Event={}, Unknown big, big_id={}",
+ ToString(GetState()), event, evt->big_id);
break;
}
if (evt->status == 0x00) {
- LOG_INFO("BIG create BIG complete, big_id=%d", evt->big_id);
+ log::info("BIG create BIG complete, big_id={}", evt->big_id);
active_config_ = {
.status = evt->status,
.big_id = evt->big_id,
@@ -550,20 +553,20 @@
callbacks_->OnBigCreated(evt->conn_handles);
TriggerIsoDatapathSetup(evt->conn_handles[0]);
} else {
- LOG_ERROR(
- "State=%s Event=%d. Unable to create big, big_id=%d, status=%d",
- ToString(GetState()).c_str(), event, evt->big_id, evt->status);
+ log::error(
+ "State={} Event={}. Unable to create big, big_id={}, status={}",
+ ToString(GetState()), event, evt->big_id, evt->status);
}
} break;
case HCI_BLE_TERM_BIG_CPL_EVT: {
auto* evt = static_cast<big_terminate_cmpl_evt*>(data);
- LOG_INFO("BIG terminate BIG cmpl, reason=%d big_id=%d", evt->reason,
- evt->big_id);
+ log::info("BIG terminate BIG cmpl, reason={} big_id={}", evt->reason,
+ evt->big_id);
if (evt->big_id != GetAdvertisingSid()) {
- LOG_ERROR("State=%s Event=%d, unknown adv.sid=%d",
- ToString(GetState()).c_str(), event, evt->big_id);
+ log::error("State={} Event={}, unknown adv.sid={}",
+ ToString(GetState()), event, evt->big_id);
break;
}
@@ -581,8 +584,7 @@
}
} break;
default:
- LOG_ERROR("State=%s Unknown event=%d", ToString(GetState()).c_str(),
- event);
+ log::error("State={} Unknown event={}", ToString(GetState()), event);
break;
}
}
@@ -606,11 +608,11 @@
BroadcastStateMachineImpl::advertiser_if_ =
bluetooth::shim::get_ble_advertiser_instance();
if (BroadcastStateMachineImpl::advertiser_if_ != nullptr) {
- LOG_INFO("Advertiser_instance acquired");
+ log::info("Advertiser_instance acquired");
BroadcastStateMachineImpl::advertiser_if_->RegisterCallbacksNative(
adv_callbacks, kAdvertiserClientIdLeAudio);
} else {
- LOG_ERROR("Could not acquire advertiser_instance!");
+ log::error("Could not acquire advertiser_instance!");
BroadcastStateMachineImpl::advertiser_if_ = nullptr;
}
}
diff --git a/system/bta/le_audio/client.cc b/system/bta/le_audio/client.cc
index 000413d..7080e33 100644
--- a/system/bta/le_audio/client.cc
+++ b/system/bta/le_audio/client.cc
@@ -18,6 +18,7 @@
#include <android_bluetooth_flags.h>
#include <base/functional/bind.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include <deque>
@@ -110,6 +111,8 @@
using bluetooth::le_audio::utils::GetAudioContextsFromSinkMetadata;
using bluetooth::le_audio::utils::GetAudioContextsFromSourceMetadata;
+using namespace bluetooth;
+
/* Enums */
enum class AudioReconfigurationResult {
RECONFIGURATION_NEEDED = 0x00,
@@ -254,15 +257,15 @@
if (bluetooth::common::InitFlags::
IsTargetedAnnouncementReconnectionMode()) {
- LOG_INFO(" Reconnection mode: TARGETED_ANNOUNCEMENTS");
+ log::info("Reconnection mode: TARGETED_ANNOUNCEMENTS");
reconnection_mode_ = BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS;
} else {
- LOG_INFO(" Reconnection mode: ALLOW_LIST");
+ log::info("Reconnection mode: ALLOW_LIST");
reconnection_mode_ = BTM_BLE_BKG_CONNECT_ALLOW_LIST;
}
if (IS_FLAG_ENABLED(leaudio_enable_health_based_actions)) {
- LOG_INFO("Loading health status module");
+ log::info("Loading health status module");
leAudioHealthStatus_ = LeAudioHealthStatus::Get();
leAudioHealthStatus_->RegisterCallback(
base::BindRepeating(le_audio_health_status_callback));
@@ -273,8 +276,8 @@
base::Bind(
[](base::Closure initCb, uint8_t client_id, uint8_t status) {
if (status != GATT_SUCCESS) {
- LOG(ERROR) << "Can't start LeAudio profile - no gatt "
- "clients left!";
+ log::error(
+ "Can't start LeAudio profile - no gatt clients left!");
return;
}
instance->gatt_if_ = client_id;
@@ -287,7 +290,7 @@
}
void ReconfigureAfterVbcClose() {
- LOG_DEBUG("VBC close timeout");
+ log::debug("VBC close timeout");
if (IsInVoipCall()) {
SetInVoipCall(false);
@@ -295,7 +298,7 @@
auto group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG_ERROR("Invalid group: %d", active_group_id_);
+ log::error("Invalid group: {}", active_group_id_);
return;
}
@@ -311,7 +314,7 @@
if ((configuration_context_type_ != LeAudioContextType::MEDIA) &&
(configuration_context_type_ != LeAudioContextType::GAME)) {
- LOG_INFO(
+ log::info(
"Keeping the old configuration as no HQ Media playback is needed "
"right now.");
return;
@@ -321,7 +324,7 @@
local_metadata_context_types_.source &= group->GetAvailableContexts(
bluetooth::le_audio::types::kLeAudioDirectionSink);
if (local_metadata_context_types_.source.none()) {
- LOG_WARN("invalid/unknown context metadata, using 'MEDIA' instead");
+ log::warn("invalid/unknown context metadata, using 'MEDIA' instead");
local_metadata_context_types_.source =
AudioContexts(LeAudioContextType::MEDIA);
}
@@ -330,8 +333,8 @@
auto new_configuration_context =
ChooseConfigurationContextType(local_metadata_context_types_.source);
- LOG_DEBUG("new_configuration_context= %s",
- ToString(new_configuration_context).c_str());
+ log::debug("new_configuration_context= {}",
+ ToString(new_configuration_context));
ReconfigureOrUpdateMetadata(group, new_configuration_context,
{.sink = local_metadata_context_types_.source,
.source = local_metadata_context_types_.sink});
@@ -343,8 +346,8 @@
}
static const uint64_t timeoutMs = 2000;
- LOG_DEBUG("Start VBC close timeout with %lu ms",
- static_cast<unsigned long>(timeoutMs));
+ log::debug("Start VBC close timeout with {} ms",
+ static_cast<unsigned long>(timeoutMs));
alarm_set_on_mloop(
close_vbc_timeout_, timeoutMs,
@@ -356,7 +359,7 @@
void StopVbcCloseTimeout() {
if (alarm_is_scheduled(close_vbc_timeout_)) {
- LOG_DEBUG("Cancel VBC close timeout");
+ log::debug("Cancel VBC close timeout");
alarm_cancel(close_vbc_timeout_);
}
}
@@ -384,9 +387,8 @@
void OnGroupAddedCb(const RawAddress& address, const bluetooth::Uuid& uuid,
int group_id) {
- LOG(INFO) << __func__ << " address: " << ADDRESS_TO_LOGGABLE_STR(address)
- << " group uuid " << uuid
- << " group_id: " << group_id;
+ log::info("address: {} group uuid {} group_id: {}",
+ ADDRESS_TO_LOGGABLE_STR(address), uuid, group_id);
/* We are interested in the groups which are in the context of CAP */
if (uuid != bluetooth::le_audio::uuid::kCapServiceUuid) return;
@@ -394,8 +396,7 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) return;
if (leAudioDevice->group_id_ != bluetooth::groups::kGroupUnknown) {
- LOG(INFO) << __func__
- << " group already set: " << leAudioDevice->group_id_;
+ log::info("group already set: {}", leAudioDevice->group_id_);
return;
}
@@ -407,27 +408,26 @@
* considering this removing device.
*/
void SetDeviceAsRemovePendingAndStopGroup(LeAudioDevice* leAudioDevice) {
- LOG_INFO("device %s", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("device {}", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
leAudioDevice->SetConnectionState(DeviceConnectState::REMOVING);
leAudioDevice->closing_stream_for_disconnection_ = true;
GroupStop(leAudioDevice->group_id_);
}
void OnGroupMemberAddedCb(const RawAddress& address, int group_id) {
- LOG(INFO) << __func__ << " address: " << ADDRESS_TO_LOGGABLE_STR(address)
- << " group_id: " << group_id;
+ log::info("address: {} group_id: {}", ADDRESS_TO_LOGGABLE_STR(address),
+ group_id);
auto group = aseGroups_.FindById(group_id);
if (!group) {
- LOG(ERROR) << __func__ << " Not interested in group id: " << group_id;
+ log::error("Not interested in group id: {}", group_id);
return;
}
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) return;
if (leAudioDevice->group_id_ != bluetooth::groups::kGroupUnknown) {
- LOG(INFO) << __func__
- << " group already set: " << leAudioDevice->group_id_;
+ log::info("group already set: {}", leAudioDevice->group_id_);
return;
}
@@ -440,23 +440,21 @@
}
void OnGroupMemberRemovedCb(const RawAddress& address, int group_id) {
- LOG(INFO) << __func__ << " address: " << ADDRESS_TO_LOGGABLE_STR(address)
- << " group_id: " << group_id;
+ log::info("address: {} group_id: {}", ADDRESS_TO_LOGGABLE_STR(address),
+ group_id);
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) return;
if (leAudioDevice->group_id_ != group_id) {
- LOG_WARN("Device: %s not assigned to the group.",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("Device: {} not assigned to the group.",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (group == NULL) {
- LOG(INFO) << __func__
- << " device not in the group: "
- << ADDRESS_TO_LOGGABLE_STR(leAudioDevice->address_)
- << ", " << group_id;
+ log::info("device not in the group: {}, {}",
+ ADDRESS_TO_LOGGABLE_STR(leAudioDevice->address_), group_id);
return;
}
@@ -491,11 +489,11 @@
group, LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED);
}
- LOG_ERROR(
- " State not achieved on time for group: group id %d, current state %s, "
- "target state: %s, check_if_recovery_needed: %d",
- group_id, ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str(), check_if_recovery_needed);
+ log::error(
+ "State not achieved on time for group: group id {}, current state {}, "
+ "target state: {}, check_if_recovery_needed: {}",
+ group_id, ToString(group->GetState()),
+ ToString(group->GetTargetState()), check_if_recovery_needed);
group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
group->ClearAllCises();
group->PrintDebugState();
@@ -506,11 +504,11 @@
CancelStreamingRequest();
LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice();
if (leAudioDevice == nullptr) {
- LOG_ERROR(" Shouldn't be called without an active device.");
+ log::error("Shouldn't be called without an active device.");
leAudioDevice = group->GetFirstDevice();
if (leAudioDevice == nullptr) {
- LOG_ERROR(" Front device is null. Number of devices: %d",
- group->Size());
+ log::error("Front device is null. Number of devices: {}",
+ group->Size());
return;
}
}
@@ -542,8 +540,8 @@
}
void OnDeviceAutonomousStateTransitionTimeout(LeAudioDevice* leAudioDevice) {
- LOG_ERROR("Device %s, failed to complete autonomous transition",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Device {}, failed to complete autonomous transition",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
DisconnectDevice(leAudioDevice, true);
}
@@ -644,13 +642,12 @@
/* TODO This part possible to remove as this is to handle adding device to
* the group which is unknown and not connected.
*/
- LOG(INFO) << __func__ << ", leAudioDevice unknown , address: "
- << ADDRESS_TO_LOGGABLE_STR(address)
- << " group: " << loghex(group_id);
+ log::info("leAudioDevice unknown , address: {} group: {}",
+ ADDRESS_TO_LOGGABLE_STR(address), loghex(group_id));
if (group_id == bluetooth::groups::kGroupUnknown) return;
- LOG(INFO) << __func__ << "Set member adding ...";
+ log::info("Set member adding ...");
leAudioDevices_.Add(address, DeviceConnectState::CONNECTING_BY_USER);
leAudioDevice = leAudioDevices_.FindByAddress(address);
} else {
@@ -671,8 +668,7 @@
new_group = aseGroups_.Add(id);
if (!new_group) {
- LOG(ERROR) << __func__
- << ", can't create group - group is already there?";
+ log::error("can't create group - group is already there?");
return;
}
} else {
@@ -687,7 +683,8 @@
}
}
- LOG_DEBUG("New group %p, id: %d", new_group, new_group->group_id_);
+ log::debug("New group {}, id: {}", fmt::ptr(new_group),
+ new_group->group_id_);
/* If device was in the group and it was not removed by the application,
* lets do it now
@@ -723,12 +720,12 @@
void remove_group_if_possible(LeAudioDeviceGroup* group) {
if (!group) {
- LOG_DEBUG("group is null");
+ log::debug("group is null");
return;
}
- LOG_DEBUG("Group %p, id: %d, size: %d, is cig_state %s", group,
- group->group_id_, group->Size(),
- ToString(group->cig.GetState()).c_str());
+ log::debug("Group {}, id: {}, size: {}, is cig_state {}", fmt::ptr(group),
+ group->group_id_, group->Size(),
+ ToString(group->cig.GetState()));
if (group->IsEmpty() &&
(group->cig.GetState() == bluetooth::le_audio::types::CigState::NONE)) {
lastNotifiedGroupStreamStatusMap_.erase(group->group_id_);
@@ -765,24 +762,23 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
- LOG(INFO) << __func__ << " group_id: " << group_id
- << " address: " << ADDRESS_TO_LOGGABLE_STR(address);
+ log::info("group_id: {} address: {}", group_id,
+ ADDRESS_TO_LOGGABLE_STR(address));
if (!leAudioDevice) {
- LOG(ERROR) << __func__
- << ", Skipping unknown leAudioDevice, address: "
- << ADDRESS_TO_LOGGABLE_STR(address);
+ log::error("Skipping unknown leAudioDevice, address: {}",
+ ADDRESS_TO_LOGGABLE_STR(address));
return;
}
if (leAudioDevice->group_id_ != group_id) {
- LOG(ERROR) << __func__ << "Device is not in group_id: " << group_id
- << ", but in group_id: " << leAudioDevice->group_id_;
+ log::error("Device is not in group_id: {}, but in group_id: {}", group_id,
+ leAudioDevice->group_id_);
return;
}
if (group == NULL) {
- LOG(ERROR) << __func__ << " device not in the group ?!";
+ log::error("device not in the group ?!");
return;
}
@@ -806,8 +802,8 @@
return metadata_context_type;
}
- LOG_DEBUG("Converting to single context type: %s",
- metadata_context_type.to_string().c_str());
+ log::debug("Converting to single context type: {}",
+ metadata_context_type.to_string());
/* Mini policy */
if (metadata_context_type.any()) {
@@ -827,15 +823,14 @@
};
for (auto ct : context_priority_list) {
if (metadata_context_type.test(ct)) {
- LOG_DEBUG("Converted to single context type: %s",
- ToString(ct).c_str());
+ log::debug("Converted to single context type: {}", ToString(ct));
return AudioContexts(ct);
}
}
}
/* Fallback to BAP mandated context type */
- LOG_WARN("Invalid/unknown context, using 'UNSPECIFIED'");
+ log::warn("Invalid/unknown context, using 'UNSPECIFIED'");
return AudioContexts(LeAudioContextType::UNSPECIFIED);
}
@@ -844,27 +839,26 @@
BidirectionalPair<AudioContexts> remote_contexts) {
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
- LOG_DEBUG("configuration_context_type= %s",
- ToString(configuration_context_type).c_str());
+ log::debug("configuration_context_type= {}",
+ ToString(configuration_context_type));
DLOG(INFO) << __func__;
if (configuration_context_type >= LeAudioContextType::RFU) {
- LOG(ERROR) << __func__ << ", stream context type is not supported: "
- << ToHexString(configuration_context_type);
+ log::error("stream context type is not supported: {}",
+ ToHexString(configuration_context_type));
return false;
}
if (!group) {
- LOG(ERROR) << __func__ << ", unknown group id: " << group_id;
+ log::error("unknown group id: {}", group_id);
return false;
}
- LOG_DEBUG("group state=%s, target_state=%s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::debug("group state={}, target_state={}", ToString(group->GetState()),
+ ToString(group->GetTargetState()));
if (!group->IsAnyDeviceConnected()) {
- LOG(ERROR) << __func__ << ", group " << group_id << " is not connected ";
+ log::error("group {} is not connected", group_id);
return false;
}
@@ -876,7 +870,7 @@
* interrupt any ongoing transition. We will check if another
* reconfiguration is needed once the group reaches streaming state.
*/
- LOG_WARN(
+ log::warn(
"Group is already in the transition state. Waiting for the target "
"state to be reached.");
return false;
@@ -936,25 +930,24 @@
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (!group) {
- LOG(ERROR) << __func__ << ", unknown group id: " << group_id;
+ log::error("unknown group id: {}", group_id);
return;
}
if (!group->IsAnyDeviceConnected()) {
- LOG(ERROR) << __func__ << ", group is not connected";
+ log::error("group is not connected");
return;
}
if (group->IsInTransition()) {
- LOG_INFO(", group is in transition from: %s to: %s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::info(", group is in transition from: {} to: {}",
+ ToString(group->GetState()), ToString(group->GetTargetState()));
return;
}
if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG_ERROR(", invalid current state of group: %s",
- ToString(group->GetState()).c_str());
+ log::error(", invalid current state of group: {}",
+ ToString(group->GetState()));
return;
}
@@ -965,23 +958,23 @@
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (!group) {
- LOG(ERROR) << __func__ << ", unknown group id: " << group_id;
+ log::error("unknown group id: {}", group_id);
return;
}
if (group->IsEmpty()) {
- LOG(ERROR) << __func__ << ", group is empty";
+ log::error("group is empty");
return;
}
if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
- LOG_WARN(" group %d was about to stream, but got canceled: %s",
- group_id, ToString(group->GetTargetState()).c_str());
+ log::warn("group {} was about to stream, but got canceled: {}",
+ group_id, ToString(group->GetTargetState()));
group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
} else {
- LOG_WARN(", group %d already stopped: %s", group_id,
- ToString(group->GetState()).c_str());
+ log::warn(", group {} already stopped: {}", group_id,
+ ToString(group->GetState()));
}
return;
}
@@ -993,7 +986,7 @@
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (!group) {
- LOG(ERROR) << __func__ << ", unknown group id: " << group_id;
+ log::error("unknown group id: {}", group_id);
return;
}
@@ -1015,21 +1008,21 @@
}
void SetCcidInformation(int ccid, int context_type) override {
- LOG_DEBUG("Ccid: %d, context type %d", ccid, context_type);
+ log::debug("Ccid: {}, context type {}", ccid, context_type);
ContentControlIdKeeper::GetInstance()->SetCcid(AudioContexts(context_type),
ccid);
}
void SetInCall(bool in_call) override {
- LOG_DEBUG("in_call: %d", in_call);
+ log::debug("in_call: {}", in_call);
in_call_ = in_call;
}
bool IsInCall() override { return in_call_; }
void SetInVoipCall(bool in_call) override {
- LOG_DEBUG("in_voip_call: %d", in_call);
+ log::debug("in_voip_call: {}", in_call);
in_voip_call_ = in_call;
}
@@ -1042,7 +1035,8 @@
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");
+ log::warn(
+ "Monitor mode is disabled, Set Unicast Monitor mode is ignored");
return;
}
@@ -1058,11 +1052,11 @@
le_audio_sink_hal_client_.reset();
}
- LOG_DEBUG("enable: %d", enable);
+ log::debug("enable: {}", enable);
sink_monitor_mode_ = enable;
} else if (direction ==
bluetooth::le_audio::types::kLeAudioDirectionSource) {
- LOG_DEBUG("enable: %d", enable);
+ log::debug("enable: {}", enable);
source_monitor_mode_ = enable;
if (!enable) {
@@ -1088,24 +1082,24 @@
UnicastMonitorModeStatus::STREAMING_SUSPENDED);
}
} else {
- LOG_ERROR("invalid direction: 0x%02x monitor mode set", direction);
+ log::error("invalid direction: 0x{:02x} monitor mode set", direction);
}
}
void SendAudioProfilePreferences(
const int group_id, bool is_output_preference_le_audio,
bool is_duplex_preference_le_audio) override {
- LOG_INFO(
- "group_id: %d, is_output_preference_le_audio: %d, "
- "is_duplex_preference_le_audio: %d",
+ log::info(
+ "group_id: {}, is_output_preference_le_audio: {}, "
+ "is_duplex_preference_le_audio: {}",
group_id, is_output_preference_le_audio, is_duplex_preference_le_audio);
if (group_id == bluetooth::groups::kGroupUnknown) {
- LOG_WARN("Unknown group_id");
+ log::warn("Unknown group_id");
return;
}
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (!group) {
- LOG_WARN("group_id %d does not exist", group_id);
+ log::warn("group_id {} does not exist", group_id);
return;
}
@@ -1165,38 +1159,38 @@
}
bool isOutputPreferenceLeAudio(const RawAddress& address) {
- LOG_INFO(" address: %s, active_group_id_: %d",
- address.ToStringForLogging().c_str(), active_group_id_);
+ log::info("address: {}, active_group_id_: {}", address.ToStringForLogging(),
+ active_group_id_);
std::vector<RawAddress> active_leaudio_devices =
GetGroupDevices(active_group_id_);
if (std::find(active_leaudio_devices.begin(), active_leaudio_devices.end(),
address) == active_leaudio_devices.end()) {
- LOG_INFO("Device %s is not active for LE Audio",
- address.ToStringForLogging().c_str());
+ log::info("Device {} is not active for LE Audio",
+ address.ToStringForLogging());
return false;
}
LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_);
- LOG_INFO(" active_group_id: %d, is_output_preference_le_audio_: %d",
- group->group_id_, group->is_output_preference_le_audio);
+ log::info("active_group_id: {}, is_output_preference_le_audio_: {}",
+ group->group_id_, group->is_output_preference_le_audio);
return group->is_output_preference_le_audio;
}
bool isDuplexPreferenceLeAudio(const RawAddress& address) {
- LOG_INFO(" address: %s, active_group_id_: %d",
- address.ToStringForLogging().c_str(), active_group_id_);
+ log::info("address: {}, active_group_id_: {}", address.ToStringForLogging(),
+ active_group_id_);
std::vector<RawAddress> active_leaudio_devices =
GetGroupDevices(active_group_id_);
if (std::find(active_leaudio_devices.begin(), active_leaudio_devices.end(),
address) == active_leaudio_devices.end()) {
- LOG_INFO("Device %s is not active for LE Audio",
- address.ToStringForLogging().c_str());
+ log::info("Device {} is not active for LE Audio",
+ address.ToStringForLogging());
return false;
}
LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_);
- LOG_INFO(" active_group_id: %d, is_duplex_preference_le_audio: %d",
- group->group_id_, group->is_duplex_preference_le_audio);
+ log::info("active_group_id: {}, is_duplex_preference_le_audio: {}",
+ group->group_id_, group->is_duplex_preference_le_audio);
return group->is_duplex_preference_le_audio;
}
@@ -1208,7 +1202,7 @@
active_group_id_ = bluetooth::groups::kGroupUnknown;
sink_monitor_notified_status_ = std::nullopt;
- LOG_INFO("Group id: %d", group_id_to_close);
+ log::info("Group id: {}", group_id_to_close);
if (alarm_is_scheduled(suspend_timeout_)) alarm_cancel(suspend_timeout_);
StopAudio();
@@ -1217,7 +1211,7 @@
}
void GroupSetActive(const int group_id) override {
- LOG_INFO(" group_id: %d", group_id);
+ log::info("group_id: {}", group_id);
if (group_id == bluetooth::groups::kGroupUnknown) {
if (active_group_id_ == bluetooth::groups::kGroupUnknown) {
@@ -1225,7 +1219,7 @@
return;
}
- LOG_INFO("Active group_id changed %d -> %d", active_group_id_, group_id);
+ log::info("Active group_id changed {} -> {}", active_group_id_, group_id);
auto group_id_to_close = active_group_id_;
groupSetAndNotifyInactive();
GroupStop(group_id_to_close);
@@ -1235,26 +1229,25 @@
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (!group) {
- LOG(ERROR) << __func__
- << ", Invalid group: " << static_cast<int>(group_id);
+ log::error("Invalid group: {}", static_cast<int>(group_id));
return;
}
if (active_group_id_ != bluetooth::groups::kGroupUnknown) {
if (active_group_id_ == group_id) {
- LOG(INFO) << __func__ << ", Group is already active: "
- << static_cast<int>(active_group_id_);
+ log::info("Group is already active: {}",
+ static_cast<int>(active_group_id_));
callbacks_->OnGroupStatus(active_group_id_, GroupStatus::ACTIVE);
return;
}
- LOG(INFO) << __func__ << ", switching active group to: " << group_id;
+ log::info("switching active group to: {}", group_id);
}
if (!le_audio_source_hal_client_) {
le_audio_source_hal_client_ =
LeAudioSourceAudioHalClient::AcquireUnicast();
if (!le_audio_source_hal_client_) {
- LOG(ERROR) << __func__ << ", could not acquire audio source interface";
+ log::error("could not acquire audio source interface");
return;
}
}
@@ -1262,7 +1255,7 @@
if (!le_audio_sink_hal_client_) {
le_audio_sink_hal_client_ = LeAudioSinkAudioHalClient::AcquireUnicast();
if (!le_audio_sink_hal_client_) {
- LOG(ERROR) << __func__ << ", could not acquire audio sink interface";
+ log::error("could not acquire audio sink interface");
return;
}
}
@@ -1290,13 +1283,13 @@
default_context_type);
if (current_source_codec_config.IsInvalid() &&
current_sink_codec_config.IsInvalid()) {
- LOG_ERROR("Unsupported device configurations");
+ log::error("Unsupported device configurations");
return;
}
auto previous_active_group = active_group_id_;
- LOG_INFO("Active group_id changed %d -> %d", previous_active_group,
- group_id);
+ log::info("Active group_id changed {} -> {}", previous_active_group,
+ group_id);
if (previous_active_group == bluetooth::groups::kGroupUnknown) {
/* Expose audio sessions if there was no previous active group */
@@ -1324,18 +1317,18 @@
}
void SetEnableState(const RawAddress& address, bool enabled) override {
- LOG_INFO(" %s: %s", ADDRESS_TO_LOGGABLE_CSTR(address),
- (enabled ? "enabled" : "disabled"));
+ log::info("{}: {}", ADDRESS_TO_LOGGABLE_CSTR(address),
+ (enabled ? "enabled" : "disabled"));
auto leAudioDevice = leAudioDevices_.FindByAddress(address);
if (leAudioDevice == nullptr) {
- LOG_WARN("%s is null", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("{} is null", ADDRESS_TO_LOGGABLE_CSTR(address));
return;
}
auto group_id = leAudioDevice->group_id_;
auto group = aseGroups_.FindById(group_id);
if (group == nullptr) {
- LOG_WARN("Group %d is not available", group_id);
+ log::warn("Group {} is not available", group_id);
return;
}
@@ -1347,7 +1340,7 @@
}
void RemoveDevice(const RawAddress& address) override {
- LOG_INFO(": %s ", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info(": {}", ADDRESS_TO_LOGGABLE_CSTR(address));
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) {
return;
@@ -1357,9 +1350,8 @@
BTA_GATTC_CancelOpen(gatt_if_, address, false);
btif_storage_set_leaudio_autoconnect(address, false);
- LOG_INFO("%s, state: %s", ADDRESS_TO_LOGGABLE_CSTR(address),
- bluetooth::common::ToString(leAudioDevice->GetConnectionState())
- .c_str());
+ log::info("{}, state: {}", ADDRESS_TO_LOGGABLE_CSTR(address),
+ bluetooth::common::ToString(leAudioDevice->GetConnectionState()));
auto connection_state = leAudioDevice->GetConnectionState();
switch (connection_state) {
case DeviceConnectState::REMOVING:
@@ -1398,7 +1390,7 @@
}
void Connect(const RawAddress& address) override {
- LOG_INFO(": %s ", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info(": {}", ADDRESS_TO_LOGGABLE_CSTR(address));
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) {
@@ -1407,9 +1399,9 @@
auto current_connect_state = leAudioDevice->GetConnectionState();
if ((current_connect_state == DeviceConnectState::CONNECTED) ||
(current_connect_state == DeviceConnectState::CONNECTING_BY_USER)) {
- LOG_ERROR("Device %s is in invalid state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- bluetooth::common::ToString(current_connect_state).c_str());
+ log::error("Device {} is in invalid state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ bluetooth::common::ToString(current_connect_state));
return;
}
@@ -1417,8 +1409,9 @@
if (leAudioDevice->group_id_ != bluetooth::groups::kGroupUnknown) {
auto group = GetGroupIfEnabled(leAudioDevice->group_id_);
if (!group) {
- LOG_WARN(" %s, trying to connect to disabled group id %d",
- ADDRESS_TO_LOGGABLE_CSTR(address), leAudioDevice->group_id_);
+ log::warn("{}, trying to connect to disabled group id {}",
+ ADDRESS_TO_LOGGABLE_CSTR(address),
+ leAudioDevice->group_id_);
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
return;
}
@@ -1461,14 +1454,14 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (leAudioDevice) {
- LOG_ERROR("Device is already loaded. Nothing to do.");
+ log::error("Device is already loaded. Nothing to do.");
return;
}
- LOG_INFO(
- "restoring: %s, autoconnect %d, sink_audio_location: %d, "
- "source_audio_location: %d, sink_supported_context_types : 0x%04x, "
- "source_supported_context_types 0x%04x ",
+ log::info(
+ "restoring: {}, autoconnect {}, sink_audio_location: {}, "
+ "source_audio_location: {}, sink_supported_context_types : 0x{:04x}, "
+ "source_supported_context_types 0x{:04x}",
ADDRESS_TO_LOGGABLE_CSTR(address), autoconnect, sink_audio_location,
source_audio_location, sink_supported_context_types,
source_supported_context_types);
@@ -1509,25 +1502,25 @@
leAudioDevice->SetAvailableContexts(supported_contexts);
if (!DeserializeHandles(leAudioDevice, handles)) {
- LOG_WARN("Could not load Handles");
+ log::warn("Could not load Handles");
}
if (!DeserializeSinkPacs(leAudioDevice, sink_pacs)) {
/* If PACs are invalid, just say whole cache is invalid */
leAudioDevice->known_service_handles_ = false;
- LOG_WARN("Could not load sink pacs");
+ log::warn("Could not load sink pacs");
}
if (!DeserializeSourcePacs(leAudioDevice, source_pacs)) {
/* If PACs are invalid, just say whole cache is invalid */
leAudioDevice->known_service_handles_ = false;
- LOG_WARN("Could not load source pacs");
+ log::warn("Could not load source pacs");
}
if (!DeserializeAses(leAudioDevice, ases)) {
/* If ASEs are invalid, just say whole cache is invalid */
leAudioDevice->known_service_handles_ = false;
- LOG_WARN("Could not load ases");
+ log::warn("Could not load ases");
}
leAudioDevice->autoconnect_flag_ = autoconnect;
@@ -1563,27 +1556,27 @@
void BackgroundConnectIfNeeded(LeAudioDevice* leAudioDevice) {
if (!leAudioDevice->autoconnect_flag_) {
- LOG_DEBUG("Device %s not in the background connect",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::debug("Device {} not in the background connect",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
AddToBackgroundConnectCheckGroupConnected(leAudioDevice);
}
void Disconnect(const RawAddress& address) override {
- LOG_INFO(": %s ", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info(": {}", ADDRESS_TO_LOGGABLE_CSTR(address));
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) {
- LOG_WARN("leAudioDevice not connected ( %s )",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("leAudioDevice not connected ( {} )",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
return;
}
auto connection_state = leAudioDevice->GetConnectionState();
- LOG_INFO("%s, state: %s", ADDRESS_TO_LOGGABLE_CSTR(address),
- bluetooth::common::ToString(connection_state).c_str());
+ log::info("{}, state: {}", ADDRESS_TO_LOGGABLE_CSTR(address),
+ bluetooth::common::ToString(connection_state));
switch (connection_state) {
case DeviceConnectState::CONNECTING_BY_USER:
@@ -1606,8 +1599,8 @@
(reconnection_mode_ != BTM_BLE_BKG_CONNECT_TARGETED_ANNOUNCEMENTS);
if (leAudioDevice->autoconnect_flag_ && remove_from_autoconnect) {
- LOG_INFO("Removing autoconnect flag for group_id %d",
- leAudioDevice->group_id_);
+ log::info("Removing autoconnect flag for group_id {}",
+ leAudioDevice->group_id_);
/* Removes device from background connect */
BTA_GATTC_CancelOpen(gatt_if_, address, false);
@@ -1654,7 +1647,7 @@
/* Java is not aware about autoconnect actions,
* therefore this should not happen.
*/
- LOG_WARN("Should not happen - disconnect device");
+ log::warn("Should not happen - disconnect device");
DisconnectDevice(leAudioDevice);
return;
case DeviceConnectState::DISCONNECTED:
@@ -1662,8 +1655,8 @@
case DeviceConnectState::DISCONNECTING_AND_RECOVER:
case DeviceConnectState::CONNECTING_AUTOCONNECT:
case DeviceConnectState::REMOVING:
- LOG_WARN("%s, invalid state %s", ADDRESS_TO_LOGGABLE_CSTR(address),
- bluetooth::common::ToString(connection_state).c_str());
+ log::warn("{}, invalid state {}", ADDRESS_TO_LOGGABLE_CSTR(address),
+ bluetooth::common::ToString(connection_state));
return;
}
}
@@ -1738,8 +1731,8 @@
struct ase* ase;
if (!leAudioDevice) {
- LOG(ERROR) << __func__ << ", no leAudioDevice assigned to connection id: "
- << static_cast<int>(conn_id);
+ log::error("no leAudioDevice assigned to connection id: {}",
+ static_cast<int>(conn_id));
return;
}
@@ -1764,7 +1757,7 @@
value))
return;
- LOG(INFO) << __func__ << ", Registering sink PACs";
+ log::info("Registering sink PACs");
leAudioDevice->RegisterPACs(&std::get<1>(*snk_pac_ent), &pac_recs);
/* Cached audio set configurations should be considered invalid when
@@ -1792,7 +1785,7 @@
value))
return;
- LOG(INFO) << __func__ << ", Registering source PACs";
+ log::info("Registering source PACs");
leAudioDevice->RegisterPACs(&std::get<1>(*src_pac_ent), &pac_recs);
/* Cached audio set configurations should be considered invalid when
@@ -1924,7 +1917,7 @@
bluetooth::le_audio::client_parser::tmap::ParseTmapRole(
leAudioDevice->tmap_role_, len, value);
} else {
- LOG(ERROR) << __func__ << ", Unknown attribute read: " << loghex(hdl);
+ log::error("Unknown attribute read: {}", loghex(hdl));
}
}
@@ -1936,11 +1929,11 @@
LeAudioDeviceGroup* GetGroupIfEnabled(int group_id) {
auto group = aseGroups_.FindById(group_id);
if (group == nullptr) {
- LOG_INFO("Group %d does not exist", group_id);
+ log::info("Group {} does not exist", group_id);
return nullptr;
}
if (!group->IsEnabled()) {
- LOG_INFO("Group %d is disabled", group_id);
+ log::info("Group {} is disabled", group_id);
return nullptr;
}
return group;
@@ -1951,7 +1944,7 @@
auto address = leAudioDevice->address_;
auto group = GetGroupIfEnabled(leAudioDevice->group_id_);
if (group == nullptr) {
- LOG_INFO("Group %d is invalid or disabled ", leAudioDevice->group_id_);
+ log::info("Group {} is invalid or disabled", leAudioDevice->group_id_);
return;
}
@@ -1961,13 +1954,13 @@
/* Cancel previous bakcground connect */
BTA_GATTC_CancelOpen(gatt_if_, address, false);
if (group->IsAnyDeviceConnected()) {
- LOG_INFO("Group %d in connected state. Adding %s to allow list ",
- leAudioDevice->group_id_, ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Group {} in connected state. Adding {} to allow list",
+ leAudioDevice->group_id_, ADDRESS_TO_LOGGABLE_CSTR(address));
BTA_GATTC_Open(gatt_if_, address, BTM_BLE_BKG_CONNECT_ALLOW_LIST, false);
} else {
- LOG_INFO(
- "Adding %s to backgroud connect (default reconnection_mode "
- "(0x%02x))",
+ log::info(
+ "Adding {} to backgroud connect (default reconnection_mode "
+ "(0x{:02x}))",
ADDRESS_TO_LOGGABLE_CSTR(address), reconnection_mode_);
BTA_GATTC_Open(gatt_if_, address, reconnection_mode_, false);
}
@@ -1978,14 +1971,13 @@
tBT_TRANSPORT transport, uint16_t mtu) {
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
- LOG_INFO("%s, conn_id=0x%04x, transport=%s, status=%s (0x%02x)",
- ADDRESS_TO_LOGGABLE_CSTR(address), conn_id,
- bt_transport_text(transport).c_str(),
- gatt_status_text(status).c_str(), status);
+ log::info("{}, conn_id=0x{:04x}, transport={}, status={} (0x{:02x})",
+ ADDRESS_TO_LOGGABLE_CSTR(address), conn_id,
+ bt_transport_text(transport), gatt_status_text(status), status);
if (transport != BT_TRANSPORT_LE) {
- LOG_WARN("Only LE connection is allowed (transport %s)",
- bt_transport_text(transport).c_str());
+ log::warn("Only LE connection is allowed (transport {})",
+ bt_transport_text(transport));
BTA_GATTC_Close(conn_id);
return;
}
@@ -1993,8 +1985,8 @@
if (!leAudioDevice) return;
if (leAudioDevice->conn_id_ != GATT_INVALID_CONN_ID) {
- LOG_DEBUG("Already connected %s, conn_id=0x%04x",
- ADDRESS_TO_LOGGABLE_CSTR(address), leAudioDevice->conn_id_);
+ log::debug("Already connected {}, conn_id=0x{:04x}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), leAudioDevice->conn_id_);
return;
}
@@ -2007,7 +1999,7 @@
(leAudioDevice->GetConnectionState() ==
DeviceConnectState::CONNECTING_AUTOCONNECT ||
leAudioDevice->autoconnect_flag_)) {
- LOG_INFO("Device not available now, do background connect.");
+ log::info("Device not available now, do background connect.");
leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED);
AddToBackgroundConnectCheckGroupConnected(leAudioDevice);
return;
@@ -2015,8 +2007,8 @@
leAudioDevice->SetConnectionState(DeviceConnectState::DISCONNECTED);
- LOG_ERROR("Failed to connect to LeAudio leAudioDevice, status: 0x%02x",
- status);
+ log::error("Failed to connect to LeAudio leAudioDevice, status: 0x{:02x}",
+ status);
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged(
leAudioDevice->group_id_, address, ConnectionState::CONNECTED,
@@ -2029,8 +2021,8 @@
if (group == nullptr) {
BTA_GATTC_CancelOpen(gatt_if_, address, false);
- LOG_WARN(
- "LeAudio profile is disabled for group_id: %d. %s is not connected",
+ log::warn(
+ "LeAudio profile is disabled for group_id: {}. {} is not connected",
leAudioDevice->group_id_, ADDRESS_TO_LOGGABLE_CSTR(address));
return;
}
@@ -2048,8 +2040,7 @@
BTA_GATTC_Open(gatt_if_, address, reconnection_mode_, false);
if (bluetooth::shim::GetController()->SupportsBle2mPhy()) {
- LOG(INFO) << ADDRESS_TO_LOGGABLE_STR(address)
- << " set preferred PHY to 2M";
+ log::info("{} set preferred PHY to 2M", ADDRESS_TO_LOGGABLE_STR(address));
BTM_BleSetPhy(address, PHY_LE_2M, PHY_LE_2M, 0);
}
@@ -2082,12 +2073,12 @@
int result = BTM_SetEncryption(address, BT_TRANSPORT_LE, nullptr, nullptr,
BTM_BLE_SEC_ENCRYPT);
- LOG_INFO("Encryption required for %s. Request result: 0x%02x",
- ADDRESS_TO_LOGGABLE_CSTR(address), result);
+ log::info("Encryption required for {}. Request result: 0x{:02x}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), result);
if (result == BTM_ERR_KEY_MISSING) {
- LOG_ERROR("Link key unknown for %s, disconnect profile",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::error("Link key unknown for {}, disconnect profile",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
bluetooth::le_audio::MetricsCollector::Get()->OnConnectionStateChanged(
leAudioDevice->group_id_, address, ConnectionState::CONNECTED,
bluetooth::le_audio::ConnectionStatus::FAILED);
@@ -2099,12 +2090,11 @@
void RegisterKnownNotifications(LeAudioDevice* leAudioDevice,
bool gatt_register, bool write_ccc) {
- LOG(INFO) << __func__ << " device: "
- << ADDRESS_TO_LOGGABLE_STR(leAudioDevice->address_);
+ log::info("device: {}", ADDRESS_TO_LOGGABLE_STR(leAudioDevice->address_));
if (leAudioDevice->ctp_hdls_.val_hdl == 0) {
- LOG_ERROR(
- "Control point characteristic is mandatory - disconnecting device %s",
+ log::error(
+ "Control point characteristic is mandatory - disconnecting device {}",
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
DisconnectDevice(leAudioDevice);
return;
@@ -2153,7 +2143,7 @@
void changeMtuIfPossible(LeAudioDevice* leAudioDevice) {
if (leAudioDevice->mtu_ == GATT_DEF_BLE_MTU_SIZE) {
- LOG(INFO) << __func__ << ", Configure MTU";
+ log::info("Configure MTU");
/* Use here kBapMinimumAttMtu, because we know that GATT will request
* default ATT MTU anyways. We also know that GATT will use this
* kBapMinimumAttMtu as an input for Data Length Update procedure in the controller.
@@ -2163,18 +2153,17 @@
}
void OnEncryptionComplete(const RawAddress& address, uint8_t status) {
- LOG_INFO("%s status 0x%02x ", ADDRESS_TO_LOGGABLE_CSTR(address), status);
+ log::info("{} status 0x{:02x}", ADDRESS_TO_LOGGABLE_CSTR(address), status);
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (leAudioDevice == NULL ||
(leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID)) {
- LOG_WARN("Skipping device which is %s",
- (leAudioDevice ? " not connected by service." : " null"));
+ log::warn("Skipping device which is {}",
+ (leAudioDevice ? " not connected by service." : " null"));
return;
}
if (status != BTM_SUCCESS) {
- LOG(ERROR) << "Encryption failed"
- << " status: " << int{status};
+ log::error("Encryption failed status: {}", int{status});
if (leAudioDevice->GetConnectionState() ==
DeviceConnectState::CONNECTED_BY_USER_GETTING_READY) {
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
@@ -2190,7 +2179,7 @@
}
if (leAudioDevice->encrypted_) {
- LOG(INFO) << __func__ << " link already encrypted, nothing to do";
+ log::info("link already encrypted, nothing to do");
return;
}
@@ -2218,7 +2207,7 @@
* just notify connected */
if (leAudioDevice->known_service_handles_ &&
!leAudioDevice->notify_connected_after_read_) {
- LOG_INFO("Wait for CCC registration and MTU change request");
+ log::info("Wait for CCC registration and MTU change request");
return;
}
@@ -2240,12 +2229,12 @@
*/
auto group = aseGroups_.FindById(group_id);
if (group == nullptr) {
- LOG_INFO("Group %d is destroyed.", group_id);
+ log::info("Group {} is destroyed.", group_id);
return;
}
if (!group->IsAnyDeviceConnected()) {
- LOG_INFO("Group %d is not connected", group_id);
+ log::info("Group {} is not connected", group_id);
/* Make sure all devices are in the default reconnection mode */
group->ApplyReconnectionMode(gatt_if_, reconnection_mode_);
return;
@@ -2259,7 +2248,7 @@
}
void scheduleGroupConnectedCheck(int group_id) {
- LOG_INFO("Schedule group_id %d connected check.", group_id);
+ log::info("Schedule group_id {} connected check.", group_id);
do_in_main_thread_delayed(
FROM_HERE,
base::BindOnce(
@@ -2271,8 +2260,8 @@
void autoConnect(RawAddress address) {
auto leAudioDevice = leAudioDevices_.FindByAddress(address);
if (leAudioDevice == nullptr) {
- LOG_WARN("Device %s not valid anymore",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("Device {} not valid anymore",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
return;
}
@@ -2280,7 +2269,7 @@
}
void scheduleAutoConnect(RawAddress& address) {
- LOG_INFO("Schedule auto connect %s ", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Schedule auto connect {}", ADDRESS_TO_LOGGABLE_CSTR(address));
do_in_main_thread_delayed(
FROM_HERE,
base::BindOnce(&LeAudioClientImpl::autoConnect,
@@ -2289,15 +2278,15 @@
}
void recoveryReconnect(RawAddress address) {
- LOG_INFO("Reconnecting to %s after timeout on state machine.",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Reconnecting to {} after timeout on state machine.",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (leAudioDevice == nullptr ||
leAudioDevice->GetConnectionState() !=
DeviceConnectState::DISCONNECTING_AND_RECOVER) {
- LOG_WARN("Device %s, not interested in recovery connect anymore",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("Device {}, not interested in recovery connect anymore",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
return;
}
@@ -2313,8 +2302,8 @@
}
void scheduleRecoveryReconnect(RawAddress& address) {
- LOG_INFO("Schedule reconnecting to %s after timeout on state machine.",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Schedule reconnecting to {} after timeout on state machine.",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
do_in_main_thread_delayed(
FROM_HERE,
base::BindOnce(&LeAudioClientImpl::recoveryReconnect,
@@ -2323,13 +2312,13 @@
}
void checkIfGroupMember(RawAddress address) {
- LOG_INFO("checking being a group member: %s",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("checking being a group member: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (leAudioDevice == nullptr) {
- LOG_WARN("Device %s, probably removed",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::warn("Device {}, probably removed",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
return;
}
@@ -2349,8 +2338,8 @@
* side.
*/
void scheduleGuardForCsisAdd(RawAddress& address) {
- LOG_INFO("Schedule reconnecting to %s after timeout on state machine.",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Schedule reconnecting to {} after timeout on state machine.",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
do_in_main_thread_delayed(
FROM_HERE,
base::BindOnce(&LeAudioClientImpl::checkIfGroupMember,
@@ -2363,8 +2352,8 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByConnId(conn_id);
if (!leAudioDevice) {
- LOG(ERROR) << ", skipping unknown leAudioDevice, address: "
- << ADDRESS_TO_LOGGABLE_STR(address);
+ log::error(", skipping unknown leAudioDevice, address: {}",
+ ADDRESS_TO_LOGGABLE_STR(address));
return;
}
@@ -2396,10 +2385,10 @@
}
auto connection_state = leAudioDevice->GetConnectionState();
- LOG_INFO("%s, autoconnect %d, reason 0x%02x, connection state %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- leAudioDevice->autoconnect_flag_, reason,
- bluetooth::common::ToString(connection_state).c_str());
+ log::info("{}, autoconnect {}, reason 0x{:02x}, connection state {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ leAudioDevice->autoconnect_flag_, reason,
+ bluetooth::common::ToString(connection_state));
if (connection_state == DeviceConnectState::DISCONNECTING_AND_RECOVER) {
/* We are back after disconnecting device which was in a bad state.
@@ -2419,8 +2408,8 @@
* issues
*/
if (group == nullptr || !group->IsEnabled()) {
- LOG_ERROR("Group id %d (%p) disabled or null", leAudioDevice->group_id_,
- group);
+ log::error("Group id {} ({}) disabled or null", leAudioDevice->group_id_,
+ fmt::ptr(group));
return;
}
@@ -2466,18 +2455,18 @@
uint16_t handle = handle_pair.val_hdl;
uint16_t ccc_handle = handle_pair.ccc_hdl;
- LOG_INFO("conn id %d, gatt_register: %b, write_ccc: %b", conn_id,
- gatt_register, write_ccc);
+ log::info("conn id {}, gatt_register: {}, write_ccc: {}", conn_id,
+ gatt_register, write_ccc);
if (gatt_register && BTA_GATTC_RegisterForNotifications(
gatt_if_, address, handle) != GATT_SUCCESS) {
- LOG(ERROR) << __func__ << ", cannot register for notification: "
- << static_cast<int>(handle);
+ log::error("cannot register for notification: {}",
+ static_cast<int>(handle));
return false;
}
if (write_ccc == false) {
- LOG_VERBOSE("CCC is not written to %s (0x%04x), handle 0x%04x",
- ADDRESS_TO_LOGGABLE_CSTR(address), conn_id, ccc_handle);
+ log::verbose("CCC is not written to {} (0x{:04x}), handle 0x{:04x}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), conn_id, ccc_handle);
return true;
}
@@ -2508,14 +2497,14 @@
void ClearDeviceInformationAndStartSearch(LeAudioDevice* leAudioDevice) {
if (!leAudioDevice) {
- LOG_WARN("leAudioDevice is null");
+ log::warn("leAudioDevice is null");
return;
}
- LOG_INFO("%s", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("{}", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
if (leAudioDevice->known_service_handles_ == false) {
- LOG_DEBUG("Database already invalidated");
+ log::debug("Database already invalidated");
return;
}
@@ -2539,8 +2528,8 @@
void OnServiceChangeEvent(const RawAddress& address) {
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) {
- LOG_WARN("Skipping unknown leAudioDevice %s (%p)",
- ADDRESS_TO_LOGGABLE_CSTR(address), leAudioDevice);
+ log::warn("Skipping unknown leAudioDevice {} ({})",
+ ADDRESS_TO_LOGGABLE_CSTR(address), fmt::ptr(leAudioDevice));
return;
}
@@ -2558,7 +2547,7 @@
void OnMtuChanged(uint16_t conn_id, uint16_t mtu) {
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByConnId(conn_id);
if (!leAudioDevice) {
- LOG_DEBUG("Unknown connectect id %d", conn_id);
+ log::debug("Unknown connectect id {}", conn_id);
return;
}
@@ -2571,8 +2560,8 @@
*
*/
if (mtu < 64) {
- LOG_ERROR("Device %s MTU is too low (%d). Disconnecting from LE Audio",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), mtu);
+ log::error("Device {} MTU is too low ({}). Disconnecting from LE Audio",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), mtu);
Disconnect(leAudioDevice->address_);
return;
}
@@ -2583,13 +2572,13 @@
void OnGattServiceDiscoveryDone(const RawAddress& address) {
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice || (leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID)) {
- LOG_VERBOSE("skipping unknown leAudioDevice, address %s (%p) ",
- ADDRESS_TO_LOGGABLE_CSTR(address), leAudioDevice);
+ log::verbose("skipping unknown leAudioDevice, address {} ({})",
+ ADDRESS_TO_LOGGABLE_CSTR(address), fmt::ptr(leAudioDevice));
return;
}
if (!leAudioDevice->encrypted_) {
- LOG_DEBUG("Wait for device to be encrypted");
+ log::debug("Wait for device to be encrypted");
return;
}
@@ -2602,8 +2591,8 @@
void disconnectInvalidDevice(LeAudioDevice* leAudioDevice,
std::string error_string,
LeAudioHealthDeviceStatType stat) {
- LOG_ERROR("%s, %s", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- error_string.c_str());
+ log::error("{}, {}", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ error_string);
if (leAudioHealthStatus_) {
leAudioHealthStatus_->AddStatisticForDevice(leAudioDevice, stat);
}
@@ -2623,19 +2612,18 @@
return;
}
- LOG(INFO) << __func__ << " test csis_member "
- << leAudioDevice->csis_member_;
+ log::info("test csis_member {}", leAudioDevice->csis_member_);
if (status != GATT_SUCCESS) {
/* close connection and report service discovery complete with error */
- LOG(ERROR) << "Service discovery failed";
+ log::error("Service discovery failed");
DisconnectDevice(leAudioDevice);
return;
}
if (!leAudioDevice->encrypted_) {
- LOG_WARN("Device not yet bonded - waiting for encryption");
+ log::warn("Device not yet bonded - waiting for encryption");
return;
}
@@ -2651,29 +2639,30 @@
for (const gatt::Service& tmp : *services) {
if (tmp.uuid ==
bluetooth::le_audio::uuid::kPublishedAudioCapabilityServiceUuid) {
- LOG_INFO("Found Audio Capability service, handle: 0x%04x, device: %s",
- tmp.handle, ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info(
+ "Found Audio Capability service, handle: 0x{:04x}, device: {}",
+ tmp.handle, ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
pac_svc = &tmp;
} else if (tmp.uuid ==
bluetooth::le_audio::uuid::kAudioStreamControlServiceUuid) {
- LOG_INFO(
- "Found Audio Stream Endpoint service, handle: 0x%04x, device: %s",
+ log::info(
+ "Found Audio Stream Endpoint service, handle: 0x{:04x}, device: {}",
tmp.handle, ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
ase_svc = &tmp;
} else if (tmp.uuid == bluetooth::csis::kCsisServiceUuid) {
- LOG_INFO(
- "Found CSIS service, handle: 0x%04x, is primary: %d, device: %s",
+ log::info(
+ "Found CSIS service, handle: 0x{:04x}, is primary: {}, device: {}",
tmp.handle, tmp.is_primary,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
if (tmp.is_primary) csis_primary_handles.push_back(tmp.handle);
} else if (tmp.uuid == bluetooth::le_audio::uuid::kCapServiceUuid) {
- LOG_INFO("Found CAP service, handle: 0x%04x, device: %s", tmp.handle,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("Found CAP service, handle: 0x{:04x}, device: {}", tmp.handle,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
/* Try to find context for CSIS instances */
for (auto& included_srvc : tmp.included_services) {
if (included_srvc.uuid == bluetooth::csis::kCsisServiceUuid) {
- LOG(INFO) << __func__ << " CSIS included into CAS";
+ log::info("CSIS included into CAS");
if (bluetooth::csis::CsisClient::IsCsisClientRunning())
cas_csis_included_handle = included_srvc.start_handle;
@@ -2682,9 +2671,9 @@
}
} else if (tmp.uuid ==
bluetooth::le_audio::uuid::kTelephonyMediaAudioServiceUuid) {
- LOG_INFO(
- "Found Telephony and Media Audio service, handle: 0x%04x, device: "
- "%s",
+ log::info(
+ "Found Telephony and Media Audio service, handle: 0x{:04x}, "
+ "device: {}",
tmp.handle, ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
tmas_svc = &tmp;
}
@@ -2717,7 +2706,7 @@
hdl_pair.ccc_hdl = find_ccc_handle(charac);
if (hdl_pair.ccc_hdl == 0) {
- LOG_INFO(", Sink PACs ccc not available");
+ log::info(", Sink PACs ccc not available");
}
if (hdl_pair.ccc_hdl != 0 &&
@@ -2737,9 +2726,9 @@
hdl_pair,
std::vector<struct bluetooth::le_audio::types::acs_ac_record>()));
- LOG_INFO(
- "Found Sink PAC characteristic, handle: 0x%04x, ccc handle: "
- "0x%04x, addr: %s",
+ log::info(
+ "Found Sink PAC characteristic, handle: 0x{:04x}, ccc handle: "
+ "0x{:04x}, addr: {}",
charac.value_handle, hdl_pair.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
} else if (charac.uuid ==
@@ -2750,7 +2739,7 @@
hdl_pair.ccc_hdl = find_ccc_handle(charac);
if (hdl_pair.ccc_hdl == 0) {
- LOG_INFO(", Source PACs ccc not available");
+ log::info(", Source PACs ccc not available");
}
if (hdl_pair.ccc_hdl != 0 &&
@@ -2770,9 +2759,9 @@
hdl_pair,
std::vector<struct bluetooth::le_audio::types::acs_ac_record>()));
- LOG_INFO(
- "Found Source PAC characteristic, handle: 0x%04x, ccc handle: "
- "0x%04x, addr: %s",
+ log::info(
+ "Found Source PAC characteristic, handle: 0x{:04x}, ccc handle: "
+ "0x{:04x}, addr: {}",
charac.value_handle, hdl_pair.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
} else if (charac.uuid == bluetooth::le_audio::uuid::
@@ -2782,7 +2771,7 @@
find_ccc_handle(charac);
if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl == 0) {
- LOG_INFO(", snk audio locations char doesn't have ccc");
+ log::info(", snk audio locations char doesn't have ccc");
}
if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl != 0 &&
@@ -2800,9 +2789,9 @@
conn_id, leAudioDevice->snk_audio_locations_hdls_.val_hdl,
OnGattReadRspStatic, NULL);
- LOG_INFO(
- "Found Sink audio locations characteristic, handle: 0x%04x, ccc "
- "handle: 0x%04x, addr: %s",
+ log::info(
+ "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc "
+ "handle: 0x{:04x}, addr: {}",
charac.value_handle,
leAudioDevice->snk_audio_locations_hdls_.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
@@ -2813,7 +2802,7 @@
find_ccc_handle(charac);
if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl == 0) {
- LOG_INFO(", src audio locations char doesn't have ccc");
+ log::info(", src audio locations char doesn't have ccc");
}
if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl != 0 &&
@@ -2831,9 +2820,9 @@
conn_id, leAudioDevice->src_audio_locations_hdls_.val_hdl,
OnGattReadRspStatic, NULL);
- LOG_INFO(
- "Found Source audio locations characteristic, handle: 0x%04x, ccc "
- "handle: 0x%04x, addr: %s",
+ log::info(
+ "Found Source audio locations characteristic, handle: 0x{:04x}, "
+ "ccc handle: 0x{:04x}, addr: {}",
charac.value_handle,
leAudioDevice->src_audio_locations_hdls_.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
@@ -2863,9 +2852,9 @@
conn_id, leAudioDevice->audio_avail_hdls_.val_hdl,
OnGattReadRspStatic, NULL);
- LOG_INFO(
- "Found Audio Availability Context characteristic, handle: 0x%04x, "
- "ccc handle: 0x%04x, addr: %s",
+ log::info(
+ "Found Audio Availability Context characteristic, handle: "
+ "0x{:04x}, ccc handle: 0x{:04x}, addr: {}",
charac.value_handle, leAudioDevice->audio_avail_hdls_.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
} else if (charac.uuid == bluetooth::le_audio::uuid::
@@ -2874,7 +2863,7 @@
leAudioDevice->audio_supp_cont_hdls_.ccc_hdl = find_ccc_handle(charac);
if (leAudioDevice->audio_supp_cont_hdls_.ccc_hdl == 0) {
- LOG_INFO(", audio supported char doesn't have ccc");
+ log::info(", audio supported char doesn't have ccc");
}
if (leAudioDevice->audio_supp_cont_hdls_.ccc_hdl != 0 &&
@@ -2892,9 +2881,9 @@
conn_id, leAudioDevice->audio_supp_cont_hdls_.val_hdl,
OnGattReadRspStatic, NULL);
- LOG_INFO(
- "Found Audio Supported Context characteristic, handle: 0x%04x, ccc "
- "handle: 0x%04x, addr: %s",
+ log::info(
+ "Found Audio Supported Context characteristic, handle: 0x{:04x}, "
+ "ccc handle: 0x{:04x}, addr: {}",
charac.value_handle, leAudioDevice->audio_supp_cont_hdls_.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
}
@@ -2904,7 +2893,7 @@
leAudioDevice->ases_.clear();
for (const gatt::Characteristic& charac : ase_svc->characteristics) {
- LOG(INFO) << "Found characteristic, uuid: " << charac.uuid.ToString();
+ log::info("Found characteristic, uuid: {}", charac.uuid.ToString());
if (charac.uuid ==
bluetooth::le_audio::uuid::kSinkAudioStreamEndpointUuid ||
charac.uuid ==
@@ -2934,9 +2923,9 @@
leAudioDevice->ases_.emplace_back(charac.value_handle, ccc_handle,
direction);
- LOG_INFO(
- "Found ASE characteristic, handle: 0x%04x, ccc handle: 0x%04x, "
- "direction: %d, addr: %s",
+ log::info(
+ "Found ASE characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, "
+ "direction: {}, addr: {}",
charac.value_handle, ccc_handle, direction,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
} else if (charac.uuid ==
@@ -2959,9 +2948,9 @@
return;
}
- LOG_INFO(
- "Found ASE Control Point characteristic, handle: 0x%04x, "
- "ccc handle: 0x%04x, addr: %s",
+ log::info(
+ "Found ASE Control Point characteristic, handle: 0x{:04x}, ccc "
+ "handle: 0x{:04x}, addr: {}",
charac.value_handle, leAudioDevice->ctp_hdls_.ccc_hdl,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
}
@@ -2979,10 +2968,9 @@
leAudioDevice->tmap_role_hdl_,
OnGattReadRspStatic, NULL);
- LOG_INFO(
+ log::info(
"Found Telephony and Media Profile characteristic, handle: "
- "0x%04x, "
- "device: %s",
+ "0x{:04x}, device: {}",
leAudioDevice->tmap_role_hdl_,
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
}
@@ -3015,14 +3003,14 @@
/* CSIS will trigger adding to group */
if (leAudioDevice->csis_member_) {
- LOG_INFO(" %s, waiting for CSIS to create group for device ",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("{}, waiting for CSIS to create group for device",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
scheduleGuardForCsisAdd(leAudioDevice->address_);
return;
}
- LOG_INFO("%s Not a CSIS member. Create group by our own",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("{} Not a CSIS member. Create group by our own",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
/* If there is no Csis just add device by our own */
DeviceGroups::Get()->AddDevice(leAudioDevice->address_,
@@ -3035,20 +3023,20 @@
std::vector<struct ase>::iterator ase_it;
if (!leAudioDevice) {
- LOG(ERROR) << __func__ << ", unknown conn_id=" << loghex(conn_id);
+ log::error("unknown conn_id={}", loghex(conn_id));
return;
}
if (status == GATT_DATABASE_OUT_OF_SYNC) {
- LOG_INFO("Database out of sync for %s, conn_id: 0x%04x",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), conn_id);
+ log::info("Database out of sync for {}, conn_id: 0x{:04x}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), conn_id);
ClearDeviceInformationAndStartSearch(leAudioDevice);
return;
}
if (status == GATT_SUCCESS) {
- LOG_INFO("Successfully registered on ccc: 0x%04x, device: %s", hdl,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("Successfully registered on ccc: 0x{:04x}, device: {}", hdl,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
if (leAudioDevice->ctp_hdls_.ccc_hdl == hdl &&
leAudioDevice->known_service_handles_ &&
@@ -3061,9 +3049,9 @@
return;
}
- LOG_ERROR(
- "Failed to register for indications: 0x%04x, device: %s, status: "
- "0x%02x",
+ log::error(
+ "Failed to register for indications: 0x{:04x}, device: {}, status: "
+ "0x{:02x}",
hdl, ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), status);
ase_it =
@@ -3073,8 +3061,8 @@
});
if (ase_it == leAudioDevice->ases_.end()) {
- LOG_ERROR("Unknown ccc handle: 0x%04x, device: %s", hdl,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Unknown ccc handle: 0x{:04x}, device: {}", hdl,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
@@ -3084,8 +3072,8 @@
void AttachToStreamingGroupIfNeeded(LeAudioDevice* leAudioDevice) {
if (leAudioDevice->group_id_ != active_group_id_) {
- LOG(INFO) << __func__ << " group " << leAudioDevice->group_id_
- << " is not streaming. Nothing to do";
+ log::info("group {} is not streaming. Nothing to do",
+ leAudioDevice->group_id_);
return;
}
@@ -3095,12 +3083,12 @@
get_bidirectional(group->GetMetadataContexts());
auto device_available_contexts = leAudioDevice->GetAvailableContexts();
if (!group_metadata_contexts.test_any(device_available_contexts)) {
- LOG_INFO("%s does is not have required context type",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("{} does is not have required context type",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
- LOG_INFO("Attaching to group: %d", leAudioDevice->group_id_);
+ log::info("Attaching to group: {}", leAudioDevice->group_id_);
/* Restore configuration */
auto* stream_conf = &group->stream_conf;
@@ -3113,7 +3101,7 @@
}
if (!stream_conf->conf) {
- LOG_INFO("Configuration not yet set. Nothing to do now");
+ log::info("Configuration not yet set. Nothing to do now");
return;
}
@@ -3146,9 +3134,9 @@
if (!groupStateMachine_->AttachToStream(group, leAudioDevice,
std::move(ccids))) {
- LOG_WARN("Could not add device %s to the group %d streaming. ",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- group->group_id_);
+ log::warn("Could not add device {} to the group {} streaming.",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ group->group_id_);
scheduleAttachDeviceToTheStream(leAudioDevice->address_);
} else {
stream_setup_start_timestamp_ =
@@ -3160,15 +3148,15 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(addr);
if (leAudioDevice == nullptr ||
leAudioDevice->conn_id_ == GATT_INVALID_CONN_ID) {
- LOG_INFO("Device %s not available anymore",
- ADDRESS_TO_LOGGABLE_CSTR(addr));
+ log::info("Device {} not available anymore",
+ ADDRESS_TO_LOGGABLE_CSTR(addr));
return;
}
AttachToStreamingGroupIfNeeded(leAudioDevice);
}
void scheduleAttachDeviceToTheStream(const RawAddress& addr) {
- LOG_INFO("Device %s scheduler for stream ", ADDRESS_TO_LOGGABLE_CSTR(addr));
+ log::info("Device {} scheduler for stream", ADDRESS_TO_LOGGABLE_CSTR(addr));
do_in_main_thread_delayed(
FROM_HERE,
base::BindOnce(&LeAudioClientImpl::restartAttachToTheStream,
@@ -3180,8 +3168,8 @@
// This shall be called when device gets active
auto* stream_conf = &group->stream_conf;
if (stream_conf == nullptr) {
- LOG_WARN("Stream configuration is not valid for group id %d",
- group->group_id_);
+ log::warn("Stream configuration is not valid for group id {}",
+ group->group_id_);
return;
}
@@ -3198,8 +3186,8 @@
// This shall be called when configuration changes
auto* stream_conf = &group->stream_conf;
if (stream_conf == nullptr) {
- LOG_WARN("Stream configuration is not valid for group id %d",
- group->group_id_);
+ log::warn("Stream configuration is not valid for group id {}",
+ group->group_id_);
return;
}
@@ -3217,9 +3205,9 @@
}
void connectionReady(LeAudioDevice* leAudioDevice) {
- LOG_DEBUG("%s, %s", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- bluetooth::common::ToString(leAudioDevice->GetConnectionState())
- .c_str());
+ log::debug(
+ "{}, {}", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ bluetooth::common::ToString(leAudioDevice->GetConnectionState()));
if (IS_FLAG_ENABLED(le_audio_fast_bond_params)) {
L2CA_LockBleConnParamsForProfileConnection(leAudioDevice->address_,
@@ -3292,7 +3280,7 @@
*out++ = accum;
}
} else {
- LOG_ERROR("Don't know how to mono blend that %d!", bytes_per_sample);
+ log::error("Don't know how to mono blend that {}!", bytes_per_sample);
}
return mono_out;
}
@@ -3308,10 +3296,8 @@
uint8_t bytes_per_sample = sw_enc_left->GetNumOfBytesPerSample();
if (data.size() < bytes_per_sample * 2 /* channels */ *
number_of_required_samples_per_channel) {
- LOG(ERROR) << __func__ << " Missing samples. Data size: " << +data.size()
- << " expected: "
- << bytes_per_sample * 2 *
- number_of_required_samples_per_channel;
+ log::error("Missing samples. Data size: {} expected: {}", data.size(),
+ bytes_per_sample * 2 * number_of_required_samples_per_channel);
return;
}
@@ -3368,7 +3354,7 @@
uint8_t bytes_per_sample = sw_enc_left->GetNumOfBytesPerSample();
if ((int)data.size() < (bytes_per_sample * num_channels *
number_of_required_samples_per_channel)) {
- LOG(ERROR) << __func__ << "Missing samples";
+ log::error("Missing samples");
return;
}
@@ -3396,12 +3382,12 @@
GetStreamSinkConfiguration(LeAudioDeviceGroup* group) {
const struct bluetooth::le_audio::stream_configuration* stream_conf =
&group->stream_conf;
- LOG_INFO("group_id: %d", group->group_id_);
+ log::info("group_id: {}", group->group_id_);
if (stream_conf->stream_params.sink.stream_locations.size() == 0) {
return nullptr;
}
- LOG_INFO("configuration: %s", stream_conf->conf->name.c_str());
+ log::info("configuration: {}", stream_conf->conf->name);
return stream_conf;
}
@@ -3412,7 +3398,7 @@
LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG(ERROR) << __func__ << "There is no streaming group available";
+ log::error("There is no streaming group available");
return;
}
@@ -3420,7 +3406,7 @@
if ((stream_conf.stream_params.sink.num_of_devices > 2) ||
(stream_conf.stream_params.sink.num_of_devices == 0) ||
stream_conf.stream_params.sink.stream_locations.empty()) {
- LOG(ERROR) << __func__ << " Stream configufation is not valid.";
+ log::error("Stream configufation is not valid.");
return;
}
@@ -3450,7 +3436,7 @@
LeAudioDeviceGroup* group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG(ERROR) << __func__ << "There is no streaming group available";
+ log::error("There is no streaming group available");
return;
}
@@ -3474,7 +3460,7 @@
} else if (cis_conn_hdl == right_cis_handle) {
decoder = sw_dec_right.get();
} else {
- LOG_ERROR("Received data for unknown handle: %04x", cis_conn_hdl);
+ log::error("Received data for unknown handle: {:04x}", cis_conn_hdl);
return;
}
@@ -3574,7 +3560,7 @@
}
/* TODO: What to do if not all data sinked ? */
- if (written != to_write) LOG(ERROR) << __func__ << ", not all data sinked";
+ if (written != to_write) log::error("not all data sinked");
}
void ConfirmLocalAudioSourceStreamingRequest() {
@@ -3600,7 +3586,7 @@
}
void StartSendingAudio(int group_id) {
- LOG(INFO) << __func__;
+ log::info("");
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
LeAudioDevice* device = group->GetFirstActiveDevice();
@@ -3610,24 +3596,24 @@
/* Assume 2 ases max just for now. */
auto* stream_conf = GetStreamSinkConfiguration(group);
if (stream_conf == nullptr) {
- LOG(ERROR) << __func__ << " could not get sink configuration";
+ log::error("could not get sink configuration");
groupStateMachine_->StopStream(group);
return;
}
- LOG_DEBUG("Sink stream config (#%d):\n",
- static_cast<int>(
- stream_conf->stream_params.sink.stream_locations.size()));
+ log::debug("Sink stream config (#{}):\n",
+ static_cast<int>(
+ stream_conf->stream_params.sink.stream_locations.size()));
for (auto stream : stream_conf->stream_params.sink.stream_locations) {
- LOG_DEBUG("Cis handle: 0x%02x, allocation 0x%04x\n", stream.first,
- stream.second);
+ log::debug("Cis handle: 0x{:02x}, allocation 0x{:04x}\n", stream.first,
+ stream.second);
}
- LOG_DEBUG("Source stream config (#%d):\n",
- static_cast<int>(
- stream_conf->stream_params.source.stream_locations.size()));
+ log::debug("Source stream config (#{}):\n",
+ static_cast<int>(
+ stream_conf->stream_params.source.stream_locations.size()));
for (auto stream : stream_conf->stream_params.source.stream_locations) {
- LOG_DEBUG("Cis handle: 0x%02x, allocation 0x%04x\n", stream.first,
- stream.second);
+ log::debug("Cis handle: 0x{:02x}, allocation 0x{:04x}\n", stream.first,
+ stream.second);
}
uint16_t remote_delay_ms = group->GetRemoteDelay(
@@ -3635,8 +3621,7 @@
if (CodecManager::GetInstance()->GetCodecLocation() ==
bluetooth::le_audio::types::CodecLocation::HOST) {
if (sw_enc_left || sw_enc_right) {
- LOG(WARNING)
- << " The encoder instance should have been already released.";
+ log::warn("The encoder instance should have been already released.");
}
sw_enc_left = bluetooth::le_audio::CodecInterface::CreateInstance(
stream_conf->codec_id);
@@ -3644,7 +3629,8 @@
audio_framework_source_config, current_source_codec_config);
if (codec_status !=
bluetooth::le_audio::CodecInterface::Status::STATUS_OK) {
- LOG_ERROR("Left channel codec setup failed with err: %d", codec_status);
+ log::error("Left channel codec setup failed with err: {}",
+ codec_status);
groupStateMachine_->StopStream(group);
return;
}
@@ -3655,8 +3641,8 @@
current_source_codec_config);
if (codec_status !=
bluetooth::le_audio::CodecInterface::Status::STATUS_OK) {
- LOG_ERROR("Right channel codec setup failed with err: %d",
- codec_status);
+ log::error("Right channel codec setup failed with err: {}",
+ codec_status);
groupStateMachine_->StopStream(group);
return;
}
@@ -3688,19 +3674,21 @@
if (stream_conf->stream_params.source.stream_locations.size() == 0) {
return nullptr;
}
- LOG_INFO("configuration: %s", stream_conf->conf->name.c_str());
+ log::info("configuration: {}", stream_conf->conf->name);
return stream_conf;
}
void StartReceivingAudio(int group_id) {
- LOG(INFO) << __func__;
+ log::info("");
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
auto* stream_conf = GetStreamSourceConfiguration(group);
if (!stream_conf) {
- LOG(WARNING) << " Could not get source configuration for group "
- << active_group_id_ << " probably microphone not configured";
+ log::warn(
+ "Could not get source configuration for group {} probably microphone "
+ "not configured",
+ active_group_id_);
groupStateMachine_->StopStream(group);
return;
}
@@ -3713,8 +3701,7 @@
if (CodecManager::GetInstance()->GetCodecLocation() ==
bluetooth::le_audio::types::CodecLocation::HOST) {
if (sw_dec_left.get() || sw_dec_right.get()) {
- LOG(WARNING)
- << " The decoder instance should have been already released.";
+ log::warn("The decoder instance should have been already released.");
}
sw_dec_left = bluetooth::le_audio::CodecInterface::CreateInstance(
stream_conf->codec_id);
@@ -3722,7 +3709,8 @@
audio_framework_sink_config);
if (codec_status !=
bluetooth::le_audio::CodecInterface::Status::STATUS_OK) {
- LOG_ERROR("Left channel codec setup failed with err: %d", codec_status);
+ log::error("Left channel codec setup failed with err: {}",
+ codec_status);
groupStateMachine_->StopStream(group);
return;
}
@@ -3733,8 +3721,8 @@
audio_framework_sink_config);
if (codec_status !=
bluetooth::le_audio::CodecInterface::Status::STATUS_OK) {
- LOG_ERROR("Right channel codec setup failed with err: %d",
- codec_status);
+ log::error("Right channel codec setup failed with err: {}",
+ codec_status);
groupStateMachine_->StopStream(group);
return;
}
@@ -3889,14 +3877,12 @@
bool sink_cfg_available = true;
bool source_cfg_available = true;
- LOG_DEBUG("Checking whether to reconfigure from %s to %s",
- ToString(configuration_context_type_).c_str(),
- ToString(context_type).c_str());
+ log::debug("Checking whether to reconfigure from {} to {}",
+ ToString(configuration_context_type_), ToString(context_type));
auto group = aseGroups_.FindById(group_id);
if (!group) {
- LOG(ERROR) << __func__
- << ", Invalid group: " << static_cast<int>(group_id);
+ log::error("Invalid group: {}", static_cast<int>(group_id));
return AudioReconfigurationResult::RECONFIGURATION_NOT_NEEDED;
}
@@ -3938,11 +3924,11 @@
reconfiguration_needed = true;
}
- LOG_DEBUG(
- " Context: %s Reconfiguration_needed = %d, sink_cfg_available = %d, "
- "source_cfg_available = %d",
- ToString(context_type).c_str(), reconfiguration_needed,
- sink_cfg_available, source_cfg_available);
+ log::debug(
+ "Context: {} Reconfiguration_needed = {}, sink_cfg_available = {}, "
+ "source_cfg_available = {}",
+ ToString(context_type), reconfiguration_needed, sink_cfg_available,
+ source_cfg_available);
if (!reconfiguration_needed) {
// Assign the new configuration context as it reprents the current
@@ -3959,8 +3945,8 @@
return AudioReconfigurationResult::RECONFIGURATION_NOT_POSSIBLE;
}
- LOG_INFO(" Session reconfiguration needed group: %d for context type: %s",
- group->group_id_, ToHexString(context_type).c_str());
+ log::info("Session reconfiguration needed group: {} for context type: {}",
+ group->group_id_, ToHexString(context_type));
configuration_context_type_ = context_type;
return AudioReconfigurationResult::RECONFIGURATION_NEEDED;
@@ -3979,7 +3965,7 @@
remote_direction);
if (!remote_contexts.sink.any() && !remote_contexts.source.any()) {
- LOG_WARN("Requested context type not available on the remote side");
+ log::warn("Requested context type not available on the remote side");
if (leAudioHealthStatus_) {
leAudioHealthStatus_->AddStatisticForGroup(
group, LeAudioHealthGroupStatType::STREAM_CONTEXT_NOT_AVAILABLE);
@@ -3993,13 +3979,13 @@
void OnAudioSuspend() {
if (active_group_id_ == bluetooth::groups::kGroupUnknown) {
- LOG(WARNING) << ", there is no longer active group";
+ log::warn(", there is no longer active group");
return;
}
if (stack_config_get_interface()
->get_pts_le_audio_disable_ases_before_stopping()) {
- LOG_INFO("Stream disable_timer_ started");
+ log::info("Stream disable_timer_ started");
if (alarm_is_scheduled(disable_timer_)) alarm_cancel(disable_timer_);
alarm_set_on_mloop(
@@ -4020,8 +4006,8 @@
timeoutMs += kAudioDisableTimeoutMs;
}
- LOG_DEBUG("Stream suspend_timeout_ started: %d ms",
- static_cast<int>(timeoutMs));
+ log::debug("Stream suspend_timeout_ started: {} ms",
+ static_cast<int>(timeoutMs));
if (alarm_is_scheduled(suspend_timeout_)) alarm_cancel(suspend_timeout_);
alarm_set_on_mloop(
@@ -4033,11 +4019,11 @@
}
void OnLocalAudioSourceSuspend() {
- LOG_INFO(
- "active group_id: %d, IN: audio_receiver_state_: %s, "
- "audio_sender_state_: %s",
- active_group_id_, ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info(
+ "active group_id: {}, IN: audio_receiver_state_: {}, "
+ "audio_sender_state_: {}",
+ active_group_id_, ToString(audio_receiver_state_),
+ ToString(audio_sender_state_));
LeAudioLogHistory::Get()->AddLogHistory(
kLogAfCallBt, active_group_id_, RawAddress::kEmpty,
kLogAfSuspend + "LocalSource",
@@ -4072,9 +4058,8 @@
active_group_id_);
}
- LOG_INFO("OUT: audio_receiver_state_: %s, audio_sender_state_: %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info("OUT: audio_receiver_state_: {}, audio_sender_state_: {}",
+ ToString(audio_receiver_state_), ToString(audio_sender_state_));
LeAudioLogHistory::Get()->AddLogHistory(
kLogBtCallAf, active_group_id_, RawAddress::kEmpty,
@@ -4084,11 +4069,11 @@
}
void OnLocalAudioSourceResume() {
- LOG_INFO(
- "active group_id: %d, IN: audio_receiver_state_: %s, "
- "audio_sender_state_: %s",
- active_group_id_, ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info(
+ "active group_id: {}, IN: audio_receiver_state_: {}, "
+ "audio_sender_state_: {}",
+ active_group_id_, ToString(audio_receiver_state_),
+ ToString(audio_sender_state_));
LeAudioLogHistory::Get()->AddLogHistory(
kLogAfCallBt, active_group_id_, RawAddress::kEmpty,
kLogAfResume + "LocalSource",
@@ -4101,8 +4086,7 @@
*/
auto group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG(ERROR) << __func__
- << ", Invalid group: " << static_cast<int>(active_group_id_);
+ log::error("Invalid group: {}", static_cast<int>(active_group_id_));
return;
}
@@ -4110,8 +4094,8 @@
if (!group->GetCodecConfigurationByDirection(
configuration_context_type_,
bluetooth::le_audio::types::kLeAudioDirectionSink)) {
- LOG(ERROR) << __func__ << ", invalid resume request for context type: "
- << ToHexString(configuration_context_type_);
+ log::error("invalid resume request for context type: {}",
+ ToHexString(configuration_context_type_));
CancelLocalAudioSourceStreamingRequest();
return;
}
@@ -4144,14 +4128,14 @@
audio_sender_state_ = AudioState::READY_TO_START;
if (!IsDirectionAvailableForCurrentConfiguration(
group, bluetooth::le_audio::types::kLeAudioDirectionSink)) {
- LOG_WARN(
- " sink is not configured. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::warn(
+ "sink is not configured. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
SetConfigurationAndStopStreamWhenNeeded(
group, configuration_context_type_);
@@ -4169,27 +4153,27 @@
bluetooth::le_audio::types::kLeAudioDirectionSink)) {
StartSendingAudio(active_group_id_);
} else {
- LOG_WARN(
- " sink is not configured. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::warn(
+ "sink is not configured. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
SetConfigurationAndStopStreamWhenNeeded(
group, configuration_context_type_);
}
} else {
- LOG_ERROR(
- " called in wrong state. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::error(
+ "called in wrong state. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
CancelStreamingRequest();
}
@@ -4209,27 +4193,27 @@
bluetooth::le_audio::types::kLeAudioDirectionSink)) {
StartSendingAudio(active_group_id_);
} else {
- LOG_WARN(
- " sink is not configured. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::warn(
+ "sink is not configured. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
SetConfigurationAndStopStreamWhenNeeded(
group, configuration_context_type_);
}
} else {
- LOG_ERROR(
- " called in wrong state. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::error(
+ "called in wrong state. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
CancelStreamingRequest();
}
@@ -4237,15 +4221,13 @@
}
break;
case AudioState::READY_TO_START:
- LOG_ERROR(
+ log::error(
"called in wrong state, ignoring double start request. \n "
- "audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ "audio_receiver_state: {} \naudio_sender_state: {} \n "
+ "isPendingConfiguration: {} \n Reconfiguring to {}",
+ ToString(audio_receiver_state_), ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
break;
case AudioState::READY_TO_RELEASE:
@@ -4274,11 +4256,11 @@
}
void OnLocalAudioSinkSuspend() {
- LOG_INFO(
- "active group_id: %d, IN: audio_receiver_state_: %s, "
- "audio_sender_state_: %s",
- active_group_id_, ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info(
+ "active group_id: {}, IN: audio_receiver_state_: {}, "
+ "audio_sender_state_: {}",
+ active_group_id_, ToString(audio_receiver_state_),
+ ToString(audio_sender_state_));
LeAudioLogHistory::Get()->AddLogHistory(
kLogAfCallBt, active_group_id_, RawAddress::kEmpty,
kLogAfSuspend + "LocalSink",
@@ -4312,9 +4294,8 @@
(audio_sender_state_ == AudioState::READY_TO_RELEASE))
OnAudioSuspend();
- LOG_INFO("OUT: audio_receiver_state_: %s, audio_sender_state_: %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info("OUT: audio_receiver_state_: {}, audio_sender_state_: {}",
+ ToString(audio_receiver_state_), ToString(audio_sender_state_));
LeAudioLogHistory::Get()->AddLogHistory(
kLogBtCallAf, active_group_id_, RawAddress::kEmpty,
@@ -4333,8 +4314,8 @@
void notifyAudioLocalSink(UnicastMonitorModeStatus status) {
if (sink_monitor_notified_status_ != status) {
- LOG_INFO("Stream monitoring status changed to: %d",
- static_cast<int>(status));
+ log::info("Stream monitoring status changed to: {}",
+ static_cast<int>(status));
sink_monitor_notified_status_ = status;
callbacks_->OnUnicastMonitorModeStatus(
bluetooth::le_audio::types::kLeAudioDirectionSink, status);
@@ -4342,11 +4323,11 @@
}
void OnLocalAudioSinkResume() {
- LOG_INFO(
- "active group_id: %d IN: audio_receiver_state_: %s, "
- "audio_sender_state_: %s",
- active_group_id_, ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info(
+ "active group_id: {} IN: audio_receiver_state_: {}, "
+ "audio_sender_state_: {}",
+ active_group_id_, ToString(audio_receiver_state_),
+ ToString(audio_sender_state_));
LeAudioLogHistory::Get()->AddLogHistory(
kLogAfCallBt, active_group_id_, RawAddress::kEmpty,
kLogAfResume + "LocalSink",
@@ -4372,8 +4353,7 @@
*/
auto group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG(ERROR) << __func__
- << ", Invalid group: " << static_cast<int>(active_group_id_);
+ log::error("Invalid group: {}", static_cast<int>(active_group_id_));
return;
}
@@ -4389,8 +4369,8 @@
if (!group->GetCodecConfigurationByDirection(
configuration_context_type_,
bluetooth::le_audio::types::kLeAudioDirectionSource)) {
- LOG(ERROR) << __func__ << ", invalid resume request for context type: "
- << ToHexString(configuration_context_type_);
+ log::error("invalid resume request for context type: {}",
+ ToHexString(configuration_context_type_));
CancelLocalAudioSinkStreamingRequest();
return;
}
@@ -4421,14 +4401,14 @@
if (!IsDirectionAvailableForCurrentConfiguration(
group,
bluetooth::le_audio::types::kLeAudioDirectionSource)) {
- LOG_WARN(
- " source is not configured. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::warn(
+ "source is not configured. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
SetConfigurationAndStopStreamWhenNeeded(
group, configuration_context_type_);
@@ -4446,27 +4426,27 @@
bluetooth::le_audio::types::kLeAudioDirectionSource)) {
StartReceivingAudio(active_group_id_);
} else {
- LOG_WARN(
- " source is not configured. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::warn(
+ "source is not configured. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
SetConfigurationAndStopStreamWhenNeeded(
group, configuration_context_type_);
}
} else {
- LOG_ERROR(
- " called in wrong state. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::error(
+ "called in wrong state. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
CancelStreamingRequest();
}
@@ -4487,27 +4467,27 @@
bluetooth::le_audio::types::kLeAudioDirectionSource)) {
StartReceivingAudio(active_group_id_);
} else {
- LOG_WARN(
- " source is not configured. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::warn(
+ "source is not configured. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
SetConfigurationAndStopStreamWhenNeeded(
group, configuration_context_type_);
}
} else {
- LOG_ERROR(
- " called in wrong state. \n audio_receiver_state: %s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::error(
+ "called in wrong state. \n audio_receiver_state: {} "
+ "\naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_),
+ ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
CancelStreamingRequest();
}
@@ -4515,15 +4495,13 @@
}
break;
case AudioState::READY_TO_START:
- LOG_ERROR(
- " Double resume request, just ignore it.. \n audio_receiver_state: "
- "%s \n"
- "audio_sender_state: %s \n isPendingConfiguration: %s \n "
- "Reconfiguring to %s",
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(),
+ log::error(
+ "Double resume request, just ignore it.. \n audio_receiver_state: "
+ "{} \naudio_sender_state: {} \n isPendingConfiguration: {} \n "
+ "Reconfiguring to {}",
+ ToString(audio_receiver_state_), ToString(audio_sender_state_),
(group->IsPendingConfiguration() ? "true" : "false"),
- ToString(configuration_context_type_).c_str());
+ ToString(configuration_context_type_));
group->PrintDebugState();
break;
case AudioState::READY_TO_RELEASE:
@@ -4556,12 +4534,12 @@
*/
LeAudioContextType ChooseConfigurationContextType(
AudioContexts available_remote_contexts) {
- LOG_DEBUG("Got contexts=%s in config_context=%s",
- bluetooth::common::ToString(available_remote_contexts).c_str(),
- bluetooth::common::ToString(configuration_context_type_).c_str());
+ log::debug("Got contexts={} in config_context={}",
+ bluetooth::common::ToString(available_remote_contexts),
+ bluetooth::common::ToString(configuration_context_type_));
if (IsInCall()) {
- LOG_DEBUG(" In Call preference used.");
+ log::debug("In Call preference used.");
return LeAudioContextType::CONVERSATIONAL;
}
@@ -4588,8 +4566,7 @@
};
for (auto ct : context_priority_list) {
if (available_remote_contexts.test(ct)) {
- LOG_DEBUG("Selecting configuration context type: %s",
- ToString(ct).c_str());
+ log::debug("Selecting configuration context type: {}", ToString(ct));
return ct;
}
}
@@ -4603,8 +4580,8 @@
fallback_config = configuration_context_type_;
}
- LOG_DEBUG("Selecting configuration context type: %s",
- ToString(fallback_config).c_str());
+ log::debug("Selecting configuration context type: {}",
+ ToString(fallback_config));
return fallback_config;
}
@@ -4617,10 +4594,9 @@
*/
configuration_context_type_ = new_context_type;
- LOG_INFO("group_id %d, context type %s (%s), %s", group->group_id_,
- ToString(new_context_type).c_str(),
- ToHexString(new_context_type).c_str(),
- ToString(reconfig_result).c_str());
+ log::info("group_id {}, context type {} ({}), {}", group->group_id_,
+ ToString(new_context_type), ToHexString(new_context_type),
+ ToString(reconfig_result));
if (reconfig_result ==
AudioReconfigurationResult::RECONFIGURATION_NOT_NEEDED) {
return false;
@@ -4647,14 +4623,13 @@
void OnLocalAudioSourceMetadataUpdate(source_metadata_v7 source_metadata,
DsaMode dsa_mode) {
if (active_group_id_ == bluetooth::groups::kGroupUnknown) {
- LOG(WARNING) << ", cannot start streaming if no active group set";
+ log::warn(", cannot start streaming if no active group set");
return;
}
auto group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG(ERROR) << __func__
- << ", Invalid group: " << static_cast<int>(active_group_id_);
+ log::error("Invalid group: {}", static_cast<int>(active_group_id_));
return;
}
@@ -4663,13 +4638,12 @@
*/
StopVbcCloseTimeout();
- LOG_INFO(
- "group_id %d state=%s, target_state=%s, audio_receiver_state_: %s, "
- "audio_sender_state_: %s, dsa_mode: %d",
- group->group_id_, ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str(),
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str(), static_cast<int>(dsa_mode));
+ log::info(
+ "group_id {} state={}, target_state={}, audio_receiver_state_: {}, "
+ "audio_sender_state_: {}, dsa_mode: {}",
+ group->group_id_, ToString(group->GetState()),
+ ToString(group->GetTargetState()), ToString(audio_receiver_state_),
+ ToString(audio_sender_state_), static_cast<int>(dsa_mode));
group->dsa_.mode = dsa_mode;
@@ -4695,8 +4669,8 @@
BidirectionalPair<AudioContexts>& contexts_pair, int remote_dir) {
// We expect at least some context when this direction gets enabled
if (contexts_pair.get(remote_dir).none()) {
- LOG_WARN(
- "invalid/unknown %s context metadata, using 'UNSPECIFIED' instead",
+ log::warn(
+ "invalid/unknown {} context metadata, using 'UNSPECIFIED' instead",
(remote_dir == bluetooth::le_audio::types::kLeAudioDirectionSink)
? "sink"
: "source");
@@ -4729,9 +4703,9 @@
group_available_contexts |= group->GetMetadataContexts().get(dir);
}
- LOG_DEBUG("Checking contexts: %s, against the available contexts: %s",
- ToString(contexts_pair.get(dir)).c_str(),
- ToString(group_available_contexts).c_str());
+ log::debug("Checking contexts: {}, against the available contexts: {}",
+ ToString(contexts_pair.get(dir)),
+ ToString(group_available_contexts));
auto unavail_contexts =
contexts_pair.get(dir) & ~group_available_contexts;
if (unavail_contexts.none()) continue;
@@ -4741,15 +4715,15 @@
(unavail_contexts & group->GetSupportedContexts(dir));
if (unavail_but_supported.none() &&
group_available_contexts.test(LeAudioContextType::UNSPECIFIED)) {
- LOG_DEBUG("Replaced the unsupported contexts: %s with UNSPECIFIED",
- ToString(unavail_contexts).c_str());
+ log::debug("Replaced the unsupported contexts: {} with UNSPECIFIED",
+ ToString(unavail_contexts));
/* All unavailable are also unsupported - replace with UNSPECIFIED if
* available
*/
contexts_pair.get(dir).set(LeAudioContextType::UNSPECIFIED);
} else {
- LOG_DEBUG("Some contexts are supported but currently unavailable: %s!",
- ToString(unavail_but_supported).c_str());
+ log::debug("Some contexts are supported but currently unavailable: {}!",
+ ToString(unavail_but_supported));
/* Some of the streamed contexts are support but not available and they
* were erased from the metadata.
* TODO: Either filter out these contexts from the stream or do not
@@ -4778,15 +4752,15 @@
if (is_other_direction_streaming &&
(contexts_pair.get(other_dir) !=
AudioContexts(LeAudioContextType::UNSPECIFIED))) {
- LOG_INFO(
- "Other direction is streaming. Aligning other direction"
- " metadata to match the current direciton context: %s",
- ToString(contexts_pair.get(other_dir)).c_str());
+ log::info(
+ "Other direction is streaming. Aligning other direction "
+ "metadata to match the current direciton context: {}",
+ ToString(contexts_pair.get(other_dir)));
contexts_pair.get(dir) = contexts_pair.get(other_dir);
}
} else {
- LOG_DEBUG("Removing UNSPECIFIED from the remote sink context: %s",
- ToString(contexts_pair.get(other_dir)).c_str());
+ log::debug("Removing UNSPECIFIED from the remote sink context: {}",
+ ToString(contexts_pair.get(other_dir)));
contexts_pair.get(dir).unset(LeAudioContextType::UNSPECIFIED);
}
}
@@ -4795,31 +4769,28 @@
contexts_pair.sink = ChooseMetadataContextType(contexts_pair.sink);
contexts_pair.source = ChooseMetadataContextType(contexts_pair.source);
- LOG_DEBUG("Aligned remote metadata audio context: sink=%s, source=%s",
- ToString(contexts_pair.sink).c_str(),
- ToString(contexts_pair.source).c_str());
+ log::debug("Aligned remote metadata audio context: sink={}, source={}",
+ ToString(contexts_pair.sink), ToString(contexts_pair.source));
}
void OnLocalAudioSinkMetadataUpdate(sink_metadata_v7 sink_metadata) {
if (active_group_id_ == bluetooth::groups::kGroupUnknown) {
- LOG(WARNING) << ", cannot start streaming if no active group set";
+ log::warn(", cannot start streaming if no active group set");
return;
}
auto group = aseGroups_.FindById(active_group_id_);
if (!group) {
- LOG(ERROR) << __func__
- << ", Invalid group: " << static_cast<int>(active_group_id_);
+ log::error("Invalid group: {}", static_cast<int>(active_group_id_));
return;
}
- LOG_INFO(
- "group_id %d state=%s, target_state=%s, audio_receiver_state_: %s, "
- "audio_sender_state_: %s",
- group->group_id_, ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str(),
- ToString(audio_receiver_state_).c_str(),
- ToString(audio_sender_state_).c_str());
+ log::info(
+ "group_id {} state={}, target_state={}, audio_receiver_state_: {}, "
+ "audio_sender_state_: {}",
+ group->group_id_, ToString(group->GetState()),
+ ToString(group->GetTargetState()), ToString(audio_receiver_state_),
+ ToString(audio_sender_state_));
/* Set remote source metadata context from the recording tracks metadata */
local_metadata_context_types_.sink =
@@ -4885,9 +4856,9 @@
* with any other bidirectional context
*/
if (IsInCall() || IsInVoipCall()) {
- LOG_DEBUG(" In Call preference used: %s, voip call: %s",
- (IsInCall() ? "true" : "false"),
- (IsInVoipCall() ? "true" : "false"));
+ log::debug("In Call preference used: {}, voip call: {}",
+ (IsInCall() ? "true" : "false"),
+ (IsInVoipCall() ? "true" : "false"));
local_metadata_context_types_.sink.unset_all(kLeAudioContextAllBidir);
local_metadata_context_types_.source.unset_all(kLeAudioContextAllBidir);
local_metadata_context_types_.sink.set(
@@ -4901,37 +4872,35 @@
.source = local_metadata_context_types_.sink};
if (IsInVoipCall()) {
- LOG_DEBUG("Unsetting RINGTONE from remote sink ");
+ log::debug("Unsetting RINGTONE from remote sink");
remote_metadata.sink.unset(LeAudioContextType::RINGTONE);
}
auto is_ongoing_call_on_other_direction =
is_streaming_other_direction && (IsInVoipCall() || IsInCall());
- LOG_DEBUG("local_metadata_context_types_.source= %s",
- ToString(local_metadata_context_types_.source).c_str());
- LOG_DEBUG("local_metadata_context_types_.sink= %s",
- ToString(local_metadata_context_types_.sink).c_str());
- LOG_DEBUG("remote_metadata.source= %s",
- ToString(remote_metadata.source).c_str());
- LOG_DEBUG("remote_metadata.sink= %s",
- ToString(remote_metadata.sink).c_str());
- LOG_DEBUG(
- "remote_direction= %s",
+ log::debug("local_metadata_context_types_.source= {}",
+ ToString(local_metadata_context_types_.source));
+ log::debug("local_metadata_context_types_.sink= {}",
+ ToString(local_metadata_context_types_.sink));
+ log::debug("remote_metadata.source= {}", ToString(remote_metadata.source));
+ log::debug("remote_metadata.sink= {}", ToString(remote_metadata.sink));
+ log::debug(
+ "remote_direction= {}",
(remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSource
? "Source"
: "Sink"));
- LOG_DEBUG("is_streaming_other_direction= %s",
- (is_streaming_other_direction ? "True" : "False"));
- LOG_DEBUG("is_releasing_for_reconfiguration= %s",
- (is_releasing_for_reconfiguration ? "True" : "False"));
- LOG_DEBUG("is_ongoing_call_on_other_direction=%s",
- (is_ongoing_call_on_other_direction ? "True" : "False"));
+ log::debug("is_streaming_other_direction= {}",
+ (is_streaming_other_direction ? "True" : "False"));
+ log::debug("is_releasing_for_reconfiguration= {}",
+ (is_releasing_for_reconfiguration ? "True" : "False"));
+ log::debug("is_ongoing_call_on_other_direction={}",
+ (is_ongoing_call_on_other_direction ? "True" : "False"));
if (remote_metadata.get(remote_other_direction)
.test_any(kLeAudioContextAllBidir) &&
!is_streaming_other_direction) {
- LOG_DEBUG(
+ log::debug(
"The other direction is not streaming bidirectional, ignore that "
"context.");
remote_metadata.get(remote_other_direction).clear();
@@ -4943,7 +4912,7 @@
*/
if (remote_metadata.get(remote_direction)
.test_any(kLeAudioContextAllBidir)) {
- LOG_DEBUG(
+ log::debug(
"Aligning the other direction remote metadata to add this direction "
"context");
@@ -4967,14 +4936,12 @@
~kLeAudioContextAllRemoteSinkOnly);
}
}
- LOG_DEBUG("remote_metadata.source= %s",
- ToString(remote_metadata.source).c_str());
- LOG_DEBUG("remote_metadata.sink= %s",
- ToString(remote_metadata.sink).c_str());
+ log::debug("remote_metadata.source= {}", ToString(remote_metadata.source));
+ log::debug("remote_metadata.sink= {}", ToString(remote_metadata.sink));
if (is_releasing_for_reconfiguration || is_streaming_other_direction) {
- LOG_DEBUG("Other direction is streaming. Taking its contexts %s",
- ToString(remote_metadata.get(remote_other_direction)).c_str());
+ log::debug("Other direction is streaming. Taking its contexts {}",
+ ToString(remote_metadata.get(remote_other_direction)));
/* If current direction has no valid context or the other direction is
* bidirectional scenario, take the other direction context as well
*/
@@ -4982,7 +4949,7 @@
remote_metadata.get(remote_other_direction).any()) ||
remote_metadata.get(remote_other_direction)
.test_any(kLeAudioContextAllBidir)) {
- LOG_DEBUG(
+ log::debug(
"Aligning this direction remote metadata to add the other "
"direction context");
/* Turn off bidirectional contexts on this direction to avoid mixing
@@ -4999,10 +4966,8 @@
* direction. */
remote_metadata.source.unset_all(kLeAudioContextAllRemoteSinkOnly);
- LOG_DEBUG("remote_metadata.source= %s",
- ToString(remote_metadata.source).c_str());
- LOG_DEBUG("remote_metadata.sink= %s",
- ToString(remote_metadata.sink).c_str());
+ log::debug("remote_metadata.source= {}", ToString(remote_metadata.source));
+ log::debug("remote_metadata.sink= {}", ToString(remote_metadata.sink));
return remote_metadata;
}
@@ -5020,16 +4985,16 @@
if (override_contexts.value() == 0xFFFF) {
override_contexts = AudioContexts(LeAudioContextType::UNSPECIFIED);
}
- LOG_WARN("Overriding local_metadata_context_types_: %s with: %s",
- local_metadata_context_types_.source.to_string().c_str(),
- override_contexts.to_string().c_str());
+ log::warn("Overriding local_metadata_context_types_: {} with: {}",
+ local_metadata_context_types_.source.to_string(),
+ override_contexts.to_string());
/* Choose the right configuration context */
auto new_configuration_context =
ChooseConfigurationContextType(override_contexts);
- LOG_DEBUG("new_configuration_context= %s.",
- ToString(new_configuration_context).c_str());
+ log::debug("new_configuration_context= {}.",
+ ToString(new_configuration_context));
BidirectionalPair<AudioContexts> remote_contexts = {
.sink = override_contexts, .source = override_contexts};
return GroupStream(active_group_id_, new_configuration_context,
@@ -5048,9 +5013,8 @@
auto config_context_candids = get_bidirectional(remote_metadata);
auto new_config_context =
ChooseConfigurationContextType(config_context_candids);
- LOG_DEBUG("config_context_candids= %s, new_config_context= %s",
- ToString(config_context_candids).c_str(),
- ToString(new_config_context).c_str());
+ log::debug("config_context_candids= {}, new_config_context= {}",
+ ToString(config_context_candids), ToString(new_config_context));
/* For the following contexts we don't actually need HQ audio:
* LeAudioContextType::NOTIFICATIONS
@@ -5072,10 +5036,10 @@
(configuration_context_type_ != LeAudioContextType::UNSPECIFIED) &&
IsDirectionAvailableForCurrentConfiguration(
group, bluetooth::le_audio::types::kLeAudioDirectionSink)) {
- LOG_INFO(
+ log::info(
"There is no need to reconfigure for the sonification events, "
- "staying with the existing configuration context of %s",
- ToString(configuration_context_type_).c_str());
+ "staying with the existing configuration context of {}",
+ ToString(configuration_context_type_));
new_config_context = configuration_context_type_;
}
@@ -5091,11 +5055,11 @@
group, bluetooth::le_audio::types::kLeAudioDirectionSource) &&
(group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
if (has_audio_source_configured) {
- LOG_INFO(
+ log::info(
"Audio source is already available in the current configuration "
- "context in %s. Not switching to %s right now.",
- ToString(configuration_context_type_).c_str(),
- ToString(new_config_context).c_str());
+ "context in {}. Not switching to {} right now.",
+ ToString(configuration_context_type_),
+ ToString(new_config_context));
new_config_context = configuration_context_type_;
}
}
@@ -5131,7 +5095,7 @@
return false;
}
- LOG_INFO("DSA mode %d requested but not active", group->dsa_.mode);
+ log::info("DSA mode {} requested but not active", group->dsa_.mode);
return true;
}
@@ -5141,9 +5105,10 @@
BidirectionalPair<AudioContexts> remote_contexts) {
if (new_configuration_context != configuration_context_type_ ||
DsaReconfigureNeeded(group, new_configuration_context)) {
- LOG_INFO("Checking whether to change configuration context from %s to %s",
- ToString(configuration_context_type_).c_str(),
- ToString(new_configuration_context).c_str());
+ log::info(
+ "Checking whether to change configuration context from {} to {}",
+ ToString(configuration_context_type_),
+ ToString(new_configuration_context));
LeAudioLogHistory::Get()->AddLogHistory(
kLogAfCallBt, active_group_id_, RawAddress::kEmpty,
@@ -5158,12 +5123,11 @@
}
if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG_INFO(
- "The %s configuration did not change. Updating the metadata to "
- "sink=%s, source=%s",
- ToString(configuration_context_type_).c_str(),
- ToString(remote_contexts.sink).c_str(),
- ToString(remote_contexts.source).c_str());
+ log::info(
+ "The {} configuration did not change. Updating the metadata to "
+ "sink={}, source={}",
+ ToString(configuration_context_type_), ToString(remote_contexts.sink),
+ ToString(remote_contexts.source));
LeAudioLogHistory::Get()->AddLogHistory(
kLogAfCallBt, active_group_id_, RawAddress::kEmpty,
@@ -5182,34 +5146,34 @@
uint8_t* value, void* data) {
if (!instance) return;
- LOG_DEBUG("conn_id: 0x%04x, status: 0x%02x", conn_id, status);
+ log::debug("conn_id: 0x{:04x}, status: 0x{:02x}", conn_id, status);
LeAudioDevice* leAudioDevice =
instance->leAudioDevices_.FindByConnId(conn_id);
if (!leAudioDevice) {
- LOG_ERROR("LeAudioDevice not found");
+ log::error("LeAudioDevice not found");
return;
}
if (status == GATT_DATABASE_OUT_OF_SYNC) {
- LOG_INFO("Database out of sync for %s, re-discovering",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("Database out of sync for {}, re-discovering",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
instance->ClearDeviceInformationAndStartSearch(leAudioDevice);
return;
}
if (status != GATT_SUCCESS || len != 2) {
- LOG_ERROR("Could not read CCC for %s, disconnecting",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Could not read CCC for {}, disconnecting",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
instance->Disconnect(leAudioDevice->address_);
return;
}
uint16_t val = *(uint16_t*)value;
if (val == 0) {
- LOG_INFO("%s forgot CCC values. Re-subscribing",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("{} forgot CCC values. Re-subscribing",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
instance->RegisterKnownNotifications(leAudioDevice, false, true);
} else {
instance->connectionReady(leAudioDevice);
@@ -5230,8 +5194,8 @@
instance->ClearDeviceInformationAndStartSearch(leAudioDevice);
return;
} else {
- LOG_ERROR("Failed to read attribute, hdl: 0x%04x, status: 0x%02x", hdl,
- static_cast<int>(status));
+ log::error("Failed to read attribute, hdl: 0x{:04x}, status: 0x{:02x}",
+ hdl, static_cast<int>(status));
return;
}
@@ -5255,8 +5219,8 @@
void LeAudioHealthSendRecommendation(const RawAddress& address, int group_id,
LeAudioHealthBasedAction action) {
- LOG_DEBUG("%s, %d, %s", ADDRESS_TO_LOGGABLE_CSTR(address), group_id,
- ToString(action).c_str());
+ log::debug("{}, {}, {}", ADDRESS_TO_LOGGABLE_CSTR(address), group_id,
+ ToString(action));
if (address != RawAddress::kEmpty &&
leAudioDevices_.FindByAddress(address)) {
@@ -5286,7 +5250,7 @@
remove_group_if_possible(group);
} break;
default:
- LOG_ERROR("Invalid event %d", +event_type);
+ log::error("Invalid event {}", event_type);
}
}
@@ -5301,8 +5265,8 @@
}
if (audio_receiver_state_ != AudioState::STARTED) {
- LOG_ERROR("receiver state not ready, current state=%s",
- ToString(audio_receiver_state_).c_str());
+ log::error("receiver state not ready, current state={}",
+ ToString(audio_receiver_state_));
break;
}
@@ -5318,8 +5282,8 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl(
event->cig_id, event->cis_conn_hdl);
if (!leAudioDevice) {
- LOG(ERROR) << __func__ << ", no bonded Le Audio Device with CIS: "
- << +event->cis_conn_hdl;
+ log::error("no bonded Le Audio Device with CIS: {}",
+ event->cis_conn_hdl);
break;
}
LeAudioDeviceGroup* group =
@@ -5350,8 +5314,8 @@
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByCisConnHdl(
event->cig_id, event->cis_conn_hdl);
if (!leAudioDevice) {
- LOG(ERROR) << __func__ << ", no bonded Le Audio Device with CIS: "
- << +event->cis_conn_hdl;
+ log::error("no bonded Le Audio Device with CIS: {}",
+ event->cis_conn_hdl);
break;
}
LeAudioDeviceGroup* group =
@@ -5361,7 +5325,7 @@
event);
} break;
default:
- LOG(INFO) << ", Not handeled ISO event";
+ log::info(", Not handeled ISO event");
break;
}
}
@@ -5372,8 +5336,9 @@
leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle);
/* In case device has been disconnected before data path was setup */
if (!leAudioDevice) {
- LOG_WARN("Device for CIG %d and using cis_handle 0x%04x is disconnected.",
- cig_id, conn_handle);
+ log::warn(
+ "Device for CIG {} and using cis_handle 0x{:04x} is disconnected.",
+ cig_id, conn_handle);
return;
}
LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_);
@@ -5392,8 +5357,9 @@
* information about conn_handle, when the data path remove compete arrives.
*/
if (!leAudioDevice) {
- LOG_WARN("Device for CIG %d and using cis_handle 0x%04x is disconnected.",
- cig_id, conn_handle);
+ log::warn(
+ "Device for CIG {} and using cis_handle 0x{:04x} is disconnected.",
+ cig_id, conn_handle);
return;
}
@@ -5411,9 +5377,10 @@
LeAudioDevice* leAudioDevice =
leAudioDevices_.FindByCisConnHdl(cig_id, conn_handle);
if (!leAudioDevice) {
- LOG(WARNING) << __func__ << ", device under connection handle: "
- << loghex(conn_handle)
- << ", has been disconnecected in meantime";
+ log::warn(
+ "device under connection handle: {}, has been disconnecected in "
+ "meantime",
+ loghex(conn_handle));
return;
}
LeAudioDeviceGroup* group = aseGroups_.FindById(leAudioDevice->group_id_);
@@ -5430,8 +5397,8 @@
if (device->GetConnectionState() == DeviceConnectState::REMOVING) {
if (device->closing_stream_for_disconnection_) {
device->closing_stream_for_disconnection_ = false;
- LOG_INFO("Disconnecting group id: %d, address: %s", group->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(device->address_));
+ log::info("Disconnecting group id: {}, address: {}", group->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(device->address_));
bool force_acl_disconnect =
device->autoconnect_flag_ && group->IsEnabled();
DisconnectDevice(device, force_acl_disconnect);
@@ -5447,8 +5414,8 @@
while (leAudioDevice) {
if (leAudioDevice->closing_stream_for_disconnection_) {
leAudioDevice->closing_stream_for_disconnection_ = false;
- LOG_DEBUG("Disconnecting group id: %d, address: %s", group->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::debug("Disconnecting group id: {}, address: {}", group->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
bool force_acl_disconnect =
leAudioDevice->autoconnect_flag_ && group->IsEnabled();
DisconnectDevice(leAudioDevice, force_acl_disconnect);
@@ -5545,12 +5512,12 @@
}
void OnStateMachineStatusReportCb(int group_id, GroupStreamStatus status) {
- LOG_INFO(
- "status: %d , group_id: %d, audio_sender_state %s, "
- "audio_receiver_state %s",
+ log::info(
+ "status: {} , group_id: {}, audio_sender_state {}, "
+ "audio_receiver_state {}",
static_cast<int>(status), group_id,
- bluetooth::common::ToString(audio_sender_state_).c_str(),
- bluetooth::common::ToString(audio_receiver_state_).c_str());
+ bluetooth::common::ToString(audio_sender_state_),
+ bluetooth::common::ToString(audio_receiver_state_));
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
notifyGroupStreamStatus(group_id, status);
@@ -5571,8 +5538,8 @@
}
if (!group) {
- LOG_ERROR("Group %d does not exist anymore. This shall not happen ",
- group_id);
+ log::error("Group {} does not exist anymore. This shall not happen",
+ group_id);
return;
}
@@ -5583,8 +5550,8 @@
/* Audio Framework is not interested in the stream anymore.
* Just stop streaming
*/
- LOG_WARN("Stopping stream for group %d as AF not interested.",
- group_id);
+ log::warn("Stopping stream for group {} as AF not interested.",
+ group_id);
groupStateMachine_->StopStream(group);
return;
}
@@ -5595,11 +5562,11 @@
*/
if (group->GetConfigurationContextType() !=
configuration_context_type_) {
- LOG_DEBUG(
- "The configuration %s is no longer valid. Stopping the stream to"
- " reconfigure to %s",
- ToString(group->GetConfigurationContextType()).c_str(),
- ToString(configuration_context_type_).c_str());
+ log::debug(
+ "The configuration {} is no longer valid. Stopping the stream to "
+ "reconfigure to {}",
+ ToString(group->GetConfigurationContextType()),
+ ToString(configuration_context_type_));
group->SetPendingConfiguration();
groupStateMachine_->StopStream(group);
stream_setup_start_timestamp_ =
@@ -5691,8 +5658,8 @@
/* If configuration succeed wait for new status. */
return;
}
- LOG_INFO("Clear pending configuration flag for group %d",
- group->group_id_);
+ log::info("Clear pending configuration flag for group {}",
+ group->group_id_);
group->ClearPendingConfiguration();
} else {
if (sink_monitor_mode_) {
@@ -5731,7 +5698,7 @@
* it means that it is some internal state machine error. This is very unlikely and
* for now just Inactivate the group.
*/
- LOG_ERROR("Internal state machine error");
+ log::error("Internal state machine error");
group->PrintDebugState();
groupSetAndNotifyInactive();
}
@@ -5751,7 +5718,7 @@
void OnUpdatedCisConfiguration(int group_id, uint8_t direction) {
LeAudioDeviceGroup* group = aseGroups_.FindById(group_id);
if (!group) {
- LOG_ERROR("Invalid group_id: %d", group_id);
+ log::error("Invalid group_id: {}", group_id);
return;
}
group->UpdateCisConfiguration(direction);
@@ -5920,7 +5887,7 @@
leAudioDevice = group->GetNextDevice(leAudioDevice);
}
if (leAudioDevice == nullptr) {
- LOG_WARN("No LE Audio device found for CIS handle: %d", cis_conn_hdl);
+ log::warn("No LE Audio device found for CIS handle: {}", cis_conn_hdl);
return false;
}
@@ -5929,7 +5896,7 @@
if (consumed) {
return true;
} else {
- LOG_VERBOSE("ISO data consumer not ready to accept data");
+ log::verbose("ISO data consumer not ready to accept data");
return false;
}
}
@@ -5970,7 +5937,7 @@
void le_audio_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) {
if (!p_data || !instance) return;
- LOG_INFO("event = %d", static_cast<int>(event));
+ log::info("event = {}", static_cast<int>(event));
switch (event) {
case BTA_GATTC_DEREG_EVT:
@@ -6160,7 +6127,7 @@
const std::vector<uint8_t>& sink_pacs,
const std::vector<uint8_t>& source_pacs, const std::vector<uint8_t>& ases) {
if (!instance) {
- LOG(ERROR) << "Not initialized yet";
+ log::error("Not initialized yet");
return;
}
@@ -6173,7 +6140,7 @@
bool LeAudioClient::GetHandlesForStorage(const RawAddress& addr,
std::vector<uint8_t>& out) {
if (!instance) {
- LOG_ERROR("Not initialized yet");
+ log::error("Not initialized yet");
return false;
}
@@ -6183,7 +6150,7 @@
bool LeAudioClient::GetSinkPacsForStorage(const RawAddress& addr,
std::vector<uint8_t>& out) {
if (!instance) {
- LOG_ERROR("Not initialized yet");
+ log::error("Not initialized yet");
return false;
}
@@ -6193,7 +6160,7 @@
bool LeAudioClient::GetSourcePacsForStorage(const RawAddress& addr,
std::vector<uint8_t>& out) {
if (!instance) {
- LOG_ERROR("Not initialized yet");
+ log::error("Not initialized yet");
return false;
}
@@ -6203,7 +6170,7 @@
bool LeAudioClient::GetAsesForStorage(const RawAddress& addr,
std::vector<uint8_t>& out) {
if (!instance) {
- LOG_ERROR("Not initialized yet");
+ log::error("Not initialized yet");
return false;
}
@@ -6232,7 +6199,7 @@
offloading_preference) {
std::scoped_lock<std::mutex> lock(instance_mutex);
if (instance) {
- LOG(ERROR) << "Already initialized";
+ log::error("Already initialized");
return;
}
@@ -6240,8 +6207,8 @@
->SupportsBleConnectedIsochronousStreamCentral() &&
!bluetooth::shim::GetController()
->SupportsBleConnectedIsochronousStreamPeripheral()) {
- LOG(ERROR) << "Controller reports no ISO support."
- " LeAudioClient Init aborted.";
+ log::error(
+ "Controller reports no ISO support. LeAudioClient Init aborted.");
return;
}
@@ -6291,7 +6258,7 @@
void LeAudioClient::Cleanup(void) {
std::scoped_lock<std::mutex> lock(instance_mutex);
if (!instance) {
- LOG(ERROR) << "Not initialized";
+ log::error("Not initialized");
return;
}
diff --git a/system/bta/le_audio/client_parser.cc b/system/bta/le_audio/client_parser.cc
index 40cd3a7..857f760 100644
--- a/system/bta/le_audio/client_parser.cc
+++ b/system/bta/le_audio/client_parser.cc
@@ -23,6 +23,7 @@
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include <endian.h>
#include <hardware/bt_common_types.h>
#include <hardware/bt_gatt_types.h>
@@ -127,8 +128,7 @@
bool ParseAseStatusHeader(ase_rsp_hdr& arh, uint16_t len,
const uint8_t* value) {
if (len < kAseRspHdrMinLen) {
- LOG(ERROR) << __func__
- << ", wrong len of ASE char (header): " << static_cast<int>(len);
+ log::error("wrong len of ASE char (header): {}", static_cast<int>(len));
return false;
}
@@ -136,10 +136,8 @@
STREAM_TO_UINT8(arh.id, value);
STREAM_TO_UINT8(arh.state, value);
- LOG(INFO) << "ASE status: "
- << "\tASE id: " << loghex(arh.id)
- << "\tASE state: " << ase_state_map_string[arh.state] << " ("
- << loghex(arh.state) << ")";
+ log::info("ASE status: \tASE id: {}\tASE state: {} ({})", loghex(arh.id),
+ ase_state_map_string[arh.state], loghex(arh.state));
return true;
}
@@ -150,7 +148,7 @@
uint8_t codec_spec_conf_len;
if (len < kAseStatusCodecConfMinLen) {
- LOG(ERROR) << "Wrong len of codec conf status (Codec conf header)";
+ log::error("Wrong len of codec conf status (Codec conf header)");
return false;
}
@@ -170,33 +168,29 @@
len -= kAseStatusCodecConfMinLen;
if (len != codec_spec_conf_len) {
- LOG(ERROR) << "Wrong len of codec conf status (Codec spec conf)";
+ log::error("Wrong len of codec conf status (Codec spec conf)");
return false;
}
if (codec_spec_conf_len)
rsp.codec_spec_conf =
std::vector<uint8_t>(value, value + codec_spec_conf_len);
- LOG(INFO) << __func__ << ", Codec configuration"
- << "\n\tFraming: " << loghex(rsp.framing)
- << "\n\tPreferred PHY: " << loghex(rsp.preferred_phy)
- << "\n\tPreferred retransmission number: "
- << loghex(rsp.preferred_retrans_nb) << "\n\tMax transport latency: "
- << loghex(rsp.max_transport_latency)
- << "\n\tPresence delay min: " << loghex(rsp.pres_delay_min)
- << "\n\tPresence delay max: " << loghex(rsp.pres_delay_max)
- << "\n\tPreferredPresentationDelayMin: "
- << loghex(rsp.preferred_pres_delay_min)
- << "\n\tPreferredPresentationDelayMax: "
- << loghex(rsp.preferred_pres_delay_max)
- << "\n\tCoding format: " << loghex(rsp.codec_id.coding_format)
- << "\n\tVendor codec company ID: "
- << loghex(rsp.codec_id.vendor_company_id)
- << "\n\tVendor codec ID: " << loghex(rsp.codec_id.vendor_codec_id)
- << "\n\tCodec specific conf len: " << (int)codec_spec_conf_len
- << "\n\tCodec specific conf: "
- << base::HexEncode(rsp.codec_spec_conf.data(),
- rsp.codec_spec_conf.size());
+ log::info(
+ "Codec configuration\n\tFraming: {}\n\tPreferred PHY: {}\n\tPreferred "
+ "retransmission number: {}\n\tMax transport latency: {}\n\tPresence "
+ "delay min: {}\n\tPresence delay max: "
+ "{}\n\tPreferredPresentationDelayMin: "
+ "{}\n\tPreferredPresentationDelayMax: {}\n\tCoding format: {}\n\tVendor "
+ "codec company ID: {}\n\tVendor codec ID: {}\n\tCodec specific conf len: "
+ "{}\n\tCodec specific conf: {}",
+ loghex(rsp.framing), loghex(rsp.preferred_phy),
+ loghex(rsp.preferred_retrans_nb), loghex(rsp.max_transport_latency),
+ loghex(rsp.pres_delay_min), loghex(rsp.pres_delay_max),
+ loghex(rsp.preferred_pres_delay_min),
+ loghex(rsp.preferred_pres_delay_max), loghex(rsp.codec_id.coding_format),
+ loghex(rsp.codec_id.vendor_company_id),
+ loghex(rsp.codec_id.vendor_codec_id), (int)codec_spec_conf_len,
+ base::HexEncode(rsp.codec_spec_conf.data(), rsp.codec_spec_conf.size()));
return true;
}
@@ -205,7 +199,7 @@
struct ase_qos_configured_state_params& rsp, uint16_t len,
const uint8_t* value) {
if (len != kAseStatusCodecQosConfMinLen) {
- LOG(ERROR) << "Wrong len of ASE characteristic (QOS conf header)";
+ log::error("Wrong len of ASE characteristic (QOS conf header)");
return false;
}
@@ -219,17 +213,14 @@
STREAM_TO_UINT16(rsp.max_transport_latency, value);
STREAM_TO_UINT24(rsp.pres_delay, value);
- LOG(INFO) << __func__ << ", Codec QoS Configured"
- << "\n\tCIG: " << loghex(rsp.cig_id)
- << "\n\tCIS: " << loghex(rsp.cis_id)
- << "\n\tSDU interval: " << loghex(rsp.sdu_interval)
- << "\n\tFraming: " << loghex(rsp.framing)
- << "\n\tPHY: " << loghex(rsp.phy)
- << "\n\tMax SDU: " << loghex(rsp.max_sdu)
- << "\n\tRetransmission number: " << loghex(rsp.retrans_nb)
- << "\n\tMax transport latency: "
- << loghex(rsp.max_transport_latency)
- << "\n\tPresentation delay: " << loghex(rsp.pres_delay);
+ log::info(
+ "Codec QoS Configured\n\tCIG: {}\n\tCIS: {}\n\tSDU interval: "
+ "{}\n\tFraming: {}\n\tPHY: {}\n\tMax SDU: {}\n\tRetransmission number: "
+ "{}\n\tMax transport latency: {}\n\tPresentation delay: {}",
+ loghex(rsp.cig_id), loghex(rsp.cis_id), loghex(rsp.sdu_interval),
+ loghex(rsp.framing), loghex(rsp.phy), loghex(rsp.max_sdu),
+ loghex(rsp.retrans_nb), loghex(rsp.max_transport_latency),
+ loghex(rsp.pres_delay));
return true;
}
@@ -239,7 +230,7 @@
uint8_t metadata_len;
if (len < kAseStatusTransMinLen) {
- LOG(ERROR) << "Wrong len of ASE characteristic (metadata)";
+ log::error("Wrong len of ASE characteristic (metadata)");
return false;
}
@@ -249,17 +240,18 @@
len -= kAseStatusTransMinLen;
if (len != metadata_len) {
- LOG(ERROR) << "Wrong len of ASE characteristic (metadata)";
+ log::error("Wrong len of ASE characteristic (metadata)");
return false;
}
if (metadata_len > 0)
rsp.metadata = std::vector<uint8_t>(value, value + metadata_len);
- LOG(INFO) << __func__ << ", Status enabling/streaming/disabling"
- << "\n\tCIG: " << loghex(rsp.cig_id)
- << "\n\tCIS: " << loghex(rsp.cis_id) << "\n\tMetadata: "
- << base::HexEncode(rsp.metadata.data(), rsp.metadata.size());
+ log::info(
+ "Status enabling/streaming/disabling\n\tCIG: {}\n\tCIS: {}\n\tMetadata: "
+ "{}",
+ loghex(rsp.cig_id), loghex(rsp.cis_id),
+ base::HexEncode(rsp.metadata.data(), rsp.metadata.size()));
return true;
}
@@ -269,7 +261,7 @@
uint8_t num_entries;
if (len < kCtpNtfMinLen) {
- LOG(ERROR) << "Wrong len of ASE control point notification: " << (int)len;
+ log::error("Wrong len of ASE control point notification: {}", (int)len);
return false;
}
@@ -277,7 +269,7 @@
STREAM_TO_UINT8(num_entries, value);
if (len != kCtpNtfMinLen + (num_entries * kCtpAseEntryMinLen)) {
- LOG(ERROR) << "Wrong len of ASE control point notification (ASE IDs)";
+ log::error("Wrong len of ASE control point notification (ASE IDs)");
return false;
}
@@ -291,22 +283,18 @@
ntf.entries.push_back(std::move(entry));
}
- LOG(INFO) << __func__ << ", Control point notification"
- << "\n\tOpcode: " << ctp_opcode_map_string[ntf.op] << " ("
- << loghex(ntf.op) << ")"
- << "\n\tNum ASE IDs: " << (int)num_entries;
+ log::info("Control point notification\n\tOpcode: {} ({})\n\tNum ASE IDs: {}",
+ ctp_opcode_map_string[ntf.op], loghex(ntf.op), (int)num_entries);
for (size_t i = 0; i < num_entries; i++)
- LOG(INFO) << "\n\tASE ID[" << loghex(ntf.entries[i].ase_id)
- << "] response: "
- << ctp_response_code_map_string[ntf.entries[i].response_code]
- << " (" << loghex(ntf.entries[i].response_code) << ")"
- << " reason: "
- << ((ctp_response_code_map.count(ntf.entries[i].response_code) !=
- 0)
- ? (*ctp_response_code_map[ntf.entries[i].response_code])
- [ntf.entries[i].reason]
- : "")
- << " (" << loghex(ntf.entries[i].reason) << ")";
+ log::info("\n\tASE ID[{}] response: {} ({}) reason: {} ({})",
+ loghex(ntf.entries[i].ase_id),
+ ctp_response_code_map_string[ntf.entries[i].response_code],
+ loghex(ntf.entries[i].response_code),
+ ((ctp_response_code_map.count(ntf.entries[i].response_code) != 0)
+ ? (*ctp_response_code_map[ntf.entries[i].response_code])
+ [ntf.entries[i].reason]
+ : ""),
+ loghex(ntf.entries[i].reason));
return true;
}
@@ -358,20 +346,15 @@
ARRAY_TO_STREAM(msg, conf.codec_config.data(),
static_cast<int>(conf.codec_config.size()));
- LOG(INFO) << __func__ << ", Codec configuration"
- << "\n\tAse id: " << loghex(conf.ase_id)
- << "\n\tTarget latency: " << loghex(conf.target_latency)
- << "\n\tTarget PHY: " << loghex(conf.target_phy)
- << "\n\tCoding format: " << loghex(conf.codec_id.coding_format)
- << "\n\tVendor codec company ID: "
- << loghex(conf.codec_id.vendor_company_id)
- << "\n\tVendor codec ID: "
- << loghex(conf.codec_id.vendor_codec_id)
- << "\n\tCodec config len: "
- << static_cast<int>(conf.codec_config.size())
- << "\n\tCodec spec conf: "
- << "\n"
- << conf_ents_str.str();
+ log::info(
+ "Codec configuration\n\tAse id: {}\n\tTarget latency: {}\n\tTarget "
+ "PHY: {}\n\tCoding format: {}\n\tVendor codec company ID: {}\n\tVendor "
+ "codec ID: {}\n\tCodec config len: {}\n\tCodec spec conf: \n{}",
+ loghex(conf.ase_id), loghex(conf.target_latency),
+ loghex(conf.target_phy), loghex(conf.codec_id.coding_format),
+ loghex(conf.codec_id.vendor_company_id),
+ loghex(conf.codec_id.vendor_codec_id),
+ static_cast<int>(conf.codec_config.size()), conf_ents_str.str());
}
return true;
@@ -398,18 +381,14 @@
UINT16_TO_STREAM(msg, conf.max_transport_latency);
UINT24_TO_STREAM(msg, conf.pres_delay);
- LOG(INFO) << __func__ << ", QoS configuration"
- << "\n\tAse id: " << loghex(conf.ase_id)
- << "\n\tcig: " << loghex(conf.cig)
- << "\n\tCis: " << loghex(conf.cis)
- << "\n\tSDU interval: " << loghex(conf.sdu_interval)
- << "\n\tFraming: " << loghex(conf.framing)
- << "\n\tPhy: " << loghex(conf.phy)
- << "\n\tMax sdu size: " << loghex(conf.max_sdu)
- << "\n\tRetrans nb: " << loghex(conf.retrans_nb)
- << "\n\tMax Transport latency: "
- << loghex(conf.max_transport_latency)
- << "\n\tPres delay: " << loghex(conf.pres_delay);
+ log::info(
+ "QoS configuration\n\tAse id: {}\n\tcig: {}\n\tCis: {}\n\tSDU "
+ "interval: {}\n\tFraming: {}\n\tPhy: {}\n\tMax sdu size: {}\n\tRetrans "
+ "nb: {}\n\tMax Transport latency: {}\n\tPres delay: {}",
+ loghex(conf.ase_id), loghex(conf.cig), loghex(conf.cis),
+ loghex(conf.sdu_interval), loghex(conf.framing), loghex(conf.phy),
+ loghex(conf.max_sdu), loghex(conf.retrans_nb),
+ loghex(conf.max_transport_latency), loghex(conf.pres_delay));
}
return true;
@@ -420,18 +399,18 @@
if (confs.size() == 0) return false;
if (confs.size() > UINT8_MAX) {
- LOG_ERROR(" To many ASEs to update metadata");
+ log::error("To many ASEs to update metadata");
return false;
}
uint16_t msg_len = confs.size() * kCtpEnableMinLen + kAseNumSize + kCtpOpSize;
for (auto& conf : confs) {
if (msg_len > GATT_MAX_ATTR_LEN) {
- LOG_ERROR(" Message length above GATT maximum");
+ log::error("Message length above GATT maximum");
return false;
}
if (conf.metadata.size() > UINT8_MAX) {
- LOG_ERROR(" ase[%d] metadata length is invalid", conf.ase_id);
+ log::error("ase[{}] metadata length is invalid", conf.ase_id);
return false;
}
@@ -449,9 +428,8 @@
ARRAY_TO_STREAM(msg, conf.metadata.data(),
static_cast<int>(conf.metadata.size()));
- LOG(INFO) << __func__ << ", Enable"
- << "\n\tAse id: " << loghex(conf.ase_id) << "\n\tMetadata: "
- << base::HexEncode(conf.metadata.data(), conf.metadata.size());
+ log::info("Enable\n\tAse id: {}\n\tMetadata: {}", loghex(conf.ase_id),
+ base::HexEncode(conf.metadata.data(), conf.metadata.size()));
}
return true;
@@ -469,8 +447,7 @@
for (const uint8_t& id : ase_ids) {
UINT8_TO_STREAM(msg, id);
- LOG(INFO) << __func__ << ", ReceiverStartReady"
- << "\n\tAse id: " << loghex(id);
+ log::info("ReceiverStartReady\n\tAse id: {}", loghex(id));
}
return true;
@@ -488,8 +465,7 @@
for (const uint8_t& id : ase_ids) {
UINT8_TO_STREAM(msg, id);
- LOG(INFO) << __func__ << ", Disable"
- << "\n\tAse id: " << loghex(id);
+ log::info("Disable\n\tAse id: {}", loghex(id));
}
return true;
@@ -507,8 +483,7 @@
for (const uint8_t& ase_id : ase_ids) {
UINT8_TO_STREAM(msg, ase_id);
- LOG(INFO) << __func__ << ", ReceiverStopReady"
- << "\n\tAse id: " << loghex(ase_id);
+ log::info("ReceiverStopReady\n\tAse id: {}", loghex(ase_id));
}
return true;
@@ -520,7 +495,7 @@
if (confs.size() == 0) return false;
if (confs.size() > UINT8_MAX) {
- LOG_ERROR(" To many ASEs to update metadata");
+ log::error("To many ASEs to update metadata");
return false;
}
@@ -528,11 +503,11 @@
confs.size() * kCtpUpdateMetadataMinLen + kAseNumSize + kCtpOpSize;
for (auto& conf : confs) {
if (msg_len > GATT_MAX_ATTR_LEN) {
- LOG_ERROR(" Message length above GATT maximum");
+ log::error("Message length above GATT maximum");
return false;
}
if (conf.metadata.size() > UINT8_MAX) {
- LOG_ERROR(" ase[%d] metadata length is invalid", conf.ase_id);
+ log::error("ase[{}] metadata length is invalid", conf.ase_id);
return false;
}
@@ -550,9 +525,9 @@
ARRAY_TO_STREAM(msg, conf.metadata.data(),
static_cast<int>(conf.metadata.size()));
- LOG(INFO) << __func__ << ", Update Metadata"
- << "\n\tAse id: " << loghex(conf.ase_id) << "\n\tMetadata: "
- << base::HexEncode(conf.metadata.data(), conf.metadata.size());
+ log::info("Update Metadata\n\tAse id: {}\n\tMetadata: {}",
+ loghex(conf.ase_id),
+ base::HexEncode(conf.metadata.data(), conf.metadata.size()));
}
return true;
@@ -570,8 +545,7 @@
for (const uint8_t& ase_id : ase_ids) {
UINT8_TO_STREAM(msg, ase_id);
- LOG(INFO) << __func__ << ", Release"
- << "\n\tAse id: " << loghex(ase_id);
+ log::info("Release\n\tAse id: {}", loghex(ase_id));
}
return true;
@@ -586,7 +560,7 @@
uint8_t codec_spec_cap_len, metadata_len;
if (len < kAcsPacRecordMinLen) {
- LOG_ERROR("Wrong len of PAC record (%d!=%d)", len, kAcsPacRecordMinLen);
+ log::error("Wrong len of PAC record ({}!={})", len, kAcsPacRecordMinLen);
pac_recs.clear();
return -1;
}
@@ -598,8 +572,8 @@
len -= kAcsPacRecordMinLen - kAcsPacMetadataLenLen;
if (len < codec_spec_cap_len + kAcsPacMetadataLenLen) {
- LOG_ERROR("Wrong len of PAC record (codec specific capabilities) (%d!=%d)",
- len, codec_spec_cap_len + kAcsPacMetadataLenLen);
+ log::error("Wrong len of PAC record (codec specific capabilities) ({}!={})",
+ len, codec_spec_cap_len + kAcsPacMetadataLenLen);
pac_recs.clear();
return -1;
}
@@ -620,7 +594,8 @@
len -= kAcsPacMetadataLenLen;
if (len < metadata_len) {
- LOG_ERROR("Wrong len of PAC record (metadata) (%d!=%d)", len, metadata_len);
+ log::error("Wrong len of PAC record (metadata) ({}!={})", len,
+ metadata_len);
pac_recs.clear();
return -1;
}
@@ -637,8 +612,8 @@
bool ParsePacs(std::vector<struct acs_ac_record>& pac_recs, uint16_t len,
const uint8_t* value) {
if (len < kAcsPacDiscoverRspMinLen) {
- LOG_ERROR("Wrong len of PAC characteristic (%d!=%d)", len,
- kAcsPacDiscoverRspMinLen);
+ log::error("Wrong len of PAC characteristic ({}!={})", len,
+ kAcsPacDiscoverRspMinLen);
return false;
}
@@ -661,13 +636,13 @@
bool ParseAudioLocations(types::AudioLocations& audio_locations, uint16_t len,
const uint8_t* value) {
if (len != kAudioLocationsRspMinLen) {
- LOG(ERROR) << "Wrong len of Audio Location characteristic";
+ log::error("Wrong len of Audio Location characteristic");
return false;
}
STREAM_TO_UINT32(audio_locations, value);
- LOG(INFO) << "Audio locations: " << audio_locations.to_string();
+ log::info("Audio locations: {}", audio_locations.to_string());
return true;
}
@@ -676,16 +651,17 @@
types::BidirectionalPair<types::AudioContexts>& contexts, uint16_t len,
const uint8_t* value) {
if (len != kAseAudioSuppContRspMinLen) {
- LOG(ERROR) << "Wrong len of Audio Supported Context characteristic";
+ log::error("Wrong len of Audio Supported Context characteristic");
return false;
}
STREAM_TO_UINT16(contexts.sink.value_ref(), value);
STREAM_TO_UINT16(contexts.source.value_ref(), value);
- LOG(INFO) << "Supported Audio Contexts: "
- << "\n\tSupported Sink Contexts: " << contexts.sink.to_string()
- << "\n\tSupported Source Contexts: " << contexts.source.to_string();
+ log::info(
+ "Supported Audio Contexts: \n\tSupported Sink Contexts: {}\n\tSupported "
+ "Source Contexts: {}",
+ contexts.sink.to_string(), contexts.source.to_string());
return true;
}
@@ -694,16 +670,17 @@
types::BidirectionalPair<types::AudioContexts>& contexts, uint16_t len,
const uint8_t* value) {
if (len != kAseAudioAvailRspMinLen) {
- LOG(ERROR) << "Wrong len of Audio Availability characteristic";
+ log::error("Wrong len of Audio Availability characteristic");
return false;
}
STREAM_TO_UINT16(contexts.sink.value_ref(), value);
STREAM_TO_UINT16(contexts.source.value_ref(), value);
- LOG(INFO) << "Available Audio Contexts: "
- << "\n\tAvailable Sink Contexts: " << contexts.sink.to_string()
- << "\n\tAvailable Source Contexts: " << contexts.source.to_string();
+ log::info(
+ "Available Audio Contexts: \n\tAvailable Sink Contexts: {}\n\tAvailable "
+ "Source Contexts: {}",
+ contexts.sink.to_string(), contexts.source.to_string());
return true;
}
@@ -713,18 +690,15 @@
bool ParseTmapRole(std::bitset<16>& role, uint16_t len, const uint8_t* value) {
if (len != kTmapRoleLen) {
- LOG_ERROR(
- ", Wrong len of Telephony Media Audio Profile Role, "
- "characteristic");
+ log::error(
+ ", Wrong len of Telephony Media Audio Profile Role, characteristic");
return false;
}
STREAM_TO_UINT16(role, value);
- LOG_INFO(
- ", Telephony Media Audio Profile Role:"
- "\n\tRole: %s",
- role.to_string().c_str());
+ log::info(", Telephony Media Audio Profile Role:\n\tRole: {}",
+ role.to_string());
return true;
}
diff --git a/system/bta/le_audio/codec_interface.cc b/system/bta/le_audio/codec_interface.cc
index c5bd065..e3eaf8f 100644
--- a/system/bta/le_audio/codec_interface.cc
+++ b/system/bta/le_audio/codec_interface.cc
@@ -19,6 +19,7 @@
#include "codec_interface.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include <memory>
@@ -63,8 +64,8 @@
return Status::STATUS_OK;
}
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id_.coding_format,
- codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format,
+ codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
return Status::STATUS_ERR_INVALID_CODEC_ID;
}
@@ -101,15 +102,15 @@
return Status::STATUS_OK;
}
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id_.coding_format,
- codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format,
+ codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
return Status::STATUS_ERR_INVALID_CODEC_ID;
}
std::vector<int16_t>& GetDecodedSamples() { return output_channel_data_; }
CodecInterface::Status Decode(uint8_t* data, uint16_t size) {
if (!IsReady()) {
- LOG_ERROR("decoder not ready");
+ log::error("decoder not ready");
return Status::STATUS_ERR_CODEC_NOT_READY;
}
@@ -119,15 +120,15 @@
auto err = lc3_decode(lc3_.decoder_, data, size, lc3_.pcm_format_,
output_channel_data_.data(), 1 /* stride */);
if (err < 0) {
- LOG(ERROR) << " bad decoding parameters: " << static_cast<int>(err);
+ log::error("bad decoding parameters: {}", static_cast<int>(err));
return Status::STATUS_ERR_CODING_ERROR;
}
return Status::STATUS_OK;
}
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id_.coding_format,
- codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format,
+ codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
return Status::STATUS_ERR_INVALID_CODEC_ID;
}
@@ -136,12 +137,12 @@
std::vector<int16_t>* out_buffer = nullptr,
uint16_t out_offset = 0) {
if (!IsReady()) {
- LOG_ERROR("decoder not ready");
+ log::error("decoder not ready");
return Status::STATUS_ERR_CODEC_NOT_READY;
}
if (out_size == 0) {
- LOG_ERROR("out_size cannot be 0");
+ log::error("out_size cannot be 0");
return Status::STATUS_ERR_CODING_ERROR;
}
@@ -165,15 +166,15 @@
lc3_encode(lc3_.encoder_, lc3_.pcm_format_, data, stride, out_size,
((uint8_t*)out_buffer->data()) + out_offset);
if (err < 0) {
- LOG(ERROR) << " bad encoding parameters: " << static_cast<int>(err);
+ log::error("bad encoding parameters: {}", static_cast<int>(err));
return Status::STATUS_ERR_CODING_ERROR;
}
return Status::STATUS_OK;
}
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id_.coding_format,
- codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format,
+ codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
return Status::STATUS_ERR_INVALID_CODEC_ID;
}
@@ -188,7 +189,7 @@
uint16_t GetNumOfSamplesPerChannel() {
if (!IsReady()) {
- LOG_ERROR("decoder not ready");
+ log::error("decoder not ready");
return 0;
}
@@ -197,8 +198,8 @@
pcm_config_->sample_rate);
}
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id_.coding_format,
- codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format,
+ codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
return 0;
}
@@ -207,8 +208,8 @@
return lc3_.bits_to_bytes_per_sample(bt_codec_config_.bits_per_sample);
}
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id_.coding_format,
- codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id_.coding_format,
+ codec_id_.vendor_company_id, codec_id_.vendor_codec_id);
return 0;
}
@@ -256,8 +257,8 @@
if (codec_id.coding_format == types::kLeAudioCodingFormatLC3) {
impl = new Impl(codec_id);
} else {
- LOG_ERROR("Invalid codec ID: [%d:%d:%d]", codec_id.coding_format,
- codec_id.vendor_company_id, codec_id.vendor_codec_id);
+ log::error("Invalid codec ID: [{}:{}:{}]", codec_id.coding_format,
+ codec_id.vendor_company_id, codec_id.vendor_codec_id);
}
}
diff --git a/system/bta/le_audio/codec_interface.h b/system/bta/le_audio/codec_interface.h
index d1b8842..ee953f2 100644
--- a/system/bta/le_audio/codec_interface.h
+++ b/system/bta/le_audio/codec_interface.h
@@ -18,6 +18,7 @@
#pragma once
+#include <bluetooth/log.h>
#include <stdint.h>
#include <vector>
@@ -72,4 +73,11 @@
struct Impl;
Impl* impl;
};
+
} // namespace bluetooth::le_audio
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::le_audio::CodecInterface::Status>
+ : enum_formatter<bluetooth::le_audio::CodecInterface::Status> {};
+} // namespace fmt
diff --git a/system/bta/le_audio/codec_manager.cc b/system/bta/le_audio/codec_manager.cc
index 7513777..4d153a3 100644
--- a/system/bta/le_audio/codec_manager.cc
+++ b/system/bta/le_audio/codec_manager.cc
@@ -16,6 +16,8 @@
#include "codec_manager.h"
+#include <bluetooth/log.h>
+
#include <bitset>
#include "audio_hal_client/audio_hal_client.h"
@@ -97,22 +99,22 @@
!osi_property_get_bool(
"persist.bluetooth.leaudio_offload.disabled", true);
if (offload_enable_ == false) {
- LOG_INFO("offload disabled");
+ log::info("offload disabled");
return;
}
if (!LeAudioHalVerifier::SupportsLeAudioHardwareOffload()) {
- LOG_WARN("HAL not support hardware offload");
+ log::warn("HAL not support hardware offload");
return;
}
if (!bluetooth::shim::GetController()->IsSupported(
bluetooth::hci::OpCode::CONFIGURE_DATA_PATH)) {
- LOG_WARN("Controller does not support config data path command");
+ log::warn("Controller does not support config data path command");
return;
}
- LOG_INFO("LeAudioCodecManagerImpl: configure_data_path for encode");
+ log::info("LeAudioCodecManagerImpl: configure_data_path for encode");
GetInterface().ConfigureDataPath(hci_data_direction_t::HOST_TO_CONTROLLER,
kIsoDataPathPlatformDefault, {});
GetInterface().ConfigureDataPath(hci_data_direction_t::CONTROLLER_TO_HOST,
@@ -240,7 +242,7 @@
void UpdateSupportedBroadcastConfig(
const std::vector<AudioSetConfiguration>& adsp_capabilities) {
- LOG_INFO("UpdateSupportedBroadcastConfig");
+ log::info("UpdateSupportedBroadcastConfig");
for (const auto& adsp_audio_set_conf : adsp_capabilities) {
ASSERT_LOG(
@@ -277,21 +279,21 @@
broadcast_config.max_transport_latency = qos.getMaxTransportLatency();
supported_broadcast_config.push_back(broadcast_config);
} else {
- LOG_ERROR(
+ log::error(
"Cannot find the correspoding QoS config for the sampling_rate: "
- "%d, frame_duration: %d",
+ "{}, frame_duration: {}",
sample_rate, frame_duration);
}
- LOG_INFO("broadcast_config sampling_rate: %d",
- broadcast_config.sampling_rate);
+ log::info("broadcast_config sampling_rate: {}",
+ broadcast_config.sampling_rate);
}
}
const broadcast_offload_config* GetBroadcastOffloadConfig(
uint8_t preferred_quality) {
if (supported_broadcast_config.empty()) {
- LOG_ERROR("There is no valid broadcast offload config");
+ log::error("There is no valid broadcast offload config");
return nullptr;
}
/* Broadcast audio config selection based on source broadcast capability
@@ -349,10 +351,10 @@
return nullptr;
}
- LOG_INFO(
- "stream_map.size(): %zu, sampling_rate: %d, frame_duration(us): %d, "
- "octets_per_frame: %d, blocks_per_sdu %d, "
- "retransmission_number: %d, max_transport_latency: %d",
+ log::info(
+ "stream_map.size(): {}, sampling_rate: {}, frame_duration(us): {}, "
+ "octets_per_frame: {}, blocks_per_sdu {}, retransmission_number: {}, "
+ "max_transport_latency: {}",
supported_broadcast_config[broadcast_target_config].stream_map.size(),
supported_broadcast_config[broadcast_target_config].sampling_rate,
supported_broadcast_config[broadcast_target_config].frame_duration,
@@ -523,7 +525,7 @@
auto available_allocations =
AdjustAllocationForOffloader(stream_params.audio_channel_allocation);
if (available_allocations == 0) {
- LOG_ERROR("There is no CIS connected");
+ log::error("There is no CIS connected");
return;
}
@@ -585,11 +587,11 @@
codec_spec_conf::kLeAudioLocationStereo & ~available_allocations;
}
- LOG_INFO(
- "%s: Cis handle 0x%04x, target allocation 0x%08x, current "
- "allocation 0x%08x, active: %d",
- tag.c_str(), cis_entry.conn_handle, target_allocation,
- current_allocation, is_active);
+ log::info(
+ "{}: Cis handle 0x{:04x}, target allocation 0x{:08x}, current "
+ "allocation 0x{:08x}, active: {}",
+ tag, cis_entry.conn_handle, target_allocation, current_allocation,
+ is_active);
if (stream_map.is_initial ||
LeAudioHalVerifier::SupportsStreamActiveApi()) {
@@ -765,19 +767,19 @@
::bluetooth::le_audio::set_configurations::AudioSetConfiguration>&
adsp_capabilities,
const std::vector<btle_audio_codec_config_t>& offload_preference_set) {
- LOG_DEBUG("Print adsp_capabilities:");
+ log::debug("Print adsp_capabilities:");
for (auto& adsp : adsp_capabilities) {
- LOG_DEBUG("'%s':", adsp.name.c_str());
+ log::debug("'{}':", adsp.name.c_str());
for (auto direction : {le_audio::types::kLeAudioDirectionSink,
le_audio::types::kLeAudioDirectionSource}) {
- LOG_DEBUG(
- "dir: %s: number of confs %d:",
+ log::debug(
+ "dir: {}: number of confs {}:",
(direction == types::kLeAudioDirectionSink ? "sink" : "source"),
(int)(adsp.confs.get(direction).size()));
for (auto conf : adsp.confs.sink) {
- LOG_DEBUG(
- "codecId: %d, sample_freq: %d, interval %d, channel_cnt: %d",
+ log::debug(
+ "codecId: {}, sample_freq: {}, interval {}, channel_cnt: {}",
conf.codec.id.coding_format, conf.codec.GetSamplingFrequencyHz(),
conf.codec.GetDataIntervalUs(),
conf.codec.GetChannelCountPerIsoStream());
@@ -807,37 +809,36 @@
: codec_input_capa;
if (std::find(capa_container.begin(), capa_container.end(),
capa_to_add) == capa_container.end()) {
- LOG_DEBUG("Adding %s capa %d",
- (direction == types::kLeAudioDirectionSink) ? "output"
- : "input",
- static_cast<int>(capa_container.size()));
+ log::debug("Adding {} capa {}",
+ (direction == types::kLeAudioDirectionSink) ? "output"
+ : "input",
+ static_cast<int>(capa_container.size()));
capa_container.push_back(capa_to_add);
}
}
}
}
- LOG_DEBUG("Output capa: %d, Input capa: %d",
- static_cast<int>(codec_output_capa.size()),
- static_cast<int>(codec_input_capa.size()));
+ log::debug("Output capa: {}, Input capa: {}",
+ static_cast<int>(codec_output_capa.size()),
+ static_cast<int>(codec_input_capa.size()));
- LOG_DEBUG(" Print offload_preference_set: %d ",
- (int)(offload_preference_set.size()));
+ log::debug("Print offload_preference_set: {}",
+ (int)(offload_preference_set.size()));
int i = 0;
for (auto set : offload_preference_set) {
- LOG_DEBUG("set %d, %s ", i++, set.ToString().c_str());
+ log::debug("set {}, {}", i++, set.ToString());
}
}
void UpdateOffloadCapability(
const std::vector<btle_audio_codec_config_t>& offloading_preference) {
- LOG(INFO) << __func__;
+ log::info("");
std::unordered_set<uint8_t> offload_preference_set;
if (AudioSetConfigurationProvider::Get() == nullptr) {
- LOG(ERROR) << __func__
- << " Audio set configuration provider is not available.";
+ log::error("Audio set configuration provider is not available.");
return;
}
@@ -867,8 +868,8 @@
if (IsAudioSetConfigurationMatched(software_audio_set_conf,
offload_preference_set,
adsp_capabilities)) {
- LOG(INFO) << "Offload supported conf, context type: " << (int)ctx_type
- << ", settings -> " << software_audio_set_conf->name;
+ log::info("Offload supported conf, context type: {}, settings -> {}",
+ (int)ctx_type, software_audio_set_conf->name);
if (dual_bidirection_swb_supported_ &&
AudioSetConfigurationProvider::Get()
->CheckConfigurationIsDualBiDirSwb(
diff --git a/system/bta/le_audio/content_control_id_keeper.cc b/system/bta/le_audio/content_control_id_keeper.cc
index dff0f58..5afe50b 100644
--- a/system/bta/le_audio/content_control_id_keeper.cc
+++ b/system/bta/le_audio/content_control_id_keeper.cc
@@ -17,6 +17,7 @@
#include "content_control_id_keeper.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <bitset>
#include <map>
@@ -41,12 +42,11 @@
void SetCcid(types::LeAudioContextType context_type, int ccid) {
if (context_type >= LeAudioContextType::RFU) {
- LOG_ERROR("Unknownd context type %s", ToString(context_type).c_str());
+ log::error("Unknownd context type {}", ToString(context_type));
return;
}
- LOG_DEBUG("Ccid: %d, context type %s", ccid,
- ToString(context_type).c_str());
+ log::debug("Ccid: {}, context type {}", ccid, ToString(context_type));
ccids_.insert_or_assign(context_type, ccid);
}
@@ -62,7 +62,7 @@
}
void RemoveCcid(int ccid) {
- LOG_DEBUG("Ccid: %d", ccid);
+ log::debug("Ccid: {}", ccid);
auto iter = ccids_.begin();
while (iter != ccids_.end()) {
@@ -76,12 +76,12 @@
int GetCcid(types::LeAudioContextType context_type) const {
if (context_type >= LeAudioContextType::RFU) {
- LOG_ERROR("Unknownd context type %s", ToString(context_type).c_str());
+ log::error("Unknownd context type {}", ToString(context_type));
return -1;
}
if (ccids_.count(context_type) == 0) {
- LOG_DEBUG("No CCID for context %s", ToString(context_type).c_str());
+ log::debug("No CCID for context {}", ToString(context_type));
return -1;
}
diff --git a/system/bta/le_audio/device_groups.cc b/system/bta/le_audio/device_groups.cc
index 3140397..2dd37b1 100644
--- a/system/bta/le_audio/device_groups.cc
+++ b/system/bta/le_audio/device_groups.cc
@@ -18,6 +18,8 @@
#include "device_groups.h"
+#include <bluetooth/log.h>
+
#include "bta/include/bta_gatt_api.h"
#include "bta_csis_api.h"
#include "btif/include/btif_profile_storage.h"
@@ -101,7 +103,7 @@
}
void LeAudioDeviceGroup::ClearSinksFromConfiguration(void) {
- LOG_INFO("Group %p, group_id %d", this, group_id_);
+ log::info("Group {}, group_id {}", fmt::ptr(this), group_id_);
auto direction = types::kLeAudioDirectionSink;
stream_conf.stream_params.get(direction).clear();
@@ -109,7 +111,7 @@
}
void LeAudioDeviceGroup::ClearSourcesFromConfiguration(void) {
- LOG_INFO("Group %p, group_id %d", this, group_id_);
+ log::info("Group {}, group_id {}", fmt::ptr(this), group_id_);
auto direction = types::kLeAudioDirectionSource;
stream_conf.stream_params.get(direction).clear();
@@ -117,7 +119,7 @@
}
void LeAudioDeviceGroup::ClearAllCises(void) {
- LOG_INFO("group_id: %d", group_id_);
+ log::info("group_id: {}", group_id_);
cig.cises.clear();
ClearSinksFromConfiguration();
ClearSourcesFromConfiguration();
@@ -193,9 +195,9 @@
bool activated = leAudioDevice.lock()->ActivateConfiguredAses(
context_type, metadata_context_types, ccid_lists);
- LOG_INFO("Device %s is %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice.lock().get()->address_),
- activated ? "activated" : " not activated");
+ log::info("Device {} is {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice.lock().get()->address_),
+ activated ? "activated" : " not activated");
if (activated) {
if (!cig.AssignCisIds(leAudioDevice.lock().get())) {
return false;
@@ -530,7 +532,7 @@
if (ase->qos_config.max_transport_latency != 0) {
max_transport_latency = ase->qos_config.max_transport_latency;
} else {
- LOG_WARN("Trying to set latency back to 0, ASE ID %d", ase->id);
+ log::warn("Trying to set latency back to 0, ASE ID {}", ase->id);
}
}
}
@@ -559,7 +561,7 @@
} else if (direction == types::kLeAudioDirectionSource) {
return transport_latency_stom_us_;
} else {
- LOG(ERROR) << __func__ << ", invalid direction";
+ log::error("invalid direction");
return 0;
}
}
@@ -573,7 +575,7 @@
} else if (direction == types::kLeAudioDirectionSource) {
transport_latency_us = &transport_latency_stom_us_;
} else {
- LOG(ERROR) << __func__ << ", invalid direction";
+ log::error("invalid direction");
return;
}
@@ -581,16 +583,16 @@
if ((*transport_latency_us != 0) &&
(*transport_latency_us != new_transport_latency_us)) {
- LOG(WARNING) << __func__ << ", Different transport latency for group: "
- << " old: " << static_cast<int>(*transport_latency_us)
- << " [us], new: " << static_cast<int>(new_transport_latency_us)
- << " [us]";
+ log::warn(
+ "Different transport latency for group: old: {} [us], new: {} [us]",
+ static_cast<int>(*transport_latency_us),
+ static_cast<int>(new_transport_latency_us));
return;
}
- LOG(INFO) << __func__ << ", updated group " << static_cast<int>(group_id_)
- << " transport latency: "
- << static_cast<int>(new_transport_latency_us) << " [us]";
+ log::info("updated group {} transport latency: {} [us]",
+ static_cast<int>(group_id_),
+ static_cast<int>(new_transport_latency_us));
*transport_latency_us = new_transport_latency_us;
}
@@ -644,7 +646,7 @@
phy_bitfield |= bluetooth::hci::kIsoCigPhy2M;
if (!leAudioDevice) {
- LOG(ERROR) << "No active leaudio device for direction?: " << +direction;
+ log::error("No active leaudio device for direction?: {}", direction);
return phy_bitfield;
}
@@ -660,12 +662,12 @@
if (ase->qos_preferences.preferred_phy &&
(phy_bitfield & ase->qos_preferences.preferred_phy)) {
phy_bitfield &= ase->qos_preferences.preferred_phy;
- LOG_DEBUG("Using ASE preferred phy 0x%02x",
- static_cast<int>(phy_bitfield));
+ log::debug("Using ASE preferred phy 0x{:02x}",
+ static_cast<int>(phy_bitfield));
} else {
- LOG_WARN(
- "ASE preferred 0x%02x has nothing common with phy_bitfield "
- "0x%02x ",
+ log::warn(
+ "ASE preferred 0x{:02x} has nothing common with phy_bitfield "
+ "0x{:02x}",
static_cast<int>(ase->qos_preferences.preferred_phy),
static_cast<int>(phy_bitfield));
}
@@ -751,7 +753,7 @@
}
bool LeAudioDeviceGroup::UpdateAudioContextAvailability(void) {
- LOG_DEBUG("%d", group_id_);
+ log::debug("{}", group_id_);
auto old_contexts = GetAvailableContexts();
SetAvailableContexts(GetLatestAvailableContexts());
return old_contexts != GetAvailableContexts();
@@ -776,8 +778,8 @@
}
if (update_config) {
- LOG_INFO("config: %s -> %s", ToHexString(ctx_type).c_str(),
- (new_conf ? new_conf->name.c_str() : "(none)"));
+ log::info("config: {} -> {}", ToHexString(ctx_type),
+ (new_conf ? new_conf->name.c_str() : "(none)"));
context_to_configuration_cache_map.erase(ctx_type);
if (new_conf)
context_to_configuration_cache_map.insert(
@@ -787,7 +789,7 @@
}
void LeAudioDeviceGroup::InvalidateCachedConfigurations(void) {
- LOG_INFO(" Group id: %d", group_id_);
+ log::info("Group id: {}", group_id_);
context_to_configuration_cache_map.clear();
}
@@ -892,8 +894,8 @@
uint8_t LeAudioDeviceGroup::CigConfiguration::GetFirstFreeCisId(
CisType cis_type) const {
- LOG_INFO("Group: %p, group_id: %d cis_type: %d", group_, group_->group_id_,
- static_cast<int>(cis_type));
+ log::info("Group: {}, group_id: {} cis_type: {}", fmt::ptr(group_),
+ group_->group_id_, static_cast<int>(cis_type));
for (size_t id = 0; id < cises.size(); id++) {
if (cises[id].addr.IsEmpty() && cises[id].type == cis_type) {
return id;
@@ -906,12 +908,12 @@
LeAudioDeviceGroup::GetGroupSinkStrategyFromPacs(
int expected_group_size) const {
/* Simple strategy picker */
- LOG_DEBUG(" Group %d size %d", group_id_, expected_group_size);
+ log::debug("Group {} size {}", group_id_, expected_group_size);
if (expected_group_size > 1) {
return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE;
}
- LOG_DEBUG("audio location 0x%04lx", snk_audio_locations_.to_ulong());
+ log::debug("audio location 0x{:04x}", snk_audio_locations_.to_ulong());
if (!(snk_audio_locations_.to_ulong() &
codec_spec_conf::kLeAudioLocationAnyLeft) ||
!(snk_audio_locations_.to_ulong() &
@@ -923,9 +925,9 @@
/* Note: Currently, the audio channel counts LTV is only mandatory for LC3. */
auto channel_count_bitmap =
device->GetSupportedAudioChannelCounts(types::kLeAudioDirectionSink);
- LOG_DEBUG("Supported channel counts for group %d (device %s) is %d",
- group_id_, ADDRESS_TO_LOGGABLE_CSTR(device->address_),
- channel_count_bitmap);
+ log::debug("Supported channel counts for group {} (device {}) is {}",
+ group_id_, ADDRESS_TO_LOGGABLE_CSTR(device->address_),
+ channel_count_bitmap);
if (channel_count_bitmap == 1) {
return types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE;
}
@@ -969,12 +971,11 @@
void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds(
LeAudioContextType context_type) {
- LOG_INFO("Group %p, group_id: %d, context_type: %s", group_,
- group_->group_id_,
- bluetooth::common::ToString(context_type).c_str());
+ log::info("Group {}, group_id: {}, context_type: {}", fmt::ptr(group_),
+ group_->group_id_, bluetooth::common::ToString(context_type));
if (cises.size() > 0) {
- LOG_INFO("CIS IDs already generated");
+ log::info("CIS IDs already generated");
return;
}
@@ -1038,12 +1039,12 @@
bool LeAudioDeviceGroup::CigConfiguration::AssignCisIds(
LeAudioDevice* leAudioDevice) {
ASSERT_LOG(leAudioDevice, "invalid device");
- LOG_INFO("device: %s", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("device: {}", ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
struct ase* ase = leAudioDevice->GetFirstActiveAse();
if (!ase) {
- LOG_ERROR(" Device %s shouldn't be called without an active ASE",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Device {} shouldn't be called without an active ASE",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -1051,10 +1052,10 @@
uint8_t cis_id = kInvalidCisId;
/* CIS ID already set */
if (ase->cis_id != kInvalidCisId) {
- LOG_INFO("ASE ID: %d, is already assigned CIS ID: %d, type %d", ase->id,
- ase->cis_id, cises[ase->cis_id].type);
+ log::info("ASE ID: {}, is already assigned CIS ID: {}, type {}", ase->id,
+ ase->cis_id, cises[ase->cis_id].type);
if (!cises[ase->cis_id].addr.IsEmpty()) {
- LOG_INFO("Bi-Directional CIS already assigned");
+ log::info("Bi-Directional CIS already assigned");
continue;
}
/* Reuse existing CIS ID if available*/
@@ -1070,8 +1071,8 @@
matching_bidir_ase)) {
if ((matching_bidir_ase->cis_id != kInvalidCisId) &&
(matching_bidir_ase->cis_id != cis_id)) {
- LOG_INFO("Bi-Directional CIS is already used. ASE Id: %d cis_id=%d",
- matching_bidir_ase->id, matching_bidir_ase->cis_id);
+ log::info("Bi-Directional CIS is already used. ASE Id: {} cis_id={}",
+ matching_bidir_ase->id, matching_bidir_ase->cis_id);
continue;
}
break;
@@ -1087,14 +1088,14 @@
matching_bidir_ase->cis_id = cis_id;
cises[cis_id].addr = leAudioDevice->address_;
- LOG_INFO(
- " ASE ID: %d and ASE ID: %d, assigned Bi-Directional CIS ID: %d",
- +ase->id, +matching_bidir_ase->id, +ase->cis_id);
+ log::info(
+ "ASE ID: {} and ASE ID: {}, assigned Bi-Directional CIS ID: {}",
+ ase->id, matching_bidir_ase->id, ase->cis_id);
continue;
}
- LOG_WARN(
- " ASE ID: %d, unable to get free Bi-Directional CIS ID but maybe "
+ log::warn(
+ "ASE ID: {}, unable to get free Bi-Directional CIS ID but maybe "
"thats fine. Try using unidirectional.",
ase->id);
}
@@ -1105,23 +1106,23 @@
}
if (cis_id == kInvalidCisId) {
- LOG_WARN(
- " Unable to get free Uni-Directional Sink CIS ID - maybe there is "
+ log::warn(
+ "Unable to get free Uni-Directional Sink CIS ID - maybe there is "
"bi-directional available");
/* This could happen when scenarios for given context type allows for
* Sink and Source configuration but also only Sink configuration.
*/
cis_id = GetFirstFreeCisId(CisType::CIS_TYPE_BIDIRECTIONAL);
if (cis_id == kInvalidCisId) {
- LOG_ERROR("Unable to get free Uni-Directional Sink CIS ID");
+ log::error("Unable to get free Uni-Directional Sink CIS ID");
return false;
}
}
ase->cis_id = cis_id;
cises[cis_id].addr = leAudioDevice->address_;
- LOG_INFO("ASE ID: %d, assigned Uni-Directional Sink CIS ID: %d", ase->id,
- ase->cis_id);
+ log::info("ASE ID: {}, assigned Uni-Directional Sink CIS ID: {}", ase->id,
+ ase->cis_id);
continue;
}
@@ -1137,20 +1138,20 @@
/* This could happen when scenarios for given context type allows for
* Sink and Source configuration but also only Sink configuration.
*/
- LOG_WARN(
- "Unable to get free Uni-Directional Source CIS ID - maybe there "
- "is bi-directional available");
+ log::warn(
+ "Unable to get free Uni-Directional Source CIS ID - maybe there is "
+ "bi-directional available");
cis_id = GetFirstFreeCisId(CisType::CIS_TYPE_BIDIRECTIONAL);
if (cis_id == kInvalidCisId) {
- LOG_ERROR("Unable to get free Uni-Directional Source CIS ID");
+ log::error("Unable to get free Uni-Directional Source CIS ID");
return false;
}
}
ase->cis_id = cis_id;
cises[cis_id].addr = leAudioDevice->address_;
- LOG_INFO("ASE ID: %d, assigned Uni-Directional Source CIS ID: %d", ase->id,
- ase->cis_id);
+ log::info("ASE ID: {}, assigned Uni-Directional Source CIS ID: {}", ase->id,
+ ase->cis_id);
}
return true;
@@ -1158,26 +1159,26 @@
void LeAudioDeviceGroup::CigConfiguration::AssignCisConnHandles(
const std::vector<uint16_t>& conn_handles) {
- LOG_INFO("num of cis handles %d", static_cast<int>(conn_handles.size()));
+ log::info("num of cis handles {}", static_cast<int>(conn_handles.size()));
for (size_t i = 0; i < cises.size(); i++) {
cises[i].conn_handle = conn_handles[i];
- LOG_INFO("assigning cis[%d] conn_handle: %d", cises[i].id,
- cises[i].conn_handle);
+ log::info("assigning cis[{}] conn_handle: {}", cises[i].id,
+ cises[i].conn_handle);
}
}
void LeAudioDeviceGroup::AssignCisConnHandlesToAses(
LeAudioDevice* leAudioDevice) {
ASSERT_LOG(leAudioDevice, "Invalid device");
- LOG_INFO("group: %p, group_id: %d, device: %s", this, group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group: {}, group_id: {}, device: {}", fmt::ptr(this), group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
/* Assign all CIS connection handles to ases */
struct bluetooth::le_audio::types::ase* ase =
leAudioDevice->GetFirstActiveAseByCisAndDataPathState(
CisState::IDLE, DataPathState::IDLE);
if (!ase) {
- LOG_WARN("No active ASE with Cis and Data path state set to IDLE");
+ log::warn("No active ASE with Cis and Data path state set to IDLE");
return;
}
@@ -1201,7 +1202,7 @@
LeAudioDevice* leAudioDevice = GetFirstActiveDevice();
ASSERT_LOG(leAudioDevice, "Shouldn't be called without an active device.");
- LOG_INFO("Group %p, group_id %d", this, group_id_);
+ log::info("Group {}, group_id {}", fmt::ptr(this), group_id_);
/* Assign all CIS connection handles to ases */
for (; leAudioDevice != nullptr;
@@ -1214,8 +1215,9 @@
LeAudioDevice* leAudioDevice) {
ASSERT_LOG(leAudioDevice, "Invalid device");
- LOG_INFO("Group %p, group_id %d, device: %s", group_, group_->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("Group {}, group_id {}, device: {}", fmt::ptr(group_),
+ group_->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
for (struct bluetooth::le_audio::types::cis& cis_entry : cises) {
if (cis_entry.addr == leAudioDevice->address_) {
@@ -1234,8 +1236,8 @@
(direction == types::kLeAudioDirectionSink) ? device.snk_audio_locations_
: device.src_audio_locations_;
- LOG_DEBUG("strategy: %d, locations: %lu", (int)strategy,
- audio_locations.to_ulong());
+ log::debug("strategy: {}, locations: {}", (int)strategy,
+ audio_locations.to_ulong());
switch (strategy) {
case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE:
@@ -1259,8 +1261,8 @@
device.GetSupportedAudioChannelCounts(direction);
auto requested_channel_count = conf.codec.params.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_DEBUG("Requested channel count: %d, supp. channel counts: %s",
- requested_channel_count, loghex(channel_count_mask).c_str());
+ log::debug("Requested channel count: {}, supp. channel counts: {}",
+ requested_channel_count, loghex(channel_count_mask));
/* Return true if requested channel count is set in the supported channel
* counts. In the channel_count_mask, bit 0 is set when 1 channel is
@@ -1293,9 +1295,8 @@
}
if (!set_configurations::check_if_may_cover_scenario(audio_set_conf,
num_of_connected)) {
- LOG_DEBUG(" cannot cover scenario %s, num. of connected: %d",
- bluetooth::common::ToString(context_type).c_str(),
- +num_of_connected);
+ log::debug("cannot cover scenario {}, num. of connected: {}",
+ bluetooth::common::ToString(context_type), num_of_connected);
return false;
}
@@ -1337,17 +1338,17 @@
uint8_t required_device_cnt = device_cnt;
uint8_t active_ase_cnt = 0;
- LOG_DEBUG(
- "Number of devices: %d, number of ASEs: %zu, Max ASE per device: %d, "
- "Strategy: %d",
- +required_device_cnt, +ase_cnt, +max_required_ase_per_dev,
+ log::debug(
+ "Number of devices: {}, number of ASEs: {}, Max ASE per device: {} "
+ "Strategy: {}",
+ required_device_cnt, ase_cnt, max_required_ase_per_dev,
static_cast<int>(strategy));
if (direction == types::kLeAudioDirectionSink &&
strategy != required_snk_strategy) {
- LOG_DEBUG(" Sink strategy mismatch group!=cfg.entry (%d!=%d)",
- static_cast<int>(required_snk_strategy),
- static_cast<int>(strategy));
+ log::debug("Sink strategy mismatch group!=cfg.entry ({}!={})",
+ static_cast<int>(required_snk_strategy),
+ static_cast<int>(strategy));
return false;
}
@@ -1415,8 +1416,8 @@
}
}
- LOG_DEBUG("Chosen ASE Configuration for group: %d, configuration: %s",
- this->group_id_, audio_set_conf->name.c_str());
+ log::debug("Chosen ASE Configuration for group: {}, configuration: {}",
+ this->group_id_, audio_set_conf->name);
return true;
}
@@ -1479,10 +1480,9 @@
* connected
*/
if (dev->GetConnectionState() != DeviceConnectState::CONNECTED) {
- LOG_WARN(
- "Device %s, in the state %s",
- ADDRESS_TO_LOGGABLE_CSTR(dev->address_),
- bluetooth::common::ToString(dev->GetConnectionState()).c_str());
+ log::warn("Device {}, in the state {}",
+ ADDRESS_TO_LOGGABLE_CSTR(dev->address_),
+ bluetooth::common::ToString(dev->GetConnectionState()));
return;
}
@@ -1515,14 +1515,14 @@
if (required_device_cnt > 0) {
/* Don't left any active devices if requirements are not met */
- LOG_ERROR(" could not configure all the devices");
+ log::error("could not configure all the devices");
Deactivate();
return false;
}
}
- LOG_INFO("Choosed ASE Configuration for group: %d, configuration: %s",
- group_id_, audio_set_conf->name.c_str());
+ log::info("Choosed ASE Configuration for group: {}, configuration: {}",
+ group_id_, audio_set_conf->name);
configuration_context_type_ = context_type;
metadata_context_type_ = metadata_context_types;
@@ -1576,30 +1576,30 @@
for (const auto& conf : audio_set_conf->confs.get(direction)) {
if (group_config.sample_rate != 0 &&
conf.codec.GetSamplingFrequencyHz() != group_config.sample_rate) {
- LOG(WARNING) << __func__
- << ", stream configuration could not be "
- "determined (sampling frequency differs) for direction: "
- << loghex(direction);
+ log::warn(
+ "stream configuration could not be determined (sampling frequency "
+ "differs) for direction: {}",
+ loghex(direction));
return std::nullopt;
}
group_config.sample_rate = conf.codec.GetSamplingFrequencyHz();
if (group_config.data_interval_us != 0 &&
conf.codec.GetDataIntervalUs() != group_config.data_interval_us) {
- LOG(WARNING) << __func__
- << ", stream configuration could not be "
- "determined (data interval differs) for direction: "
- << loghex(direction);
+ log::warn(
+ "stream configuration could not be determined (data interval "
+ "differs) for direction: {}",
+ loghex(direction));
return std::nullopt;
}
group_config.data_interval_us = conf.codec.GetDataIntervalUs();
if (group_config.bits_per_sample != 0 &&
conf.codec.GetBitsPerSample() != group_config.bits_per_sample) {
- LOG(WARNING) << __func__
- << ", stream configuration could not be "
- "determined (bits per sample differs) for direction: "
- << loghex(direction);
+ log::warn(
+ "stream configuration could not be determined (bits per sample "
+ "differs) for direction: {}",
+ loghex(direction));
return std::nullopt;
}
group_config.bits_per_sample = conf.codec.GetBitsPerSample();
@@ -1674,7 +1674,7 @@
void LeAudioDeviceGroup::RemoveCisFromStreamIfNeeded(
LeAudioDevice* leAudioDevice, uint16_t cis_conn_hdl) {
- LOG_INFO(" CIS Connection Handle: %d", cis_conn_hdl);
+ log::info("CIS Connection Handle: {}", cis_conn_hdl);
if (!IsCisPartOfCurrentStream(cis_conn_hdl)) return;
@@ -1706,11 +1706,9 @@
params.stream_locations.end());
}
- LOG_INFO(
- " Sink Number Of Devices: %d"
- ", Sink Number Of Channels: %d"
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
+ log::info(
+ "Sink Number Of Devices: {}, Sink Number Of Channels: {}, Source Number "
+ "Of Devices: {}, Source Number Of Channels: {}",
stream_conf.stream_params.sink.num_of_devices,
stream_conf.stream_params.sink.num_of_channels,
stream_conf.stream_params.source.num_of_devices,
@@ -1769,9 +1767,9 @@
btif_storage_set_leaudio_autoconnect(address, false);
device_iter.lock()->autoconnect_flag_ = false;
- LOG_INFO("Group %d in state %s. Removing %s from background connect",
- group_id_, bluetooth::common::ToString(GetState()).c_str(),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Group {} in state {}. Removing {} from background connect",
+ group_id_, bluetooth::common::ToString(GetState()),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
BTA_GATTC_CancelOpen(gatt_if, address, false);
@@ -1795,9 +1793,9 @@
btif_storage_set_leaudio_autoconnect(address, true);
device_iter.lock()->autoconnect_flag_ = true;
- LOG_INFO("Group %d in state %s. Adding %s from background connect",
- group_id_, bluetooth::common::ToString(GetState()).c_str(),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Group {} in state {}. Adding {} from background connect",
+ group_id_, bluetooth::common::ToString(GetState()),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
if (connection_state == DeviceConnectState::DISCONNECTED) {
BTA_GATTC_Open(gatt_if, address, reconnection_mode, false);
@@ -1822,9 +1820,9 @@
}
auto address = device_iter.lock()->address_;
- LOG_INFO("Group %d in state %s. Adding %s to allow list ", group_id_,
- bluetooth::common::ToString(GetState()).c_str(),
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::info("Group {} in state {}. Adding {} to allow list", group_id_,
+ bluetooth::common::ToString(GetState()),
+ ADDRESS_TO_LOGGABLE_CSTR(address));
/* When adding set members to allow list, let use direct connect first.
* When it fails (i.e. device is not advertising), it will go to background
@@ -1845,9 +1843,9 @@
BTA_GATTC_CancelOpen(gatt_if, device_iter.lock()->address_, false);
BTA_GATTC_Open(gatt_if, device_iter.lock()->address_, reconnection_mode,
false);
- LOG_INFO("Group %d in state %s. Adding %s to default reconnection mode ",
- group_id_, bluetooth::common::ToString(GetState()).c_str(),
- ADDRESS_TO_LOGGABLE_CSTR(device_iter.lock()->address_));
+ log::info("Group {} in state {}. Adding {} to default reconnection mode",
+ group_id_, bluetooth::common::ToString(GetState()),
+ ADDRESS_TO_LOGGABLE_CSTR(device_iter.lock()->address_));
device_iter.lock()->SetConnectionState(
DeviceConnectState::CONNECTING_AUTOCONNECT);
}
@@ -1895,9 +1893,8 @@
const set_configurations::AudioSetConfigurations* confs) const {
ASSERT_LOG(confs != nullptr, "confs should not be null");
- LOG_DEBUG("context type: %s, number of connected devices: %d",
- bluetooth::common::ToString(context_type).c_str(),
- +NumOfConnected());
+ log::debug("context type: {}, number of connected devices: {}",
+ bluetooth::common::ToString(context_type), NumOfConnected());
auto num_of_connected = NumOfConnected(context_type);
if (num_of_connected == 0) {
@@ -1906,7 +1903,7 @@
/* Filter out device set for all scenarios */
if (!set_configurations::check_if_may_cover_scenario(confs,
num_of_connected)) {
- LOG_DEBUG(", group is unable to cover scenario");
+ log::debug(", group is unable to cover scenario");
return nullptr;
}
@@ -1916,7 +1913,7 @@
ASSERT_LOG(conf != nullptr, "confs should not be null");
if (IsAudioSetConfigurationSupported(conf, context_type,
required_snk_strategy)) {
- LOG_DEBUG("found: %s", conf->name.c_str());
+ log::debug("found: {}", conf->name);
return conf;
}
}
@@ -1933,22 +1930,22 @@
types::BidirectionalPair<std::vector<uint8_t>> ccid_lists) {
auto conf = GetConfiguration(context_type);
if (!conf) {
- LOG_ERROR(
- ", requested context type: %s , is in mismatch with cached available "
- "contexts ",
- bluetooth::common::ToString(context_type).c_str());
+ log::error(
+ ", requested context type: {} , is in mismatch with cached available "
+ "contexts",
+ bluetooth::common::ToString(context_type));
return false;
}
- LOG_DEBUG(" setting context type: %s",
- bluetooth::common::ToString(context_type).c_str());
+ log::debug("setting context type: {}",
+ bluetooth::common::ToString(context_type));
if (!ConfigureAses(conf.get(), context_type, metadata_context_types,
ccid_lists)) {
- LOG_ERROR(
- ", requested context type: %s , is in mismatch with cached available "
+ log::error(
+ ", requested context type: {}, is in mismatch with cached available "
"contexts",
- bluetooth::common::ToString(context_type).c_str());
+ bluetooth::common::ToString(context_type));
return false;
}
@@ -1981,10 +1978,10 @@
<< (active_conf ? active_conf->name : " not set");
if (cig.cises.size() > 0) {
- LOG_INFO("\n Allocated CISes: %d", static_cast<int>(cig.cises.size()));
+ log::info("\n Allocated CISes: {}", static_cast<int>(cig.cises.size()));
for (auto cis : cig.cises) {
- LOG_INFO("\n cis id: %d, type: %d, conn_handle %d, addr: %s", cis.id,
- cis.type, cis.conn_handle, cis.addr.ToString().c_str());
+ log::info("\n cis id: {}, type: {}, conn_handle {}, addr: {}", cis.id,
+ cis.type, cis.conn_handle, cis.addr.ToString());
}
}
@@ -2016,7 +2013,7 @@
<< " \n MtoS sdu: " << +sdu_mts << ", StoM sdu: " << +sdu_stom;
}
- LOG_INFO("%s", debug_str.str().c_str());
+ log::info("{}", debug_str.str());
for (const auto& device_iter : leAudioDevices_) {
device_iter.lock()->PrintDebugState();
@@ -2104,8 +2101,7 @@
LeAudioDeviceGroup* LeAudioDeviceGroups::Add(int group_id) {
/* Get first free group id */
if (FindById(group_id)) {
- LOG(ERROR) << __func__
- << ", group already exists, id: " << loghex(group_id);
+ log::error("group already exists, id: {}", loghex(group_id));
return nullptr;
}
@@ -2119,7 +2115,7 @@
[&group_id](auto const& group) { return group->group_id_ == group_id; });
if (iter == groups_.end()) {
- LOG(ERROR) << __func__ << ", no such group_id: " << group_id;
+ log::error("no such group_id: {}", group_id);
return;
}
diff --git a/system/bta/le_audio/device_groups.h b/system/bta/le_audio/device_groups.h
index 5178c83..c4e517e 100644
--- a/system/bta/le_audio/device_groups.h
+++ b/system/bta/le_audio/device_groups.h
@@ -36,6 +36,7 @@
#endif
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
#include "devices.h"
#include "le_audio_types.h"
@@ -54,8 +55,8 @@
types::CigState GetState(void) const { return state_; }
void SetState(bluetooth::le_audio::types::CigState state) {
- LOG_VERBOSE("%s -> %s", bluetooth::common::ToString(state_).c_str(),
- bluetooth::common::ToString(state).c_str());
+ log::verbose("{} -> {}", bluetooth::common::ToString(state_),
+ bluetooth::common::ToString(state));
state_ = state;
}
@@ -238,9 +239,9 @@
inline types::AseState GetState(void) const { return current_state_; }
void SetState(types::AseState state) {
- LOG_INFO(" current state: %s, new state %s, in_transition_ %d",
- bluetooth::common::ToString(current_state_).c_str(),
- bluetooth::common::ToString(state).c_str(), in_transition_);
+ log::info("current state: {}, new state {}, in_transition_ {}",
+ bluetooth::common::ToString(current_state_),
+ bluetooth::common::ToString(state), in_transition_);
LeAudioLogHistory::Get()->AddLogHistory(
kLogStateMachineTag, group_id_, RawAddress::kEmpty, kLogStateChangedOp,
bluetooth::common::ToString(current_state_) + "->" +
@@ -249,7 +250,7 @@
if (target_state_ == current_state_) {
in_transition_ = false;
- LOG_INFO("In transition flag cleared");
+ log::info("In transition flag cleared");
}
}
@@ -261,9 +262,9 @@
return notify_streaming_when_cises_are_ready_;
}
void SetTargetState(types::AseState state) {
- LOG_INFO("target state: %s, new target state: %s, in_transition_ %d",
- bluetooth::common::ToString(target_state_).c_str(),
- bluetooth::common::ToString(state).c_str(), in_transition_);
+ log::info("target state: {}, new target state: {}, in_transition_ {}",
+ bluetooth::common::ToString(target_state_),
+ bluetooth::common::ToString(state), in_transition_);
LeAudioLogHistory::Get()->AddLogHistory(
kLogStateMachineTag, group_id_, RawAddress::kEmpty,
kLogTargetStateChangedOp,
@@ -273,7 +274,7 @@
target_state_ = state;
in_transition_ = target_state_ != current_state_;
- LOG_INFO("In transition flag = %d", in_transition_);
+ log::info("In transition flag = {}", in_transition_);
}
/* Returns context types for which support was recently added or removed */
@@ -308,12 +309,11 @@
inline void SetAvailableContexts(
types::BidirectionalPair<types::AudioContexts> new_contexts) {
group_available_contexts_ = new_contexts;
- LOG_DEBUG(
- " group id: %d, available contexts sink: %s, available contexts "
- "source: "
- "%s",
- group_id_, group_available_contexts_.sink.to_string().c_str(),
- group_available_contexts_.source.to_string().c_str());
+ log::debug(
+ "group id: {}, available contexts sink: {}, available contexts source: "
+ "{}",
+ group_id_, group_available_contexts_.sink.to_string(),
+ group_available_contexts_.source.to_string());
}
types::AudioContexts GetAvailableContexts(
@@ -321,12 +321,11 @@
ASSERT_LOG(direction <= (types::kLeAudioDirectionBoth),
"Invalid direction used.");
if (direction < types::kLeAudioDirectionBoth) {
- LOG_DEBUG(
- " group id: %d, available contexts sink: %s, available contexts "
- "source: "
- "%s",
- group_id_, group_available_contexts_.sink.to_string().c_str(),
- group_available_contexts_.source.to_string().c_str());
+ log::debug(
+ "group id: {}, available contexts sink: {}, available contexts "
+ "source: {}",
+ group_id_, group_available_contexts_.sink.to_string(),
+ group_available_contexts_.source.to_string());
return group_available_contexts_.get(direction);
} else {
return types::get_bidirectional(group_available_contexts_);
diff --git a/system/bta/le_audio/devices.cc b/system/bta/le_audio/devices.cc
index a8b03ce..c47e5f9 100644
--- a/system/bta/le_audio/devices.cc
+++ b/system/bta/le_audio/devices.cc
@@ -19,6 +19,7 @@
#include <android_bluetooth_flags.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include "acl_api.h"
#include "bta_gatt_queue.h"
@@ -159,9 +160,9 @@
uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy,
const AudioLocations& device_locations,
AudioLocations& group_locations) {
- LOG_DEBUG("strategy: %d, locations: 0x%lx, input group locations: 0x%lx",
- (int)strategy, device_locations.to_ulong(),
- group_locations.to_ulong());
+ log::debug("strategy: {}, locations: 0x{:x}, input group locations: 0x{:x}",
+ (int)strategy, device_locations.to_ulong(),
+ group_locations.to_ulong());
auto is_left_not_yet_assigned =
!(group_locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft);
@@ -171,7 +172,7 @@
uint32_t right_device_loc = GetFirstRight(device_locations);
if (left_device_loc == 0 && right_device_loc == 0) {
- LOG_WARN("Can't find device able to render left and right audio channel");
+ log::warn("Can't find device able to render left and right audio channel");
}
switch (strategy) {
@@ -195,13 +196,13 @@
}
break;
default:
- LOG_ALWAYS_FATAL("%s: Unknown strategy: %hhu", __func__, strategy);
+ log::fatal("Unknown strategy: {}", strategy);
return 0;
}
- LOG_ERROR(
- "Can't find device for left/right channel. Strategy: %hhu, "
- "device_locations: %lx, output group_locations: %lx.",
+ log::error(
+ "Can't find device for left/right channel. Strategy: {}, "
+ "device_locations: {:x}, output group_locations: {:x}.",
strategy, device_locations.to_ulong(), group_locations.to_ulong());
/* Return either any left or any right audio location. It might result with
@@ -221,13 +222,13 @@
/* First try to use the already configured ASE */
auto ase = GetFirstActiveAseByDirection(direction);
if (ase) {
- LOG_INFO("Using an already active ASE id=%d", ase->id);
+ log::info("Using an already active ASE id={}", ase->id);
} else {
ase = GetFirstInactiveAse(direction, reuse_cis_id);
}
if (!ase) {
- LOG_ERROR("Unable to find an ASE to configure");
+ log::error("Unable to find an ASE to configure");
return false;
}
@@ -311,9 +312,9 @@
SetMetadataToAse(ase, metadata_context_types, ccid_lists);
}
- LOG_DEBUG(
- "device=%s, activated ASE id=%d, direction=%s, max_sdu_size=%d, "
- "cis_id=%d, target_latency=%d",
+ log::debug(
+ "device={}, activated ASE id={}, direction={}, max_sdu_size={}, "
+ "cis_id={}, target_latency={}",
ADDRESS_TO_LOGGABLE_CSTR(address_), ase->id,
(direction == 1 ? "snk" : "src"), ase->qos_config.max_sdu_size,
ase->cis_id, ents[i].qos.target_latency);
@@ -332,9 +333,9 @@
/* LeAudioDevice Class methods implementation */
void LeAudioDevice::SetConnectionState(DeviceConnectState state) {
- LOG_DEBUG("%s, %s --> %s", ADDRESS_TO_LOGGABLE_CSTR(address_),
- bluetooth::common::ToString(connection_state_).c_str(),
- bluetooth::common::ToString(state).c_str());
+ log::debug("{}, {} --> {}", ADDRESS_TO_LOGGABLE_CSTR(address_),
+ bluetooth::common::ToString(connection_state_),
+ bluetooth::common::ToString(state));
LeAudioLogHistory::Get()->AddLogHistory(
kLogConnectionTag, group_id_, address_,
bluetooth::common::ToString(connection_state_) + " -> ",
@@ -389,11 +390,11 @@
}
debug_str << "\n\tMetadata: "
<< base::HexEncode(pac.metadata.data(), pac.metadata.size());
- LOG_DEBUG("%s", debug_str.str().c_str());
+ log::debug("{}", debug_str.str());
if (IS_FLAG_ENABLED(leaudio_dynamic_spatial_audio)) {
if (pac.codec_id == types::kLeAudioCodecHeadtracking) {
- LOG(INFO) << __func__ << ": Headtracking supported";
+ log::info("Headtracking supported");
/* Todo: Set DSA modes according to the codec configuration */
dsa_.modes = {
DsaMode::DISABLED,
@@ -472,7 +473,7 @@
/* Invalid ase given */
if (std::distance(iter, ases_.end()) < 1) {
- LOG_DEBUG("ASE %d does not use bidirectional CIS", base_ase->id);
+ log::debug("ASE {} does not use bidirectional CIS", base_ase->id);
return nullptr;
}
@@ -611,8 +612,8 @@
bool LeAudioDevice::HaveAllActiveAsesSameState(AseState state) {
auto iter =
std::find_if(ases_.begin(), ases_.end(), [&state](const auto& ase) {
- LOG_VERBOSE("ASE id: %d, active: %d, state: %s", ase.id, ase.active,
- bluetooth::common::ToString(ase.state).c_str());
+ log::verbose("ASE id: {}, active: {}, state: {}", ase.id, ase.active,
+ bluetooth::common::ToString(ase.state));
return ase.active && (ase.state != state);
});
@@ -623,8 +624,8 @@
types::DataPathState state) const {
auto iter =
std::find_if(ases_.begin(), ases_.end(), [&state](const auto& ase) {
- LOG_VERBOSE("ASE id: %d, active: %d, state: %s", ase.id, ase.active,
- bluetooth::common::ToString(ase.data_path_state).c_str());
+ log::verbose("ASE id: {}, active: {}, state: {}", ase.id, ase.active,
+ bluetooth::common::ToString(ase.data_path_state));
return ase.active && (ase.data_path_state != state);
});
@@ -635,8 +636,8 @@
auto iter = std::find_if(ases_.begin(), ases_.end(), [](const auto& ase) {
if (!ase.active) return false;
- LOG_VERBOSE("ASE id: %d, state: %s, direction: %d", ase.id,
- bluetooth::common::ToString(ase.state).c_str(), ase.direction);
+ log::verbose("ASE id: {}, state: {}, direction: {}", ase.id,
+ bluetooth::common::ToString(ase.state), ase.direction);
if (ase.direction == types::kLeAudioDirectionSink &&
(ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING &&
ase.state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING))
@@ -672,7 +673,7 @@
bool LeAudioDevice::HaveAllActiveAsesCisEst(void) const {
if (ases_.empty()) {
- LOG_WARN("No ases for device %s", ADDRESS_TO_LOGGABLE_CSTR(address_));
+ log::warn("No ases for device {}", ADDRESS_TO_LOGGABLE_CSTR(address_));
/* If there is no ASEs at all, it means we are good here - meaning, it is
* not waiting for any CIS to be established.
*/
@@ -684,9 +685,8 @@
if (!has_active_ase && ase.active) {
has_active_ase = true;
}
- LOG_VERBOSE("ASE id: %d, cis_state: %s, direction: %d", ase.id,
- bluetooth::common::ToString(ase.cis_state).c_str(),
- ase.direction);
+ log::verbose("ASE id: {}, cis_state: {}, direction: {}", ase.id,
+ bluetooth::common::ToString(ase.cis_state), ase.direction);
return ase.active && (ase.cis_state != CisState::CONNECTED);
});
@@ -711,7 +711,7 @@
direction == types::kLeAudioDirectionSink ? snk_pacs_ : src_pacs_;
if (pacs.size() == 0) {
- LOG(ERROR) << __func__ << " missing PAC for direction " << +direction;
+ log::error("missing PAC for direction {}", direction);
return 0;
}
@@ -750,7 +750,7 @@
direction == types::kLeAudioDirectionSink ? snk_pacs_ : src_pacs_;
if (pacs.size() == 0) {
- LOG_ERROR("missing PAC for direction %d", direction);
+ log::error("missing PAC for direction {}", direction);
return nullptr;
}
@@ -816,7 +816,7 @@
}
}
- LOG_INFO("%s", debug_str.str().c_str());
+ log::info("{}", debug_str.str());
}
uint8_t LeAudioDevice::GetPreferredPhyBitmask(uint8_t preferred_phy) const {
@@ -949,13 +949,11 @@
void LeAudioDevice::SetAvailableContexts(
BidirectionalPair<AudioContexts> contexts) {
- LOG_DEBUG(
- "\n\t previous_contexts_.sink: %s \n\t previous_contexts_.source: %s "
- "\n\t "
- "new_contexts.sink: %s \n\t new_contexts.source: %s \n\t ",
- avail_contexts_.sink.to_string().c_str(),
- avail_contexts_.source.to_string().c_str(),
- contexts.sink.to_string().c_str(), contexts.source.to_string().c_str());
+ log::debug(
+ "\n\t previous_contexts_.sink: {} \n\t previous_contexts_.source: {} "
+ "\n\t new_contexts.sink: {} \n\t new_contexts.source: {} \n\t",
+ avail_contexts_.sink.to_string(), avail_contexts_.source.to_string(),
+ contexts.sink.to_string(), contexts.source.to_string());
avail_contexts_.sink = contexts.sink;
avail_contexts_.source = contexts.source;
@@ -982,19 +980,19 @@
const BidirectionalPair<AudioContexts>& metadata_context_types,
BidirectionalPair<std::vector<uint8_t>> ccid_lists) {
if (conn_id_ == GATT_INVALID_CONN_ID) {
- LOG_WARN(" Device %s is not connected ",
- ADDRESS_TO_LOGGABLE_CSTR(address_));
+ log::warn("Device {} is not connected", ADDRESS_TO_LOGGABLE_CSTR(address_));
return false;
}
bool ret = false;
- LOG_INFO(" Configuring device %s", ADDRESS_TO_LOGGABLE_CSTR(address_));
+ log::info("Configuring device {}", ADDRESS_TO_LOGGABLE_CSTR(address_));
for (auto& ase : ases_) {
if (ase.state == AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED &&
ase.configured_for_context_type == context_type) {
- LOG_INFO(
- " conn_id: %d, ase id %d, cis id %d, cis_handle 0x%04x is activated.",
+ log::info(
+ "conn_id: {}, ase id {}, cis id {}, cis_handle 0x{:04x} is "
+ "activated.",
conn_id_, ase.id, ase.cis_id, ase.cis_conn_hdl);
ase.active = true;
ret = true;
@@ -1010,12 +1008,12 @@
for (auto& ase : ases_) {
if (ase.active == false && ase.cis_state != CisState::IDLE &&
ase.data_path_state != DataPathState::IDLE) {
- LOG_WARN(
- " %s, ase_id: %d, ase.cis_id: %d, cis_handle: 0x%02x, "
- "ase.cis_state=%s, ase.data_path_state=%s",
+ log::warn(
+ "{}, ase_id: {}, ase.cis_id: {}, cis_handle: 0x{:02x}, "
+ "ase.cis_state={}, ase.data_path_state={}",
ADDRESS_TO_LOGGABLE_CSTR(address_), ase.id, ase.cis_id,
- ase.cis_conn_hdl, bluetooth::common::ToString(ase.cis_state).c_str(),
- bluetooth::common::ToString(ase.data_path_state).c_str());
+ ase.cis_conn_hdl, bluetooth::common::ToString(ase.cis_state),
+ bluetooth::common::ToString(ase.data_path_state));
}
if (alarm_is_scheduled(ase.autonomous_operation_timer_)) {
alarm_free(ase.autonomous_operation_timer_);
@@ -1108,8 +1106,8 @@
int group_id) {
auto device = FindByAddress(address);
if (device != nullptr) {
- LOG(ERROR) << __func__ << ", address: " << ADDRESS_TO_LOGGABLE_STR(address)
- << " is already assigned to group: " << device->group_id_;
+ log::error("address: {} is already assigned to group: {}",
+ ADDRESS_TO_LOGGABLE_STR(address), device->group_id_);
return;
}
@@ -1124,8 +1122,7 @@
});
if (iter == leAudioDevices_.end()) {
- LOG(ERROR) << __func__ << ", no such address: "
- << ADDRESS_TO_LOGGABLE_STR(address);
+ log::error("no such address: {}", ADDRESS_TO_LOGGABLE_STR(address));
return;
}
diff --git a/system/bta/le_audio/devices_test.cc b/system/bta/le_audio/devices_test.cc
index 1ad9780..2930e48 100644
--- a/system/bta/le_audio/devices_test.cc
+++ b/system/bta/le_audio/devices_test.cc
@@ -17,6 +17,7 @@
#include "devices.h"
+#include <bluetooth/log.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -26,7 +27,6 @@
#include "le_audio_set_configuration_provider.h"
#include "le_audio_types.h"
#include "mock_codec_manager.h"
-#include "mock_controller.h"
#include "mock_csis_client.h"
#include "os/log.h"
#include "stack/btm/btm_int_types.h"
@@ -67,12 +67,10 @@
void SetUp() override {
devices_ = new LeAudioDevices();
bluetooth::manager::SetMockBtmInterface(&btm_interface);
- controller::SetMockControllerInterface(&controller_interface_);
bluetooth::storage::SetMockBtifStorageInterface(&mock_btif_storage_);
}
void TearDown() override {
- controller::SetMockControllerInterface(nullptr);
bluetooth::manager::SetMockBtmInterface(nullptr);
bluetooth::storage::SetMockBtifStorageInterface(nullptr);
delete devices_;
@@ -80,7 +78,6 @@
LeAudioDevices* devices_ = nullptr;
bluetooth::manager::MockBtmInterface btm_interface;
- controller::MockControllerInterface controller_interface_;
bluetooth::storage::MockBtifStorageInterface mock_btif_storage_;
};
@@ -473,7 +470,6 @@
void SetUp() override {
group_ = new LeAudioDeviceGroup(group_id_);
bluetooth::manager::SetMockBtmInterface(&btm_interface_);
- controller::SetMockControllerInterface(&controller_interface_);
auto codec_location = ::bluetooth::le_audio::types::CodecLocation::HOST;
bluetooth::le_audio::AudioSetConfigurationProvider::Initialize(
@@ -527,7 +523,6 @@
}
void TearDown() override {
- controller::SetMockControllerInterface(nullptr);
bluetooth::manager::SetMockBtmInterface(nullptr);
devices_.clear();
addresses_.clear();
@@ -551,9 +546,9 @@
auto device = (std::make_shared<LeAudioDevice>(
GetTestAddress(index), DeviceConnectState::DISCONNECTED));
devices_.push_back(device);
- LOG_INFO(" addresses %d", (int)(addresses_.size()));
+ log::info("addresses {}", (int)(addresses_.size()));
addresses_.push_back(device->address_);
- LOG_INFO(" Addresses %d", (int)(addresses_.size()));
+ log::info("Addresses {}", (int)(addresses_.size()));
if (out_of_range_device == false) {
group_->AddNode(device);
@@ -983,7 +978,6 @@
std::vector<RawAddress> addresses_;
LeAudioDeviceGroup* group_ = nullptr;
bluetooth::manager::MockBtmInterface btm_interface_;
- controller::MockControllerInterface controller_interface_;
MockCsisClient mock_csis_client_module_;
bluetooth::le_audio::CodecManager* codec_manager_;
diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc
index 34db81a..9837327 100644
--- a/system/bta/le_audio/le_audio_client_test.cc
+++ b/system/bta/le_audio/le_audio_client_test.cc
@@ -15,6 +15,7 @@
* limitations under the License.
*/
+#include <bluetooth/log.h>
#include <com_android_bluetooth_flags.h>
#include <flag_macros.h>
#include <gmock/gmock.h>
@@ -42,7 +43,6 @@
#include "le_audio_set_configuration_provider.h"
#include "le_audio_types.h"
#include "mock_codec_manager.h"
-#include "mock_controller.h"
#include "mock_csis_client.h"
#include "mock_device_groups.h"
#include "mock_state_machine.h"
@@ -149,7 +149,7 @@
num_async_tasks--;
},
std::move(task), std::ref(num_async_tasks)))) {
- LOG(ERROR) << __func__ << ": failed from " << from_here.ToString();
+ bluetooth::log::error("failed from {}", from_here.ToString());
return BT_STATUS_FAIL;
}
num_async_tasks++;
@@ -173,7 +173,7 @@
}
if (!message_loop_thread.EnableRealTimeScheduling())
- LOG(ERROR) << "Unable to set real time scheduling";
+ bluetooth::log::error("Unable to set real time scheduling");
message_loop_ = message_loop_thread.message_loop();
if (message_loop_ == nullptr) FAIL() << "unable to get message loop.";
@@ -868,8 +868,8 @@
if (!group->Configure(context_type, metadata_context_types,
ccid_lists)) {
- LOG_ERROR(
- "Could not configure ASEs for group %d content type %d",
+ log::error(
+ "Could not configure ASEs for group {} content type {}",
group->group_id_, int(context_type));
return false;
@@ -956,15 +956,13 @@
stream_conf->stream_params.source.num_of_channels +=
core_config.GetChannelCountPerIsoStream();
- LOG_INFO(
- " Added Source Stream Configuration. CIS Connection "
- "Handle: %d"
- ", Audio Channel Allocation: %d"
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
- +ase.cis_conn_hdl, +(*core_config.audio_channel_allocation),
- +stream_conf->stream_params.source.num_of_devices,
- +stream_conf->stream_params.source.num_of_channels);
+ log::info(
+ "Added Source Stream Configuration. CIS Connection Handle: "
+ "{}, Audio Channel Allocation: {}, Source Number Of "
+ "Devices: {}, Source Number Of Channels: {}",
+ ase.cis_conn_hdl, (*core_config.audio_channel_allocation),
+ stream_conf->stream_params.source.num_of_devices,
+ stream_conf->stream_params.source.num_of_channels);
}
} else {
auto iter = std::find_if(
@@ -984,15 +982,13 @@
stream_conf->stream_params.sink.num_of_channels +=
core_config.GetChannelCountPerIsoStream();
- LOG_INFO(
- " Added Sink Stream Configuration. CIS Connection Handle: "
- "%d"
- ", Audio Channel Allocation: %d"
- ", Sink Number Of Devices: %d"
- ", Sink Number Of Channels: %d",
- +ase.cis_conn_hdl, +(*core_config.audio_channel_allocation),
- +stream_conf->stream_params.sink.num_of_devices,
- +stream_conf->stream_params.sink.num_of_channels);
+ log::info(
+ "Added Sink Stream Configuration. CIS Connection Handle: "
+ "{}, Audio Channel Allocation: {}, Sink Number Of Devices: "
+ "{}, Sink Number Of Channels: {}",
+ ase.cis_conn_hdl, (*core_config.audio_channel_allocation),
+ stream_conf->stream_params.sink.num_of_devices,
+ stream_conf->stream_params.sink.num_of_channels);
}
}
}
@@ -1028,7 +1024,7 @@
if (!group->Configure(context_type, metadata_context_types,
ccid_lists)) {
- LOG(ERROR) << __func__ << ", failed to set ASE configuration";
+ log::error("failed to set ASE configuration");
return false;
}
@@ -1135,16 +1131,13 @@
*core_config.codec_frames_blocks_per_sdu);
}
- LOG_INFO(
- " Added Source Stream Configuration. CIS Connection "
- "Handle: %d"
- ", Audio Channel Allocation: %d"
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
- +ase.cis_conn_hdl,
- +(*core_config.audio_channel_allocation),
- +stream_conf->stream_params.source.num_of_devices,
- +stream_conf->stream_params.source.num_of_channels);
+ log::info(
+ "Added Source Stream Configuration. CIS Connection "
+ "Handle: {}, Audio Channel Allocation: {}, Source Number "
+ "Of Devices: {}, Source Number Of Channels: {}",
+ ase.cis_conn_hdl, (*core_config.audio_channel_allocation),
+ stream_conf->stream_params.source.num_of_devices,
+ stream_conf->stream_params.source.num_of_channels);
}
} else {
auto iter = std::find_if(
@@ -1209,16 +1202,13 @@
*core_config.codec_frames_blocks_per_sdu);
}
- LOG_INFO(
- " Added Sink Stream Configuration. CIS Connection "
- "Handle: %d"
- ", Audio Channel Allocation: %d"
- ", Sink Number Of Devices: %d"
- ", Sink Number Of Channels: %d",
- +ase.cis_conn_hdl,
- +(*core_config.audio_channel_allocation),
- +stream_conf->stream_params.sink.num_of_devices,
- +stream_conf->stream_params.sink.num_of_channels);
+ log::info(
+ "Added Sink Stream Configuration. CIS Connection Handle: "
+ "{}, Audio Channel Allocation: {}, Sink Number Of "
+ "Devices: {}, Sink Number Of Channels: {}",
+ ase.cis_conn_hdl, (*core_config.audio_channel_allocation),
+ stream_conf->stream_params.sink.num_of_devices,
+ stream_conf->stream_params.sink.num_of_channels);
}
}
}
@@ -1290,11 +1280,11 @@
ases.sink->codec_config.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_INFO(
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
- +stream_conf->stream_params.source.num_of_devices,
- +stream_conf->stream_params.source.num_of_channels);
+ log::info(
+ ", Source Number Of Devices: {}, Source Number Of "
+ "Channels: {}",
+ stream_conf->stream_params.source.num_of_devices,
+ stream_conf->stream_params.source.num_of_channels);
}
return ases.sink;
}),
@@ -1313,11 +1303,11 @@
ases.source->codec_config.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_INFO(
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
- +stream_conf->stream_params.source.num_of_devices,
- +stream_conf->stream_params.source.num_of_channels);
+ log::info(
+ ", Source Number Of Devices: {}, Source Number Of "
+ "Channels: {}",
+ stream_conf->stream_params.source.num_of_devices,
+ stream_conf->stream_params.source.num_of_channels);
}
return ases.source;
}),
@@ -1360,21 +1350,21 @@
auto ases =
leAudioDevice->GetAsesByCisConnHdl(pair.first);
- LOG_INFO(
- ", sink ase to delete. Cis handle: %d"
- ", ase pointer: %p",
- +(int)(pair.first), +ases.sink);
+ log::info(
+ ", sink ase to delete. Cis handle: {}, ase pointer: "
+ "{}",
+ (int)(pair.first), fmt::ptr(+ases.sink));
if (ases.sink) {
stream_conf->stream_params.sink.num_of_devices--;
stream_conf->stream_params.sink.num_of_channels -=
ases.sink->codec_config.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_INFO(
- " Sink Number Of Devices: %d"
- ", Sink Number Of Channels: %d",
- +stream_conf->stream_params.sink.num_of_devices,
- +stream_conf->stream_params.sink.num_of_channels);
+ log::info(
+ "Sink Number Of Devices: {}, Sink Number Of "
+ "Channels: {}",
+ stream_conf->stream_params.sink.num_of_devices,
+ stream_conf->stream_params.sink.num_of_channels);
}
return ases.sink;
}),
@@ -1388,21 +1378,20 @@
auto ases =
leAudioDevice->GetAsesByCisConnHdl(pair.first);
- LOG_INFO(
- ", source to delete. Cis handle: %d"
- ", ase pointer: %p",
- +(int)(pair.first), ases.source);
+ log::info(
+ ", source to delete. Cis handle: {}, ase pointer: {}",
+ (int)(pair.first), fmt::ptr(ases.source));
if (ases.source) {
stream_conf->stream_params.source.num_of_devices--;
stream_conf->stream_params.source.num_of_channels -=
ases.source->codec_config.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_INFO(
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
- +stream_conf->stream_params.source.num_of_devices,
- +stream_conf->stream_params.source.num_of_channels);
+ log::info(
+ ", Source Number Of Devices: {}, Source Number Of "
+ "Channels: {}",
+ stream_conf->stream_params.source.num_of_devices,
+ stream_conf->stream_params.source.num_of_channels);
}
return ases.source;
}),
@@ -1427,21 +1416,21 @@
[device, &stream_conf](auto& pair) {
auto ases = device->GetAsesByCisConnHdl(pair.first);
- LOG_INFO(
- ", sink ase to delete. Cis handle: %d"
- ", ase pointer: %p",
- +(int)(pair.first), +ases.sink);
+ log::info(
+ ", sink ase to delete. Cis handle: {}, ase "
+ "pointer: {}",
+ (int)(pair.first), fmt::ptr(+ases.sink));
if (ases.sink) {
stream_conf->stream_params.sink.num_of_devices--;
stream_conf->stream_params.sink.num_of_channels -=
ases.sink->codec_config.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_INFO(
- " Sink Number Of Devices: %d"
- ", Sink Number Of Channels: %d",
- +stream_conf->stream_params.sink.num_of_devices,
- +stream_conf->stream_params.sink.num_of_channels);
+ log::info(
+ "Sink Number Of Devices: {}, Sink Number Of "
+ "Channels: {}",
+ stream_conf->stream_params.sink.num_of_devices,
+ stream_conf->stream_params.sink.num_of_channels);
}
return ases.sink;
}),
@@ -1455,22 +1444,22 @@
[device, &stream_conf](auto& pair) {
auto ases = device->GetAsesByCisConnHdl(pair.first);
- LOG_INFO(
- ", source to delete. Cis handle: %d"
- ", ase pointer: %p",
- +(int)(pair.first), +ases.source);
+ log::info(
+ ", source to delete. Cis handle: {}, ase pointer: "
+ "{}",
+ (int)(pair.first), fmt::ptr(+ases.source));
if (ases.source) {
stream_conf->stream_params.source.num_of_devices--;
stream_conf->stream_params.source.num_of_channels -=
ases.source->codec_config.GetAsCoreCodecConfig()
.GetChannelCountPerIsoStream();
- LOG_INFO(
- ", Source Number Of Devices: %d"
- ", Source Number Of Channels: %d",
- +stream_conf->stream_params.source.num_of_devices,
- +stream_conf->stream_params.source
- .num_of_channels);
+ log::info(
+ ", Source Number Of Devices: {}, Source Number "
+ "Of Channels: {}",
+ stream_conf->stream_params.source.num_of_devices,
+ stream_conf->stream_params.source
+ .num_of_channels);
}
return ases.source;
}),
@@ -2806,7 +2795,7 @@
return conn_id;
}
}
- LOG_ERROR("GetHCIConnHandle Mock: not a valid test device!");
+ log::error("GetHCIConnHandle Mock: not a valid test device!");
return 0x00FE;
});
ON_CALL(mock_btm_interface_, AclDisconnectFromHandle(_, _))
diff --git a/system/bta/le_audio/le_audio_health_status.cc b/system/bta/le_audio/le_audio_health_status.cc
index a850f2e..c53b28a 100644
--- a/system/bta/le_audio/le_audio_health_status.cc
+++ b/system/bta/le_audio/le_audio_health_status.cc
@@ -16,6 +16,8 @@
#include "le_audio_health_status.h"
+#include <bluetooth/log.h>
+
#include <vector>
#include "bta/include/bta_groups.h"
@@ -36,7 +38,7 @@
class LeAudioHealthStatusImpl : public LeAudioHealthStatus {
public:
- LeAudioHealthStatusImpl(void) { LOG_DEBUG(" Initiated"); }
+ LeAudioHealthStatusImpl(void) { log::debug("Initiated"); }
~LeAudioHealthStatusImpl(void) { clear_module(); }
@@ -45,7 +47,7 @@
}
void RemoveStatistics(const RawAddress& address, int group_id) override {
- LOG_DEBUG("%s, group_id: %d", ADDRESS_TO_LOGGABLE_CSTR(address), group_id);
+ log::debug("{}, group_id: {}", ADDRESS_TO_LOGGABLE_CSTR(address), group_id);
remove_device(address);
remove_group(group_id);
}
@@ -53,20 +55,20 @@
void AddStatisticForDevice(const LeAudioDevice* device,
LeAudioHealthDeviceStatType type) override {
if (device == nullptr) {
- LOG_ERROR("device is null");
+ log::error("device is null");
return;
}
const RawAddress& address = device->address_;
- LOG_DEBUG("%s, %s", ADDRESS_TO_LOGGABLE_CSTR(address),
- ToString(type).c_str());
+ log::debug("{}, {}", ADDRESS_TO_LOGGABLE_CSTR(address), ToString(type));
auto dev = find_device(address);
if (dev == nullptr) {
add_device(address);
dev = find_device(address);
if (dev == nullptr) {
- LOG_ERROR("Could not add device %s", ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::error("Could not add device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
return;
}
}
@@ -103,27 +105,27 @@
void AddStatisticForGroup(const LeAudioDeviceGroup* device_group,
LeAudioHealthGroupStatType type) override {
if (device_group == nullptr) {
- LOG_ERROR("device_group is null");
+ log::error("device_group is null");
return;
}
int group_id = device_group->group_id_;
- LOG_DEBUG("group_id: %d, %s", group_id, ToString(type).c_str());
+ log::debug("group_id: {}, {}", group_id, ToString(type));
auto group = find_group(group_id);
if (group == nullptr) {
add_group(group_id);
group = find_group(group_id);
if (group == nullptr) {
- LOG_ERROR("Could not add group %d", group_id);
+ log::error("Could not add group {}", group_id);
return;
}
}
LeAudioDevice* device = device_group->GetFirstDevice();
if (device == nullptr) {
- LOG_ERROR("Front device is null. Number of devices: %d",
- device_group->Size());
+ log::error("Front device is null. Number of devices: {}",
+ device_group->Size());
return;
}
// log counter metrics
@@ -231,8 +233,8 @@
void send_recommendation_for_device(const RawAddress& address,
LeAudioHealthBasedAction recommendation) {
- LOG_DEBUG("%s, %s", ADDRESS_TO_LOGGABLE_CSTR(address),
- ToString(recommendation).c_str());
+ log::debug("{}, {}", ADDRESS_TO_LOGGABLE_CSTR(address),
+ ToString(recommendation));
/* Notify new user about known groups */
for (auto& cb : callbacks_) {
cb.Run(address, kGroupUnknown, recommendation);
@@ -241,7 +243,7 @@
void send_recommendation_for_group(
int group_id, const LeAudioHealthBasedAction recommendation) {
- LOG_DEBUG("group_id: %d, %s", group_id, ToString(recommendation).c_str());
+ log::debug("group_id: {}, {}", group_id, ToString(recommendation));
/* Notify new user about known groups */
for (auto& cb : callbacks_) {
cb.Run(RawAddress::kEmpty, group_id, recommendation);
@@ -301,8 +303,7 @@
void log_counter_metrics_for_device(LeAudioHealthDeviceStatType type,
bool in_allowlist) {
- LOG_DEBUG("in_allowlist: %d, type: %s", in_allowlist,
- ToString(type).c_str());
+ log::debug("in_allowlist: {}, type: {}", in_allowlist, ToString(type));
android::bluetooth::CodePathCounterKeyEnum key;
if (in_allowlist) {
switch (type) {
@@ -320,7 +321,7 @@
LE_AUDIO_ALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_CSIS;
break;
default:
- LOG_ERROR("Metric unhandled %d", type);
+ log::error("Metric unhandled {}", type);
return;
}
} else {
@@ -339,7 +340,7 @@
LE_AUDIO_NONALLOWLIST_DEVICE_HEALTH_STATUS_BAD_INVALID_CSIS;
break;
default:
- LOG_ERROR("Metric unhandled %d", type);
+ log::error("Metric unhandled {}", type);
return;
}
}
@@ -348,8 +349,7 @@
void log_counter_metrics_for_group(LeAudioHealthGroupStatType type,
bool in_allowlist) {
- LOG_DEBUG("in_allowlist: %d, type: %s", in_allowlist,
- ToString(type).c_str());
+ log::debug("in_allowlist: {}, type: {}", in_allowlist, ToString(type));
android::bluetooth::CodePathCounterKeyEnum key;
if (in_allowlist) {
switch (type) {
@@ -366,7 +366,7 @@
LE_AUDIO_ALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_SIGNALING_FAILED;
break;
default:
- LOG_ERROR("Metric unhandled %d", type);
+ log::error("Metric unhandled {}", type);
return;
}
} else {
@@ -384,7 +384,7 @@
LE_AUDIO_NONALLOWLIST_GROUP_HEALTH_STATUS_BAD_ONCE_SIGNALING_FAILED;
break;
default:
- LOG_ERROR("Metric unhandled %d", type);
+ log::error("Metric unhandled {}", type);
return;
}
}
diff --git a/system/bta/le_audio/le_audio_health_status.h b/system/bta/le_audio/le_audio_health_status.h
index 29cae6d..d7d833a 100644
--- a/system/bta/le_audio/le_audio_health_status.h
+++ b/system/bta/le_audio/le_audio_health_status.h
@@ -162,4 +162,13 @@
}
return os;
}
-} // namespace bluetooth::le_audio
\ No newline at end of file
+} // namespace bluetooth::le_audio
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::le_audio::LeAudioHealthDeviceStatType>
+ : enum_formatter<bluetooth::le_audio::LeAudioHealthDeviceStatType> {};
+template <>
+struct formatter<bluetooth::le_audio::LeAudioHealthGroupStatType>
+ : enum_formatter<bluetooth::le_audio::LeAudioHealthGroupStatType> {};
+} // namespace fmt
diff --git a/system/bta/le_audio/le_audio_log_history.cc b/system/bta/le_audio/le_audio_log_history.cc
index fe9dafd..21decea 100644
--- a/system/bta/le_audio/le_audio_log_history.cc
+++ b/system/bta/le_audio/le_audio_log_history.cc
@@ -17,6 +17,7 @@
#include "le_audio_log_history.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <check.h>
#include <cstdint>
@@ -30,6 +31,8 @@
#include "osi/include/osi.h"
#include "osi/include/properties.h"
+using namespace bluetooth;
+
constexpr size_t kMaxLogSize = 255;
constexpr size_t kLeAudioLogHistoryBufferSize = 200;
@@ -109,7 +112,7 @@
const RawAddress& addr, const std::string& msg,
const std::string& extra) {
if (history_ == nullptr) {
- LOG_ERROR(
+ log::error(
"LeAudioLogHistory has not been constructed or already destroyed !");
return;
}
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 dfbad0d..79494d5 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
@@ -16,6 +16,7 @@
*/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <mutex>
#include <string>
@@ -150,17 +151,17 @@
if (context_configurations_.count(context_type))
return &context_configurations_.at(context_type);
- LOG_WARN(": No predefined scenario for the context %d was found.",
- (int)context_type);
+ log::warn(": No predefined scenario for the context {} was found.",
+ (int)context_type);
auto [it_begin, it_end] = ScenarioToContextTypes(kDefaultScenario);
if (it_begin != it_end) {
- LOG_WARN(": Using '%s' scenario by default.", kDefaultScenario);
+ log::warn(": Using '{}' scenario by default.", kDefaultScenario);
return &context_configurations_.at(it_begin->second);
}
- LOG_ERROR(
- ": No valid configuration for the default '%s' scenario, or no audio "
+ log::error(
+ ": No valid configuration for the default '{}' scenario, or no audio "
"set configurations loaded at all.",
kDefaultScenario);
return nullptr;
@@ -319,9 +320,10 @@
}
}
- LOG_INFO("Audio set config %s: codec config %s, qos_sink %s, qos_source %s",
- flat_cfg->name()->c_str(), codec_config_key.c_str(),
- qos_sink_key.c_str(), qos_source_key.c_str());
+ log::info(
+ "Audio set config {}: codec config {}, qos_sink {}, qos_source {}",
+ flat_cfg->name()->c_str(), codec_config_key, qos_sink_key,
+ qos_source_key);
const fbs::le_audio::QosConfiguration* qos_sink_cfg = nullptr;
for (auto i = qos_cfgs->begin(); i != qos_cfgs->end(); ++i) {
@@ -347,7 +349,7 @@
qos.sink.retransmission_number = qos_sink_cfg->retransmission_number();
qos.sink.max_transport_latency = qos_sink_cfg->max_transport_latency();
} else {
- LOG_ERROR("No qos config matching key %s found", qos_sink_key.c_str());
+ log::error("No qos config matching key {} found", qos_sink_key);
}
if (qos_source_cfg != nullptr) {
@@ -358,7 +360,7 @@
qos.source.max_transport_latency =
qos_source_cfg->max_transport_latency();
} else {
- LOG_ERROR("No qos config matching key %s found", qos_source_key.c_str());
+ log::error("No qos config matching key {} found", qos_source_key);
}
const fbs::le_audio::CodecConfiguration* codec_cfg = nullptr;
@@ -402,11 +404,10 @@
}
} else {
if (codec_cfg == nullptr) {
- LOG_ERROR("No codec config matching key %s found",
- codec_config_key.c_str());
+ log::error("No codec config matching key {} found", codec_config_key);
} else {
- LOG_ERROR("Configuration '%s' has no valid subconfigurations.",
- flat_cfg->name()->c_str());
+ log::error("Configuration '{}' has no valid subconfigurations.",
+ flat_cfg->name()->c_str());
}
}
@@ -477,7 +478,7 @@
if ((flat_qos_configs == nullptr) || (flat_qos_configs->size() == 0))
return false;
- LOG_DEBUG(": Updating %d qos config entries.", flat_qos_configs->size());
+ log::debug(": Updating {} qos config entries.", flat_qos_configs->size());
std::vector<const fbs::le_audio::QosConfiguration*> qos_cfgs;
for (auto const& flat_qos_cfg : *flat_qos_configs) {
qos_cfgs.push_back(flat_qos_cfg);
@@ -487,8 +488,8 @@
if ((flat_codec_configs == nullptr) || (flat_codec_configs->size() == 0))
return false;
- LOG_DEBUG(": Updating %d codec config entries.",
- flat_codec_configs->size());
+ log::debug(": Updating {} codec config entries.",
+ flat_codec_configs->size());
std::vector<const fbs::le_audio::CodecConfiguration*> codec_cfgs;
for (auto const& flat_codec_cfg : *flat_codec_configs) {
codec_cfgs.push_back(flat_codec_cfg);
@@ -497,7 +498,7 @@
auto flat_configs = configurations_root->configurations();
if ((flat_configs == nullptr) || (flat_configs->size() == 0)) return false;
- LOG_DEBUG(": Updating %d config entries.", flat_configs->size());
+ log::debug(": Updating {} config entries.", flat_configs->size());
for (auto const& flat_cfg : *flat_configs) {
auto configuration = AudioSetConfigurationFromFlat(flat_cfg, &codec_cfgs,
&qos_cfgs, location);
@@ -557,12 +558,12 @@
if ((flat_scenarios == nullptr) || (flat_scenarios->size() == 0))
return false;
- LOG_DEBUG(": Updating %d scenarios.", flat_scenarios->size());
+ log::debug(": Updating {} scenarios.", flat_scenarios->size());
for (auto const& scenario : *flat_scenarios) {
- LOG_DEBUG("Scenario %s configs:", scenario->name()->c_str());
+ log::debug("Scenario {} configs:", scenario->name()->c_str());
auto configs = AudioSetConfigurationsFromFlatScenario(scenario);
for (auto& config : configs) {
- LOG_DEBUG("\t\t Audio set config: %s", config->name.c_str());
+ log::debug("\t\t Audio set config: {}", config->name);
}
auto [it_begin, it_end] =
diff --git a/system/bta/le_audio/le_audio_types.cc b/system/bta/le_audio/le_audio_types.cc
index c942de1..66fdf2a 100644
--- a/system/bta/le_audio/le_audio_types.cc
+++ b/system/bta/le_audio/le_audio_types.cc
@@ -24,6 +24,7 @@
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include "audio_hal_client/audio_hal_client.h"
#include "common/strings.h"
@@ -71,12 +72,11 @@
uint8_t& out_cis_count_bidir,
uint8_t& out_cis_count_unidir_sink,
uint8_t& out_cis_count_unidir_source) {
- LOG_INFO(
- " %s strategy %d, group avail sink ases: %d, group avail source ases %d "
- "expected_device_count %d",
- bluetooth::common::ToString(context_type).c_str(),
- static_cast<int>(strategy), avail_group_ase_snk_cnt,
- avail_group_ase_src_count, expected_device_cnt);
+ log::info(
+ "{} strategy {}, group avail sink ases: {}, group avail source ases {} "
+ "expected_device_count {}",
+ bluetooth::common::ToString(context_type), static_cast<int>(strategy),
+ avail_group_ase_snk_cnt, avail_group_ase_src_count, expected_device_cnt);
bool is_bidirectional = types::kLeAudioContextAllBidir.test(context_type);
@@ -124,13 +124,13 @@
}
break;
case types::LeAudioConfigurationStrategy::RFU:
- LOG_ERROR("Should not happen;");
+ log::error("Should not happen;");
break;
}
- LOG_INFO(
- "Required cis count: Bi-Directional: %d, Uni-Directional Sink: %d, "
- "Uni-Directional Source: %d",
+ log::info(
+ "Required cis count: Bi-Directional: {}, Uni-Directional Sink: {}, "
+ "Uni-Directional Source: {}",
out_cis_count_bidir, out_cis_count_unidir_sink,
out_cis_count_unidir_source);
}
@@ -138,7 +138,7 @@
bool check_if_may_cover_scenario(const AudioSetConfigurations* audio_set_confs,
uint8_t group_size) {
if (!audio_set_confs) {
- LOG(ERROR) << __func__ << ", no audio requirements for group";
+ log::error("no audio requirements for group");
return false;
}
@@ -148,7 +148,7 @@
bool check_if_may_cover_scenario(const AudioSetConfiguration* audio_set_conf,
uint8_t group_size) {
if (!audio_set_conf) {
- LOG(ERROR) << __func__ << ", no audio requirement for group";
+ log::error("no audio requirement for group");
return false;
}
@@ -167,58 +167,58 @@
/* Sampling frequency */
if (!caps.HasSupportedSamplingFrequencies() || !config.sampling_frequency) {
- LOG_DEBUG("Missing supported sampling frequencies capability");
+ log::debug("Missing supported sampling frequencies capability");
return false;
}
if (!caps.IsSamplingFrequencyConfigSupported(
config.sampling_frequency.value())) {
- LOG_DEBUG("Cfg: SamplingFrequency= 0x%04x",
- config.sampling_frequency.value());
- LOG_DEBUG("Cap: SupportedSamplingFrequencies= 0x%04x",
- caps.supported_sampling_frequencies.value());
- LOG_DEBUG("Sampling frequency not supported");
+ log::debug("Cfg: SamplingFrequency= 0x{:04x}",
+ config.sampling_frequency.value());
+ log::debug("Cap: SupportedSamplingFrequencies= 0x{:04x}",
+ caps.supported_sampling_frequencies.value());
+ log::debug("Sampling frequency not supported");
return false;
}
/* Channel counts */
if (!caps.IsAudioChannelCountsSupported(
config.GetChannelCountPerIsoStream())) {
- LOG_DEBUG("Cfg: Allocated channel count= 0x%04x",
- config.GetChannelCountPerIsoStream());
- LOG_DEBUG("Cap: Supported channel counts= 0x%04x",
- caps.supported_audio_channel_counts.value_or(1));
- LOG_DEBUG("Channel count not supported");
+ log::debug("Cfg: Allocated channel count= 0x{:04x}",
+ config.GetChannelCountPerIsoStream());
+ log::debug("Cap: Supported channel counts= 0x{:04x}",
+ caps.supported_audio_channel_counts.value_or(1));
+ log::debug("Channel count not supported");
return false;
}
/* Frame duration */
if (!caps.HasSupportedFrameDurations() || !config.frame_duration) {
- LOG_DEBUG("Missing supported frame durations capability");
+ log::debug("Missing supported frame durations capability");
return false;
}
if (!caps.IsFrameDurationConfigSupported(config.frame_duration.value())) {
- LOG_DEBUG("Cfg: FrameDuration= 0x%04x", config.frame_duration.value());
- LOG_DEBUG("Cap: SupportedFrameDurations= 0x%04x",
- caps.supported_frame_durations.value());
- LOG_DEBUG("Frame duration not supported");
+ log::debug("Cfg: FrameDuration= 0x{:04x}", config.frame_duration.value());
+ log::debug("Cap: SupportedFrameDurations= 0x{:04x}",
+ caps.supported_frame_durations.value());
+ log::debug("Frame duration not supported");
return false;
}
/* Octets per frame */
if (!caps.HasSupportedOctetsPerCodecFrame() ||
!config.octets_per_codec_frame) {
- LOG_DEBUG("Missing supported octets per codec frame");
+ log::debug("Missing supported octets per codec frame");
return false;
}
if (!caps.IsOctetsPerCodecFrameConfigSupported(
config.octets_per_codec_frame.value())) {
- LOG_DEBUG("Cfg: Octets per frame=%d",
- config.octets_per_codec_frame.value());
- LOG_DEBUG("Cap: Min octets per frame=%d",
- caps.supported_min_octets_per_codec_frame.value());
- LOG_DEBUG("Cap: Max octets per frame=%d",
- caps.supported_max_octets_per_codec_frame.value());
- LOG_DEBUG("Octets per codec frame outside the capabilities");
+ log::debug("Cfg: Octets per frame={}",
+ config.octets_per_codec_frame.value());
+ log::debug("Cap: Min octets per frame={}",
+ caps.supported_min_octets_per_codec_frame.value());
+ log::debug("Cap: Max octets per frame={}",
+ caps.supported_max_octets_per_codec_frame.value());
+ log::debug("Octets per codec frame outside the capabilities");
return false;
}
@@ -231,7 +231,7 @@
if (codec_id != pac.codec_id) return false;
- LOG_DEBUG(": Settings for format: 0x%02x ", codec_id.coding_format);
+ log::debug(": Settings for format: 0x{:02x}", codec_id.coding_format);
if (utils::IsCodecUsingLtvFormat(codec_id)) {
ASSERT_LOG(!pac.codec_spec_caps.IsEmpty(),
@@ -250,7 +250,7 @@
case kLeAudioCodingFormatLC3:
return params.GetAsCoreCodecConfig().GetSamplingFrequencyHz();
default:
- LOG_WARN(", invalid codec id: 0x%02x", id.coding_format);
+ log::warn(", invalid codec id: 0x{:02x}", id.coding_format);
return 0;
}
};
@@ -260,7 +260,7 @@
case kLeAudioCodingFormatLC3:
return params.GetAsCoreCodecConfig().GetFrameDurationUs();
default:
- LOG_WARN(", invalid codec id: 0x%02x", id.coding_format);
+ log::warn(", invalid codec id: 0x{:02x}", id.coding_format);
return 0;
}
};
@@ -271,7 +271,7 @@
/* XXX LC3 supports 16, 24, 32 */
return 16;
default:
- LOG_WARN(", invalid codec id: 0x%02x", id.coding_format);
+ log::warn(", invalid codec id: 0x{:02x}", id.coding_format);
return 0;
}
};
@@ -552,8 +552,7 @@
if (ltv_len == 0) continue;
if (p_value_end < (p_value + ltv_len)) {
- LOG(ERROR) << __func__
- << " Invalid ltv_len: " << static_cast<int>(ltv_len);
+ log::error("Invalid ltv_len: {}", static_cast<int>(ltv_len));
invalidate();
return false;
}
@@ -650,7 +649,7 @@
void AppendMetadataLtvEntryForCcidList(std::vector<uint8_t>& metadata,
const std::vector<uint8_t>& ccid_list) {
if (ccid_list.size() == 0) {
- LOG_WARN("Empty CCID list.");
+ log::warn("Empty CCID list.");
return;
}
diff --git a/system/bta/le_audio/le_audio_types.h b/system/bta/le_audio/le_audio_types.h
index 7e38763..067e462 100644
--- a/system/bta/le_audio/le_audio_types.h
+++ b/system/bta/le_audio/le_audio_types.h
@@ -22,6 +22,7 @@
#pragma once
+#include <bluetooth/log.h>
#include <stdint.h>
#include <bitset>
@@ -1277,4 +1278,17 @@
void AppendMetadataLtvEntryForStreamingContext(
std::vector<uint8_t>& metadata, types::AudioContexts context_type);
uint8_t GetMaxCodecFramesPerSduFromPac(const types::acs_ac_record* pac_record);
-} // namespace bluetooth::le_audio
\ No newline at end of file
+} // namespace bluetooth::le_audio
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::le_audio::DsaMode>
+ : enum_formatter<bluetooth::le_audio::DsaMode> {};
+template <>
+struct formatter<bluetooth::le_audio::types::CisType>
+ : enum_formatter<bluetooth::le_audio::types::CisType> {};
+template <>
+struct formatter<bluetooth::le_audio::types::LeAudioConfigurationStrategy>
+ : enum_formatter<bluetooth::le_audio::types::LeAudioConfigurationStrategy> {
+};
+} // namespace fmt
diff --git a/system/bta/le_audio/le_audio_utils.cc b/system/bta/le_audio/le_audio_utils.cc
index 0907a58..1e4ed1e 100644
--- a/system/bta/le_audio/le_audio_utils.cc
+++ b/system/bta/le_audio/le_audio_utils.cc
@@ -16,6 +16,8 @@
#include "le_audio_utils.h"
+#include <bluetooth/log.h>
+
#include "bta/le_audio/content_control_id_keeper.h"
#include "common/strings.h"
#include "le_audio_types.h"
@@ -25,6 +27,18 @@
using bluetooth::le_audio::types::AudioContexts;
using bluetooth::le_audio::types::LeAudioContextType;
+namespace fmt {
+template <>
+struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {};
+template <>
+struct formatter<audio_content_type_t> : enum_formatter<audio_content_type_t> {
+};
+template <>
+struct formatter<audio_source_t> : enum_formatter<audio_source_t> {};
+template <>
+struct formatter<audio_devices_t> : enum_formatter<audio_devices_t> {};
+} // namespace fmt
+
namespace bluetooth::le_audio {
namespace utils {
@@ -159,7 +173,7 @@
std::istringstream iss(tags);
std::string t;
while (std::getline(iss, t, AUDIO_ATTRIBUTES_TAGS_SEPARATOR)) {
- LOG_VERBOSE("Tag %s", t.c_str());
+ log::verbose("Tag {}", t);
if (t.compare(tag) == 0) {
return true;
}
@@ -174,10 +188,10 @@
auto track = source_metadata.tracks[i].base;
if (track.content_type == 0 && track.usage == 0) continue;
- LOG_INFO("%s: usage=%s(%d), content_type=%s(%d), gain=%f, tag:%s", __func__,
- usageToString(track.usage).c_str(), track.usage,
- contentTypeToString(track.content_type).c_str(),
- track.content_type, track.gain, source_metadata.tracks[i].tags);
+ log::info("usage={}({}), content_type={}({}), gain={:f}, tag:{}",
+ usageToString(track.usage), track.usage,
+ contentTypeToString(track.content_type), track.content_type,
+ track.gain, source_metadata.tracks[i].tags);
if (isMetadataTagPresent(source_metadata.tracks[i].tags,
"VX_AOSP_SAMPLESOUND")) {
@@ -199,9 +213,9 @@
if (track.source == AUDIO_SOURCE_INVALID) continue;
LeAudioContextType track_context;
- LOG_DEBUG(
- "source=%s(0x%02x), gain=%f, destination device=0x%08x, destination "
- "device address=%.32s",
+ log::debug(
+ "source={}(0x{:02x}), gain={:f}, destination device=0x{:08x}, "
+ "destination device address={:32s}",
audioSourceToStr(track.source), track.source, track.gain,
track.dest_device, track.dest_device_address);
@@ -217,10 +231,10 @@
* AUDIO_SOURCE_VOICE_RECOGNITION
*/
track_context = LeAudioContextType::VOICEASSISTANTS;
- LOG_WARN(
+ log::warn(
"Could not match the recording track type to group available "
- "context. Using context %s.",
- ToString(track_context).c_str());
+ "context. Using context {}.",
+ ToString(track_context));
}
all_track_contexts.set(track_context);
@@ -230,14 +244,14 @@
all_track_contexts = AudioContexts(
static_cast<std::underlying_type<LeAudioContextType>::type>(
LeAudioContextType::UNSPECIFIED));
- LOG_DEBUG(
+ log::debug(
"Unable to find supported audio source context for the remote audio "
"sink device. This may result in voice back channel malfunction.");
}
- LOG_INFO("Allowed contexts from sink metadata: %s (0x%08hx)",
- bluetooth::common::ToString(all_track_contexts).c_str(),
- all_track_contexts.value());
+ log::info("Allowed contexts from sink metadata: {} (0x{:08x})",
+ bluetooth::common::ToString(all_track_contexts),
+ all_track_contexts.value());
return all_track_contexts;
}
@@ -252,7 +266,7 @@
bluetooth::le_audio::btle_audio_sample_rate_index_t
translateToBtLeAudioCodecConfigSampleRate(uint32_t sample_rate_capa) {
- LOG_INFO("%d", sample_rate_capa);
+ log::info("{}", sample_rate_capa);
return (bluetooth::le_audio::btle_audio_sample_rate_index_t)(
sample_rate_capa);
}
@@ -296,7 +310,7 @@
types::LeAudioCodecId codec_id, const stream_parameters* stream_params,
bluetooth::le_audio::btle_audio_codec_config_t& out_config) {
if (stream_params == nullptr) {
- LOG_WARN("Stream params are null");
+ log::warn("Stream params are null");
return;
}
diff --git a/system/bta/le_audio/metrics_collector.cc b/system/bta/le_audio/metrics_collector.cc
index cbcf731..9b07e82 100644
--- a/system/bta/le_audio/metrics_collector.cc
+++ b/system/bta/le_audio/metrics_collector.cc
@@ -17,6 +17,7 @@
#include "metrics_collector.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <memory>
#include <vector>
@@ -296,7 +297,7 @@
}
void MetricsCollector::Flush() {
- LOG(INFO) << __func__;
+ log::info("");
for (auto& p : opened_groups_) {
p.second->Flush();
}
diff --git a/system/bta/le_audio/state_machine.cc b/system/bta/le_audio/state_machine.cc
index 2e83633..2193e81 100644
--- a/system/bta/le_audio/state_machine.cc
+++ b/system/bta/le_audio/state_machine.cc
@@ -21,6 +21,7 @@
#include <base/functional/bind.h>
#include <base/functional/callback.h>
#include <base/strings/string_number_conversions.h>
+#include <bluetooth/log.h>
#include "bta_gatt_queue.h"
#include "btm_iso_api.h"
@@ -116,6 +117,8 @@
namespace {
+using namespace bluetooth;
+
constexpr int linkQualityCheckInterval = 4000;
constexpr int kAutonomousTransitionTimeoutMs = 5000;
constexpr int kNumberOfCisRetries = 2;
@@ -147,8 +150,8 @@
bool AttachToStream(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice,
BidirectionalPair<std::vector<uint8_t>> ccids) override {
- LOG(INFO) << __func__ << " group id: " << group->group_id_
- << " device: " << ADDRESS_TO_LOGGABLE_STR(leAudioDevice->address_);
+ log::info("group id: {} device: {}", group->group_id_,
+ ADDRESS_TO_LOGGABLE_STR(leAudioDevice->address_));
/* This function is used to attach the device to the stream.
* Limitation here is that device should be previously in the streaming
@@ -156,10 +159,10 @@
*/
if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING ||
group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG_ERROR(
- " group %d no in correct streaming state: %s or target state: %s",
- group->group_id_, ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(
+ "group {} no in correct streaming state: {} or target state: {}",
+ group->group_id_, ToString(group->GetState()),
+ ToString(group->GetTargetState()));
return false;
}
@@ -168,8 +171,8 @@
get_bidirectional(group->GetMetadataContexts());
auto device_available_contexts = leAudioDevice->GetAvailableContexts();
if (!group_metadata_contexts.test_any(device_available_contexts)) {
- LOG_INFO("%s does is not have required context type",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("{} does is not have required context type",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -180,7 +183,7 @@
if (!group->Configure(group->GetConfigurationContextType(),
group->GetMetadataContexts(), ccids)) {
- LOG_ERROR(" failed to set ASE configuration");
+ log::error("failed to set ASE configuration");
return false;
}
@@ -192,7 +195,7 @@
LeAudioDeviceGroup* group, LeAudioContextType context_type,
const BidirectionalPair<AudioContexts>& metadata_context_types,
BidirectionalPair<std::vector<uint8_t>> ccid_lists) override {
- LOG_INFO(" current state: %s", ToString(group->GetState()).c_str());
+ log::info("current state: {}", ToString(group->GetState()));
switch (group->GetState()) {
case AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED:
@@ -205,7 +208,7 @@
return true;
}
}
- LOG_INFO("Could not activate device, try to configure it again");
+ log::info("Could not activate device, try to configure it again");
}
/* Deactivate previousely activated ASEs in case if there were just a
@@ -223,7 +226,7 @@
case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE:
if (!group->Configure(context_type, metadata_context_types,
ccid_lists)) {
- LOG(ERROR) << __func__ << ", failed to set ASE configuration";
+ log::error("failed to set ASE configuration");
return false;
}
@@ -239,7 +242,7 @@
case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED: {
LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG(ERROR) << __func__ << ", group has no active devices";
+ log::error("group has no active devices");
return false;
}
@@ -259,7 +262,7 @@
LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG(ERROR) << __func__ << ", group has no active devices";
+ log::error("group has no active devices");
return false;
}
@@ -272,8 +275,7 @@
}
default:
- LOG_ERROR("Unable to transit from %s",
- ToString(group->GetState()).c_str());
+ log::error("Unable to transit from {}", ToString(group->GetState()));
return false;
}
@@ -285,9 +287,9 @@
const BidirectionalPair<AudioContexts>& metadata_context_types,
BidirectionalPair<std::vector<uint8_t>> ccid_lists) override {
if (group->GetState() > AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) {
- LOG_ERROR(
- "Stream should be stopped or in configured stream. Current state: %s",
- ToString(group->GetState()).c_str());
+ log::error(
+ "Stream should be stopped or in configured stream. Current state: {}",
+ ToString(group->GetState()));
return false;
}
@@ -295,8 +297,8 @@
ReleaseCisIds(group);
if (!group->Configure(context_type, metadata_context_types, ccid_lists)) {
- LOG_ERROR("Could not configure ASEs for group %d content type %d",
- group->group_id_, int(context_type));
+ log::error("Could not configure ASEs for group {} content type {}",
+ group->group_id_, int(context_type));
return false;
}
@@ -315,8 +317,7 @@
void StopStream(LeAudioDeviceGroup* group) override {
if (group->IsReleasingOrIdle()) {
- LOG(INFO) << __func__ << ", group: " << group->group_id_
- << " already in releasing process";
+ log::info("group: {} already in releasing process", group->group_id_);
return;
}
@@ -347,7 +348,7 @@
bool valid_notification = ParseAseCtpNotification(*ntf, len, value);
if (group == nullptr) {
- LOG_WARN("Notification received to invalid group");
+ log::warn("Notification received to invalid group");
return;
}
@@ -366,16 +367,16 @@
auto in_transition = group->IsInTransition();
if (!in_transition ||
target_state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG_DEBUG(
- "Not interested in ctp result for group %d inTransistion: %d , "
- "targetState: %s",
- group->group_id_, in_transition, ToString(target_state).c_str());
+ log::debug(
+ "Not interested in ctp result for group {} inTransistion: {} , "
+ "targetState: {}",
+ group->group_id_, in_transition, ToString(target_state));
return;
}
if (!valid_notification) {
/* Do nothing, just allow guard timer to fire */
- LOG_ERROR("Invalid CTP notification for group %d", group->group_id_);
+ log::error("Invalid CTP notification for group {}", group->group_id_);
return;
}
@@ -383,9 +384,9 @@
if (entry.response_code !=
bluetooth::le_audio::client_parser::ascs::kCtpResponseCodeSuccess) {
/* Gracefully stop the stream */
- LOG_ERROR(
- "Stoping stream due to control point error for ase: %d, error: "
- "0x%02x, reason: 0x%02x",
+ log::error(
+ "Stoping stream due to control point error for ase: {}, error: "
+ "0x{:02x}, reason: 0x{:02x}",
entry.ase_id, entry.response_code, entry.reason);
notifyLeAudioHealth(group,
@@ -396,10 +397,8 @@
}
}
- LOG_DEBUG(
- "Ctp result OK for group %d inTransistion: %d , "
- "targetState: %s",
- group->group_id_, in_transition, ToString(target_state).c_str());
+ log::debug("Ctp result OK for group {} inTransistion: {} , targetState: {}",
+ group->group_id_, in_transition, ToString(target_state));
}
void ProcessGattNotifEvent(uint8_t* value, uint16_t len, struct ase* ase,
@@ -411,15 +410,15 @@
if (ase->id == 0x00) {
/* Initial state of Ase - update id */
- LOG_INFO(", discovered ase id: %d", arh.id);
+ log::info(", discovered ase id: {}", arh.id);
ase->id = arh.id;
}
auto state = static_cast<AseState>(arh.state);
- LOG_INFO(" %s , ASE id: %d, state changed %s -> %s ",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), +ase->id,
- ToString(ase->state).c_str(), ToString(state).c_str());
+ log::info("{} , ASE id: {}, state changed {} -> {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ToString(ase->state), ToString(state));
log_history_->AddLogHistory(
kLogAseStateNotif, leAudioDevice->group_id_, leAudioDevice->address_,
@@ -457,8 +456,7 @@
AseStateMachineProcessReleasing(arh, ase, group, leAudioDevice);
break;
default:
- LOG(ERROR) << __func__
- << ", Wrong AES status: " << static_cast<int>(arh.state);
+ log::error("Wrong AES status: {}", static_cast<int>(arh.state));
StopStream(group);
break;
}
@@ -472,7 +470,7 @@
*/
if (!group) {
- LOG_ERROR(", group is null");
+ log::error(", group is null");
return;
}
@@ -494,8 +492,8 @@
}
group->cig.SetState(CigState::NONE);
- LOG_ERROR(", failed to create CIG, reason: 0x%02x, new cig state: %s",
- +status, ToString(group->cig.GetState()).c_str());
+ log::error(", failed to create CIG, reason: 0x{:02x}, new cig state: {}",
+ status, ToString(group->cig.GetState()));
StopStream(group);
return;
}
@@ -505,9 +503,10 @@
group->group_id_, ToString(group->cig.GetState()).c_str());
group->cig.SetState(CigState::CREATED);
- LOG_INFO("Group: %p, id: %d cig state: %s, number of cis handles: %d",
- group, group->group_id_, ToString(group->cig.GetState()).c_str(),
- static_cast<int>(conn_handles.size()));
+ log::info("Group: {}, id: {} cig state: {}, number of cis handles: {}",
+ fmt::ptr(group), group->group_id_,
+ ToString(group->cig.GetState()),
+ static_cast<int>(conn_handles.size()));
/* Assign all connection handles to CIS ids of the CIG */
group->cig.AssignCisConnHandles(conn_handles);
@@ -521,9 +520,9 @@
if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
PrepareAndSendQoSToTheGroup(group);
} else {
- LOG_ERROR(", invalid state transition, from: %s , to: %s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {} , to: {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
return;
}
@@ -544,17 +543,17 @@
RawAddress::kEmpty,
kLogCigRemoveOp + " STATUS=" + loghex(status));
if (status != HCI_SUCCESS) {
- LOG_ERROR(
+ log::error(
"Could not recover from the COMMAND DISALLOAD on CigCreate. Status "
- "on CIG remove is 0x%02x",
+ "on CIG remove is 0x{:02x}",
status);
StopStream(group);
return;
}
- LOG_INFO("Succeed on CIG Recover - back to creating CIG");
+ log::info("Succeed on CIG Recover - back to creating CIG");
if (!CigCreate(group)) {
- LOG_ERROR("Could not create CIG. Stop the stream for group %d",
- group->group_id_);
+ log::error("Could not create CIG. Stop the stream for group {}",
+ group->group_id_);
StopStream(group);
}
}
@@ -572,9 +571,9 @@
if (status != HCI_SUCCESS) {
group->cig.SetState(CigState::CREATED);
- LOG_ERROR(
- "failed to remove cig, id: %d, status 0x%02x, new cig state: %s",
- group->group_id_, +status, ToString(group->cig.GetState()).c_str());
+ log::error(
+ "failed to remove cig, id: {}, status 0x{:02x}, new cig state: {}",
+ group->group_id_, status, ToString(group->cig.GetState()));
return;
}
@@ -607,7 +606,7 @@
" STATUS=" + loghex(status));
if (status) {
- LOG(ERROR) << __func__ << ", failed to setup data path";
+ log::error("failed to setup data path");
StopStream(group);
return;
@@ -618,7 +617,7 @@
(group->dsa_.mode == DsaMode::ISO_SW ||
group->dsa_.mode == DsaMode::ISO_HW) &&
leAudioDevice->GetDsaDataPathState() == DataPathState::CONFIGURING) {
- LOG_INFO("Datapath configured for headtracking");
+ log::info("Datapath configured for headtracking");
leAudioDevice->SetDsaDataPathState(DataPathState::CONFIGURED);
return;
}
@@ -629,15 +628,15 @@
CisState::CONNECTED, DataPathState::CONFIGURING);
if (!ase || ase->cis_conn_hdl != conn_handle) {
- LOG(ERROR) << __func__ << " Cannot find ase by handle " << +conn_handle;
+ log::error("Cannot find ase by handle {}", conn_handle);
return;
}
ase->data_path_state = DataPathState::CONFIGURED;
if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG(WARNING) << __func__ << " Group " << group->group_id_
- << " is not targeting streaming state any more";
+ log::warn("Group {} is not targeting streaming state any more",
+ group->group_id_);
return;
}
@@ -654,7 +653,7 @@
if (group->GetNotifyStreamingWhenCisesAreReadyFlag() &&
group->IsGroupStreamReady()) {
group->SetNotifyStreamingWhenCisesAreReadyFlag(false);
- LOG_INFO("Ready to notify Group Streaming.");
+ log::info("Ready to notify Group Streaming.");
cancel_watchdog_if_needed(group->group_id_);
if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
@@ -673,8 +672,8 @@
kLogRemoveDataPathOp + "STATUS=" + loghex(status));
if (status != HCI_SUCCESS) {
- LOG_ERROR(
- "failed to remove ISO data path, reason: 0x%0x - contining stream "
+ log::error(
+ "failed to remove ISO data path, reason: 0x{:0x} - contining stream "
"closing",
status);
/* Just continue - disconnecting CIS removes data path as well.*/
@@ -704,7 +703,7 @@
} else if (IS_FLAG_ENABLED(leaudio_dynamic_spatial_audio)) {
if (group->dsa_.active &&
leAudioDevice->GetDsaDataPathState() == DataPathState::REMOVING) {
- LOG_INFO("DSA data path removed");
+ log::info("DSA data path removed");
leAudioDevice->SetDsaDataPathState(DataPathState::IDLE);
leAudioDevice->SetDsaCisHandle(GATT_INVALID_CONN_ID);
}
@@ -726,22 +725,22 @@
uint32_t txLastSubeventPackets, uint32_t retransmittedPackets,
uint32_t crcErrorPackets, uint32_t rxUnreceivedPackets,
uint32_t duplicatePackets) {
- LOG(INFO) << "conn_handle: " << loghex(conn_handle)
- << ", txUnackedPackets: " << loghex(txUnackedPackets)
- << ", txFlushedPackets: " << loghex(txFlushedPackets)
- << ", txLastSubeventPackets: " << loghex(txLastSubeventPackets)
- << ", retransmittedPackets: " << loghex(retransmittedPackets)
- << ", crcErrorPackets: " << loghex(crcErrorPackets)
- << ", rxUnreceivedPackets: " << loghex(rxUnreceivedPackets)
- << ", duplicatePackets: " << loghex(duplicatePackets);
+ log::info(
+ "conn_handle: {}, txUnackedPackets: {}, txFlushedPackets: {}, "
+ "txLastSubeventPackets: {}, retransmittedPackets: {}, crcErrorPackets: "
+ "{}, rxUnreceivedPackets: {}, duplicatePackets: {}",
+ loghex(conn_handle), loghex(txUnackedPackets), loghex(txFlushedPackets),
+ loghex(txLastSubeventPackets), loghex(retransmittedPackets),
+ loghex(crcErrorPackets), loghex(rxUnreceivedPackets),
+ loghex(duplicatePackets));
}
void ReleaseCisIds(LeAudioDeviceGroup* group) {
if (group == nullptr) {
- LOG_DEBUG(" Group is null.");
+ log::debug("Group is null.");
return;
}
- LOG_DEBUG(" Releasing CIS is for group %d", group->group_id_);
+ log::debug("Releasing CIS is for group {}", group->group_id_);
LeAudioDevice* leAudioDevice = group->GetFirstDevice();
while (leAudioDevice != nullptr) {
@@ -756,18 +755,19 @@
}
void RemoveCigForGroup(LeAudioDeviceGroup* group) {
- LOG_DEBUG("Group: %p, id: %d cig state: %s", group, group->group_id_,
- ToString(group->cig.GetState()).c_str());
+ log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group),
+ group->group_id_, ToString(group->cig.GetState()));
if (group->cig.GetState() != CigState::CREATED) {
- LOG_WARN("Group: %p, id: %d cig state: %s cannot be removed", group,
- group->group_id_, ToString(group->cig.GetState()).c_str());
+ log::warn("Group: {}, id: {} cig state: {} cannot be removed",
+ fmt::ptr(group), group->group_id_,
+ ToString(group->cig.GetState()));
return;
}
group->cig.SetState(CigState::REMOVING);
IsoManager::GetInstance()->RemoveCig(group->group_id_);
- LOG_DEBUG("Group: %p, id: %d cig state: %s", group, group->group_id_,
- ToString(group->cig.GetState()).c_str());
+ log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group),
+ group->group_id_, ToString(group->cig.GetState()));
log_history_->AddLogHistory(kLogStateMachineTag, group->group_id_,
RawAddress::kEmpty, kLogCigRemoveOp);
}
@@ -776,10 +776,9 @@
LeAudioDevice* leAudioDevice) {
FreeLinkQualityReports(leAudioDevice);
if (!group) {
- LOG(ERROR) << __func__
- << " group is null for device: "
- << ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_)
- << " group_id: " << leAudioDevice->group_id_;
+ log::error("group is null for device: {} group_id: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ leAudioDevice->group_id_);
/* mark ASEs as not used. */
leAudioDevice->DeactivateAllAses();
return;
@@ -807,7 +806,7 @@
*/
if ((group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) &&
!group->IsInTransition()) {
- LOG_INFO("group: %d is in IDLE", group->group_id_);
+ log::info("group: {} is in IDLE", group->group_id_);
/* When OnLeAudioDeviceSetStateTimeout happens, group will transition
* to IDLE, and after that an ACL disconnect will be triggered. We need
@@ -816,15 +815,15 @@
* Create when starting stream.
*/
if (group->cig.GetState() == CigState::CREATED) {
- LOG_INFO("CIG is in CREATED state so removing CIG for Group %d",
- group->group_id_);
+ log::info("CIG is in CREATED state so removing CIG for Group {}",
+ group->group_id_);
RemoveCigForGroup(group);
}
return;
}
- LOG_DEBUG(
- " device: %s, group connected: %d, all active ase disconnected:: %d",
+ log::debug(
+ "device: {}, group connected: {}, all active ase disconnected:: {}",
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
group->IsAnyDeviceConnected(), group->HaveAllCisesDisconnected());
@@ -846,8 +845,8 @@
state_machine_callbacks_->StatusReportCb(
group->group_id_, GroupStreamStatus::STREAMING);
} else {
- LOG_WARN("group_id %d not in streaming, CISes are still there",
- group->group_id_);
+ log::warn("group_id {} not in streaming, CISes are still there",
+ group->group_id_);
group->PrintDebugState();
}
@@ -876,14 +875,14 @@
}
if (!group->dsa_.active) {
- LOG_INFO("DSA mode not used");
+ log::info("DSA mode not used");
return;
}
DsaModes dsa_modes = leAudioDevice->GetDsaModes();
if (dsa_modes.empty()) {
- LOG_WARN("DSA mode not supported by this LE Audio device: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("DSA mode not supported by this LE Audio device: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
group->dsa_.active = false;
return;
}
@@ -892,14 +891,14 @@
dsa_modes.end() &&
std::find(dsa_modes.begin(), dsa_modes.end(), DsaMode::ISO_HW) ==
dsa_modes.end()) {
- LOG_WARN("DSA mode not supported by this LE Audio device: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("DSA mode not supported by this LE Audio device: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
group->dsa_.active = false;
return;
}
uint8_t data_path_id = bluetooth::hci::iso_manager::kIsoDataPathHci;
- LOG_INFO("DSA mode used: %d", static_cast<int>(group->dsa_.mode));
+ log::info("DSA mode used: {}", static_cast<int>(group->dsa_.mode));
switch (group->dsa_.mode) {
case DsaMode::ISO_HW:
data_path_id = bluetooth::hci::iso_manager::kIsoDataPathPlatformDefault;
@@ -908,7 +907,7 @@
data_path_id = bluetooth::hci::iso_manager::kIsoDataPathHci;
break;
default:
- LOG_WARN("Unexpected DsaMode: %d", static_cast<int>(group->dsa_.mode));
+ log::warn("Unexpected DsaMode: {}", static_cast<int>(group->dsa_.mode));
group->dsa_.active = false;
return;
}
@@ -916,8 +915,8 @@
leAudioDevice->SetDsaDataPathState(DataPathState::CONFIGURING);
leAudioDevice->SetDsaCisHandle(conn_hdl);
- LOG_VERBOSE(
- "DSA mode supported on this LE Audio device: %s, apply data path: %d",
+ log::verbose(
+ "DSA mode supported on this LE Audio device: {}, apply data path: {}",
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), data_path_id);
LeAudioLogHistory::Get()->AddLogHistory(
@@ -957,18 +956,18 @@
if (ases_pair.sink) ases_pair.sink->cis_state = CisState::ASSIGNED;
if (ases_pair.source) ases_pair.source->cis_state = CisState::ASSIGNED;
- LOG_WARN("%s: failed to create CIS 0x%04x, status: %s (0x%02x)",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- event->cis_conn_hdl,
- ErrorCodeText((ErrorCode)event->status).c_str(), event->status);
+ log::warn("{}: failed to create CIS 0x{:04x}, status: {} (0x{:02x})",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ event->cis_conn_hdl, ErrorCodeText((ErrorCode)event->status),
+ event->status);
if (event->status == HCI_ERR_CONN_FAILED_ESTABLISHMENT &&
((leAudioDevice->cis_failed_to_be_established_retry_cnt_++) <
kNumberOfCisRetries) &&
(CisCreateForDevice(group, leAudioDevice))) {
- LOG_INFO("Retrying (%d) to create CIS for %s ",
- leAudioDevice->cis_failed_to_be_established_retry_cnt_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("Retrying ({}) to create CIS for {}",
+ leAudioDevice->cis_failed_to_be_established_retry_cnt_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
@@ -979,8 +978,8 @@
group->asymmetric_phy_for_unidirectional_cis_supported = false;
}
- LOG_ERROR("CIS creation failed %d times, stopping the stream",
- leAudioDevice->cis_failed_to_be_established_retry_cnt_);
+ log::error("CIS creation failed {} times, stopping the stream",
+ leAudioDevice->cis_failed_to_be_established_retry_cnt_);
leAudioDevice->cis_failed_to_be_established_retry_cnt_ = 0;
/* CIS establishment failed. Remove CIG if no other CIS is already created
@@ -1001,8 +1000,8 @@
}
if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG_ERROR("Unintended CIS establishement event came for group id: %d",
- group->group_id_);
+ log::error("Unintended CIS establishement event came for group id: {}",
+ group->group_id_);
StopStream(group);
return;
}
@@ -1063,9 +1062,9 @@
tGATT_WRITE_TYPE write_type = GATT_WRITE_NO_RSP;
if (value.size() > (leAudioDevice->mtu_ - 3)) {
- LOG_WARN("%s, using long write procedure (%d > %d)",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- static_cast<int>(value.size()), (leAudioDevice->mtu_ - 3));
+ log::warn("{}, using long write procedure ({} > {})",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ static_cast<int>(value.size()), (leAudioDevice->mtu_ - 3));
/* Note, that this type is actually LONG WRITE.
* Meaning all the Prepare Writes plus Execute is handled in the stack
@@ -1104,7 +1103,7 @@
}
if (value == 0) {
- LOG_INFO("Data path was not set. Nothing to do here.");
+ log::info("Data path was not set. Nothing to do here.");
return;
}
@@ -1164,13 +1163,13 @@
*/
if (!group->HaveAllCisesDisconnected()) {
/* There is ASE streaming for some device. Continue streaming. */
- LOG_WARN(
- "Group member disconnected during streaming. Cis handle 0x%04x",
+ log::warn(
+ "Group member disconnected during streaming. Cis handle 0x{:04x}",
event->cis_conn_hdl);
return;
}
- LOG_INFO("Lost all members from the group %d", group->group_id_);
+ log::info("Lost all members from the group {}", group->group_id_);
group->cig.cises.clear();
RemoveCigForGroup(group);
@@ -1203,17 +1202,17 @@
/* Those two are used when closing the stream and CIS disconnection is
* expected */
if (!group->HaveAllCisesDisconnected()) {
- LOG_DEBUG(
- "Still waiting for all CISes being disconnected for group:%d",
+ log::debug(
+ "Still waiting for all CISes being disconnected for group:{}",
group->group_id_);
return;
}
auto current_group_state = group->GetState();
- LOG_INFO("group %d current state: %s, target state: %s",
- group->group_id_,
- bluetooth::common::ToString(current_group_state).c_str(),
- bluetooth::common::ToString(target_state).c_str());
+ log::info("group {} current state: {}, target state: {}",
+ group->group_id_,
+ bluetooth::common::ToString(current_group_state),
+ bluetooth::common::ToString(target_state));
/* It might happen that controller notified about CIS disconnection
* later, after ASE state already changed.
* In such an event, there is need to notify upper layer about state
@@ -1222,8 +1221,8 @@
cancel_watchdog_if_needed(group->group_id_);
if (current_group_state == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
- LOG_INFO(
- "Cises disconnected for group %d, we are good in Idle state.",
+ log::info(
+ "Cises disconnected for group {}, we are good in Idle state.",
group->group_id_);
ReleaseCisIds(group);
state_machine_callbacks_->StatusReportCb(group->group_id_,
@@ -1231,9 +1230,9 @@
} else if (current_group_state ==
AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED) {
auto reconfig = group->IsPendingConfiguration();
- LOG_INFO(
- "Cises disconnected for group: %d, we are good in Configured "
- "state, reconfig=%d.",
+ log::info(
+ "Cises disconnected for group: {}, we are good in Configured "
+ "state, reconfig={}.",
group->group_id_, reconfig);
/* This is Autonomous change if both, target and current state
@@ -1302,8 +1301,8 @@
auto current_state = ToString(group->GetTargetState());
auto new_state = ToString(state);
- LOG_DEBUG("Watchdog watch started for group=%d transition from %s to %s",
- group->group_id_, current_state.c_str(), new_state.c_str());
+ log::debug("Watchdog watch started for group={} transition from {} to {}",
+ group->group_id_, current_state, new_state);
group->SetTargetState(state);
@@ -1331,10 +1330,11 @@
auto cis_conn_hdl = ase->cis_conn_hdl;
auto& params = group->stream_conf.stream_params.get(ase->direction);
- LOG_INFO("Adding cis handle 0x%04x (%s) to stream list", cis_conn_hdl,
- ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink
- ? "sink"
- : "source");
+ log::info(
+ "Adding cis handle 0x{:04x} ({}) to stream list", cis_conn_hdl,
+ ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink
+ ? "sink"
+ : "source");
auto iter = std::find_if(
params.stream_locations.begin(), params.stream_locations.end(),
@@ -1348,7 +1348,7 @@
params.num_of_channels += core_config.GetChannelCountPerIsoStream();
if (!core_config.audio_channel_allocation.has_value()) {
- LOG_WARN("ASE has invalid audio location");
+ log::warn("ASE has invalid audio location");
}
auto ase_audio_channel_allocation =
core_config.audio_channel_allocation.value_or(0);
@@ -1393,11 +1393,9 @@
core_config.GetFrameDurationUs());
}
- LOG_INFO(
- " Added %s Stream Configuration. CIS Connection Handle: %d"
- ", Audio Channel Allocation: %d"
- ", Number Of Devices: %d"
- ", Number Of Channels: %d",
+ log::info(
+ "Added {} Stream Configuration. CIS Connection Handle: {}, Audio "
+ "Channel Allocation: {}, Number Of Devices: {}, Number Of Channels: {}",
(ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink
? "Sink"
: "Source"),
@@ -1411,8 +1409,8 @@
static bool isIntervalAndLatencyProperlySet(uint32_t sdu_interval_us,
uint16_t max_latency_ms) {
- LOG_VERBOSE("sdu_interval_us: %d, max_latency_ms: %d", sdu_interval_us,
- max_latency_ms);
+ log::verbose("sdu_interval_us: {}, max_latency_ms: {}", sdu_interval_us,
+ max_latency_ms);
if (sdu_interval_us == 0) {
return max_latency_ms ==
@@ -1427,12 +1425,12 @@
return;
}
- LOG_INFO("DSA mode selected: %d", (int)group->dsa_.mode);
+ log::info("DSA mode selected: {}", (int)group->dsa_.mode);
group->dsa_.active = false;
/* Unidirectional streaming */
if (param.sdu_itv_stom == 0) {
- LOG_INFO("Media streaming, apply DSA parameters");
+ log::info("Media streaming, apply DSA parameters");
switch (group->dsa_.mode) {
case DsaMode::ISO_HW:
@@ -1444,7 +1442,7 @@
if (!dsa_modes.empty() && it != cis_cfgs.end()) {
if (std::find(dsa_modes.begin(), dsa_modes.end(),
group->dsa_.mode) != dsa_modes.end()) {
- LOG_INFO("Device found with support for selected DsaMode");
+ log::info("Device found with support for selected DsaMode");
group->dsa_.active = true;
@@ -1470,7 +1468,7 @@
break;
}
} else {
- LOG_DEBUG("Bidirection streaming, ignore DSA mode");
+ log::debug("Bidirection streaming, ignore DSA mode");
}
}
@@ -1480,12 +1478,12 @@
uint8_t packing, framing, sca;
std::vector<EXT_CIS_CFG> cis_cfgs;
- LOG_DEBUG("Group: %p, id: %d cig state: %s", group, group->group_id_,
- ToString(group->cig.GetState()).c_str());
+ log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group),
+ group->group_id_, ToString(group->cig.GetState()));
if (group->cig.GetState() != CigState::NONE) {
- LOG_WARN(" Group %p, id: %d has invalid cig state: %s ", group,
- group->group_id_, ToString(group->cig.GetState()).c_str());
+ log::warn("Group {}, id: {} has invalid cig state: {}", fmt::ptr(group),
+ group->group_id_, ToString(group->cig.GetState()));
return false;
}
@@ -1510,7 +1508,7 @@
max_trans_lat_mtos) ||
!isIntervalAndLatencyProperlySet(sdu_interval_stom,
max_trans_lat_stom)) {
- LOG_ERROR("Latency and interval not properly set");
+ log::error("Latency and interval not properly set");
group->PrintDebugState();
return false;
}
@@ -1520,7 +1518,7 @@
if (group->asymmetric_phy_for_unidirectional_cis_supported &&
sdu_interval_stom == 0 &&
(phy_stom & bluetooth::hci::kIsoCigPhy1M) != 0) {
- LOG_INFO("Use asymmetric PHY for unidirectional CIS");
+ log::info("Use asymmetric PHY for unidirectional CIS");
phy_stom = bluetooth::hci::kIsoCigPhy1M;
}
@@ -1589,7 +1587,7 @@
max_trans_lat_stom ==
bluetooth::le_audio::types::kMaxTransportLatencyMin) ||
(max_sdu_size_mtos == 0 && max_sdu_size_stom == 0)) {
- LOG_ERROR(" Trying to create invalid group");
+ log::error("Trying to create invalid group");
group->PrintDebugState();
return false;
}
@@ -1613,8 +1611,8 @@
group->cig.SetState(CigState::CREATING);
IsoManager::GetInstance()->CreateCig(group->group_id_, std::move(param));
- LOG_DEBUG("Group: %p, id: %d cig state: %s", group, group->group_id_,
- ToString(group->cig.GetState()).c_str());
+ log::debug("Group: {}, id: {} cig state: {}", fmt::ptr(group),
+ group->group_id_, ToString(group->cig.GetState()));
return true;
}
@@ -1625,7 +1623,7 @@
/* Make sure CIG is there */
if (group->cig.GetState() != CigState::CREATED) {
- LOG_ERROR("CIG is not created for group_id %d ", group->group_id_);
+ log::error("CIG is not created for group_id {}", group->group_id_);
group->PrintDebugState();
return false;
}
@@ -1648,8 +1646,8 @@
BTM_GetHCIConnHandle(leAudioDevice->address_, BT_TRANSPORT_LE);
conn_pairs.push_back({.cis_conn_handle = ase->cis_conn_hdl,
.acl_conn_handle = acl_handle});
- LOG_INFO(" cis handle: 0x%04x, acl handle: 0x%04x", ase->cis_conn_hdl,
- acl_handle);
+ log::info("cis handle: 0x{:04x}, acl handle: 0x{:04x}", ase->cis_conn_hdl,
+ acl_handle);
extra_stream << "cis_h:" << loghex(ase->cis_conn_hdl)
<< " acl_h:" << loghex(acl_handle) << ";;";
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
@@ -1675,7 +1673,7 @@
/* Make sure CIG is there */
if (group->cig.GetState() != CigState::CREATED) {
- LOG_ERROR("CIG is not created for group_id %d ", group->group_id_);
+ log::error("CIG is not created for group_id {}", group->group_id_);
group->PrintDebugState();
return false;
}
@@ -1751,9 +1749,9 @@
void SetAseState(LeAudioDevice* leAudioDevice, struct ase* ase,
AseState state) {
- LOG_INFO("%s, ase_id: %d, %s -> %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ToString(ase->state).c_str(), ToString(state).c_str());
+ log::info("{}, ase_id: {}, {} -> {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ToString(ase->state), ToString(state));
log_history_->AddLogHistory(
kLogStateMachineTag, leAudioDevice->group_id_, leAudioDevice->address_,
@@ -1781,8 +1779,8 @@
AseState::BTA_LE_AUDIO_ASE_STATE_IDLE)) {
/* More ASEs notification from this device has to come for this group
*/
- LOG_DEBUG("Wait for more ASE to configure for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::debug("Wait for more ASE to configure for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
@@ -1790,14 +1788,15 @@
* If not (e.g. only single device got disconnected), stop here
*/
if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
- LOG_DEBUG("Autonomus change of stated for device %s, ase id: %d",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
+ log::debug("Autonomus change of stated for device {}, ase id: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ ase->id);
return;
}
if (!group->HaveAllActiveDevicesAsesTheSameState(
AseState::BTA_LE_AUDIO_ASE_STATE_IDLE)) {
- LOG_DEBUG("Waiting for more devices to get into idle state");
+ log::debug("Waiting for more devices to get into idle state");
return;
}
@@ -1808,8 +1807,8 @@
/* If all CISes are disconnected, notify upper layer about IDLE state,
* otherwise wait for */
if (!group->HaveAllCisesDisconnected()) {
- LOG_WARN(
- "Not all CISes removed before going to IDLE for group %d, "
+ log::warn(
+ "Not all CISes removed before going to IDLE for group {}, "
"waiting...",
group->group_id_);
group->PrintDebugState();
@@ -1825,21 +1824,21 @@
}
case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED:
case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING:
- LOG_ERROR(
- "Ignore invalid attempt of state transition from %s to %s, %s, "
- "ase_id: %d",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE).c_str(),
+ log::error(
+ "Ignore invalid attempt of state transition from {} to {}, {}, "
+ "ase_id: {}",
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE),
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
break;
case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING:
case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING:
- LOG_ERROR(
- "Invalid state transition from %s to %s, %s, ase_id: "
- "%d. Stopping the stream.",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE).c_str(),
+ log::error(
+ "Invalid state transition from {} to {}, {}, ase_id: {}. Stopping "
+ "the stream.",
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE),
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
StopStream(group);
@@ -1850,7 +1849,7 @@
void PrepareAndSendQoSToTheGroup(LeAudioDeviceGroup* group) {
LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG_ERROR("No active device for the group");
+ log::error("No active device for the group");
group->PrintDebugState();
ClearGroup(group, true);
return;
@@ -1863,10 +1862,10 @@
}
bool PrepareAndSendCodecConfigToTheGroup(LeAudioDeviceGroup* group) {
- LOG_INFO("group_id: %d", group->group_id_);
+ log::info("group_id: {}", group->group_id_);
auto leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG_ERROR("No active device for the group");
+ log::error("No active device for the group");
return false;
}
@@ -1887,7 +1886,7 @@
std::stringstream extra_stream;
if (!group->cig.AssignCisIds(leAudioDevice)) {
- LOG_ERROR(" unable to assign CIS IDs");
+ log::error("unable to assign CIS IDs");
StopStream(group);
return;
}
@@ -1900,9 +1899,9 @@
ase = leAudioDevice->GetFirstActiveAse();
ASSERT_LOG(ase, "shouldn't be called without an active ASE");
for (; ase != nullptr; ase = leAudioDevice->GetNextActiveAse(ase)) {
- LOG_DEBUG("device: %s, ase_id: %d, cis_id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ase->cis_id, ToString(ase->state).c_str());
+ log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ase->cis_id, ToString(ase->state));
conf.ase_id = ase->id;
conf.target_latency = ase->target_latency;
conf.target_phy = group->GetTargetPhy(ase->direction);
@@ -1935,7 +1934,7 @@
struct ase* ase, uint8_t* data, uint16_t len, LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice) {
if (!group) {
- LOG(ERROR) << __func__ << ", leAudioDevice doesn't belong to any group";
+ log::error("leAudioDevice doesn't belong to any group");
return;
}
@@ -2020,8 +2019,9 @@
if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
/* This is autonomus change of the remote device */
- LOG_DEBUG("Autonomus change for device %s, ase id %d. Just store it.",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
+ log::debug(
+ "Autonomus change for device {}, ase id {}. Just store it.",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
/* Since at least one ASE is in configured state, we should admit
* group is configured state */
@@ -2032,8 +2032,8 @@
if (leAudioDevice->HaveAnyUnconfiguredAses()) {
/* More ASEs notification from this device has to come for this group
*/
- LOG_DEBUG("More Ases to be configured for the device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::debug("More Ases to be configured for the device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
@@ -2047,8 +2047,8 @@
bluetooth::le_audio::DeviceConnectState::CONNECTED) {
PrepareAndSendConfigQos(group, leAudioDevice);
} else {
- LOG_DEBUG(
- "Device %s initiated configured state but it is not yet ready "
+ log::debug(
+ "Device {} initiated configured state but it is not yet ready "
"to be configured",
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
}
@@ -2057,7 +2057,7 @@
/* Configure ASEs for next device in group */
if (group->HaveAnyActiveDeviceInUnconfiguredState()) {
- LOG_DEBUG("Waiting for all the ASES in the Configured state");
+ log::debug("Waiting for all the ASES in the Configured state");
return;
}
@@ -2067,8 +2067,8 @@
if (group->GetTargetState() ==
AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
if (!CigCreate(group)) {
- LOG_ERROR("Could not create CIG. Stop the stream for group %d",
- group->group_id_);
+ log::error("Could not create CIG. Stop the stream for group {}",
+ group->group_id_);
StopStream(group);
}
return;
@@ -2077,15 +2077,14 @@
if (group->GetTargetState() ==
AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED &&
group->IsPendingConfiguration()) {
- LOG_INFO(" Configured state completed ");
+ log::info("Configured state completed");
/* If all CISes are disconnected, notify upper layer about IDLE
* state, otherwise wait for */
if (!group->HaveAllCisesDisconnected()) {
- LOG_WARN(
+ log::warn(
"Not all CISes removed before going to CONFIGURED for group "
- "%d, "
- "waiting...",
+ "{}, waiting...",
group->group_id_);
group->PrintDebugState();
return;
@@ -2100,9 +2099,9 @@
return;
}
- LOG_ERROR(", invalid state transition, from: %s to %s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {} to {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
break;
@@ -2142,8 +2141,8 @@
bluetooth::le_audio::DeviceConnectState::CONNECTED) {
PrepareAndSendConfigQos(group, leAudioDevice);
} else {
- LOG_DEBUG(
- "Device %s initiated configured state but it is not yet ready "
+ log::debug(
+ "Device {} initiated configured state but it is not yet ready "
"to be configured",
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
}
@@ -2151,8 +2150,8 @@
}
if (group->HaveAnyActiveDeviceInUnconfiguredState()) {
- LOG_DEBUG(
- "Waiting for all the devices to be configured for group id %d",
+ log::debug(
+ "Waiting for all the devices to be configured for group id {}",
group->group_id_);
return;
}
@@ -2163,8 +2162,8 @@
if (group->GetTargetState() ==
AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
if (!CigCreate(group)) {
- LOG_ERROR("Could not create CIG. Stop the stream for group %d",
- group->group_id_);
+ log::error("Could not create CIG. Stop the stream for group {}",
+ group->group_id_);
StopStream(group);
}
return;
@@ -2173,7 +2172,7 @@
if (group->GetTargetState() ==
AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED &&
group->IsPendingConfiguration()) {
- LOG_INFO(" Configured state completed ");
+ log::info("Configured state completed");
group->ClearPendingConfiguration();
state_machine_callbacks_->StatusReportCb(
group->group_id_, GroupStreamStatus::CONFIGURED_BY_USER);
@@ -2183,9 +2182,9 @@
return;
}
- LOG_INFO("Autonomous change, from: %s to %s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::info("Autonomous change, from: {} to {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
break;
}
@@ -2195,11 +2194,11 @@
group->PrintDebugState();
break;
case AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING:
- LOG_ERROR(
- "Ignore invalid attempt of state transition from %s to %s, %s, "
- "ase_id: %d",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED).c_str(),
+ log::error(
+ "Ignore invalid attempt of state transition from {} to {}, {}, "
+ "ase_id: {}",
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED),
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
break;
@@ -2212,8 +2211,8 @@
AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED)) {
/* More ASEs notification from this device has to come for this group
*/
- LOG_DEBUG("Wait for more ASE to configure for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::debug("Wait for more ASE to configure for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return;
}
@@ -2221,16 +2220,17 @@
* If not (e.g. only single device got disconnected), stop here
*/
if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
- LOG_DEBUG("Autonomus change of stated for device %s, ase id: %d",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
+ log::debug("Autonomus change of stated for device {}, ase id: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ ase->id);
return;
}
{
auto activeDevice = group->GetFirstActiveDevice();
if (activeDevice) {
- LOG_DEBUG(
- "There is at least one active device %s, wait to become "
+ log::debug(
+ "There is at least one active device {}, wait to become "
"inactive",
ADDRESS_TO_LOGGABLE_CSTR(activeDevice->address_));
return;
@@ -2246,8 +2246,8 @@
group->SetTargetState(group->GetState());
if (!group->HaveAllCisesDisconnected()) {
- LOG_WARN(
- "Not all CISes removed before going to IDLE for group %d, "
+ log::warn(
+ "Not all CISes removed before going to IDLE for group {}, "
"waiting...",
group->group_id_);
group->PrintDebugState();
@@ -2261,11 +2261,11 @@
break;
case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING:
case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING:
- LOG_ERROR(
- "Invalid state transition from %s to %s, %s, ase_id: %d. Stopping "
+ log::error(
+ "Invalid state transition from {} to {}, {}, ase_id: {}. Stopping "
"the stream",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED).c_str(),
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_CODEC_CONFIGURED),
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
StopStream(group);
@@ -2278,7 +2278,7 @@
struct ase* ase, LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice) {
if (!group) {
- LOG(ERROR) << __func__ << ", leAudioDevice doesn't belong to any group";
+ log::error("leAudioDevice doesn't belong to any group");
return;
}
@@ -2303,7 +2303,7 @@
if (!group->HaveAllActiveDevicesAsesTheSameState(
AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED)) {
- LOG_DEBUG("Waiting for all the devices to be in QoS state");
+ log::debug("Waiting for all the devices to be in QoS state");
return;
}
@@ -2315,10 +2315,10 @@
if (ase->direction ==
bluetooth::le_audio::types::kLeAudioDirectionSource) {
/* Source ASE cannot go from Streaming to QoS Configured state */
- LOG(ERROR) << __func__ << ", invalid state transition, from: "
- << static_cast<int>(ase->state) << ", to: "
- << static_cast<int>(
- AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED);
+ log::error("invalid state transition, from: {}, to: {}",
+ static_cast<int>(ase->state),
+ static_cast<int>(
+ AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED));
StopStream(group);
return;
}
@@ -2359,9 +2359,9 @@
state_machine_callbacks_->StatusReportCb(
group->group_id_, GroupStreamStatus::SUSPENDED);
} else {
- LOG_ERROR(", invalid state transition, from: %s, to: %s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {}, to: {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
return;
}
@@ -2369,30 +2369,29 @@
}
case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED:
- LOG_INFO(
- "Unexpected state transition from %s to %s, %s, ase_id: %d",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED).c_str(),
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
+ log::info("Unexpected state transition from {} to {}, {}, ase_id: {}",
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED),
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
break;
case AseState::BTA_LE_AUDIO_ASE_STATE_IDLE:
case AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING:
// Do nothing here, just print an error message
- LOG_ERROR(
- "Ignore invalid attempt of state transition from %s to %s, %s, "
- "ase_id: %d",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED).c_str(),
+ log::error(
+ "Ignore invalid attempt of state transition from {} to {}, {}, "
+ "ase_id: {}",
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED),
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
break;
case AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING:
- LOG_ERROR(
- "Invalid state transition from %s to %s, %s, ase_id: "
- "%d. Stopping the stream.",
- ToString(ase->state).c_str(),
- ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED).c_str(),
+ log::error(
+ "Invalid state transition from {} to {}, {}, ase_id: {}. Stopping "
+ "the stream.",
+ ToString(ase->state),
+ ToString(AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED),
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
StopStream(group);
break;
@@ -2400,7 +2399,7 @@
}
void ClearGroup(LeAudioDeviceGroup* group, bool report_idle_state) {
- LOG_DEBUG("group_id: %d", group->group_id_);
+ log::debug("group_id: {}", group->group_id_);
group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
@@ -2419,11 +2418,11 @@
}
void PrepareAndSendEnableToTheGroup(LeAudioDeviceGroup* group) {
- LOG_INFO("group_id: %d", group->group_id_);
+ log::info("group_id: {}", group->group_id_);
auto leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG_ERROR("No active device for the group");
+ log::error("No active device for the group");
group->PrintDebugState();
ClearGroup(group, true);
return;
@@ -2449,9 +2448,9 @@
ase = leAudioDevice->GetFirstActiveAse();
LOG_ASSERT(ase) << __func__ << " shouldn't be called without an active ASE";
do {
- LOG_DEBUG("device: %s, ase_id: %d, cis_id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ase->cis_id, ToString(ase->state).c_str());
+ log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ase->cis_id, ToString(ase->state));
conf.ase_id = ase->id;
conf.metadata = ase->metadata;
confs.push_back(conf);
@@ -2468,19 +2467,19 @@
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpEnable(confs, value);
WriteToControlPoint(leAudioDevice, value);
- LOG_INFO("group_id: %d, %s", leAudioDevice->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group_id: {}, {}", leAudioDevice->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_,
leAudioDevice->address_, msg_stream.str(),
extra_stream.str());
}
GroupStreamStatus PrepareAndSendDisableToTheGroup(LeAudioDeviceGroup* group) {
- LOG_INFO("grop_id: %d", group->group_id_);
+ log::info("grop_id: {}", group->group_id_);
auto leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG_ERROR("No active device for the group");
+ log::error("No active device for the group");
group->PrintDebugState();
ClearGroup(group, false);
return GroupStreamStatus::IDLE;
@@ -2502,16 +2501,16 @@
std::vector<uint8_t> ids;
do {
- LOG_DEBUG("device: %s, ase_id: %d, cis_id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ase->cis_id, ToString(ase->state).c_str());
+ log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ase->cis_id, ToString(ase->state));
ids.push_back(ase->id);
msg_stream << "ASE_ID " << +ase->id << ", ";
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
- LOG_INFO("group_id: %d, %s", leAudioDevice->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group_id: {}, {}", leAudioDevice->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
std::vector<uint8_t> value;
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpDisable(ids, value);
@@ -2522,10 +2521,10 @@
}
GroupStreamStatus PrepareAndSendReleaseToTheGroup(LeAudioDeviceGroup* group) {
- LOG_INFO("group_id: %d", group->group_id_);
+ log::info("group_id: {}", group->group_id_);
LeAudioDevice* leAudioDevice = group->GetFirstActiveDevice();
if (!leAudioDevice) {
- LOG_ERROR("No active device for the group");
+ log::error("No active device for the group");
group->PrintDebugState();
ClearGroup(group, false);
return GroupStreamStatus::IDLE;
@@ -2548,9 +2547,9 @@
stream << kLogAseReleaseOp;
do {
- LOG_DEBUG("device: %s, ase_id: %d, cis_id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ase->cis_id, ToString(ase->state).c_str());
+ log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ase->cis_id, ToString(ase->state));
ids.push_back(ase->id);
stream << "ASE_ID " << +ase->id << ",";
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
@@ -2559,8 +2558,8 @@
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpRelease(ids, value);
WriteToControlPoint(leAudioDevice, value);
- LOG_INFO("group_id: %d, %s", leAudioDevice->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group_id: {}, {}", leAudioDevice->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_,
leAudioDevice->address_, stream.str());
}
@@ -2580,14 +2579,14 @@
for (struct ase* ase = leAudioDevice->GetFirstActiveAse(); ase != nullptr;
ase = leAudioDevice->GetNextActiveAse(ase)) {
- LOG_DEBUG("device: %s, ase_id: %d, cis_id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ase->cis_id, ToString(ase->state).c_str());
+ log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ase->cis_id, ToString(ase->state));
/* Fill in the whole group dependent ASE parameters */
if (!group->GetPresentationDelay(&ase->qos_config.presentation_delay,
ase->direction)) {
- LOG_ERROR("inconsistent presentation delay for group");
+ log::error("inconsistent presentation delay for group");
group->PrintDebugState();
StopStream(group);
return;
@@ -2606,7 +2605,7 @@
conf.sdu_interval = ase->qos_config.sdu_interval;
if (!conf.sdu_interval) {
- LOG_ERROR("unsupported SDU interval for group");
+ log::error("unsupported SDU interval for group");
group->PrintDebugState();
StopStream(group);
return;
@@ -2639,7 +2638,7 @@
if (confs.size() == 0 || !validate_transport_latency ||
!validate_max_sdu_size) {
- LOG_ERROR("Invalid configuration or latency or sdu size");
+ log::error("Invalid configuration or latency or sdu size");
group->PrintDebugState();
StopStream(group);
return;
@@ -2650,8 +2649,8 @@
value);
WriteToControlPoint(leAudioDevice, value);
- LOG_INFO("group_id: %d, %s", leAudioDevice->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group_id: {}, {}", leAudioDevice->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
log_history_->AddLogHistory(kLogControlPointCmd, group->group_id_,
leAudioDevice->address_, msg_stream.str(),
extra_stream.str());
@@ -2675,15 +2674,15 @@
/* Request server to update ASEs with new metadata */
for (struct ase* ase = leAudioDevice->GetFirstActiveAse(); ase != nullptr;
ase = leAudioDevice->GetNextActiveAse(ase)) {
- LOG_DEBUG("device: %s, ase_id: %d, cis_id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- ase->cis_id, ToString(ase->state).c_str());
+ log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ ase->cis_id, ToString(ase->state));
if (ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING &&
ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
/* This might happen when update metadata happens on late connect */
- LOG_DEBUG(
- "Metadata for ase_id %d cannot be updated due to invalid ase state "
+ log::debug(
+ "Metadata for ase_id {} cannot be updated due to invalid ase state "
"- see log above",
ase->id);
continue;
@@ -2736,8 +2735,8 @@
confs, value);
WriteToControlPoint(leAudioDevice, value);
- LOG_INFO("group_id: %d, %s", leAudioDevice->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group_id: {}, {}", leAudioDevice->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_,
leAudioDevice->address_, msg_stream.str(),
@@ -2766,8 +2765,8 @@
PrepareAseCtpAudioReceiverStartReady(ids, value);
WriteToControlPoint(leAudioDevice, value);
- LOG_INFO("group_id: %d, %s", leAudioDevice->group_id_,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::info("group_id: {}, {}", leAudioDevice->group_id_,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_,
leAudioDevice->address_, stream.str());
}
@@ -2778,7 +2777,7 @@
struct ase* ase, LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice) {
if (!group) {
- LOG(ERROR) << __func__ << ", leAudioDevice doesn't belong to any group";
+ log::error("leAudioDevice doesn't belong to any group");
return;
}
@@ -2829,10 +2828,9 @@
/* Enable/Switch Content */
break;
default:
- LOG(ERROR) << __func__ << ", invalid state transition, from: "
- << static_cast<int>(ase->state) << ", to: "
- << static_cast<int>(
- AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING);
+ log::error("invalid state transition, from: {}, to: {}",
+ static_cast<int>(ase->state),
+ static_cast<int>(AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING));
StopStream(group);
break;
}
@@ -2843,15 +2841,15 @@
struct ase* ase, uint8_t* data, uint16_t len, LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice) {
if (!group) {
- LOG(ERROR) << __func__ << ", leAudioDevice doesn't belong to any group";
+ log::error("leAudioDevice doesn't belong to any group");
return;
}
switch (ase->state) {
case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED:
- LOG_ERROR(
- "%s, ase_id: %d, moving from QoS Configured to Streaming is "
+ log::error(
+ "{}, ase_id: {}, moving from QoS Configured to Streaming is "
"impossible.",
ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id);
group->PrintDebugState();
@@ -2873,9 +2871,9 @@
if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
/* We are here because of the reconnection of the single device */
- LOG_INFO("%s, Ase id: %d, ase state: %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
- bluetooth::common::ToString(ase->state).c_str());
+ log::info("{}, Ase id: {}, ase state: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_), ase->id,
+ bluetooth::common::ToString(ase->state));
cancel_watchdog_if_needed(group->group_id_);
state_machine_callbacks_->StatusReportCb(
group->group_id_, GroupStreamStatus::STREAMING);
@@ -2884,7 +2882,7 @@
/* Not all CISes establish events will came */
if (!group->IsGroupStreamReady()) {
- LOG_INFO("CISes are not yet ready, wait for it.");
+ log::info("CISes are not yet ready, wait for it.");
group->SetNotifyStreamingWhenCisesAreReadyFlag(true);
return;
}
@@ -2902,9 +2900,9 @@
return;
}
- LOG_ERROR(", invalid state transition, from: %s, to: %s",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {}, to: {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
break;
@@ -2928,10 +2926,10 @@
break;
}
default:
- LOG(ERROR) << __func__ << ", invalid state transition, from: "
- << static_cast<int>(ase->state) << ", to: "
- << static_cast<int>(
- AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+ log::error(
+ "invalid state transition, from: {}, to: {}",
+ static_cast<int>(ase->state),
+ static_cast<int>(AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING));
StopStream(group);
break;
}
@@ -2958,16 +2956,16 @@
struct ase* ase, LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice) {
if (!group) {
- LOG(ERROR) << __func__ << ", leAudioDevice doesn't belong to any group";
+ log::error("leAudioDevice doesn't belong to any group");
return;
}
if (ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink) {
/* Sink ASE state machine does not have Disabling state */
- LOG_ERROR(", invalid state transition, from: %s , to: %s ",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {} , to: {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
return;
}
@@ -2993,10 +2991,10 @@
break;
default:
- LOG(ERROR) << __func__ << ", invalid state transition, from: "
- << static_cast<int>(ase->state) << ", to: "
- << static_cast<int>(
- AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING);
+ log::error(
+ "invalid state transition, from: {}, to: {}",
+ static_cast<int>(ase->state),
+ static_cast<int>(AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING));
StopStream(group);
break;
}
@@ -3004,25 +3002,26 @@
void DisconnectCisIfNeeded(LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice, struct ase* ase) {
- LOG_DEBUG(
- "Group id: %d, %s, ase id: %d, cis_handle: 0x%04x, direction: %s, "
- "data_path_state: %s, cis_state: %s",
+ log::debug(
+ "Group id: {}, {}, ase id: {}, cis_handle: 0x{:04x}, direction: {}, "
+ "data_path_state: {}, cis_state: {}",
group->group_id_, ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
ase->id, ase->cis_conn_hdl,
ase->direction == bluetooth::le_audio::types::kLeAudioDirectionSink
? "sink"
: "source",
- bluetooth::common::ToString(ase->data_path_state).c_str(),
- bluetooth::common::ToString(ase->cis_state).c_str());
+ bluetooth::common::ToString(ase->data_path_state),
+ bluetooth::common::ToString(ase->cis_state));
auto bidirection_ase = leAudioDevice->GetAseToMatchBidirectionCis(ase);
if (bidirection_ase != nullptr &&
bidirection_ase->cis_state == CisState::CONNECTED &&
(bidirection_ase->state == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING ||
bidirection_ase->state == AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING)) {
- LOG_INFO("Still waiting for the bidirectional ase %d to be released (%s)",
- bidirection_ase->id,
- bluetooth::common::ToString(bidirection_ase->state).c_str());
+ log::info(
+ "Still waiting for the bidirectional ase {} to be released ({})",
+ bidirection_ase->id,
+ bluetooth::common::ToString(bidirection_ase->state));
return;
}
@@ -3039,7 +3038,7 @@
struct ase* ase, LeAudioDeviceGroup* group,
LeAudioDevice* leAudioDevice) {
if (!group) {
- LOG(ERROR) << __func__ << ", leAudioDevice doesn't belong to any group";
+ log::error("leAudioDevice doesn't belong to any group");
return;
}
@@ -3112,10 +3111,10 @@
break;
}
default:
- LOG(ERROR) << __func__ << ", invalid state transition, from: "
- << static_cast<int>(ase->state) << ", to: "
- << static_cast<int>(
- AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING);
+ log::error(
+ "invalid state transition, from: {}, to: {}",
+ static_cast<int>(ase->state),
+ static_cast<int>(AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING));
break;
}
}
@@ -3124,7 +3123,7 @@
if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING) {
/* Check if the group is ready to create stream. If not, keep waiting. */
if (!group->IsGroupReadyToCreateStream()) {
- LOG_DEBUG(
+ log::debug(
"Waiting for more ASEs to be in enabling or directly in streaming "
"state");
return;
@@ -3136,9 +3135,9 @@
/* If Target State is not streaming, then something is wrong. */
if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- LOG_ERROR(", invalid state transition, from: %s , to: %s ",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {} , to: {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
return;
}
@@ -3153,7 +3152,7 @@
/* Disable ASEs for next device in group. */
if (group->GetState() != AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING) {
if (!group->IsGroupReadyToSuspendStream()) {
- LOG_INFO("Waiting for all devices to be in disable state");
+ log::info("Waiting for all devices to be in disable state");
return;
}
group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING);
@@ -3173,9 +3172,9 @@
AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED) {
ReleaseDataPath(group);
} else {
- LOG_ERROR(", invalid state transition, from: %s , to: %s ",
- ToString(group->GetState()).c_str(),
- ToString(group->GetTargetState()).c_str());
+ log::error(", invalid state transition, from: {} , to: {}",
+ ToString(group->GetState()),
+ ToString(group->GetTargetState()));
StopStream(group);
}
}
@@ -3213,7 +3212,7 @@
namespace bluetooth::le_audio {
void LeAudioGroupStateMachine::Initialize(Callbacks* state_machine_callbacks_) {
if (instance) {
- LOG(ERROR) << "Already initialized";
+ log::error("Already initialized");
return;
}
diff --git a/system/bta/le_audio/state_machine_test.cc b/system/bta/le_audio/state_machine_test.cc
index 5d5728b..b39f1fd 100644
--- a/system/bta/le_audio/state_machine_test.cc
+++ b/system/bta/le_audio/state_machine_test.cc
@@ -17,6 +17,7 @@
#include "state_machine.h"
+#include <bluetooth/log.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -33,7 +34,6 @@
#include "internal_include/stack_config.h"
#include "le_audio_set_configuration_provider.h"
#include "mock_codec_manager.h"
-#include "mock_controller.h"
#include "mock_csis_client.h"
#include "stack/include/bt_types.h"
#include "test/common/mock_functions.h"
@@ -289,8 +289,8 @@
ON_CALL(mock_callbacks_, StatusReportCb(_, _))
.WillByDefault(Invoke(
[](int group_id, bluetooth::le_audio::GroupStreamStatus status) {
- LOG_DEBUG(" [Testing] StatusReportCb: group id: %d, status: %d",
- group_id, status);
+ log::debug("[Testing] StatusReportCb: group id: {}, status: {}",
+ group_id, status);
}));
MockCsisClient::SetMockInstanceForTesting(&mock_csis_client_module_);
@@ -1213,8 +1213,8 @@
ase_p += 3;
if (caching) {
- LOG(INFO) << __func__ << " Device: "
- << ADDRESS_TO_LOGGABLE_STR(device->address_);
+ log::info("Device: {}",
+ ADDRESS_TO_LOGGABLE_STR(device->address_));
if (cached_ase_to_cis_id_map_.count(device->address_) > 0) {
auto ase_list = cached_ase_to_cis_id_map_.at(device->address_);
if (ase_list.count(ase_id) > 0) {
@@ -1502,8 +1502,8 @@
this](LeAudioDevice* device, std::vector<uint8_t> value,
GATT_WRITE_OP_CB cb, void* cb_data) {
if (dev != nullptr && device != dev) {
- LOG_INFO("Do nothing for %s",
- ADDRESS_TO_LOGGABLE_CSTR(dev->address_));
+ log::info("Do nothing for {}",
+ ADDRESS_TO_LOGGABLE_CSTR(dev->address_));
return;
}
@@ -4246,8 +4246,8 @@
LeAudioGroupStateMachine::Get()->StopStream(group);
for (auto& ase : firstDevice->ases_) {
- LOG_DEBUG("%s , %d, %s", ADDRESS_TO_LOGGABLE_CSTR(firstDevice->address_),
- ase.id, bluetooth::common::ToString(ase.state).c_str());
+ log::debug("{} , {}, {}", ADDRESS_TO_LOGGABLE_CSTR(firstDevice->address_),
+ ase.id, bluetooth::common::ToString(ase.state));
ASSERT_EQ(ase.state, types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING);
// Simulate autonomus configured state.
InjectAseStateNotification(&ase, firstDevice, group,
@@ -4265,8 +4265,8 @@
bluetooth::le_audio::GroupStreamStatus::CONFIGURED_AUTONOMOUS))
.Times(1);
for (auto& ase : secondDevice->ases_) {
- LOG_DEBUG("%s , %d, %s", ADDRESS_TO_LOGGABLE_CSTR(firstDevice->address_),
- ase.id, bluetooth::common::ToString(ase.state).c_str());
+ log::debug("{} , {}, {}", ADDRESS_TO_LOGGABLE_CSTR(firstDevice->address_),
+ ase.id, bluetooth::common::ToString(ase.state));
ASSERT_EQ(ase.state, types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING);
// Simulate autonomus configured state.
InjectAseStateNotification(&ase, secondDevice, group,
@@ -5099,8 +5099,8 @@
if (ase.id == bluetooth::le_audio::types::ase::kAseIdInvalid) {
continue;
}
- LOG_ERROR("ID : %d, status %s", ase.id,
- bluetooth::common::ToString(ase.state).c_str());
+ log::error("ID : {}, status {}", ase.id,
+ bluetooth::common::ToString(ase.state));
num_of_notifications++;
InjectAseStateNotification(&ase, lastDevice, group,
ascs::kAseStateCodecConfigured,
diff --git a/system/bta/le_audio/storage_helper.cc b/system/bta/le_audio/storage_helper.cc
index 2f23347..45483ce 100644
--- a/system/bta/le_audio/storage_helper.cc
+++ b/system/bta/le_audio/storage_helper.cc
@@ -18,6 +18,8 @@
#include "storage_helper.h"
+#include <bluetooth/log.h>
+
#include "client_parser.h"
#include "common/strings.h"
#include "le_audio_types.h"
@@ -69,7 +71,7 @@
std::vector<uint8_t>& out) {
auto num_of_pacs = pacs.size();
if (num_of_pacs == 0 || (num_of_pacs > std::numeric_limits<uint8_t>::max())) {
- LOG_WARN("No pacs available");
+ log::warn("No pacs available");
return false;
}
@@ -102,14 +104,14 @@
UINT16_TO_STREAM(ptr, ccc_handle);
UINT8_TO_STREAM(ptr, pac_recs.size());
- LOG_VERBOSE(" Handle: 0x%04x, ccc handle: 0x%04x, pac count: %d", handle,
- ccc_handle, static_cast<int>(pac_recs.size()));
+ log::verbose("Handle: 0x{:04x}, ccc handle: 0x{:04x}, pac count: {}",
+ handle, ccc_handle, static_cast<int>(pac_recs.size()));
for (const auto& pac : pac_recs) {
/* Pac len */
auto pac_len = LEAUDIO_PACS_ENTRY_SZ + pac.codec_spec_caps_raw.size() +
pac.metadata.size();
- LOG_VERBOSE("Pac size %d", static_cast<int>(pac_len));
+ log::verbose("Pac size {}", static_cast<int>(pac_len));
UINT8_TO_STREAM(ptr, pac_len - 1 /* Minus size */);
/* Codec ID*/
@@ -118,8 +120,8 @@
UINT16_TO_STREAM(ptr, pac.codec_id.vendor_codec_id);
/* Codec caps */
- LOG_VERBOSE("Codec capability size %d",
- static_cast<int>(pac.codec_spec_caps_raw.size()));
+ log::verbose("Codec capability size {}",
+ static_cast<int>(pac.codec_spec_caps_raw.size()));
UINT8_TO_STREAM(ptr, pac.codec_spec_caps_raw.size());
if (pac.codec_spec_caps_raw.size() > 0) {
ARRAY_TO_STREAM(ptr, pac.codec_spec_caps_raw.data(),
@@ -127,7 +129,7 @@
}
/* Metadata */
- LOG_VERBOSE("Metadata size %d", static_cast<int>(pac.metadata.size()));
+ log::verbose("Metadata size {}", static_cast<int>(pac.metadata.size()));
UINT8_TO_STREAM(ptr, pac.metadata.size());
if (pac.metadata.size() > 0) {
ARRAY_TO_STREAM(ptr, pac.metadata.data(), (int)pac.metadata.size());
@@ -140,12 +142,12 @@
bool SerializeSinkPacs(const bluetooth::le_audio::LeAudioDevice* leAudioDevice,
std::vector<uint8_t>& out) {
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
- LOG_VERBOSE("Device %s, num of PAC characteristics: %d",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- static_cast<int>(leAudioDevice->snk_pacs_.size()));
+ log::verbose("Device {}, num of PAC characteristics: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ static_cast<int>(leAudioDevice->snk_pacs_.size()));
return serializePacs(leAudioDevice->snk_pacs_, out);
}
@@ -153,12 +155,12 @@
const bluetooth::le_audio::LeAudioDevice* leAudioDevice,
std::vector<uint8_t>& out) {
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
- LOG_VERBOSE("Device %s, num of PAC characteristics: %d",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- static_cast<int>(leAudioDevice->src_pacs_.size()));
+ log::verbose("Device {}, num of PAC characteristics: {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ static_cast<int>(leAudioDevice->src_pacs_.size()));
return serializePacs(leAudioDevice->src_pacs_, out);
}
@@ -167,7 +169,7 @@
const std::vector<uint8_t>& in) {
if (in.size() <
LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_PACS_ENTRY_SZ) {
- LOG_WARN("There is not single PACS stored");
+ log::warn("There is not single PACS stored");
return false;
}
@@ -177,9 +179,9 @@
STREAM_TO_UINT8(magic, ptr);
if (magic != LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC) {
- LOG_ERROR("Invalid magic (%d!=%d) for device %s", magic,
- LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Invalid magic ({}!={}) for device {}", magic,
+ LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -188,8 +190,8 @@
if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ +
(num_of_pacs_chars * LEAUDIO_PACS_ENTRY_SZ)) {
- LOG_ERROR("Invalid persistent storage data for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Invalid persistent storage data for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -202,8 +204,8 @@
STREAM_TO_UINT16(hdl_pair.ccc_hdl, ptr);
STREAM_TO_UINT8(pac_count, ptr);
- LOG_VERBOSE(" Handle: 0x%04x, ccc handle: 0x%04x, pac_count: %d",
- hdl_pair.val_hdl, hdl_pair.ccc_hdl, pac_count);
+ log::verbose("Handle: 0x{:04x}, ccc handle: 0x{:04x}, pac_count: {}",
+ hdl_pair.val_hdl, hdl_pair.ccc_hdl, pac_count);
pacs_db.push_back(std::make_tuple(
hdl_pair,
@@ -218,10 +220,10 @@
while (pac_count--) {
uint8_t pac_len;
STREAM_TO_UINT8(pac_len, ptr);
- LOG_VERBOSE("Pac len %d", pac_len);
+ log::verbose("Pac len {}", pac_len);
if (client_parser::pacs::ParseSinglePac(pac_recs, pac_len, ptr) < 0) {
- LOG_ERROR("Cannot parse stored PACs (impossible)");
+ log::error("Cannot parse stored PACs (impossible)");
return false;
}
ptr += pac_len;
@@ -234,9 +236,9 @@
bool DeserializeSinkPacs(bluetooth::le_audio::LeAudioDevice* leAudioDevice,
const std::vector<uint8_t>& in) {
- LOG_VERBOSE("");
+ log::verbose("");
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
return deserializePacs(leAudioDevice, leAudioDevice->snk_pacs_, in);
@@ -244,9 +246,9 @@
bool DeserializeSourcePacs(bluetooth::le_audio::LeAudioDevice* leAudioDevice,
const std::vector<uint8_t>& in) {
- LOG_VERBOSE("");
+ log::verbose("");
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
return deserializePacs(leAudioDevice, leAudioDevice->src_pacs_, in);
@@ -255,18 +257,18 @@
bool SerializeAses(const bluetooth::le_audio::LeAudioDevice* leAudioDevice,
std::vector<uint8_t>& out) {
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
auto num_of_ases = leAudioDevice->ases_.size();
- LOG_DEBUG(" device: %s, number of ases %d",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
- static_cast<int>(num_of_ases));
+ log::debug("device: {}, number of ases {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_),
+ static_cast<int>(num_of_ases));
if (num_of_ases == 0 || (num_of_ases > std::numeric_limits<uint8_t>::max())) {
- LOG_WARN("No ases available for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("No ases available for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -282,8 +284,9 @@
/* pacs entries */
for (const auto& ase : leAudioDevice->ases_) {
- LOG_VERBOSE(
- "Storing ASE ID: %d, direction %s, handle 0x%04x, ccc_handle 0x%04x",
+ log::verbose(
+ "Storing ASE ID: {}, direction {}, handle 0x{:04x}, ccc_handle "
+ "0x{:04x}",
ase.id,
ase.direction == bluetooth::le_audio::types::kLeAudioDirectionSink
? "sink "
@@ -302,14 +305,14 @@
bool DeserializeAses(bluetooth::le_audio::LeAudioDevice* leAudioDevice,
const std::vector<uint8_t>& in) {
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
if (in.size() <
LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_ASES_ENTRY_SZ) {
- LOG_WARN("There is not single ASE stored for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("There is not single ASE stored for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -319,8 +322,8 @@
STREAM_TO_UINT8(magic, ptr);
if (magic != LEAUDIO_ASE_STORAGE_CURRENT_LAYOUT_MAGIC) {
- LOG_ERROR("Invalid magic (%d!=%d", magic,
- LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC);
+ log::error("Invalid magic ({}!={}", magic,
+ LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC);
return false;
}
@@ -329,13 +332,13 @@
if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ +
(num_of_ases * LEAUDIO_ASES_ENTRY_SZ)) {
- LOG_ERROR("Invalid persistent storage data for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Invalid persistent storage data for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
- LOG_DEBUG("Loading %d Ases for device %s", num_of_ases,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::debug("Loading {} Ases for device {}", num_of_ases,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
/* sets entries */
while (num_of_ases--) {
uint16_t handle;
@@ -349,8 +352,9 @@
STREAM_TO_UINT8(direction, ptr);
leAudioDevice->ases_.emplace_back(handle, ccc_handle, direction, ase_id);
- LOG_VERBOSE(
- " Loading ASE ID: %d, direction %s, handle 0x%04x, ccc_handle 0x%04x",
+ log::verbose(
+ "Loading ASE ID: {}, direction {}, handle 0x{:04x}, ccc_handle "
+ "0x{:04x}",
ase_id,
direction == bluetooth::le_audio::types::kLeAudioDirectionSink
? "sink "
@@ -364,7 +368,7 @@
bool SerializeHandles(const LeAudioDevice* leAudioDevice,
std::vector<uint8_t>& out) {
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
@@ -377,8 +381,8 @@
if (leAudioDevice->ctp_hdls_.val_hdl == 0 ||
leAudioDevice->ctp_hdls_.ccc_hdl == 0) {
- LOG_WARN("Invalid control point handles for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("Invalid control point handles for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -405,13 +409,13 @@
bool DeserializeHandles(LeAudioDevice* leAudioDevice,
const std::vector<uint8_t>& in) {
if (leAudioDevice == nullptr) {
- LOG_WARN(" Skipping unknown device");
+ log::warn("Skipping unknown device");
return false;
}
if (in.size() != LEAUDIO_STORAGE_HANDLES_ENTRIES_SZ) {
- LOG_WARN("There is not single ASE stored for device %s",
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::warn("There is not single ASE stored for device {}",
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
@@ -421,52 +425,51 @@
STREAM_TO_UINT8(magic, ptr);
if (magic != LEAUDIO_HANDLES_STORAGE_CURRENT_LAYOUT_MAGIC) {
- LOG_ERROR("Invalid magic (%d!=%d) for device %s", magic,
- LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC,
- ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
+ log::error("Invalid magic ({}!={}) for device {}", magic,
+ LEAUDIO_PACS_STORAGE_CURRENT_LAYOUT_MAGIC,
+ ADDRESS_TO_LOGGABLE_CSTR(leAudioDevice->address_));
return false;
}
STREAM_TO_UINT16(leAudioDevice->ctp_hdls_.val_hdl, ptr);
STREAM_TO_UINT16(leAudioDevice->ctp_hdls_.ccc_hdl, ptr);
- LOG_VERBOSE("ctp.val_hdl: 0x%04x, ctp.ccc_hdl: 0x%04x",
- leAudioDevice->ctp_hdls_.val_hdl,
- leAudioDevice->ctp_hdls_.ccc_hdl);
+ log::verbose("ctp.val_hdl: 0x{:04x}, ctp.ccc_hdl: 0x{:04x}",
+ leAudioDevice->ctp_hdls_.val_hdl,
+ leAudioDevice->ctp_hdls_.ccc_hdl);
STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.val_hdl, ptr);
STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, ptr);
- LOG_VERBOSE(
- "snk_audio_locations_hdls_.val_hdl: 0x%04x,"
- "snk_audio_locations_hdls_.ccc_hdl: 0x%04x",
+ log::verbose(
+ "snk_audio_locations_hdls_.val_hdl: "
+ "0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}",
leAudioDevice->snk_audio_locations_hdls_.val_hdl,
leAudioDevice->snk_audio_locations_hdls_.ccc_hdl);
STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.val_hdl, ptr);
STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.ccc_hdl, ptr);
- LOG_VERBOSE(
- "src_audio_locations_hdls_.val_hdl: 0x%04x,"
- "src_audio_locations_hdls_.ccc_hdl: 0x%04x",
+ log::verbose(
+ "src_audio_locations_hdls_.val_hdl: "
+ "0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}",
leAudioDevice->src_audio_locations_hdls_.val_hdl,
leAudioDevice->src_audio_locations_hdls_.ccc_hdl);
STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.val_hdl, ptr);
STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.ccc_hdl, ptr);
- LOG_VERBOSE(
- "audio_supp_cont_hdls_.val_hdl: 0x%04x,"
- "audio_supp_cont_hdls_.ccc_hdl: 0x%04x",
+ log::verbose(
+ "audio_supp_cont_hdls_.val_hdl: 0x{:04x},audio_supp_cont_hdls_.ccc_hdl: "
+ "0x{:04x}",
leAudioDevice->audio_supp_cont_hdls_.val_hdl,
leAudioDevice->audio_supp_cont_hdls_.ccc_hdl);
STREAM_TO_UINT16(leAudioDevice->audio_avail_hdls_.val_hdl, ptr);
STREAM_TO_UINT16(leAudioDevice->audio_avail_hdls_.ccc_hdl, ptr);
- LOG_VERBOSE(
- "audio_avail_hdls_.val_hdl: 0x%04x,"
- "audio_avail_hdls_.ccc_hdl: 0x%04x",
+ log::verbose(
+ "audio_avail_hdls_.val_hdl: 0x{:04x},audio_avail_hdls_.ccc_hdl: 0x{:04x}",
leAudioDevice->audio_avail_hdls_.val_hdl,
leAudioDevice->audio_avail_hdls_.ccc_hdl);
STREAM_TO_UINT16(leAudioDevice->tmap_role_hdl_, ptr);
- LOG_VERBOSE("tmap_role_hdl_: 0x%04x", leAudioDevice->tmap_role_hdl_);
+ log::verbose("tmap_role_hdl_: 0x{:04x}", leAudioDevice->tmap_role_hdl_);
leAudioDevice->known_service_handles_ = true;
return true;
diff --git a/system/bta/ras/ras_server.cc b/system/bta/ras/ras_server.cc
index 1ed63cf..a30e956 100644
--- a/system/bta/ras/ras_server.cc
+++ b/system/bta/ras/ras_server.cc
@@ -443,7 +443,7 @@
SendResponseCode(ResponseCodeValue::OP_CODE_NOT_SUPPORTED, tracker);
} break;
default:
- LOG_WARN("Unknown opcode:0x%02x", (uint16_t)command.opcode_);
+ log::warn("Unknown opcode:0x{:02x}", (uint16_t)command.opcode_);
SendResponseCode(ResponseCodeValue::OP_CODE_NOT_SUPPORTED, tracker);
}
}
diff --git a/system/bta/ras/ras_utils.cc b/system/bta/ras/ras_utils.cc
index 59a7d94..e98f872 100644
--- a/system/bta/ras/ras_utils.cc
+++ b/system/bta/ras/ras_utils.cc
@@ -59,7 +59,7 @@
const uint8_t* value, uint16_t len) {
// Check for minimum expected length
if (len != kControlPointCommandSize) {
- LOG_WARN("Invalid len %d", len);
+ log::warn("Invalid len {}", len);
return false;
}
command->opcode_ = static_cast<Opcode>(value[0]);
diff --git a/system/bta/test/bta_disc_test.cc b/system/bta/test/bta_disc_test.cc
index 7047356..d1ab38f 100644
--- a/system/bta/test/bta_disc_test.cc
+++ b/system/bta/test/bta_disc_test.cc
@@ -49,7 +49,7 @@
void bta_dm_discover_next_device();
void bta_dm_execute_queued_request();
void bta_dm_find_services(const RawAddress& bd_addr);
-void bta_dm_inq_cmpl(uint8_t num);
+void bta_dm_inq_cmpl();
void bta_dm_inq_cmpl_cb(void* p_result);
void bta_dm_observe_cmpl_cb(void* p_result);
void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, const uint8_t* p_eir,
@@ -136,10 +136,8 @@
}
TEST_F(BtaDiscTest, bta_dm_inq_cmpl) {
- bluetooth::legacy::testing::bta_dm_inq_cmpl(0);
- bluetooth::legacy::testing::bta_dm_inq_cmpl(1);
- bluetooth::legacy::testing::bta_dm_inq_cmpl(2);
- bluetooth::legacy::testing::bta_dm_inq_cmpl(255);
+ bluetooth::legacy::testing::bta_dm_inq_cmpl();
+ bluetooth::legacy::testing::bta_dm_inq_cmpl();
}
TEST_F(BtaDiscTest, bta_dm_inq_cmpl_cb) {
diff --git a/system/bta/test/bta_dm_test.cc b/system/bta/test/bta_dm_test.cc
index d41d59c..95090d1 100644
--- a/system/bta/test/bta_dm_test.cc
+++ b/system/bta/test/bta_dm_test.cc
@@ -383,12 +383,10 @@
tBTM_REMOTE_DEV_NAME name = {
.status = BTM_SUCCESS,
.bd_addr = kRawAddress,
- .length = static_cast<uint16_t>(strlen(kRemoteName)),
.remote_bd_name = {},
.hci_status = HCI_SUCCESS,
};
- strlcpy(reinterpret_cast<char*>(&name.remote_bd_name), kRemoteName,
- strlen(kRemoteName));
+ bd_name_from_char_pointer(name.remote_bd_name, kRemoteName);
mock_btm_client_interface.security.BTM_SecDeleteRmtNameNotifyCallback =
[](tBTM_RMT_NAME_CALLBACK*) -> bool {
@@ -415,12 +413,10 @@
tBTM_REMOTE_DEV_NAME name = {
.status = BTM_SUCCESS,
.bd_addr = kRawAddress2,
- .length = static_cast<uint16_t>(strlen(kRemoteName)),
.remote_bd_name = {},
.hci_status = HCI_SUCCESS,
};
- strlcpy(reinterpret_cast<char*>(&name.remote_bd_name), kRemoteName,
- strlen(kRemoteName));
+ bd_name_from_char_pointer(name.remote_bd_name, kRemoteName);
mock_btm_client_interface.security.BTM_SecDeleteRmtNameNotifyCallback =
[](tBTM_RMT_NAME_CALLBACK*) -> bool {
@@ -443,12 +439,10 @@
tBTM_REMOTE_DEV_NAME name = {
.status = BTM_SUCCESS,
.bd_addr = RawAddress::kEmpty,
- .length = static_cast<uint16_t>(strlen(kRemoteName)),
.remote_bd_name = {},
.hci_status = HCI_ERR_CONNECTION_EXISTS,
};
- strlcpy(reinterpret_cast<char*>(&name.remote_bd_name), kRemoteName,
- strlen(kRemoteName));
+ bd_name_from_char_pointer(name.remote_bd_name, kRemoteName);
mock_btm_client_interface.security.BTM_SecDeleteRmtNameNotifyCallback =
[](tBTM_RMT_NAME_CALLBACK*) -> bool {
diff --git a/system/bta/test/bta_hf_client_security_test.cc b/system/bta/test/bta_hf_client_security_test.cc
index 464d26a..a2ee5d2 100644
--- a/system/bta/test/bta_hf_client_security_test.cc
+++ b/system/bta/test/bta_hf_client_security_test.cc
@@ -22,7 +22,6 @@
#include "bta/include/bta_hf_client_api.h"
#include "common/message_loop_thread.h"
#include "device/include/esco_parameters.h"
-#include "test/mock/mock_device_controller.h"
#include "types/raw_address.h"
namespace base {
diff --git a/system/bta/test/common/mock_controller.cc b/system/bta/test/common/mock_controller.cc
deleted file mode 100644
index 3e2353f..0000000
--- a/system/bta/test/common/mock_controller.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2021 HIMSA II K/S - www.himsa.dk.
- * Represented by EHIMA - www.ehima.com
- *
- * 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 "mock_controller.h"
-
-#include "device/include/controller.h"
-
-static controller::MockControllerInterface* controller_interface = nullptr;
-
-void controller::SetMockControllerInterface(
- MockControllerInterface* interface) {
- controller_interface = interface;
-}
-
-const controller_t* controller_get_interface() {
- static controller_t* controller_instance = new controller_t();
-
- return controller_instance;
-}
diff --git a/system/bta/test/common/mock_controller.h b/system/bta/test/common/mock_controller.h
deleted file mode 100644
index befa006..0000000
--- a/system/bta/test/common/mock_controller.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright 2021 HIMSA II K/S - www.himsa.dk.
- * Represented by EHIMA - www.ehima.com
- *
- * 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/functional/callback.h>
-#include <gmock/gmock.h>
-
-namespace controller {
-class ControllerInterface {
- public:
- virtual uint8_t GetIsoBufferCount(void) = 0;
- virtual uint16_t GetIsoDataSize(void) = 0;
-
- virtual ~ControllerInterface() = default;
-};
-
-class MockControllerInterface : public ControllerInterface {
- public:
- MOCK_METHOD((uint8_t), GetIsoBufferCount, (), (override));
- MOCK_METHOD((uint16_t), GetIsoDataSize, (), (override));
-};
-
-void SetMockControllerInterface(
- MockControllerInterface* mock_controller_interface);
-} // namespace controller
diff --git a/system/btif/co/bta_hh_co.cc b/system/btif/co/bta_hh_co.cc
index f7f1976..a19be9a 100644
--- a/system/btif/co/bta_hh_co.cc
+++ b/system/btif/co/bta_hh_co.cc
@@ -33,9 +33,9 @@
#include "bta_hh_api.h"
#include "btif_hh.h"
-#include "device/include/controller.h"
+#include "hci/controller_interface.h"
#include "include/check.h"
-#include "os/log.h"
+#include "main/shim/entry.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
#include "osi/include/osi.h"
@@ -609,10 +609,10 @@
// Write controller address to phys field to correlate the hid device with a
// specific bluetooth controller.
- const controller_t* controller = controller_get_interface();
+ auto controller = bluetooth::shim::GetController();
// TODO (b/258090765) fix: ToString -> ToColonSepHexString
snprintf((char*)ev.u.create.phys, sizeof(ev.u.create.phys), "%s",
- controller->get_address()->ToString().c_str());
+ controller->GetMacAddress().ToString().c_str());
ev.u.create.rd_size = dscp_len;
ev.u.create.rd_data = p_dscp;
diff --git a/system/btif/include/btif_jni_task.h b/system/btif/include/btif_jni_task.h
index e2771db..3b3f17d 100644
--- a/system/btif/include/btif_jni_task.h
+++ b/system/btif/include/btif_jni_task.h
@@ -17,6 +17,7 @@
#pragma once
#include "btif/include/btif_common.h"
+#include "common/postable_context.h"
#include "include/hardware/bluetooth.h"
void jni_thread_startup();
@@ -55,3 +56,5 @@
bool is_on_jni_thread();
void post_on_bt_jni(BtJniClosure closure);
+
+bluetooth::common::PostableContext* get_jni();
diff --git a/system/btif/include/btif_sock_l2cap.h b/system/btif/include/btif_sock_l2cap.h
index d43d837..f353c7b 100644
--- a/system/btif/include/btif_sock_l2cap.h
+++ b/system/btif/include/btif_sock_l2cap.h
@@ -19,5 +19,7 @@
void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id);
void on_l2cap_psm_assigned(int id, int psm);
bt_status_t btsock_l2cap_disconnect(const RawAddress* bd_addr);
+bt_status_t btsock_l2cap_get_l2cap_local_cid(Uuid& conn_uuid, uint16_t* cid);
+bt_status_t btsock_l2cap_get_l2cap_remote_cid(Uuid& conn_uuid, uint16_t* cid);
#endif
diff --git a/system/btif/src/btif_core.cc b/system/btif/src/btif_core.cc
index a7bc08c..4b4a5d2 100644
--- a/system/btif/src/btif_core.cc
+++ b/system/btif/src/btif_core.cc
@@ -50,12 +50,12 @@
#include "btif/include/core_callbacks.h"
#include "btif/include/stack_manager_t.h"
#include "common/message_loop_thread.h"
-#include "device/include/controller.h"
#include "device/include/device_iot_config.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/future.h"
@@ -179,7 +179,8 @@
void btif_enable_bluetooth_evt() {
/* Fetch the local BD ADDR */
- RawAddress local_bd_addr = *controller_get_interface()->get_address();
+ RawAddress local_bd_addr = bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress());
std::string bdstr = local_bd_addr.ToString();
@@ -501,11 +502,10 @@
local_le_features.debug_logging_supported =
cmn_vsc_cb.debug_logging_supported > 0;
auto controller = bluetooth::shim::GetController();
- auto old_controller = controller_get_interface();
if (controller->SupportsBleExtendedAdvertising()) {
local_le_features.max_adv_instance =
- old_controller->get_ble_number_of_supported_advertising_sets();
+ controller->GetLeNumberOfSupportedAdverisingSets();
}
local_le_features.le_2m_phy_supported = controller->SupportsBle2mPhy();
local_le_features.le_coded_phy_supported =
@@ -515,7 +515,7 @@
local_le_features.le_periodic_advertising_supported =
controller->SupportsBlePeriodicAdvertising();
local_le_features.le_maximum_advertising_data_length =
- old_controller->get_ble_maximum_advertising_data_length();
+ controller->GetLeMaximumAdvertisingDataLength();
local_le_features.dynamic_audio_buffer_supported =
cmn_vsc_cb.dynamic_audio_buffer_support;
diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc
index a7f34ab..c136ccc 100644
--- a/system/btif/src/btif_dm.cc
+++ b/system/btif/src/btif_dm.cc
@@ -54,6 +54,7 @@
#include "advertise_data_parser.h"
#include "bt_dev_class.h"
+#include "bt_name.h"
#include "bta/dm/bta_dm_disc.h"
#include "bta/include/bta_api.h"
#include "btif/include/stack_manager_t.h"
@@ -68,7 +69,6 @@
#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 "hci/controller_interface.h"
#include "hci/le_rand_callback.h"
@@ -1011,8 +1011,7 @@
(tBT_DEVICE_TYPE)dev_type);
const RawAddress& bd_addr = p_pin_req->bd_addr;
- memcpy(bd_name.name, p_pin_req->bd_name, BD_NAME_LEN);
- bd_name.name[BD_NAME_LEN] = '\0';
+ bd_name_copy(bd_name.name, p_pin_req->bd_name);
if (pairing_cb.state == BT_BOND_STATE_BONDING &&
bd_addr != pairing_cb.bd_addr) {
@@ -2149,7 +2148,7 @@
}
bt_property_t properties[] = {{
.type = BT_PROPERTY_BDNAME,
- .len = (int)strlen((char*)disc_res.bd_name),
+ .len = (int)strnlen((char*)disc_res.bd_name, BD_NAME_LEN),
.val = (void*)disc_res.bd_name,
}};
const bt_status_t status = btif_storage_set_remote_device_property(
@@ -3469,7 +3468,9 @@
start_oob_advertiser(transport, is_valid, c, r);
} else {
GetInterfaceToProfiles()->events->invoke_oob_data_request_cb(
- transport, is_valid, c, r, *controller_get_interface()->get_address(),
+ transport, is_valid, c, r,
+ bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress()),
0x00);
}
}
@@ -3585,8 +3586,7 @@
p_ssp_key_notif->bd_name, kDevClassEmpty,
(tBT_DEVICE_TYPE)dev_type);
bd_addr = p_ssp_key_notif->bd_addr;
- memcpy(bd_name.name, p_ssp_key_notif->bd_name, BD_NAME_LEN);
- bd_name.name[BD_NAME_LEN] = '\0';
+ bd_name_copy(bd_name.name, p_ssp_key_notif->bd_name);
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_ssp = false;
@@ -3840,8 +3840,7 @@
(tBT_DEVICE_TYPE)dev_type);
RawAddress bd_addr = p_ble_req->bd_addr;
- memcpy(bd_name.name, p_ble_req->bd_name, BD_NAME_LEN);
- bd_name.name[BD_NAME_LEN] = '\0';
+ bd_name_copy(bd_name.name, p_ble_req->bd_name);
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
@@ -3884,8 +3883,7 @@
(tBT_DEVICE_TYPE)dev_type);
RawAddress bd_addr = p_pin_req->bd_addr;
- memcpy(bd_name.name, p_pin_req->bd_name, BD_NAME_LEN);
- bd_name.name[BD_NAME_LEN] = '\0';
+ bd_name_copy(bd_name.name, p_pin_req->bd_name);
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_le_only = true;
@@ -3909,8 +3907,7 @@
RawAddress bd_addr = p_notif_req->bd_addr;
bt_bdname_t bd_name;
- memcpy(bd_name.name, p_notif_req->bd_name, BD_NAME_LEN);
- bd_name.name[BD_NAME_LEN] = '\0';
+ bd_name_copy(bd_name.name, p_notif_req->bd_name);
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_ssp = false;
diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc
index a25399f..c0eea9a 100644
--- a/system/btif/src/btif_hh.cc
+++ b/system/btif/src/btif_hh.cc
@@ -144,6 +144,7 @@
* Static functions
******************************************************************************/
+static void btif_hh_transport_select(tAclLinkSpec& link_spec);
/*******************************************************************************
* Externs
******************************************************************************/
@@ -514,12 +515,30 @@
return false;
}
-void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec,
+void btif_hh_load_bonded_dev(const tAclLinkSpec& link_spec_ref,
tBTA_HH_ATTR_MASK attr_mask, uint8_t sub_class,
uint8_t app_id, tBTA_HH_DEV_DSCP_INFO dscp_info,
bool reconnect_allowed) {
btif_hh_device_t* p_dev;
uint8_t i;
+ tAclLinkSpec link_spec = link_spec_ref;
+
+ if (IS_FLAG_ENABLED(allow_switching_hid_and_hogp) &&
+ link_spec.transport == BT_TRANSPORT_AUTO) {
+ log::warn("Resolving link spec {} transport to BREDR/LE",
+ link_spec.ToRedactedStringForLogging());
+ btif_hh_transport_select(link_spec);
+ reconnect_allowed = true;
+ btif_storage_set_hid_connection_policy(link_spec, reconnect_allowed);
+
+ // remove and re-write the hid info
+ btif_storage_remove_hid_info(link_spec);
+ btif_storage_add_hid_device_info(
+ link_spec, attr_mask, sub_class, app_id, dscp_info.vendor_id,
+ dscp_info.product_id, dscp_info.version, dscp_info.ctry_code,
+ dscp_info.ssr_max_latency, dscp_info.ssr_min_tout,
+ dscp_info.descriptor.dl_len, dscp_info.descriptor.dsc_list);
+ }
if (hh_add_device(link_spec, attr_mask)) {
BTA_HhAddDev(link_spec, attr_mask, sub_class, app_id, dscp_info);
diff --git a/system/btif/src/btif_jni_task.cc b/system/btif/src/btif_jni_task.cc
index 083515c..9be6e18 100644
--- a/system/btif/src/btif_jni_task.cc
+++ b/system/btif/src/btif_jni_task.cc
@@ -26,6 +26,7 @@
#include <utility>
#include "common/message_loop_thread.h"
+#include "common/postable_context.h"
#include "include/hardware/bluetooth.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_types.h"
@@ -124,3 +125,5 @@
std::move(closure))) ==
BT_STATUS_SUCCESS);
}
+
+bluetooth::common::PostableContext* get_jni() { return jni_thread.Postable(); }
diff --git a/system/btif/src/btif_pan.cc b/system/btif/src/btif_pan.cc
index b69d886..4bfe238 100644
--- a/system/btif/src/btif_pan.cc
+++ b/system/btif/src/btif_pan.cc
@@ -44,10 +44,12 @@
#include "btif/include/btif_common.h"
#include "btif/include/btif_pan_internal.h"
#include "btif/include/btif_sock_thread.h"
-#include "device/include/controller.h"
+#include "hci/controller_interface.h"
#include "include/check.h"
#include "include/hardware/bt_pan.h"
#include "internal_include/bt_target.h"
+#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/compat.h"
@@ -262,7 +264,7 @@
}
}
-static int tap_if_up(const char* devname, const RawAddress* addr) {
+static int tap_if_up(const char* devname, const RawAddress& addr) {
struct ifreq ifr;
int sk, err;
@@ -281,7 +283,7 @@
}
strlcpy(ifr.ifr_name, devname, IFNAMSIZ);
- memcpy(ifr.ifr_hwaddr.sa_data, addr->address, 6);
+ memcpy(ifr.ifr_hwaddr.sa_data, addr.address, 6);
/* The IEEE has specified that the most significant bit of the most
* significant byte is used to
@@ -380,7 +382,9 @@
close(fd);
return err;
}
- if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0) {
+ if (tap_if_up(TAP_IF_NAME,
+ bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress())) == 0) {
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return fd;
diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc
index d17aade..3ad2c64 100644
--- a/system/btif/src/btif_profile_storage.cc
+++ b/system/btif/src/btif_profile_storage.cc
@@ -148,7 +148,7 @@
}
if (link_spec.transport == BT_TRANSPORT_AUTO) {
- LOG_ERROR("Unexpected transport!");
+ log::error("Unexpected transport!");
return BT_STATUS_FAIL;
}
btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_DB_VERSION,
@@ -1233,7 +1233,7 @@
btif_config_set_int(bdstr, BTIF_STORAGE_KEY_HID_RECONNECT_ALLOWED,
reconnect_allowed);
} else {
- LOG_ERROR("Unexpected!");
+ log::error("Unexpected!");
}
return BT_STATUS_SUCCESS;
@@ -1258,7 +1258,7 @@
} else if (link_spec.transport == BT_TRANSPORT_BR_EDR) {
btif_config_get_int(bdstr, BTIF_STORAGE_KEY_HID_RECONNECT_ALLOWED, &value);
} else {
- LOG_ERROR("Un expected!");
+ log::error("Un expected!");
}
*reconnect_allowed = value ? true : false;
diff --git a/system/btif/src/btif_sock.cc b/system/btif/src/btif_sock.cc
index 8044786..7306cc4 100644
--- a/system/btif/src/btif_sock.cc
+++ b/system/btif/src/btif_sock.cc
@@ -62,15 +62,22 @@
static void btsock_signaled(int fd, int type, int flags, uint32_t user_id);
static bt_status_t btsock_disconnect_all(const RawAddress* bd_addr);
+static bt_status_t btsock_get_l2cap_local_cid(Uuid& conn_uuid, uint16_t* cid);
+static bt_status_t btsock_get_l2cap_remote_cid(Uuid& conn_uuid, uint16_t* cid);
static std::atomic_int thread_handle{-1};
static thread_t* thread;
const btsock_interface_t* btif_sock_get_interface(void) {
static btsock_interface_t interface = {
- sizeof(interface), btsock_listen,
- btsock_connect, btsock_request_max_tx_data_length,
- btsock_control_req, btsock_disconnect_all,
+ sizeof(interface),
+ btsock_listen,
+ btsock_connect,
+ btsock_request_max_tx_data_length,
+ btsock_control_req,
+ btsock_disconnect_all,
+ btsock_get_l2cap_local_cid,
+ btsock_get_l2cap_remote_cid,
};
return &interface;
@@ -289,3 +296,11 @@
}
return rfc_status;
}
+
+static bt_status_t btsock_get_l2cap_local_cid(Uuid& conn_uuid, uint16_t* cid) {
+ return btsock_l2cap_get_l2cap_local_cid(conn_uuid, cid);
+}
+
+static bt_status_t btsock_get_l2cap_remote_cid(Uuid& conn_uuid, uint16_t* cid) {
+ return btsock_l2cap_get_l2cap_remote_cid(conn_uuid, cid);
+}
diff --git a/system/btif/src/btif_sock_l2cap.cc b/system/btif/src/btif_sock_l2cap.cc
index a209e0e..395e4ff 100644
--- a/system/btif/src/btif_sock_l2cap.cc
+++ b/system/btif/src/btif_sock_l2cap.cc
@@ -79,6 +79,7 @@
int64_t rx_bytes;
uint16_t local_cid; // The local CID
uint16_t remote_cid; // The remote CID
+ Uuid conn_uuid; // The connection uuid
} l2cap_socket;
static void btsock_l2cap_server_listen(l2cap_socket* sock);
@@ -203,6 +204,20 @@
return sock;
}
+/* only call with std::mutex taken */
+static l2cap_socket* btsock_l2cap_find_by_conn_uuid_l(Uuid& conn_uuid) {
+ l2cap_socket* sock = socks;
+
+ while (sock) {
+ if (sock->conn_uuid == conn_uuid) {
+ return sock;
+ }
+ sock = sock->next;
+ }
+
+ return nullptr;
+}
+
static void btsock_l2cap_free_l(l2cap_socket* sock) {
uint8_t* buf;
l2cap_socket* t = socks;
@@ -374,10 +389,33 @@
sizeof(code);
}
+static uint64_t uuid_lsb(const Uuid& uuid) {
+ uint64_t lsb = 0;
+
+ auto uu = uuid.To128BitBE();
+ for (int i = 8; i <= 15; i++) {
+ lsb <<= 8;
+ lsb |= uu[i];
+ }
+
+ return lsb;
+}
+
+static uint64_t uuid_msb(const Uuid& uuid) {
+ uint64_t msb = 0;
+
+ auto uu = uuid.To128BitBE();
+ for (int i = 0; i <= 7; i++) {
+ msb <<= 8;
+ msb |= uu[i];
+ }
+
+ return msb;
+}
+
static bool send_app_connect_signal(int fd, const RawAddress* addr, int channel,
int status, int send_fd, uint16_t rx_mtu,
- uint16_t tx_mtu, uint16_t local_cid,
- uint16_t remote_cid) {
+ uint16_t tx_mtu, const Uuid& conn_uuid) {
sock_connect_signal_t cs;
cs.size = sizeof(cs);
cs.bd_addr = *addr;
@@ -385,8 +423,8 @@
cs.status = status;
cs.max_rx_packet_size = rx_mtu;
cs.max_tx_packet_size = tx_mtu;
- cs.l2cap_lcid = local_cid;
- cs.l2cap_rcid = remote_cid;
+ cs.conn_uuid_lsb = uuid_lsb(conn_uuid);
+ cs.conn_uuid_msb = uuid_msb(conn_uuid);
if (send_fd != -1) {
if (sock_send_fd(fd, (const uint8_t*)&cs, sizeof(cs), send_fd) ==
sizeof(cs))
@@ -479,6 +517,7 @@
accept_rs->tx_mtu = sock->tx_mtu = p_open->tx_mtu;
accept_rs->local_cid = p_open->local_cid;
accept_rs->remote_cid = p_open->remote_cid;
+ accept_rs->conn_uuid = Uuid::GetRandom();
/* Swap IDs to hand over the GAP connection to the accepted socket, and start
a new server on the newly create socket ID. */
@@ -505,7 +544,7 @@
accept_rs->id);
send_app_connect_signal(sock->our_fd, &accept_rs->addr, sock->channel, 0,
accept_rs->app_fd, sock->rx_mtu, p_open->tx_mtu,
- accept_rs->local_cid, accept_rs->remote_cid);
+ accept_rs->conn_uuid);
accept_rs->app_fd =
-1; // The fd is closed after sent to app in send_app_connect_signal()
// But for some reason we still leak a FD - either the server socket
@@ -519,6 +558,7 @@
sock->tx_mtu = p_open->tx_mtu;
sock->local_cid = p_open->local_cid;
sock->remote_cid = p_open->remote_cid;
+ sock->conn_uuid = Uuid::GetRandom();
if (!send_app_psm_or_chan_l(sock)) {
log::error("Unable to send l2cap socket to application socket_id:{}",
@@ -527,8 +567,7 @@
}
if (!send_app_connect_signal(sock->our_fd, &sock->addr, sock->channel, 0, -1,
- sock->rx_mtu, p_open->tx_mtu, sock->local_cid,
- sock->remote_cid)) {
+ sock->rx_mtu, p_open->tx_mtu, sock->conn_uuid)) {
log::error("Unable to connect l2cap socket to application socket_id:{}",
sock->id);
return;
@@ -995,3 +1034,31 @@
return BT_STATUS_SUCCESS;
}
+
+bt_status_t btsock_l2cap_get_l2cap_local_cid(Uuid& conn_uuid, uint16_t* cid) {
+ l2cap_socket* sock;
+
+ std::unique_lock<std::mutex> lock(state_lock);
+ sock = btsock_l2cap_find_by_conn_uuid_l(conn_uuid);
+ if (!sock) {
+ log::error("Unable to find l2cap socket with conn_uuid:{}",
+ conn_uuid.ToString());
+ return BT_STATUS_FAIL;
+ }
+ *cid = sock->local_cid;
+ return BT_STATUS_SUCCESS;
+}
+
+bt_status_t btsock_l2cap_get_l2cap_remote_cid(Uuid& conn_uuid, uint16_t* cid) {
+ l2cap_socket* sock;
+
+ std::unique_lock<std::mutex> lock(state_lock);
+ sock = btsock_l2cap_find_by_conn_uuid_l(conn_uuid);
+ if (!sock) {
+ log::error("Unable to find l2cap socket with conn_uuid:{}",
+ conn_uuid.ToString());
+ return BT_STATUS_FAIL;
+ }
+ *cid = sock->remote_cid;
+ return BT_STATUS_SUCCESS;
+}
diff --git a/system/btif/src/btif_sock_rfc.cc b/system/btif/src/btif_sock_rfc.cc
index 3118f90..4fb5883 100644
--- a/system/btif/src/btif_sock_rfc.cc
+++ b/system/btif/src/btif_sock_rfc.cc
@@ -497,6 +497,8 @@
cs.status = status;
cs.max_rx_packet_size = 0; // not used for RFCOMM
cs.max_tx_packet_size = 0; // not used for RFCOMM
+ cs.conn_uuid_lsb = 0; // not used for RFCOMM
+ cs.conn_uuid_msb = 0; // not used for RFCOMM
if (send_fd == INVALID_FD)
return sock_send_all(fd, (const uint8_t*)&cs, sizeof(cs)) == sizeof(cs);
diff --git a/system/btif/src/btif_storage.cc b/system/btif/src/btif_storage.cc
index d7487d7..53d8ae0 100644
--- a/system/btif/src/btif_storage.cc
+++ b/system/btif/src/btif_storage.cc
@@ -49,8 +49,10 @@
#include "btif_util.h"
#include "common/init_flags.h"
#include "core_callbacks.h"
-#include "device/include/controller.h"
+#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
+#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_octets.h"
#include "stack/include/bt_uuid16.h"
@@ -617,14 +619,14 @@
if (property->type == BT_PROPERTY_BDADDR) {
RawAddress* bd_addr = (RawAddress*)property->val;
/* Fetch the local BD ADDR */
- const controller_t* controller = controller_get_interface();
- if (!controller->get_is_ready()) {
+ if (bluetooth::shim::GetController() == nullptr) {
log::error("Controller not ready! Unable to return Bluetooth Address");
*bd_addr = RawAddress::kEmpty;
return BT_STATUS_FAIL;
} else {
log::info("Controller ready!");
- *bd_addr = *controller->get_address();
+ *bd_addr = bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress());
}
property->len = RawAddress::kLength;
return BT_STATUS_SUCCESS;
diff --git a/system/btif/src/stack_manager.cc b/system/btif/src/stack_manager.cc
index 661b5b1..025222f 100644
--- a/system/btif/src/stack_manager.cc
+++ b/system/btif/src/stack_manager.cc
@@ -63,7 +63,6 @@
#include "bta/dm/bta_dm_int.h"
#include "device/include/interop.h"
#include "internal_include/stack_config.h"
-#include "main/shim/controller.h"
#include "rust/src/core/ffi/module.h"
#include "stack/btm/btm_ble_int.h"
#include "stack/include/smp_api.h"
@@ -197,7 +196,6 @@
extern const module_t bt_utils_module;
extern const module_t bte_logmsg_module;
extern const module_t btif_config_module;
-extern const module_t gd_controller_module;
extern const module_t gd_shim_module;
extern const module_t interop_module;
extern const module_t osi_module;
@@ -213,7 +211,6 @@
const struct module_lookup module_table[] = {
{BTE_LOGMSG_MODULE, &bte_logmsg_module},
{BTIF_CONFIG_MODULE, &btif_config_module},
- {GD_CONTROLLER_MODULE, &gd_controller_module},
{GD_SHIM_MODULE, &gd_shim_module},
{INTEROP_MODULE, &interop_module},
{OSI_MODULE, &osi_module},
@@ -321,7 +318,6 @@
bta_dm_enable(btif_dm_sec_evt, btif_dm_acl_evt);
btm_acl_device_down();
- CHECK(module_start_up(get_local_module(GD_CONTROLLER_MODULE)));
BTM_reset_complete();
BTA_dm_on_hw_on();
diff --git a/system/common/Android.bp b/system/common/Android.bp
index 379ec98..73170b1 100644
--- a/system/common/Android.bp
+++ b/system/common/Android.bp
@@ -97,6 +97,7 @@
},
},
shared_libs: [
+ "libbase",
"libcrypto",
"liblog",
],
@@ -104,6 +105,7 @@
"libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_log",
+ "libbluetooth_log",
"libbt-common",
"libbt-platform-protos-lite",
"libbt_shim_bridge",
@@ -135,9 +137,11 @@
"test/thread_performance_test.cc",
],
shared_libs: [
+ "libbase",
"liblog",
],
static_libs: [
+ "libbluetooth_log",
"libbt-common",
"libchrome",
"libevent",
@@ -162,9 +166,11 @@
"benchmark/thread_performance_benchmark.cc",
],
shared_libs: [
+ "libbase",
"liblog",
],
static_libs: [
+ "libbluetooth_log",
"libbt-common",
"libchrome",
"libevent",
diff --git a/system/common/BUILD.gn b/system/common/BUILD.gn
index 58c3a9d..52c14aa 100644
--- a/system/common/BUILD.gn
+++ b/system/common/BUILD.gn
@@ -62,6 +62,7 @@
"//bt/system:external_gtest_main",
"//bt/system:external_gmock_main",
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
libs = [
diff --git a/system/common/leaky_bonded_queue_unittest.cc b/system/common/leaky_bonded_queue_unittest.cc
index b2ff35b..c2e6abf 100644
--- a/system/common/leaky_bonded_queue_unittest.cc
+++ b/system/common/leaky_bonded_queue_unittest.cc
@@ -15,16 +15,17 @@
* limitations under the License.
*
******************************************************************************/
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
+#include "common/leaky_bonded_queue.h"
#include <base/logging.h>
-
-#include "common/leaky_bonded_queue.h"
+#include <bluetooth/log.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
namespace testing {
using bluetooth::common::LeakyBondedQueue;
+using namespace bluetooth;
#define ITEM_EQ(a, b) \
do { \
@@ -72,7 +73,7 @@
ITEM_EQ(item3_3, item3);
EXPECT_THAT(item4_4, NotNull());
ITEM_EQ(item4_4, item4);
- LOG(INFO) << "All done release items";
+ log::info("All done release items");
EXPECT_CALL(*item2_2, Destruct()).Times(1);
delete item2_2;
EXPECT_CALL(*item3_3, Destruct()).Times(1);
diff --git a/system/common/lru.h b/system/common/lru.h
index 91d5648..1c685a6 100644
--- a/system/common/lru.h
+++ b/system/common/lru.h
@@ -18,6 +18,9 @@
#pragma once
+#include <base/logging.h>
+#include <bluetooth/log.h>
+
#include <functional>
#include <iterator>
#include <list>
@@ -26,8 +29,6 @@
#include <thread>
#include <unordered_map>
-#include <base/logging.h>
-
#include "check.h"
namespace bluetooth {
@@ -48,7 +49,7 @@
: capacity_(capacity) {
if (capacity_ == 0) {
// don't allow invalid capacity
- LOG(FATAL) << log_tag << " unable to have 0 LRU Cache capacity";
+ log::fatal("{} unable to have 0 LRU Cache capacity", log_tag);
}
}
diff --git a/system/common/message_loop_thread.cc b/system/common/message_loop_thread.cc
index faca7f0..dcfc8c5 100644
--- a/system/common/message_loop_thread.cc
+++ b/system/common/message_loop_thread.cc
@@ -21,6 +21,7 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
#include <base/time/time.h>
+#include <bluetooth/log.h>
#include <sys/syscall.h>
#include <unistd.h>
@@ -29,6 +30,8 @@
#include <string>
#include <thread>
+#include "common/postable_context.h"
+
namespace bluetooth {
namespace common {
@@ -60,7 +63,7 @@
{
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
if (thread_ != nullptr) {
- LOG(WARNING) << __func__ << ": thread " << *this << " is already started";
+ log::warn("thread {} is already started", *this);
return;
}
@@ -82,15 +85,14 @@
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
if (message_loop_ == nullptr) {
- LOG(ERROR) << __func__ << ": message loop is null for thread " << *this
- << ", from " << from_here.ToString();
+ log::error("message loop is null for thread {}, from {}", *this,
+ from_here.ToString());
return false;
}
if (!message_loop_->task_runner()->PostDelayedTask(
from_here, std::move(task), timeDeltaFromMicroseconds(delay))) {
- LOG(ERROR) << __func__
- << ": failed to post task to message loop for thread " << *this
- << ", from " << from_here.ToString();
+ log::error("failed to post task to message loop for thread {}, from {}",
+ *this, from_here.ToString());
return false;
}
return true;
@@ -100,15 +102,15 @@
{
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
if (thread_ == nullptr) {
- LOG(INFO) << __func__ << ": thread " << *this << " is already stopped";
+ log::info("thread {} is already stopped", *this);
return;
}
if (message_loop_ == nullptr) {
- LOG(INFO) << __func__ << ": message_loop_ is null. Already stopping";
+ log::info("message_loop_ is null. Already stopping");
return;
}
if (shutting_down_) {
- LOG(INFO) << __func__ << ": waiting for thread to join";
+ log::info("waiting for thread to join");
return;
}
shutting_down_ = true;
@@ -159,7 +161,7 @@
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
if (!IsRunning()) {
- LOG(ERROR) << __func__ << ": thread " << *this << " is not running";
+ log::error("thread {} is not running", *this);
return false;
}
@@ -167,10 +169,10 @@
kRealTimeFifoSchedulingPriority};
int rc = sched_setscheduler(linux_tid_, SCHED_FIFO, &rt_params);
if (rc != 0) {
- LOG(ERROR) << __func__ << ": unable to set SCHED_FIFO priority "
- << kRealTimeFifoSchedulingPriority << " for linux_tid "
- << std::to_string(linux_tid_) << ", thread " << *this
- << ", error: " << strerror(errno);
+ log::error(
+ "unable to set SCHED_FIFO priority {} for linux_tid {}, thread {}, "
+ "error: {}",
+ kRealTimeFifoSchedulingPriority, linux_tid_, *this, strerror(errno));
return false;
}
return true;
@@ -185,8 +187,7 @@
{
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
- LOG(INFO) << __func__ << ": message loop starting for thread "
- << thread_name_;
+ log::info("message loop starting for thread {}", thread_name_);
base::PlatformThread::SetName(thread_name_);
message_loop_ = new btbase::AbstractMessageLoop();
run_loop_ = new base::RunLoop();
@@ -206,8 +207,7 @@
message_loop_ = nullptr;
delete run_loop_;
run_loop_ = nullptr;
- LOG(INFO) << __func__ << ": message loop finished for thread "
- << thread_name_;
+ log::info("message loop finished for thread {}", thread_name_);
}
}
@@ -215,5 +215,7 @@
DoInThread(FROM_HERE, std::move(closure));
}
+PostableContext* MessageLoopThread::Postable() { return this; }
+
} // namespace common
} // namespace bluetooth
diff --git a/system/common/message_loop_thread.h b/system/common/message_loop_thread.h
index 525fcf2..3c43daf 100644
--- a/system/common/message_loop_thread.h
+++ b/system/common/message_loop_thread.h
@@ -20,6 +20,7 @@
#include <base/location.h>
#include <base/run_loop.h>
#include <base/threading/platform_thread.h>
+#include <bluetooth/log.h>
#include <unistd.h>
#include <future>
@@ -27,8 +28,7 @@
#include <thread>
#include "abstract_message_loop.h"
-#include "common/contextual_callback.h"
-#include "common/i_postable_context.h"
+#include "common/postable_context.h"
namespace bluetooth {
@@ -37,7 +37,7 @@
/**
* An interface to various thread related functionality
*/
-class MessageLoopThread final : public IPostableContext {
+class MessageLoopThread final : public PostableContext {
public:
/**
* Create a message loop thread with name. Thread won't be running until
@@ -173,37 +173,10 @@
*/
void Post(base::OnceClosure closure) override;
- template <typename Functor, typename... Args>
- auto BindOnce(Functor&& functor, Args&&... args) {
- return common::ContextualOnceCallback(
- common::BindOnce(std::forward<Functor>(functor),
- std::forward<Args>(args)...),
- this);
- }
-
- template <typename Functor, typename T, typename... Args>
- auto BindOnceOn(T* obj, Functor&& functor, Args&&... args) {
- return common::ContextualOnceCallback(
- common::BindOnce(std::forward<Functor>(functor),
- common::Unretained(obj), std::forward<Args>(args)...),
- this);
- }
-
- template <typename Functor, typename... Args>
- auto Bind(Functor&& functor, Args&&... args) {
- return common::ContextualCallback(
- common::Bind(std::forward<Functor>(functor),
- std::forward<Args>(args)...),
- this);
- }
-
- template <typename Functor, typename T, typename... Args>
- auto BindOn(T* obj, Functor&& functor, Args&&... args) {
- return common::ContextualCallback(
- common::Bind(std::forward<Functor>(functor), common::Unretained(obj),
- std::forward<Args>(args)...),
- this);
- }
+ /**
+ * Returns a postable object
+ */
+ PostableContext* Postable();
private:
/**
@@ -245,5 +218,9 @@
}
} // namespace common
-
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::common::MessageLoopThread> : ostream_formatter {};
+} // namespace fmt
diff --git a/system/common/message_loop_thread_unittest.cc b/system/common/message_loop_thread_unittest.cc
index 74d6287..e904e3f 100644
--- a/system/common/message_loop_thread_unittest.cc
+++ b/system/common/message_loop_thread_unittest.cc
@@ -15,18 +15,19 @@
*/
#include "message_loop_thread.h"
+#include <base/functional/bind.h>
+#include <base/threading/platform_thread.h>
+#include <bluetooth/log.h>
+#include <gtest/gtest.h>
+#include <sys/capability.h>
+#include <syscall.h>
+
#include <condition_variable>
#include <memory>
#include <mutex>
-#include <gtest/gtest.h>
-
-#include <base/functional/bind.h>
-#include <base/threading/platform_thread.h>
-#include <sys/capability.h>
-#include <syscall.h>
-
using bluetooth::common::MessageLoopThread;
+using namespace bluetooth;
/**
* Unit tests to verify MessageLoopThread. Must have CAP_SYS_NICE capability.
@@ -68,16 +69,16 @@
static bool CanSetCurrentThreadPriority() {
struct __user_cap_header_struct linux_user_header = {
.version = _LINUX_CAPABILITY_VERSION_3};
- struct __user_cap_data_struct linux_user_data = {};
- if (capget(&linux_user_header, &linux_user_data) != 0) {
- LOG(ERROR) << "Failed to get capability for current thread, error: "
- << strerror(errno);
+ struct __user_cap_data_struct linux_user_data[2] = {};
+ if (capget(&linux_user_header, linux_user_data) != 0) {
+ log::error("Failed to get capability for current thread, error: {}",
+ strerror(errno));
// Log record in XML
RecordProperty("MessageLoopThreadTestCannotGetCapabilityReason",
strerror(errno));
return false;
}
- return ((linux_user_data.permitted >> CAP_SYS_NICE) & 0x1) != 0;
+ return ((linux_user_data[0].permitted >> CAP_SYS_NICE) & 0x1) != 0;
}
};
@@ -181,8 +182,9 @@
if (CanSetCurrentThreadPriority()) {
FAIL() << "Cannot set real time priority even though we have permission";
} else {
- LOG(WARNING) << "Allowing EnableRealTimeScheduling to fail because we"
- " don't have CAP_SYS_NICE capability";
+ log::warn(
+ "Allowing EnableRealTimeScheduling to fail because we don't have "
+ "CAP_SYS_NICE capability");
// Log record in XML
RecordProperty("MessageLoopThreadTestConditionalSuccess",
"Mark test as success even though EnableRealTimeScheduling"
@@ -246,17 +248,17 @@
MessageLoopThread message_loop_thread(name);
std::string thread_string_before_start = message_loop_thread.ToString();
ASSERT_FALSE(thread_string_before_start.empty());
- LOG(INFO) << "Before start: " << message_loop_thread;
+ log::info("Before start: {}", message_loop_thread);
message_loop_thread.StartUp();
std::string thread_string_running = message_loop_thread.ToString();
ASSERT_FALSE(thread_string_running.empty());
- LOG(INFO) << "Running: " << message_loop_thread;
+ log::info("Running: {}", message_loop_thread);
// String representation should look different when thread is not running
ASSERT_STRNE(thread_string_running.c_str(),
thread_string_before_start.c_str());
message_loop_thread.ShutDown();
std::string thread_string_after_shutdown = message_loop_thread.ToString();
- LOG(INFO) << "After shutdown: " << message_loop_thread;
+ log::info("After shutdown: {}", message_loop_thread);
// String representation should look the same when thread is not running
ASSERT_STREQ(thread_string_after_shutdown.c_str(),
thread_string_before_start.c_str());
diff --git a/system/common/metric_id_allocator.cc b/system/common/metric_id_allocator.cc
index 09b9a26..ea4ac00 100644
--- a/system/common/metric_id_allocator.cc
+++ b/system/common/metric_id_allocator.cc
@@ -19,6 +19,7 @@
#include "metric_id_allocator.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <functional>
#include <mutex>
@@ -58,9 +59,9 @@
// init paired_devices_map
if (paired_device_map.size() > kMaxNumPairedDevicesInMemory) {
- LOG(FATAL)
- << LOGGING_TAG
- << "Paired device map is bigger than kMaxNumPairedDevicesInMemory";
+ log::fatal(
+ "{}Paired device map is bigger than kMaxNumPairedDevicesInMemory",
+ LOGGING_TAG);
// fail loudly to let caller know
return false;
}
@@ -68,7 +69,7 @@
next_id_ = kMinId;
for (const auto& p : paired_device_map) {
if (p.second < kMinId || p.second > kMaxId) {
- LOG(FATAL) << LOGGING_TAG << "Invalid Bluetooth Metric Id in config";
+ log::fatal("{}Invalid Bluetooth Metric Id in config", LOGGING_TAG);
}
auto evicted = paired_device_cache_.Put(p.first, p.second);
if (evicted) {
@@ -130,7 +131,7 @@
next_id_++;
if (next_id_ > kMaxId) {
next_id_ = kMinId;
- LOG(WARNING) << LOGGING_TAG << "Bluetooth metric id overflow.";
+ log::warn("{}Bluetooth metric id overflow.", LOGGING_TAG);
}
}
id = next_id_++;
@@ -154,14 +155,15 @@
return true;
}
if (!temporary_device_cache_.Get(mac_address, &id)) {
- LOG(ERROR) << LOGGING_TAG
- << "Failed to save device because device is not in "
- << "temporary_device_cache_";
+ log::error(
+ "{}Failed to save device because device is not in "
+ "temporary_device_cache_",
+ LOGGING_TAG);
return false;
}
if (!temporary_device_cache_.Remove(mac_address)) {
- LOG(ERROR) << LOGGING_TAG
- << "Failed to remove device from temporary_device_cache_";
+ log::error("{}Failed to remove device from temporary_device_cache_",
+ LOGGING_TAG);
return false;
}
auto evicted = paired_device_cache_.Put(mac_address, id);
@@ -169,8 +171,8 @@
ForgetDevicePostprocess(evicted->first, evicted->second);
}
if (!save_id_callback_(mac_address, id)) {
- LOG(ERROR) << LOGGING_TAG
- << "Callback returned false after saving the device";
+ log::error("{}Callback returned false after saving the device",
+ LOGGING_TAG);
return false;
}
return true;
@@ -181,14 +183,15 @@
std::lock_guard<std::mutex> lock(id_allocator_mutex_);
int id = 0;
if (!paired_device_cache_.Get(mac_address, &id)) {
- LOG(ERROR) << LOGGING_TAG
- << "Failed to forget device because device is not in "
- << "paired_device_cache_";
+ log::error(
+ "{}Failed to forget device because device is not in "
+ "paired_device_cache_",
+ LOGGING_TAG);
return;
}
if (!paired_device_cache_.Remove(mac_address)) {
- LOG(ERROR) << LOGGING_TAG
- << "Failed to remove device from paired_device_cache_";
+ log::error("{}Failed to remove device from paired_device_cache_",
+ LOGGING_TAG);
return;
}
ForgetDevicePostprocess(mac_address, id);
diff --git a/system/common/metrics.cc b/system/common/metrics.cc
index b9a1e2d..9397aae 100644
--- a/system/common/metrics.cc
+++ b/system/common/metrics.cc
@@ -20,6 +20,7 @@
#include <base/base64.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/le/enums.pb.h>
#include <include/hardware/bt_av.h>
#include <statslog_bt.h>
@@ -45,8 +46,25 @@
#include "time_util.h"
#include "types/raw_address.h"
-namespace bluetooth {
+namespace fmt {
+template <>
+struct formatter<android::bluetooth::DirectionEnum>
+ : enum_formatter<android::bluetooth::DirectionEnum> {};
+template <>
+struct formatter<android::bluetooth::SocketConnectionstateEnum>
+ : enum_formatter<android::bluetooth::SocketConnectionstateEnum> {};
+template <>
+struct formatter<android::bluetooth::SocketRoleEnum>
+ : enum_formatter<android::bluetooth::SocketRoleEnum> {};
+template <>
+struct formatter<android::bluetooth::AddressTypeEnum>
+ : enum_formatter<android::bluetooth::AddressTypeEnum> {};
+template <>
+struct formatter<android::bluetooth::DeviceInfoSrcEnum>
+ : enum_formatter<android::bluetooth::DeviceInfoSrcEnum> {};
+} // namespace fmt
+namespace bluetooth {
namespace common {
using bluetooth::metrics::BluetoothMetricsProto::A2DPSession;
@@ -460,11 +478,11 @@
void BluetoothMetricsLogger::WriteString(std::string* serialized) {
std::lock_guard<std::recursive_mutex> lock(pimpl_->bluetooth_log_lock_);
- LOG(INFO) << __func__ << ": building metrics";
+ log::info("building metrics");
Build();
- LOG(INFO) << __func__ << ": serializing metrics";
+ log::info("serializing metrics");
if (!pimpl_->bluetooth_log_->SerializeToString(serialized)) {
- LOG(ERROR) << __func__ << ": error serializing metrics";
+ log::error("error serializing metrics");
}
// Always clean up log objects
pimpl_->bluetooth_log_->Clear();
@@ -481,9 +499,7 @@
ssize_t ret;
OSI_NO_INTR(ret = write(fd, protoBase64.c_str(), protoBase64.size()));
if (ret == -1) {
- LOG(ERROR) << __func__
- << ": error writing to dumpsys fd: " << strerror(errno) << " ("
- << std::to_string(errno) << ")";
+ log::error("error writing to dumpsys fd: {} ({})", strerror(errno), errno);
}
}
@@ -595,12 +611,13 @@
connection_handle, direction, link_type, hci_cmd, hci_event,
hci_ble_event, cmd_status, reason_code, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed to log status " << loghex(cmd_status)
- << ", reason " << loghex(reason_code) << " from cmd "
- << loghex(hci_cmd) << ", event " << loghex(hci_event)
- << ", ble_event " << loghex(hci_ble_event) << " for "
- << address << ", handle " << connection_handle << ", type "
- << loghex(link_type) << ", error " << ret;
+ log::warn(
+ "failed to log status {}, reason {} from cmd {}, event {}, ble_event "
+ "{} for {}, handle {}, type {}, error {}",
+ loghex(cmd_status), loghex(reason_code), loghex(hci_cmd),
+ loghex(hci_event), loghex(hci_ble_event),
+ ADDRESS_TO_LOGGABLE_STR(*address), connection_handle, loghex(link_type),
+ ret);
}
}
@@ -608,8 +625,7 @@
int ret = stats_write(BLUETOOTH_HCI_TIMEOUT_REPORTED,
static_cast<int64_t>(hci_cmd));
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for opcode " << loghex(hci_cmd)
- << ", error " << ret;
+ log::warn("failed for opcode {}, error {}", loghex(hci_cmd), ret);
}
}
@@ -618,10 +634,11 @@
int ret = stats_write(BLUETOOTH_REMOTE_VERSION_INFO_REPORTED, handle, status,
version, manufacturer_name, subversion);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for handle " << handle << ", status "
- << loghex(status) << ", version " << loghex(version)
- << ", manufacturer_name " << loghex(manufacturer_name)
- << ", subversion " << loghex(subversion) << ", error " << ret;
+ log::warn(
+ "failed for handle {}, status {}, version {}, manufacturer_name {}, "
+ "subversion {}, error {}",
+ handle, loghex(status), loghex(version), loghex(manufacturer_name),
+ loghex(subversion), ret);
}
}
@@ -642,10 +659,11 @@
stats_write(BLUETOOTH_A2DP_AUDIO_UNDERRUN_REPORTED, bytes_field,
encoding_interval_nanos, num_missing_pcm_bytes, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address
- << ", encoding_interval_nanos " << encoding_interval_nanos
- << ", num_missing_pcm_bytes " << num_missing_pcm_bytes
- << ", error " << ret;
+ log::warn(
+ "failed for {}, encoding_interval_nanos {}, num_missing_pcm_bytes {}, "
+ "error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), encoding_interval_nanos,
+ num_missing_pcm_bytes, ret);
}
}
@@ -669,12 +687,13 @@
num_dropped_encoded_frames, num_dropped_encoded_bytes,
metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed to log for " << address
- << ", encoding_interval_nanos " << encoding_interval_nanos
- << ", num_dropped_buffers " << num_dropped_buffers
- << ", num_dropped_encoded_frames "
- << num_dropped_encoded_frames << ", num_dropped_encoded_bytes "
- << num_dropped_encoded_bytes << ", error " << ret;
+ log::warn(
+ "failed to log for {}, encoding_interval_nanos {}, num_dropped_buffers "
+ "{}, num_dropped_encoded_frames {}, num_dropped_encoded_bytes {}, "
+ "error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), encoding_interval_nanos,
+ num_dropped_buffers, num_dropped_encoded_frames,
+ num_dropped_encoded_bytes, ret);
}
}
@@ -692,10 +711,11 @@
int ret = stats_write(BLUETOOTH_A2DP_PLAYBACK_STATE_CHANGED, bytes_field,
playback_state, audio_coding_mode, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed to log for " << address
- << ", playback_state " << playback_state
- << ", audio_coding_mode " << audio_coding_mode << ", error "
- << ret;
+ log::warn(
+ "failed to log for {}, playback_state {}, audio_coding_mode {}, error "
+ "{}",
+ ADDRESS_TO_LOGGABLE_STR(address), playback_state, audio_coding_mode,
+ ret);
}
}
@@ -713,9 +733,9 @@
int ret = stats_write(BLUETOOTH_DEVICE_RSSI_REPORTED, bytes_field, handle,
cmd_status, rssi, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", handle "
- << handle << ", status " << loghex(cmd_status) << ", rssi "
- << rssi << " dBm, error " << ret;
+ log::warn("failed for {}, handle {}, status {}, rssi {} dBm, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), handle, loghex(cmd_status),
+ rssi, ret);
}
}
@@ -735,10 +755,11 @@
stats_write(BLUETOOTH_DEVICE_FAILED_CONTACT_COUNTER_REPORTED, bytes_field,
handle, cmd_status, failed_contact_counter, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", handle "
- << handle << ", status " << loghex(cmd_status)
- << ", failed_contact_counter " << failed_contact_counter
- << " packets, error " << ret;
+ log::warn(
+ "failed for {}, handle {}, status {}, failed_contact_counter {} "
+ "packets, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), handle, loghex(cmd_status),
+ failed_contact_counter, ret);
}
}
@@ -757,10 +778,11 @@
int ret = stats_write(BLUETOOTH_DEVICE_TX_POWER_LEVEL_REPORTED, bytes_field,
handle, cmd_status, transmit_power_level, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", handle "
- << handle << ", status " << loghex(cmd_status)
- << ", transmit_power_level " << transmit_power_level
- << " packets, error " << ret;
+ log::warn(
+ "failed for {}, handle {}, status {}, transmit_power_level {} packets, "
+ "error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), handle, loghex(cmd_status),
+ transmit_power_level, ret);
}
}
@@ -781,10 +803,10 @@
stats_write(BLUETOOTH_SMP_PAIRING_EVENT_REPORTED, obfuscated_id_field,
smp_cmd, direction, smp_fail_reason, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", smp_cmd "
- << loghex(smp_cmd) << ", direction " << direction
- << ", smp_fail_reason " << loghex(smp_fail_reason)
- << ", error " << ret;
+ log::warn(
+ "failed for {}, smp_cmd {}, direction {}, smp_fail_reason {}, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), loghex(smp_cmd), direction,
+ loghex(smp_fail_reason), ret);
}
}
@@ -804,9 +826,12 @@
obfuscated_id_field, handle, hci_cmd, hci_event,
cmd_status, reason_code, event_value, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", handle " << handle << ", hci_cmd " << loghex(hci_cmd)
- << ", hci_event " << loghex(hci_event) << ", cmd_status " << loghex(cmd_status) << ", reason "
- << loghex(reason_code) << ", event_value " << event_value << ", error " << ret;
+ log::warn(
+ "failed for {}, handle {}, hci_cmd {}, hci_event {}, cmd_status {}, "
+ "reason {}, event_value {}, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), handle, loghex(hci_cmd),
+ loghex(hci_event), loghex(cmd_status), loghex(reason_code), event_value,
+ ret);
}
}
@@ -828,9 +853,9 @@
stats_write(BLUETOOTH_SDP_ATTRIBUTE_REPORTED, obfuscated_id_field,
protocol_uuid, attribute_id, attribute_field, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", protocol_uuid "
- << loghex(protocol_uuid) << ", attribute_id "
- << loghex(attribute_id) << ", error " << ret;
+ log::warn("failed for {}, protocol_uuid {}, attribute_id {}, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), loghex(protocol_uuid),
+ loghex(attribute_id), ret);
}
}
@@ -854,11 +879,11 @@
obfuscated_id_field, port, type, connection_state, tx_bytes,
rx_bytes, uid, server_port, socket_role, metric_id);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", port " << port
- << ", type " << type << ", state " << connection_state
- << ", tx_bytes " << tx_bytes << ", rx_bytes " << rx_bytes
- << ", uid " << uid << ", server_port " << server_port
- << ", socket_role " << socket_role << ", error " << ret;
+ log::warn(
+ "failed for {}, port {}, type {}, state {}, tx_bytes {}, rx_bytes {}, "
+ "uid {}, server_port {}, socket_role {}, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), port, type, connection_state,
+ tx_bytes, rx_bytes, uid, server_port, socket_role, ret);
}
}
@@ -886,15 +911,13 @@
hardware_version.c_str(), software_version.c_str(), metric_id,
address_type, address.address[5], address.address[4], address.address[3]);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", source_type "
- << source_type << ", source_name " << source_name
- << ", manufacturer " << manufacturer << ", model " << model
- << ", hardware_version " << hardware_version
- << ", software_version " << software_version
- << " MAC address type " << address_type
- << " MAC address prefix " << address.address[5] << " "
- << address.address[4] << " " << address.address[3] << ", error "
- << ret;
+ log::warn(
+ "failed for {}, source_type {}, source_name {}, manufacturer {}, model "
+ "{}, hardware_version {}, software_version {} MAC address type {} MAC "
+ "address prefix {} {} {}, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), source_type, source_name,
+ manufacturer, model, hardware_version, software_version, address_type,
+ address.address[5], address.address[4], address.address[3], ret);
}
}
@@ -911,9 +934,9 @@
int ret = stats_write(BLUETOOTH_HAL_CRASH_REASON_REPORTED, 0,
obfuscated_id_field, error_code, vendor_error_code);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for " << address << ", error_code "
- << loghex(error_code) << ", vendor_error_code "
- << loghex(vendor_error_code) << ", error " << ret;
+ log::warn("failed for {}, error_code {}, vendor_error_code {}, error {}",
+ ADDRESS_TO_LOGGABLE_STR(address), loghex(error_code),
+ loghex(vendor_error_code), ret);
}
}
@@ -945,31 +968,26 @@
device_connection_status, device_disconnection_status, device_metric_id,
streaming_offset_nanos, streaming_duration_nanos, streaming_context_type);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for group " << group_metric_id
- << "device_connecting_offset_nanos["
- << device_connecting_offset_nanos.size() << "], "
- << "device_connected_offset_nanos["
- << device_connected_offset_nanos.size() << "], "
- << "device_connection_duration_nanos["
- << device_connection_duration_nanos.size() << "], "
- << "device_connection_status["
- << device_connection_status.size() << "], "
- << "device_disconnection_status["
- << device_disconnection_status.size() << "], "
- << "device_metric_id[" << device_metric_id.size() << "], "
- << "streaming_offset_nanos[" << streaming_offset_nanos.size()
- << "], "
- << "streaming_duration_nanos["
- << streaming_duration_nanos.size() << "], "
- << "streaming_context_type[" << streaming_context_type.size()
- << "]";
+ log::warn(
+ "failed for group {}device_connecting_offset_nanos[{}], "
+ "device_connected_offset_nanos[{}], "
+ "device_connection_duration_nanos[{}], device_connection_status[{}], "
+ "device_disconnection_status[{}], device_metric_id[{}], "
+ "streaming_offset_nanos[{}], streaming_duration_nanos[{}], "
+ "streaming_context_type[{}]",
+ group_metric_id, device_connecting_offset_nanos.size(),
+ device_connected_offset_nanos.size(),
+ device_connection_duration_nanos.size(),
+ device_connection_status.size(), device_disconnection_status.size(),
+ device_metric_id.size(), streaming_offset_nanos.size(),
+ streaming_duration_nanos.size(), streaming_context_type.size());
}
}
void LogLeAudioBroadcastSessionReported(int64_t duration_nanos) {
int ret = stats_write(LE_AUDIO_BROADCAST_SESSION_REPORTED, duration_nanos);
if (ret < 0) {
- LOG(WARNING) << __func__ << ": failed for duration=" << duration_nanos;
+ log::warn("failed for duration={}", duration_nanos);
}
}
diff --git a/system/common/metrics_linux.cc b/system/common/metrics_linux.cc
index 883a645e..707e0a54 100644
--- a/system/common/metrics_linux.cc
+++ b/system/common/metrics_linux.cc
@@ -17,6 +17,7 @@
******************************************************************************/
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "leaky_bonded_queue.h"
#include "metrics.h"
@@ -29,7 +30,7 @@
void A2dpSessionMetrics::Update(const A2dpSessionMetrics& metrics) {}
bool A2dpSessionMetrics::operator==(const A2dpSessionMetrics& rhs) const {
- LOG(INFO) << "UNIMPLEMENTED";
+ log::info("UNIMPLEMENTED");
return true;
}
diff --git a/system/common/repeating_timer.cc b/system/common/repeating_timer.cc
index 9abea46..39825eb 100644
--- a/system/common/repeating_timer.cc
+++ b/system/common/repeating_timer.cc
@@ -16,11 +16,12 @@
#include "repeating_timer.h"
-#include "message_loop_thread.h"
-#include "time_util.h"
-
#include <base/functional/callback.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
+
+#include "message_loop_thread.h"
+#include "time_util.h"
namespace bluetooth {
@@ -43,8 +44,7 @@
const base::Location& from_here, base::RepeatingClosure task,
std::chrono::microseconds period) {
if (period < kMinimumPeriod) {
- LOG(ERROR) << __func__ << ": period must be at least "
- << kMinimumPeriod.count();
+ log::error("period must be at least {}", kMinimumPeriod.count());
return false;
}
@@ -52,7 +52,7 @@
uint64_t time_next_task_us = time_now_us + period.count();
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
if (thread == nullptr) {
- LOG(ERROR) << __func__ << ": thread must be non-null";
+ log::error("thread must be non-null");
return false;
}
CancelAndWait();
@@ -66,9 +66,8 @@
if (!thread->DoInThreadDelayed(
from_here, task_wrapper_.callback(),
std::chrono::microseconds(time_until_next_us))) {
- LOG(ERROR) << __func__
- << ": failed to post task to message loop for thread " << *thread
- << ", from " << from_here.ToString();
+ log::error("failed to post task to message loop for thread {}, from {}",
+ *thread, from_here.ToString());
expected_time_next_task_us_ = 0;
task_wrapper_.Cancel();
message_loop_thread_ = nullptr;
@@ -132,8 +131,7 @@
// This runs on message loop thread
void RepeatingTimer::RunTask() {
if (message_loop_thread_ == nullptr || !message_loop_thread_->IsRunning()) {
- LOG(ERROR) << __func__
- << ": message_loop_thread_ is null or is not running";
+ log::error("message_loop_thread_ is null or is not running");
return;
}
CHECK_EQ(message_loop_thread_->GetThreadId(),
@@ -159,9 +157,10 @@
auto task_time_us =
static_cast<int64_t>(time_after_task_us - time_before_task_us);
if (task_time_us > period_.count()) {
- LOG(ERROR) << __func__ << ": Periodic task execution took " << task_time_us
- << " microseconds, longer than interval " << period_.count()
- << " microseconds";
+ log::error(
+ "Periodic task execution took {} microseconds, longer than interval {} "
+ "microseconds",
+ task_time_us, period_.count());
}
}
diff --git a/system/common/stop_watch_legacy.cc b/system/common/stop_watch_legacy.cc
index 6b783cb..eb0a05e 100644
--- a/system/common/stop_watch_legacy.cc
+++ b/system/common/stop_watch_legacy.cc
@@ -19,6 +19,7 @@
#include "common/stop_watch_legacy.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <iomanip>
#include <mutex>
@@ -39,12 +40,12 @@
void StopWatchLegacy::RecordLog(StopWatchLog log) {
std::unique_lock<std::recursive_mutex> lock(stopwatch_log_mutex, std::defer_lock);
if (!lock.try_lock()) {
- LOG_INFO("try_lock fail. log content: %s, took %zu us", log.message.c_str(),
- static_cast<size_t>(
- std::chrono::duration_cast<std::chrono::microseconds>(
- stopwatch_logs[current_buffer_index].end_timestamp -
- stopwatch_logs[current_buffer_index].start_timestamp)
- .count()));
+ log::info("try_lock fail. log content: {}, took {} us", log.message,
+ static_cast<size_t>(
+ std::chrono::duration_cast<std::chrono::microseconds>(
+ stopwatch_logs[current_buffer_index].end_timestamp -
+ stopwatch_logs[current_buffer_index].start_timestamp)
+ .count()));
return;
}
if (current_buffer_index >= LOG_BUFFER_LENGTH) {
@@ -57,8 +58,8 @@
void StopWatchLegacy::DumpStopWatchLog() {
std::lock_guard<std::recursive_mutex> lock(stopwatch_log_mutex);
- LOG_INFO("=-----------------------------------=");
- LOG_INFO("bluetooth stopwatch log history:");
+ log::info("=-----------------------------------=");
+ log::info("bluetooth stopwatch log history:");
for (int i = 0; i < LOG_BUFFER_LENGTH; i++) {
if (current_buffer_index >= LOG_BUFFER_LENGTH) {
current_buffer_index = 0;
@@ -76,16 +77,16 @@
ss << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %H:%M:%S");
ss << '.' << std::setfill('0') << std::setw(3) << millis.count();
std::string start_timestamp = ss.str();
- LOG_INFO("%s: %s: took %zu us", start_timestamp.c_str(),
- stopwatch_logs[current_buffer_index].message.c_str(),
- static_cast<size_t>(
- std::chrono::duration_cast<std::chrono::microseconds>(
- stopwatch_logs[current_buffer_index].end_timestamp -
- stopwatch_logs[current_buffer_index].start_timestamp)
- .count()));
+ log::info("{}: {}: took {} us", start_timestamp,
+ stopwatch_logs[current_buffer_index].message,
+ static_cast<size_t>(
+ std::chrono::duration_cast<std::chrono::microseconds>(
+ stopwatch_logs[current_buffer_index].end_timestamp -
+ stopwatch_logs[current_buffer_index].start_timestamp)
+ .count()));
current_buffer_index++;
}
- LOG_INFO("=-----------------------------------=");
+ log::info("=-----------------------------------=");
}
StopWatchLegacy::StopWatchLegacy(std::string text)
diff --git a/system/common/test/thread_performance_test.cc b/system/common/test/thread_performance_test.cc
index 84eecdf..7b57306 100644
--- a/system/common/test/thread_performance_test.cc
+++ b/system/common/test/thread_performance_test.cc
@@ -18,9 +18,11 @@
#include <base/logging.h>
#include <base/run_loop.h>
#include <base/threading/thread.h>
+#include <bluetooth/log.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <unistd.h>
+
#include <chrono>
#include <future>
#include <iostream>
@@ -32,6 +34,7 @@
#include "osi/include/thread.h"
using bluetooth::common::MessageLoopThread;
+using namespace bluetooth;
#define NUM_MESSAGES_TO_SEND 100000
@@ -135,8 +138,8 @@
std::chrono::duration_cast<std::chrono::milliseconds>(end_time -
start_time);
- LOG(INFO) << "OsiThreadMessageLoopPerformanceTest, " << duration.count()
- << " ms, " << NUM_MESSAGES_TO_SEND << " messages";
+ log::info("OsiThreadMessageLoopPerformanceTest, {} ms, {} messages",
+ duration.count(), NUM_MESSAGES_TO_SEND);
}
class StlThreadMessageLoopPerformanceTest : public MessageLoopPerformanceTest {
@@ -180,8 +183,8 @@
std::chrono::duration_cast<std::chrono::milliseconds>(end_time -
start_time);
- LOG(INFO) << "StlThreadMessageLoopPerformanceTest, " << duration.count()
- << " ms, " << NUM_MESSAGES_TO_SEND << " messages";
+ log::info("StlThreadMessageLoopPerformanceTest, {} ms, {} messages",
+ duration.count(), NUM_MESSAGES_TO_SEND);
}
class PosixThreadMessageLoopPerformanceTest
@@ -226,8 +229,8 @@
std::chrono::duration_cast<std::chrono::milliseconds>(end_time -
start_time);
- LOG(INFO) << "PosixThreadMessageLoopPerformanceTest, " << duration.count()
- << " ms, " << NUM_MESSAGES_TO_SEND << " messages";
+ log::info("PosixThreadMessageLoopPerformanceTest, {} ms, {} messages",
+ duration.count(), NUM_MESSAGES_TO_SEND);
}
class ReactorPerformanceTest : public PerformanceTest {
@@ -268,8 +271,8 @@
start_time);
fixed_queue_unregister_dequeue(bt_msg_queue_);
- LOG(INFO) << "ReactorPerformanceTest, " << duration.count() << " ms, "
- << NUM_MESSAGES_TO_SEND << " messages";
+ log::info("ReactorPerformanceTest, {} ms, {} messages", duration.count(),
+ NUM_MESSAGES_TO_SEND);
}
class WorkerThreadPerformanceTest : public PerformanceTest {
@@ -317,8 +320,8 @@
std::chrono::duration_cast<std::chrono::milliseconds>(end_time -
start_time);
- LOG(INFO) << "WorkerThreadPerformanceTest, " << duration.count() << " ms, "
- << NUM_MESSAGES_TO_SEND << " messages";
+ log::info("WorkerThreadPerformanceTest, {} ms, {} messages", duration.count(),
+ NUM_MESSAGES_TO_SEND);
}
class LibChromeThreadPerformanceTest : public PerformanceTest {
@@ -365,6 +368,6 @@
std::chrono::duration_cast<std::chrono::milliseconds>(end_time -
start_time);
- LOG(INFO) << "LibChromeThreadPerformanceTest, " << duration.count() << " ms, "
- << NUM_MESSAGES_TO_SEND << " messages";
+ log::info("LibChromeThreadPerformanceTest, {} ms, {} messages",
+ duration.count(), NUM_MESSAGES_TO_SEND);
}
diff --git a/system/conf/interop_database.conf b/system/conf/interop_database.conf
index 8419815..9b2017f 100644
--- a/system/conf/interop_database.conf
+++ b/system/conf/interop_database.conf
@@ -860,6 +860,8 @@
# Some HID devices have more than one HID services, this rule ask the stack to connect to the
# specify one.
-# 0X046D-0XBB01 - Logitech CASA Pop-Up Touch
+# 0X046D-0XBB00 - Logitech CASA Pop-Up Touch SKU1
+# 0X046D-0XBB01 - Logitech CASA Pop-Up Touch SKU2
[INTEROP_MULTIPLE_HOGP_SERVICE_CHOOSE_THIRD]
+0X046D-0XBB00 = Vndr_Prdt_Based
0X046D-0XBB01 = Vndr_Prdt_Based
diff --git a/system/device/Android.bp b/system/device/Android.bp
index 313ce17..c20a240 100644
--- a/system/device/Android.bp
+++ b/system/device/Android.bp
@@ -21,7 +21,6 @@
"packages/modules/Bluetooth/system/stack/include",
],
srcs: [
- "src/controller.cc",
"src/device_iot_config.cc",
"src/device_iot_config_int.cc",
"src/esco_parameters.cc",
diff --git a/system/device/BUILD.gn b/system/device/BUILD.gn
index 1d8c938..eb53537 100644
--- a/system/device/BUILD.gn
+++ b/system/device/BUILD.gn
@@ -16,7 +16,6 @@
static_library("device") {
sources = [
- "src/controller.cc",
"src/esco_parameters.cc",
"src/interop.cc",
"src/device_iot_config.cc",
diff --git a/system/device/include/controller.h b/system/device/include/controller.h
deleted file mode 100644
index 2aa201c..0000000
--- a/system/device/include/controller.h
+++ /dev/null
@@ -1,60 +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 <cstddef>
-#include <cstdint>
-#include <vector>
-
-#include "base/functional/callback.h"
-#include "btcore/include/version.h"
-#include "types/raw_address.h"
-
-typedef struct controller_t {
- bool (*get_is_ready)(void);
-
- const RawAddress* (*get_address)(void);
- const bt_version_t* (*get_bt_version)(void);
-
- const uint8_t* (*get_ble_supported_states)(void);
-
- uint16_t (*get_ble_default_data_packet_length)(void);
- uint16_t (*get_ble_maximum_tx_data_length)(void);
- uint16_t (*get_ble_maximum_tx_time)(void);
- uint16_t (*get_ble_maximum_advertising_data_length)(void);
- uint8_t (*get_ble_number_of_supported_advertising_sets)(void);
- uint8_t (*get_ble_periodic_advertiser_list_size)(void);
-
- uint8_t (*get_ble_acceptlist_size)(void);
-
- uint8_t (*get_ble_resolving_list_max_size)(void);
- void (*set_ble_resolving_list_max_size)(int resolving_list_max_size);
- uint8_t* (*get_local_supported_codecs)(uint8_t* number_of_codecs);
- uint8_t (*get_le_all_initiating_phys)(void);
- uint8_t (*clear_event_filter)(void);
- uint8_t (*clear_event_mask)(void);
- uint8_t (*set_event_filter_connection_setup_all_devices)(void);
- uint8_t (*set_event_filter_allow_device_connection)(
- std::vector<RawAddress> devices);
- uint8_t (*set_default_event_mask_except)(uint64_t mask, uint64_t le_mask);
- uint8_t (*set_event_filter_inquiry_result_all_devices)(void);
-
-} controller_t;
-
-const controller_t* controller_get_interface();
diff --git a/system/device/src/controller.cc b/system/device/src/controller.cc
deleted file mode 100644
index 8af4651..0000000
--- a/system/device/src/controller.cc
+++ /dev/null
@@ -1,23 +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.
- *
- ******************************************************************************/
-
-#include "main/shim/controller.h"
-
-const controller_t* controller_get_interface() {
- return bluetooth::shim::controller_get_interface();
-}
diff --git a/system/device/src/device_iot_config.cc b/system/device/src/device_iot_config.cc
index 7517366..7a21242 100644
--- a/system/device/src/device_iot_config.cc
+++ b/system/device/src/device_iot_config.cc
@@ -16,10 +16,12 @@
* limitations under the License.
*
******************************************************************************/
-#include "internal_include/bt_target.h"
-
#define LOG_TAG "device_iot_config"
+
+#include "device/include/device_iot_config.h"
+
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
@@ -30,9 +32,9 @@
#include <string>
#include "common/init_flags.h"
-#include "device/include/device_iot_config.h"
#include "device_iot_config_int.h"
#include "include/check.h"
+#include "internal_include/bt_target.h"
#include "os/log.h"
#include "osi/include/alarm.h"
#include "osi/include/allocator.h"
@@ -49,6 +51,7 @@
alarm_t* config_timer;
using bluetooth::common::InitFlags;
+using namespace bluetooth;
bool device_iot_config_has_section(const std::string& section) {
if (!InitFlags::IsDeviceIotConfigLoggingEnabled()) return false;
@@ -275,12 +278,12 @@
CHECK(config != NULL);
- LOG_VERBOSE("Key = %s", key.c_str());
+ log::verbose("Key = {}", key);
if (length > 0) CHECK(value != NULL);
char* str = (char*)osi_calloc(length * 2 + 1);
if (str == NULL) {
- LOG_ERROR("Unable to allocate a str.");
+ log::error("Unable to allocate a str.");
return false;
}
@@ -320,7 +323,7 @@
int event = alarm_is_scheduled(config_timer) ? IOT_CONFIG_SAVE_TIMER_FIRED_EVT
: IOT_CONFIG_FLUSH_EVT;
- LOG_VERBOSE("evt=%d", event);
+ log::verbose("evt={}", event);
alarm_cancel(config_timer);
device_iot_config_write(event, NULL);
}
@@ -331,7 +334,7 @@
CHECK(config != NULL);
CHECK(config_timer != NULL);
- LOG_INFO("");
+ log::info("");
alarm_cancel(config_timer);
std::unique_lock<std::mutex> lock(config_lock);
diff --git a/system/device/src/device_iot_config_int.cc b/system/device/src/device_iot_config_int.cc
index fc4d1a4..78b455b 100644
--- a/system/device/src/device_iot_config_int.cc
+++ b/system/device/src/device_iot_config_int.cc
@@ -21,6 +21,7 @@
#include "device_iot_config_int.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
@@ -52,6 +53,7 @@
extern alarm_t* config_timer;
using bluetooth::common::InitFlags;
+using namespace bluetooth;
static void cleanup() {
alarm_free(config_timer);
@@ -63,7 +65,7 @@
// Module lifecycle functions
future_t* device_iot_config_module_init(void) {
- LOG_INFO("");
+ log::info("");
std::unique_lock<std::mutex> lock(config_lock);
@@ -77,20 +79,20 @@
config = config_new(IOT_CONFIG_FILE_PATH);
device_iot_config_source = ORIGINAL;
if (!config) {
- LOG_WARN("Unable to load config file: %s; using backup.",
- IOT_CONFIG_FILE_PATH);
+ log::warn("Unable to load config file: {}; using backup.",
+ IOT_CONFIG_FILE_PATH);
config = config_new(IOT_CONFIG_BACKUP_PATH);
device_iot_config_source = BACKUP;
}
if (!config) {
- LOG_ERROR("Unable to load bak file; creating empty config.");
+ log::error("Unable to load bak file; creating empty config.");
config = config_new_empty();
device_iot_config_source = NEW_FILE;
}
if (!config) {
- LOG_ERROR("Unable to allocate a config object.");
+ log::error("Unable to allocate a config object.");
cleanup();
return future_new_immediate(FUTURE_FAIL);
}
@@ -108,14 +110,14 @@
}
if (version != DEVICE_IOT_INFO_CURRENT_VERSION) {
- LOG_INFO("Version in file is %d, CURRENT_VERSION is %d ", version,
- DEVICE_IOT_INFO_CURRENT_VERSION);
+ log::info("Version in file is {}, CURRENT_VERSION is {}", version,
+ DEVICE_IOT_INFO_CURRENT_VERSION);
remove(IOT_CONFIG_FILE_PATH);
remove(IOT_CONFIG_BACKUP_PATH);
config.reset();
config = config_new_empty();
if (!config) {
- LOG_ERROR("Unable to allocate a config object.");
+ log::error("Unable to allocate a config object.");
cleanup();
return future_new_immediate(FUTURE_FAIL);
}
@@ -125,7 +127,7 @@
}
device_iot_config_devices_loaded = device_iot_config_get_device_num(*config);
- LOG_INFO("Devices loaded %d", device_iot_config_devices_loaded);
+ log::info("Devices loaded {}", device_iot_config_devices_loaded);
// Read or set config file creation timestamp
const std::string* time_str =
@@ -150,7 +152,7 @@
// write back to disk.
config_timer = alarm_new("btif.iot.config");
if (!config_timer) {
- LOG_ERROR("Unable to create alarm.");
+ log::error("Unable to create alarm.");
cleanup();
return future_new_immediate(FUTURE_FAIL);
}
@@ -159,18 +161,18 @@
}
future_t* device_iot_config_module_start_up(void) {
- LOG_INFO("");
+ log::info("");
return future_new_immediate(FUTURE_SUCCESS);
}
future_t* device_iot_config_module_shut_down(void) {
- LOG_INFO("");
+ log::info("");
device_iot_config_flush();
return future_new_immediate(FUTURE_SUCCESS);
}
future_t* device_iot_config_module_clean_up(void) {
- LOG_INFO("");
+ log::info("");
if (config_timer != NULL && alarm_is_scheduled(config_timer))
device_iot_config_flush();
@@ -196,7 +198,7 @@
CHECK(config != NULL);
CHECK(config_timer != NULL);
- LOG_INFO("evt=%d", event);
+ log::info("evt={}", event);
std::unique_lock<std::mutex> lock(config_lock);
if (event == IOT_CONFIG_SAVE_TIMER_FIRED_EVT) {
device_iot_config_set_modified_time();
@@ -235,7 +237,7 @@
CHECK(config != NULL);
CHECK(config_timer != NULL);
- LOG_VERBOSE("");
+ log::verbose("");
alarm_set(config_timer, CONFIG_SETTLE_PERIOD_MS,
device_iot_config_timer_save_cb, NULL);
}
@@ -264,8 +266,8 @@
need_remove_devices_num =
curr_num - DEVICES_MAX_NUM_IN_IOT_INFO_FILE + DEVICES_NUM_MARGIN;
- LOG_INFO("curr_num=%d, need_remove_num=%d", curr_num,
- need_remove_devices_num);
+ log::info("curr_num={}, need_remove_num={}", curr_num,
+ need_remove_devices_num);
std::list<section_t>::iterator i = config.sections.begin();
while (i != config.sections.end()) {
@@ -299,7 +301,7 @@
// Moving file I/O to btif context instead of timer callback because
// it usually takes a lot of time to be completed, introducing
// delays during A2DP playback causing blips or choppiness.
- LOG_VERBOSE("");
+ log::verbose("");
btif_transfer_context(device_iot_config_write,
IOT_CONFIG_SAVE_TIMER_FIRED_EVT, NULL, 0, NULL);
}
diff --git a/system/device/src/esco_parameters.cc b/system/device/src/esco_parameters.cc
index 15f1397..75e9d82 100644
--- a/system/device/src/esco_parameters.cc
+++ b/system/device/src/esco_parameters.cc
@@ -19,12 +19,14 @@
#include "device/include/esco_parameters.h"
#include <android_bluetooth_flags.h>
+#include <bluetooth/log.h>
-#include "base/logging.h"
#include "check.h"
#include "hci/controller_interface.h"
#include "main/shim/entry.h"
+using namespace bluetooth;
+
static const enh_esco_params_t default_esco_parameters[ESCO_NUM_CODECS] = {
// CVSD D1
{
@@ -334,13 +336,13 @@
if (IS_FLAG_ENABLED(use_dsp_codec_when_controller_does_not_support)) {
auto controller = bluetooth::shim::GetController();
if (controller == nullptr) {
- LOG_WARN("controller is null");
+ log::warn("controller is null");
} else {
codecIds = controller->GetLocalSupportedBrEdrCodecIds();
if (std::find(codecIds.begin(), codecIds.end(), ESCO_CODING_FORMAT_LC3) ==
codecIds.end()) {
if (codec == ESCO_CODEC_LC3_T1 || codec == ESCO_CODEC_LC3_T2) {
- LOG_INFO("BT controller does not support LC3 codec, use DSP codec");
+ log::info("BT controller does not support LC3 codec, use DSP codec");
enh_esco_params_t param = default_esco_parameters[codec];
param.input_coding_format.coding_format = ESCO_CODING_FORMAT_LC3;
param.output_coding_format.coding_format = ESCO_CODING_FORMAT_LC3;
diff --git a/system/device/src/interop.cc b/system/device/src/interop.cc
index 69dd8a2..f7ca236 100644
--- a/system/device/src/interop.cc
+++ b/system/device/src/interop.cc
@@ -23,6 +23,7 @@
#include <assert.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <ctype.h>
#include <fcntl.h>
#include <hardware/bluetooth.h>
@@ -50,6 +51,8 @@
#include "osi/include/osi.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
#ifdef __ANDROID__
static const char* INTEROP_DYNAMIC_FILE_PATH =
"/data/misc/bluedroid/interop_database_dynamic.conf";
@@ -186,6 +189,11 @@
} interop_db_entry_t;
+namespace fmt {
+template <>
+struct formatter<interop_bl_type> : enum_formatter<interop_bl_type> {};
+} // namespace fmt
+
static const char* interop_feature_string_(const interop_feature_t feature);
static void interop_free_entry_(void* data);
static void interop_lazy_init_(void);
@@ -266,8 +274,8 @@
}
void interop_database_clear() {
- LOG_DEBUG("interop_is_initialized: %d interop_list: %p",
- interop_is_initialized, interop_list);
+ log::debug("interop_is_initialized: {} interop_list: {}",
+ interop_is_initialized, fmt::ptr(interop_list));
if (interop_is_initialized && interop_list) {
for (int feature = BEGINNING_OF_INTEROP_LIST;
@@ -278,7 +286,7 @@
}
static void interop_init_feature_name_id_map() {
- LOG_DEBUG("");
+ log::debug("");
feature_name_id_map.clear();
@@ -422,8 +430,8 @@
if (!stat(INTEROP_STATIC_FILE_PATH, &sts) && sts.st_size) {
if (!(config_static = config_new(INTEROP_STATIC_FILE_PATH))) {
- LOG_WARN("unable to load static config file for : %s",
- INTEROP_STATIC_FILE_PATH);
+ log::warn("unable to load static config file for : {}",
+ INTEROP_STATIC_FILE_PATH);
}
}
if (!config_static && !(config_static = config_new_empty())) {
@@ -432,8 +440,8 @@
if (!stat(INTEROP_DYNAMIC_FILE_PATH, &sts) && sts.st_size) {
if (!(config_dynamic = config_new(INTEROP_DYNAMIC_FILE_PATH))) {
- LOG_WARN("unable to load dynamic config file for : %s",
- INTEROP_DYNAMIC_FILE_PATH);
+ log::warn("unable to load dynamic config file for : {}",
+ INTEROP_DYNAMIC_FILE_PATH);
}
}
if (!config_dynamic && !(config_dynamic = config_new_empty())) {
@@ -497,7 +505,7 @@
auto it = feature_name_id_map.find(std::string(feature_name));
if (it == feature_name_id_map.end()) {
- LOG_WARN("feature does not exist: %s", feature_name);
+ log::warn("feature does not exist: {}", feature_name);
return -1;
}
@@ -601,7 +609,7 @@
break;
}
default:
- LOG_ERROR("bl_type: %d not handled", db_entry->bl_type);
+ log::error("bl_type: {} not handled", db_entry->bl_type);
status = false;
break;
}
@@ -627,7 +635,7 @@
if (match_found) {
// return as the entry is already present
- LOG_DEBUG("Entry is already present in the list");
+ log::debug("Entry is already present in the list");
return;
}
@@ -766,7 +774,7 @@
break;
}
default:
- LOG_ERROR("bl_type: %d not handled", db_entry->bl_type);
+ log::error("bl_type: {} not handled", db_entry->bl_type);
break;
}
@@ -786,7 +794,7 @@
if (!interop_database_match(
entry, &ret_entry,
(interop_entry_type)(INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_ERROR("Entry not found in the list");
+ log::error("Entry not found in the list");
return false;
}
@@ -916,7 +924,7 @@
len = (strlen(key) + 1) / 3;
if (len < 3 || len > 4) {
- LOG_WARN("Ignoring as invalid entry for Address %s", key);
+ log::warn("Ignoring as invalid entry for Address {}", key);
return false;
}
@@ -925,8 +933,8 @@
for (int i = 6; i > len; i--) bdstr.append(append_str);
if (!RawAddress::FromString(bdstr, addr)) {
- LOG_WARN(
- "key %s or Bluetooth Address %s is invalid, not added to interop "
+ log::warn(
+ "key {} or Bluetooth Address {} is invalid, not added to interop "
"list",
key, ADDRESS_TO_LOGGABLE_CSTR(addr));
return false;
@@ -943,7 +951,7 @@
} else if (!strncasecmp(value, NAME_BASED, strlen(NAME_BASED))) {
if (strlen(key) > KEY_MAX_LENGTH - 1) {
- LOG_WARN("ignoring %s due to invalid length", key);
+ log::warn("ignoring {} due to invalid length", key);
return false;
}
interop_db_entry_t* entry =
@@ -960,8 +968,8 @@
uint16_t manufacturer;
if (strlen(key) != VALID_MNFR_STR_LEN) {
- LOG_WARN("ignoring %s due to invalid Manufacturer id in config file",
- key);
+ log::warn("ignoring {} due to invalid Manufacturer id in config file",
+ key);
return false;
}
@@ -981,14 +989,14 @@
char tmp_key[VALID_VNDR_PRDT_LEN + 1] = {'\0'};
if (strlen(key) != VALID_VNDR_PRDT_LEN) {
- LOG_WARN("ignoring %s due to invalid vendor/product id in config file",
- key);
+ log::warn("ignoring {} due to invalid vendor/product id in config file",
+ key);
return false;
}
strlcpy(tmp_key, key, VALID_VNDR_PRDT_LEN + 1);
if (!get_vendor_product_id(tmp_key, &vendor_id, &product_id)) {
- LOG_WARN("Error in parsing vendor/product id %s", key);
+ log::warn("Error in parsing vendor/product id {}", key);
return false;
}
@@ -1007,14 +1015,14 @@
char bdaddr_str[KEY_MAX_LENGTH] = {'\0'};
if (strlen(key) != VALID_SSR_LAT_LEN) {
- LOG_WARN("ignoring %s due to invalid key for ssr max lat in config file",
- key);
+ log::warn("ignoring {} due to invalid key for ssr max lat in config file",
+ key);
return false;
}
strlcpy(tmp_key, key, KEY_MAX_LENGTH);
if (!get_addr_maxlat(tmp_key, bdaddr_str, &max_lat)) {
- LOG_WARN("Error in parsing address and max_lat %s", key);
+ log::warn("Error in parsing address and max_lat {}", key);
return false;
}
@@ -1022,7 +1030,7 @@
len = (strlen(bdaddr_str) + 1) / 3;
if (len != 3) {
- LOG_WARN("Ignoring as invalid entry for Address %s", bdaddr_str);
+ log::warn("Ignoring as invalid entry for Address {}", bdaddr_str);
return false;
}
@@ -1033,8 +1041,8 @@
bdstr.append(append_str);
if (!RawAddress::FromString(bdstr, addr)) {
- LOG_WARN(
- "key %s or Bluetooth Address %s is invalid, not added to interop "
+ log::warn(
+ "key {} or Bluetooth Address {} is invalid, not added to interop "
"list",
key, ADDRESS_TO_LOGGABLE_CSTR(addr));
return false;
@@ -1052,7 +1060,7 @@
uint16_t version;
if (strlen(key) != VALID_VERSION_LEN) {
- LOG_WARN("ignoring %s due to invalid version in config file", key);
+ log::warn("ignoring {} due to invalid version in config file", key);
return false;
}
@@ -1073,14 +1081,14 @@
char bdaddr_str[KEY_MAX_LENGTH] = {'\0'};
if (strlen(key) != VALID_LMP_VERSION_LEN) {
- LOG_WARN("ignoring %s due to invalid key for lmp ver in config file",
- key);
+ log::warn("ignoring {} due to invalid key for lmp ver in config file",
+ key);
return false;
}
strlcpy(tmp_key, key, KEY_MAX_LENGTH);
if (!get_addr_lmp_ver(tmp_key, bdaddr_str, &lmp_ver, &lmp_sub_ver)) {
- LOG_WARN("Error in parsing address and lmp_ver %s", key);
+ log::warn("Error in parsing address and lmp_ver {}", key);
return false;
}
@@ -1088,7 +1096,7 @@
len = (strlen(bdaddr_str) + 1) / 3;
if (len != 3) {
- LOG_WARN("Ignoring as invalid entry for Address %s", bdaddr_str);
+ log::warn("Ignoring as invalid entry for Address {}", bdaddr_str);
return false;
}
@@ -1099,8 +1107,8 @@
bdstr.append(append_str);
if (!RawAddress::FromString(bdstr, addr)) {
- LOG_WARN(
- "key %s or Bluetooth Address %s is invalid, not added to interop "
+ log::warn(
+ "key {} or Bluetooth Address {} is invalid, not added to interop "
"list",
key, ADDRESS_TO_LOGGABLE_CSTR(addr));
return false;
@@ -1121,15 +1129,16 @@
char tmp_key[KEY_MAX_LENGTH] = {'\0'};
if (strlen(key) != VALID_ADDR_RANGE_LEN) {
- LOG_WARN("Ignoring as invalid entry for Address range %s", key);
+ log::warn("Ignoring as invalid entry for Address range {}", key);
return false;
}
strlcpy(tmp_key, key, VALID_ADDR_RANGE_LEN + 1);
if (!get_addr_range(tmp_key, &addr_start, &addr_end)) {
- LOG_WARN("key: %s addr_start %s or addr end %s is added to interop list",
- key, ADDRESS_TO_LOGGABLE_CSTR(addr_start),
- ADDRESS_TO_LOGGABLE_CSTR(addr_end));
+ log::warn(
+ "key: {} addr_start {} or addr end {} is added to interop list", key,
+ ADDRESS_TO_LOGGABLE_CSTR(addr_start),
+ ADDRESS_TO_LOGGABLE_CSTR(addr_end));
return false;
}
@@ -1144,7 +1153,7 @@
interop_database_add_(entry, false);
}
- LOG_VERBOSE("feature:: %d, key :: %s, value :: %s", feature, key, value);
+ log::verbose("feature:: {}, key :: {}, value :: {}", feature, key, value);
return true;
}
@@ -1152,7 +1161,7 @@
int init_status = interop_config_init();
if (init_status == -1) {
- LOG_ERROR("Error in initializing interop static config file");
+ log::error("Error in initializing interop static config file");
return;
}
@@ -1304,8 +1313,8 @@
&entry, NULL,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN(
- "Device with manufacturer id: %d is a match for interop workaround %s",
+ log::warn(
+ "Device with manufacturer id: {} is a match for interop workaround {}",
manufacturer, interop_feature_string_(feature));
return true;
}
@@ -1330,8 +1339,8 @@
&entry, NULL,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN("Device with name: %s is a match for interop workaround %s", name,
- interop_feature_string_(feature));
+ log::warn("Device with name: {} is a match for interop workaround {}", name,
+ interop_feature_string_(feature));
return true;
}
@@ -1353,8 +1362,9 @@
&entry, NULL,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN("Device %s is a match for interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a match for interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
return true;
}
@@ -1365,8 +1375,9 @@
if (interop_database_match(&entry, NULL,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC))) {
- LOG_WARN("Device %s is a match for interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a match for interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
return true;
}
@@ -1386,9 +1397,9 @@
&entry, NULL,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN(
- "Device with vendor_id: %d product_id: %d is a match for interop "
- "workaround %s",
+ log::warn(
+ "Device with vendor_id: {} product_id: {} is a match for interop "
+ "workaround {}",
vendor_id, product_id, interop_feature_string_(feature));
return true;
}
@@ -1411,8 +1422,9 @@
&entry, &ret_entry,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN("Device %s is a match for interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a match for interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
*max_lat = ret_entry->entry_type.ssr_max_lat_entry.max_lat;
return true;
}
@@ -1432,8 +1444,9 @@
&entry, NULL,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN("Device with version: 0x%04x is a match for interop workaround %s",
- version, interop_feature_string_(feature));
+ log::warn(
+ "Device with version: 0x{:04x} is a match for interop workaround {}",
+ version, interop_feature_string_(feature));
return true;
}
@@ -1456,8 +1469,9 @@
&entry, &ret_entry,
(interop_entry_type)(INTEROP_ENTRY_TYPE_STATIC |
INTEROP_ENTRY_TYPE_DYNAMIC))) {
- LOG_WARN("Device %s is a match for interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a match for interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
*lmp_ver = ret_entry->entry_type.lmp_version_entry.lmp_ver;
*lmp_sub_ver = ret_entry->entry_type.lmp_version_entry.lmp_sub_ver;
return true;
@@ -1478,8 +1492,8 @@
entry.entry_type.name_entry.feature = (interop_feature_t)feature;
entry.entry_type.name_entry.length = strlen(entry.entry_type.name_entry.name);
if (interop_database_remove_(&entry)) {
- LOG_WARN("Device with name: %s is removed from interop workaround %s", name,
- interop_feature_string_(feature));
+ log::warn("Device with name: {} is removed from interop workaround {}",
+ name, interop_feature_string_(feature));
return true;
}
@@ -1495,8 +1509,8 @@
entry.entry_type.mnfr_entry.feature = feature;
entry.entry_type.mnfr_entry.manufacturer = manufacturer;
if (interop_database_remove_(&entry)) {
- LOG_WARN(
- "Device with manufacturer id: %d is removed from interop workaround %s",
+ log::warn(
+ "Device with manufacturer id: {} is removed from interop workaround {}",
manufacturer, interop_feature_string_(feature));
return true;
}
@@ -1516,8 +1530,9 @@
entry.entry_type.addr_entry.feature = (interop_feature_t)feature;
entry.entry_type.addr_entry.length = sizeof(RawAddress);
if (interop_database_remove_(&entry)) {
- LOG_WARN("Device %s is a removed from interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a removed from interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
return true;
}
@@ -1587,7 +1602,7 @@
for (const section_t& sec : config_dynamic.get()->sections) {
if (feature == interop_feature_name_to_feature_id(sec.name.c_str())) {
- LOG_WARN("found feature - %s", interop_feature_string_(feature));
+ log::warn("found feature - {}", interop_feature_string_(feature));
interop_config_remove_section(sec.name);
return true;
}
@@ -1609,9 +1624,9 @@
entry.entry_type.vnr_pdt_entry.product_id = product_id;
if (interop_database_remove_(&entry)) {
- LOG_WARN(
- "Device with vendor_id: %d product_id: %d is removed from interop "
- "workaround %s",
+ log::warn(
+ "Device with vendor_id: {} product_id: {} is removed from interop "
+ "workaround {}",
vendor_id, product_id, interop_feature_string_(feature));
return true;
}
@@ -1631,8 +1646,9 @@
entry.entry_type.ssr_max_lat_entry.max_lat = max_lat;
if (interop_database_remove_(&entry)) {
- LOG_WARN("Device %s is a removed from interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a removed from interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
return true;
}
return false;
@@ -1649,8 +1665,8 @@
entry.entry_type.version_entry.version = version;
if (interop_database_remove_(&entry)) {
- LOG_WARN(
- "Device with version: 0x%04x is removed from interop workaround %s",
+ log::warn(
+ "Device with version: 0x{:04x} is removed from interop workaround {}",
version, interop_feature_string_(feature));
return true;
}
@@ -1672,8 +1688,9 @@
entry.entry_type.lmp_version_entry.lmp_sub_ver = lmp_sub_ver;
if (interop_database_remove_(&entry)) {
- LOG_WARN("Device %s is a removed from interop workaround %s.",
- ADDRESS_TO_LOGGABLE_CSTR(*addr), interop_feature_string_(feature));
+ log::warn("Device {} is a removed from interop workaround {}.",
+ ADDRESS_TO_LOGGABLE_CSTR(*addr),
+ interop_feature_string_(feature));
return true;
}
return false;
@@ -1690,7 +1707,7 @@
for (const section_t& sec : config->sections) {
if (INTEROP_BROWSE_PLAYER_ALLOW_LIST ==
interop_feature_name_to_feature_id(sec.name.c_str())) {
- LOG_WARN("found feature - %s", sec.name.c_str());
+ log::warn("found feature - {}", sec.name);
for (const entry_t& entry : sec.entries) {
list_append(media_player_list, (void*)(new std::string(entry.key)));
}
diff --git a/system/gd/Android.bp b/system/gd/Android.bp
index 37f5666..cf5004a 100644
--- a/system/gd/Android.bp
+++ b/system/gd/Android.bp
@@ -387,15 +387,11 @@
host: {
srcs: [
":BluetoothHalTestSources_hci_host",
- ":BluetoothHostTestingLogCapture",
- ":BluetoothHostTestingLogCaptureTest",
":BluetoothOsTestSources_host",
],
},
android: {
srcs: [
- ":BluetoothAndroidTestingLogCapture",
- ":BluetoothAndroidTestingLogCaptureTest",
":BluetoothHalTestSources_hci_android_hidl",
":BluetoothOsTestSources_android",
],
@@ -791,106 +787,3 @@
"wakelock_manager_generated.h",
],
}
-
-cc_defaults {
- name: "bluetooth_py3_native_extension_defaults",
- include_dirs: [
- "external/python/cpython3/Include",
- ],
- target: {
- android: {
- include_dirs: ["external/python/cpython3/android/bionic/pyconfig"],
- },
- android_arm: {
- cflags: ["-DSOABI=\"cpython-38android-arm-android-bionic\""],
- suffix: ".cpython-38android-arm-android-bionic",
- },
- android_arm64: {
- cflags: ["-DSOABI=\"cpython-38android-arm64-android-bionic\""],
- suffix: ".cpython-38android-arm64-android-bionic",
- },
- android_x86: {
- cflags: ["-DSOABI=\"cpython-38android-x86-android-bionic\""],
- suffix: ".cpython-38android-x86-android-bionic",
- },
- android_x86_64: {
- cflags: ["-DSOABI=\"cpython-38android-x86_64-android-bionic\""],
- suffix: ".cpython-38android-x86_64-android-bionic",
- },
- // Regenerate include dirs with android_regen.sh
- darwin_x86_64: {
- include_dirs: ["external/python/cpython3/android/darwin_x86_64/pyconfig"],
- cflags: [
- "-DSOABI=\"cpython-38android-x86_64-darwin\"",
- "-Wno-deprecated-declarations",
- "-Wno-pointer-arith",
- ],
- suffix: ".cpython-38android-x86_64-darwin",
- },
- linux_bionic: {
- // NB linux_bionic is a 'host' architecture but it uses the bionic libc like 'android'
- // targets so use the android pyconfig.
- include_dirs: ["external/python/cpython3/android/bionic/pyconfig"],
- cflags: ["-DSOABI=\"cpython-38android-x86_64-linux-bionic\""],
- suffix: ".cpython-38android-x86_64-linux-bionic",
- },
- linux_glibc_x86: {
- enabled: false,
- },
- linux_glibc_x86_64: {
- include_dirs: ["external/python/cpython3/android/linux_x86_64/pyconfig"],
- cflags: ["-DSOABI=\"cpython-38android-x86_64-linux-gnu\""],
- // Commenting out the Linux suffix so that cpython-38-x86_64-linux-gnu
- // Python 3.8 can also import the untagged .so library per PEP 3149
- // Keep this change until Android py3-cmd can run ACTS, gRPC and can
- // Export Python native symbols such as PyType_Type
- // suffix: ".cpython-38android-x86_64-linux-gnu",
- },
- linux_musl_x86: {
- enabled: false,
- },
- linux_musl_x86_64: {
- include_dirs: ["external/python/cpython3/android/linux_x86_64/pyconfig"],
- cflags: ["-DSOABI=\"cpython-38android-x86_64-linux-gnu\""],
- // Commenting out the Linux suffix so that cpython-38-x86_64-linux-gnu
- // Python 3.8 can also import the untagged .so library per PEP 3149
- // Keep this change until Android py3-cmd can run ACTS, gRPC and can
- // Export Python native symbols such as PyType_Type
- // suffix: ".cpython-38android-x86_64-linux-gnu",
- },
- windows: {
- enabled: false,
- },
- },
- allow_undefined_symbols: true,
-}
-
-cc_library_host_shared {
- name: "bluetooth_packets_python3",
- defaults: [
- "bluetooth_py3_native_extension_defaults",
- "gd_defaults",
- ],
- srcs: [
- ":BluetoothPacketSources",
- "common/strings.cc",
- "l2cap/fcs.cc",
- "packet/python3_module.cc",
-
- ],
- generated_sources: [
- "BluetoothGeneratedPackets_python3_cc",
- ],
- header_libs: [
- "pybind11_headers",
- ],
- static_libs: [
- "libbase",
- "libbluetooth_l2cap_pdl",
- "libbluetooth_log",
- ],
- cflags: [
- "-fexceptions",
- ],
- rtti: true,
-}
diff --git a/system/gd/cert/bluetooth_packets_python3_setup.py b/system/gd/cert/bluetooth_packets_python3_setup.py
deleted file mode 100644
index 26257c6..0000000
--- a/system/gd/cert/bluetooth_packets_python3_setup.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python3
-#
-# Copyright 2019 - The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Usage:
-# 1. Run envsetup and lunch first in an Android checkout
-# 2. Make target bluetooth_packets_python3 that will generate C++ sources for the
-# Extension
-# 3. Build only:
-# python3 bluetooth_packets_python3_setup.py build_ext
-# Then Find the .so file in build/lib.linux-x86_64-3.X
-# 4. Install:
-# python3 bluetooth_packets_python3_setup.py install --user
-
-import os
-import glob
-from setuptools import setup, Extension
-
-ANDROID_BUILD_TOP = os.getenv("ANDROID_BUILD_TOP")
-PYBIND11_INCLUDE_DIR = os.path.join(ANDROID_BUILD_TOP, "external/python/pybind11/include")
-GD_DIR = os.path.join(ANDROID_BUILD_TOP, "packages/modules/Bluetooth/system/gd")
-BT_PACKETS_GEN_DIR = os.path.join(
- ANDROID_BUILD_TOP,
- "out/soong/.intermediates/packages/modules/Bluetooth/system/pdl/l2cap/BluetoothGeneratedPacketsL2cap_h/gen")
-BT_PACKETS_PY3_GEN_DIR = os.path.join(
- ANDROID_BUILD_TOP,
- "out/soong/.intermediates/packages/modules/Bluetooth/system/gd/BluetoothGeneratedPackets_python3_cc/gen")
-
-BT_PACKETS_BASE_SRCS = [
- os.path.join(GD_DIR, "l2cap/fcs.cc"),
- os.path.join(GD_DIR, "packet/bit_inserter.cc"),
- os.path.join(GD_DIR, "packet/byte_inserter.cc"),
- os.path.join(GD_DIR, "packet/byte_observer.cc"),
- os.path.join(GD_DIR, "packet/iterator.cc"),
- os.path.join(GD_DIR, "packet/fragmenting_inserter.cc"),
- os.path.join(GD_DIR, "packet/packet_view.cc"),
- os.path.join(GD_DIR, "packet/raw_builder.cc"),
- os.path.join(GD_DIR, "packet/view.cc"),
-]
-
-BT_PACKETS_PY3_SRCs = \
- [os.path.join(GD_DIR, "packet/python3_module.cc")] \
- + glob.glob(os.path.join(BT_PACKETS_PY3_GEN_DIR, "l2cap", "*.cc")) \
-
-bluetooth_packets_python3_module = Extension(
- 'bluetooth_packets_python3',
- sources=BT_PACKETS_BASE_SRCS + BT_PACKETS_PY3_SRCs,
- include_dirs=[GD_DIR, BT_PACKETS_GEN_DIR, BT_PACKETS_PY3_GEN_DIR, PYBIND11_INCLUDE_DIR],
- extra_compile_args=['-std=c++17'])
-
-setup(
- name='bluetooth_packets_python3',
- version='1.0',
- author="Android Open Source Project",
- description="""Bluetooth Packet Library""",
- ext_modules=[bluetooth_packets_python3_module],
- py_modules=["bluetooth_packets_python3"],
-)
diff --git a/system/gd/cert/run b/system/gd/cert/run
index 7e3db40..4aa006d 100755
--- a/system/gd/cert/run
+++ b/system/gd/cert/run
@@ -81,8 +81,8 @@
TEST_CONFIG="${ANDROID_BUILD_TOP}/packages/modules/Bluetooth/system/blueberry/tests/gd/host_config.yaml"
TEST_FILTER="--presubmit"
TEST_RUNNER="blueberry/tests/gd/gd_test_runner.py"
-CPP_BUILD_TARGET="bluetooth_stack_with_facade root-canal bluetooth_packets_python3 gd_hci_packets_python3_gen gd_smp_packets_python3_gen"
-RUST_BUILD_TARGET="bluetooth_with_facades root-canal bluetooth_packets_python3 bt_topshim_facade gd_hci_packets_python3_gen gd_smp_packets_python3_gen"
+CPP_BUILD_TARGET="bluetooth_stack_with_facade root-canal gd_hci_packets_python3_gen gd_smp_packets_python3_gen"
+RUST_BUILD_TARGET="bluetooth_with_facades root-canal bt_topshim_facade gd_hci_packets_python3_gen gd_smp_packets_python3_gen"
BUILD_TARGET=$CPP_BUILD_TARGET
CLEAN_VENV=false
@@ -344,8 +344,6 @@
cp {$HOST_BIN,$DEST_DIR}/bt_topshim_facade
cp {$HOST_BIN,$DEST_DIR}/root-canal
- cp {$HOST_LIB,$DEST_DIR}/bluetooth_packets_python3.so
-
cp {$HOST_LIB,$DEST_LIB_DIR}/libbase.so
cp {$HOST_LIB,$DEST_LIB_DIR}/libbluetooth_gd.so
cp {$HOST_LIB,$DEST_LIB_DIR}/libc++.so
@@ -385,15 +383,6 @@
exit 1
fi
-"${CERT_TEST_VENV}/bin/python" -c "
-import bluetooth_packets_python3 as bp3
-bp3.BaseStruct
-"
-if [[ $? -ne 0 ]] ; then
- echo -e "${RED}Setup failed as bluetooth_packets_python3 cannot be imported${NOCOLOR}"
- exit 1
-fi
-
if [ "${VERBOSE_MODE}" == true ] ; then
TEMP_CONFIG=/tmp/temp_mobly_config.yaml
cat "${TEST_CONFIG}" | "${CERT_TEST_VENV}/bin/python" -c "
diff --git a/system/gd/common/metric_id_manager.cc b/system/gd/common/metric_id_manager.cc
index 0815986..76c74f9 100644
--- a/system/gd/common/metric_id_manager.cc
+++ b/system/gd/common/metric_id_manager.cc
@@ -17,6 +17,10 @@
******************************************************************************/
#define LOG_TAG "BluetoothMetricIdManager"
+#include "common/metric_id_manager.h"
+
+#include <bluetooth/log.h>
+
#include <functional>
#include <iterator>
#include <mutex>
@@ -24,7 +28,6 @@
#include <thread>
#include "os/log.h"
-#include "common/metric_id_manager.h"
namespace bluetooth {
namespace common {
@@ -58,10 +61,10 @@
// init paired_devices_map
if (paired_device_map.size() > kMaxNumPairedDevicesInMemory) {
- LOG_ALWAYS_FATAL(
- "Paired device map has size %zu, which is bigger than "
- "kMaxNumPairedDevicesInMemory %zu",
- paired_device_map.size(), kMaxNumPairedDevicesInMemory);
+ log::fatal(
+ "Paired device map has size {}, which is bigger than kMaxNumPairedDevicesInMemory {}",
+ paired_device_map.size(),
+ kMaxNumPairedDevicesInMemory);
// fail loudly to let caller know
return false;
}
@@ -69,9 +72,8 @@
next_id_ = kMinId;
for (const auto& p : paired_device_map) {
if (p.second < kMinId || p.second > kMaxId) {
- LOG_ALWAYS_FATAL(
- "Invalid Bluetooth Metric Id in config. "
- "Id %d of %s is out of range [%d, %d]",
+ log::fatal(
+ "Invalid Bluetooth Metric Id in config. Id {} of {} is out of range [{}, {}]",
p.second,
ADDRESS_TO_LOGGABLE_CSTR(p.first),
kMinId,
@@ -138,7 +140,7 @@
next_id_++;
if (next_id_ > kMaxId) {
next_id_ = kMinId;
- LOG_WARN("Bluetooth metric id overflow.");
+ log::warn("Bluetooth metric id overflow.");
}
}
int id = next_id_++;
@@ -161,13 +163,12 @@
return true;
}
if (!temporary_device_cache_.contains(mac_address)) {
- LOG_ERROR("Failed to save device because device is not in "
- "temporary_device_cache_");
+ log::error("Failed to save device because device is not in temporary_device_cache_");
return false;
}
auto opt = temporary_device_cache_.extract(mac_address);
if (!opt) {
- LOG_ERROR("Failed to remove device from temporary_device_cache_");
+ log::error("Failed to remove device from temporary_device_cache_");
return false;
}
int id = opt->second;
@@ -176,7 +177,7 @@
ForgetDevicePostprocess(evicted->first, evicted->second);
}
if (!save_id_callback_(mac_address, id)) {
- LOG_ERROR("Callback returned false after saving the device");
+ log::error("Callback returned false after saving the device");
return false;
}
return true;
@@ -187,7 +188,7 @@
std::lock_guard<std::mutex> lock(id_allocator_mutex_);
auto opt = paired_device_cache_.extract(mac_address);
if (!opt) {
- LOG_ERROR("Failed to remove device from paired_device_cache_");
+ log::error("Failed to remove device from paired_device_cache_");
return;
}
ForgetDevicePostprocess(mac_address, opt->second);
diff --git a/system/gd/common/postable_context.h b/system/gd/common/postable_context.h
new file mode 100644
index 0000000..e44850c
--- /dev/null
+++ b/system/gd/common/postable_context.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "common/bind.h"
+#include "common/contextual_callback.h"
+#include "common/i_postable_context.h"
+
+namespace bluetooth::common {
+
+class PostableContext : public IPostableContext {
+ public:
+ virtual ~PostableContext() = default;
+
+ template <typename Functor, typename... Args>
+ auto BindOnce(Functor&& functor, Args&&... args) {
+ return common::ContextualOnceCallback(
+ common::BindOnce(std::forward<Functor>(functor), std::forward<Args>(args)...), this);
+ }
+
+ template <typename Functor, typename T, typename... Args>
+ auto BindOnceOn(T* obj, Functor&& functor, Args&&... args) {
+ return common::ContextualOnceCallback(
+ common::BindOnce(
+ std::forward<Functor>(functor), common::Unretained(obj), std::forward<Args>(args)...),
+ this);
+ }
+
+ template <typename Functor, typename... Args>
+ auto Bind(Functor&& functor, Args&&... args) {
+ return common::ContextualCallback(
+ common::Bind(std::forward<Functor>(functor), std::forward<Args>(args)...), this);
+ }
+
+ template <typename Functor, typename T, typename... Args>
+ auto BindOn(T* obj, Functor&& functor, Args&&... args) {
+ return common::ContextualCallback(
+ common::Bind(
+ std::forward<Functor>(functor), common::Unretained(obj), std::forward<Args>(args)...),
+ this);
+ }
+};
+
+} // namespace bluetooth::common
diff --git a/system/gd/common/stop_watch.cc b/system/gd/common/stop_watch.cc
index 2d7a9cb..2a64f2c 100644
--- a/system/gd/common/stop_watch.cc
+++ b/system/gd/common/stop_watch.cc
@@ -18,6 +18,8 @@
#include "common/stop_watch.h"
+#include <bluetooth/log.h>
+
#include <iomanip>
#include <mutex>
#include <sstream>
@@ -37,12 +39,13 @@
void StopWatch::RecordLog(StopWatchLog log) {
std::unique_lock<std::recursive_mutex> lock(stopwatch_log_mutex, std::defer_lock);
if (!lock.try_lock()) {
- LOG_INFO("try_lock fail. log content: %s, took %zu us", log.message.c_str(),
- static_cast<size_t>(
- std::chrono::duration_cast<std::chrono::microseconds>(
- stopwatch_logs[current_buffer_index].end_timestamp -
- stopwatch_logs[current_buffer_index].start_timestamp)
- .count()));
+ log::info(
+ "try_lock fail. log content: {}, took {} us",
+ log.message,
+ static_cast<size_t>(std::chrono::duration_cast<std::chrono::microseconds>(
+ stopwatch_logs[current_buffer_index].end_timestamp -
+ stopwatch_logs[current_buffer_index].start_timestamp)
+ .count()));
return;
}
if (current_buffer_index >= LOG_BUFFER_LENGTH) {
@@ -55,8 +58,8 @@
void StopWatch::DumpStopWatchLog() {
std::lock_guard<std::recursive_mutex> lock(stopwatch_log_mutex);
- LOG_INFO("=-----------------------------------=");
- LOG_INFO("bluetooth stopwatch log history:");
+ log::info("=-----------------------------------=");
+ log::info("bluetooth stopwatch log history:");
for (int i = 0; i < LOG_BUFFER_LENGTH; i++) {
if (current_buffer_index >= LOG_BUFFER_LENGTH) {
current_buffer_index = 0;
@@ -74,17 +77,17 @@
ss << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %H:%M:%S");
ss << '.' << std::setfill('0') << std::setw(3) << millis.count();
std::string start_timestamp = ss.str();
- LOG_INFO(
- "%s: %s: took %zu us",
- start_timestamp.c_str(),
- stopwatch_logs[current_buffer_index].message.c_str(),
+ log::info(
+ "{}: {}: took {} us",
+ start_timestamp,
+ stopwatch_logs[current_buffer_index].message,
static_cast<size_t>(std::chrono::duration_cast<std::chrono::microseconds>(
stopwatch_logs[current_buffer_index].end_timestamp -
stopwatch_logs[current_buffer_index].start_timestamp)
.count()));
current_buffer_index++;
}
- LOG_INFO("=-----------------------------------=");
+ log::info("=-----------------------------------=");
}
StopWatch::StopWatch(std::string text)
diff --git a/system/gd/common/strings.cc b/system/gd/common/strings.cc
index c79516a..361bbe3 100644
--- a/system/gd/common/strings.cc
+++ b/system/gd/common/strings.cc
@@ -16,6 +16,8 @@
#include "common/strings.h"
+#include <bluetooth/log.h>
+
#include <algorithm>
#include <charconv>
#include <cstdlib>
@@ -54,11 +56,11 @@
std::optional<std::vector<uint8_t>> FromHexString(const std::string& str) {
if (str.size() % 2 != 0) {
- LOG_INFO("str size is not divisible by 2, size is %zu", str.size());
+ log::info("str size is not divisible by 2, size is {}", str.size());
return std::nullopt;
}
if (std::find_if_not(str.begin(), str.end(), IsHexDigit{}) != str.end()) {
- LOG_INFO("value contains none hex digit");
+ log::info("value contains none hex digit");
return std::nullopt;
}
std::vector<uint8_t> value;
@@ -67,7 +69,7 @@
uint8_t v = 0;
auto ret = std::from_chars(str.c_str() + i, str.c_str() + i + 2, v, 16);
if (std::make_error_code(ret.ec)) {
- LOG_INFO("failed to parse hex char at index %zu", i);
+ log::info("failed to parse hex char at index {}", i);
return std::nullopt;
}
value.push_back(v);
@@ -115,15 +117,15 @@
errno = 0;
int64_t value = std::strtoll(str.c_str(), &ptr, 10);
if (errno != 0) {
- LOG_INFO("cannot parse string '%s' with error '%s'", str.c_str(), strerror(errno));
+ log::info("cannot parse string '{}' with error '{}'", str, strerror(errno));
return std::nullopt;
}
if (ptr == str.c_str()) {
- LOG_INFO("string '%s' is empty or has wrong format", str.c_str());
+ log::info("string '{}' is empty or has wrong format", str);
return std::nullopt;
}
if (ptr != (str.c_str() + str.size())) {
- LOG_INFO("cannot parse whole string '%s'", str.c_str());
+ log::info("cannot parse whole string '{}'", str);
return std::nullopt;
}
return value;
@@ -135,22 +137,22 @@
std::optional<uint64_t> Uint64FromString(const std::string& str) {
if (str.find('-') != std::string::npos) {
- LOG_INFO("string '%s' contains minus sign, this function is for unsigned", str.c_str());
+ log::info("string '{}' contains minus sign, this function is for unsigned", str);
return std::nullopt;
}
char* ptr = nullptr;
errno = 0;
uint64_t value = std::strtoull(str.c_str(), &ptr, 10);
if (errno != 0) {
- LOG_INFO("cannot parse string '%s' with error '%s'", str.c_str(), strerror(errno));
+ log::info("cannot parse string '{}' with error '{}'", str, strerror(errno));
return std::nullopt;
}
if (ptr == str.c_str()) {
- LOG_INFO("string '%s' is empty or has wrong format", str.c_str());
+ log::info("string '{}' is empty or has wrong format", str);
return std::nullopt;
}
if (ptr != (str.c_str() + str.size())) {
- LOG_INFO("cannot parse whole string '%s'", str.c_str());
+ log::info("cannot parse whole string '{}'", str);
return std::nullopt;
}
return value;
@@ -166,7 +168,7 @@
} else if (str == "false") {
return false;
} else {
- LOG_INFO("string '%s' is neither true nor false", str.c_str());
+ log::info("string '{}' is neither true nor false", str);
return std::nullopt;
}
}
diff --git a/system/gd/common/strings_test.cc b/system/gd/common/strings_test.cc
index ddc03c3..b68507f 100644
--- a/system/gd/common/strings_test.cc
+++ b/system/gd/common/strings_test.cc
@@ -16,6 +16,7 @@
#include "common/strings.h"
+#include <bluetooth/log.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -74,7 +75,7 @@
ASSERT_EQ(ToHexString(LONG_MIN), "LONG_MIN");
ASSERT_EQ(ToHexString(LONG_MIN + 1L), "-0x7fffffffffffffff");
} else {
- LOG_ERROR("Unknown architecture");
+ bluetooth::log::error("Unknown architecture");
ASSERT_TRUE(false);
}
ASSERT_EQ(ToHexString('a'), "0x61");
diff --git a/system/gd/common/testing/Android.bp b/system/gd/common/testing/Android.bp
deleted file mode 100644
index a4c795d..0000000
--- a/system/gd/common/testing/Android.bp
+++ /dev/null
@@ -1,36 +0,0 @@
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "system_bt_license"
- // to get the below license kinds:
- // SPDX-license-identifier-Apache-2.0
- default_applicable_licenses: ["system_bt_license"],
-}
-
-filegroup {
- name: "BluetoothAndroidTestingLogCapture",
- srcs: [
- "android/log_capture.cc",
- ],
-}
-
-filegroup {
- name: "BluetoothAndroidTestingLogCaptureTest",
- srcs: [
- "android/log_capture_test.cc",
- ],
-}
-
-filegroup {
- name: "BluetoothHostTestingLogCapture",
- srcs: [
- "host/log_capture.cc",
- ],
-}
-
-filegroup {
- name: "BluetoothHostTestingLogCaptureTest",
- srcs: [
- "host/log_capture_test.cc",
- ],
-}
diff --git a/system/gd/common/testing/android/log_capture.cc b/system/gd/common/testing/android/log_capture.cc
deleted file mode 100644
index 3b09dc3..0000000
--- a/system/gd/common/testing/android/log_capture.cc
+++ /dev/null
@@ -1,79 +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.
- */
-
-#include "common/testing/log_capture.h"
-
-#include <fcntl.h>
-#include <sys/stat.h>
-
-#include <cstddef>
-#include <string>
-
-#include "os/log.h"
-
-namespace bluetooth {
-namespace testing {
-
-LogCapture::LogCapture() {
- LOG_INFO(
- "Log capture disabled for android build dup_fd:%d fd:%d original_stderr_fd:%d",
- dup_fd_,
- fd_,
- original_stderr_fd_);
-}
-
-LogCapture::~LogCapture() {}
-
-LogCapture* LogCapture::Rewind() {
- return this;
-}
-
-bool LogCapture::Find(const std::string& /* to_find */) {
- // For |atest| assume all log captures succeed
- return true;
-}
-
-void LogCapture::Flush() {}
-
-void LogCapture::Sync() {}
-
-void LogCapture::Reset() {}
-
-std::string LogCapture::Read() {
- return std::string();
-}
-
-size_t LogCapture::Size() const {
- size_t size{0UL};
- return size;
-}
-
-void LogCapture::WaitUntilLogContains(const std::string& /* text */) {}
-
-std::pair<int, int> LogCapture::create_backing_store() const {
- int dup_fd = -1;
- int fd = -1;
- return std::make_pair(dup_fd, fd);
-}
-
-bool LogCapture::set_non_blocking(int /* fd */) const {
- return true;
-}
-
-void LogCapture::clean_up() {}
-
-} // namespace testing
-} // namespace bluetooth
diff --git a/system/gd/common/testing/android/log_capture_test.cc b/system/gd/common/testing/android/log_capture_test.cc
deleted file mode 100644
index a85eac0..0000000
--- a/system/gd/common/testing/android/log_capture_test.cc
+++ /dev/null
@@ -1,41 +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.
- */
-
-#include "../log_capture.h"
-
-#include <gtest/gtest.h>
-
-#include <cstring>
-#include <memory>
-#include <string>
-
-#include "common/init_flags.h"
-#include "os/log.h"
-
-namespace bluetooth {
-namespace testing {
-
-class LogCaptureTest : public ::testing::Test {
- protected:
- void SetUp() override {}
-
- void TearDown() override {}
-};
-
-TEST_F(LogCaptureTest, not_working_over_atest) {}
-
-} // namespace testing
-} // namespace bluetooth
diff --git a/system/gd/common/testing/host/log_capture.cc b/system/gd/common/testing/host/log_capture.cc
deleted file mode 100644
index 7749b8e..0000000
--- a/system/gd/common/testing/host/log_capture.cc
+++ /dev/null
@@ -1,185 +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.
- */
-
-#include "common/testing/log_capture.h"
-
-#include <fcntl.h>
-#include <sys/stat.h>
-
-#include <cstddef>
-#include <sstream>
-#include <string>
-
-#include "os/log.h"
-
-namespace {
-constexpr char kTempFilename[] = "/tmp/bt_gtest_log_capture-XXXXXX";
-constexpr size_t kTempFilenameMaxSize = 64;
-constexpr size_t kBufferSize = 4096;
-constexpr int kStandardErrorFd = STDERR_FILENO;
-} // namespace
-
-namespace bluetooth {
-namespace testing {
-
-LogCapture::LogCapture() {
- std::tie(dup_fd_, fd_) = create_backing_store();
- if (dup_fd_ == -1 || fd_ == -1) {
- LOG_ERROR("Unable to create backing storage : %s", strerror(errno));
- return;
- }
- if (!set_non_blocking(dup_fd_)) {
- LOG_ERROR("Unable to set socket non-blocking : %s", strerror(errno));
- return;
- }
- original_stderr_fd_ = fcntl(kStandardErrorFd, F_DUPFD_CLOEXEC);
- if (original_stderr_fd_ == -1) {
- LOG_ERROR("Unable to save original fd : %s", strerror(errno));
- return;
- }
- if (dup3(dup_fd_, kStandardErrorFd, O_CLOEXEC) == -1) {
- LOG_ERROR("Unable to duplicate stderr fd : %s", strerror(errno));
- return;
- }
-}
-
-LogCapture::~LogCapture() {
- Rewind()->Flush();
- clean_up();
-}
-
-LogCapture* LogCapture::Rewind() {
- if (fd_ != -1) {
- if (lseek(fd_, 0, SEEK_SET) != 0) {
- LOG_ERROR("Unable to rewind log capture : %s", strerror(errno));
- }
- }
- return this;
-}
-
-bool LogCapture::Find(const std::string& to_find) {
- std::string str = this->Read();
- return str.find(to_find) != std::string::npos;
-}
-
-void LogCapture::Flush() {
- if (fd_ != -1 && original_stderr_fd_ != -1) {
- ssize_t sz{-1};
- do {
- char buf[kBufferSize];
- sz = read(fd_, buf, sizeof(buf));
- if (sz > 0) {
- write(original_stderr_fd_, buf, sz);
- }
- } while (sz == kBufferSize);
- }
-}
-
-void LogCapture::Sync() {
- if (fd_ != -1) {
- fsync(fd_);
- }
-}
-
-void LogCapture::Reset() {
- if (fd_ != -1) {
- if (ftruncate(fd_, 0UL) == -1) {
- LOG_ERROR("Unable to truncate backing storage : %s", strerror(errno));
- }
- this->Rewind();
- // The only time we rewind the dup()'ed fd is during Reset()
- if (dup_fd_ != -1) {
- if (lseek(dup_fd_, 0, SEEK_SET) != 0) {
- LOG_ERROR("Unable to rewind log capture : %s", strerror(errno));
- }
- }
- }
-}
-
-std::string LogCapture::Read() {
- if (fd_ == -1) {
- return std::string();
- }
- std::ostringstream oss;
- ssize_t sz{-1};
- do {
- char buf[kBufferSize];
- sz = read(fd_, buf, sizeof(buf));
- if (sz > 0) {
- oss << buf;
- }
- } while (sz == kBufferSize);
- return oss.str();
-}
-
-size_t LogCapture::Size() const {
- size_t size{0UL};
- struct stat statbuf;
- if (fd_ != -1 && fstat(fd_, &statbuf) != -1) {
- size = statbuf.st_size;
- }
- return size;
-}
-
-void LogCapture::WaitUntilLogContains(const std::string& text) {
- bool found = false;
- do {
- found = this->Rewind()->Find(text);
- } while (!found);
-}
-
-std::pair<int, int> LogCapture::create_backing_store() const {
- char backing_store_filename[kTempFilenameMaxSize];
- strncpy(backing_store_filename, kTempFilename, kTempFilenameMaxSize);
- int dup_fd = mkstemp(backing_store_filename);
- int fd = open(backing_store_filename, O_RDWR);
- if (dup_fd != -1) {
- unlink(backing_store_filename);
- }
- return std::make_pair(dup_fd, fd);
-}
-
-bool LogCapture::set_non_blocking(int fd) const {
- int flags = fcntl(fd, F_GETFL, 0);
- if (flags == -1) {
- LOG_ERROR("Unable to get file descriptor flags : %s", strerror(errno));
- return false;
- }
- if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
- LOG_ERROR("Unable to set file descriptor flags : %s", strerror(errno));
- return false;
- }
- return true;
-}
-
-void LogCapture::clean_up() {
- if (original_stderr_fd_ != -1) {
- if (dup3(original_stderr_fd_, kStandardErrorFd, O_CLOEXEC) != kStandardErrorFd) {
- LOG_ERROR("Unable to restore original fd : %s", strerror(errno));
- }
- }
- if (dup_fd_ != -1) {
- close(dup_fd_);
- dup_fd_ = -1;
- }
- if (fd_ != -1) {
- close(fd_);
- fd_ = -1;
- }
-}
-
-} // namespace testing
-} // namespace bluetooth
diff --git a/system/gd/common/testing/host/log_capture_test.cc b/system/gd/common/testing/host/log_capture_test.cc
deleted file mode 100644
index e10c83d..0000000
--- a/system/gd/common/testing/host/log_capture_test.cc
+++ /dev/null
@@ -1,154 +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.
- */
-
-#include "../log_capture.h"
-
-#include <gtest/gtest.h>
-
-#include <cstring>
-#include <memory>
-#include <string>
-
-#include "common/init_flags.h"
-#include "os/log.h"
-
-namespace {
-const char* test_flags[] = {
- "INIT_logging_debug_enabled_for_all=true",
- nullptr,
-};
-
-constexpr char kEmptyLine[] = "";
-constexpr char kLogError[] = "LOG_ERROR";
-constexpr char kLogWarn[] = "LOG_WARN";
-constexpr char kLogInfo[] = "LOG_INFO";
-constexpr char kLogDebug[] = "LOG_DEBUG";
-constexpr char kLogVerbose[] = "LOG_VERBOSE";
-
-} // namespace
-
-namespace bluetooth {
-namespace testing {
-
-class LogCaptureTest : public ::testing::Test {
- protected:
- void SetUp() override {}
-
- void TearDown() override {}
-
- // The line number is part of the log output and must be factored out
- size_t CalibrateOneLine(const char* log_line) {
- LOG_INFO("%s", log_line);
- return strlen(log_line);
- }
-};
-
-TEST_F(LogCaptureTest, no_output) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
- ASSERT_TRUE(log_capture->Size() == 0);
-}
-
-// b/260917913
-TEST_F(LogCaptureTest, DISABLED_truncate) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
- CalibrateOneLine(kLogError);
- size_t size = log_capture->Size();
- ASSERT_TRUE(size > 0);
-
- log_capture->Reset();
- ASSERT_EQ(0UL, log_capture->Size());
-
- CalibrateOneLine(kLogError);
- ASSERT_EQ(size, log_capture->Size());
-}
-
-// b/260917913
-TEST_F(LogCaptureTest, DISABLED_log_size) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
- CalibrateOneLine(kEmptyLine);
- size_t empty_line_size = log_capture->Size();
- log_capture->Reset();
-
- std::vector<std::string> log_lines = {
- kLogError,
- kLogWarn,
- kLogInfo,
- };
-
- size_t msg_size{0};
- for (auto& log_line : log_lines) {
- msg_size += CalibrateOneLine(log_line.c_str());
- }
-
- ASSERT_EQ(empty_line_size * log_lines.size() + msg_size, log_capture->Size());
-
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogError));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogWarn));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogInfo));
-}
-
-// b/260917913
-TEST_F(LogCaptureTest, DISABLED_typical) {
- bluetooth::common::InitFlags::Load(nullptr);
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
- LOG_ERROR("%s", kLogError);
- LOG_WARN("%s", kLogWarn);
- LOG_INFO("%s", kLogInfo);
- LOG_DEBUG("%s", kLogDebug);
- LOG_VERBOSE("%s", kLogVerbose);
-
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogError));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogWarn));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogInfo));
- ASSERT_FALSE(log_capture->Rewind()->Find(kLogDebug));
- ASSERT_FALSE(log_capture->Rewind()->Find(kLogVerbose));
-}
-
-// b/260917913
-TEST_F(LogCaptureTest, DISABLED_with_logging_debug_enabled_for_all) {
- bluetooth::common::InitFlags::Load(test_flags);
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
- LOG_ERROR("%s", kLogError);
- LOG_WARN("%s", kLogWarn);
- LOG_INFO("%s", kLogInfo);
- LOG_DEBUG("%s", kLogDebug);
- LOG_VERBOSE("%s", kLogVerbose);
-
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogError));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogWarn));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogInfo));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogDebug));
- ASSERT_TRUE(log_capture->Rewind()->Find(kLogVerbose));
- bluetooth::common::InitFlags::Load(nullptr);
-}
-
-// b/260917913
-TEST_F(LogCaptureTest, DISABLED_wait_until_log_contains) {
- bluetooth::common::InitFlags::Load(test_flags);
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
- LOG_DEBUG("%s", kLogDebug);
- log_capture->WaitUntilLogContains(kLogDebug);
- bluetooth::common::InitFlags::Load(nullptr);
-}
-
-} // namespace testing
-} // namespace bluetooth
diff --git a/system/gd/common/testing/log_capture.h b/system/gd/common/testing/log_capture.h
deleted file mode 100644
index ac34feb..0000000
--- a/system/gd/common/testing/log_capture.h
+++ /dev/null
@@ -1,59 +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.
- */
-
-#include <cstddef>
-#include <future>
-#include <string>
-
-namespace bluetooth {
-namespace testing {
-
-class LogCapture {
- public:
- LogCapture();
- ~LogCapture();
-
- // Rewind file pointer to start of log
- // Returns a |this| pointer for chaining. See |Find|
- LogCapture* Rewind();
- // Searches from filepointer to end of file for |to_find| string
- // Returns true if found, false otherwise
- bool Find(const std::string& to_find);
- // Reads and returns the entirety of the backing store into a string
- std::string Read();
- // Flushes contents of log capture back to |stderr|
- void Flush();
- // Synchronize buffer contents to file descriptor
- void Sync();
- // Returns the backing store size in bytes
- size_t Size() const;
- // Truncates and resets the file pointer discarding all logs up to this point
- void Reset();
- // Wait until the provided string shows up in the logs
- void WaitUntilLogContains(const std::string& text);
-
- private:
- std::pair<int, int> create_backing_store() const;
- bool set_non_blocking(int fd) const;
- void clean_up();
-
- int dup_fd_{-1};
- int fd_{-1};
- int original_stderr_fd_{-1};
-};
-
-} // namespace testing
-} // namespace bluetooth
diff --git a/system/gd/common/testing/wired_pair_of_bidi_queues.h b/system/gd/common/testing/wired_pair_of_bidi_queues.h
index b0603c5..027798d 100644
--- a/system/gd/common/testing/wired_pair_of_bidi_queues.h
+++ b/system/gd/common/testing/wired_pair_of_bidi_queues.h
@@ -18,6 +18,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <memory>
#include <vector>
@@ -37,14 +39,14 @@
class WiredPairOfBiDiQueues {
void dequeue_callback_a() {
auto down_thing = queue_a_.GetDownEnd()->TryDequeue();
- if (!down_thing) LOG_ERROR("Received dequeue, but no data ready...");
+ if (!down_thing) log::error("Received dequeue, but no data ready...");
down_buffer_b_.Enqueue(A_TO_B(std::move(down_thing)), handler_);
}
void dequeue_callback_b() {
auto down_thing = queue_b_.GetDownEnd()->TryDequeue();
- if (!down_thing) LOG_ERROR("Received dequeue, but no data ready...");
+ if (!down_thing) log::error("Received dequeue, but no data ready...");
down_buffer_a_.Enqueue(A_TO_B(std::move(down_thing)), handler_);
}
diff --git a/system/gd/discovery/device/bt_property_unittest.cc b/system/gd/discovery/device/bt_property_unittest.cc
index b5d95ae..a925a1d 100644
--- a/system/gd/discovery/device/bt_property_unittest.cc
+++ b/system/gd/discovery/device/bt_property_unittest.cc
@@ -895,7 +895,8 @@
void TearDown() override {}
std::vector<std::future<std::vector<std::shared_ptr<BtProperty>>>> future_vector;
- bt_property_t bt_properties[kNumberTestedProperties][kNumThreads] = {};
+
+ bt_property_t bt_properties[kNumThreads][kNumberTestedProperties] = {};
std::vector<std::shared_ptr<BtProperty>> properties;
};
@@ -904,7 +905,7 @@
for (size_t i = 0; i < kNumThreads; i++) {
future_vector.push_back(std::async(std::launch::async, [i]() {
std::vector<std::shared_ptr<BtProperty>> properties;
- properties.push_back(RemoteDeviceTimestamp::Create((uint32_t)i));
+ properties.emplace_back(RemoteDeviceTimestamp::Create((uint32_t)i));
return properties;
}));
}
diff --git a/system/gd/hci/acl_manager/classic_impl.h b/system/gd/hci/acl_manager/classic_impl.h
index 696da05..f328f47 100644
--- a/system/gd/hci/acl_manager/classic_impl.h
+++ b/system/gd/hci/acl_manager/classic_impl.h
@@ -614,12 +614,12 @@
void on_enhanced_flush_complete(EventView packet) {
auto flush_complete = EnhancedFlushCompleteView::Create(packet);
if (!flush_complete.IsValid()) {
- LOG_ERROR("Received an invalid packet");
+ log::error("Received an invalid packet");
return;
}
uint16_t handle = flush_complete.GetConnectionHandle();
connections.execute(
- handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); });
+ handle, [](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); });
}
void on_read_remote_version_information(
diff --git a/system/gd/hci/acl_manager/classic_impl_test.cc b/system/gd/hci/acl_manager/classic_impl_test.cc
index 3f7fdda..f92521b 100644
--- a/system/gd/hci/acl_manager/classic_impl_test.cc
+++ b/system/gd/hci/acl_manager/classic_impl_test.cc
@@ -22,7 +22,6 @@
#include <chrono>
#include "common/bidi_queue.h"
-#include "common/testing/log_capture.h"
#include "hci/acl_manager/acl_scheduler.h"
#include "hci/acl_manager/connection_callbacks_mock.h"
#include "hci/acl_manager/connection_management_callbacks_mock.h"
@@ -43,7 +42,6 @@
using ::bluetooth::os::Thread;
using ::bluetooth::packet::BitInserter;
using ::bluetooth::packet::RawBuilder;
-using ::bluetooth::testing::LogCapture;
using ::testing::_;
using ::testing::DoAll;
diff --git a/system/gd/hci/acl_manager/le_acl_connection.cc b/system/gd/hci/acl_manager/le_acl_connection.cc
index 1201cfc..fa6a78a 100644
--- a/system/gd/hci/acl_manager/le_acl_connection.cc
+++ b/system/gd/hci/acl_manager/le_acl_connection.cc
@@ -19,6 +19,7 @@
#include <bluetooth/log.h>
#include "hci/acl_manager/le_connection_management_callbacks.h"
+#include "hci/event_checkers.h"
#include "os/metrics.h"
using bluetooth::hci::Address;
@@ -234,10 +235,7 @@
supervision_timeout,
min_ce_length,
max_ce_length),
- pimpl_->tracker.client_handler_->BindOnce([](CommandStatusView status) {
- ASSERT(status.IsValid());
- ASSERT(status.GetCommandOpCode() == OpCode::LE_CONNECTION_UPDATE);
- }));
+ pimpl_->tracker.client_handler_->BindOnce(check_status<LeConnectionUpdateStatusView>));
return true;
}
diff --git a/system/gd/hci/acl_manager/le_impl_test.cc b/system/gd/hci/acl_manager/le_impl_test.cc
index 239017e..52dfa99 100644
--- a/system/gd/hci/acl_manager/le_impl_test.cc
+++ b/system/gd/hci/acl_manager/le_impl_test.cc
@@ -23,14 +23,12 @@
#include <chrono>
#include "common/bidi_queue.h"
-#include "common/testing/log_capture.h"
#include "hci/acl_manager/le_connection_callbacks.h"
#include "hci/acl_manager/le_connection_management_callbacks.h"
#include "hci/address_with_type.h"
#include "hci/controller.h"
#include "hci/hci_layer_fake.h"
#include "hci/hci_packets.h"
-#include "hci/le_acl_connection_interface.h"
#include "hci/octets.h"
#include "os/handler.h"
#include "os/log.h"
@@ -46,7 +44,6 @@
using ::bluetooth::os::Thread;
using ::bluetooth::packet::BitInserter;
using ::bluetooth::packet::RawBuilder;
-using ::bluetooth::testing::LogCapture;
using ::testing::_;
using ::testing::DoAll;
@@ -656,8 +653,6 @@
// b/260917913
TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNotSet) {
- auto log_capture = std::make_unique<LogCapture>();
-
std::promise<void> promise;
auto future = promise.get_future();
handler_->Post(common::BindOnce(
@@ -697,135 +692,85 @@
// Let |LeAddressManager::unregister_client| execute on handler
auto status2 = future2.wait_for(2s);
ASSERT_EQ(status2, std::future_status::ready);
-
- handler_->Post(common::BindOnce(
- [](std::unique_ptr<LogCapture> log_capture) {
- log_capture->Sync();
- ASSERT_TRUE(log_capture->Rewind()->Find("address policy isn't set yet"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
- },
- std::move(log_capture)));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::DISARMED;
le_impl_->disarm_connectability();
ASSERT_FALSE(le_impl_->disarmed_while_arming_);
le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
- ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMED"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED_extended) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::DISARMED;
le_impl_->disarm_connectability();
ASSERT_FALSE(le_impl_->disarmed_while_arming_);
le_impl_->on_extended_create_connection(
ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
- ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMED"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::ARMING;
le_impl_->disarm_connectability();
ASSERT_TRUE(le_impl_->disarmed_while_arming_);
le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Queueing cancel connect until"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Le connection state machine armed state"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING_extended) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::ARMING;
le_impl_->disarm_connectability();
ASSERT_TRUE(le_impl_->disarmed_while_arming_);
le_impl_->on_extended_create_connection(
ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Queueing cancel connect until"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Le connection state machine armed state"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::ARMED;
le_impl_->disarm_connectability();
ASSERT_FALSE(le_impl_->disarmed_while_arming_);
le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine with create connection"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED_extended) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::ARMED;
le_impl_->disarm_connectability();
ASSERT_FALSE(le_impl_->disarmed_while_arming_);
le_impl_->on_extended_create_connection(
ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine with create connection"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::DISARMING;
le_impl_->disarm_connectability();
ASSERT_FALSE(le_impl_->disarmed_while_arming_);
le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
- ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMING"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING_extended) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
le_impl_->connectability_state_ = ConnectabilityState::DISARMING;
le_impl_->disarm_connectability();
ASSERT_FALSE(le_impl_->disarmed_while_arming_);
le_impl_->on_extended_create_connection(
ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
-
- ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
- ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMING"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyPublicAddress) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
le_impl_->register_with_address_manager();
@@ -839,15 +784,10 @@
sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
ASSERT_FALSE(le_impl_->address_manager_registered);
ASSERT_FALSE(le_impl_->pause_connection);
-
- ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 1"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyStaticAddress) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS);
le_impl_->register_with_address_manager();
@@ -861,15 +801,10 @@
sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
ASSERT_FALSE(le_impl_->address_manager_registered);
ASSERT_FALSE(le_impl_->pause_connection);
-
- ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 2"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNonResolvableAddress) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS);
le_impl_->register_with_address_manager();
@@ -883,15 +818,10 @@
sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
ASSERT_FALSE(le_impl_->address_manager_registered);
ASSERT_FALSE(le_impl_->pause_connection);
-
- ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 3"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
}
// b/260917913
TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyResolvableAddress) {
- std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
-
set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS);
le_impl_->register_with_address_manager();
@@ -905,9 +835,6 @@
sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
ASSERT_FALSE(le_impl_->address_manager_registered);
ASSERT_FALSE(le_impl_->pause_connection);
-
- ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 4"));
- ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
}
// b/260920739
@@ -1321,10 +1248,8 @@
// b/260917913
TEST_F(LeImplTest, DISABLED_on_common_le_connection_complete__NoPriorConnection) {
- auto log_capture = std::make_unique<LogCapture>();
le_impl_->on_common_le_connection_complete(remote_public_address_with_type_);
ASSERT_TRUE(le_impl_->connecting_le_.empty());
- ASSERT_TRUE(log_capture->Rewind()->Find("No prior connection request for"));
}
TEST_F(LeImplTest, cancel_connect) {
diff --git a/system/gd/hci/address_pybind11_type_caster.h b/system/gd/hci/address_pybind11_type_caster.h
deleted file mode 100644
index 18151c3..0000000
--- a/system/gd/hci/address_pybind11_type_caster.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#pragma once
-
-#include <cstring>
-#include <string>
-
-#include <pybind11/pybind11.h>
-#include <pybind11/stl.h>
-
-#include "hci/address.h"
-
-namespace py = pybind11;
-
-namespace pybind11 {
-namespace detail {
-template <>
-struct type_caster<::bluetooth::hci::Address> {
- public:
- // Set the Python name of Address and declare "value"
- PYBIND11_TYPE_CASTER(::bluetooth::hci::Address, _("Address"));
-
- // Convert from Python->C++
- bool load(handle src, bool) {
- PyObject* source = src.ptr();
- if (py::isinstance<py::str>(src)) {
- bool conversion_successful = bluetooth::hci::Address::FromString(PyUnicode_AsUTF8(source), value);
- return conversion_successful && !PyErr_Occurred();
- }
- return false;
- }
-
- // Convert from C++->Python
- static handle cast(bluetooth::hci::Address src, return_value_policy, handle) {
- return PyUnicode_FromString(src.ToString().c_str());
- }
-};
-} // namespace detail
-} // namespace pybind11
diff --git a/system/gd/hci/class_of_device_pybind11_type_caster.h b/system/gd/hci/class_of_device_pybind11_type_caster.h
deleted file mode 100644
index 0615e3b..0000000
--- a/system/gd/hci/class_of_device_pybind11_type_caster.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#pragma once
-
-#include <cstring>
-#include <string>
-
-#include <pybind11/pybind11.h>
-#include <pybind11/stl.h>
-
-#include "hci/class_of_device.h"
-
-namespace py = pybind11;
-
-namespace pybind11 {
-namespace detail {
-template <>
-struct type_caster<::bluetooth::hci::ClassOfDevice> {
- public:
- // Set the Python name of ClassOfDevice and declare "value"
- PYBIND11_TYPE_CASTER(::bluetooth::hci::ClassOfDevice, _("ClassOfDevice"));
-
- // Convert from Python->C++
- bool load(handle src, bool) {
- PyObject* source = src.ptr();
- if (py::isinstance<py::str>(src)) {
- bool conversion_successful = bluetooth::hci::ClassOfDevice::FromString(PyUnicode_AsUTF8(source), value);
- return conversion_successful && !PyErr_Occurred();
- }
- return false;
- }
-
- // Convert from C++->Python
- static handle cast(bluetooth::hci::ClassOfDevice src, return_value_policy, handle) {
- return PyUnicode_FromString(src.ToString().c_str());
- }
-};
-} // namespace detail
-} // namespace pybind11
diff --git a/system/gd/hci/le_advertising_manager.cc b/system/gd/hci/le_advertising_manager.cc
index dd04712..07f7457 100644
--- a/system/gd/hci/le_advertising_manager.cc
+++ b/system/gd/hci/le_advertising_manager.cc
@@ -79,6 +79,7 @@
uint16_t duration;
uint8_t max_extended_advertising_events;
bool started = false;
+ bool is_legacy = false;
bool connectable = false;
bool discoverable = false;
bool directed = false;
@@ -793,6 +794,7 @@
void set_parameters(AdvertiserId advertiser_id, AdvertisingConfig config) {
config.tx_power = get_tx_power_after_calibration(static_cast<int8_t>(config.tx_power));
+ advertising_sets_[advertiser_id].is_legacy = config.legacy_pdus;
advertising_sets_[advertiser_id].connectable = config.connectable;
advertising_sets_[advertiser_id].discoverable = config.discoverable;
advertising_sets_[advertiser_id].tx_power = config.tx_power;
@@ -1067,10 +1069,13 @@
data_len += data[i].size();
}
- if (data_len > le_maximum_advertising_data_length_) {
- log::warn(
- "advertising data len exceeds le_maximum_advertising_data_length_ {}",
- le_maximum_advertising_data_length_);
+ int maxDataLength = (IS_FLAG_ENABLED(ble_check_data_length_on_legacy_advertising) &&
+ advertising_sets_[advertiser_id].is_legacy)
+ ? kLeMaximumLegacyAdvertisingDataLength
+ : le_maximum_advertising_data_length_;
+
+ if (data_len > maxDataLength) {
+ log::warn("advertising data len {} exceeds maxDataLength {}", data_len, maxDataLength);
if (advertising_callbacks_ != nullptr) {
if (set_scan_rsp) {
advertising_callbacks_->OnScanResponseDataSet(
diff --git a/system/gd/hci/le_advertising_manager.h b/system/gd/hci/le_advertising_manager.h
index 559f46e..75cf2f1 100644
--- a/system/gd/hci/le_advertising_manager.h
+++ b/system/gd/hci/le_advertising_manager.h
@@ -106,6 +106,7 @@
static constexpr AdvertiserId kInvalidId = 0xFF;
static constexpr uint8_t kInvalidHandle = 0xFF;
static constexpr uint8_t kAdvertisingSetIdMask = 0x0F;
+ static constexpr uint16_t kLeMaximumLegacyAdvertisingDataLength = 31;
static constexpr uint16_t kLeMaximumFragmentLength = 251;
static constexpr uint16_t kLeMaximumPeriodicDataFragmentLength = 252;
static constexpr uint16_t kLeMaximumGapDataLength = 255;
diff --git a/system/gd/os/handler.cc b/system/gd/os/handler.cc
index 1443df6..bbb0005 100644
--- a/system/gd/os/handler.cc
+++ b/system/gd/os/handler.cc
@@ -18,13 +18,10 @@
#include <bluetooth/log.h>
-#include <cstring>
-
#include "common/bind.h"
#include "common/callback.h"
#include "os/log.h"
#include "os/reactor.h"
-#include "os/utils.h"
namespace bluetooth {
namespace os {
diff --git a/system/gd/os/handler.h b/system/gd/os/handler.h
index 2609ea8..03f65e5 100644
--- a/system/gd/os/handler.h
+++ b/system/gd/os/handler.h
@@ -16,16 +16,14 @@
#pragma once
-#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include "common/bind.h"
#include "common/callback.h"
-#include "common/contextual_callback.h"
+#include "common/postable_context.h"
#include "os/thread.h"
-#include "os/utils.h"
namespace bluetooth {
namespace os {
@@ -33,7 +31,7 @@
// A message-queue style handler for reactor-based thread to handle incoming events from different threads. When it's
// constructed, it will register a reactable on the specified thread; when it's destroyed, it will unregister itself
// from the thread.
-class Handler : public common::IPostableContext {
+class Handler : public common::PostableContext {
public:
// Create and register a handler on given thread
explicit Handler(Thread* thread);
@@ -63,30 +61,6 @@
Post(common::BindOnce(std::forward<Functor>(functor), common::Unretained(obj), std::forward<Args>(args)...));
}
- template <typename Functor, typename... Args>
- auto BindOnce(Functor&& functor, Args&&... args) {
- return common::ContextualOnceCallback(
- common::BindOnce(std::forward<Functor>(functor), std::forward<Args>(args)...), this);
- }
-
- template <typename Functor, typename T, typename... Args>
- auto BindOnceOn(T* obj, Functor&& functor, Args&&... args) {
- return common::ContextualOnceCallback(
- common::BindOnce(std::forward<Functor>(functor), common::Unretained(obj), std::forward<Args>(args)...), this);
- }
-
- template <typename Functor, typename... Args>
- auto Bind(Functor&& functor, Args&&... args) {
- return common::ContextualCallback(
- common::Bind(std::forward<Functor>(functor), std::forward<Args>(args)...), this);
- }
-
- template <typename Functor, typename T, typename... Args>
- auto BindOn(T* obj, Functor&& functor, Args&&... args) {
- return common::ContextualCallback(
- common::Bind(std::forward<Functor>(functor), common::Unretained(obj), std::forward<Args>(args)...), this);
- }
-
template <typename T>
friend class Queue;
diff --git a/system/gd/packet/parser/custom_field_def.cc b/system/gd/packet/parser/custom_field_def.cc
index 2d7a6fd..b950ca1 100644
--- a/system/gd/packet/parser/custom_field_def.cc
+++ b/system/gd/packet/parser/custom_field_def.cc
@@ -43,10 +43,6 @@
s << "#include \"" << include_ << util::CamelCaseToUnderScore(GetTypeName()) << ".h\"\n";
}
-void CustomFieldDef::GenPyBind11Include(std::ostream& s) const {
- s << "#include \"" << include_ << util::CamelCaseToUnderScore(GetTypeName()) << "_pybind11_type_caster.h\"\n";
-}
-
void CustomFieldDef::GenUsing(std::ostream& s) const {
s << "using ::bluetooth::";
for (const auto& c : include_) {
diff --git a/system/gd/packet/parser/custom_field_def.h b/system/gd/packet/parser/custom_field_def.h
index 033801a..24b2830 100644
--- a/system/gd/packet/parser/custom_field_def.h
+++ b/system/gd/packet/parser/custom_field_def.h
@@ -35,8 +35,6 @@
void GenInclude(std::ostream& s) const;
- void GenPyBind11Include(std::ostream& s) const;
-
void GenUsing(std::ostream& s) const;
void GenFixedSizeCustomFieldCheck(std::ostream& s) const;
diff --git a/system/gd/packet/parser/gen_cpp.cc b/system/gd/packet/parser/gen_cpp.cc
index 02f4ae3..0d5014e 100644
--- a/system/gd/packet/parser/gen_cpp.cc
+++ b/system/gd/packet/parser/gen_cpp.cc
@@ -283,159 +283,3 @@
auto file_index = std::min(symbol_count / symbols_per_shard, out_files->size() - 1);
return out_files->at(file_index);
}
-
-bool generate_pybind11_sources_one_file(
- const Declarations& decls,
- const std::filesystem::path& input_file,
- const std::filesystem::path& include_dir,
- const std::filesystem::path& out_dir,
- const std::string& root_namespace,
- size_t num_shards) {
- auto gen_relative_path = input_file.lexically_relative(include_dir).parent_path();
-
- auto input_filename = input_file.filename().string().substr(0, input_file.filename().string().find(".pdl"));
- auto gen_path = out_dir / gen_relative_path;
-
- std::filesystem::create_directories(gen_path);
-
- auto gen_relative_header = gen_relative_path / (input_filename + ".h");
-
- std::vector<std::string> namespace_list;
- parse_namespace(root_namespace, gen_relative_path, &namespace_list);
-
- std::vector<std::ofstream> out_file_shards(num_shards);
- for (size_t i = 0; i < out_file_shards.size(); i++) {
- auto filename = gen_path / (input_filename + "_python3_shard_" + std::to_string(i) + ".cc");
- std::cout << "generating " << filename << std::endl;
- auto& out_file = out_file_shards[i];
- out_file.open(filename);
- if (!out_file.is_open()) {
- std::cerr << "can't open " << filename << std::endl;
- return false;
- }
- out_file << "#include <pybind11/pybind11.h>\n";
- out_file << "#include <pybind11/stl.h>\n";
- out_file << "\n\n";
- out_file << "#include " << gen_relative_header << "\n";
- out_file << "\n\n";
- out_file << "#include \"packet/raw_builder.h\"\n";
- out_file << "\n\n";
-
- for (const auto& c : decls.type_defs_queue_) {
- if (c.second->GetDefinitionType() == TypeDef::Type::CUSTOM) {
- const auto* custom_def = static_cast<const CustomFieldDef*>(c.second);
- custom_def->GenPyBind11Include(out_file);
- }
- }
-
- out_file << "\n\n";
-
- generate_namespace_open(namespace_list, out_file);
- out_file << "\n\n";
-
- for (const auto& c : decls.type_defs_queue_) {
- if (c.second->GetDefinitionType() == TypeDef::Type::CUSTOM ||
- c.second->GetDefinitionType() == TypeDef::Type::CHECKSUM) {
- const auto* custom_def = static_cast<const CustomFieldDef*>(c.second);
- custom_def->GenUsing(out_file);
- }
- }
- out_file << "\n\n";
-
- out_file << "using ::bluetooth::packet::BasePacketBuilder;";
- out_file << "using ::bluetooth::packet::BitInserter;";
- out_file << "using ::bluetooth::packet::CustomTypeChecker;";
- out_file << "using ::bluetooth::packet::Iterator;";
- out_file << "using ::bluetooth::packet::kLittleEndian;";
- out_file << "using ::bluetooth::packet::PacketBuilder;";
- out_file << "using ::bluetooth::packet::BaseStruct;";
- out_file << "using ::bluetooth::packet::PacketStruct;";
- out_file << "using ::bluetooth::packet::PacketView;";
- out_file << "using ::bluetooth::packet::RawBuilder;";
- out_file << "using ::bluetooth::packet::parser::ChecksumTypeChecker;";
- out_file << "\n\n";
-
- out_file << "namespace py = pybind11;\n\n";
-
- out_file << "void define_" << input_filename << "_submodule_shard_" << std::to_string(i) << "(py::module& m) {\n\n";
- }
- size_t symbol_total = 0;
- // Only count types that will be generated
- for (const auto& e : decls.type_defs_queue_) {
- if (e.second->GetDefinitionType() == TypeDef::Type::ENUM) {
- symbol_total++;
- } else if (e.second->GetDefinitionType() == TypeDef::Type::STRUCT) {
- symbol_total++;
- }
- }
- // View and builder are counted separately
- symbol_total += decls.packet_defs_queue_.size() * 2;
- size_t symbol_count = 0;
-
- for (const auto& e : decls.type_defs_queue_) {
- if (e.second->GetDefinitionType() == TypeDef::Type::ENUM) {
- const auto* enum_def = static_cast<const EnumDef*>(e.second);
- EnumGen gen(*enum_def);
- auto& out_file = get_out_file(symbol_count, symbol_total, &out_file_shards);
- gen.GenDefinitionPybind11(out_file);
- out_file << "\n\n";
- symbol_count++;
- }
- }
-
- for (const auto& s : decls.type_defs_queue_) {
- if (s.second->GetDefinitionType() == TypeDef::Type::STRUCT) {
- const auto* struct_def = static_cast<const StructDef*>(s.second);
- auto& out_file = get_out_file(symbol_count, symbol_total, &out_file_shards);
- struct_def->GenDefinitionPybind11(out_file);
- out_file << "\n";
- symbol_count++;
- }
- }
-
- for (const auto& packet_def : decls.packet_defs_queue_) {
- auto& out_file = get_out_file(symbol_count, symbol_total, &out_file_shards);
- packet_def.second->GenParserDefinitionPybind11(out_file);
- out_file << "\n\n";
- symbol_count++;
- }
-
- for (const auto& p : decls.packet_defs_queue_) {
- auto& out_file = get_out_file(symbol_count, symbol_total, &out_file_shards);
- p.second->GenBuilderDefinitionPybind11(out_file);
- out_file << "\n\n";
- symbol_count++;
- }
-
- for (auto& out_file : out_file_shards) {
- out_file << "}\n\n";
- generate_namespace_close(namespace_list, out_file);
- }
-
- auto gen_file_main = gen_path / (input_filename + "_python3.cc");
- std::ofstream out_file_main;
- out_file_main.open(gen_file_main);
- if (!out_file_main.is_open()) {
- std::cerr << "can't open " << gen_file_main << std::endl;
- return false;
- }
- out_file_main << "#include <pybind11/pybind11.h>\n";
- generate_namespace_open(namespace_list, out_file_main);
-
- out_file_main << "namespace py = pybind11;\n\n";
-
- for (size_t i = 0; i < out_file_shards.size(); i++) {
- out_file_main << "void define_" << input_filename << "_submodule_shard_" << std::to_string(i)
- << "(py::module& m);\n";
- }
-
- out_file_main << "void define_" << input_filename << "_submodule(py::module& m) {\n\n";
- for (size_t i = 0; i < out_file_shards.size(); i++) {
- out_file_main << "define_" << input_filename << "_submodule_shard_" << std::to_string(i) << "(m);\n";
- }
- out_file_main << "}\n\n";
-
- generate_namespace_close(namespace_list, out_file_main);
-
- return true;
-}
diff --git a/system/gd/packet/parser/main.cc b/system/gd/packet/parser/main.cc
index 929fc9f..bf79504 100644
--- a/system/gd/packet/parser/main.cc
+++ b/system/gd/packet/parser/main.cc
@@ -46,14 +46,6 @@
const std::filesystem::path& out_dir,
const std::string& root_namespace);
-bool generate_pybind11_sources_one_file(
- const Declarations& decls,
- const std::filesystem::path& input_file,
- const std::filesystem::path& include_dir,
- const std::filesystem::path& out_dir,
- const std::string& root_namespace,
- size_t num_shards);
-
bool parse_declarations_one_file(const std::filesystem::path& input_file, Declarations* declarations) {
void* scanner;
yylex_init(&scanner);
@@ -115,9 +107,6 @@
ofs << std::setw(24) << "--source_root= ";
ofs << "Root path to the source directory. Find input files relative to this." << std::endl;
-
- ofs << std::setw(24) << "--num_shards= ";
- ofs << "Number of shards per output pybind11 cc file." << std::endl;
}
int main(int argc, const char** argv) {
@@ -126,8 +115,6 @@
std::filesystem::path cwd = std::filesystem::current_path();
std::filesystem::path source_root = cwd;
std::string root_namespace = "bluetooth";
- // Number of shards per output pybind11 cc file
- size_t num_shards = 1;
bool generate_fuzzing = false;
bool generate_tests = false;
std::queue<std::filesystem::path> input_files;
@@ -135,7 +122,6 @@
const std::string arg_out = "--out=";
const std::string arg_include = "--include=";
const std::string arg_namespace = "--root_namespace=";
- const std::string arg_num_shards = "--num_shards=";
const std::string arg_fuzzing = "--fuzzing";
const std::string arg_testing = "--testing";
const std::string arg_source_root = "--source_root=";
@@ -157,8 +143,6 @@
include_dir = source_root / std::filesystem::path(arg.substr(arg_include.size()));
} else if (arg.find(arg_namespace) == 0) {
root_namespace = arg.substr(arg_namespace.size());
- } else if (arg.find(arg_num_shards) == 0) {
- num_shards = std::stoul(arg.substr(arg_num_shards.size()));
} else if (arg.find(arg_fuzzing) == 0) {
generate_fuzzing = true;
} else if (arg.find(arg_testing) == 0) {
@@ -169,7 +153,7 @@
input_files.emplace(source_root / std::filesystem::path(arg));
}
}
- if (out_dir == std::filesystem::path() || include_dir == std::filesystem::path() || num_shards == 0) {
+ if (out_dir == std::filesystem::path() || include_dir == std::filesystem::path()) {
usage(argv[0]);
return 1;
}
@@ -183,7 +167,7 @@
std::cerr << "Cannot parse " << input_files.front() << " correctly" << std::endl;
return 2;
}
- std::cout << "generating c++ and pybind11" << std::endl;
+ std::cout << "generating c++" << std::endl;
if (!generate_cpp_headers_one_file(
declarations,
generate_fuzzing,
@@ -195,11 +179,6 @@
std::cerr << "Didn't generate cpp headers for " << input_files.front() << std::endl;
return 3;
}
- if (!generate_pybind11_sources_one_file(
- declarations, input_files.front(), include_dir, out_dir, root_namespace, num_shards)) {
- std::cerr << "Didn't generate pybind11 sources for " << input_files.front() << std::endl;
- return 4;
- }
input_files.pop();
}
diff --git a/system/gd/packet/parser/packetgen.gni b/system/gd/packet/parser/packetgen.gni
index 35e88de..eee0d8b 100644
--- a/system/gd/packet/parser/packetgen.gni
+++ b/system/gd/packet/parser/packetgen.gni
@@ -14,83 +14,6 @@
# limitations under the License.
#
-# Generate pybind11 source files + headers
-#
-# Parameters:
-# include: Base include path (i.e. bt/gd)
-# source_root: Root of source relative to current BUILD.gn
-# sources: PDL files to use for generation.
-# shards [optional]: Shard generated source into N files.
-# Default = 0. Max = 10.
-template("packetgen_py") {
- action_name = "${target_name}_gen"
-
- all_dependent_config_name = "_${target_name}_all_dependent_config"
- config(all_dependent_config_name) {
- include_dirs = [ "${root_gen_dir}" ]
- }
-
- action(action_name) {
- forward_variables_from(invoker, [ "sources", "include", "shards", "source_root" ])
- assert(defined(sources), "sources must be set")
- assert(defined(include), "include must be set")
- assert(defined(source_root), "source root must be set")
-
- outdir = rebase_path(root_gen_dir)
- source_root = rebase_path(source_root)
-
- # Set shards cmd
- shards_cmd = ""
- outputs = []
- source_args = []
- if (defined(shards)) {
- shards_list = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
- foreach (source, sources) {
- rel_source = rebase_path(source, ".")
- source_args += [ rebase_path(source, source_root) ]
- shards_cmd = "--num_shards=${shards}"
-
- # TODO - GN reference doesn't explain how to programatically create
- # a range (i.e. range(shards)) so we use a fixed list and foreach loop to
- # work around it.
- assert(shards <= 10, "Maximum supported shards is 10.")
- index = 0
- outputs += [ string_replace("${outdir}/${rel_source}_python3.cc", ".pdl", "") ]
- foreach(num, shards_list) {
- if (index < shards) {
- outputs += [ string_replace("${outdir}/${rel_source}_python3_shard_${num}.cc", ".pdl", "") ]
- }
-
- index = index + 1
- }
- }
- }
-
- script = "//common-mk/file_generator_wrapper.py"
- binfile = "${root_out_dir}/bluetooth_packetgen"
- args = [
- binfile,
- "--include=${include}",
- "--out=${outdir}",
- "--source_root=${source_root}",
- shards_cmd,
- ] + source_args
- }
-
- # TODO: Make building with python-dev work.
- # source_set(target_name) {
- # sources = get_target_outputs(":${action_name}")
- # deps = [":${action_name}"]
- # all_dependent_configs = [":${all_dependent_config_name}"]
- # if (defined(invoker.all_dependent_configs)) {
- # all_dependent_configs += invoker.all_dependent_configs
- # }
- # if (defined(invoker.configs)) {
- # configs += invoker.configs
- # }
- # }
-}
-
# Generate single c++ headers for each pdl
#
# Parameters:
diff --git a/system/gd/packet/python3_module.cc b/system/gd/packet/python3_module.cc
deleted file mode 100644
index 3059114..0000000
--- a/system/gd/packet/python3_module.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <pybind11/pybind11.h>
-#include <pybind11/stl.h>
-
-#include <cstring>
-#include <memory>
-
-#include "packet/base_packet_builder.h"
-#include "packet/bit_inserter.h"
-#include "packet/checksum_type_checker.h"
-#include "packet/custom_type_checker.h"
-#include "packet/iterator.h"
-#include "packet/packet_builder.h"
-#include "packet/packet_struct.h"
-#include "packet/packet_view.h"
-#include "packet/raw_builder.h"
-
-namespace py = pybind11;
-
-namespace bluetooth {
-
-namespace l2cap {
-void define_l2cap_packets_submodule(py::module&);
-}
-
-namespace packet {
-
-using ::bluetooth::packet::BasePacketBuilder;
-using ::bluetooth::packet::BaseStruct;
-using ::bluetooth::packet::BitInserter;
-using ::bluetooth::packet::CustomTypeChecker;
-using ::bluetooth::packet::Iterator;
-using ::bluetooth::packet::kLittleEndian;
-using ::bluetooth::packet::PacketBuilder;
-using ::bluetooth::packet::PacketStruct;
-using ::bluetooth::packet::PacketView;
-using ::bluetooth::packet::RawBuilder;
-using ::bluetooth::packet::parser::ChecksumTypeChecker;
-
-PYBIND11_MODULE(bluetooth_packets_python3, m) {
- py::class_<BasePacketBuilder, std::shared_ptr<BasePacketBuilder>>(m, "BasePacketBuilder");
- py::class_<RawBuilder, BasePacketBuilder, std::shared_ptr<RawBuilder>>(m, "RawBuilder")
- .def(py::init([](std::vector<uint8_t> bytes) { return std::make_unique<RawBuilder>(bytes); }))
- .def(py::init([](std::string bytes) {
- return std::make_unique<RawBuilder>(std::vector<uint8_t>(bytes.begin(), bytes.end()));
- }))
- .def("Serialize", [](RawBuilder& builder) {
- std::vector<uint8_t> packet;
- BitInserter it(packet);
- builder.Serialize(it);
- std::string result = std::string(packet.begin(), packet.end());
- return py::bytes(result);
- });
- py::class_<PacketBuilder<kLittleEndian>, BasePacketBuilder, std::shared_ptr<PacketBuilder<kLittleEndian>>>(
- m, "PacketBuilderLittleEndian");
- py::class_<PacketBuilder<!kLittleEndian>, BasePacketBuilder, std::shared_ptr<PacketBuilder<!kLittleEndian>>>(
- m, "PacketBuilderBigEndian");
- py::class_<BaseStruct, std::shared_ptr<BaseStruct>>(m, "BaseStruct");
- py::class_<PacketStruct<kLittleEndian>, BaseStruct, std::shared_ptr<PacketStruct<kLittleEndian>>>(
- m, "PacketStructLittleEndian");
- py::class_<PacketStruct<!kLittleEndian>, BaseStruct, std::shared_ptr<PacketStruct<!kLittleEndian>>>(
- m, "PacketStructBigEndian");
- py::class_<Iterator<kLittleEndian>>(m, "IteratorLittleEndian");
- py::class_<Iterator<!kLittleEndian>>(m, "IteratorBigEndian");
- py::class_<PacketView<kLittleEndian>>(m, "PacketViewLittleEndian")
- .def(py::init([](std::vector<uint8_t> bytes) {
- // Make a copy
- auto bytes_shared = std::make_shared<std::vector<uint8_t>>(bytes);
- return std::make_unique<PacketView<kLittleEndian>>(bytes_shared);
- }))
- .def("GetBytes", [](const PacketView<kLittleEndian> view) {
- std::string result;
- for (auto byte : view) {
- result += byte;
- }
- return py::bytes(result);
- });
- py::class_<PacketView<!kLittleEndian>>(m, "PacketViewBigEndian").def(py::init([](std::vector<uint8_t> bytes) {
- // Make a copy
- auto bytes_shared = std::make_shared<std::vector<uint8_t>>(bytes);
- return std::make_unique<PacketView<!kLittleEndian>>(bytes_shared);
- }));
-
- py::module l2cap_m = m.def_submodule("l2cap_packets", "A submodule of l2cap_packets");
- bluetooth::l2cap::define_l2cap_packets_submodule(l2cap_m);
-}
-
-} // namespace packet
-} // namespace bluetooth
diff --git a/system/hci/BUILD.gn b/system/hci/BUILD.gn
index 4309549..c17f4b2 100644
--- a/system/hci/BUILD.gn
+++ b/system/hci/BUILD.gn
@@ -33,6 +33,7 @@
configs += [
"//bt/system:target_defaults",
+ "//bt/system/log:log_defaults",
]
}
diff --git a/system/hci/src/packet_fragmenter.cc b/system/hci/src/packet_fragmenter.cc
index 950402f..cfcc438 100644
--- a/system/hci/src/packet_fragmenter.cc
+++ b/system/hci/src/packet_fragmenter.cc
@@ -21,6 +21,7 @@
#include "packet_fragmenter.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <string.h>
#include <unordered_map>
@@ -77,6 +78,8 @@
// Our interface and callbacks
+using namespace bluetooth;
+
static const allocator_t* buffer_allocator;
static const packet_fragmenter_callbacks_t* callbacks;
@@ -170,10 +173,9 @@
uint8_t packet_status_flags;
if (map_iter != partial_iso_packets.end()) {
- LOG_WARN(
- "%s found unfinished packet for the iso handle with start packet. "
- "Dropping old.",
- __func__);
+ log::warn(
+ "found unfinished packet for the iso handle with start packet. "
+ "Dropping old.");
BT_HDR* hdl = map_iter->second;
partial_iso_packets.erase(map_iter);
buffer_allocator->free(hdl);
@@ -187,8 +189,8 @@
}
if (iso_length < iso_hdr_len) {
- LOG_WARN("%s ISO packet too small (%d < %d). Dropping it.", __func__,
- packet->len, iso_hdr_len);
+ log::warn("ISO packet too small ({} < {}). Dropping it.", packet->len,
+ iso_hdr_len);
buffer_allocator->free(packet);
return;
}
@@ -207,13 +209,12 @@
iso_sdu_length = iso_sdu_length & HCI_ISO_SDU_LENGTH_MASK;
if (packet_status_flags)
- LOG_ERROR("%s packet status flags: 0x%02x", __func__,
- packet_status_flags);
+ log::error("packet status flags: 0x{:02x}", packet_status_flags);
iso_full_len = iso_sdu_length + iso_hdr_len + HCI_ISO_PREAMBLE_SIZE;
if ((iso_full_len + sizeof(BT_HDR)) > BT_DEFAULT_BUFFER_SIZE) {
- LOG_ERROR("%s Dropping ISO packet with invalid length (%d).", __func__,
- iso_sdu_length);
+ log::error("Dropping ISO packet with invalid length ({}).",
+ iso_sdu_length);
buffer_allocator->free(packet);
return;
}
@@ -222,7 +223,7 @@
(iso_full_len != packet->len)) ||
((boundary_flag == HCI_ISO_BF_FIRST_FRAGMENTED_PACKET) &&
(iso_full_len <= packet->len))) {
- LOG_ERROR("%s corrupted ISO frame", __func__);
+ log::error("corrupted ISO frame");
buffer_allocator->free(packet);
return;
}
@@ -230,7 +231,7 @@
partial_packet =
(BT_HDR*)buffer_allocator->alloc(iso_full_len + sizeof(BT_HDR));
if (!partial_packet) {
- LOG_ERROR("%s cannot allocate partial packet", __func__);
+ log::error("cannot allocate partial packet");
buffer_allocator->free(packet);
return;
}
@@ -262,8 +263,7 @@
// pass-through
case HCI_ISO_BF_LAST_FRAGMENT_PACKET:
if (map_iter == partial_iso_packets.end()) {
- LOG_WARN("%s got continuation for unknown packet. Dropping it.",
- __func__);
+ log::warn("got continuation for unknown packet. Dropping it.");
buffer_allocator->free(packet);
return;
}
@@ -271,10 +271,10 @@
partial_packet = map_iter->second;
if (partial_packet->len <
(partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE)) {
- LOG_ERROR(
- "%s got packet which would exceed expected length of %d. "
- "dropping full packet",
- __func__, partial_packet->len);
+ log::error(
+ "got packet which would exceed expected length of {}. dropping "
+ "full packet",
+ partial_packet->len);
buffer_allocator->free(packet);
partial_iso_packets.erase(map_iter);
buffer_allocator->free(partial_packet);
@@ -293,10 +293,10 @@
if (partial_packet->len !=
partial_packet->offset + packet->len - HCI_ISO_PREAMBLE_SIZE) {
- LOG_ERROR(
- "%s got last fragment, but it doesn't fill up the whole packet of "
- "size %d",
- __func__, partial_packet->len);
+ log::error(
+ "got last fragment, but it doesn't fill up the whole packet of "
+ "size {}",
+ partial_packet->len);
buffer_allocator->free(packet);
partial_iso_packets.erase(map_iter);
buffer_allocator->free(partial_packet);
@@ -317,7 +317,7 @@
break;
default:
- LOG_ERROR("%s Unexpected packet, dropping full packet", __func__);
+ log::error("Unexpected packet, dropping full packet");
buffer_allocator->free(packet);
break;
}
diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h
index a8fefc1..9097ffa 100644
--- a/system/include/hardware/bt_le_audio.h
+++ b/system/include/hardware/bt_le_audio.h
@@ -570,4 +570,7 @@
template <>
struct formatter<bluetooth::le_audio::btle_audio_frame_duration_index_t>
: enum_formatter<bluetooth::le_audio::btle_audio_frame_duration_index_t> {};
+template <>
+struct formatter<bluetooth::le_audio::GroupStreamStatus>
+ : enum_formatter<bluetooth::le_audio::GroupStreamStatus> {};
} // namespace fmt
diff --git a/system/include/hardware/bt_sock.h b/system/include/hardware/bt_sock.h
index 27d3847..d49c5bd 100644
--- a/system/include/hardware/bt_sock.h
+++ b/system/include/hardware/bt_sock.h
@@ -22,6 +22,8 @@
#include "bluetooth/uuid.h"
#include "raw_address.h"
+using bluetooth::Uuid;
+
__BEGIN_DECLS
#define BTSOCK_FLAG_ENCRYPT 1
@@ -52,8 +54,10 @@
// The reader must read using a buffer of at least this size to avoid
// loosing data. (L2CAP only)
unsigned short max_rx_packet_size;
- unsigned short l2cap_lcid;
- unsigned short l2cap_rcid;
+
+ // The connection uuid. (L2CAP only)
+ uint64_t conn_uuid_lsb;
+ uint64_t conn_uuid_msb;
} __attribute__((packed)) sock_connect_signal_t;
typedef struct {
@@ -109,6 +113,16 @@
*/
bt_status_t (*disconnect_all)(const RawAddress* bd_addr);
+ /**
+ * Get L2CAP local channel ID with the associated connection uuid.
+ */
+ bt_status_t (*get_l2cap_local_cid)(Uuid& conn_uuid, uint16_t* cid);
+
+ /**
+ * Get L2CAP remote channel ID with the associated connection uuid.
+ */
+ bt_status_t (*get_l2cap_remote_cid)(Uuid& conn_uuid, uint16_t* cid);
+
} btsock_interface_t;
__END_DECLS
diff --git a/system/internal_include/bt_target.h b/system/internal_include/bt_target.h
index 363403c..0ad5b38 100644
--- a/system/internal_include/bt_target.h
+++ b/system/internal_include/bt_target.h
@@ -390,8 +390,15 @@
* create l2cap connection, it will use this fixed ID. */
#define CONN_MGR_ID_L2CAP (GATT_MAX_APPS + 10)
+/* This value is used for static allocation of resources. The actual maximum at
+ * runtime is controlled by a system property. */
#ifndef GATT_MAX_PHY_CHANNEL
-#define GATT_MAX_PHY_CHANNEL 7
+#define GATT_MAX_PHY_CHANNEL 16
+#endif
+
+/* Devices must support at least 8 GATT channels per the CDD. */
+#ifndef GATT_MAX_PHY_CHANNEL_FLOOR
+#define GATT_MAX_PHY_CHANNEL_FLOOR 8
#endif
/* Used for conformance testing ONLY */
diff --git a/system/log/src/truncating_buffer_test.cc b/system/log/src/truncating_buffer_test.cc
index 5790270..a0b4a09 100644
--- a/system/log/src/truncating_buffer_test.cc
+++ b/system/log/src/truncating_buffer_test.cc
@@ -20,7 +20,6 @@
#include <fmt/format.h>
#include <gtest/gtest.h>
-#include <log/log.h>
using namespace bluetooth::log_internal;
diff --git a/system/main/Android.bp b/system/main/Android.bp
index 8f729d7..1e2eeae 100644
--- a/system/main/Android.bp
+++ b/system/main/Android.bp
@@ -190,7 +190,6 @@
"shim/btm.cc",
"shim/btm_api.cc",
"shim/config.cc",
- "shim/controller.cc",
"shim/distance_measurement_manager.cc",
"shim/dumpsys.cc",
"shim/hci_layer.cc",
diff --git a/system/main/bte_conf.cc b/system/main/bte_conf.cc
index b08f079..21c2511 100644
--- a/system/main/bte_conf.cc
+++ b/system/main/bte_conf.cc
@@ -18,6 +18,8 @@
#define LOG_TAG "bt_bte_conf"
+#include <bluetooth/log.h>
+
#include <cstdint>
#include <cstdio>
#include <memory>
@@ -28,6 +30,8 @@
#include "osi/include/compat.h" // strlcpy
#include "osi/include/config.h"
+using namespace bluetooth;
+
// Parses the specified Device ID configuration file and registers the
// Device ID records with SDP.
void bte_load_did_conf(const char* p_path) {
@@ -35,7 +39,7 @@
std::unique_ptr<config_t> config = config_new(p_path);
if (!config) {
- LOG_ERROR("%s unable to load DID config '%s'.", __func__, p_path);
+ log::error("unable to load DID config '{}'.", p_path);
return;
}
@@ -44,7 +48,7 @@
snprintf(section_name, sizeof(section_name), "DID%d", i);
if (!config_has_section(*config, section_name)) {
- LOG_INFO("%s no section named %s.", __func__, section_name);
+ log::info("no section named {}.", section_name);
break;
}
@@ -75,26 +79,25 @@
if (record.vendor_id_source != DI_VENDOR_ID_SOURCE_BTSIG &&
record.vendor_id_source != DI_VENDOR_ID_SOURCE_USBIF) {
- LOG_ERROR("%s invalid vendor id source %d; ignoring DID record %d.",
- __func__, record.vendor_id_source, i);
+ log::error("invalid vendor id source {}; ignoring DID record {}.",
+ record.vendor_id_source, i);
continue;
}
- LOG_INFO("Device ID record %d : %s", i,
- (record.primary_record ? "primary" : "not primary"));
- LOG_INFO(" vendorId = %04x", record.vendor);
- LOG_INFO(" vendorIdSource = %04x", record.vendor_id_source);
- LOG_INFO(" product = %04x", record.product);
- LOG_INFO(" version = %04x", record.version);
- LOG_INFO(" clientExecutableURL = %s", record.client_executable_url);
- LOG_INFO(" serviceDescription = %s", record.service_description);
- LOG_INFO(" documentationURL = %s", record.documentation_url);
+ log::info("Device ID record {} : {}", i,
+ (record.primary_record ? "primary" : "not primary"));
+ log::info("vendorId = {:04x}", record.vendor);
+ log::info("vendorIdSource = {:04x}", record.vendor_id_source);
+ log::info("product = {:04x}", record.product);
+ log::info("version = {:04x}", record.version);
+ log::info("clientExecutableURL = {}", record.client_executable_url);
+ log::info("serviceDescription = {}", record.service_description);
+ log::info("documentationURL = {}", record.documentation_url);
uint32_t record_handle;
tBTA_STATUS status = BTA_DmSetLocalDiRecord(&record, &record_handle);
if (status != BTA_SUCCESS) {
- LOG_ERROR("%s unable to set device ID record %d: error %d.", __func__, i,
- status);
+ log::error("unable to set device ID record {}: error {}.", i, status);
}
}
}
diff --git a/system/main/bte_init_cpp_logging.cc b/system/main/bte_init_cpp_logging.cc
index 367cce1..cdc2c01 100644
--- a/system/main/bte_init_cpp_logging.cc
+++ b/system/main/bte_init_cpp_logging.cc
@@ -18,12 +18,14 @@
#include <base/command_line.h>
#include <base/logging.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <os/log.h>
#include "main_int.h"
#ifdef TARGET_FLOSS
#include <syslog.h>
+
static bool MessageHandler(int severity, const char* file, int line,
size_t message_start, const std::string& message) {
ASSERT(message_start <= message.size());
@@ -91,7 +93,7 @@
logging::LoggingSettings log_settings;
if (!logging::InitLogging(log_settings)) {
- LOG_ERROR("Failed to set up logging");
+ bluetooth::log::error("Failed to set up logging");
}
// Android already logs thread_id, proc_id, timestamp, so disable those.
diff --git a/system/main/shim/Android.bp b/system/main/shim/Android.bp
index b896720..863c4c3 100644
--- a/system/main/shim/Android.bp
+++ b/system/main/shim/Android.bp
@@ -24,7 +24,6 @@
"btm.cc",
"btm_api.cc",
"config.cc",
- "controller.cc",
"distance_measurement_manager.cc",
"dumpsys.cc",
"hci_layer.cc",
diff --git a/system/main/shim/BUILD.gn b/system/main/shim/BUILD.gn
index 33ffeb9..4df13f6 100644
--- a/system/main/shim/BUILD.gn
+++ b/system/main/shim/BUILD.gn
@@ -57,7 +57,6 @@
"btm.cc",
"btm_api.cc",
"config.cc",
- "controller.cc",
"distance_measurement_manager.cc",
"dumpsys.cc",
"hci_layer.cc",
diff --git a/system/main/shim/acl.cc b/system/main/shim/acl.cc
index 8103f54..1980b6c 100644
--- a/system/main/shim/acl.cc
+++ b/system/main/shim/acl.cc
@@ -18,6 +18,7 @@
#include <base/location.h>
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <time.h>
#include <chrono>
@@ -158,13 +159,13 @@
bool Add(const hci::AddressWithType& address_with_type) {
if (acceptlist_set_.size() == max_acceptlist_size_) {
- LOG_ERROR("Acceptlist is full size:%zu", acceptlist_set_.size());
+ log::error("Acceptlist is full size:{}", acceptlist_set_.size());
return false;
}
if (!acceptlist_set_.insert(ConnectAddressWithType(address_with_type))
.second) {
- LOG_WARN("Attempted to add duplicate le address to acceptlist:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::warn("Attempted to add duplicate le address to acceptlist:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
}
return true;
}
@@ -172,8 +173,8 @@
bool Remove(const hci::AddressWithType& address_with_type) {
auto iter = acceptlist_set_.find(ConnectAddressWithType(address_with_type));
if (iter == acceptlist_set_.end()) {
- LOG_WARN("Unknown device being removed from acceptlist:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::warn("Unknown device being removed from acceptlist:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
return false;
}
acceptlist_set_.erase(ConnectAddressWithType(*iter));
@@ -204,13 +205,14 @@
bool Add(const hci::AddressWithType& address_with_type) {
if (address_resolution_set_.size() == max_address_resolution_size_) {
- LOG_ERROR("Address Resolution is full size:%zu",
- address_resolution_set_.size());
+ log::error("Address Resolution is full size:{}",
+ address_resolution_set_.size());
return false;
}
if (!address_resolution_set_.insert(address_with_type).second) {
- LOG_WARN("Attempted to add duplicate le address to address_resolution:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::warn(
+ "Attempted to add duplicate le address to address_resolution:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
}
return true;
}
@@ -218,8 +220,8 @@
bool Remove(const hci::AddressWithType& address_with_type) {
auto iter = address_resolution_set_.find(address_with_type);
if (iter == address_resolution_set_.end()) {
- LOG_WARN("Unknown device being removed from address_resolution:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::warn("Unknown device being removed from address_resolution:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
return false;
}
address_resolution_set_.erase(iter);
@@ -363,7 +365,7 @@
#define TRY_POSTING_ON_MAIN(cb, ...) \
do { \
if (cb == nullptr) { \
- LOG_WARN("Dropping ACL event with no callback"); \
+ log::warn("Dropping ACL event with no callback"); \
} else { \
do_in_main_thread(FROM_HERE, base::BindOnce(cb, ##__VA_ARGS__)); \
} \
@@ -389,8 +391,9 @@
virtual ~ShimAclConnection() {
if (!queue_.empty())
- LOG_ERROR(
- "ACL cleaned up with non-empty queue handle:0x%04x stranded_pkts:%zu",
+ log::error(
+ "ACL cleaned up with non-empty queue handle:0x{:04x} "
+ "stranded_pkts:{}",
handle_, queue_.size());
ASSERT_LOG(is_disconnected_,
"Shim Acl was not properly disconnected handle:0x%04x", handle_);
@@ -423,7 +426,7 @@
ASSERT_LOG(p_buf != nullptr,
"Unable to allocate BT_HDR legacy packet handle:%04x", handle_);
if (send_data_upwards_ == nullptr) {
- LOG_WARN("Dropping ACL data with no callback");
+ log::warn("Dropping ACL data with no callback");
osi_free(p_buf);
} else if (do_in_main_thread(FROM_HERE,
base::BindOnce(send_data_upwards_, p_buf)) !=
@@ -440,7 +443,8 @@
void Shutdown() {
Disconnect();
- LOG_INFO("Shutdown and disconnect ACL connection handle:0x%04x", handle_);
+ log::info("Shutdown and disconnect ACL connection handle:0x{:04x}",
+ handle_);
}
protected:
@@ -455,20 +459,19 @@
void Disconnect() {
if (is_disconnected_) {
- LOG_ERROR(
- "Cannot disconnect ACL multiple times handle:%04x creation_time:%s",
+ log::error(
+ "Cannot disconnect ACL multiple times handle:{:04x} creation_time:{}",
handle_,
common::StringFormatTimeWithMilliseconds(
- kConnectionDescriptorTimeFormat, creation_time_)
- .c_str());
+ kConnectionDescriptorTimeFormat, creation_time_));
return;
}
is_disconnected_ = true;
UnregisterEnqueue();
queue_up_end_->UnregisterDequeue();
if (!queue_.empty())
- LOG_WARN(
- "ACL disconnect with non-empty queue handle:%04x stranded_pkts::%zu",
+ log::warn(
+ "ACL disconnect with non-empty queue handle:{:04x} stranded_pkts::{}",
handle_, queue_.size());
}
@@ -542,7 +545,7 @@
}
void OnReadClockOffsetComplete(uint16_t /* clock_offset */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnModeChange(hci::ErrorCode status, hci::Mode current_mode,
@@ -566,7 +569,7 @@
uint32_t /* token_rate */,
uint32_t /* peak_bandwidth */, uint32_t /* latency */,
uint32_t /* delay_variation */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */,
@@ -575,61 +578,61 @@
uint32_t /* token_bucket_size */,
uint32_t /* peak_bandwidth */,
uint32_t /* access_latency */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
- void OnFlushOccurred() override { LOG_INFO("UNIMPLEMENTED"); }
+ void OnFlushOccurred() override { log::info("UNIMPLEMENTED"); }
void OnRoleDiscoveryComplete(hci::Role /* current_role */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadLinkPolicySettingsComplete(
uint16_t /* link_policy_settings */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadAutomaticFlushTimeoutComplete(
uint16_t /* flush_timeout */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadTransmitPowerLevelComplete(
uint8_t /* transmit_power_level */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadLinkSupervisionTimeoutComplete(
uint16_t /* link_supervision_timeout */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadFailedContactCounterComplete(
uint16_t /* failed_contact_counter */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadLinkQualityComplete(uint8_t /* link_quality */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadAfhChannelMapComplete(
hci::AfhMode /* afh_mode */,
std::array<uint8_t, 10> /* afh_channel_map */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadRssiComplete(uint8_t /* rssi */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnReadClockComplete(uint32_t /* clock */,
uint16_t /* accuracy */) override {
- LOG_INFO("UNIMPLEMENTED");
+ log::info("UNIMPLEMENTED");
}
void OnCentralLinkKeyComplete(hci::KeyFlag /* key_flag */) override {
- LOG_INFO("%s UNIMPLEMENTED", __func__);
+ log::info("UNIMPLEMENTED");
}
void OnRoleChange(hci::ErrorCode hci_status, hci::Role new_role) override {
@@ -665,7 +668,7 @@
connection_->ReadRemoteExtendedFeatures(1);
return;
}
- LOG_DEBUG("Device does not support extended features");
+ log::debug("Device does not support extended features");
}
void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,
@@ -676,7 +679,7 @@
// Supported features aliases to extended features page 0
if (page_number == 0 && !(features & ((uint64_t(1) << 63)))) {
- LOG_DEBUG("Device does not support extended features");
+ log::debug("Device does not support extended features");
return;
}
@@ -716,6 +719,8 @@
return connection_->locally_initiated_;
}
+ void Flush() { connection_->Flush(); }
+
private:
OnDisconnect on_disconnect_;
const shim::legacy::acl_classic_link_interface_t interface_;
@@ -846,6 +851,13 @@
return connection_->IsInFilterAcceptList();
}
+ void UpdateConnectionParameters(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) {
+ connection_->LeConnectionUpdate(conn_int_min, conn_int_max, conn_latency,
+ conn_timeout, min_ce_len, max_ce_len);
+ }
+
private:
OnDisconnect on_disconnect_;
const shim::legacy::acl_le_link_interface_t interface_;
@@ -884,6 +896,14 @@
handle_to_classic_connection_map_[handle]->EnqueuePacket(std::move(packet));
}
+ void Flush(HciHandle handle) {
+ if (IsClassicAcl(handle)) {
+ handle_to_classic_connection_map_[handle]->Flush();
+ } else {
+ LOG_ERROR("handle %d is not a classic connection", handle);
+ }
+ }
+
bool IsLeAcl(HciHandle handle) {
return handle_to_le_connection_map_.find(handle) !=
handle_to_le_connection_map_.end();
@@ -896,7 +916,7 @@
}
void DisconnectClassicConnections(std::promise<void> promise) {
- LOG_INFO("Disconnect gd acl shim classic connections");
+ log::info("Disconnect gd acl shim classic connections");
std::vector<HciHandle> disconnect_handles;
for (auto& connection : handle_to_classic_connection_map_) {
disconnect_classic(connection.first, HCI_ERR_REMOTE_POWER_OFF,
@@ -921,7 +941,7 @@
}
void ShutdownClassicConnections(std::promise<void> promise) {
- LOG_INFO("Shutdown gd acl shim classic connections");
+ log::info("Shutdown gd acl shim classic connections");
for (auto& connection : handle_to_classic_connection_map_) {
connection.second->Shutdown();
}
@@ -930,7 +950,7 @@
}
void DisconnectLeConnections(std::promise<void> promise) {
- LOG_INFO("Disconnect gd acl shim le connections");
+ log::info("Disconnect gd acl shim le connections");
std::vector<HciHandle> disconnect_handles;
for (auto& connection : handle_to_le_connection_map_) {
disconnect_le(connection.first, HCI_ERR_REMOTE_POWER_OFF,
@@ -954,7 +974,7 @@
}
void ShutdownLeConnections(std::promise<void> promise) {
- LOG_INFO("Shutdown gd acl shim le connections");
+ log::info("Shutdown gd acl shim le connections");
for (auto& connection : handle_to_le_connection_map_) {
connection.second->Shutdown();
}
@@ -968,8 +988,8 @@
connection.second->Shutdown();
}
handle_to_classic_connection_map_.clear();
- LOG_INFO("Cleared all classic connections count:%zu",
- handle_to_classic_connection_map_.size());
+ log::info("Cleared all classic connections count:{}",
+ handle_to_classic_connection_map_.size());
}
if (!handle_to_le_connection_map_.empty()) {
@@ -977,8 +997,8 @@
connection.second->Shutdown();
}
handle_to_le_connection_map_.clear();
- LOG_INFO("Cleared all le connections count:%zu",
- handle_to_le_connection_map_.size());
+ log::info("Cleared all le connections count:{}",
+ handle_to_le_connection_map_.size());
}
promise.set_value();
}
@@ -1042,8 +1062,8 @@
auto remote_address = connection->second->GetRemoteAddress();
connection->second->InitiateDisconnect(
ToDisconnectReasonFromLegacy(reason));
- LOG_DEBUG("Disconnection initiated classic remote:%s handle:%hu",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address), handle);
+ log::debug("Disconnection initiated classic remote:{} handle:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address), handle);
BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address),
"Disconnection initiated",
base::StringPrintf("classic reason:%s comment:%s",
@@ -1051,8 +1071,9 @@
comment.c_str()));
classic_acl_disconnect_reason_.Put(comment);
} else {
- LOG_WARN("Unable to disconnect unknown classic connection handle:0x%04x",
- handle);
+ log::warn(
+ "Unable to disconnect unknown classic connection handle:0x{:04x}",
+ handle);
}
}
@@ -1066,8 +1087,8 @@
}
connection->second->InitiateDisconnect(
ToDisconnectReasonFromLegacy(reason));
- LOG_DEBUG("Disconnection initiated le remote:%s handle:%hu",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address_with_type), handle);
+ log::debug("Disconnection initiated le remote:{} handle:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address_with_type), handle);
BTM_LogHistory(kBtmLogTag,
ToLegacyAddressWithType(remote_address_with_type),
"Disconnection initiated",
@@ -1076,23 +1097,38 @@
comment.c_str()));
le_acl_disconnect_reason_.Put(comment);
} else {
- LOG_WARN("Unable to disconnect unknown le connection handle:0x%04x",
- handle);
+ log::warn("Unable to disconnect unknown le connection handle:0x{:04x}",
+ handle);
}
}
+ void update_connection_parameters(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) {
+ auto connection = handle_to_le_connection_map_.find(handle);
+ if (connection == handle_to_le_connection_map_.end()) {
+ LOG_WARN("Unknown le connection handle:0x%04x", handle);
+ return;
+ }
+ connection->second->UpdateConnectionParameters(conn_int_min, conn_int_max,
+ conn_latency, conn_timeout,
+ min_ce_len, max_ce_len);
+ }
+
void accept_le_connection_from(const hci::AddressWithType& address_with_type,
bool is_direct, std::promise<bool> promise) {
if (shadow_acceptlist_.IsFull()) {
- LOG_ERROR("Acceptlist is full preventing new Le connection");
+ log::error("Acceptlist is full preventing new Le connection");
promise.set_value(false);
return;
}
shadow_acceptlist_.Add(address_with_type);
promise.set_value(true);
GetAclManager()->CreateLeConnection(address_with_type, is_direct);
- LOG_DEBUG("Allow Le connection from remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::debug("Allow Le connection from remote:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
"Allow connection from", "Le");
}
@@ -1101,8 +1137,8 @@
const hci::AddressWithType& address_with_type) {
shadow_acceptlist_.Remove(address_with_type);
GetAclManager()->CancelLeConnect(address_with_type);
- LOG_DEBUG("Ignore Le connection from remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::debug("Ignore Le connection from remote:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
"Ignore connection from", "Le");
}
@@ -1112,15 +1148,15 @@
size_t count = shadow_acceptlist.size();
GetAclManager()->ClearFilterAcceptList();
shadow_acceptlist_.Clear();
- LOG_DEBUG("Cleared entire Le address acceptlist count:%zu", count);
+ log::debug("Cleared entire Le address acceptlist count:{}", count);
}
void AddToAddressResolution(const hci::AddressWithType& address_with_type,
const std::array<uint8_t, 16>& peer_irk,
const std::array<uint8_t, 16>& local_irk) {
if (shadow_address_resolution_list_.IsFull()) {
- LOG_WARN("Le Address Resolution list is full size:%zu",
- shadow_address_resolution_list_.Size());
+ log::warn("Le Address Resolution list is full size:{}",
+ shadow_address_resolution_list_.Size());
return;
}
// TODO This should really be added upon successful completion
@@ -1133,8 +1169,8 @@
const hci::AddressWithType& address_with_type) {
// TODO This should really be removed upon successful removal
if (!shadow_address_resolution_list_.Remove(address_with_type)) {
- LOG_WARN("Unable to remove from Le Address Resolution list device:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::warn("Unable to remove from Le Address Resolution list device:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
}
GetAclManager()->RemoveDeviceFromResolvingList(address_with_type);
}
@@ -1153,13 +1189,13 @@
std::vector<std::string> history =
connection_history_.ReadElementsAsString();
for (auto& entry : history) {
- LOG_DEBUG("%s", entry.c_str());
+ log::debug("{}", entry);
}
const auto acceptlist = shadow_acceptlist_.GetCopy();
- LOG_DEBUG("Shadow le accept list size:%-3zu controller_max_size:%hhu",
- acceptlist.size(), shadow_acceptlist_.GetMaxSize());
+ log::debug("Shadow le accept list size:{:<3} controller_max_size:{}",
+ acceptlist.size(), shadow_acceptlist_.GetMaxSize());
for (auto& entry : acceptlist) {
- LOG_DEBUG("acceptlist:%s", ADDRESS_TO_LOGGABLE_CSTR(entry));
+ log::debug("acceptlist:{}", ADDRESS_TO_LOGGABLE_CSTR(entry));
}
}
@@ -1379,29 +1415,29 @@
bool orphaned_acl_connections = false;
if (!pimpl_->handle_to_classic_connection_map_.empty()) {
- LOG_ERROR("About to destroy classic active ACL");
+ log::error("About to destroy classic active ACL");
for (const auto& connection : pimpl_->handle_to_classic_connection_map_) {
- LOG_ERROR(" Orphaned classic ACL handle:0x%04x bd_addr:%s created:%s",
- connection.second->Handle(),
- ADDRESS_TO_LOGGABLE_CSTR(connection.second->GetRemoteAddress()),
- common::StringFormatTimeWithMilliseconds(
- kConnectionDescriptorTimeFormat,
- connection.second->GetCreationTime())
- .c_str());
+ log::error(
+ "Orphaned classic ACL handle:0x{:04x} bd_addr:{} created:{}",
+ connection.second->Handle(),
+ ADDRESS_TO_LOGGABLE_CSTR(connection.second->GetRemoteAddress()),
+ common::StringFormatTimeWithMilliseconds(
+ kConnectionDescriptorTimeFormat,
+ connection.second->GetCreationTime()));
}
orphaned_acl_connections = true;
}
if (!pimpl_->handle_to_le_connection_map_.empty()) {
- LOG_ERROR("About to destroy le active ACL");
+ log::error("About to destroy le active ACL");
for (const auto& connection : pimpl_->handle_to_le_connection_map_) {
- LOG_ERROR(" Orphaned le ACL handle:0x%04x bd_addr:%s created:%s",
- connection.second->Handle(),
- ADDRESS_TO_LOGGABLE_CSTR(connection.second->GetRemoteAddressWithType()),
- common::StringFormatTimeWithMilliseconds(
- kConnectionDescriptorTimeFormat,
- connection.second->GetCreationTime())
- .c_str());
+ log::error("Orphaned le ACL handle:0x{:04x} bd_addr:{} created:{}",
+ connection.second->Handle(),
+ ADDRESS_TO_LOGGABLE_CSTR(
+ connection.second->GetRemoteAddressWithType()),
+ common::StringFormatTimeWithMilliseconds(
+ kConnectionDescriptorTimeFormat,
+ connection.second->GetCreationTime()));
}
orphaned_acl_connections = true;
}
@@ -1420,7 +1456,7 @@
} else if (pimpl_->IsLeAcl(handle)) {
pimpl_->EnqueueLePacket(handle, std::move(packet));
} else {
- LOG_ERROR("Unable to find destination to write data\n");
+ log::error("Unable to find destination to write data\n");
}
}
@@ -1431,18 +1467,25 @@
std::move(packet)));
}
+void shim::legacy::Acl::flush(HciHandle handle) { pimpl_->Flush(handle); }
+
+void shim::legacy::Acl::Flush(HciHandle handle) {
+ handler_->Post(
+ common::BindOnce(&Acl::flush, common::Unretained(this), handle));
+}
+
void shim::legacy::Acl::CreateClassicConnection(const hci::Address& address) {
GetAclManager()->CreateConnection(address);
- LOG_DEBUG("Connection initiated for classic to remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("Connection initiated for classic to remote:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Initiated connection",
"classic");
}
void shim::legacy::Acl::CancelClassicConnection(const hci::Address& address) {
GetAclManager()->CancelConnect(address);
- LOG_DEBUG("Connection cancelled for classic to remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address));
+ log::debug("Connection cancelled for classic to remote:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address));
BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Cancelled connection",
"classic");
}
@@ -1450,16 +1493,16 @@
void shim::legacy::Acl::AcceptLeConnectionFrom(
const hci::AddressWithType& address_with_type, bool is_direct,
std::promise<bool> promise) {
- LOG_DEBUG("AcceptLeConnectionFrom %s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type.GetAddress()));
+ log::debug("AcceptLeConnectionFrom {}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type.GetAddress()));
handler_->CallOn(pimpl_.get(), &Acl::impl::accept_le_connection_from,
address_with_type, is_direct, std::move(promise));
}
void shim::legacy::Acl::IgnoreLeConnectionFrom(
const hci::AddressWithType& address_with_type) {
- LOG_DEBUG("IgnoreLeConnectionFrom %s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type.GetAddress()));
+ log::debug("IgnoreLeConnectionFrom {}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type.GetAddress()));
handler_->CallOn(pimpl_.get(), &Acl::impl::ignore_le_connection_from,
address_with_type);
}
@@ -1479,9 +1522,9 @@
TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_disconnected,
ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
ToLegacyHciErrorCode(reason));
- LOG_DEBUG("Disconnected classic link remote:%s handle:%hu reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address), handle,
- ErrorCodeText(reason).c_str());
+ log::debug("Disconnected classic link remote:{} handle:{} reason:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address), handle,
+ ErrorCodeText(reason));
BTM_LogHistory(
kBtmLogTag, ToRawAddress(remote_address), "Disconnected",
base::StringPrintf("classic reason:%s", ErrorCodeText(reason).c_str()));
@@ -1505,7 +1548,7 @@
}
return connection->GetLocalAddressWithType();
}
- LOG_WARN("address not found!");
+ log::warn("address not found!");
return address_with_type;
}
@@ -1522,7 +1565,7 @@
}
return connection->GetPeerAddressWithType();
}
- LOG_WARN("address not found!");
+ log::warn("address not found!");
return address_with_type;
}
@@ -1534,7 +1577,7 @@
return connection->GetAdvertisingSetConnectedTo();
}
}
- LOG_WARN("address not found!");
+ log::warn("address not found!");
return {};
}
@@ -1553,9 +1596,9 @@
TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_disconnected,
ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
ToLegacyHciErrorCode(reason));
- LOG_DEBUG("Disconnected le link remote:%s handle:%hu reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address_with_type), handle,
- ErrorCodeText(reason).c_str());
+ log::debug("Disconnected le link remote:{} handle:{} reason:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address_with_type), handle,
+ ErrorCodeText(reason));
BTM_LogHistory(
kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type),
"Disconnected",
@@ -1586,9 +1629,9 @@
TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connected, bd_addr,
handle, false, locally_initiated);
- LOG_DEBUG("Connection successful classic remote:%s handle:%hu initiator:%s",
- ADDRESS_TO_LOGGABLE_CSTR(remote_address), handle,
- (locally_initiated) ? "local" : "remote");
+ log::debug("Connection successful classic remote:{} handle:{} initiator:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(remote_address), handle,
+ (locally_initiated) ? "local" : "remote");
BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address),
"Connection successful",
(locally_initiated) ? "classic Local initiated"
@@ -1602,9 +1645,9 @@
TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connect_request,
bd_addr, cod);
- LOG_DEBUG("Received connect request remote:%s gd_cod:%s legacy_dev_class:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address), cod.ToString().c_str(),
- dev_class_text(dev_class).c_str());
+ log::debug("Received connect request remote:{} gd_cod:{} legacy_dev_class:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), cod.ToString(),
+ dev_class_text(dev_class));
BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection request",
base::StringPrintf("gd_cod:%s legacy_dev_class:%s",
cod.ToString().c_str(),
@@ -1617,8 +1660,8 @@
const RawAddress bd_addr = ToRawAddress(address);
TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_failed, bd_addr,
ToLegacyHciErrorCode(reason), locally_initiated);
- LOG_WARN("Connection failed classic remote:%s reason:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address), hci::ErrorCodeText(reason).c_str());
+ log::warn("Connection failed classic remote:{} reason:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address), hci::ErrorCodeText(reason));
BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection failed",
base::StringPrintf("classic reason:%s",
hci::ErrorCodeText(reason).c_str()));
@@ -1674,13 +1717,13 @@
// the device address is removed from the controller accept list.
if (IsRpa(address_with_type)) {
- LOG_DEBUG("Connection address is rpa:%s identity_addr:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type),
- ADDRESS_TO_LOGGABLE_CSTR(peer_address_with_type));
+ log::debug("Connection address is rpa:{} identity_addr:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type),
+ ADDRESS_TO_LOGGABLE_CSTR(peer_address_with_type));
pimpl_->shadow_acceptlist_.Remove(peer_address_with_type);
} else {
- LOG_DEBUG("Connection address is not rpa addr:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::debug("Connection address is not rpa addr:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
pimpl_->shadow_acceptlist_.Remove(address_with_type);
}
@@ -1688,7 +1731,7 @@
connection_role == hci::Role::CENTRAL) {
pimpl_->handle_to_le_connection_map_[handle]->InitiateDisconnect(
hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
- LOG_INFO("Disconnected ACL after connection canceled");
+ log::info("Disconnected ACL after connection canceled");
BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
"Connection canceled", "Le");
return;
@@ -1706,9 +1749,9 @@
conn_latency, conn_timeout, local_rpa, peer_rpa,
peer_addr_type, can_read_discoverable_characteristics);
- LOG_DEBUG("Connection successful le remote:%s handle:%hu initiator:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type), handle,
- (locally_initiated) ? "local" : "remote");
+ log::debug("Connection successful le remote:{} handle:{} initiator:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type), handle,
+ (locally_initiated) ? "local" : "remote");
BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
"Connection successful", "Le");
}
@@ -1726,8 +1769,8 @@
legacy_address_with_type, handle, enhanced, status);
pimpl_->shadow_acceptlist_.Remove(address_with_type);
- LOG_WARN("Connection failed le remote:%s",
- ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
+ log::warn("Connection failed le remote:{}",
+ ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
BTM_LogHistory(
kBtmLogTag, ToLegacyAddressWithType(address_with_type),
"Connection failed",
@@ -1746,6 +1789,15 @@
comment);
}
+void shim::legacy::Acl::UpdateConnectionParameters(
+ 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) {
+ handler_->CallOn(pimpl_.get(), &Acl::impl::update_connection_parameters,
+ handle, conn_int_min, conn_int_max, conn_latency,
+ conn_timeout, min_ce_len, max_ce_len);
+}
+
bool shim::legacy::Acl::HoldMode(uint16_t hci_handle, uint16_t max_interval,
uint16_t min_interval) {
handler_->CallOn(pimpl_.get(), &Acl::impl::HoldMode, hci_handle, max_interval,
@@ -1812,7 +1864,7 @@
handler_->CallOn(pimpl_.get(), &Acl::impl::DisconnectLeConnections,
std::move(disconnect_promise));
disconnect_future.wait();
- LOG_WARN("Disconnected open ACL connections");
+ log::warn("Disconnected open ACL connections");
}
}
@@ -1830,9 +1882,9 @@
handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownLeConnections,
std::move(shutdown_promise));
shutdown_future.wait();
- LOG_WARN("Flushed open ACL connections");
+ log::warn("Flushed open ACL connections");
} else {
- LOG_INFO("All ACL connections have been previously closed");
+ log::info("All ACL connections have been previously closed");
}
}
@@ -1841,19 +1893,19 @@
auto future = promise.get_future();
GetAclManager()->UnregisterCallbacks(this, std::move(promise));
future.wait();
- LOG_DEBUG("Unregistered classic callbacks from gd acl manager");
+ log::debug("Unregistered classic callbacks from gd acl manager");
promise = std::promise<void>();
future = promise.get_future();
GetAclManager()->UnregisterLeCallbacks(this, std::move(promise));
future.wait();
- LOG_DEBUG("Unregistered le callbacks from gd acl manager");
+ log::debug("Unregistered le callbacks from gd acl manager");
promise = std::promise<void>();
future = promise.get_future();
handler_->CallOn(pimpl_.get(), &Acl::impl::FinalShutdown, std::move(promise));
future.wait();
- LOG_INFO("Unregistered and cleared any orphaned ACL connections");
+ log::info("Unregistered and cleared any orphaned ACL connections");
}
void shim::legacy::Acl::ClearFilterAcceptList() {
diff --git a/system/main/shim/acl.h b/system/main/shim/acl.h
index cd44441..ec659bd 100644
--- a/system/main/shim/acl.h
+++ b/system/main/shim/acl.h
@@ -82,6 +82,10 @@
std::string comment) override;
void DisconnectLe(uint16_t handle, tHCI_REASON reason,
std::string comment) override;
+ void UpdateConnectionParameters(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) override;
// Address Resolution List
void AddToAddressResolution(const hci::AddressWithType& address_with_type,
@@ -111,6 +115,8 @@
void WriteData(uint16_t hci_handle,
std::unique_ptr<packet::RawBuilder> packet);
+ void Flush(uint16_t hci_handle);
+
void Dump(int fd) const;
void DumpConnectionHistory(int fd) const;
@@ -125,6 +131,7 @@
void on_incoming_acl_credits(uint16_t handle, uint16_t credits);
void write_data_sync(uint16_t hci_handle,
std::unique_ptr<packet::RawBuilder> packet);
+ void flush(uint16_t hci_handle);
private:
os::Handler* handler_;
diff --git a/system/main/shim/acl_api.cc b/system/main/shim/acl_api.cc
index ee9150f..2495d49 100644
--- a/system/main/shim/acl_api.cc
+++ b/system/main/shim/acl_api.cc
@@ -72,6 +72,19 @@
osi_free(p_buf);
}
+void bluetooth::shim::ACL_Flush(uint16_t handle) {
+ Stack::GetInstance()->GetAcl()->Flush(handle);
+}
+
+void bluetooth::shim::ACL_SendConnectionParameterUpdateRequest(
+ 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) {
+ Stack::GetInstance()->GetAcl()->UpdateConnectionParameters(
+ handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
+ min_ce_len, max_ce_len);
+}
+
void bluetooth::shim::ACL_ConfigureLePrivacy(bool is_le_privacy_enabled) {
hci::LeAddressManager::AddressPolicy address_policy =
is_le_privacy_enabled
diff --git a/system/main/shim/acl_api.h b/system/main/shim/acl_api.h
index 3c705cf..07ccfe1 100644
--- a/system/main/shim/acl_api.h
+++ b/system/main/shim/acl_api.h
@@ -36,6 +36,7 @@
void ACL_Disconnect(uint16_t handle, bool is_classic, tHCI_STATUS reason,
std::string comment);
void ACL_WriteData(uint16_t handle, BT_HDR* p_buf);
+void ACL_Flush(uint16_t handle);
void ACL_ConfigureLePrivacy(bool is_le_privacy_enabled);
void ACL_Shutdown();
void ACL_IgnoreAllLeConnections();
@@ -59,6 +60,10 @@
void ACL_LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max,
uint16_t max_latency, uint16_t cont_num,
uint16_t sup_tout);
+void ACL_SendConnectionParameterUpdateRequest(
+ 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 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);
diff --git a/system/main/shim/btm.cc b/system/main/shim/btm.cc
index 5269832..4d6dd10 100644
--- a/system/main/shim/btm.cc
+++ b/system/main/shim/btm.cc
@@ -19,6 +19,7 @@
#include "main/shim/btm.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <chrono>
#include <cstddef>
@@ -42,6 +43,8 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
extern tBTM_CB btm_cb;
static constexpr bool kActiveScanning = true;
@@ -185,7 +188,7 @@
LegacyInquiryCompleteCallback legacy_inquiry_complete_callback) {
switch (mode) {
case kInquiryModeOff:
- LOG_INFO("%s Stopping inquiry mode", __func__);
+ log::info("Stopping inquiry mode");
if (limited_inquiry_active_ || general_inquiry_active_) {
GetInquiry()->StopInquiry();
limited_inquiry_active_ = false;
@@ -197,18 +200,14 @@
case kLimitedInquiryMode:
case kGeneralInquiryMode: {
if (mode == kLimitedInquiryMode) {
- LOG_INFO(
-
- "%s Starting limited inquiry mode duration:%hhd max responses:%hhd",
- __func__, duration, max_responses);
+ log::info("Starting limited inquiry mode duration:{} max responses:{}",
+ duration, max_responses);
limited_inquiry_active_ = true;
GetInquiry()->StartLimitedInquiry(duration, max_responses);
active_inquiry_mode_ = kLimitedInquiryMode;
} else {
- LOG_INFO(
-
- "%s Starting general inquiry mode duration:%hhd max responses:%hhd",
- __func__, duration, max_responses);
+ log::info("Starting general inquiry mode duration:{} max responses:{}",
+ duration, max_responses);
general_inquiry_active_ = true;
GetInquiry()->StartGeneralInquiry(duration, max_responses);
legacy_inquiry_complete_callback_ = legacy_inquiry_complete_callback;
@@ -216,14 +215,14 @@
} break;
default:
- LOG_WARN("%s Unknown inquiry mode:%d", __func__, mode);
+ log::warn("Unknown inquiry mode:{}", mode);
return false;
}
return true;
}
void Btm::CancelInquiry() {
- LOG_INFO("%s", __func__);
+ log::info("");
if (limited_inquiry_active_ || general_inquiry_active_) {
GetInquiry()->StopInquiry();
limited_inquiry_active_ = false;
@@ -256,12 +255,12 @@
case kLimitedInquiryMode:
case kGeneralInquiryMode: {
if (mode == kLimitedInquiryMode) {
- LOG_INFO("%s Starting limited periodic inquiry mode", __func__);
+ log::info("Starting limited periodic inquiry mode");
limited_periodic_inquiry_active_ = true;
GetInquiry()->StartLimitedPeriodicInquiry(duration, max_responses,
max_delay, min_delay);
} else {
- LOG_INFO("%s Starting general periodic inquiry mode", __func__);
+ log::info("Starting general periodic inquiry mode");
general_periodic_inquiry_active_ = true;
GetInquiry()->StartGeneralPeriodicInquiry(duration, max_responses,
max_delay, min_delay);
@@ -269,7 +268,7 @@
} break;
default:
- LOG_WARN("%s Unknown inquiry mode:%d", __func__, mode);
+ log::warn("Unknown inquiry mode:{}", mode);
return false;
}
return true;
@@ -324,15 +323,11 @@
return state;
}
-void Btm::SetLeGeneralDiscoverability() {
- LOG_WARN("UNIMPLEMENTED %s", __func__);
-}
+void Btm::SetLeGeneralDiscoverability() { log::warn("UNIMPLEMENTED"); }
-void Btm::SetLeLimitedDiscoverability() {
- LOG_WARN("UNIMPLEMENTED %s", __func__);
-}
+void Btm::SetLeLimitedDiscoverability() { log::warn("UNIMPLEMENTED"); }
-void Btm::SetLeDiscoverabilityOff() { LOG_WARN("UNIMPLEMENTED %s", __func__); }
+void Btm::SetLeDiscoverabilityOff() { log::warn("UNIMPLEMENTED"); }
DiscoverabilityState Btm::GetLeDiscoverabilityState() const {
DiscoverabilityState state{
@@ -340,7 +335,7 @@
.interval = 0,
.window = 0,
};
- LOG_WARN("UNIMPLEMENTED %s", __func__);
+ log::warn("UNIMPLEMENTED");
return state;
}
@@ -371,9 +366,9 @@
void Btm::SetStandardPageScan() { GetPage()->SetStandardScan(); }
-void Btm::SetLeConnectibleOn() { LOG_WARN("UNIMPLEMENTED %s", __func__); }
+void Btm::SetLeConnectibleOn() { log::warn("UNIMPLEMENTED"); }
-void Btm::SetLeConnectibleOff() { LOG_WARN("UNIMPLEMENTED %s", __func__); }
+void Btm::SetLeConnectibleOff() { log::warn("UNIMPLEMENTED"); }
ConnectabilityState Btm::GetLeConnectabilityState() const {
ConnectabilityState state{
@@ -381,7 +376,7 @@
.interval = 0,
.window = 0,
};
- LOG_WARN("UNIMPLEMENTED %s", __func__);
+ log::warn("UNIMPLEMENTED");
return state;
}
@@ -399,25 +394,25 @@
BtmStatus Btm::ReadClassicRemoteDeviceName(const RawAddress& /* raw_address */,
tBTM_NAME_CMPL_CB* /* callback */) {
- LOG_ALWAYS_FATAL("unreachable");
+ log::fatal("unreachable");
return BTM_UNDEFINED;
}
BtmStatus Btm::CancelAllReadRemoteDeviceName() {
- LOG_ALWAYS_FATAL("unreachable");
+ log::fatal("unreachable");
return BTM_UNDEFINED;
}
-void Btm::StartAdvertising() { LOG_ALWAYS_FATAL("unreachable"); }
+void Btm::StartAdvertising() { log::fatal("unreachable"); }
void Btm::StopAdvertising() {
if (advertiser_id_ == hci::LeAdvertisingManager::kInvalidId) {
- LOG_WARN("%s No active advertising", __func__);
+ log::warn("No active advertising");
return;
}
GetAdvertising()->RemoveAdvertiser(advertiser_id_);
advertiser_id_ = hci::LeAdvertisingManager::kInvalidId;
- LOG_INFO("%s Stopped advertising", __func__);
+ log::info("Stopped advertising");
}
void Btm::StartConnectability() { StartAdvertising(); }
@@ -482,7 +477,7 @@
p_dev_rec->ble.AddressType());
}
}
- LOG(ERROR) << "Unknown bd_addr. Use public address";
+ log::error("Unknown bd_addr. Use public address");
return ToAddressWithType(bd_addr, BLE_ADDR_PUBLIC);
}
diff --git a/system/main/shim/btm_api.cc b/system/main/shim/btm_api.cc
index 188f12b..dd1784b 100644
--- a/system/main/shim/btm_api.cc
+++ b/system/main/shim/btm_api.cc
@@ -21,8 +21,10 @@
#include <base/functional/callback.h>
#include <base/logging.h>
+#include "hci/controller.h"
+#include "hci/controller_interface.h"
#include "main/shim/btm.h"
-#include "main/shim/controller.h"
+#include "main/shim/entry.h"
#include "main/shim/helpers.h"
#include "main/shim/stack.h"
#include "stack/btm/btm_ble_sec.h"
@@ -35,12 +37,13 @@
}
tBTM_STATUS bluetooth::shim::BTM_ClearEventFilter() {
- controller_get_interface()->clear_event_filter();
+ GetController()->SetEventFilterClearAll();
return BTM_SUCCESS;
}
tBTM_STATUS bluetooth::shim::BTM_ClearEventMask() {
- controller_get_interface()->clear_event_mask();
+ GetController()->SetEventMask(0);
+ GetController()->LeSetEventMask(0);
return BTM_SUCCESS;
}
@@ -57,7 +60,8 @@
tBTM_STATUS bluetooth::shim::BTM_SetEventFilterConnectionSetupAllDevices() {
// Autoplumbed
- controller_get_interface()->set_event_filter_connection_setup_all_devices();
+ GetController()->SetEventFilterConnectionSetupAllDevices(
+ bluetooth::hci::AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED);
return BTM_SUCCESS;
}
@@ -68,8 +72,11 @@
Stack::GetInstance()->GetAcl()->SetSystemSuspendState(/*suspended=*/true);
// Allow classic HID wake.
- controller_get_interface()->set_event_filter_allow_device_connection(
- std::move(classic_hid_devices));
+ auto controller = GetController();
+ for (auto device : classic_hid_devices) {
+ controller->SetEventFilterConnectionSetupAddress(
+ bluetooth::ToGdAddress(device), hci::AutoAcceptFlag::AUTO_ACCEPT_OFF);
+ }
// Allow BLE HID
for (auto hid_address : le_hid_devices) {
@@ -111,14 +118,18 @@
tBTM_STATUS bluetooth::shim::BTM_SetDefaultEventMaskExcept(uint64_t mask,
uint64_t le_mask) {
- // Autoplumbed
- controller_get_interface()->set_default_event_mask_except(mask, le_mask);
+ uint64_t applied_mask =
+ bluetooth::hci::Controller::kDefaultEventMask & ~(mask);
+ uint64_t applied_le_mask =
+ bluetooth::hci::Controller::kDefaultLeEventMask & ~(le_mask);
+ GetController()->SetEventMask(applied_mask);
+ GetController()->LeSetEventMask(applied_le_mask);
return BTM_SUCCESS;
}
tBTM_STATUS bluetooth::shim::BTM_SetEventFilterInquiryResultAllDevices() {
// Autoplumbed
- controller_get_interface()->set_event_filter_inquiry_result_all_devices();
+ GetController()->SetEventFilterInquiryResultAllDevices();
return BTM_SUCCESS;
}
diff --git a/system/main/shim/controller.cc b/system/main/shim/controller.cc
deleted file mode 100644
index 0daf436..0000000
--- a/system/main/shim/controller.cc
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "bt_shim_controller"
-
-#include "main/shim/controller.h"
-
-#include "btcore/include/module.h"
-#include "hci/controller.h"
-#include "hci/controller_interface.h"
-#include "include/check.h"
-#include "main/shim/entry.h"
-#include "main/shim/helpers.h"
-#include "main/shim/shim.h"
-#include "osi/include/future.h"
-#include "stack/include/btm_status.h"
-#include "types/raw_address.h"
-
-using ::bluetooth::shim::GetController;
-
-constexpr int kMaxSupportedCodecs = 8; // MAX_LOCAL_SUPPORTED_CODECS_SIZE
-
-constexpr uint8_t kPhyLe1M = 0x01;
-
-// Module lifecycle functions
-static future_t* start_up(void);
-static future_t* shut_down(void);
-
-EXPORT_SYMBOL extern const module_t gd_controller_module = {
- .name = GD_CONTROLLER_MODULE,
- .init = nullptr,
- .start_up = start_up,
- .shut_down = shut_down,
- .clean_up = nullptr,
- .dependencies = {GD_SHIM_MODULE, nullptr}};
-
-struct {
- bool ready;
- RawAddress raw_address;
- bt_version_t bt_version;
- uint8_t local_supported_codecs[kMaxSupportedCodecs];
- uint8_t number_of_local_supported_codecs;
- uint64_t le_supported_states;
- uint8_t phy;
-} data_;
-
-static future_t* start_up(void) {
- LOG_INFO("%s Starting up", __func__);
- data_.ready = true;
-
- std::string string_address = GetController()->GetMacAddress().ToString();
- RawAddress::FromString(string_address, data_.raw_address);
-
- data_.le_supported_states =
- bluetooth::shim::GetController()->GetLeSupportedStates();
-
- auto local_version_info =
- bluetooth::shim::GetController()->GetLocalVersionInformation();
- data_.bt_version.hci_version =
- static_cast<uint8_t>(local_version_info.hci_version_);
- data_.bt_version.hci_revision = local_version_info.hci_revision_;
- data_.bt_version.lmp_version =
- static_cast<uint8_t>(local_version_info.lmp_version_);
- data_.bt_version.lmp_subversion = local_version_info.lmp_subversion_;
- data_.bt_version.manufacturer = local_version_info.manufacturer_name_;
-
- LOG_INFO("Mac address:%s", ADDRESS_TO_LOGGABLE_CSTR(data_.raw_address));
-
- data_.phy = kPhyLe1M;
-
- return future_new_immediate(FUTURE_SUCCESS);
-}
-
-static future_t* shut_down(void) {
- data_.ready = false;
- return future_new_immediate(FUTURE_SUCCESS);
-}
-
-/**
- * Module methods
- */
-
-static bool get_is_ready(void) { return data_.ready; }
-
-static const RawAddress* get_address(void) { return &data_.raw_address; }
-
-static const bt_version_t* get_bt_version(void) { return &data_.bt_version; }
-
-static uint8_t* get_local_supported_codecs(uint8_t* number_of_codecs) {
- CHECK(number_of_codecs != nullptr);
- if (data_.number_of_local_supported_codecs != 0) {
- *number_of_codecs = data_.number_of_local_supported_codecs;
- return data_.local_supported_codecs;
- }
- return (uint8_t*)nullptr;
-}
-
-static const uint8_t* get_ble_supported_states(void) {
- return (const uint8_t*)&data_.le_supported_states;
-}
-
-#define FORWARD_GETTER(type, legacy, gd) \
- static type legacy(void) { return gd; }
-
-FORWARD_GETTER(uint16_t, get_le_suggested_default_data_length,
- GetController()->GetLeSuggestedDefaultDataLength())
-
-static uint16_t get_le_maximum_tx_data_length(void) {
- ::bluetooth::hci::LeMaximumDataLength le_maximum_data_length =
- GetController()->GetLeMaximumDataLength();
- return le_maximum_data_length.supported_max_tx_octets_;
-}
-
-static uint16_t get_le_maximum_tx_time(void) {
- ::bluetooth::hci::LeMaximumDataLength le_maximum_data_length =
- GetController()->GetLeMaximumDataLength();
- return le_maximum_data_length.supported_max_tx_time_;
-}
-
-FORWARD_GETTER(uint16_t, get_le_max_advertising_data_length,
- GetController()->GetLeMaximumAdvertisingDataLength())
-FORWARD_GETTER(uint8_t, get_le_supported_advertising_sets,
- GetController()->GetLeNumberOfSupportedAdverisingSets())
-FORWARD_GETTER(uint8_t, get_le_periodic_advertiser_list_size,
- GetController()->GetLePeriodicAdvertiserListSize())
-FORWARD_GETTER(uint8_t, get_le_connect_list_size,
- GetController()->GetLeFilterAcceptListSize())
-
-static void set_ble_resolving_list_max_size(int /* resolving_list_max_size */) {
- LOG_DEBUG("UNSUPPORTED");
-}
-
-static uint8_t get_le_resolving_list_size(void) {
- return bluetooth::shim::GetController()->GetLeResolvingListSize();
-}
-
-static uint8_t get_le_all_initiating_phys() { return data_.phy; }
-
-static uint8_t controller_clear_event_filter() {
- LOG_VERBOSE("Called!");
- bluetooth::shim::GetController()->SetEventFilterClearAll();
- return BTM_SUCCESS;
-}
-
-static uint8_t controller_clear_event_mask() {
- LOG_VERBOSE("Called!");
- bluetooth::shim::GetController()->SetEventMask(0);
- bluetooth::shim::GetController()->LeSetEventMask(0);
- return BTM_SUCCESS;
-}
-
-static uint8_t controller_set_event_filter_connection_setup_all_devices() {
- bluetooth::shim::GetController()->SetEventFilterConnectionSetupAllDevices(
- bluetooth::hci::AutoAcceptFlag::AUTO_ACCEPT_ON_ROLE_SWITCH_ENABLED);
- return BTM_SUCCESS;
-}
-
-static uint8_t controller_set_event_filter_allow_device_connection(
- std::vector<RawAddress> devices) {
- for (const RawAddress& address : devices) {
- bluetooth::shim::GetController()->SetEventFilterConnectionSetupAddress(
- bluetooth::ToGdAddress(address),
- bluetooth::hci::AutoAcceptFlag::AUTO_ACCEPT_OFF);
- }
- return BTM_SUCCESS;
-}
-
-static uint8_t controller_set_default_event_mask_except(uint64_t mask,
- uint64_t le_mask) {
- uint64_t applied_mask =
- bluetooth::hci::Controller::kDefaultEventMask & ~(mask);
- uint64_t applied_le_mask =
- bluetooth::hci::Controller::kDefaultLeEventMask & ~(le_mask);
-
- bluetooth::shim::GetController()->SetEventMask(applied_mask);
- bluetooth::shim::GetController()->LeSetEventMask(applied_le_mask);
- return BTM_SUCCESS;
-}
-
-static uint8_t controller_set_event_filter_inquiry_result_all_devices() {
- bluetooth::shim::GetController()->SetEventFilterInquiryResultAllDevices();
- return BTM_SUCCESS;
-}
-
-static const controller_t interface = {
- .get_is_ready = get_is_ready,
-
- .get_address = get_address,
- .get_bt_version = get_bt_version,
-
- .get_ble_supported_states = get_ble_supported_states,
-
- .get_ble_default_data_packet_length = get_le_suggested_default_data_length,
- .get_ble_maximum_tx_data_length = get_le_maximum_tx_data_length,
- .get_ble_maximum_tx_time = get_le_maximum_tx_time,
- .get_ble_maximum_advertising_data_length =
- get_le_max_advertising_data_length,
- .get_ble_number_of_supported_advertising_sets =
- get_le_supported_advertising_sets,
- .get_ble_periodic_advertiser_list_size =
- get_le_periodic_advertiser_list_size,
-
- .get_ble_acceptlist_size = get_le_connect_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,
- .get_local_supported_codecs = get_local_supported_codecs,
- .get_le_all_initiating_phys = get_le_all_initiating_phys,
- .clear_event_filter = controller_clear_event_filter,
- .clear_event_mask = controller_clear_event_mask,
- .set_event_filter_connection_setup_all_devices =
- controller_set_event_filter_connection_setup_all_devices,
- .set_event_filter_allow_device_connection =
- controller_set_event_filter_allow_device_connection,
- .set_default_event_mask_except = controller_set_default_event_mask_except,
- .set_event_filter_inquiry_result_all_devices =
- controller_set_event_filter_inquiry_result_all_devices};
-
-const controller_t* bluetooth::shim::controller_get_interface() {
- static bool loaded = false;
- if (!loaded) {
- loaded = true;
- }
- return &interface;
-}
-
-bool bluetooth::shim::controller_is_write_link_supervision_timeout_supported() {
- return bluetooth::shim::GetController()->IsSupported(
- bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT);
-}
diff --git a/system/main/shim/controller.h b/system/main/shim/controller.h
deleted file mode 100644
index d04f1d7..0000000
--- a/system/main/shim/controller.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include "device/include/controller.h"
-
-static const char GD_CONTROLLER_MODULE[] = "gd_controller_module";
-
-namespace bluetooth {
-namespace shim {
-
-const controller_t* controller_get_interface();
-
-void controller_clear_event_mask();
-bool controller_is_write_link_supervision_timeout_supported();
-
-} // namespace shim
-} // namespace bluetooth
diff --git a/system/main/shim/hci_layer.cc b/system/main/shim/hci_layer.cc
index e14e106..fda270b8 100644
--- a/system/main/shim/hci_layer.cc
+++ b/system/main/shim/hci_layer.cc
@@ -19,6 +19,7 @@
#include "main/shim/hci_layer.h"
#include <base/functional/bind.h>
+#include <bluetooth/log.h>
#include <algorithm>
#include <cstdint>
@@ -41,6 +42,8 @@
#include "stack/include/hcimsgs.h"
#include "stack/include/main_thread.h"
+using namespace bluetooth;
+
/**
* Callback data wrapped as opaque token bundled with the command
* transmit request to the Gd layer.
@@ -175,8 +178,8 @@
void OnTransmitPacketCommandComplete(command_complete_cb complete_callback,
void* context,
bluetooth::hci::CommandCompleteView view) {
- LOG_DEBUG("Received cmd complete for %s",
- bluetooth::hci::OpCodeText(view.GetCommandOpCode()).c_str());
+ log::debug("Received cmd complete for {}",
+ bluetooth::hci::OpCodeText(view.GetCommandOpCode()));
BT_HDR* response = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &view);
complete_callback(response, context);
}
@@ -184,9 +187,9 @@
void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
std::unique_ptr<OsiObject> command,
bluetooth::hci::CommandStatusView view) {
- LOG_DEBUG("Received cmd status %s for %s",
- bluetooth::hci::ErrorCodeText(view.GetStatus()).c_str(),
- bluetooth::hci::OpCodeText(view.GetCommandOpCode()).c_str());
+ log::debug("Received cmd status {} for {}",
+ bluetooth::hci::ErrorCodeText(view.GetStatus()),
+ bluetooth::hci::OpCodeText(view.GetCommandOpCode()));
uint8_t status = static_cast<uint8_t>(view.GetStatus());
status_callback(status, static_cast<BT_HDR*>(command->Release()), context);
}
@@ -212,7 +215,7 @@
auto packet =
bluetooth::hci::CommandBuilder::Create(op_code, std::move(payload));
- LOG_DEBUG("Sending command %s", bluetooth::hci::OpCodeText(op_code).c_str());
+ log::debug("Sending command {}", bluetooth::hci::OpCodeText(op_code));
if (bluetooth::hci::Checker::IsCommandStatusOpcode(op_code)) {
auto command_unique = std::make_unique<OsiObject>(command);
@@ -270,7 +273,7 @@
auto packet = hci_iso_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 (!send_data_upwards) {
@@ -295,8 +298,9 @@
auto iso = bluetooth::hci::IsoManager::GetInstance();
if (iso) {
auto reason = static_cast<uint8_t>(error_code);
- LOG_INFO("ISO disconnection from GD, handle: 0x%02x, reason: 0x%02x",
- handle, reason);
+ log::info(
+ "ISO disconnection from GD, handle: 0x{:02x}, reason: 0x{:02x}",
+ handle, reason);
iso->HandleDisconnect(handle, reason);
}
}));
diff --git a/system/main/shim/helpers.h b/system/main/shim/helpers.h
index 36cc9fe..cb4f8a3 100644
--- a/system/main/shim/helpers.h
+++ b/system/main/shim/helpers.h
@@ -15,6 +15,8 @@
*/
#pragma once
+#include <bluetooth/log.h>
+
#include <vector>
#include "common/init_flags.h"
@@ -69,7 +71,7 @@
else if (legacy_type == BLE_ADDR_RANDOM_ID)
type = hci::AddressType::RANDOM_IDENTITY_ADDRESS;
else {
- LOG_ALWAYS_FATAL("Bad address type %02x", legacy_type);
+ log::fatal("Bad address type {:02x}", legacy_type);
return hci::AddressWithType{address,
hci::AddressType::PUBLIC_DEVICE_ADDRESS};
}
@@ -101,8 +103,8 @@
hci::AddressType::RANDOM_IDENTITY_ADDRESS) {
legacy_address_with_type.type = BLE_ADDR_RANDOM_ID;
} else {
- LOG_ALWAYS_FATAL("%s Bad address type %02x", __func__,
- static_cast<uint8_t>(address_with_type.GetAddressType()));
+ log::fatal("Bad address type {:02x}",
+ static_cast<uint8_t>(address_with_type.GetAddressType()));
legacy_address_with_type.type = BLE_ADDR_PUBLIC;
}
return legacy_address_with_type;
@@ -274,7 +276,7 @@
if (len == 0) break;
pbuf += sprintf(pbuf, "0x%02x ", *data);
}
- LOG_DEBUG("%s %s", token, buf);
+ log::debug("{} {}", token, buf);
}
}
diff --git a/system/main/shim/le_advertising_manager.cc b/system/main/shim/le_advertising_manager.cc
index a1ec02f..07ff568 100644
--- a/system/main/shim/le_advertising_manager.cc
+++ b/system/main/shim/le_advertising_manager.cc
@@ -19,6 +19,7 @@
#include "le_advertising_manager.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <hardware/bluetooth.h>
#include <hardware/bt_gatt.h>
@@ -42,6 +43,7 @@
using bluetooth::hci::OwnAddressType;
using bluetooth::shim::parse_gap_data;
using std::vector;
+using namespace bluetooth;
namespace {
constexpr char kBtmLogTag[] = "ADV";
@@ -58,7 +60,7 @@
}
void RegisterAdvertiser(IdStatusCallback cb) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetAdvertising()->RegisterAdvertiser(
bluetooth::shim::GetGdShimHandler()->BindOnce(
@@ -73,7 +75,7 @@
}
void Unregister(uint8_t advertiser_id) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetAdvertising()->RemoveAdvertiser(advertiser_id);
int reg_id =
bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id);
@@ -87,14 +89,14 @@
}
void GetOwnAddress(uint8_t advertiser_id, GetAddressCallback cb) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
address_callbacks_[advertiser_id] = jni_thread_wrapper(FROM_HERE, cb);
bluetooth::shim::GetAdvertising()->GetOwnAddress(advertiser_id);
}
void SetParameters(uint8_t advertiser_id, AdvertiseParameters params,
ParametersCallback /* cb */) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::hci::AdvertisingConfig config{};
parse_parameter(config, params);
bluetooth::shim::GetAdvertising()->SetParameters(advertiser_id, config);
@@ -102,7 +104,7 @@
void SetData(int advertiser_id, bool set_scan_rsp, vector<uint8_t> data,
StatusCallback /* cb */) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
std::vector<GapData> advertising_data = {};
parse_gap_data(data, advertising_data);
bluetooth::shim::GetAdvertising()->SetData(advertiser_id, set_scan_rsp,
@@ -112,7 +114,7 @@
void Enable(uint8_t advertiser_id, bool enable, StatusCallback /* cb */,
uint16_t duration, uint8_t maxExtAdvEvents,
StatusCallback /* timeout_cb */) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetAdvertising()->EnableAdvertiser(
advertiser_id, enable, duration, maxExtAdvEvents);
}
@@ -123,7 +125,7 @@
std::vector<uint8_t> advertise_data,
std::vector<uint8_t> scan_response_data, int timeout_s,
StatusCallback timeout_cb) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::hci::AdvertisingConfig config{};
parse_parameter(config, params);
@@ -145,7 +147,7 @@
std::vector<uint8_t> periodic_data,
uint16_t duration, uint8_t maxExtAdvEvents,
IdStatusCallback /* timeout_cb */) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::hci::AdvertisingConfig config{};
parse_parameter(config, params);
@@ -165,8 +167,8 @@
client_id, reg_id, config, scan_callback, set_terminated_callback,
duration, maxExtAdvEvents, bluetooth::shim::GetGdShimHandler());
- LOG_INFO("create advertising set, client_id:%d, reg_id:%d", client_id,
- reg_id);
+ log::info("create advertising set, client_id:{}, reg_id:{}", client_id,
+ reg_id);
BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, "Le advert started",
base::StringPrintf("reg_id:%d", reg_id));
@@ -176,7 +178,7 @@
void SetPeriodicAdvertisingParameters(
int advertiser_id, PeriodicAdvertisingParameters periodic_params,
StatusCallback /* cb */) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::hci::PeriodicAdvertisingParameters parameters;
parameters.max_interval = periodic_params.max_interval;
parameters.min_interval = periodic_params.min_interval;
@@ -187,7 +189,7 @@
void SetPeriodicAdvertisingData(int advertiser_id, std::vector<uint8_t> data,
StatusCallback /* cb */) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
std::vector<GapData> advertising_data = {};
parse_gap_data(data, advertising_data);
bluetooth::shim::GetAdvertising()->SetPeriodicData(advertiser_id,
@@ -197,7 +199,7 @@
void SetPeriodicAdvertisingEnable(int advertiser_id, bool enable,
bool include_adi,
StatusCallback /* cb */) override {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetAdvertising()->EnablePeriodicAdvertising(
advertiser_id, enable, include_adi);
}
@@ -212,11 +214,11 @@
}
void on_scan(Address /* address */, AddressType /* address_type */) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
}
void on_set_terminated(ErrorCode /* error_code */, uint8_t, uint8_t) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
}
const bluetooth::common::Callback<void(Address, AddressType)> scan_callback =
@@ -373,8 +375,8 @@
AdvertiserAddressType::NONRESOLVABLE_RANDOM;
break;
default:
- LOG_ERROR("Received unexpected address type: %d",
- params.own_address_type);
+ log::error("Received unexpected address type: {}",
+ params.own_address_type);
config.requested_advertiser_address_type =
AdvertiserAddressType::RESOLVABLE_RANDOM;
}
diff --git a/system/main/shim/le_scanning_manager.cc b/system/main/shim/le_scanning_manager.cc
index ebb2489..55a5e65 100644
--- a/system/main/shim/le_scanning_manager.cc
+++ b/system/main/shim/le_scanning_manager.cc
@@ -21,6 +21,7 @@
#include <base/functional/bind.h>
#include <base/logging.h>
#include <base/threading/thread.h>
+#include <bluetooth/log.h>
#include <hardware/bluetooth.h>
#include <stdio.h>
@@ -48,6 +49,7 @@
using bluetooth::ToGdAddress;
using bluetooth::ToRawAddress;
+using namespace bluetooth;
extern tBTM_CB btm_cb;
@@ -118,7 +120,7 @@
private:
static void LogUnused() {
- LOG_WARN("BLE Scanning callbacks have not been registered");
+ log::warn("BLE Scanning callbacks have not been registered");
}
} default_scanning_callback_;
@@ -148,7 +150,7 @@
using bluetooth::shim::BleScannerInterfaceImpl;
void BleScannerInterfaceImpl::Init() {
- LOG_INFO("init BleScannerInterfaceImpl");
+ log::info("init BleScannerInterfaceImpl");
bluetooth::shim::GetScanning()->RegisterScanningCallback(this);
if (bluetooth::shim::GetMsftExtensionManager()) {
@@ -159,20 +161,20 @@
/** Registers a scanner with the stack */
void BleScannerInterfaceImpl::RegisterScanner(const bluetooth::Uuid& uuid,
RegisterCallback) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
auto app_uuid = bluetooth::hci::Uuid::From128BitBE(uuid.To128BitBE());
bluetooth::shim::GetScanning()->RegisterScanner(app_uuid);
}
/** Unregister a scanner from the stack */
void BleScannerInterfaceImpl::Unregister(int scanner_id) {
- LOG(INFO) << __func__ << " in shim layer, scanner_id:" << scanner_id;
+ log::info("in shim layer, scanner_id:{}", scanner_id);
bluetooth::shim::GetScanning()->Unregister(scanner_id);
}
/** Start or stop LE device scanning */
void BleScannerInterfaceImpl::Scan(bool start) {
- LOG(INFO) << __func__ << " in shim layer " << ((start) ? "started" : "stopped");
+ log::info("in shim layer {}", ((start) ? "started" : "stopped"));
bluetooth::shim::GetScanning()->Scan(start);
if (start && !btm_cb.ble_ctr_cb.is_ble_observe_active()) {
btm_cb.neighbor.le_scan = {
@@ -193,8 +195,8 @@
btm_cb.ble_ctr_cb.reset_ble_observe();
btm_cb.neighbor.le_scan = {};
} else {
- LOG_WARN("Invalid state: start:%d, current scan state: %d", start,
- btm_cb.ble_ctr_cb.is_ble_observe_active());
+ log::warn("Invalid state: start:{}, current scan state: {}", start,
+ btm_cb.ble_ctr_cb.is_ble_observe_active());
return;
}
@@ -208,7 +210,7 @@
uint8_t client_if, uint8_t action, uint8_t filter_index,
std::unique_ptr<btgatt_filt_param_setup_t> filt_param,
FilterParamSetupCallback cb) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
auto apcf_action = static_cast<bluetooth::hci::ApcfAction>(action);
bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter;
@@ -247,13 +249,13 @@
void BleScannerInterfaceImpl::ScanFilterAdd(int filter_index,
std::vector<ApcfCommand> filters,
FilterConfigCallback cb) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
std::vector<bluetooth::hci::AdvertisingPacketContentFilterCommand>
new_filters = {};
for (size_t i = 0; i < filters.size(); i++) {
bluetooth::hci::AdvertisingPacketContentFilterCommand command{};
if (!parse_filter_command(command, filters[i])) {
- LOG_ERROR("invalid apcf command");
+ log::error("invalid apcf command");
return;
}
new_filters.push_back(command);
@@ -266,13 +268,13 @@
/** Clear all scan filter conditions for specific filter index*/
void BleScannerInterfaceImpl::ScanFilterClear(int /* filter_index */,
FilterConfigCallback /* cb */) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
// This function doesn't used in java layer
}
/** Enable / disable scan filter feature*/
void BleScannerInterfaceImpl::ScanFilterEnable(bool enable, EnableCallback cb) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetScanning()->ScanFilterEnable(enable);
uint8_t action = enable ? 1 : 0;
@@ -282,7 +284,7 @@
/** Is MSFT Extension supported? */
bool BleScannerInterfaceImpl::IsMsftSupported() {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
return bluetooth::shim::GetMsftExtensionManager()->SupportsMsftExtensions();
}
@@ -290,7 +292,7 @@
/** Adds MSFT filter */
void BleScannerInterfaceImpl::MsftAdvMonitorAdd(MsftAdvMonitor monitor,
MsftAdvMonitorAddCallback cb) {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
msft_callbacks_.Add = cb;
bluetooth::shim::GetMsftExtensionManager()->MsftAdvMonitorAdd(
monitor, base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorAdd,
@@ -300,7 +302,7 @@
/** Removes MSFT filter */
void BleScannerInterfaceImpl::MsftAdvMonitorRemove(
uint8_t monitor_handle, MsftAdvMonitorRemoveCallback cb) {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
msft_callbacks_.Remove = cb;
bluetooth::shim::GetMsftExtensionManager()->MsftAdvMonitorRemove(
monitor_handle,
@@ -311,7 +313,7 @@
/** Enable / disable MSFT scan filter */
void BleScannerInterfaceImpl::MsftAdvMonitorEnable(
bool enable, MsftAdvMonitorEnableCallback cb) {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
msft_callbacks_.Enable = cb;
bluetooth::shim::GetMsftExtensionManager()->MsftAdvMonitorEnable(
enable, base::Bind(&BleScannerInterfaceImpl::OnMsftAdvMonitorEnable,
@@ -321,21 +323,21 @@
/** Callback of adding MSFT filter */
void BleScannerInterfaceImpl::OnMsftAdvMonitorAdd(
uint8_t monitor_handle, bluetooth::hci::ErrorCode status) {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
msft_callbacks_.Add.Run(monitor_handle, (uint8_t)status);
}
/** Callback of removing MSFT filter */
void BleScannerInterfaceImpl::OnMsftAdvMonitorRemove(
bluetooth::hci::ErrorCode status) {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
msft_callbacks_.Remove.Run((uint8_t)status);
}
/** Callback of enabling / disabling MSFT scan filter */
void BleScannerInterfaceImpl::OnMsftAdvMonitorEnable(
bool enable, bluetooth::hci::ErrorCode status) {
- LOG_INFO("in shim layer");
+ log::info("in shim layer");
if (status == bluetooth::hci::ErrorCode::SUCCESS) {
bluetooth::shim::GetScanning()->SetScanFilterPolicy(
@@ -352,7 +354,7 @@
int scan_interval,
int scan_window, int scan_phy,
Callback /* cb */) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
if (BTM_BLE_ISVALID_PARAM(scan_interval, BTM_BLE_SCAN_INT_MIN,
BTM_BLE_EXT_SCAN_INT_MAX) &&
BTM_BLE_ISVALID_PARAM(scan_window, BTM_BLE_SCAN_WIN_MIN,
@@ -372,7 +374,7 @@
void BleScannerInterfaceImpl::BatchscanConfigStorage(
int client_if, int batch_scan_full_max, int batch_scan_trunc_max,
int batch_scan_notify_threshold, Callback cb) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetScanning()->BatchScanConifgStorage(
batch_scan_full_max, batch_scan_trunc_max, batch_scan_notify_threshold,
client_if);
@@ -385,7 +387,7 @@
int scan_window,
int /* addr_type */,
int discard_rule, Callback cb) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
auto batch_scan_mode = static_cast<bluetooth::hci::BatchScanMode>(scan_mode);
auto batch_scan_discard_rule =
static_cast<bluetooth::hci::BatchScanDiscardRule>(discard_rule);
@@ -397,7 +399,7 @@
/* Disable batchscan */
void BleScannerInterfaceImpl::BatchscanDisable(Callback cb) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetScanning()->BatchScanDisable();
do_in_jni_thread(FROM_HERE,
base::BindOnce(cb, btm_status_value(BTM_SUCCESS)));
@@ -406,7 +408,7 @@
/* Read out batchscan reports */
void BleScannerInterfaceImpl::BatchscanReadReports(int client_if,
int scan_mode) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
auto batch_scan_mode = static_cast<bluetooth::hci::BatchScanMode>(scan_mode);
auto scanner_id = static_cast<bluetooth::hci::ScannerId>(client_if);
bluetooth::shim::GetScanning()->BatchScanReadReport(scanner_id,
@@ -426,7 +428,7 @@
void BleScannerInterfaceImpl::StartSync(uint8_t sid, RawAddress address,
uint16_t skip, uint16_t timeout,
int reg_id) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
tBLE_ADDR_TYPE address_type = BLE_ADDR_RANDOM;
tINQ_DB_ENT* p_i = btm_inq_db_find(address);
if (p_i) {
@@ -439,13 +441,13 @@
}
void BleScannerInterfaceImpl::StopSync(uint16_t handle) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetScanning()->StopSync(handle);
}
void BleScannerInterfaceImpl::CancelCreateSync(uint8_t sid,
RawAddress address) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetScanning()->CancelCreateSync(sid, ToGdAddress(address));
}
@@ -453,11 +455,11 @@
uint16_t service_data,
uint16_t sync_handle,
int pa_source) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
tACL_CONN* p_acl = btm_acl_for_bda(address, BT_TRANSPORT_LE);
if (p_acl == NULL || !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(
p_acl->peer_le_features)) {
- LOG_ERROR("[PAST] Remote doesn't support PAST");
+ log::error("[PAST] Remote doesn't support PAST");
scanning_callbacks_->OnPeriodicSyncTransferred(
pa_source, BTM_MODE_UNSUPPORTED, address);
return;
@@ -472,11 +474,11 @@
uint16_t service_data,
uint8_t adv_handle,
int pa_source) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
tACL_CONN* p_acl = btm_acl_for_bda(address, BT_TRANSPORT_LE);
if (p_acl == NULL || !HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER_RECIPIENT(
p_acl->peer_le_features)) {
- LOG_ERROR("[PAST] Remote doesn't support PAST");
+ log::error("[PAST] Remote doesn't support PAST");
scanning_callbacks_->OnPeriodicSyncTransferred(
pa_source, BTM_MODE_UNSUPPORTED, address);
return;
@@ -490,13 +492,13 @@
void BleScannerInterfaceImpl::SyncTxParameters(RawAddress addr, uint8_t mode,
uint16_t skip, uint16_t timeout,
int reg_id) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
bluetooth::shim::GetScanning()->SyncTxParameters(ToGdAddress(addr), mode,
skip, timeout, reg_id);
}
void BleScannerInterfaceImpl::RegisterCallbacks(ScanningCallbacks* callbacks) {
- LOG(INFO) << __func__ << " in shim layer";
+ log::info("in shim layer");
scanning_callbacks_ = callbacks;
}
@@ -703,7 +705,7 @@
bluetooth::hci::Uuid::From128BitBE(apcf_command.uuid.To128BitBE());
} break;
default:
- LOG_WARN("illegal UUID length %d", (uint16_t)uuid_len);
+ log::warn("illegal UUID length {}", (uint16_t)uuid_len);
return false;
}
}
@@ -725,7 +727,7 @@
apcf_command.uuid_mask.To128BitBE());
} break;
default:
- LOG_WARN("illegal UUID length %d", (uint16_t)uuid_len);
+ log::warn("illegal UUID length {}", (uint16_t)uuid_len);
return false;
}
}
@@ -757,7 +759,7 @@
RawAddress bd_addr, tBLE_ADDR_TYPE addr_type,
std::vector<uint8_t> advertising_data) {
if (!bluetooth::shim::is_gd_stack_started_up()) {
- LOG_WARN("Gd stack is stopped, return");
+ log::warn("Gd stack is stopped, return");
return;
}
@@ -796,8 +798,8 @@
if (remote_name_len > BD_NAME_LEN + 1 ||
(remote_name_len == BD_NAME_LEN + 1 &&
p_eir_remote_name[BD_NAME_LEN] != '\0')) {
- LOG_INFO("%s dropping invalid packet - device name too long: %d",
- __func__, remote_name_len);
+ log::info("dropping invalid packet - device name too long: {}",
+ remote_name_len);
return;
}
@@ -916,7 +918,7 @@
void bluetooth::shim::set_target_announcements_filter(bool enable) {
uint8_t filter_index = 0x03;
- LOG_DEBUG(" enable %d", enable);
+ log::debug("enable {}", enable);
bluetooth::hci::AdvertisingFilterParameter advertising_filter_parameter = {};
bluetooth::shim::GetScanning()->ScanFilterParameterSetup(
diff --git a/system/main/shim/link_connection_interface.h b/system/main/shim/link_connection_interface.h
index 7788ae4..86d5975 100644
--- a/system/main/shim/link_connection_interface.h
+++ b/system/main/shim/link_connection_interface.h
@@ -44,6 +44,10 @@
std::string comment) = 0;
virtual void DisconnectLe(uint16_t handle, tHCI_REASON reason,
std::string comment) = 0;
+ virtual void UpdateConnectionParameters(
+ 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) = 0;
};
} // namespace shim
diff --git a/system/main/shim/shim.cc b/system/main/shim/shim.cc
index 51de0af..280d50c 100644
--- a/system/main/shim/shim.cc
+++ b/system/main/shim/shim.cc
@@ -18,6 +18,8 @@
#include "main/shim/shim.h"
+#include <bluetooth/log.h>
+
#include "common/init_flags.h"
#include "main/shim/entry.h"
#include "main/shim/hci_layer.h"
@@ -33,8 +35,8 @@
BT_HDR* p_msg) {
if (do_in_main_thread(from_here, base::Bind(&btu_hci_msg_process, p_msg)) !=
BT_STATUS_SUCCESS) {
- LOG_ERROR(": do_in_main_thread failed from %s",
- from_here.ToString().c_str());
+ bluetooth::log::error(": do_in_main_thread failed from {}",
+ from_here.ToString());
}
}
diff --git a/system/main/shim/stack.cc b/system/main/shim/stack.cc
index 615119e..db59623 100644
--- a/system/main/shim/stack.cc
+++ b/system/main/shim/stack.cc
@@ -18,6 +18,7 @@
#include "main/shim/stack.h"
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
@@ -26,11 +27,11 @@
#include "common/init_flags.h"
#include "common/strings.h"
-#include "device/include/controller.h"
#include "hal/hci_hal.h"
#include "hci/acl_manager.h"
#include "hci/acl_manager/acl_scheduler.h"
#include "hci/controller.h"
+#include "hci/controller_interface.h"
#include "hci/distance_measurement_manager.h"
#include "hci/hci_layer.h"
#include "hci/le_advertising_manager.h"
@@ -40,6 +41,7 @@
#include "hci/vendor_specific_event_manager.h"
#include "main/shim/acl_legacy_interface.h"
#include "main/shim/distance_measurement_manager.h"
+#include "main/shim/entry.h"
#include "main/shim/hci_layer.h"
#include "main/shim/le_advertising_manager.h"
#include "main/shim/le_scanning_manager.h"
@@ -63,7 +65,7 @@
void Stack::StartEverything() {
std::lock_guard<std::recursive_mutex> lock(mutex_);
ASSERT_LOG(!is_running_, "%s Gd stack already running", __func__);
- LOG_INFO("%s Starting Gd stack", __func__);
+ log::info("Starting Gd stack");
ModuleList modules;
modules.add<metrics::CounterMetrics>();
@@ -88,12 +90,11 @@
ASSERT(stack_manager_.GetInstance<storage::StorageModule>() != nullptr);
ASSERT(stack_manager_.GetInstance<shim::Dumpsys>() != nullptr);
if (stack_manager_.IsStarted<hci::Controller>()) {
- acl_ = new legacy::Acl(
- stack_handler_, legacy::GetAclInterface(),
- controller_get_interface()->get_ble_acceptlist_size(),
- controller_get_interface()->get_ble_resolving_list_max_size());
+ acl_ = new legacy::Acl(stack_handler_, legacy::GetAclInterface(),
+ GetController()->GetLeFilterAcceptListSize(),
+ GetController()->GetLeResolvingListSize());
} else {
- LOG_ERROR("Unable to create shim ACL layer as Controller has not started");
+ log::error("Unable to create shim ACL layer as Controller has not started");
}
bluetooth::shim::hci_on_reset_complete();
@@ -107,7 +108,7 @@
std::lock_guard<std::recursive_mutex> lock(mutex_);
ASSERT_LOG(!is_running_, "%s Gd stack already running", __func__);
stack_thread_ = const_cast<os::Thread*>(thread);
- LOG_INFO("Starting Gd stack");
+ log::info("Starting Gd stack");
stack_manager_.StartUp(const_cast<ModuleList*>(modules), stack_thread_);
stack_handler_ = new os::Handler(stack_thread_);
@@ -118,7 +119,7 @@
void Stack::Start(ModuleList* modules) {
ASSERT_LOG(!is_running_, "%s Gd stack already running", __func__);
- LOG_INFO("%s Starting Gd stack", __func__);
+ log::info("Starting Gd stack");
stack_thread_ =
new os::Thread("gd_stack_thread", os::Thread::Priority::REAL_TIME);
@@ -126,7 +127,7 @@
stack_handler_ = new os::Handler(stack_thread_);
- LOG_INFO("%s Successfully toggled Gd stack", __func__);
+ log::info("Successfully toggled Gd stack");
}
void Stack::Stop() {
@@ -157,7 +158,7 @@
delete stack_thread_;
stack_thread_ = nullptr;
- LOG_INFO("%s Successfully shut down Gd stack", __func__);
+ log::info("Successfully shut down Gd stack");
}
bool Stack::IsRunning() {
diff --git a/system/main/shim/utils.cc b/system/main/shim/utils.cc
index c660ecd..bf42398 100644
--- a/system/main/shim/utils.cc
+++ b/system/main/shim/utils.cc
@@ -18,7 +18,7 @@
#include "utils.h"
-#include "os/log.h"
+#include <bluetooth/log.h>
namespace bluetooth {
namespace shim {
@@ -30,7 +30,7 @@
uint8_t len = raw_data[offset];
if (offset + len + 1 > raw_data.size()) {
- LOG_WARN("GAP data out of bound");
+ log::warn("GAP data out of bound");
break;
}
diff --git a/system/main/stack_config.cc b/system/main/stack_config.cc
index 4f0e86c..b8a1d10 100644
--- a/system/main/stack_config.cc
+++ b/system/main/stack_config.cc
@@ -21,11 +21,14 @@
#include "internal_include/stack_config.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "include/check.h"
#include "os/log.h"
#include "osi/include/future.h"
+using namespace bluetooth;
+
namespace {
const char* PTS_AVRCP_TEST = "PTS_AvrcpTest";
const char* PTS_SECURE_ONLY_MODE = "PTS_SecurePairOnly";
@@ -69,11 +72,11 @@
#endif // defined(__ANDROID__)
CHECK(path != NULL);
- LOG_INFO("%s attempt to load stack conf from %s", __func__, path);
+ log::info("attempt to load stack conf from {}", path);
config = config_new(path);
if (!config) {
- LOG_INFO("%s file >%s< not found", __func__, path);
+ log::info("file >{}< not found", path);
config = config_new_empty();
}
@@ -191,7 +194,7 @@
static const std::string* get_pts_broadcast_audio_config_options(void) {
if (!config) {
- LOG_INFO("Config isn't ready, use default option");
+ log::info("Config isn't ready, use default option");
return NULL;
}
return config_get_string(*config, CONFIG_DEFAULT_SECTION,
diff --git a/system/main/test/main_shim_test.cc b/system/main/test/main_shim_test.cc
index b0af5dd..d79f59a 100644
--- a/system/main/test/main_shim_test.cc
+++ b/system/main/test/main_shim_test.cc
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -28,7 +29,6 @@
#include <vector>
#include "btif/include/btif_hh.h"
-#include "device/include/controller.h"
#include "hal/hci_hal.h"
#include "hci/acl_manager.h"
#include "hci/acl_manager/classic_acl_connection.h"
@@ -49,7 +49,6 @@
#include "main/shim/dumpsys.h"
#include "main/shim/helpers.h"
#include "main/shim/le_advertising_manager.h"
-#include "main/shim/utils.h"
#include "main/shim/le_scanning_manager.h"
#include "main/shim/utils.h"
#include "os/handler.h"
@@ -120,14 +119,6 @@
bluetooth::common::TimestamperInMilliseconds timestamper_in_milliseconds;
-uint8_t mock_get_ble_acceptlist_size() { return 123; }
-
-struct controller_t mock_controller {
- .get_ble_acceptlist_size = mock_get_ble_acceptlist_size,
-};
-
-const controller_t* controller_get_interface() { return &mock_controller; }
-
void mock_on_send_data_upwards(BT_HDR*) {}
void mock_on_packets_completed(uint16_t handle, uint16_t num_packets) {}
@@ -360,7 +351,7 @@
protected:
void SetUp() override {
main_thread_start_up();
- post_on_bt_main([]() { LOG_INFO("Main thread started"); });
+ post_on_bt_main([]() { log::info("Main thread started"); });
thread_ = new os::Thread("acl_thread", os::Thread::Priority::NORMAL);
handler_ = new os::Handler(thread_);
@@ -392,7 +383,7 @@
delete handler_;
delete thread_;
- post_on_bt_main([]() { LOG_INFO("Main thread stopped"); });
+ post_on_bt_main([]() { log::info("Main thread stopped"); });
main_thread_shut_down();
reset_mock_function_count_map();
}
diff --git a/system/osi/src/alarm.cc b/system/osi/src/alarm.cc
index 408f4f3..1c7336b 100644
--- a/system/osi/src/alarm.cc
+++ b/system/osi/src/alarm.cc
@@ -22,6 +22,7 @@
#include <base/cancelable_callback.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <hardware/bluetooth.h>
#include <malloc.h>
@@ -45,6 +46,7 @@
using base::Bind;
using base::CancelableClosure;
+using namespace bluetooth;
// Callback and timer threads should run at RT priority in order to ensure they
// meet audio deadlines. Use this priority for all audio/timer related thread.
@@ -312,7 +314,7 @@
alarms = list_new(NULL);
if (!alarms) {
- LOG_ERROR("%s unable to allocate alarm list.", __func__);
+ log::error("unable to allocate alarm list.");
goto error;
}
@@ -328,20 +330,20 @@
alarm_expired = semaphore_new(0);
if (!alarm_expired) {
- LOG_ERROR("%s unable to create alarm expired semaphore", __func__);
+ log::error("unable to create alarm expired semaphore");
goto error;
}
default_callback_thread =
thread_new_sized("alarm_default_callbacks", SIZE_MAX);
if (default_callback_thread == NULL) {
- LOG_ERROR("%s unable to create default alarm callbacks thread.", __func__);
+ log::error("unable to create default alarm callbacks thread.");
goto error;
}
thread_set_rt_priority(default_callback_thread, THREAD_RT_PRIORITY);
default_callback_queue = fixed_queue_new(SIZE_MAX);
if (default_callback_queue == NULL) {
- LOG_ERROR("%s unable to create default alarm callbacks queue.", __func__);
+ log::error("unable to create default alarm callbacks queue.");
goto error;
}
alarm_register_processing_queue(default_callback_queue,
@@ -350,7 +352,7 @@
dispatcher_thread_active = true;
dispatcher_thread = thread_new("alarm_dispatcher");
if (!dispatcher_thread) {
- LOG_ERROR("%s unable to create alarm callback thread.", __func__);
+ log::error("unable to create alarm callback thread.");
goto error;
}
thread_set_rt_priority(dispatcher_thread, THREAD_RT_PRIORITY);
@@ -386,7 +388,7 @@
struct timespec ts;
if (clock_gettime(CLOCK_ID, &ts) == -1) {
- LOG_ERROR("%s unable to get current time: %s", __func__, strerror(errno));
+ log::error("unable to get current time: {}", strerror(errno));
return 0;
}
@@ -468,7 +470,7 @@
if (next_expiration < TIMER_INTERVAL_FOR_WAKELOCK_IN_MS) {
if (!timer_set) {
if (!wakelock_acquire()) {
- LOG_ERROR("%s unable to acquire wake lock", __func__);
+ log::error("unable to acquire wake lock");
}
}
@@ -501,7 +503,7 @@
wakeup_time.it_value.tv_sec = (next->deadline_ms / 1000);
wakeup_time.it_value.tv_nsec = (next->deadline_ms % 1000) * 1000000LL;
if (timer_settime(wakeup_timer, TIMER_ABSTIME, &wakeup_time, NULL) == -1)
- LOG_ERROR("%s unable to set wakeup timer: %s", __func__, strerror(errno));
+ log::error("unable to set wakeup timer: {}", strerror(errno));
}
done:
@@ -512,7 +514,7 @@
}
if (timer_settime(timer, TIMER_ABSTIME, &timer_time, NULL) == -1)
- LOG_ERROR("%s unable to set timer: %s", __func__, strerror(errno));
+ log::error("unable to set timer: {}", strerror(errno));
// If next expiration was in the past (e.g. short timer that got context
// switched) then the timer might have diarmed itself. Detect this case and
@@ -529,10 +531,8 @@
timer_gettime(timer, &time_to_expire);
if (time_to_expire.it_value.tv_sec == 0 &&
time_to_expire.it_value.tv_nsec == 0) {
- LOG_INFO(
-
- "%s alarm expiration too close for posix timers, switching to guns",
- __func__);
+ log::info(
+ "alarm expiration too close for posix timers, switching to guns");
semaphore_post(alarm_expired);
}
}
@@ -559,8 +559,7 @@
// alarms and active ones.
//
if (!alarm->callback) {
- LOG(FATAL) << __func__
- << ": timer callback is NULL! Name=" << alarm->stats.name;
+ log::fatal("timer callback is NULL! Name={}", alarm->stats.name);
}
alarm_callback_t callback = alarm->callback;
void* data = alarm->data;
@@ -642,8 +641,7 @@
// Enqueue the alarm for processing
if (alarm->for_msg_loop) {
if (!get_main_thread()) {
- LOG_ERROR("%s: message loop already NULL. Alarm: %s", __func__,
- alarm->stats.name);
+ log::error("message loop already NULL. Alarm: {}", alarm->stats.name);
continue;
}
@@ -654,7 +652,7 @@
}
}
- LOG_INFO("%s Callback thread exited", __func__);
+ log::info("Callback thread exited");
}
static bool timer_create_internal(const clockid_t clock_id, timer_t* timer) {
@@ -674,17 +672,17 @@
sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
sigevent.sigev_notify_attributes = &thread_attr;
if (timer_create(clock_id, &sigevent, timer) == -1) {
- LOG_ERROR("%s unable to create timer with clock %d: %s", __func__, clock_id,
- strerror(errno));
+ log::error("unable to create timer with clock {}: {}", clock_id,
+ strerror(errno));
if (clock_id == CLOCK_BOOTTIME_ALARM) {
- LOG_ERROR(
+ log::error(
"The kernel might not have support for "
"timer_create(CLOCK_BOOTTIME_ALARM): "
"https://lwn.net/Articles/429925/");
- LOG_ERROR(
+ log::error(
"See following patches: "
- "https://git.kernel.org/cgit/linux/kernel/git/torvalds/"
- "linux.git/log/?qt=grep&q=CLOCK_BOOTTIME_ALARM");
+ "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/log/"
+ "?qt=grep&q=CLOCK_BOOTTIME_ALARM");
}
return false;
}
diff --git a/system/osi/src/config.cc b/system/osi/src/config.cc
index ec951626..181ffe6 100644
--- a/system/osi/src/config.cc
+++ b/system/osi/src/config.cc
@@ -20,10 +20,10 @@
#include <base/files/file_util.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <ctype.h>
#include <fcntl.h>
#include <libgen.h>
-#include <log/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -36,6 +36,8 @@
#include "check.h"
+using namespace bluetooth;
+
void section_t::Set(std::string key, std::string value) {
for (entry_t& entry : entries) {
if (entry.key == key) {
@@ -103,8 +105,7 @@
FILE* fp = fopen(filename, "rt");
if (!fp) {
- LOG(ERROR) << __func__ << ": unable to open file '" << filename
- << "': " << strerror(errno);
+ log::error("unable to open file '{}': {}", filename, strerror(errno));
return nullptr;
}
@@ -119,12 +120,12 @@
std::string checksum_read(const char* filename) {
base::FilePath path(filename);
if (!base::PathExists(path)) {
- LOG(ERROR) << __func__ << ": unable to locate file '" << filename << "'";
+ log::error("unable to locate file '{}'", filename);
return "";
}
std::string encrypted_hash;
if (!base::ReadFileToString(path, &encrypted_hash)) {
- LOG(ERROR) << __func__ << ": unable to read file '" << filename << "'";
+ log::error("unable to read file '{}'", filename);
}
return encrypted_hash;
}
@@ -283,22 +284,21 @@
// Extract directory from file path (e.g. /data/misc/bluedroid).
const std::string directoryname = base::FilePath(filename).DirName().value();
if (directoryname.empty()) {
- LOG(ERROR) << __func__ << ": error extracting directory from '" << filename
- << "': " << strerror(errno);
+ log::error("error extracting directory from '{}': {}", filename,
+ strerror(errno));
goto error;
}
dir_fd = open(directoryname.c_str(), O_RDONLY);
if (dir_fd < 0) {
- LOG(ERROR) << __func__ << ": unable to open dir '" << directoryname
- << "': " << strerror(errno);
+ log::error("unable to open dir '{}': {}", directoryname, strerror(errno));
goto error;
}
fp = fopen(temp_filename.c_str(), "wt");
if (!fp) {
- LOG(ERROR) << __func__ << ": unable to write to file '" << temp_filename
- << "': " << strerror(errno);
+ log::error("unable to write to file '{}': {}", temp_filename,
+ strerror(errno));
goto error;
}
@@ -312,28 +312,26 @@
}
if (fprintf(fp, "%s", serialized.str().c_str()) < 0) {
- LOG(ERROR) << __func__ << ": unable to write to file '" << temp_filename
- << "': " << strerror(errno);
+ log::error("unable to write to file '{}': {}", temp_filename,
+ strerror(errno));
goto error;
}
// Flush the stream buffer to the temp file.
if (fflush(fp) < 0) {
- LOG(ERROR) << __func__ << ": unable to write flush buffer to file '"
- << temp_filename << "': " << strerror(errno);
+ log::error("unable to write flush buffer to file '{}': {}", temp_filename,
+ strerror(errno));
goto error;
}
// Sync written temp file out to disk. fsync() is blocking until data makes it
// to disk.
if (fsync(fileno(fp)) < 0) {
- LOG(WARNING) << __func__ << ": unable to fsync file '" << temp_filename
- << "': " << strerror(errno);
+ log::warn("unable to fsync file '{}': {}", temp_filename, strerror(errno));
}
if (fclose(fp) == EOF) {
- LOG(ERROR) << __func__ << ": unable to close file '" << temp_filename
- << "': " << strerror(errno);
+ log::error("unable to close file '{}': {}", temp_filename, strerror(errno));
goto error;
}
fp = nullptr;
@@ -341,27 +339,24 @@
// Change the file's permissions to Read/Write by User and Group
if (chmod(temp_filename.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) ==
-1) {
- LOG(ERROR) << __func__ << ": unable to change file permissions '"
- << filename << "': " << strerror(errno);
+ log::error("unable to change file permissions '{}': {}", filename,
+ strerror(errno));
goto error;
}
// Rename written temp file to the actual config file.
if (rename(temp_filename.c_str(), filename.c_str()) == -1) {
- LOG(ERROR) << __func__ << ": unable to commit file '" << filename
- << "': " << strerror(errno);
+ log::error("unable to commit file '{}': {}", filename, strerror(errno));
goto error;
}
// This should ensure the directory is updated as well.
if (fsync(dir_fd) < 0) {
- LOG(WARNING) << __func__ << ": unable to fsync dir '" << directoryname
- << "': " << strerror(errno);
+ log::warn("unable to fsync dir '{}': {}", directoryname, strerror(errno));
}
if (close(dir_fd) < 0) {
- LOG(ERROR) << __func__ << ": unable to close dir '" << directoryname
- << "': " << strerror(errno);
+ log::error("unable to close dir '{}': {}", directoryname, strerror(errno));
goto error;
}
@@ -400,41 +395,38 @@
// Extract directory from file path (e.g. /data/misc/bluedroid).
const std::string directoryname = base::FilePath(filename).DirName().value();
if (directoryname.empty()) {
- LOG(ERROR) << __func__ << ": error extracting directory from '" << filename
- << "': " << strerror(errno);
+ log::error("error extracting directory from '{}': {}", filename,
+ strerror(errno));
goto error2;
}
dir_fd = open(directoryname.c_str(), O_RDONLY);
if (dir_fd < 0) {
- LOG(ERROR) << __func__ << ": unable to open dir '" << directoryname
- << "': " << strerror(errno);
+ log::error("unable to open dir '{}': {}", directoryname, strerror(errno));
goto error2;
}
if (base::WriteFile(path, checksum.data(), checksum.size()) !=
(int)checksum.size()) {
- LOG(ERROR) << __func__ << ": unable to write file '" << filename.c_str();
+ log::error("unable to write file '{}", filename);
goto error2;
}
fp = fopen(temp_filename.c_str(), "rb");
if (!fp) {
- LOG(ERROR) << __func__ << ": unable to write to file '" << temp_filename
- << "': " << strerror(errno);
+ log::error("unable to write to file '{}': {}", temp_filename,
+ strerror(errno));
goto error2;
}
// Sync written temp file out to disk. fsync() is blocking until data makes it
// to disk.
if (fsync(fileno(fp)) < 0) {
- LOG(WARNING) << __func__ << ": unable to fsync file '" << temp_filename
- << "': " << strerror(errno);
+ log::warn("unable to fsync file '{}': {}", temp_filename, strerror(errno));
}
if (fclose(fp) == EOF) {
- LOG(ERROR) << __func__ << ": unable to close file '" << temp_filename
- << "': " << strerror(errno);
+ log::error("unable to close file '{}': {}", temp_filename, strerror(errno));
goto error2;
}
fp = nullptr;
@@ -442,27 +434,24 @@
// Change the file's permissions to Read/Write by User and Group
if (chmod(temp_filename.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) ==
-1) {
- LOG(ERROR) << __func__ << ": unable to change file permissions '"
- << filename << "': " << strerror(errno);
+ log::error("unable to change file permissions '{}': {}", filename,
+ strerror(errno));
goto error2;
}
// Rename written temp file to the actual config file.
if (rename(temp_filename.c_str(), filename.c_str()) == -1) {
- LOG(ERROR) << __func__ << ": unable to commit file '" << filename
- << "': " << strerror(errno);
+ log::error("unable to commit file '{}': {}", filename, strerror(errno));
goto error2;
}
// This should ensure the directory is updated as well.
if (fsync(dir_fd) < 0) {
- LOG(WARNING) << __func__ << ": unable to fsync dir '" << directoryname
- << "': " << strerror(errno);
+ log::warn("unable to fsync dir '{}': {}", directoryname, strerror(errno));
}
if (close(dir_fd) < 0) {
- LOG(ERROR) << __func__ << ": unable to close dir '" << directoryname
- << "': " << strerror(errno);
+ log::error("unable to close dir '{}': {}", directoryname, strerror(errno));
goto error2;
}
@@ -508,8 +497,7 @@
if (*line_ptr == '[') {
size_t len = strlen(line_ptr);
if (line_ptr[len - 1] != ']') {
- VLOG(1) << __func__ << ": unterminated section name on line "
- << line_num;
+ log::verbose("unterminated section name on line {}", line_num);
return false;
}
strncpy(section, line_ptr + 1, len - 2); // NOLINT (len < 4096)
@@ -517,8 +505,7 @@
} else {
char* split = strchr(line_ptr, '=');
if (!split) {
- VLOG(1) << __func__ << ": no key/value separator found on line "
- << line_num;
+ log::verbose("no key/value separator found on line {}", line_num);
return false;
}
diff --git a/system/osi/src/future.cc b/system/osi/src/future.cc
index ece49c7..775d20f 100644
--- a/system/osi/src/future.cc
+++ b/system/osi/src/future.cc
@@ -21,6 +21,7 @@
#include "osi/include/future.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "check.h"
#include "os/log.h"
@@ -41,7 +42,7 @@
ret->semaphore = semaphore_new(0);
if (!ret->semaphore) {
- LOG_ERROR("%s unable to allocate memory for the semaphore.", __func__);
+ bluetooth::log::error("unable to allocate memory for the semaphore.");
goto error;
}
diff --git a/system/osi/src/internal/semaphore.cc b/system/osi/src/internal/semaphore.cc
index b5c6041..6e2e53d 100644
--- a/system/osi/src/internal/semaphore.cc
+++ b/system/osi/src/internal/semaphore.cc
@@ -21,6 +21,7 @@
#include "osi/semaphore.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <malloc.h>
#include <string.h>
@@ -36,6 +37,8 @@
#define EFD_SEMAPHORE (1 << 0)
#endif
+using namespace bluetooth;
+
struct semaphore_t {
int fd;
};
@@ -44,7 +47,7 @@
semaphore_t* ret = static_cast<semaphore_t*>(osi_malloc(sizeof(semaphore_t)));
ret->fd = eventfd(value, EFD_SEMAPHORE);
if (ret->fd == INVALID_FD) {
- LOG_ERROR("%s unable to allocate semaphore: %s", __func__, strerror(errno));
+ log::error("unable to allocate semaphore: {}", strerror(errno));
osi_free(ret);
ret = NULL;
}
@@ -64,7 +67,7 @@
eventfd_t value;
if (eventfd_read(semaphore->fd, &value) == -1)
- LOG_ERROR("%s unable to wait on semaphore: %s", __func__, strerror(errno));
+ log::error("unable to wait on semaphore: {}", strerror(errno));
}
bool semaphore_try_wait(semaphore_t* semaphore) {
@@ -73,13 +76,12 @@
int flags = fcntl(semaphore->fd, F_GETFL);
if (flags == -1) {
- LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__,
- strerror(errno));
+ log::error("unable to get flags for semaphore fd: {}", strerror(errno));
return false;
}
if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) {
- LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__,
- strerror(errno));
+ log::error("unable to set O_NONBLOCK for semaphore fd: {}",
+ strerror(errno));
return false;
}
@@ -88,8 +90,7 @@
if (eventfd_read(semaphore->fd, &value) == -1) rc = false;
if (fcntl(semaphore->fd, F_SETFL, flags) == -1)
- LOG_ERROR("%s unable to restore flags for semaphore fd: %s", __func__,
- strerror(errno));
+ log::error("unable to restore flags for semaphore fd: {}", strerror(errno));
return rc;
}
@@ -98,7 +99,7 @@
CHECK(semaphore->fd != INVALID_FD);
if (eventfd_write(semaphore->fd, 1ULL) == -1)
- LOG_ERROR("%s unable to post to semaphore: %s", __func__, strerror(errno));
+ log::error("unable to post to semaphore: {}", strerror(errno));
}
int semaphore_get_fd(const semaphore_t* semaphore) {
diff --git a/system/osi/src/osi.cc b/system/osi/src/osi.cc
index 33a3886..ed2f6d2 100644
--- a/system/osi/src/osi.cc
+++ b/system/osi/src/osi.cc
@@ -21,6 +21,7 @@
#include "osi/include/osi.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
@@ -38,8 +39,8 @@
int rand_fd = open(RANDOM_PATH, O_RDONLY);
if (rand_fd == INVALID_FD) {
- LOG_ERROR("%s can't open rand fd %s: %s ", __func__, RANDOM_PATH,
- strerror(errno));
+ bluetooth::log::error("can't open rand fd {}: {}", RANDOM_PATH,
+ strerror(errno));
CHECK(rand_fd != INVALID_FD);
}
diff --git a/system/osi/src/reactor.cc b/system/osi/src/reactor.cc
index d6f5784..0c65677 100644
--- a/system/osi/src/reactor.cc
+++ b/system/osi/src/reactor.cc
@@ -21,6 +21,7 @@
#include "osi/include/reactor.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
@@ -39,6 +40,8 @@
#define EFD_SEMAPHORE (1 << 0)
#endif
+using namespace bluetooth;
+
struct reactor_t {
int epoll_fd;
int event_fd;
@@ -74,21 +77,20 @@
ret->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (ret->epoll_fd == INVALID_FD) {
- LOG_ERROR("%s unable to create epoll instance: %s", __func__,
- strerror(errno));
+ log::error("unable to create epoll instance: {}", strerror(errno));
goto error;
}
ret->event_fd = eventfd(0, 0);
if (ret->event_fd == INVALID_FD) {
- LOG_ERROR("%s unable to create eventfd: %s", __func__, strerror(errno));
+ log::error("unable to create eventfd: {}", strerror(errno));
goto error;
}
ret->list_mutex = new std::mutex;
ret->invalidation_list = list_new(NULL);
if (!ret->invalidation_list) {
- LOG_ERROR("%s unable to allocate object invalidation list.", __func__);
+ log::error("unable to allocate object invalidation list.");
goto error;
}
@@ -97,8 +99,8 @@
event.events = EPOLLIN;
event.data.ptr = NULL;
if (epoll_ctl(ret->epoll_fd, EPOLL_CTL_ADD, ret->event_fd, &event) == -1) {
- LOG_ERROR("%s unable to register eventfd with epoll set: %s", __func__,
- strerror(errno));
+ log::error("unable to register eventfd with epoll set: {}",
+ strerror(errno));
goto error;
}
@@ -158,8 +160,8 @@
event.data.ptr = object;
if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_ADD, fd, &event) == -1) {
- LOG_ERROR("%s unable to register fd %d to epoll set: %s", __func__, fd,
- strerror(errno));
+ log::error("unable to register fd {} to epoll set: {}", fd,
+ strerror(errno));
delete object->mutex;
osi_free(object);
return NULL;
@@ -181,8 +183,8 @@
if (epoll_ctl(object->reactor->epoll_fd, EPOLL_CTL_MOD, object->fd, &event) ==
-1) {
- LOG_ERROR("%s unable to modify interest set for fd %d: %s", __func__,
- object->fd, strerror(errno));
+ log::error("unable to modify interest set for fd {}: {}", object->fd,
+ strerror(errno));
return false;
}
@@ -199,8 +201,8 @@
reactor_t* reactor = obj->reactor;
if (epoll_ctl(reactor->epoll_fd, EPOLL_CTL_DEL, obj->fd, NULL) == -1)
- LOG_ERROR("%s unable to unregister fd %d from epoll set: %s", __func__,
- obj->fd, strerror(errno));
+ log::error("unable to unregister fd {} from epoll set: {}", obj->fd,
+ strerror(errno));
if (reactor->is_running &&
pthread_equal(pthread_self(), reactor->run_thread)) {
@@ -246,7 +248,7 @@
int ret;
OSI_NO_INTR(ret = epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1));
if (ret == -1) {
- LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno));
+ log::error("error in epoll_wait: {}", strerror(errno));
reactor->is_running = false;
return REACTOR_STATUS_ERROR;
}
diff --git a/system/osi/src/socket.cc b/system/osi/src/socket.cc
index 43b90ee..0b29871 100644
--- a/system/osi/src/socket.cc
+++ b/system/osi/src/socket.cc
@@ -22,6 +22,7 @@
#include <asm/ioctls.h>
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
@@ -34,6 +35,8 @@
#include "osi/include/osi.h"
#include "osi/include/reactor.h"
+using namespace bluetooth;
+
// The IPv4 loopback address: 127.0.0.1
static const in_addr_t LOCALHOST_ = 0x7f000001;
@@ -54,13 +57,13 @@
ret->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ret->fd == INVALID_FD) {
- LOG_ERROR("%s unable to create socket: %s", __func__, strerror(errno));
+ log::error("unable to create socket: {}", strerror(errno));
goto error;
}
if (setsockopt(ret->fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) ==
-1) {
- LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
+ log::error("unable to set SO_REUSEADDR: {}", strerror(errno));
goto error;
}
@@ -97,14 +100,12 @@
addr.sin_addr.s_addr = htonl(LOCALHOST_);
addr.sin_port = htons(port);
if (bind(socket->fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
- LOG_ERROR("%s unable to bind socket to port %u: %s", __func__, port,
- strerror(errno));
+ log::error("unable to bind socket to port {}: {}", port, strerror(errno));
return false;
}
if (listen(socket->fd, 10) == -1) {
- LOG_ERROR("%s unable to listen on port %u: %s", __func__, port,
- strerror(errno));
+ log::error("unable to listen on port {}: {}", port, strerror(errno));
return false;
}
@@ -117,7 +118,7 @@
int fd;
OSI_NO_INTR(fd = accept(socket->fd, NULL, NULL));
if (fd == INVALID_FD) {
- LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno));
+ log::error("unable to accept socket: {}", strerror(errno));
return NULL;
}
diff --git a/system/osi/src/stack_power_telemetry.cc b/system/osi/src/stack_power_telemetry.cc
index 65aefeb..89228e8 100644
--- a/system/osi/src/stack_power_telemetry.cc
+++ b/system/osi/src/stack_power_telemetry.cc
@@ -19,6 +19,7 @@
#include "osi/include/stack_power_telemetry.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <sys/stat.h>
#include <time.h>
@@ -35,6 +36,8 @@
#include "stack/include/btm_status.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
time_t get_current_time() { return time(0); }
namespace {
@@ -287,9 +290,9 @@
LogDataContainer& ldc = GetCurrentLogDataContainer();
- LOG_INFO(
- "bt_power: scan: %d, inqScan: %d, aclTx: %d, aclRx: %d, hciCmd: %d, "
- "hciEvt: %d, bleScan: %d",
+ log::info(
+ "bt_power: scan: {}, inqScan: {}, aclTx: {}, aclRx: {}, hciCmd: {}, "
+ "hciEvt: {}, bleScan: {}",
ldc.scan_details.count, ldc.inq_scan_details.count,
ldc.acl_pkt_ds.tx.pkt_count, ldc.acl_pkt_ds.rx.pkt_count,
ldc.hci_cmd_evt_ds.tx.pkt_count, ldc.hci_cmd_evt_ds.rx.pkt_count,
@@ -352,7 +355,7 @@
LogDataContainer& ldc = pimpl_->GetCurrentLogDataContainer();
if (ldc.adv_list.size() == 0) {
- LOG_WARN("Empty advList. Skip LogBleAdvDetails.");
+ log::warn("Empty advList. Skip LogBleAdvDetails.");
return;
}
ldc.adv_list.back().active.end = current_time;
diff --git a/system/osi/src/thread.cc b/system/osi/src/thread.cc
index 093ba76..2a4f843 100644
--- a/system/osi/src/thread.cc
+++ b/system/osi/src/thread.cc
@@ -21,6 +21,7 @@
#include "osi/include/thread.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <malloc.h>
#include <pthread.h>
#include <string.h>
@@ -40,6 +41,8 @@
#include "osi/include/reactor.h"
#include "osi/semaphore.h"
+using namespace bluetooth;
+
struct thread_t {
std::atomic_bool is_joined{false};
pthread_t pthread;
@@ -151,8 +154,8 @@
const int rc = setpriority(PRIO_PROCESS, thread->tid, priority);
if (rc < 0) {
- LOG_ERROR("%s unable to set thread priority %d for tid %d, error %d",
- __func__, priority, thread->tid, rc);
+ log::error("unable to set thread priority {} for tid {}, error {}",
+ priority, thread->tid, rc);
return false;
}
@@ -167,8 +170,8 @@
const int rc = sched_setscheduler(thread->tid, SCHED_FIFO, &rt_params);
if (rc != 0) {
- LOG_ERROR("%s unable to set SCHED_FIFO priority %d for tid %d, error %s",
- __func__, priority, thread->tid, strerror(errno));
+ log::error("unable to set SCHED_FIFO priority {} for tid {}, error {}",
+ priority, thread->tid, strerror(errno));
return false;
}
@@ -199,15 +202,14 @@
CHECK(thread != NULL);
if (prctl(PR_SET_NAME, (unsigned long)thread->name) == -1) {
- LOG_ERROR("%s unable to set thread name: %s", __func__, strerror(errno));
+ log::error("unable to set thread name: {}", strerror(errno));
start->error = errno;
semaphore_post(start->start_sem);
return NULL;
}
thread->tid = gettid();
- LOG_INFO("%s: thread id %d, thread name %s started", __func__, thread->tid,
- thread->name);
+ log::info("thread id {}, thread name {} started", thread->tid, thread->name);
semaphore_post(start->start_sem);
@@ -234,10 +236,9 @@
}
if (count > fixed_queue_capacity(thread->work_queue))
- LOG_INFO("%s growing event queue on shutdown.", __func__);
+ log::info("growing event queue on shutdown.");
- LOG_WARN("%s: thread id %d, thread name %s exited", __func__, thread->tid,
- thread->name);
+ log::warn("thread id {}, thread name {} exited", thread->tid, thread->name);
return NULL;
}
diff --git a/system/osi/src/wakelock.cc b/system/osi/src/wakelock.cc
index 34e0885..e5cb868 100644
--- a/system/osi/src/wakelock.cc
+++ b/system/osi/src/wakelock.cc
@@ -20,6 +20,7 @@
#include "osi/include/wakelock.h"
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <hardware/bluetooth.h>
#include <pthread.h>
@@ -38,6 +39,7 @@
#include "osi/include/osi.h"
using bluetooth::common::BluetoothMetricsLogger;
+using namespace bluetooth;
static bt_os_callouts_t* wakelock_os_callouts = NULL;
static bool is_native = true;
@@ -90,7 +92,7 @@
void wakelock_set_os_callouts(bt_os_callouts_t* callouts) {
wakelock_os_callouts = callouts;
is_native = (wakelock_os_callouts == NULL);
- LOG_INFO("%s set to %s", __func__, (is_native) ? "native" : "non-native");
+ log::info("set to {}", (is_native) ? "native" : "non-native");
}
bool wakelock_acquire(void) {
@@ -106,7 +108,7 @@
update_wakelock_acquired_stats(status);
if (status != BT_STATUS_SUCCESS)
- LOG_ERROR("%s unable to acquire wake lock: %d", __func__, status);
+ log::error("unable to acquire wake lock: {}", status);
return (status == BT_STATUS_SUCCESS);
}
@@ -118,23 +120,23 @@
static bt_status_t wakelock_acquire_native(void) {
if (wake_lock_fd == INVALID_FD) {
- LOG_ERROR("%s lock not acquired, invalid fd", __func__);
+ log::error("lock not acquired, invalid fd");
return BT_STATUS_PARM_INVALID;
}
if (wake_unlock_fd == INVALID_FD) {
- LOG_ERROR("%s not acquiring lock: can't release lock", __func__);
+ log::error("not acquiring lock: can't release lock");
return BT_STATUS_PARM_INVALID;
}
long lock_name_len = strlen(WAKE_LOCK_ID);
locked_id_len = write(wake_lock_fd, WAKE_LOCK_ID, lock_name_len);
if (locked_id_len == -1) {
- LOG_ERROR("%s wake lock not acquired: %s", __func__, strerror(errno));
+ log::error("wake lock not acquired: {}", strerror(errno));
return BT_STATUS_FAIL;
} else if (locked_id_len < lock_name_len) {
// TODO (jamuraa): this is weird. maybe we should release and retry.
- LOG_WARN("%s wake lock truncated to %zd chars", __func__, locked_id_len);
+ log::warn("wake lock truncated to {} chars", locked_id_len);
}
return BT_STATUS_SUCCESS;
}
@@ -161,16 +163,15 @@
static bt_status_t wakelock_release_native(void) {
if (wake_unlock_fd == INVALID_FD) {
- LOG_ERROR("%s lock not released, invalid fd", __func__);
+ log::error("lock not released, invalid fd");
return BT_STATUS_PARM_INVALID;
}
ssize_t wrote_name_len = write(wake_unlock_fd, WAKE_LOCK_ID, locked_id_len);
if (wrote_name_len == -1) {
- LOG_ERROR("%s can't release wake lock: %s", __func__, strerror(errno));
+ log::error("can't release wake lock: {}", strerror(errno));
} else if (wrote_name_len < locked_id_len) {
- LOG_ERROR("%s lock release only wrote %zd, assuming released", __func__,
- wrote_name_len);
+ log::error("lock release only wrote {}, assuming released", wrote_name_len);
}
return BT_STATUS_SUCCESS;
}
@@ -182,28 +183,27 @@
}
static void wakelock_initialize_native(void) {
- LOG_INFO("%s opening wake locks", __func__);
+ log::info("opening wake locks");
if (wake_lock_path.empty()) wake_lock_path = DEFAULT_WAKE_LOCK_PATH;
wake_lock_fd = open(wake_lock_path.c_str(), O_RDWR | O_CLOEXEC);
if (wake_lock_fd == INVALID_FD) {
- LOG_ERROR("%s can't open wake lock %s: %s", __func__,
- wake_lock_path.c_str(), strerror(errno));
+ log::error("can't open wake lock {}: {}", wake_lock_path, strerror(errno));
}
if (wake_unlock_path.empty()) wake_unlock_path = DEFAULT_WAKE_UNLOCK_PATH;
wake_unlock_fd = open(wake_unlock_path.c_str(), O_RDWR | O_CLOEXEC);
if (wake_unlock_fd == INVALID_FD) {
- LOG_ERROR("%s can't open wake unlock %s: %s", __func__,
- wake_unlock_path.c_str(), strerror(errno));
+ log::error("can't open wake unlock {}: {}", wake_unlock_path,
+ strerror(errno));
}
}
void wakelock_cleanup(void) {
if (wakelock_stats.is_acquired) {
- LOG_ERROR("%s releasing wake lock as part of cleanup", __func__);
+ log::error("releasing wake lock as part of cleanup");
wakelock_release();
}
wake_lock_path.clear();
@@ -220,7 +220,7 @@
static uint64_t now_ms(void) {
struct timespec ts;
if (clock_gettime(CLOCK_ID, &ts) == -1) {
- LOG_ERROR("%s unable to get current time: %s", __func__, strerror(errno));
+ log::error("unable to get current time: {}", strerror(errno));
return 0;
}
diff --git a/system/osi/test/fuzzers/alarm/Android.bp b/system/osi/test/fuzzers/alarm/Android.bp
index 4a409c0..b8f57fd 100644
--- a/system/osi/test/fuzzers/alarm/Android.bp
+++ b/system/osi/test/fuzzers/alarm/Android.bp
@@ -15,12 +15,14 @@
"fuzz_alarm.cc",
],
shared_libs: [
+ "libbase",
"libcutils",
"liblog",
"libprotobuf-cpp-lite",
"libstatssocket",
],
static_libs: [
+ "libbluetooth_log",
"libbt-common",
"libchrome",
"libgmock",
diff --git a/system/osi/test/fuzzers/allocator/Android.bp b/system/osi/test/fuzzers/allocator/Android.bp
index 4b2541f..f4874ff 100644
--- a/system/osi/test/fuzzers/allocator/Android.bp
+++ b/system/osi/test/fuzzers/allocator/Android.bp
@@ -15,6 +15,8 @@
"fuzz_allocator.cc",
],
static_libs: [
+ "libbase",
+ "libbluetooth_log",
"libchrome",
"liblog",
"libosi",
diff --git a/system/osi/test/fuzzers/compat/Android.bp b/system/osi/test/fuzzers/compat/Android.bp
index b462b1a..33cb80a 100644
--- a/system/osi/test/fuzzers/compat/Android.bp
+++ b/system/osi/test/fuzzers/compat/Android.bp
@@ -15,10 +15,12 @@
"fuzz_compat.cc",
],
shared_libs: [
+ "libbase",
"libcutils",
"liblog",
],
static_libs: [
+ "libbluetooth_log",
"libosi",
],
cflags: ["-Wno-unused-parameter"],
diff --git a/system/osi/test/fuzzers/fixed_queue/Android.bp b/system/osi/test/fuzzers/fixed_queue/Android.bp
index 10cc656..8bb68f4 100644
--- a/system/osi/test/fuzzers/fixed_queue/Android.bp
+++ b/system/osi/test/fuzzers/fixed_queue/Android.bp
@@ -15,10 +15,12 @@
"fuzz_fixed_queue.cc",
],
shared_libs: [
+ "libbase",
"libcutils",
"liblog",
],
static_libs: [
+ "libbluetooth_log",
"libchrome",
"libosi",
],
diff --git a/system/osi/test/fuzzers/future/Android.bp b/system/osi/test/fuzzers/future/Android.bp
index 46cb4aa..46673e2 100644
--- a/system/osi/test/fuzzers/future/Android.bp
+++ b/system/osi/test/fuzzers/future/Android.bp
@@ -15,10 +15,12 @@
"fuzz_future.cc",
],
shared_libs: [
+ "libbase",
"libcutils",
"liblog",
],
static_libs: [
+ "libbluetooth_log",
"libchrome",
"libosi",
],
diff --git a/system/osi/test/fuzzers/list/Android.bp b/system/osi/test/fuzzers/list/Android.bp
index ff86765..65f4fcb 100644
--- a/system/osi/test/fuzzers/list/Android.bp
+++ b/system/osi/test/fuzzers/list/Android.bp
@@ -15,6 +15,8 @@
"fuzz_list.cc",
],
static_libs: [
+ "libbase",
+ "libbluetooth_log",
"libchrome",
"liblog",
"libosi",
diff --git a/system/osi/test/fuzzers/ringbuffer/Android.bp b/system/osi/test/fuzzers/ringbuffer/Android.bp
index beed8d1..bbba166 100644
--- a/system/osi/test/fuzzers/ringbuffer/Android.bp
+++ b/system/osi/test/fuzzers/ringbuffer/Android.bp
@@ -15,6 +15,8 @@
"fuzz_ringbuffer.cc",
],
static_libs: [
+ "libbase",
+ "libbluetooth_log",
"libchrome",
"liblog",
"libosi",
diff --git a/system/packet/avrcp/register_notification_packet.cc b/system/packet/avrcp/register_notification_packet.cc
index 0ba8374..d2c4e8c 100644
--- a/system/packet/avrcp/register_notification_packet.cc
+++ b/system/packet/avrcp/register_notification_packet.cc
@@ -17,6 +17,7 @@
#include "register_notification_packet.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "include/check.h"
#include "internal_include/bt_trace.h"
@@ -188,7 +189,7 @@
data_size = 2;
break;
case Event::VOLUME_CHANGED:
- LOG(FATAL) << "Volume Changed Notification Not Implemented";
+ log::fatal("Volume Changed Notification Not Implemented");
break;
}
@@ -244,7 +245,7 @@
}
case Event::VOLUME_CHANGED:
// TODO (apanicke): Add Volume Changed builder for when we are controller.
- LOG(FATAL) << "Volume Changed Notification Not Implemented";
+ log::fatal("Volume Changed Notification Not Implemented");
break;
}
diff --git a/system/packet/tests/fuzzers/Android.bp b/system/packet/tests/fuzzers/Android.bp
index a617b48..b002967 100644
--- a/system/packet/tests/fuzzers/Android.bp
+++ b/system/packet/tests/fuzzers/Android.bp
@@ -39,7 +39,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -75,7 +78,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -111,7 +117,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -147,7 +156,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -183,7 +195,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -219,7 +234,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -255,7 +273,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -291,7 +312,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -327,7 +351,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -363,7 +390,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -399,7 +429,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -435,7 +468,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -471,7 +507,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -507,7 +546,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -543,7 +585,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -579,7 +624,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -615,7 +663,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -651,7 +702,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -687,7 +741,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -723,7 +780,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -759,7 +819,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -795,7 +858,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -831,7 +897,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -867,7 +936,10 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
cc_fuzz {
@@ -903,5 +975,8 @@
cflags: [
"-Wno-unused-parameter",
],
- shared_libs: ["liblog"],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
}
diff --git a/system/pdl/Android.bp b/system/pdl/Android.bp
index c315c81..c9ae5f2 100644
--- a/system/pdl/Android.bp
+++ b/system/pdl/Android.bp
@@ -4,28 +4,3 @@
cmd: "$(location bluetooth_packetgen) --fuzzing --testing --include=packages/modules/Bluetooth/system/pdl --out=$(genDir) $(in)",
defaults_visibility: [":__subpackages__"],
}
-
-// TODO get rid of this by converting the l2cap cert tests (or deprecating them)
-genrule {
- name: "BluetoothGeneratedPackets_python3_cc",
- tools: [
- "bluetooth_packetgen",
- ],
- cmd: "$(location bluetooth_packetgen) --include=packages/modules/Bluetooth/system/pdl --out=$(genDir) --num_shards=10 $(in)",
- srcs: [
- "l2cap/l2cap_packets.pdl",
- ],
- out: [
- "l2cap/l2cap_packets_python3.cc",
- "l2cap/l2cap_packets_python3_shard_0.cc",
- "l2cap/l2cap_packets_python3_shard_1.cc",
- "l2cap/l2cap_packets_python3_shard_2.cc",
- "l2cap/l2cap_packets_python3_shard_3.cc",
- "l2cap/l2cap_packets_python3_shard_4.cc",
- "l2cap/l2cap_packets_python3_shard_5.cc",
- "l2cap/l2cap_packets_python3_shard_6.cc",
- "l2cap/l2cap_packets_python3_shard_7.cc",
- "l2cap/l2cap_packets_python3_shard_8.cc",
- "l2cap/l2cap_packets_python3_shard_9.cc",
- ],
-}
diff --git a/system/rust/src/connection/ffi/connection_shim.cc b/system/rust/src/connection/ffi/connection_shim.cc
index 5c5b227..c52cd19 100644
--- a/system/rust/src/connection/ffi/connection_shim.cc
+++ b/system/rust/src/connection/ffi/connection_shim.cc
@@ -14,6 +14,8 @@
#include "connection_shim.h"
+#include <bluetooth/log.h>
+
#include <algorithm>
#include <cstdint>
#include <iterator>
@@ -35,13 +37,13 @@
#ifdef TARGET_FLOSS
struct LeAclManagerCallbackShim {
void OnLeConnectSuccess(core::AddressWithType addr) const {
- LOG_ALWAYS_FATAL("system/rust not available in Floss");
+ log::fatal("system/rust not available in Floss");
}
void OnLeConnectFail(core::AddressWithType addr, uint8_t status) const {
- LOG_ALWAYS_FATAL("system/rust not available in Floss");
+ log::fatal("system/rust not available in Floss");
};
void OnLeDisconnection(core::AddressWithType addr) const {
- LOG_ALWAYS_FATAL("system/rust not available in Floss");
+ log::fatal("system/rust not available in Floss");
};
};
diff --git a/system/rust/src/core/ffi/module.cc b/system/rust/src/core/ffi/module.cc
index ace30e9..3b7d916 100644
--- a/system/rust/src/core/ffi/module.cc
+++ b/system/rust/src/core/ffi/module.cc
@@ -16,6 +16,7 @@
#include "module.h"
+#include <bluetooth/log.h>
#include <hardware/bt_gatt.h>
#include "btcore/include/module.h"
@@ -56,7 +57,7 @@
// We can't crash here since some adapter tests mis-use the stack
// startup/cleanup logic and start the stack without GATT, but don't fully
// mock out the native layer.
- LOG_ERROR(
+ bluetooth::log::error(
"GATT profile not started, so we cannot start the Rust loop - this "
"happens only in tests.");
bluetooth::rust_shim::FutureReady(*fut);
diff --git a/system/rust/src/gatt/ffi/gatt_shim.cc b/system/rust/src/gatt/ffi/gatt_shim.cc
index c85ca58..c63311e 100644
--- a/system/rust/src/gatt/ffi/gatt_shim.cc
+++ b/system/rust/src/gatt/ffi/gatt_shim.cc
@@ -16,6 +16,7 @@
#include <base/functional/bind.h>
#include <base/location.h>
+#include <bluetooth/log.h>
#include <cstdint>
#include <optional>
@@ -56,8 +57,8 @@
uint32_t offset, bool is_long) const {
auto addr = AddressOfConnection(conn_id);
if (!addr.has_value()) {
- LOG_WARN(
- "Dropping server read characteristic since connection %d not found",
+ log::warn(
+ "Dropping server read characteristic since connection {} not found",
conn_id);
return;
}
@@ -76,7 +77,7 @@
trans_id, addr.value(), attr_handle, offset, is_long));
break;
default:
- LOG_ALWAYS_FATAL("Unexpected backing type %d", attr_type);
+ log::fatal("Unexpected backing type {}", attr_type);
}
}
@@ -86,8 +87,8 @@
bool is_prepare, ::rust::Slice<const uint8_t> value) const {
auto addr = AddressOfConnection(conn_id);
if (!addr.has_value()) {
- LOG_WARN(
- "Dropping server write characteristic since connection %d not found",
+ log::warn(
+ "Dropping server write characteristic since connection {} not found",
conn_id);
return;
}
@@ -113,7 +114,7 @@
value.size()));
break;
default:
- LOG_ALWAYS_FATAL("Unexpected backing type %hhu", attr_type);
+ log::fatal("Unexpected backing type {}", attr_type);
}
}
@@ -127,8 +128,8 @@
bool execute) const {
auto addr = AddressOfConnection(conn_id);
if (!addr.has_value()) {
- LOG_WARN("Dropping server execute write since connection %d not found",
- conn_id);
+ log::warn("Dropping server execute write since connection {} not found",
+ conn_id);
return;
}
diff --git a/system/rust/src/gatt/ffi/gatt_shim.h b/system/rust/src/gatt/ffi/gatt_shim.h
index 6c7532f..faa6851 100644
--- a/system/rust/src/gatt/ffi/gatt_shim.h
+++ b/system/rust/src/gatt/ffi/gatt_shim.h
@@ -14,6 +14,8 @@
#pragma once
+#include <bluetooth/log.h>
+
#include <cstdint>
#include "include/hardware/bluetooth.h"
@@ -58,3 +60,9 @@
} // namespace gatt
} // namespace bluetooth
+
+namespace fmt {
+template <>
+struct formatter<bluetooth::gatt::AttributeBackingType>
+ : enum_formatter<bluetooth::gatt::AttributeBackingType> {};
+} // namespace fmt
diff --git a/system/setup.py b/system/setup.py
index 597b9df..b593205 100644
--- a/system/setup.py
+++ b/system/setup.py
@@ -87,8 +87,6 @@
author='Android Open Source Project',
license='Apache2.0',
description="""Bluetooth Cert Tests Package""",
- # Include root package so that bluetooth_packets_python3.so can be
- # included as well
packages=[''] + find_packages(exclude=['llvm_binutils', 'llvm_binutils.*']),
install_requires=install_requires,
package_data={
diff --git a/system/stack/Android.bp b/system/stack/Android.bp
index 5525a47..c1909cc 100644
--- a/system/stack/Android.bp
+++ b/system/stack/Android.bp
@@ -669,6 +669,8 @@
"libbt_shim_ffi",
],
shared_libs: [
+ "libbase",
+ "liblog",
"server_configurable_flags",
],
target: {
@@ -706,6 +708,7 @@
shared_libs: [
"libPlatformProperties",
"libaaudio",
+ "libbase",
"libcrypto",
"libcutils",
"libdl",
@@ -807,6 +810,7 @@
":TestMockHci",
":TestMockMainShim",
":TestMockMainShimEntry",
+ ":TestMockStackBtm",
":TestMockStackMetrics",
"rfcomm/port_api.cc",
"rfcomm/port_rfc.cc",
@@ -818,7 +822,6 @@
"rfcomm/rfc_ts_frames.cc",
"rfcomm/rfc_utils.cc",
"test/common/mock_btm_layer.cc",
- "test/common/mock_btu_layer.cc",
"test/common/mock_l2cap_layer.cc",
"test/common/stack_test_packet_utils.cc",
"test/rfcomm/stack_rfcomm_test.cc",
@@ -1193,15 +1196,7 @@
"packages/modules/Bluetooth/system/stack/include",
],
target: {
- host: {
- srcs: [
- ":BluetoothHostTestingLogCapture",
- ],
- },
android: {
- srcs: [
- ":BluetoothAndroidTestingLogCapture",
- ],
test_config: "test/a2dp/AndroidTest.xml",
},
android_x86: {
@@ -1427,7 +1422,6 @@
":TestMockMainShimEntry",
"btm/btm_iso.cc",
"test/btm_iso_test.cc",
- "test/common/mock_controller.cc",
"test/common/mock_gatt_layer.cc",
"test/common/mock_hcic_layer.cc",
],
@@ -1495,7 +1489,6 @@
"eatt/eatt.cc",
"test/common/mock_btif_storage.cc",
"test/common/mock_btm_api_layer.cc",
- "test/common/mock_controller.cc",
"test/common/mock_gatt_layer.cc",
"test/common/mock_l2cap_layer.cc",
"test/eatt/eatt_test.cc",
@@ -1691,6 +1684,7 @@
"test/hci/stack_hci_test.cc",
],
static_libs: [
+ "libbase",
"libbluetooth_crypto_toolbox",
"libbluetooth_log",
"libbt-common",
diff --git a/system/stack/BUILD.gn b/system/stack/BUILD.gn
index 07999bc..6309d1b 100644
--- a/system/stack/BUILD.gn
+++ b/system/stack/BUILD.gn
@@ -236,7 +236,6 @@
sources = [
"btm/btm_iso.cc",
"test/btm_iso_test.cc",
- "test/common/mock_controller.cc",
"test/common/mock_gatt_layer.cc",
"test/common/mock_hcic_layer.cc",
]
diff --git a/system/stack/acl/btm_acl.cc b/system/stack/acl/btm_acl.cc
index bc3234c..9c5eef7 100644
--- a/system/stack/acl/btm_acl.cc
+++ b/system/stack/acl/btm_acl.cc
@@ -31,7 +31,6 @@
*
*****************************************************************************/
-#include "main/shim/entry.h"
#define LOG_TAG "btm_acl"
#include <bluetooth/log.h>
@@ -42,7 +41,6 @@
#include "bta/sys/bta_sys.h"
#include "common/init_flags.h"
#include "common/metrics.h"
-#include "device/include/controller.h"
#include "device/include/device_iot_config.h"
#include "device/include/interop.h"
#include "hci/controller_interface.h"
@@ -50,8 +48,9 @@
#include "include/l2cap_hci_link_interface.h"
#include "internal_include/bt_target.h"
#include "main/shim/acl_api.h"
-#include "main/shim/controller.h"
#include "main/shim/dumpsys.h"
+#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "os/log.h"
#include "os/parameter_provider.h"
#include "osi/include/allocator.h"
@@ -227,8 +226,8 @@
return;
}
- if (!bluetooth::shim::
- controller_is_write_link_supervision_timeout_supported()) {
+ if (!bluetooth::shim::GetController()->IsSupported(
+ bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT)) {
log::warn(
"UNSUPPORTED by controller write link supervision timeout:{:.2f}ms "
"bd_addr:{}",
@@ -246,7 +245,7 @@
/* 3 seconds timeout waiting for responses */
#define BTM_DEV_REPLY_TIMEOUT_MS (3 * 1000)
-void BTM_acl_after_controller_started(const controller_t* controller) {
+void BTM_acl_after_controller_started() {
internal_.btm_set_default_link_policy(
HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH | HCI_ENABLE_HOLD_MODE |
HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_PARK_MODE);
@@ -1123,8 +1122,8 @@
/* Only send if current role is Central; 2.0 spec requires this */
if (p_acl->link_role == HCI_ROLE_CENTRAL) {
- if (!bluetooth::shim::
- controller_is_write_link_supervision_timeout_supported()) {
+ if (!bluetooth::shim::GetController()->IsSupported(
+ bluetooth::hci::OpCode::WRITE_LINK_SUPERVISION_TIMEOUT)) {
log::warn(
"UNSUPPORTED by controller write link supervision timeout:{:.2f}ms "
"bd_addr:{}",
@@ -1542,7 +1541,8 @@
pkt_types = p->pkt_types_mask;
} else {
/* Special case for when info for the local device is requested */
- if (addr == *controller_get_interface()->get_address()) {
+ if (addr == bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress())) {
pkt_types = btm_cb.acl_cb_.DefaultPacketTypes();
}
}
@@ -2231,6 +2231,15 @@
return HCI_LE_CONN_PARAM_REQ_SUPPORTED(p_acl->peer_le_features);
}
+void acl_ble_connection_parameters_request(
+ 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) {
+ bluetooth::shim::ACL_SendConnectionParameterUpdateRequest(
+ handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
+ min_ce_len, max_ce_len);
+}
+
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) {
@@ -2532,7 +2541,7 @@
/* Some device may request a connection before we are done with the HCI_Reset
* sequence */
- if (!controller_get_interface()->get_is_ready()) {
+ if (bluetooth::shim::GetController() == nullptr) {
log::verbose("Security Manager: connect request when device not ready");
btsnd_hcic_reject_conn(bda, HCI_ERR_HOST_REJECT_DEVICE);
return;
@@ -2803,3 +2812,14 @@
*address_with_type = {.type = BLE_ADDR_PUBLIC, .bda = bd_addr};
return;
}
+
+/*******************************************************************************
+ *
+ * Function btm_acl_flush
+ *
+ * Description This function is called by L2CAP to flush an ACL link.
+ *
+ * Returns void
+ *
+ ******************************************************************************/
+void btm_acl_flush(uint16_t handle) { bluetooth::shim::ACL_Flush(handle); }
diff --git a/system/stack/bnep/bnep_main.cc b/system/stack/bnep/bnep_main.cc
index 6f6ed8f..5f8f9da 100644
--- a/system/stack/bnep/bnep_main.cc
+++ b/system/stack/bnep/bnep_main.cc
@@ -30,10 +30,12 @@
#include "bnep_api.h"
#include "bnep_int.h"
#include "bta/include/bta_sec_api.h"
-#include "device/include/controller.h"
+#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "l2c_api.h"
#include "l2cdefs.h"
+#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/osi.h"
@@ -496,7 +498,8 @@
if (src_addr == RawAddress::kEmpty) src_addr = p_bcb->rem_bda;
if (dst_addr == RawAddress::kEmpty)
- dst_addr = *controller_get_interface()->get_address();
+ dst_addr = bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress());
/* check whether there are any extensions to be forwarded */
if (ext_type)
diff --git a/system/stack/bnep/bnep_utils.cc b/system/stack/bnep/bnep_utils.cc
index 51e5059..dcbb7c0 100644
--- a/system/stack/bnep/bnep_utils.cc
+++ b/system/stack/bnep/bnep_utils.cc
@@ -27,8 +27,10 @@
#include <string.h>
#include "bnep_int.h"
-#include "device/include/controller.h"
+#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
+#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
@@ -433,7 +435,6 @@
void bnepu_build_bnep_hdr(tBNEP_CONN* p_bcb, BT_HDR* p_buf, uint16_t protocol,
const RawAddress& src_addr,
const RawAddress& dest_addr, bool fw_ext_present) {
- const controller_t* controller = controller_get_interface();
uint8_t ext_bit, *p = (uint8_t*)NULL;
uint8_t type = BNEP_FRAME_COMPRESSED_ETHERNET;
RawAddress source_addr = src_addr;
@@ -441,7 +442,8 @@
ext_bit = fw_ext_present ? 0x80 : 0x00;
if (source_addr != RawAddress::kEmpty &&
- source_addr != *controller->get_address())
+ source_addr != bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress()))
type = BNEP_FRAME_COMPRESSED_ETHERNET_SRC_ONLY;
if (dest_addr != p_bcb->rem_bda)
@@ -450,7 +452,8 @@
: BNEP_FRAME_GENERAL_ETHERNET;
if (source_addr == RawAddress::kEmpty)
- source_addr = *controller->get_address();
+ source_addr = bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress());
switch (type) {
case BNEP_FRAME_GENERAL_ETHERNET:
diff --git a/system/stack/btm/ble_scanner_hci_interface.cc b/system/stack/btm/ble_scanner_hci_interface.cc
index 527f23b..1a0f689 100644
--- a/system/stack/btm/ble_scanner_hci_interface.cc
+++ b/system/stack/btm/ble_scanner_hci_interface.cc
@@ -22,7 +22,6 @@
#include <bluetooth/log.h>
#include "btm_api.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "main/shim/entry.h"
#include "stack/include/bt_types.h"
@@ -110,7 +109,7 @@
void PeriodicAdvertiserListGetSize(
BleScannerHciInterface::list_size_cb command_complete) override {
command_complete.Run(
- controller_get_interface()->get_ble_periodic_advertiser_list_size());
+ bluetooth::shim::GetController()->GetLePeriodicAdvertiserListSize());
}
void PeriodicAdvertiserListAddDevice(uint8_t adv_addr_type,
@@ -304,7 +303,7 @@
void BleScannerHciInterface::Initialize() {
LOG_ASSERT(instance == nullptr) << "Was already initialized.";
- if ((controller_get_interface()->get_ble_periodic_advertiser_list_size()) &&
+ if ((bluetooth::shim::GetController()->GetLePeriodicAdvertiserListSize()) &&
(bluetooth::shim::GetController()
->SupportsBlePeriodicAdvertisingSyncTransferSender())) {
log::info("Advertiser list in controller can be used");
@@ -314,8 +313,8 @@
->SupportsBlePeriodicAdvertisingSyncTransferSender()) {
log::info("Periodic Adv Sync Transfer Sender role is supported");
instance = new BleScannerSyncTransferImpl();
- } else if (controller_get_interface()
- ->get_ble_periodic_advertiser_list_size()) {
+ } else if (bluetooth::shim::GetController()
+ ->GetLePeriodicAdvertiserListSize()) {
log::info("Periodic Adv Sync Transfer Recipient role is supported");
instance = new BleScannerListImpl();
}
diff --git a/system/stack/btm/btm_ble_addr.cc b/system/stack/btm/btm_ble_addr.cc
index 8f38e58..db0a888 100644
--- a/system/stack/btm/btm_ble_addr.cc
+++ b/system/stack/btm/btm_ble_addr.cc
@@ -34,7 +34,6 @@
#include "btm_dev.h"
#include "btm_sec_cb.h"
#include "crypto_toolbox/crypto_toolbox.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "main/shim/entry.h"
#include "os/log.h"
@@ -194,7 +193,7 @@
/* evt reported on static address, map static address to random pseudo */
/* if RPA offloading is supported, or 4.2 controller, do RPA refresh */
if (refresh &&
- controller_get_interface()->get_ble_resolving_list_max_size() != 0) {
+ bluetooth::shim::GetController()->GetLeResolvingListSize() != 0) {
btm_ble_read_resolving_list_entry(p_dev_rec);
}
diff --git a/system/stack/btm/btm_ble_gap.cc b/system/stack/btm/btm_ble_gap.cc
index 8190a7d..b89c6fc 100644
--- a/system/stack/btm/btm_ble_gap.cc
+++ b/system/stack/btm/btm_ble_gap.cc
@@ -38,7 +38,6 @@
#include "bta/include/bta_api.h"
#include "common/time_util.h"
-#include "device/include/controller.h"
#include "hci/controller.h"
#include "hci/controller_interface.h"
#include "include/check.h"
@@ -469,10 +468,9 @@
}};
/* check LE combo state supported */
-inline bool BTM_LE_STATES_SUPPORTED(const uint8_t* x, uint8_t bit_num) {
- uint8_t mask = 1 << (bit_num % 8);
- uint8_t offset = bit_num / 8;
- return ((x)[offset] & mask);
+inline bool BTM_LE_STATES_SUPPORTED(const uint64_t x, uint8_t bit_num) {
+ uint64_t mask = 1 << bit_num;
+ return ((x)&mask);
}
void BTM_BleOpportunisticObserve(bool enable,
@@ -763,8 +761,9 @@
}
if (btm_cb.cmn_ble_vsc_cb.filter_support == 1 &&
- controller_get_interface()->get_bt_version()->manufacturer ==
- LMP_COMPID_QTI) {
+ bluetooth::shim::GetController()
+ ->GetLocalVersionInformation()
+ .manufacturer_name_ == LMP_COMPID_QTI) {
// QTI controller, TDS data filter are supported by default. Check is added
// to keep backward compatibility.
btm_cb.cmn_ble_vsc_cb.adv_filter_extended_features_mask = 0x01;
@@ -787,7 +786,7 @@
if (bluetooth::shim::GetController()->SupportsBle() &&
bluetooth::shim::GetController()->SupportsBlePrivacy() &&
btm_cb.cmn_ble_vsc_cb.max_irk_list_sz > 0 &&
- controller_get_interface()->get_ble_resolving_list_max_size() == 0)
+ bluetooth::shim::GetController()->GetLeResolvingListSize() == 0)
btm_ble_resolving_list_init(btm_cb.cmn_ble_vsc_cb.max_irk_list_sz);
if (p_ctrl_le_feature_rd_cmpl_cback != NULL)
@@ -843,8 +842,8 @@
if (IS_FLAG_ENABLED(report_vsc_data_from_the_gd_controller)) {
btm_cb.cmn_ble_vsc_cb.values_read = true;
- bluetooth::hci::Controller::VendorCapabilities vendor_capabilities =
- GetController()->GetVendorCapabilities();
+ bluetooth::hci::ControllerInterface::VendorCapabilities
+ vendor_capabilities = GetController()->GetVendorCapabilities();
btm_cb.cmn_ble_vsc_cb.adv_inst_max =
vendor_capabilities.max_advt_instances_;
@@ -1999,12 +1998,7 @@
uint16_t length, char* p_name) {
tHCI_STATUS hci_status = HCI_SUCCESS;
BD_NAME bd_name;
-
- memset(bd_name, 0, (BD_NAME_LEN + 1));
- if (length > BD_NAME_LEN) {
- length = BD_NAME_LEN;
- }
- memcpy((uint8_t*)bd_name, p_name, length);
+ bd_name_from_char_pointer(bd_name, p_name);
if ((!status) || (length == 0)) {
hci_status = HCI_ERR_HOST_TIMEOUT;
@@ -2616,6 +2610,9 @@
include_rsi = true;
}
+ const uint8_t* p_flag = AdvertiseDataParser::GetFieldByType(
+ advertising_data, BTM_BLE_AD_TYPE_FLAG, &len);
+
tINQ_DB_ENT* p_i = btm_inq_db_find(bda);
/* Check if this address has already been processed for this inquiry */
@@ -2624,7 +2621,9 @@
if (p_i && (!(p_i->inq_info.results.device_type & BT_DEVICE_TYPE_BLE) ||
/* scan response to be updated */
(!p_i->scan_rsp) ||
- (!p_i->inq_info.results.include_rsi && include_rsi))) {
+ (!p_i->inq_info.results.include_rsi && include_rsi) ||
+ (IS_FLAG_ENABLED(update_inquiry_result_on_flag_change) &&
+ !p_i->inq_info.results.flag && p_flag && *p_flag))) {
update = true;
} else if (btm_cb.ble_ctr_cb.is_ble_observe_active()) {
btm_cb.neighbor.le_observe.results++;
@@ -3230,8 +3229,8 @@
/* check if the requested state is supported or not */
uint8_t bit_num = btm_le_state_combo_tbl[0][request_state - 1];
- const uint8_t* ble_supported_states =
- controller_get_interface()->get_ble_supported_states();
+ uint64_t ble_supported_states =
+ bluetooth::shim::GetController()->GetLeSupportedStates();
if (!BTM_LE_STATES_SUPPORTED(ble_supported_states, bit_num)) {
log::error("state requested not supported: {}", request_state);
diff --git a/system/stack/btm/btm_ble_privacy.cc b/system/stack/btm/btm_ble_privacy.cc
index 2217400..aa0b6d1 100644
--- a/system/stack/btm/btm_ble_privacy.cc
+++ b/system/stack/btm/btm_ble_privacy.cc
@@ -30,7 +30,6 @@
#include "btm_dev.h"
#include "btm_sec_cb.h"
#include "btm_sec_int_types.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "main/shim/acl_api.h"
#include "main/shim/entry.h"
@@ -85,7 +84,7 @@
p_q->resolve_q_random_pseudo[p_q->q_next] = pseudo_bda;
p_q->resolve_q_action[p_q->q_next] = op_code;
p_q->q_next++;
- p_q->q_next %= controller_get_interface()->get_ble_resolving_list_max_size();
+ p_q->q_next %= bluetooth::shim::GetController()->GetLeResolvingListSize();
}
/*******************************************************************************
@@ -110,7 +109,7 @@
return true;
i++;
- i %= controller_get_interface()->get_ble_resolving_list_max_size();
+ i %= bluetooth::shim::GetController()->GetLeResolvingListSize();
}
return false;
}
@@ -135,7 +134,7 @@
p_q->resolve_q_random_pseudo[p_q->q_pending] = RawAddress::kEmpty;
p_q->q_pending++;
p_q->q_pending %=
- controller_get_interface()->get_ble_resolving_list_max_size();
+ bluetooth::shim::GetController()->GetLeResolvingListSize();
return true;
}
@@ -155,7 +154,7 @@
uint8_t byte;
uint8_t bit;
- if (index < controller_get_interface()->get_ble_resolving_list_max_size()) {
+ if (index < bluetooth::shim::GetController()->GetLeResolvingListSize()) {
byte = index / 8;
bit = index % 8;
btm_cb.ble_ctr_cb.irk_list_mask[byte] &= (~(1 << bit));
@@ -176,7 +175,7 @@
uint8_t byte;
uint8_t bit;
- while (i < controller_get_interface()->get_ble_resolving_list_max_size()) {
+ while (i < bluetooth::shim::GetController()->GetLeResolvingListSize()) {
byte = i / 8;
bit = i % 8;
@@ -257,7 +256,7 @@
uint8_t irk_list_sz_max = 0;
STREAM_TO_UINT8(irk_list_sz_max, p);
- if (controller_get_interface()->get_ble_resolving_list_max_size() == 0)
+ if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0)
btm_ble_resolving_list_init(irk_list_sz_max);
uint8_t irk_mask_size = (irk_list_sz_max % 8) ? (irk_list_sz_max / 8 + 1)
@@ -266,7 +265,7 @@
}
btm_cb.ble_ctr_cb.resolving_list_avail_size =
- controller_get_interface()->get_ble_resolving_list_max_size();
+ bluetooth::shim::GetController()->GetLeResolvingListSize();
log::verbose("resolving_list_avail_size={}",
btm_cb.ble_ctr_cb.resolving_list_avail_size);
@@ -443,7 +442,7 @@
static tBTM_STATUS btm_ble_remove_resolving_list_entry(
tBTM_SEC_DEV_REC* p_dev_rec) {
/* if controller does not support RPA offloading or privacy 1.2, skip */
- if (controller_get_interface()->get_ble_resolving_list_max_size() == 0)
+ if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0)
return BTM_WRONG_MODE;
if (bluetooth::shim::GetController()->SupportsBlePrivacy()) {
@@ -560,7 +559,7 @@
log::debug("Privacy 1.2 is not enabled");
return;
}
- if (controller_get_interface()->get_ble_resolving_list_max_size() == 0) {
+ if (bluetooth::shim::GetController()->GetLeResolvingListSize() == 0) {
log::info("Controller does not support RPA offloading or privacy 1.2");
return;
}
@@ -665,7 +664,6 @@
log::verbose("max_irk_list_sz={}", max_irk_list_sz);
}
- controller_get_interface()->set_ble_resolving_list_max_size(max_irk_list_sz);
btm_ble_clear_resolving_list();
btm_cb.ble_ctr_cb.resolving_list_avail_size = max_irk_list_sz;
}
diff --git a/system/stack/btm/btm_ble_scanner.cc b/system/stack/btm/btm_ble_scanner.cc
index 107d710..0831468 100644
--- a/system/stack/btm/btm_ble_scanner.cc
+++ b/system/stack/btm/btm_ble_scanner.cc
@@ -18,8 +18,6 @@
#include "ble_scanner.h"
#include "ble_scanner_hci_interface.h"
-#include "internal_include/bt_target.h"
-#include "internal_include/stack_config.h"
#include "stack/btm/btm_ble_int.h"
using namespace bluetooth;
diff --git a/system/stack/btm/btm_ble_sec.cc b/system/stack/btm/btm_ble_sec.cc
index 346a155..9a2fb57 100644
--- a/system/stack/btm/btm_ble_sec.cc
+++ b/system/stack/btm/btm_ble_sec.cc
@@ -28,7 +28,6 @@
#include "btif/include/btif_storage.h"
#include "crypto_toolbox/crypto_toolbox.h"
-#include "device/include/controller.h"
#include "device/include/interop.h"
#include "device/include/interop_config.h"
#include "hci/controller_interface.h"
@@ -605,8 +604,9 @@
uint16_t tx_time = BTM_BLE_DATA_TX_TIME_MAX_LEGACY;
- if (controller_get_interface()->get_bt_version()->hci_version >=
- HCI_PROTO_VERSION_5_0)
+ if (bluetooth::shim::GetController()
+ ->GetLocalVersionInformation()
+ .hci_version_ >= bluetooth::hci::HciVersion::V_5_0)
tx_time = BTM_BLE_DATA_TX_TIME_MAX;
if (!BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) {
@@ -622,11 +622,13 @@
return BTM_ILLEGAL_VALUE;
}
- tx_pdu_length = std::min<uint16_t>(
- tx_pdu_length,
- controller_get_interface()->get_ble_maximum_tx_data_length());
- tx_time = std::min<uint16_t>(
- tx_time, controller_get_interface()->get_ble_maximum_tx_time());
+ tx_pdu_length =
+ std::min<uint16_t>(tx_pdu_length, bluetooth::shim::GetController()
+ ->GetLeMaximumDataLength()
+ .supported_max_tx_octets_);
+ tx_time = std::min<uint16_t>(tx_time, bluetooth::shim::GetController()
+ ->GetLeMaximumDataLength()
+ .supported_max_tx_time_);
btsnd_hcic_ble_set_data_length(hci_handle, tx_pdu_length, tx_time);
p_dev_rec->set_suggested_tx_octect(tx_pdu_length);
diff --git a/system/stack/btm/btm_dev.cc b/system/stack/btm/btm_dev.cc
index bd02c70..4042cfa 100644
--- a/system/stack/btm/btm_dev.cc
+++ b/system/stack/btm/btm_dev.cc
@@ -77,26 +77,20 @@
*
* Parameters: bd_addr - BD address of the peer
* dev_class - Device Class
- * bd_name - Name of the peer device. NULL if unknown.
- * features - Remote device's features (up to 3 pages).
- * NULL if not known
* link_key - Connection link key. NULL if unknown.
*
- * Returns true if added OK, else false
+ * Returns void
*
******************************************************************************/
-bool BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class,
- const BD_NAME& bd_name, uint8_t* features,
- LinkKey* p_link_key, uint8_t key_type,
- uint8_t pin_length) {
+void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class,
+ LinkKey link_key, uint8_t key_type, uint8_t pin_length) {
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:{} link_key_type:{:x} "
- "name:{}",
- ADDRESS_TO_LOGGABLE_STR(bd_addr), key_type,
- reinterpret_cast<const char*>(bd_name));
+ log::info(
+ "Caching new record from config file device: {}, dev_class: 0x{:02x}, "
+ "link_key_type: 0x{:x}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), fmt::join(dev_class, ""), key_type);
p_dev_rec->bd_addr = bd_addr;
p_dev_rec->hci_handle = BTM_GetHCIConnHandle(bd_addr, BT_TRANSPORT_BR_EDR);
@@ -105,9 +99,10 @@
/* 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:{} link_key_type:{:x}",
- ADDRESS_TO_LOGGABLE_STR(bd_addr), key_type);
+ log::info(
+ "Caching existing record from config file device: {}, dev_class: "
+ "0x{:02x}, link_key_type: 0x{:x}",
+ ADDRESS_TO_LOGGABLE_STR(bd_addr), fmt::join(dev_class, ""), key_type);
/* "Bump" timestamp for existing record */
p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
@@ -125,39 +120,25 @@
memset(p_dev_rec->sec_bd_name, 0, sizeof(BD_NAME));
- if (bd_name && bd_name[0]) {
- 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;
- bd_name_copy(p_dev_rec->sec_bd_name, bd_name);
+ p_dev_rec->sec_rec.sec_flags |= BTM_SEC_LINK_KEY_KNOWN;
+ p_dev_rec->sec_rec.link_key = link_key;
+ p_dev_rec->sec_rec.link_key_type = key_type;
+ p_dev_rec->sec_rec.pin_code_length = pin_length;
+
+ if (IS_FLAG_ENABLED(correct_bond_type_of_loaded_devices)) {
+ p_dev_rec->sec_rec.bond_type = BOND_TYPE_PERSISTENT;
}
- if (p_link_key) {
- 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;
- p_dev_rec->sec_rec.pin_code_length = pin_length;
-
- if (IS_FLAG_ENABLED(correct_bond_type_of_loaded_devices)) {
- p_dev_rec->sec_rec.bond_type = BOND_TYPE_PERSISTENT;
- }
-
- if (pin_length >= 16 || key_type == BTM_LKEY_TYPE_AUTH_COMB ||
- key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
- // Set the flag if the link key was made by using either a 16 digit
- // pin or MITM.
- p_dev_rec->sec_rec.sec_flags |=
- BTM_SEC_16_DIGIT_PIN_AUTHED | BTM_SEC_LINK_KEY_AUTHED;
- }
+ if (pin_length >= 16 || key_type == BTM_LKEY_TYPE_AUTH_COMB ||
+ key_type == BTM_LKEY_TYPE_AUTH_COMB_P_256) {
+ // Set the flag if the link key was made by using either a 16 digit
+ // pin or MITM.
+ p_dev_rec->sec_rec.sec_flags |=
+ BTM_SEC_16_DIGIT_PIN_AUTHED | BTM_SEC_LINK_KEY_AUTHED;
}
p_dev_rec->sec_rec.rmt_io_caps = BTM_IO_CAP_OUT;
p_dev_rec->device_type |= BT_DEVICE_TYPE_BREDR;
-
- return true;
}
/** Removes the device from acceptlist */
diff --git a/system/stack/btm/btm_devctl.cc b/system/stack/btm/btm_devctl.cc
index a484e27..3310aee3 100644
--- a/system/stack/btm/btm_devctl.cc
+++ b/system/stack/btm/btm_devctl.cc
@@ -34,7 +34,6 @@
#include "btif/include/btif_bqr.h"
#include "btm_sec_cb.h"
#include "btm_sec_int_types.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "main/shim/btm_api.h"
@@ -174,8 +173,6 @@
}
void BTM_reset_complete() {
- const controller_t* controller = controller_get_interface();
-
/* Tell L2CAP that all connections are gone */
l2cu_device_reset();
@@ -205,8 +202,9 @@
/* Set up the BLE privacy settings */
if (bluetooth::shim::GetController()->SupportsBle() &&
bluetooth::shim::GetController()->SupportsBlePrivacy() &&
- controller->get_ble_resolving_list_max_size() > 0) {
- btm_ble_resolving_list_init(controller->get_ble_resolving_list_max_size());
+ bluetooth::shim::GetController()->GetLeResolvingListSize() > 0) {
+ btm_ble_resolving_list_init(
+ bluetooth::shim::GetController()->GetLeResolvingListSize());
/* set the default random private address timeout */
btsnd_hcic_ble_set_rand_priv_addr_timeout(
btm_get_next_private_addrress_interval_ms() / 1000);
@@ -236,7 +234,9 @@
* Returns true if device is up, else false
*
******************************************************************************/
-bool BTM_IsDeviceUp(void) { return controller_get_interface()->get_is_ready(); }
+bool BTM_IsDeviceUp(void) {
+ return bluetooth::shim::GetController() != nullptr;
+}
/*******************************************************************************
*
@@ -300,7 +300,7 @@
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_acl_after_controller_started();
btm_sec_dev_reset();
if (bluetooth::shim::GetController()->SupportsRssiWithInquiryResults()) {
@@ -331,7 +331,7 @@
if (!p_name || !p_name[0] || (strlen((char*)p_name) > BD_NAME_LEN))
return (BTM_ILLEGAL_VALUE);
- if (!controller_get_interface()->get_is_ready()) return (BTM_DEV_RESET);
+ if (bluetooth::shim::GetController() == nullptr) return (BTM_DEV_RESET);
/* Save the device name if local storage is enabled */
p = (uint8_t*)btm_sec_cb.cfg.bd_name;
if (p != (uint8_t*)p_name)
@@ -428,7 +428,7 @@
btm_cb.devcb.dev_class = dev_class;
- if (!controller_get_interface()->get_is_ready()) return (BTM_DEV_RESET);
+ if (bluetooth::shim::GetController() == nullptr) return (BTM_DEV_RESET);
btsnd_hcic_write_dev_class(dev_class);
diff --git a/system/stack/btm/btm_inq.cc b/system/stack/btm/btm_inq.cc
index 57629f7..f094c0b 100644
--- a/system/stack/btm/btm_inq.cc
+++ b/system/stack/btm/btm_inq.cc
@@ -37,10 +37,10 @@
#include <mutex>
#include "advertise_data_parser.h"
+#include "bt_name.h"
#include "btif/include/btif_acl.h"
#include "btif/include/btif_config.h"
#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"
@@ -298,9 +298,6 @@
/*** Check mode parameter ***/
if (inq_mode > BTM_MAX_DISCOVERABLE) return (BTM_ILLEGAL_VALUE);
- /* Make sure the controller is active */
- 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 {} [NonDisc-0, Lim-1, Gen-2]", inq_mode);
(inq_mode != BTM_NON_DISCOVERABLE)
@@ -461,9 +458,6 @@
if (page_mode != BTM_NON_CONNECTABLE && page_mode != BTM_CONNECTABLE)
return (BTM_ILLEGAL_VALUE);
- /* Make sure the controller is active */
- if (!controller_get_interface()->get_is_ready()) return (BTM_DEV_RESET);
-
/*** Only check window and duration if mode is connectable ***/
if (page_mode == BTM_CONNECTABLE) {
scan_mode |= HCI_PAGE_SCAN_ENABLED;
@@ -1995,18 +1989,14 @@
/* Copy the name from the data stream into the return structure */
/* Note that even if it is not being returned, it is used as a */
/* temporary buffer. */
- rem_name.length = (evt_len < BD_NAME_LEN) ? evt_len : BD_NAME_LEN;
rem_name.status = BTM_SUCCESS;
rem_name.hci_status = hci_status;
-
bd_name_copy(rem_name.remote_bd_name, bdn);
- rem_name.remote_bd_name[rem_name.length] = 0;
} else {
/* If processing a stand alone remote name then report the error in the
callback */
rem_name.status = BTM_BAD_VALUE_RET;
rem_name.hci_status = hci_status;
- rem_name.length = 0;
rem_name.remote_bd_name[0] = 0;
}
/* Reset the remote BAD to zero and call callback if possible */
diff --git a/system/stack/btm/btm_iso_impl.h b/system/stack/btm/btm_iso_impl.h
index e2f5a89..ad513ce 100644
--- a/system/stack/btm/btm_iso_impl.h
+++ b/system/stack/btm/btm_iso_impl.h
@@ -28,7 +28,6 @@
#include "btm_dev.h"
#include "btm_iso_api.h"
#include "common/time_util.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "hci/include/hci_layer.h"
#include "internal_include/bt_trace.h"
diff --git a/system/stack/btm/btm_sco.cc b/system/stack/btm/btm_sco.cc
index 99a21b2..bcfb857 100644
--- a/system/stack/btm/btm_sco.cc
+++ b/system/stack/btm/btm_sco.cc
@@ -37,7 +37,6 @@
#include <vector>
#include "common/bidi_queue.h"
-#include "device/include/controller.h"
#include "device/include/device_iot_config.h"
#include "hci/class_of_device.h"
#include "hci/controller_interface.h"
@@ -743,8 +742,9 @@
p_setup->packet_types = pkt_types & BTM_SCO_SUPPORTED_PKTS_MASK &
btm_cb.btm_sco_pkt_types_supported;
/* OR in any exception packet types */
- if (controller_get_interface()->get_bt_version()->hci_version >=
- HCI_PROTO_VERSION_2_0) {
+ if (bluetooth::shim::GetController()
+ ->GetLocalVersionInformation()
+ .hci_version_ >= bluetooth::hci::HciVersion::V_2_0) {
p_setup->packet_types |=
(pkt_types & BTM_SCO_EXCEPTION_PKTS_MASK) |
(btm_cb.btm_sco_pkt_types_supported & BTM_SCO_EXCEPTION_PKTS_MASK);
diff --git a/system/stack/btm/btm_sec.cc b/system/stack/btm/btm_sec.cc
index b88a087..184bbf0 100644
--- a/system/stack/btm/btm_sec.cc
+++ b/system/stack/btm/btm_sec.cc
@@ -30,6 +30,7 @@
#include <base/strings/stringprintf.h>
#include <bluetooth/log.h>
+#include <cstddef>
#include <cstdint>
#include <string>
@@ -38,13 +39,13 @@
#include "common/init_flags.h"
#include "common/metrics.h"
#include "common/time_util.h"
-#include "device/include/controller.h"
#include "device/include/device_iot_config.h"
#include "device/include/interop.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "l2c_api.h"
#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "osi/include/allocator.h"
#include "osi/include/properties.h"
#include "stack/btm/btm_ble_int.h"
@@ -395,7 +396,7 @@
/* If device is not up security mode will be set as a part of startup */
if ((btm_sec_cb.cfg.pin_type != pin_type) &&
- controller_get_interface()->get_is_ready()) {
+ bluetooth::shim::GetController() != nullptr) {
btsnd_hcic_write_pin_type(pin_type);
}
@@ -620,7 +621,7 @@
return (BTM_NO_RESOURCES);
}
- if (!controller_get_interface()->get_is_ready()) {
+ if (bluetooth::shim::GetController() == nullptr) {
log::error("controller module is not ready");
return (BTM_NO_RESOURCES);
}
@@ -2218,6 +2219,12 @@
if (!p_bd_name) p_bd_name = (const uint8_t*)kBtmBdNameEmpty;
+ BTM_LogHistory(kBtmLogTag, (p_bd_addr) ? *p_bd_addr : RawAddress::kEmpty,
+ "RNR complete",
+ base::StringPrintf("status:%s name:%s",
+ hci_error_code_text(status).c_str(),
+ PRIVATE_NAME(p_bd_name)));
+
if (p_dev_rec == nullptr) {
log::debug(
"Remote read request complete for unknown device pairing_state:{} "
@@ -4253,7 +4260,8 @@
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();
+ RawAddress local_bd_addr = bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress());
if (p_bda == local_bd_addr) {
btsnd_hcic_pin_code_neg_reply(p_bda);
return;
diff --git a/system/stack/btm/neighbor_inquiry.h b/system/stack/btm/neighbor_inquiry.h
index bf74997..b0fc502 100644
--- a/system/stack/btm/neighbor_inquiry.h
+++ b/system/stack/btm/neighbor_inquiry.h
@@ -217,7 +217,6 @@
typedef struct {
tBTM_STATUS status;
RawAddress bd_addr;
- uint16_t length;
BD_NAME remote_bd_name;
tHCI_STATUS hci_status;
} tBTM_REMOTE_DEV_NAME;
diff --git a/system/stack/btu/main_thread.cc b/system/stack/btu/main_thread.cc
index a2cdd7b..b53ffd3 100644
--- a/system/stack/btu/main_thread.cc
+++ b/system/stack/btu/main_thread.cc
@@ -36,6 +36,9 @@
static MessageLoopThread main_thread("bt_main_thread");
bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; }
+bluetooth::common::PostableContext* get_main() {
+ return main_thread.Postable();
+}
bt_status_t do_in_main_thread(const base::Location& from_here,
base::OnceClosure task) {
diff --git a/system/stack/fuzzers/l2cap_fuzzer.cc b/system/stack/fuzzers/l2cap_fuzzer.cc
index 3399282..c7c32860 100644
--- a/system/stack/fuzzers/l2cap_fuzzer.cc
+++ b/system/stack/fuzzers/l2cap_fuzzer.cc
@@ -34,7 +34,6 @@
#include "stack/include/l2cap_controller_interface.h"
#include "stack/include/l2cap_hci_link_interface.h"
#include "test/fake/fake_osi.h"
-#include "test/mock/mock_device_controller.h"
#include "test/mock/mock_main_shim_entry.h"
#include "test/mock/mock_stack_acl.h"
#include "test/mock/mock_stack_btm_devctl.h"
@@ -117,7 +116,8 @@
GetInterfaceToProfiles()->profileSpecific_HACK->GetHearingAidDeviceCount =
[]() { return 1; };
- test::mock::device_controller::ble_suggested_default_data_length = 512;
+ ON_CALL(controller_, GetLeSuggestedDefaultDataLength)
+ .WillByDefault(Return(512));
bluetooth::hci::LeBufferSize iso_size;
iso_size.le_data_packet_length_ = 512;
iso_size.total_num_le_packets_ = 6;
diff --git a/system/stack/gatt/att_protocol.cc b/system/stack/gatt/att_protocol.cc
index 23243bd..be95f6a 100644
--- a/system/stack/gatt/att_protocol.cc
+++ b/system/stack/gatt/att_protocol.cc
@@ -293,13 +293,13 @@
size_t pair_len;
size_t size_now = 1;
-#define CHECK_SIZE() \
- do { \
- if (size_now > payload_size) { \
- LOG_ERROR("payload size too small"); \
- osi_free(p_buf); \
- return nullptr; \
- } \
+#define CHECK_SIZE() \
+ do { \
+ if (size_now > payload_size) { \
+ log::error("payload size too small"); \
+ osi_free(p_buf); \
+ return nullptr; \
+ } \
} while (false)
BT_HDR* p_buf =
@@ -351,7 +351,7 @@
// backfill pair len field
if (op_code == GATT_RSP_READ_BY_TYPE) {
if (pair_len > UINT8_MAX) {
- LOG_ERROR("pair_len greater than %d", UINT8_MAX);
+ log::error("pair_len greater than {}", UINT8_MAX);
osi_free(p_buf);
return nullptr;
}
diff --git a/system/stack/gatt/gatt_api.cc b/system/stack/gatt/gatt_api.cc
index f6d59b9..887a17d 100644
--- a/system/stack/gatt/gatt_api.cc
+++ b/system/stack/gatt/gatt_api.cc
@@ -32,7 +32,6 @@
#include <string>
-#include "device/include/controller.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
#include "internal_include/stack_config.h"
@@ -46,7 +45,6 @@
#include "stack/gatt/connection_manager.h"
#include "stack/gatt/gatt_int.h"
#include "stack/include/bt_hdr.h"
-#include "stack/include/bt_types.h"
#include "stack/include/bt_uuid16.h"
#include "stack/include/l2cap_acl_interface.h"
#include "stack/include/sdp_api.h"
@@ -1398,7 +1396,8 @@
bool GATT_Connect(tGATT_IF gatt_if, const RawAddress& bd_addr,
tBTM_BLE_CONN_TYPE connection_type, tBT_TRANSPORT transport,
bool opportunistic) {
- uint8_t phy = controller_get_interface()->get_le_all_initiating_phys();
+ constexpr uint8_t kPhyLe1M = 0x01; // From the old controller shim.
+ uint8_t phy = kPhyLe1M;
return GATT_Connect(gatt_if, bd_addr, connection_type, transport,
opportunistic, phy);
}
diff --git a/system/stack/gatt/gatt_db.cc b/system/stack/gatt/gatt_db.cc
index 55ded60..6817690 100644
--- a/system/stack/gatt/gatt_db.cc
+++ b/system/stack/gatt/gatt_db.cc
@@ -24,7 +24,6 @@
#include <base/logging.h>
#include <bluetooth/log.h>
-#include <log/log.h>
#include <stdio.h>
#include <string.h>
diff --git a/system/stack/gatt/gatt_utils.cc b/system/stack/gatt/gatt_utils.cc
index b430eab..31f4294 100644
--- a/system/stack/gatt/gatt_utils.cc
+++ b/system/stack/gatt/gatt_utils.cc
@@ -35,6 +35,7 @@
#include "internal_include/bt_target.h"
#include "os/log.h"
#include "osi/include/allocator.h"
+#include "osi/include/properties.h"
#include "rust/src/connection/ffi/connection_shim.h"
#include "stack/btm/btm_sec.h"
#include "stack/eatt/eatt.h"
@@ -55,8 +56,8 @@
using namespace bluetooth;
using bluetooth::Uuid;
-using bluetooth::eatt::EattExtension;
using bluetooth::eatt::EattChannel;
+using bluetooth::eatt::EattExtension;
/* check if [x, y] and [a, b] have overlapping range */
#define GATT_VALIDATE_HANDLE_RANGE(x, y, a, b) ((y) >= (a) && (x) <= (b))
@@ -99,13 +100,22 @@
uint16_t gatt_get_local_mtu(void) {
/* Default ATT MTU must not be greater than GATT_MAX_MTU_SIZE, nor smaller
* than GATT_DEF_BLE_MTU_SIZE */
- const static uint16_t ATT_MTU_DEFAULT =
+ static const uint16_t ATT_MTU_DEFAULT =
std::max(std::min(bluetooth::common::init_flags::get_att_mtu_default(),
GATT_MAX_MTU_SIZE),
GATT_DEF_BLE_MTU_SIZE);
return ATT_MTU_DEFAULT;
}
+uint16_t gatt_get_max_phy_channel() {
+ static const uint16_t MAX_PHY_CHANNEL = std::min(
+ std::max(osi_property_get_int32(
+ "bluetooth.core.le.max_number_of_concurrent_connections", 0),
+ GATT_MAX_PHY_CHANNEL_FLOOR),
+ GATT_MAX_PHY_CHANNEL);
+ return MAX_PHY_CHANNEL;
+}
+
/*******************************************************************************
*
* Function gatt_free_pending_ind
@@ -280,7 +290,7 @@
bool found = false;
log::debug("start_idx={}", start_idx);
- for (i = start_idx; i < GATT_MAX_PHY_CHANNEL; i++) {
+ for (i = start_idx; i < gatt_get_max_phy_channel(); i++) {
if (gatt_cb.tcb[i].in_use && gatt_cb.tcb[i].ch_state == GATT_CH_OPEN) {
bda = gatt_cb.tcb[i].peer_bda;
*p_found_idx = i;
@@ -368,7 +378,7 @@
uint8_t i = 0;
bool connected = false;
- for (i = 0; i < GATT_MAX_PHY_CHANNEL; i++) {
+ for (i = 0; i < gatt_get_max_phy_channel(); i++) {
if (gatt_cb.tcb[i].in_use && gatt_cb.tcb[i].peer_bda == bda) {
connected = true;
break;
@@ -390,7 +400,7 @@
tBT_TRANSPORT transport) {
uint8_t i = 0;
- for (; i < GATT_MAX_PHY_CHANNEL; i++) {
+ for (; i < gatt_get_max_phy_channel(); i++) {
if (gatt_cb.tcb[i].peer_bda == bda &&
gatt_cb.tcb[i].transport == transport) {
return i;
@@ -411,7 +421,7 @@
tGATT_TCB* gatt_get_tcb_by_idx(uint8_t tcb_idx) {
tGATT_TCB* p_tcb = NULL;
- if ((tcb_idx < GATT_MAX_PHY_CHANNEL) && gatt_cb.tcb[tcb_idx].in_use)
+ if ((tcb_idx < gatt_get_max_phy_channel()) && gatt_cb.tcb[tcb_idx].in_use)
p_tcb = &gatt_cb.tcb[tcb_idx];
return p_tcb;
@@ -450,7 +460,7 @@
std::stringstream stream;
int in_use_cnt = 0;
- for (int i = 0; i < GATT_MAX_PHY_CHANNEL; i++) {
+ for (int i = 0; i < gatt_get_max_phy_channel(); i++) {
tGATT_TCB* p_tcb = &gatt_cb.tcb[i];
if (p_tcb->in_use) {
@@ -464,7 +474,7 @@
}
dprintf(fd, "TCB (GATT_MAX_PHY_CHANNEL: %d) in_use: %d\n%s\n",
- GATT_MAX_PHY_CHANNEL, in_use_cnt, stream.str().c_str());
+ gatt_get_max_phy_channel(), in_use_cnt, stream.str().c_str());
}
/*******************************************************************************
@@ -483,7 +493,7 @@
if (j != GATT_INDEX_INVALID) return &gatt_cb.tcb[j];
/* find free tcb */
- for (int i = 0; i < GATT_MAX_PHY_CHANNEL; i++) {
+ for (int i = 0; i < gatt_get_max_phy_channel(); i++) {
tGATT_TCB* p_tcb = &gatt_cb.tcb[i];
if (p_tcb->in_use) continue;
@@ -648,7 +658,8 @@
void gatt_start_conf_timer(tGATT_TCB* p_tcb, uint16_t cid) {
/* start notification cache timer */
if (p_tcb->eatt && cid != L2CAP_ATT_CID)
- EattExtension::GetInstance()->StartIndicationConfirmationTimer(p_tcb->peer_bda, cid);
+ EattExtension::GetInstance()->StartIndicationConfirmationTimer(
+ p_tcb->peer_bda, cid);
else
alarm_set_on_mloop(p_tcb->conf_timer, GATT_WAIT_FOR_RSP_TIMEOUT_MS,
gatt_indication_confirmation_timeout, p_tcb);
@@ -666,7 +677,8 @@
void gatt_stop_conf_timer(tGATT_TCB& tcb, uint16_t cid) {
/* start notification cache timer */
if (tcb.eatt && cid != L2CAP_ATT_CID)
- EattExtension::GetInstance()->StopIndicationConfirmationTimer(tcb.peer_bda, cid);
+ EattExtension::GetInstance()->StopIndicationConfirmationTimer(tcb.peer_bda,
+ cid);
else
alarm_cancel(tcb.conf_timer);
}
@@ -797,7 +809,7 @@
* Returns void
*
******************************************************************************/
-void gatt_ind_ack_timeout(void* data) {
+void gatt_ind_ack_timeout(void* data) {
tGATT_TCB* p_tcb = (tGATT_TCB*)data;
CHECK(p_tcb);
@@ -904,8 +916,7 @@
} else
status = GATT_INSUF_RESOURCE;
- if (deq)
- gatt_dequeue_sr_cmd(tcb, cid);
+ if (deq) gatt_dequeue_sr_cmd(tcb, cid);
return status;
}
@@ -1093,7 +1104,8 @@
uint16_t* cid_p) {
if (p_tcb->eatt && eatt_support) {
EattChannel* channel =
- EattExtension::GetInstance()->GetChannelAvailableForIndication(p_tcb->peer_bda);
+ EattExtension::GetInstance()->GetChannelAvailableForIndication(
+ p_tcb->peer_bda);
if (channel) {
*indicated_handle_p = &channel->indicate_handle_;
*cid_p = channel->cid_;
@@ -1153,7 +1165,8 @@
uint16_t gatt_tcb_get_att_cid(tGATT_TCB& tcb, bool eatt_support) {
if (eatt_support && tcb.eatt) {
EattChannel* channel =
- EattExtension::GetInstance()->GetChannelAvailableForClientRequest(tcb.peer_bda);
+ EattExtension::GetInstance()->GetChannelAvailableForClientRequest(
+ tcb.peer_bda);
if (channel) {
return channel->cid_;
}
@@ -1286,11 +1299,11 @@
uint16_t xx = 0;
tGATT_TCB* p_tcb = NULL;
- for (xx = 0; xx < GATT_MAX_PHY_CHANNEL; xx++) {
+ for (xx = 0; xx < gatt_get_max_phy_channel(); xx++) {
if (gatt_cb.tcb[xx].in_use &&
((gatt_cb.tcb[xx].att_lcid == lcid) ||
- ((EattExtension::GetInstance()->FindEattChannelByCid(gatt_cb.tcb[xx].peer_bda,
- lcid) != nullptr)))) {
+ ((EattExtension::GetInstance()->FindEattChannelByCid(
+ gatt_cb.tcb[xx].peer_bda, lcid) != nullptr)))) {
p_tcb = &gatt_cb.tcb[xx];
break;
}
@@ -1330,8 +1343,8 @@
if (!p_tcb->eatt) return nullptr;
- EattChannel* channel =
- EattExtension::GetInstance()->FindEattChannelByTransId(p_tcb->peer_bda, trans_id);
+ EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByTransId(
+ p_tcb->peer_bda, trans_id);
if (!channel) return nullptr;
return &channel->server_outstanding_cmd_;
@@ -1584,8 +1597,8 @@
if (p_clcb->cid == tcb.att_lcid) {
tcb.cl_cmd_q.push_back(cmd);
} else {
- EattChannel* channel =
- EattExtension::GetInstance()->FindEattChannelByCid(tcb.peer_bda, cmd.cid);
+ EattChannel* channel = EattExtension::GetInstance()->FindEattChannelByCid(
+ tcb.peer_bda, cmd.cid);
if (channel == nullptr) {
log::warn("{}, cid 0x{:02x} already disconnected",
ADDRESS_TO_LOGGABLE_CSTR(tcb.peer_bda), cmd.cid);
@@ -1837,7 +1850,7 @@
pseduo_op_code_idx = 0x15; /* just an index to op_code_name */
}
- #define ARR_SIZE(a) (sizeof(a)/sizeof(a[0]))
+#define ARR_SIZE(a) (sizeof(a) / sizeof(a[0]))
if (pseduo_op_code_idx < ARR_SIZE(op_code_name))
return op_code_name[pseduo_op_code_idx];
else
diff --git a/system/stack/hcic/hciblecmds.cc b/system/stack/hcic/hciblecmds.cc
index 37e307d..5d77a44 100644
--- a/system/stack/hcic/hciblecmds.cc
+++ b/system/stack/hcic/hciblecmds.cc
@@ -225,33 +225,6 @@
btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
}
-void btsnd_hcic_ble_upd_ll_conn_params(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) {
- 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_BLE_UPD_LL_CONN_PARAMS;
- p->offset = 0;
-
- UINT16_TO_STREAM(pp, HCI_BLE_UPD_LL_CONN_PARAMS);
- UINT8_TO_STREAM(pp, HCIC_PARAM_SIZE_BLE_UPD_LL_CONN_PARAMS);
-
- UINT16_TO_STREAM(pp, handle);
-
- UINT16_TO_STREAM(pp, conn_int_min);
- UINT16_TO_STREAM(pp, conn_int_max);
- UINT16_TO_STREAM(pp, conn_latency);
- UINT16_TO_STREAM(pp, conn_timeout);
- UINT16_TO_STREAM(pp, min_ce_len);
- UINT16_TO_STREAM(pp, max_ce_len);
-
- btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
-}
-
void btsnd_hcic_ble_read_remote_feat(uint16_t handle) {
BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE);
uint8_t* pp = (uint8_t*)(p + 1);
diff --git a/system/stack/hcic/hcicmds.cc b/system/stack/hcic/hcicmds.cc
index 21c819d..6ec0f62 100644
--- a/system/stack/hcic/hcicmds.cc
+++ b/system/stack/hcic/hcicmds.cc
@@ -317,8 +317,6 @@
/* Read Default Erroneous Data Reporting */
#define HCIC_PARAM_SIZE_R_ERR_DATA_RPT 0
-#define HCIC_PARAM_SIZE_ENHANCED_FLUSH 3
-
#define HCIC_PARAM_SIZE_SEND_KEYPRESS_NOTIF 7
#define HCI_SEND_KEYPRESS_NOTIF_BD_ADDR_OFF 0
@@ -1478,21 +1476,6 @@
/**** end of Simple Pairing Commands ****/
-void btsnd_hcic_enhanced_flush(uint16_t handle, uint8_t packet_type) {
- 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_ENHANCED_FLUSH;
- p->offset = 0;
- UINT16_TO_STREAM(pp, HCI_ENHANCED_FLUSH);
- UINT8_TO_STREAM(pp, HCIC_PARAM_SIZE_ENHANCED_FLUSH);
-
- UINT16_TO_STREAM(pp, handle);
- UINT8_TO_STREAM(pp, packet_type);
-
- btu_hcif_send_cmd(LOCAL_BR_EDR_CONTROLLER_ID, p);
-}
-
/*************************
* End of Lisbon Commands
*************************/
diff --git a/system/stack/include/acl_api.h b/system/stack/include/acl_api.h
index 34d2d50..0399765 100644
--- a/system/stack/include/acl_api.h
+++ b/system/stack/include/acl_api.h
@@ -17,7 +17,6 @@
#include <cstdint>
-#include "device/include/controller.h"
#include "stack/acl/acl.h"
#include "stack/btm/security_device_record.h"
#include "stack/include/btm_api_types.h"
@@ -45,7 +44,7 @@
void BTM_default_unblock_role_switch();
void BTM_default_block_role_switch();
-void BTM_acl_after_controller_started(const controller_t* controller);
+void BTM_acl_after_controller_started();
/*******************************************************************************
*
@@ -205,6 +204,10 @@
bool acl_peer_supports_ble_connection_parameters_request(
const RawAddress& remote_bda);
+void acl_ble_connection_parameters_request(
+ 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);
bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle);
bool acl_peer_supports_ble_2m_phy(uint16_t hci_handle);
@@ -292,6 +295,8 @@
void btm_acl_removed(uint16_t handle);
+void btm_acl_flush(uint16_t handle);
+
void acl_disconnect_from_handle(uint16_t handle, tHCI_STATUS reason,
std::string comment);
void acl_disconnect_after_role_switch(uint16_t conn_handle, tHCI_STATUS reason,
diff --git a/system/stack/include/bt_name.h b/system/stack/include/bt_name.h
index 40cdc0d..4a92224 100644
--- a/system/stack/include/bt_name.h
+++ b/system/stack/include/bt_name.h
@@ -16,19 +16,14 @@
#pragma once
-#ifdef __cplusplus
#include <cstdint>
#include <cstring>
-#else
-#include <stdint.h>
-#include <string.h>
-#endif
+
+#include "osi/include/compat.h" // strlcpy
#define BD_NAME_LEN 248
typedef uint8_t BD_NAME[BD_NAME_LEN + 1]; /* Device name */
-#ifdef __cplusplus
-#include "osi/include/compat.h" // strlcpy
inline constexpr BD_NAME kBtmBdNameEmpty = {};
constexpr size_t kBdNameLength = static_cast<size_t>(BD_NAME_LEN);
constexpr uint8_t kBdNameDelim = (uint8_t)NULL;
@@ -61,4 +56,3 @@
reinterpret_cast<void*>(const_cast<uint8_t*>(bd_name2)),
kBdNameLength + 1) == 0;
}
-#endif
diff --git a/system/stack/include/btm_ble_api_types.h b/system/stack/include/btm_ble_api_types.h
index d3519f0..c40fd6c4 100644
--- a/system/stack/include/btm_ble_api_types.h
+++ b/system/stack/include/btm_ble_api_types.h
@@ -20,6 +20,7 @@
#define BTM_BLE_API_TYPES_H
#include <base/functional/callback_forward.h>
+#include <bluetooth/log.h>
#include <hardware/bt_common_types.h>
#include <cstdint>
@@ -514,4 +515,9 @@
typedef void(tBTM_BLE_CTRL_FEATURES_CBACK)(tHCI_STATUS status);
+namespace fmt {
+template <>
+struct formatter<tBTM_BLE_CONN_TYPE> : enum_formatter<tBTM_BLE_CONN_TYPE> {};
+} // namespace fmt
+
#endif // BTM_BLE_API_TYPES_H
diff --git a/system/stack/include/btm_sec_api.h b/system/stack/include/btm_sec_api.h
index cf588e4..5b997f9 100644
--- a/system/stack/include/btm_sec_api.h
+++ b/system/stack/include/btm_sec_api.h
@@ -38,15 +38,13 @@
* Description Add/modify device. This function will be normally called
* during host startup to restore all required information
* stored in the NVRAM.
- * dev_class, bd_name, link_key, and features are NULL if
- * unknown
+ * dev_class, link_key are NULL if unknown
*
- * Returns true if added OK, else false
+ * Returns void
*
******************************************************************************/
-bool BTM_SecAddDevice(const RawAddress& bd_addr, const DEV_CLASS dev_class,
- const BD_NAME& bd_name, uint8_t* features,
- LinkKey* link_key, uint8_t key_type, uint8_t pin_length);
+void BTM_SecAddDevice(const RawAddress& bd_addr, const DEV_CLASS dev_class,
+ LinkKey link_key, uint8_t key_type, uint8_t pin_length);
/** Free resources associated with the device associated with |bd_addr| address.
*
diff --git a/system/stack/include/hcimsgs.h b/system/stack/include/hcimsgs.h
index 8713ccc..54049f7 100644
--- a/system/stack/include/hcimsgs.h
+++ b/system/stack/include/hcimsgs.h
@@ -201,8 +201,6 @@
/* Read Default Erroneous Data Reporting */
void btsnd_hcic_read_default_erroneous_data_rpt(void);
-void btsnd_hcic_enhanced_flush(uint16_t handle, uint8_t packet_type);
-
/**** end of Simple Pairing Commands ****/
extern void btsnd_hcic_set_event_filter(uint8_t filt_type,
@@ -329,12 +327,6 @@
void btsnd_hcic_ble_read_acceptlist_size(void);
-void btsnd_hcic_ble_upd_ll_conn_params(uint16_t handle, uint16_t conn_int_min,
- uint16_t conn_int_max,
- uint16_t conn_latency,
- uint16_t conn_timeout, uint16_t min_len,
- uint16_t max_len);
-
void btsnd_hcic_ble_read_remote_feat(uint16_t handle);
void btsnd_hcic_ble_rand(base::Callback<void(BT_OCTET8)> cb);
diff --git a/system/stack/include/main_thread.h b/system/stack/include/main_thread.h
index 5c3b124..b8725d2 100644
--- a/system/stack/include/main_thread.h
+++ b/system/stack/include/main_thread.h
@@ -21,12 +21,14 @@
#include <base/threading/thread.h>
#include "common/message_loop_thread.h"
+#include "common/postable_context.h"
#include "include/hardware/bluetooth.h"
using BtMainClosure = std::function<void()>;
-using bluetooth::common::MessageLoopThread;
bluetooth::common::MessageLoopThread* get_main_thread();
+bluetooth::common::PostableContext* get_main();
+
bt_status_t do_in_main_thread(const base::Location& from_here,
base::OnceClosure task);
bt_status_t do_in_main_thread_delayed(const base::Location& from_here,
diff --git a/system/stack/include/security_client_callbacks.h b/system/stack/include/security_client_callbacks.h
index 5fb4130..d082332 100644
--- a/system/stack/include/security_client_callbacks.h
+++ b/system/stack/include/security_client_callbacks.h
@@ -97,9 +97,8 @@
void (*BTM_BleLoadLocalKeys)(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key);
// Update/Query in-memory device records
- bool (*BTM_SecAddDevice)(const RawAddress& bd_addr, const DEV_CLASS dev_class,
- const BD_NAME& bd_name, uint8_t* features,
- LinkKey* link_key, uint8_t key_type,
+ void (*BTM_SecAddDevice)(const RawAddress& bd_addr, const DEV_CLASS dev_class,
+ LinkKey link_key, uint8_t key_type,
uint8_t pin_length);
void (*BTM_SecAddBleDevice)(const RawAddress& bd_addr,
tBT_DEVICE_TYPE dev_type,
diff --git a/system/stack/l2cap/l2c_api.cc b/system/stack/l2cap/l2c_api.cc
index 946d8f8..b3708e2 100644
--- a/system/stack/l2cap/l2c_api.cc
+++ b/system/stack/l2cap/l2c_api.cc
@@ -45,7 +45,6 @@
#include "os/log.h"
#include "os/system_properties.h"
#include "osi/include/allocator.h"
-#include "stack/btm/btm_sec.h"
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_psm_types.h"
#include "stack/include/btm_api.h"
@@ -57,9 +56,6 @@
using namespace bluetooth;
-void btsnd_hcic_enhanced_flush(uint16_t handle,
- uint8_t packet_type); // TODO Remove
-
using base::StringPrintf;
extern fixed_queue_t* btu_general_alarm_queue;
@@ -1586,7 +1582,7 @@
if (bluetooth::shim::GetController()->SupportsNonFlushablePb() &&
(BTM_GetNumScoLinks() == 0)) {
/* The only packet type defined - 0 - Automatically-Flushable Only */
- btsnd_hcic_enhanced_flush(p_lcb->Handle(), 0);
+ l2c_acl_flush(p_lcb->Handle());
}
}
diff --git a/system/stack/l2cap/l2c_ble.cc b/system/stack/l2cap/l2c_ble.cc
index 3095958..3187f39 100644
--- a/system/stack/l2cap/l2c_ble.cc
+++ b/system/stack/l2cap/l2c_ble.cc
@@ -27,7 +27,6 @@
#include <base/logging.h>
#include <base/strings/stringprintf.h>
#include <bluetooth/log.h>
-#include <log/log.h>
#ifdef __ANDROID__
#include <android/sysprop/BluetoothProperties.sysprop.h>
@@ -35,17 +34,12 @@
#include "btif/include/core_callbacks.h"
#include "btif/include/stack_manager_t.h"
-#include "device/include/controller.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
-#include "internal_include/stack_config.h"
-#include "main/shim/acl_api.h"
#include "main/shim/entry.h"
-#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/properties.h"
#include "stack/btm/btm_ble_sec.h"
-#include "stack/btm/btm_dev.h"
#include "stack/btm/btm_int_types.h"
#include "stack/btm/btm_sec.h"
#include "stack/btm/btm_sec_int_types.h"
diff --git a/system/stack/l2cap/l2c_ble_conn_params.cc b/system/stack/l2cap/l2c_ble_conn_params.cc
index 8cd618d..97b7744 100644
--- a/system/stack/l2cap/l2c_ble_conn_params.cc
+++ b/system/stack/l2cap/l2c_ble_conn_params.cc
@@ -27,7 +27,6 @@
#include <base/logging.h>
#include <bluetooth/log.h>
-#include <log/log.h>
#include "hci/controller_interface.h"
#include "internal_include/stack_config.h"
@@ -245,9 +244,9 @@
->SupportsBleConnectionParametersRequest() &&
acl_peer_supports_ble_connection_parameters_request(
p_lcb->remote_bd_addr))) {
- btsnd_hcic_ble_upd_ll_conn_params(p_lcb->Handle(), min_conn_int,
- max_conn_int, peripheral_latency,
- supervision_tout, 0, 0);
+ acl_ble_connection_parameters_request(p_lcb->Handle(), min_conn_int,
+ max_conn_int, peripheral_latency,
+ supervision_tout, 0, 0);
p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING;
} else {
l2cu_send_peer_ble_par_req(p_lcb, min_conn_int, max_conn_int,
@@ -265,10 +264,10 @@
->SupportsBleConnectionParametersRequest() &&
acl_peer_supports_ble_connection_parameters_request(
p_lcb->remote_bd_addr))) {
- btsnd_hcic_ble_upd_ll_conn_params(p_lcb->Handle(), p_lcb->min_interval,
- p_lcb->max_interval, p_lcb->latency,
- p_lcb->timeout, p_lcb->min_ce_len,
- p_lcb->max_ce_len);
+ acl_ble_connection_parameters_request(
+ p_lcb->Handle(), p_lcb->min_interval, p_lcb->max_interval,
+ p_lcb->latency, p_lcb->timeout, p_lcb->min_ce_len,
+ p_lcb->max_ce_len);
p_lcb->conn_update_mask |= L2C_BLE_UPDATE_PENDING;
} else {
l2cu_send_peer_ble_par_req(p_lcb, p_lcb->min_interval,
@@ -385,7 +384,7 @@
p_lcb->timeout = p_dev_rec->conn_params.supervision_tout;
p_lcb->latency = p_dev_rec->conn_params.peripheral_latency;
- btsnd_hcic_ble_upd_ll_conn_params(
+ acl_ble_connection_parameters_request(
p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int,
p_dev_rec->conn_params.max_conn_int,
p_dev_rec->conn_params.peripheral_latency,
diff --git a/system/stack/l2cap/l2c_int.h b/system/stack/l2cap/l2c_int.h
index 6221ff1..77c97dd 100644
--- a/system/stack/l2cap/l2c_int.h
+++ b/system/stack/l2cap/l2c_int.h
@@ -702,6 +702,7 @@
void l2c_lcb_timer_timeout(void* data);
void l2c_fcrb_ack_timer_timeout(void* data);
uint8_t l2c_data_write(uint16_t cid, BT_HDR* p_data, uint16_t flag);
+void l2c_acl_flush(uint16_t handle);
tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding,
tBT_TRANSPORT transport);
diff --git a/system/stack/l2cap/l2c_utils.cc b/system/stack/l2cap/l2c_utils.cc
index fd881c0..f3db854 100644
--- a/system/stack/l2cap/l2c_utils.cc
+++ b/system/stack/l2cap/l2c_utils.cc
@@ -28,7 +28,6 @@
#include <stdio.h>
#include <string.h>
-#include "device/include/controller.h"
#include "hal/snoop_logger.h"
#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
@@ -90,7 +89,7 @@
}
p_lcb->transport = transport;
p_lcb->tx_data_len =
- controller_get_interface()->get_ble_default_data_packet_length();
+ bluetooth::shim::GetController()->GetLeSuggestedDefaultDataLength();
p_lcb->le_sec_pending_q = fixed_queue_new(SIZE_MAX);
if (transport == BT_TRANSPORT_LE) {
@@ -2373,7 +2372,9 @@
(reset_after_rs && p_lcb->acl_priority == L2CAP_PRIORITY_HIGH)) {
#ifndef TARGET_FLOSS
/* Use vendor specific commands to set the link priority */
- switch (controller_get_interface()->get_bt_version()->manufacturer) {
+ switch (bluetooth::shim::GetController()
+ ->GetLocalVersionInformation()
+ .manufacturer_name_) {
case LMP_COMPID_BROADCOM:
l2cu_set_acl_priority_latency_brcm(p_lcb, priority);
break;
@@ -2504,7 +2505,9 @@
/* only change controller's latency when stream using latency mode */
if (p_lcb->use_latency_mode && p_lcb->is_high_priority() &&
latency != p_lcb->acl_latency) {
- switch (controller_get_interface()->get_bt_version()->manufacturer) {
+ switch (bluetooth::shim::GetController()
+ ->GetLocalVersionInformation()
+ .manufacturer_name_) {
case LMP_COMPID_BROADCOM:
l2cu_set_acl_latency_brcm(p_lcb, latency);
break;
@@ -3590,3 +3593,12 @@
return L2CAP_CONN_OTHER_ERROR;
}
}
+
+/*******************************************************************************
+ *
+ * Function l2c_acl_flush
+ *
+ * Description API functions call this function to flush data.
+ *
+ ******************************************************************************/
+void l2c_acl_flush(uint16_t handle) { btm_acl_flush(handle); }
\ No newline at end of file
diff --git a/system/stack/mmc/BUILD.gn b/system/stack/mmc/BUILD.gn
index 8111db7..2aa3a31 100644
--- a/system/stack/mmc/BUILD.gn
+++ b/system/stack/mmc/BUILD.gn
@@ -82,7 +82,10 @@
}
source_set("libmmc") {
- configs += [ ":target_defaults" ]
+ configs += [
+ ":target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
sources = [
"daemon/service.cc",
]
@@ -97,8 +100,17 @@
}
executable("mmc_service") {
- configs += [ ":target_defaults" ]
- deps = [ ":libmmc" ]
+ configs += [
+ ":target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
+ deps = [
+ ":libmmc",
+ "//bt/system/log:libbluetooth_log",
+ ]
+ libs = [
+ "fmt",
+ ]
sources = [ "main.cc" ]
}
@@ -117,10 +129,15 @@
]
configs += [
":target_defaults",
+ "//bt/system/log:log_defaults",
"//bt/system:external_gtest_main",
]
+ libs = [
+ "fmt",
+ ]
deps = [
"//bt/system/stack/mmc/proto:mmc_config_proto",
+ "//bt/system/log:libbluetooth_log",
"//bt/system/common",
"//bt/system/osi",
"//bt/system/types",
@@ -141,10 +158,15 @@
]
configs += [
":target_defaults",
+ "//bt/system/log:log_defaults",
"//bt/system:external_gtest_main",
]
+ libs = [
+ "fmt",
+ ]
deps = [
"//bt/system/stack/mmc/proto:mmc_config_proto",
+ "//bt/system/log:libbluetooth_log",
"//bt/system/common",
"//bt/system/osi",
"//bt/system/types",
diff --git a/system/stack/mmc/codec_client/BUILD.gn b/system/stack/mmc/codec_client/BUILD.gn
index 6fe2df8..ae02259 100644
--- a/system/stack/mmc/codec_client/BUILD.gn
+++ b/system/stack/mmc/codec_client/BUILD.gn
@@ -15,7 +15,11 @@
#
source_set("libcodec_client"){
- configs += [ "//bt/system/stack/mmc:target_defaults" ]
+ configs += [
+ "//bt/system/stack/mmc:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
+
sources = [
"codec_client.cc",
]
diff --git a/system/stack/mmc/codec_client/codec_client.cc b/system/stack/mmc/codec_client/codec_client.cc
index 648b2d4..7ff627e 100644
--- a/system/stack/mmc/codec_client/codec_client.cc
+++ b/system/stack/mmc/codec_client/codec_client.cc
@@ -18,6 +18,7 @@
#include <base/logging.h>
#include <base/timer/elapsed_timer.h>
+#include <bluetooth/log.h>
#include <dbus/bus.h>
#include <dbus/message.h>
#include <dbus/object_proxy.h>
@@ -37,6 +38,8 @@
namespace mmc {
namespace {
+using namespace bluetooth;
+
// Codec param field number in |ConfigParam|
const int kUnsupportedType = -1;
const int kHfpLc3EncoderId = 1;
@@ -53,7 +56,7 @@
} else if (config.has_a2dp_aac_encoder_param()) {
return kA2dpAacEncoderId;
} else {
- LOG(WARNING) << "Unsupported codec type is used.";
+ log::warn("Unsupported codec type is used.");
return kUnsupportedType;
}
}
@@ -70,7 +73,7 @@
bus_ = new dbus::Bus(options);
if (!bus_->Connect()) {
- LOG(ERROR) << "Failed to connect system bus";
+ log::error("Failed to connect system bus");
return;
}
@@ -78,7 +81,7 @@
codec_manager_ = bus_->GetObjectProxy(mmc::kMmcServiceName,
dbus::ObjectPath(mmc::kMmcServicePath));
if (!codec_manager_) {
- LOG(ERROR) << "Failed to get object proxy";
+ log::error("Failed to get object proxy");
return;
}
}
@@ -101,7 +104,7 @@
mmc::CodecInitRequest request;
*request.mutable_config() = config;
if (!writer.AppendProtoAsArrayOfBytes(request)) {
- LOG(ERROR) << "Failed to encode CodecInitRequest protobuf";
+ log::error("Failed to encode CodecInitRequest protobuf");
return -EINVAL;
}
@@ -116,31 +119,31 @@
;
if (!dbus_response) {
- LOG(ERROR) << "CodecInit failed";
+ log::error("CodecInit failed");
return -ECOMM;
}
dbus::MessageReader reader(dbus_response.get());
mmc::CodecInitResponse response;
if (!reader.PopArrayOfBytesAsProto(&response)) {
- LOG(ERROR) << "Failed to parse response protobuf";
+ log::error("Failed to parse response protobuf");
return -EINVAL;
}
if (response.socket_token().empty()) {
- LOG(ERROR) << "CodecInit returned empty socket token";
+ log::error("CodecInit returned empty socket token");
return -EBADMSG;
}
if (response.input_frame_size() < 0) {
- LOG(ERROR) << "CodecInit returned negative frame size";
+ log::error("CodecInit returned negative frame size");
return -EBADMSG;
}
// Create socket.
skt_fd_ = socket(AF_UNIX, SOCK_SEQPACKET, 0);
if (skt_fd_ < 0) {
- LOG(ERROR) << "Failed to create socket: " << strerror(errno);
+ log::error("Failed to create socket: {}", strerror(errno));
return -errno;
}
@@ -153,7 +156,7 @@
int rc =
connect(skt_fd_, (struct sockaddr*)&addr, sizeof(struct sockaddr_un));
if (rc < 0) {
- LOG(ERROR) << "Failed to connect socket: " << strerror(errno);
+ log::error("Failed to connect socket: {}", strerror(errno));
return -errno;
}
unlink(addr.sun_path);
@@ -186,7 +189,7 @@
;
if (!dbus_response) {
- LOG(WARNING) << "CodecCleanUp failed";
+ log::warn("CodecCleanUp failed");
}
return;
}
@@ -198,12 +201,12 @@
// i_buf and o_buf cannot be null.
if (i_buf == nullptr || o_buf == nullptr) {
- LOG(ERROR) << "Buffer is null";
+ log::error("Buffer is null");
return -EINVAL;
}
if (i_len <= 0 || o_len <= 0) {
- LOG(ERROR) << "Non-positive buffer length";
+ log::error("Non-positive buffer length");
return -EINVAL;
}
@@ -211,12 +214,12 @@
int rc = send(skt_fd_, i_buf, i_len, MSG_NOSIGNAL);
if (rc < 0) {
- LOG(ERROR) << "Failed to send data: " << strerror(errno);
+ log::error("Failed to send data: {}", strerror(errno));
return -errno;
}
// Full packet should be sent under SOCK_SEQPACKET setting.
if (rc < i_len) {
- LOG(ERROR) << "Failed to send full packet";
+ log::error("Failed to send full packet");
return -EIO;
}
@@ -226,24 +229,24 @@
int pollret = poll(&pfd, 1, -1);
if (pollret < 0) {
- LOG(ERROR) << "Failed to poll: " << strerror(errno);
+ log::error("Failed to poll: {}", strerror(errno));
return -errno;
}
if (pfd.revents & (POLLHUP | POLLNVAL)) {
- LOG(ERROR) << "Socket closed remotely.";
+ log::error("Socket closed remotely.");
return -EIO;
}
// POLLIN is returned..
rc = recv(skt_fd_, o_buf, o_len, MSG_NOSIGNAL);
if (rc < 0) {
- LOG(ERROR) << "Failed to recv data: " << strerror(errno);
+ log::error("Failed to recv data: {}", strerror(errno));
return -errno;
}
// Should be able to recv data when POLLIN is returned.
if (rc == 0) {
- LOG(ERROR) << "Failed to recv data";
+ log::error("Failed to recv data");
return -EIO;
}
diff --git a/system/stack/mmc/codec_server/BUILD.gn b/system/stack/mmc/codec_server/BUILD.gn
index 5adfac9..a8f6b14 100644
--- a/system/stack/mmc/codec_server/BUILD.gn
+++ b/system/stack/mmc/codec_server/BUILD.gn
@@ -39,7 +39,10 @@
}
source_set("libcodec_server_hfp_lc3"){
- configs += [ "//bt/system/stack/mmc:target_defaults" ]
+ configs += [
+ "//bt/system/stack/mmc:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
include_dirs = [
"//bt/system",
"//bt/system/include",
diff --git a/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc b/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc
index 612aa9f..7af13ef 100644
--- a/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc
+++ b/system/stack/mmc/codec_server/a2dp_aac_mmc_encoder.cc
@@ -25,6 +25,7 @@
}
#include <base/logging.h>
+#include <bluetooth/log.h>
#include "a2dp_aac.h"
#include "mmc/proto/mmc_config.pb.h"
@@ -32,6 +33,8 @@
namespace mmc {
namespace {
+using namespace bluetooth;
+
const int A2DP_AAC_HEADER_LEN = 9;
const int A2DP_AAC_MAX_LEN_REPR = 4;
const int A2DP_AAC_MAX_PREFIX_SIZE =
@@ -51,20 +54,20 @@
int A2dpAacEncoder::init(ConfigParam config) {
if (!config.has_a2dp_aac_encoder_param()) {
- LOG(ERROR) << "A2DP AAC Encoder params are not set";
+ log::error("A2DP AAC Encoder params are not set");
return -EINVAL;
}
const AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_AAC);
if (!codec) {
- LOG(ERROR) << "Codec not found";
+ log::error("Codec not found");
return -ENOENT;
}
if (!avctx_) {
avctx_ = avcodec_alloc_context3(codec);
if (!avctx_) {
- LOG(ERROR) << "Cannot allocate context";
+ log::error("Cannot allocate context");
return -EINVAL;
}
}
@@ -81,12 +84,12 @@
AVChannelLayout stereo = AV_CHANNEL_LAYOUT_STEREO;
av_channel_layout_copy(&avctx_->ch_layout, &stereo);
} else {
- LOG(ERROR) << "Invalid number of channels: " << channel_count;
+ log::error("Invalid number of channels: {}", channel_count);
return -EINVAL;
}
if (sample_rate != 44100 && sample_rate != 48000) {
- LOG(ERROR) << "Unsupported sample rate: " << sample_rate;
+ log::error("Unsupported sample rate: {}", sample_rate);
return -EINVAL;
}
@@ -97,7 +100,7 @@
int rc = avcodec_open2(avctx_, codec, NULL);
if (rc < 0) {
- LOG(ERROR) << "Could not open context: " << rc;
+ log::error("Could not open context: {}", rc);
return -EINVAL;
}
@@ -117,7 +120,7 @@
AVFrame* frame = av_frame_alloc();
if (!frame) {
- LOG(ERROR) << "Could not alloc frame";
+ log::error("Could not alloc frame");
return -ENOMEM;
}
@@ -127,21 +130,21 @@
rc = av_channel_layout_copy(&frame->ch_layout, &avctx_->ch_layout);
if (rc < 0) {
- LOG(ERROR) << "Failed to copy channel layout: " << rc;
+ log::error("Failed to copy channel layout: {}", rc);
av_frame_free(&frame);
return -EINVAL;
}
rc = av_frame_get_buffer(frame, 0);
if (rc < 0) {
- LOG(ERROR) << "Failed to get buffer for frame: " << rc;
+ log::error("Failed to get buffer for frame: {}", rc);
av_frame_free(&frame);
return -EIO;
}
rc = av_frame_make_writable(frame);
if (rc < 0) {
- LOG(ERROR) << "Failed to make frame writable: " << rc;
+ log::error("Failed to make frame writable: {}", rc);
av_frame_free(&frame);
return -EIO;
}
@@ -182,13 +185,13 @@
AVPacket* pkt = av_packet_alloc();
if (!pkt) {
- LOG(ERROR) << "Could not alloc packet";
+ log::error("Could not alloc packet");
return -ENOMEM;
}
rc = avcodec_send_frame(avctx_, frame);
if (rc < 0) {
- LOG(ERROR) << "Failed to send frame: " << rc;
+ log::error("Failed to send frame: {}", rc);
av_frame_free(&frame);
av_packet_free(&pkt);
return -EIO;
@@ -196,7 +199,7 @@
rc = avcodec_receive_packet(avctx_, pkt);
if (rc < 0 && rc != -EAGAIN) {
- LOG(ERROR) << "Failed to receive packet: " << rc;
+ log::error("Failed to receive packet: {}", rc);
av_frame_free(&frame);
av_packet_free(&pkt);
return -EIO;
@@ -215,7 +218,7 @@
int cap = param_.effective_frame_size();
if (rc == -EAGAIN || cap < pkt->size + A2DP_AAC_MAX_PREFIX_SIZE) {
if (rc != -EAGAIN) {
- LOG(WARNING) << "Dropped pkt: size=" << pkt->size << ", cap=" << cap;
+ log::warn("Dropped pkt: size={}, cap={}", pkt->size, cap);
}
static uint8_t silent_frame[7] = {
0x06, 0x21, 0x10, 0x04, 0x60, 0x8c, 0x1c,
diff --git a/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc b/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc
index d684594..add1d7b 100644
--- a/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc
+++ b/system/stack/mmc/codec_server/hfp_lc3_mmc_decoder.cc
@@ -17,6 +17,7 @@
#include "mmc/codec_server/hfp_lc3_mmc_decoder.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include "mmc/codec_server/lc3_utils.h"
@@ -25,6 +26,8 @@
namespace mmc {
+using namespace bluetooth;
+
HfpLc3Decoder::HfpLc3Decoder() : hfp_lc3_decoder_mem_(nullptr) {}
HfpLc3Decoder::~HfpLc3Decoder() { cleanup(); }
@@ -33,7 +36,7 @@
cleanup();
if (!config.has_hfp_lc3_decoder_param()) {
- LOG(ERROR) << "HFP LC3 decoder params are not set";
+ log::error("HFP LC3 decoder params are not set");
return -EINVAL;
}
@@ -49,7 +52,7 @@
lc3_setup_decoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_decoder_mem_);
if (hfp_lc3_decoder_ == nullptr) {
- LOG(ERROR) << "Wrong parameters provided";
+ log::error("Wrong parameters provided");
return -EINVAL;
}
@@ -59,14 +62,14 @@
void HfpLc3Decoder::cleanup() {
if (hfp_lc3_decoder_mem_) {
osi_free_and_reset((void**)&hfp_lc3_decoder_mem_);
- LOG(INFO) << "Released the decoder instance";
+ log::info("Released the decoder instance");
}
}
int HfpLc3Decoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf,
int o_len) {
if (o_buf == nullptr || o_len < HFP_LC3_PCM_BYTES + 1) {
- LOG(ERROR) << "Output buffer size is less than LC3 frame size";
+ log::error("Output buffer size is less than LC3 frame size");
return -EINVAL;
}
@@ -82,7 +85,7 @@
MapLc3PcmFmt(param_.fmt()), out_frame, param_.stride());
if (rc != 0 && rc != 1) {
- LOG(WARNING) << "Wrong decode parameters";
+ log::warn("Wrong decode parameters");
std::fill(o_buf, o_buf + o_len, 0);
} else
o_buf[0] = rc;
diff --git a/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc b/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc
index cbdc728..c695f99 100644
--- a/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc
+++ b/system/stack/mmc/codec_server/hfp_lc3_mmc_encoder.cc
@@ -17,6 +17,7 @@
#include "mmc/codec_server/hfp_lc3_mmc_encoder.h"
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include <algorithm>
@@ -27,6 +28,8 @@
namespace mmc {
+using namespace bluetooth;
+
HfpLc3Encoder::HfpLc3Encoder() : hfp_lc3_encoder_mem_(nullptr) {}
HfpLc3Encoder::~HfpLc3Encoder() { cleanup(); }
@@ -35,7 +38,7 @@
cleanup();
if (!config.has_hfp_lc3_encoder_param()) {
- LOG(ERROR) << "HFP LC3 encoder params are not set";
+ log::error("HFP LC3 encoder params are not set");
return -EINVAL;
}
@@ -51,7 +54,7 @@
lc3_setup_encoder(dt_us, sr_hz, sr_pcm_hz, hfp_lc3_encoder_mem_);
if (hfp_lc3_encoder_ == nullptr) {
- LOG(ERROR) << "Wrong parameters provided";
+ log::error("Wrong parameters provided");
return -EINVAL;
}
@@ -61,14 +64,14 @@
void HfpLc3Encoder::cleanup() {
if (hfp_lc3_encoder_mem_) {
osi_free_and_reset((void**)&hfp_lc3_encoder_mem_);
- LOG(INFO) << "Released the encoder instance";
+ log::info("Released the encoder instance");
}
}
int HfpLc3Encoder::transcode(uint8_t* i_buf, int i_len, uint8_t* o_buf,
int o_len) {
if (i_buf == nullptr || o_buf == nullptr) {
- LOG(ERROR) << "Buffer is null";
+ log::error("Buffer is null");
return -EINVAL;
}
@@ -77,7 +80,7 @@
param_.stride(), HFP_LC3_PKT_FRAME_LEN, o_buf);
if (rc != 0) {
- LOG(WARNING) << "Wrong encode parameters";
+ log::warn("Wrong encode parameters");
std::fill(o_buf, o_buf + o_len, 0);
}
diff --git a/system/stack/mmc/codec_server/lc3_utils.h b/system/stack/mmc/codec_server/lc3_utils.h
index 1cba2ef..18551b4 100644
--- a/system/stack/mmc/codec_server/lc3_utils.h
+++ b/system/stack/mmc/codec_server/lc3_utils.h
@@ -18,6 +18,7 @@
#define MMC_CODEC_SERVER_LC3_UTILS_H_
#include <base/logging.h>
+#include <bluetooth/log.h>
#include <lc3.h>
#include "mmc/proto/mmc_config.pb.h"
@@ -37,8 +38,8 @@
case Lc3Param::kLc3PcmFormatS24:
return LC3_PCM_FORMAT_S24;
default:
- LOG(INFO)
- << "No corresponding LC3 PCM format, return `LC3_PCM_FORMAT_S16`.";
+ bluetooth::log::info(
+ "No corresponding LC3 PCM format, return `LC3_PCM_FORMAT_S16`.");
return LC3_PCM_FORMAT_S16;
}
}
diff --git a/system/stack/mmc/daemon/service.cc b/system/stack/mmc/daemon/service.cc
index 31ba2e1..ac84d37 100644
--- a/system/stack/mmc/daemon/service.cc
+++ b/system/stack/mmc/daemon/service.cc
@@ -22,6 +22,7 @@
#include <base/stl_util.h>
#include <base/task/single_thread_task_runner.h>
#include <base/unguessable_token.h>
+#include <bluetooth/log.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -45,6 +46,9 @@
namespace mmc {
namespace {
+
+using namespace bluetooth;
+
// Task that would run on the thread.
void StartSocketListener(int fd, struct sockaddr_un addr,
std::promise<void> task_ended,
@@ -55,7 +59,7 @@
close(fd);
if (client_fd < 0) {
- LOG(ERROR) << "Failed to accept: " << strerror(errno);
+ log::error("Failed to accept: {}", strerror(errno));
codec_server.release();
task_ended.set_value();
return;
@@ -72,20 +76,20 @@
// Blocking poll.
int poll_ret = poll(&pfd, 1, -1);
if (poll_ret <= 0) {
- LOG(ERROR) << "Poll failed: " << strerror(errno);
+ log::error("Poll failed: {}", strerror(errno));
break;
}
// Ignore remaining data in the closed socket.
if (pfd.revents & (POLLHUP | POLLNVAL)) {
- LOG(INFO) << "Socket disconnected";
+ log::info("Socket disconnected");
break;
}
int i_data_len =
recv(client_fd, i_buf.data(), kMaximumBufferSize, MSG_NOSIGNAL);
if (i_data_len <= 0) {
- LOG(ERROR) << "Failed to recv data: " << strerror(errno);
+ log::error("Failed to recv data: {}", strerror(errno));
break;
}
@@ -93,13 +97,13 @@
int o_data_len = codec_server->transcode(i_buf.data(), i_data_len,
o_buf.data(), kMaximumBufferSize);
if (o_data_len < 0) {
- LOG(ERROR) << "Failed to transcode: " << strerror(-o_data_len);
+ log::error("Failed to transcode: {}", strerror(-o_data_len));
break;
}
int sent_rc = send(client_fd, o_buf.data(), o_data_len, MSG_NOSIGNAL);
if (sent_rc <= 0) {
- LOG(ERROR) << "Failed to send data: " << strerror(errno);
+ log::error("Failed to send data: {}", strerror(errno));
break;
}
o_buf.fill(0);
@@ -124,13 +128,13 @@
bus_ = new dbus::Bus(std::move(opts));
if (!bus_->Connect()) {
- LOG(ERROR) << "Failed to connect to system bus";
+ log::error("Failed to connect to system bus");
return false;
}
exported_object_ = bus_->GetExportedObject(dbus::ObjectPath(kMmcServicePath));
if (!exported_object_) {
- LOG(ERROR) << "Failed to export " << kMmcServicePath << " object";
+ log::error("Failed to export {} object", kMmcServicePath);
return false;
}
@@ -146,14 +150,14 @@
kMmcServiceInterface, iter.first,
base::BindRepeating(iter.second, weak_ptr_factory_.GetWeakPtr()));
if (!ret) {
- LOG(ERROR) << "Failed to export method: " << iter.first;
+ log::error("Failed to export method: {}", iter.first);
return false;
}
}
if (!bus_->RequestOwnershipAndBlock(kMmcServiceName,
dbus::Bus::REQUIRE_PRIMARY)) {
- LOG(ERROR) << "Failed to take ownership of " << kMmcServiceName;
+ log::error("Failed to take ownership of {}", kMmcServiceName);
return false;
}
return true;
@@ -282,21 +286,21 @@
// Start up thread and assign task to it.
thread_pool_.back().first->StartUp();
if (!thread_pool_.back().first->IsRunning()) {
- LOG(ERROR) << "Failed to start thread";
+ log::error("Failed to start thread");
return false;
}
// Real-time scheduling increases thread priority.
// Without it, the thread still works.
if (!thread_pool_.back().first->EnableRealTimeScheduling()) {
- LOG(WARNING) << "Failed to enable real time scheduling";
+ log::warn("Failed to enable real time scheduling");
}
if (!thread_pool_.back().first->DoInThread(
FROM_HERE,
base::BindOnce(&StartSocketListener, fd, std::move(addr),
std::move(task_ended), std::move(codec_server)))) {
- LOG(ERROR) << "Failed to run task";
+ log::error("Failed to run task");
return false;
}
diff --git a/system/stack/mmc/main.cc b/system/stack/mmc/main.cc
index e040ebefa..8294b5a 100644
--- a/system/stack/mmc/main.cc
+++ b/system/stack/mmc/main.cc
@@ -21,6 +21,7 @@
#include <base/run_loop.h>
#include <base/strings/stringprintf.h>
#include <base/task/single_thread_task_executor.h>
+#include <bluetooth/log.h>
#include <sys/syslog.h>
#include "mmc/daemon/service.h"
@@ -86,7 +87,7 @@
logging::InitLogging(settings);
logging::SetLogMessageHandler(MessageHandler);
- LOG(INFO) << "Start MMC daemon";
+ bluetooth::log::info("Start MMC daemon");
// These are needed to send D-Bus signals and receive messages.
// Even though they are not used directly, they set up some global state
diff --git a/system/stack/mmc/metrics/BUILD.gn b/system/stack/mmc/metrics/BUILD.gn
index 276693c..dd27d7a 100644
--- a/system/stack/mmc/metrics/BUILD.gn
+++ b/system/stack/mmc/metrics/BUILD.gn
@@ -15,7 +15,10 @@
#
source_set("libmmc_metrics"){
- configs += [ "//bt/system/stack/mmc:target_defaults" ]
+ configs += [
+ "//bt/system/stack/mmc:target_defaults",
+ "//bt/system/log:log_defaults",
+ ]
sources = [
"mmc_rtt_logger.cc",
]
diff --git a/system/stack/rfcomm/port_api.cc b/system/stack/rfcomm/port_api.cc
index daf9b897..5ca378a0 100644
--- a/system/stack/rfcomm/port_api.cc
+++ b/system/stack/rfcomm/port_api.cc
@@ -33,7 +33,7 @@
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
#include "osi/include/mutex.h"
#include "stack/include/bt_hdr.h"
diff --git a/system/stack/rfcomm/port_rfc.cc b/system/stack/rfcomm/port_rfc.cc
index 140efd6..32b12c4 100644
--- a/system/stack/rfcomm/port_rfc.cc
+++ b/system/stack/rfcomm/port_rfc.cc
@@ -31,16 +31,14 @@
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <cstdint>
-#include <string>
#include "hal/snoop_logger.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
#include "main/shim/entry.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
#include "osi/include/mutex.h"
-#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_uuid16.h"
#include "stack/include/stack_metrics_logging.h"
@@ -552,8 +550,8 @@
* state for the port. Propagate change to the user.
*
******************************************************************************/
-void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci,
- UNUSED_ATTR tPORT_STATE* p_pars, uint16_t result) {
+void PORT_PortNegCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_STATE* /* p_pars */,
+ uint16_t result) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
log::verbose("PORT_PortNegCnf");
@@ -640,8 +638,7 @@
* peer acknowleges change of the modem signals.
*
******************************************************************************/
-void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci,
- UNUSED_ATTR tPORT_CTRL* p_pars) {
+void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* /* p_pars */) {
tPORT* p_port = port_find_mcb_dlci_port(p_mcb, dlci);
uint32_t event = 0;
diff --git a/system/stack/rfcomm/port_utils.cc b/system/stack/rfcomm/port_utils.cc
index 79de26e..aaecc83 100644
--- a/system/stack/rfcomm/port_utils.cc
+++ b/system/stack/rfcomm/port_utils.cc
@@ -32,7 +32,7 @@
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
#include "osi/include/mutex.h"
#include "stack/include/bt_hdr.h"
diff --git a/system/stack/rfcomm/rfc_l2cap_if.cc b/system/stack/rfcomm/rfc_l2cap_if.cc
index 907889a..845e7d2 100644
--- a/system/stack/rfcomm/rfc_l2cap_if.cc
+++ b/system/stack/rfcomm/rfc_l2cap_if.cc
@@ -31,9 +31,8 @@
#include "common/time_util.h"
#include "internal_include/bt_target.h"
#include "internal_include/bt_trace.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
-#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_psm_types.h"
#include "stack/include/l2c_api.h"
@@ -91,7 +90,7 @@
*
******************************************************************************/
void RFCOMM_ConnectInd(const RawAddress& bd_addr, uint16_t lcid,
- UNUSED_ATTR uint16_t psm, uint8_t id) {
+ uint16_t /* psm */, uint8_t id) {
tRFC_MCB* p_mcb = rfc_alloc_multiplexer_channel(bd_addr, false);
if ((p_mcb) && (p_mcb->state != RFC_MX_STATE_IDLE)) {
@@ -214,7 +213,7 @@
* event to the FSM.
*
******************************************************************************/
-void RFCOMM_ConfigCnf(uint16_t lcid, UNUSED_ATTR uint16_t initiator,
+void RFCOMM_ConfigCnf(uint16_t lcid, uint16_t /* initiator */,
tL2CAP_CFG_INFO* p_cfg) {
RFCOMM_ConfigInd(lcid, p_cfg);
diff --git a/system/stack/rfcomm/rfc_mx_fsm.cc b/system/stack/rfcomm/rfc_mx_fsm.cc
index e406670..2bd54da 100644
--- a/system/stack/rfcomm/rfc_mx_fsm.cc
+++ b/system/stack/rfcomm/rfc_mx_fsm.cc
@@ -29,9 +29,8 @@
#include <cstdint>
#include "include/check.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
-#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bt_hdr.h"
#include "stack/include/bt_psm_types.h"
#include "stack/include/l2c_api.h"
@@ -57,7 +56,7 @@
static void rfc_mx_sm_state_wait_sabme(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
void* p_data);
static void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
- UNUSED_ATTR void* p_data);
+ void* p_data);
static void rfc_mx_sm_state_disc_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
void* p_data);
@@ -322,7 +321,7 @@
*
******************************************************************************/
void rfc_mx_sm_sabme_wait_ua(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
- UNUSED_ATTR void* p_data) {
+ void* /* p_data */) {
log::verbose("event {}", event);
switch (event) {
case RFC_MX_EVENT_START_REQ:
@@ -450,7 +449,7 @@
*
******************************************************************************/
void rfc_mx_sm_state_connected(tRFC_MCB* p_mcb, tRFC_MX_EVENT event,
- UNUSED_ATTR void* p_data) {
+ void* /* p_data */) {
log::verbose("event {}", event);
switch (event) {
diff --git a/system/stack/rfcomm/rfc_port_if.cc b/system/stack/rfcomm/rfc_port_if.cc
index 5144985..a3ec47c 100644
--- a/system/stack/rfcomm/rfc_port_if.cc
+++ b/system/stack/rfcomm/rfc_port_if.cc
@@ -30,9 +30,6 @@
#include <cstdint>
#include <unordered_map>
-#include "internal_include/bt_target.h"
-#include "os/log.h"
-#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bt_hdr.h"
#include "stack/rfcomm/port_int.h"
#include "stack/rfcomm/rfc_int.h"
@@ -80,8 +77,7 @@
* machine.
*
******************************************************************************/
-void RFCOMM_DlcEstablishReq(tRFC_MCB* p_mcb, uint8_t dlci,
- UNUSED_ATTR uint16_t mtu) {
+void RFCOMM_DlcEstablishReq(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t /* mtu */) {
if (p_mcb->state != RFC_MX_STATE_CONNECTED) {
PORT_DlcEstablishCnf(p_mcb, dlci, 0, RFCOMM_ERROR);
return;
@@ -104,8 +100,8 @@
* acks Establish Indication.
*
******************************************************************************/
-void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci,
- UNUSED_ATTR uint16_t mtu, uint16_t result) {
+void RFCOMM_DlcEstablishRsp(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t /* mtu */,
+ uint16_t result) {
if ((p_mcb->state != RFC_MX_STATE_CONNECTED) && (result == RFCOMM_SUCCESS)) {
PORT_DlcReleaseInd(p_mcb, dlci);
return;
diff --git a/system/stack/rfcomm/rfc_ts_frames.cc b/system/stack/rfcomm/rfc_ts_frames.cc
index cf49eda..e3e9a2b 100644
--- a/system/stack/rfcomm/rfc_ts_frames.cc
+++ b/system/stack/rfcomm/rfc_ts_frames.cc
@@ -26,12 +26,11 @@
#include <base/logging.h>
#include <bluetooth/log.h>
-#include <log/log.h>
#include <cstdint>
#include "internal_include/bt_target.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
#include "stack/include/bt_hdr.h"
#include "stack/include/l2c_api.h"
diff --git a/system/stack/rfcomm/rfc_utils.cc b/system/stack/rfcomm/rfc_utils.cc
index 91651ba..9fc19dc 100644
--- a/system/stack/rfcomm/rfc_utils.cc
+++ b/system/stack/rfcomm/rfc_utils.cc
@@ -31,9 +31,8 @@
#include "include/check.h"
#include "internal_include/bt_target.h"
-#include "os/log.h"
+#include "os/logging/log_adapter.h"
#include "osi/include/allocator.h"
-#include "osi/include/osi.h" // UNUSED_ATTR
#include "stack/include/bt_hdr.h"
#include "stack/include/port_ext.h"
#include "stack/rfcomm/rfc_int.h"
@@ -322,9 +321,9 @@
* Returns void
*
******************************************************************************/
-void rfc_sec_check_complete(UNUSED_ATTR const RawAddress* bd_addr,
- UNUSED_ATTR tBT_TRANSPORT transport,
- void* p_ref_data, tBTM_STATUS res) {
+void rfc_sec_check_complete(const RawAddress* /* bd_addr */,
+ tBT_TRANSPORT /* transport */, void* p_ref_data,
+ tBTM_STATUS res) {
CHECK(p_ref_data != nullptr);
tPORT* p_port = (tPORT*)p_ref_data;
diff --git a/system/stack/sdp/sdp_utils.cc b/system/stack/sdp/sdp_utils.cc
index 14a3863..940a0c1 100644
--- a/system/stack/sdp/sdp_utils.cc
+++ b/system/stack/sdp/sdp_utils.cc
@@ -26,7 +26,6 @@
#include <android_bluetooth_flags.h>
#include <base/logging.h>
#include <bluetooth/log.h>
-#include <log/log.h>
#include <array>
#include <cstdint>
@@ -1158,7 +1157,7 @@
if (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == Uuid::kNumBytes16) {
return uuid.As16Bit() == p_attr->attr_value.v.u16;
} else {
- LOG_ERROR("invalid length for discovery attribute");
+ log::error("invalid length for discovery attribute");
return (false);
}
}
@@ -1166,13 +1165,13 @@
if (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) == Uuid::kNumBytes32) {
return uuid.As32Bit() == p_attr->attr_value.v.u32;
} else {
- LOG_ERROR("invalid length for discovery attribute");
+ log::error("invalid length for discovery attribute");
return (false);
}
}
if (SDP_DISC_ATTR_LEN(p_attr->attr_len_type) != Uuid::kNumBytes128) {
- LOG_ERROR("invalid length for discovery attribute");
+ log::error("invalid length for discovery attribute");
return (false);
}
diff --git a/system/stack/smp/smp_utils.cc b/system/stack/smp/smp_utils.cc
index 8ba3457..f157b39 100644
--- a/system/stack/smp/smp_utils.cc
+++ b/system/stack/smp/smp_utils.cc
@@ -30,9 +30,11 @@
#include <cstring>
#include "crypto_toolbox/crypto_toolbox.h"
-#include "device/include/controller.h"
+#include "hci/controller_interface.h"
#include "internal_include/bt_target.h"
#include "internal_include/stack_config.h"
+#include "main/shim/entry.h"
+#include "main/shim/helpers.h"
#include "os/log.h"
#include "osi/include/allocator.h"
#include "osi/include/osi.h"
@@ -675,7 +677,8 @@
p = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
UINT8_TO_STREAM(p, SMP_OPCODE_ID_ADDR);
UINT8_TO_STREAM(p, 0);
- BDADDR_TO_STREAM(p, *controller_get_interface()->get_address());
+ BDADDR_TO_STREAM(p, bluetooth::ToRawAddress(
+ bluetooth::shim::GetController()->GetMacAddress()));
p_buf->offset = L2CAP_MIN_OFFSET;
p_buf->len = SMP_ID_ADDR_SIZE;
diff --git a/system/stack/srvc/srvc_dis.cc b/system/stack/srvc/srvc_dis.cc
index fe4f2bc..81f9c6b 100644
--- a/system/stack/srvc/srvc_dis.cc
+++ b/system/stack/srvc/srvc_dis.cc
@@ -266,7 +266,7 @@
uint16_t conn_id = p_clcb->conn_id;
if (dis_cb.dis_read_uuid_idx >= (sizeof(dis_attr_uuid)/sizeof(dis_attr_uuid[0]))) {
- LOG(ERROR) << "invalid dis_cb.dis_read_uuid_idx";
+ log::error("invalid dis_cb.dis_read_uuid_idx");
return;
}
diff --git a/system/stack/test/a2dp/a2dp_aac_unittest.cc b/system/stack/test/a2dp/a2dp_aac_unittest.cc
index bc83ab9..71ab529 100644
--- a/system/stack/test/a2dp/a2dp_aac_unittest.cc
+++ b/system/stack/test/a2dp/a2dp_aac_unittest.cc
@@ -25,7 +25,6 @@
#include <string>
#include "common/init_flags.h"
-#include "common/testing/log_capture.h"
#include "common/time_util.h"
#include "os/log.h"
#include "osi/include/allocator.h"
@@ -39,10 +38,6 @@
namespace {
constexpr uint32_t kAacReadSize = 1024 * 2 * 2;
constexpr uint32_t kA2dpTickUs = 23 * 1000;
-constexpr char kDecodedDataCallbackIsInvoked[] =
- "A2DP decoded data callback is invoked.";
-constexpr char kEnqueueCallbackIsInvoked[] =
- "A2DP source enqueue callback is invoked.";
constexpr uint16_t kPeerMtu = 1000;
constexpr char kWavFile[] = "test/a2dp/raw_data/pcm1644s.wav";
constexpr uint8_t kCodecInfoAacCapability[AVDT_CODEC_SIZE] = {
@@ -150,45 +145,44 @@
A2dpCodecs* a2dp_codecs_;
tA2DP_ENCODER_INTERFACE* encoder_iface_;
tA2DP_DECODER_INTERFACE* decoder_iface_;
- std::unique_ptr<LogCapture> log_capture_;
};
TEST_F(A2dpAacTest, a2dp_source_read_underflow) {
- log_capture_ = std::make_unique<LogCapture>();
- auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t {
- // underflow
- return 0;
- };
- auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool {
- return false;
- };
- InitializeEncoder(true, read_cb, enqueue_cb);
- uint64_t timestamp_us = bluetooth::common::time_gettimeofday_us();
- encoder_iface_->send_frames(timestamp_us);
- usleep(kA2dpTickUs);
- timestamp_us = bluetooth::common::time_gettimeofday_us();
- encoder_iface_->send_frames(timestamp_us);
- log_capture_->WaitUntilLogContains("a2dp_aac_encode_frames: underflow");
-}
+ static int enqueue_cb_invoked = 0;
-TEST_F(A2dpAacTest, a2dp_enqueue_cb_is_invoked) {
- log_capture_ = std::make_unique<LogCapture>();
- auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t {
- ASSERT(kAacReadSize == len);
- return len;
- };
+ auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t { return 0; };
+
auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool {
- log::info("{}", kEnqueueCallbackIsInvoked);
+ enqueue_cb_invoked += 1;
osi_free(p_buf);
return false;
};
+
InitializeEncoder(true, read_cb, enqueue_cb);
uint64_t timestamp_us = bluetooth::common::time_gettimeofday_us();
encoder_iface_->send_frames(timestamp_us);
- usleep(kA2dpTickUs);
- timestamp_us = bluetooth::common::time_gettimeofday_us();
+ encoder_iface_->send_frames(timestamp_us + kA2dpTickUs);
+
+ ASSERT_EQ(enqueue_cb_invoked, 0);
+}
+
+TEST_F(A2dpAacTest, a2dp_enqueue_cb_is_invoked) {
+ static int enqueue_cb_invoked = 0;
+
+ auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t { return len; };
+
+ auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool {
+ enqueue_cb_invoked += 1;
+ osi_free(p_buf);
+ return false;
+ };
+
+ InitializeEncoder(true, read_cb, enqueue_cb);
+ uint64_t timestamp_us = bluetooth::common::time_gettimeofday_us();
encoder_iface_->send_frames(timestamp_us);
- log_capture_->WaitUntilLogContains(kEnqueueCallbackIsInvoked);
+ encoder_iface_->send_frames(timestamp_us + kA2dpTickUs);
+
+ ASSERT_EQ(enqueue_cb_invoked, 1);
}
TEST_F(A2dpAacTest, decoded_data_cb_not_invoked_when_empty_packet) {
@@ -201,10 +195,11 @@
}
TEST_F(A2dpAacTest, decoded_data_cb_invoked) {
- log_capture_ = std::make_unique<LogCapture>();
- auto data_cb = +[](uint8_t* p_buf, uint32_t len) {
- log::info("{}", kDecodedDataCallbackIsInvoked);
- };
+ static int data_cb_invoked = 0;
+ static int enqueue_cb_invoked = 0;
+
+ auto data_cb = +[](uint8_t* p_buf, uint32_t len) { data_cb_invoked += 1; };
+
InitializeDecoder(data_cb);
auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t {
@@ -213,23 +208,23 @@
counter += len;
return len;
};
+
auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool {
+ enqueue_cb_invoked += 1;
packet = p_buf;
- log::info("{}", kEnqueueCallbackIsInvoked);
return false;
};
+
InitializeEncoder(true, read_cb, enqueue_cb);
uint64_t timestamp_us = bluetooth::common::time_gettimeofday_us();
encoder_iface_->send_frames(timestamp_us);
- usleep(kA2dpTickUs);
- timestamp_us = bluetooth::common::time_gettimeofday_us();
- encoder_iface_->send_frames(timestamp_us);
+ encoder_iface_->send_frames(timestamp_us + kA2dpTickUs);
- log_capture_->WaitUntilLogContains(kEnqueueCallbackIsInvoked);
+ ASSERT_EQ(enqueue_cb_invoked, 1);
decoder_iface_->decode_packet(packet);
osi_free(packet);
- ASSERT_TRUE(log_capture_->Find(kDecodedDataCallbackIsInvoked));
+ ASSERT_EQ(data_cb_invoked, 1);
}
TEST_F(A2dpAacTest, set_source_codec_config_works) {
@@ -272,12 +267,6 @@
ASSERT_EQ(a2dp_aac_get_effective_frame_size(), 663 /* MAX_2MBPS_AVDTP_MTU */);
}
-TEST_F(A2dpAacTest, debug_codec_dump) {
- log_capture_ = std::make_unique<LogCapture>();
- a2dp_codecs_->debug_codec_dump(2);
- log_capture_->WaitUntilLogContains("Current Codec: AAC");
-}
-
TEST_F(A2dpAacTest, codec_info_string) {
auto codec_info = A2DP_CodecInfoString(kCodecInfoAacCapability);
ASSERT_NE(codec_info.find("samp_freq: 44100"), std::string::npos);
diff --git a/system/stack/test/a2dp/a2dp_sbc_unittest.cc b/system/stack/test/a2dp/a2dp_sbc_unittest.cc
index 9487fbc..8b5dbba 100644
--- a/system/stack/test/a2dp/a2dp_sbc_unittest.cc
+++ b/system/stack/test/a2dp/a2dp_sbc_unittest.cc
@@ -26,7 +26,6 @@
#include <string>
#include "common/init_flags.h"
-#include "common/testing/log_capture.h"
#include "common/time_util.h"
#include "os/log.h"
#include "osi/include/allocator.h"
@@ -147,7 +146,6 @@
A2dpCodecs* a2dp_codecs_;
tA2DP_ENCODER_INTERFACE* encoder_iface_;
tA2DP_DECODER_INTERFACE* decoder_iface_;
- std::unique_ptr<LogCapture> log_capture_;
};
TEST_F(A2dpSbcTest, a2dp_source_read_underflow) {
@@ -281,12 +279,6 @@
ASSERT_EQ(a2dp_sbc_get_effective_frame_size(), 663 /* MAX_2MBPS_AVDTP_MTU */);
}
-TEST_F(A2dpSbcTest, debug_codec_dump) {
- log_capture_ = std::make_unique<LogCapture>();
- a2dp_codecs_->debug_codec_dump(2);
- log_capture_->WaitUntilLogContains("Current Codec: SBC");
-}
-
TEST_F(A2dpSbcTest, codec_info_string) {
auto codec_info = A2DP_CodecInfoString(kCodecInfoSbcCapability);
ASSERT_NE(codec_info.find("samp_freq: 44100"), std::string::npos);
diff --git a/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc b/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc
index 34c6198..96a6461 100644
--- a/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc
+++ b/system/stack/test/a2dp/a2dp_vendor_ldac_unittest.cc
@@ -20,7 +20,6 @@
#include <stdio.h>
#include "common/init_flags.h"
-#include "common/testing/log_capture.h"
#include "common/time_util.h"
#include "osi/include/allocator.h"
#include "stack/include/a2dp_vendor_ldac_constants.h"
@@ -128,25 +127,27 @@
A2dpCodecs* a2dp_codecs_;
tA2DP_ENCODER_INTERFACE* encoder_iface_;
tA2DP_DECODER_INTERFACE* decoder_iface_;
- std::unique_ptr<LogCapture> log_capture_;
};
TEST_F(A2dpLdacTest, a2dp_source_read_underflow) {
- // log_capture_ = std::make_unique<LogCapture>();
+ static int enqueue_cb_invoked = 0;
+
auto read_cb = +[](uint8_t* p_buf, uint32_t len) -> uint32_t {
return 0;
};
+
auto enqueue_cb = +[](BT_HDR* p_buf, size_t frames_n, uint32_t len) -> bool {
+ enqueue_cb_invoked += 1;
return false;
};
+
InitializeEncoder(read_cb, enqueue_cb);
uint64_t timestamp_us = bluetooth::common::time_gettimeofday_us();
encoder_iface_->send_frames(timestamp_us);
- usleep(kA2dpTickUs);
- timestamp_us = bluetooth::common::time_gettimeofday_us();
- encoder_iface_->send_frames(timestamp_us);
- // log_capture_->WaitUntilLogContains("a2dp_ldac_encode_frames: underflow");
+ encoder_iface_->send_frames(timestamp_us + kA2dpTickUs);
+
+ ASSERT_EQ(enqueue_cb_invoked, 0);
}
} // namespace testing
-} //namespace bluetooth
+} // namespace bluetooth
diff --git a/system/stack/test/btm_iso_test.cc b/system/stack/test/btm_iso_test.cc
index 77322ac..3a00d6c 100644
--- a/system/stack/test/btm_iso_test.cc
+++ b/system/stack/test/btm_iso_test.cc
@@ -23,7 +23,6 @@
#include "hci/hci_packets.h"
#include "hci/include/hci_layer.h"
#include "main/shim/hci_layer.h"
-#include "mock_controller.h"
#include "mock_hcic_layer.h"
#include "osi/include/allocator.h"
#include "stack/btm/btm_dev.h"
@@ -141,7 +140,6 @@
void SetUp() override {
bluetooth::shim::SetMockIsoInterface(&iso_interface_);
hcic::SetMockHcicInterface(&hcic_interface_);
- controller::SetMockControllerInterface(&controller_interface_);
bluetooth::shim::testing::hci_layer_set_interface(
&bluetooth::shim::interface);
bluetooth::hci::testing::mock_controller_ = &controller_;
@@ -166,7 +164,6 @@
bluetooth::shim::SetMockIsoInterface(nullptr);
hcic::SetMockHcicInterface(nullptr);
- controller::SetMockControllerInterface(nullptr);
bluetooth::shim::testing::hci_layer_set_interface(nullptr);
bluetooth::hci::testing::mock_controller_ = nullptr;
}
@@ -344,7 +341,6 @@
hcic::MockHcicInterface hcic_interface_;
bluetooth::hci::testing::MockControllerInterface controller_;
bluetooth::hci::LeBufferSize iso_sizes_;
- controller::MockControllerInterface controller_interface_;
std::unique_ptr<MockBigCallbacks> big_callbacks_;
std::unique_ptr<MockCigCallbacks> cig_callbacks_;
diff --git a/system/stack/test/common/mock_btm_layer.cc b/system/stack/test/common/mock_btm_layer.cc
index 22a17a7..cff191d 100644
--- a/system/stack/test/common/mock_btm_layer.cc
+++ b/system/stack/test/common/mock_btm_layer.cc
@@ -18,7 +18,6 @@
#include "mock_btm_layer.h"
-#include "stack/include/bt_psm_types.h"
#include "stack/include/btm_client_interface.h"
#include "stack/include/rfcdefs.h"
#include "types/raw_address.h"
@@ -31,25 +30,6 @@
btm_security_internal_interface = mock_btm_security_internal_interface;
}
-void btm_sec_abort_access_req(const RawAddress& bd_addr) {
- btm_security_internal_interface->AbortAccessRequest(bd_addr);
-}
-
-tBTM_STATUS btm_sec_mx_access_request(const RawAddress& bd_addr,
- bool is_originator, uint16_t requirement,
- tBTM_SEC_CALLBACK* p_callback,
- void* p_ref_data) {
- return btm_security_internal_interface->MultiplexingProtocolAccessRequest(
- bd_addr, BT_PSM_RFCOMM, is_originator, BTM_SEC_PROTO_RFCOMM, 0,
- p_callback, p_ref_data);
-}
-
-bool BTM_SetSecurityLevel(bool is_originator, const char* p_name,
- uint8_t service_id, uint16_t sec_level, uint16_t psm,
- uint32_t mx_proto_id, uint32_t mx_chan_id) {
- return true;
-}
-
uint16_t BTM_GetMaxPacketSize(const RawAddress& addr) {
return RFCOMM_DEFAULT_MTU;
}
@@ -66,7 +46,3 @@
.BTM_GetMaxPacketSize = BTM_GetMaxPacketSize,
},
};
-
-struct btm_client_interface_t& get_btm_client_interface() {
- return btm_client_interface;
-}
diff --git a/system/stack/test/common/mock_controller.cc b/system/stack/test/common/mock_controller.cc
deleted file mode 100644
index dd96dad..0000000
--- a/system/stack/test/common/mock_controller.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2020 HIMSA II K/S - www.himsa.com.
- * Represented by EHIMA - www.ehima.com
- *
- * 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 "mock_controller.h"
-
-#include "device/include/controller.h"
-
-static controller::MockControllerInterface* controller_interface = nullptr;
-
-void controller::SetMockControllerInterface(
- MockControllerInterface* interface) {
- controller_interface = interface;
-}
-
-const controller_t* controller_get_interface() {
- static controller_t* controller_instance = new controller_t();
-
- return controller_instance;
-}
diff --git a/system/stack/test/common/mock_controller.h b/system/stack/test/common/mock_controller.h
deleted file mode 100644
index eca7160..0000000
--- a/system/stack/test/common/mock_controller.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright 2020 HIMSA II K/S - www.himsa.com.
- * Represented by EHIMA - www.ehima.com
- *
- * 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/functional/callback.h>
-#include <gmock/gmock.h>
-
-namespace controller {
-class ControllerInterface {
- public:
- virtual uint16_t GetAclDataSizeBle(void) = 0;
-
- virtual ~ControllerInterface() = default;
-};
-
-class MockControllerInterface : public ControllerInterface {
- public:
- MOCK_METHOD((uint16_t), GetAclDataSizeBle, (), (override));
-};
-
-void SetMockControllerInterface(
- MockControllerInterface* mock_controller_interface);
-} // namespace controller
diff --git a/system/stack/test/rfcomm/stack_rfcomm_test_main.cc b/system/stack/test/rfcomm/stack_rfcomm_test_main.cc
index 9de02ea..bc01657 100644
--- a/system/stack/test/rfcomm/stack_rfcomm_test_main.cc
+++ b/system/stack/test/rfcomm/stack_rfcomm_test_main.cc
@@ -23,8 +23,6 @@
#include <bluetooth/log.h>
#include <gtest/gtest.h>
-#include <string>
-
using namespace bluetooth;
int main(int argc, char** argv) {
diff --git a/system/stack/test/sdp/stack_sdp_parse_test.cc b/system/stack/test/sdp/stack_sdp_parse_test.cc
index 51561ae..e5b64b6 100644
--- a/system/stack/test/sdp/stack_sdp_parse_test.cc
+++ b/system/stack/test/sdp/stack_sdp_parse_test.cc
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+#include <bluetooth/log.h>
#include <com_android_bluetooth_flags.h>
#include <flag_macros.h>
#include <gtest/gtest.h>
@@ -157,8 +158,8 @@
pkt->len - kSdpPacketStartOffset);
sdp_disc_server_rsp(p_ccb_, bt_hdr);
osi_free(data);
- LOG_INFO("i:%zu L2CA_DisconnectReq:%d", i,
- get_func_call_count("L2CA_DisconnectReq"));
+ bluetooth::log::info("i:{} L2CA_DisconnectReq:{}", i,
+ get_func_call_count("L2CA_DisconnectReq"));
}
}
};
diff --git a/system/test/Android.bp b/system/test/Android.bp
index 29bd034..80a4fd2 100644
--- a/system/test/Android.bp
+++ b/system/test/Android.bp
@@ -211,7 +211,6 @@
"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_hci_layer.cc",
"mock/mock_main_shim_l2cap_api.cc",
@@ -650,6 +649,7 @@
"android.hardware.bluetooth.audio@2.1",
"android.hardware.common-V2-ndk",
"android.hardware.common.fmq-V1-ndk",
+ "libbluetooth_log",
"libbt-audio-hal-interface",
],
test_suites: ["general-tests"],
diff --git a/system/test/common/mock_functions.cc b/system/test/common/mock_functions.cc
index 638d5b3..7532d4c 100644
--- a/system/test/common/mock_functions.cc
+++ b/system/test/common/mock_functions.cc
@@ -16,6 +16,8 @@
#include "test/common/mock_functions.h"
+#include <bluetooth/log.h>
+
#include <map>
#include "os/log.h"
@@ -35,10 +37,10 @@
int get_func_call_size() { return _get_func_call_count_map().size(); }
void dump_mock_function_count_map() {
- LOG_INFO("Mock function count map size:%zu",
- _get_func_call_count_map().size());
+ bluetooth::log::info("Mock function count map size:{}",
+ _get_func_call_count_map().size());
for (const auto& it : _get_func_call_count_map()) {
- LOG_INFO("function:%s: call_count:%d", it.first.c_str(), it.second);
+ bluetooth::log::info("function:{}: call_count:{}", it.first, it.second);
}
}
diff --git a/system/test/fake/fake_looper.cc b/system/test/fake/fake_looper.cc
index a9ea606..9c705e8 100644
--- a/system/test/fake/fake_looper.cc
+++ b/system/test/fake/fake_looper.cc
@@ -17,6 +17,7 @@
#include "test/fake/fake_looper.h"
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <gtest/gtest.h>
#include <stddef.h>
#include <stdlib.h>
@@ -60,8 +61,8 @@
// thread->tid_ = syscall(__NR_gettid);
thread->tid_ = get_thread_id();
- LOG_DEBUG("Thread message loop is operational name:%s tid:%u",
- thread->name_.c_str(), thread->tid_);
+ bluetooth::log::debug("Thread message loop is operational name:{} tid:{}",
+ thread->name_, thread->tid_);
while (thread->is_running()) {
thread->work_queue_semaphore.wait();
diff --git a/system/test/headless/adapter/adapter.cc b/system/test/headless/adapter/adapter.cc
index 7de75c7..04348cb 100644
--- a/system/test/headless/adapter/adapter.cc
+++ b/system/test/headless/adapter/adapter.cc
@@ -18,6 +18,8 @@
#include "test/headless/adapter/adapter.h"
+#include <bluetooth/log.h>
+
#include "base/logging.h" // LOG() stdout and android log
#include "gd/os/log.h"
#include "test/headless/headless.h"
@@ -27,6 +29,7 @@
#include "test/headless/stopwatch.h"
using namespace bluetooth::test;
+using namespace bluetooth;
using namespace std::chrono_literals;
namespace {
@@ -34,7 +37,7 @@
unsigned kTimeoutMs = 5000;
int get_adapter_info([[maybe_unused]] unsigned int num_loops) {
- LOG(INFO) << "Started Device Adapter Properties";
+ log::info("Started Device Adapter Properties");
ASSERT(bluetoothInterface.get_adapter_properties() == BT_STATUS_SUCCESS);
LOG_CONSOLE("Started get adapter properties");
diff --git a/system/test/headless/connect/connect.cc b/system/test/headless/connect/connect.cc
index 415501f..3063aeb 100644
--- a/system/test/headless/connect/connect.cc
+++ b/system/test/headless/connect/connect.cc
@@ -18,6 +18,7 @@
#include "test/headless/connect/connect.h"
+#include <bluetooth/log.h>
#include <inttypes.h>
#include <chrono>
@@ -41,6 +42,7 @@
#include "types/raw_address.h"
using namespace bluetooth::test;
+using namespace bluetooth;
using namespace std::chrono_literals;
const stack_manager_t* stack_manager_get_interface();
@@ -72,7 +74,7 @@
};
LOG_CONSOLE("Creating connection to:%s", bd_addr.ToString().c_str());
- LOG(INFO) << "Creating classic connection to " << bd_addr.ToString();
+ log::info("Creating classic connection to {}", bd_addr.ToString());
acl_create_classic_connection(bd_addr, false, false);
std::shared_ptr<callback_params_t> acl{nullptr};
@@ -106,7 +108,7 @@
if (f_simulate_stack_crash) {
LOG_CONSOLE("Just crushing stack");
- LOG(INFO) << "Just crushing stack";
+ log::info("Just crushing stack");
bluetoothInterface.disable();
}
std::shared_ptr<callback_params_t> acl2{nullptr};
diff --git a/system/test/headless/headless.cc b/system/test/headless/headless.cc
index e364803..f96b86a 100644
--- a/system/test/headless/headless.cc
+++ b/system/test/headless/headless.cc
@@ -18,6 +18,7 @@
#include "test/headless/headless.h"
+#include <bluetooth/log.h>
#include <dlfcn.h> // dlopen
#include <iostream>
@@ -40,6 +41,7 @@
extern bt_interface_t bluetoothInterface;
using namespace bluetooth::test::headless;
+using namespace bluetooth;
namespace {
@@ -88,11 +90,9 @@
(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);
+ log::info("num_callbacks:{} status:{} num_properties:{} properties:{}",
+ num_callbacks, bt_status_text(status), num_properties,
+ fmt::ptr(properties));
}
void remote_device_properties(bt_status_t status, RawAddress* bd_addr,
@@ -109,11 +109,10 @@
(callback)(¶ms);
}
}
- LOG_INFO(
- "num_callbacks:%zu status:%s device:%s num_properties:%d "
- "properties:%p",
- num_callbacks, bt_status_text(status).c_str(), STR(*bd_addr),
- num_properties, properties);
+ log::info(
+ "num_callbacks:{} status:{} device:{} num_properties:{} properties:{}",
+ num_callbacks, bt_status_text(status), STR(*bd_addr), num_properties,
+ fmt::ptr(properties));
}
// Aggregate disparate variables from callback API into unified single structure
@@ -127,8 +126,8 @@
(callback)(¶ms);
}
}
- LOG_INFO("Device found callback: num_properties:%d properties:%p",
- num_properties, properties);
+ log::info("Device found callback: num_properties:{} properties:{}",
+ num_properties, fmt::ptr(properties));
}
void discovery_state_changed(bt_discovery_state_t state) {
@@ -146,7 +145,7 @@
[[maybe_unused]] bt_bdname_t* bd_name,
[[maybe_unused]] uint32_t cod,
[[maybe_unused]] bool min_16_digit) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
void ssp_request([[maybe_unused]] RawAddress* remote_bd_addr,
@@ -154,7 +153,7 @@
[[maybe_unused]] uint32_t cod,
[[maybe_unused]] bt_ssp_variant_t pairing_variant,
[[maybe_unused]] uint32_t pass_key) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
/** Bluetooth Bond state changed callback */
@@ -163,17 +162,17 @@
[[maybe_unused]] RawAddress* remote_bd_addr,
[[maybe_unused]] bt_bond_state_t state,
[[maybe_unused]] int fail_reason) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
void address_consolidate([[maybe_unused]] RawAddress* main_bd_addr,
[[maybe_unused]] RawAddress* secondary_bd_addr) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
void le_address_associate([[maybe_unused]] RawAddress* main_bd_addr,
[[maybe_unused]] RawAddress* secondary_bd_addr) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
/** Bluetooth ACL connection state changed callback */
@@ -193,10 +192,9 @@
(callback)(¶ms);
}
}
- LOG_INFO("%s num_callbacks:%zu status:%s device:%s state:%s", __func__,
- num_callbacks, bt_status_text(status).c_str(),
- remote_bd_addr->ToString().c_str(),
- (state) ? "disconnected" : "connected");
+ log::info("num_callbacks:{} status:{} device:{} state:{}", num_callbacks,
+ bt_status_text(status), remote_bd_addr->ToString(),
+ (state) ? "disconnected" : "connected");
}
/** Bluetooth Link Quality Report callback */
@@ -206,37 +204,35 @@
[[maybe_unused]] int retransmission_count,
[[maybe_unused]] int packets_not_receive_count,
[[maybe_unused]] int negative_acknowledgement_count) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
/** Switch buffer size callback */
void switch_buffer_size([[maybe_unused]] bool is_low_latency_buffer_size) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
/** Switch codec callback */
void switch_codec([[maybe_unused]] bool is_low_latency_buffer_size) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
-void thread_event([[maybe_unused]] bt_cb_thread_evt evt) {
- LOG_INFO("%s", __func__);
-}
+void thread_event([[maybe_unused]] bt_cb_thread_evt evt) { log::info(""); }
void dut_mode_recv([[maybe_unused]] uint16_t opcode,
[[maybe_unused]] uint8_t* buf,
[[maybe_unused]] uint8_t len) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
void le_test_mode([[maybe_unused]] bt_status_t status,
[[maybe_unused]] uint16_t num_packets) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
void energy_info([[maybe_unused]] bt_activity_energy_info* energy_info,
[[maybe_unused]] bt_uid_traffic_t* uid_data) {
- LOG_INFO("%s", __func__);
+ log::info("");
}
bt_callbacks_t bt_callbacks{
@@ -265,12 +261,12 @@
// OS CALLOUTS
int acquire_wake_lock_co([[maybe_unused]] const char* lock_name) {
- LOG_INFO("%s", __func__);
+ log::info("");
return 1;
}
int release_wake_lock_co([[maybe_unused]] const char* lock_name) {
- LOG_INFO("%s", __func__);
+ log::info("");
return 0;
}
@@ -281,7 +277,7 @@
};
void HeadlessStack::SetUp() {
- LOG(INFO) << __func__ << " Entry";
+ log::info("Entry");
const bool start_restricted = false;
const bool is_common_criteria_mode = false;
@@ -292,21 +288,25 @@
&bt_callbacks, start_restricted, is_common_criteria_mode,
config_compare_result, StackInitFlags(), is_atv, nullptr);
- (status == BT_STATUS_SUCCESS)
- ? LOG(INFO) << __func__ << " Initialized bluetooth callbacks"
- : LOG(FATAL) << "Failed to initialize Bluetooth stack";
+ if (status == BT_STATUS_SUCCESS) {
+ log::info("Initialized bluetooth callbacks");
+ } else {
+ log::fatal("Failed to initialize Bluetooth stack");
+ }
status = bluetoothInterface.set_os_callouts(&bt_os_callouts);
- (status == BT_STATUS_SUCCESS)
- ? LOG(INFO) << __func__ << " Initialized os callouts"
- : LOG(ERROR) << "Failed to set up Bluetooth OS callouts";
+ if (status == BT_STATUS_SUCCESS) {
+ log::info("Initialized os callouts");
+ } else {
+ log::error("Failed to set up Bluetooth OS callouts");
+ }
bluetoothInterface.enable();
- LOG_INFO("%s HeadlessStack stack has enabled", __func__);
+ log::info("HeadlessStack stack has enabled");
std::unique_lock<std::mutex> lck(adapter_state_mutex_);
while (bt_state_ != BT_STATE_ON) adapter_state_cv_.wait(lck);
- LOG_INFO("%s HeadlessStack stack is operational", __func__);
+ log::info("HeadlessStack stack is operational");
bt_stack_info_ = std::make_unique<BtStackInfo>();
@@ -318,16 +318,16 @@
void HeadlessStack::TearDown() {
bluetooth::test::headless::stop_messenger();
- LOG_INFO("Stack has disabled");
+ log::info("Stack has disabled");
int status = bluetoothInterface.disable();
- LOG(INFO) << __func__ << " Interface has been disabled status:" << status;
+ log::info("Interface has been disabled status:{}", status);
bluetoothInterface.cleanup();
- LOG(INFO) << __func__ << " Cleaned up hal bluetooth library";
+ log::info("Cleaned up hal bluetooth library");
std::unique_lock<std::mutex> lck(adapter_state_mutex_);
while (bt_state_ != BT_STATE_OFF) adapter_state_cv_.wait(lck);
- LOG_INFO("%s HeadlessStack stack has exited", __func__);
+ log::info("HeadlessStack stack has exited");
LOG_CONSOLE("%s Headless stack has shutdown successfully", kHeadlessIcon);
}
diff --git a/system/test/headless/headless.h b/system/test/headless/headless.h
index 37ad7c9..758f540 100644
--- a/system/test/headless/headless.h
+++ b/system/test/headless/headless.h
@@ -16,6 +16,7 @@
#pragma once
+#include <bluetooth/log.h>
#include <unistd.h>
#include <unordered_map>
@@ -70,9 +71,9 @@
template <typename T>
T RunOnHeadlessStack(ExecutionUnit<T> func) {
- LOG(INFO) << kHeadlessInitialSentinel;
+ log::info("{}", kHeadlessInitialSentinel);
SetUp();
- LOG(INFO) << kHeadlessStartSentinel;
+ log::info("{}", kHeadlessStartSentinel);
T rc;
for (loop_ = 0; loop_ < options_.loop_; loop_++) {
@@ -87,16 +88,14 @@
LOG_CONSOLE("Loop completed: %lu", loop_);
}
if (rc) {
- LOG(ERROR) << "FAIL:" << rc << " loop/loops:" << loop_ << "/"
- << options_.loop_;
+ log::error("FAIL:{} loop/loops:{}/{}", rc, loop_, options_.loop_);
} else {
- LOG(INFO) << "PASS:" << rc << " loop/loops:" << loop_ << "/"
- << options_.loop_;
+ log::info("PASS:{} loop/loops:{}/{}", rc, loop_, options_.loop_);
}
- LOG(INFO) << kHeadlessStopSentinel;
+ log::info("{}", kHeadlessStopSentinel);
TearDown();
- LOG(INFO) << kHeadlessFinalSentinel;
+ log::info("{}", kHeadlessFinalSentinel);
return rc;
}
virtual ~HeadlessRun() = default;
diff --git a/system/test/headless/interface.h b/system/test/headless/interface.h
index 8b4c9ef..1cb4a6c 100644
--- a/system/test/headless/interface.h
+++ b/system/test/headless/interface.h
@@ -17,6 +17,7 @@
#pragma once
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <deque>
#include <string>
@@ -29,6 +30,8 @@
#include "test/headless/text.h"
#include "types/raw_address.h"
+using namespace bluetooth;
+
enum class Callback {
AclStateChanged,
AdapterProperties,
@@ -102,9 +105,9 @@
::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);
+ log::debug("Processing property {}/{} {} type:{} val:{}", i,
+ num_properties, fmt::ptr(&properties[i]), properties[i].type,
+ fmt::ptr(properties[i].val));
property_queue_.push_back(
bluetooth::test::headless::property_factory(properties[i]));
}
diff --git a/system/test/headless/scan/scan.cc b/system/test/headless/scan/scan.cc
index 4cc674a..481311b 100644
--- a/system/test/headless/scan/scan.cc
+++ b/system/test/headless/scan/scan.cc
@@ -18,6 +18,8 @@
#include "test/headless/scan/scan.h"
+#include <bluetooth/log.h>
+
#include "base/logging.h" // LOG() stdout and android log
#include "os/log.h"
#include "test/headless/get_options.h"
@@ -29,12 +31,13 @@
#include "test/headless/stopwatch.h"
using namespace bluetooth::test;
+using namespace bluetooth;
using namespace std::chrono_literals;
namespace {
int start_scan([[maybe_unused]] unsigned int num_loops) {
- LOG(INFO) << "Started Device Scan";
+ log::info("Started Device Scan");
ASSERT(bluetoothInterface.start_discovery() == BT_STATUS_SUCCESS);
LOG_CONSOLE("Started inquiry - device discovery");
diff --git a/system/test/headless/utils/power_mode_client.h b/system/test/headless/utils/power_mode_client.h
index e35d455..5b7b0b6 100644
--- a/system/test/headless/utils/power_mode_client.h
+++ b/system/test/headless/utils/power_mode_client.h
@@ -19,6 +19,7 @@
#define LOG_TAG "bt_headless_mode"
#include <base/strings/stringprintf.h>
+#include <bluetooth/log.h>
#include <future>
#include <mutex>
@@ -31,6 +32,7 @@
#include "types/raw_address.h"
using namespace std::chrono_literals;
+using namespace bluetooth;
namespace {
const tBTM_PM_PWR_MD default_mandatory_sniff_mode = {
@@ -89,12 +91,11 @@
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());
+ log::info("Power mode callback cnt:{} data:{}", cnt++, data.ToString());
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());
+ log::info("Received unsolicited power mode callback: {}",
+ data.ToString());
return;
}
promises_map_[data.bd_addr].front().set_value(data);
diff --git a/system/test/mock/mock_bta_dm_act.cc b/system/test/mock/mock_bta_dm_act.cc
index 86e14ce..35bd67f 100644
--- a/system/test/mock/mock_bta_dm_act.cc
+++ b/system/test/mock/mock_bta_dm_act.cc
@@ -48,12 +48,10 @@
struct bta_dm_acl_up bta_dm_acl_up;
struct bta_dm_add_ble_device bta_dm_add_ble_device;
struct bta_dm_add_blekey bta_dm_add_blekey;
-struct bta_dm_add_device bta_dm_add_device;
struct bta_dm_ble_config_local_privacy bta_dm_ble_config_local_privacy;
struct bta_dm_ble_confirm_reply bta_dm_ble_confirm_reply;
struct bta_dm_ble_csis_observe bta_dm_ble_csis_observe;
struct bta_dm_ble_get_energy_info bta_dm_ble_get_energy_info;
-struct bta_dm_ble_observe bta_dm_ble_observe;
struct bta_dm_ble_passkey_reply bta_dm_ble_passkey_reply;
struct bta_dm_ble_scan bta_dm_ble_scan;
struct bta_dm_ble_set_conn_params bta_dm_ble_set_conn_params;
@@ -137,10 +135,6 @@
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_add_blekey(bd_addr, blekey, key_type);
}
-void bta_dm_add_device(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg) {
- inc_func_call_count(__func__);
- test::mock::bta_dm_act::bta_dm_add_device(std::move(msg));
-}
void bta_dm_ble_config_local_privacy(bool privacy_enable) {
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_ble_config_local_privacy(privacy_enable);
@@ -158,11 +152,6 @@
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_ble_get_energy_info(p_energy_info_cback);
}
-void bta_dm_ble_observe(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_cback) {
- inc_func_call_count(__func__);
- test::mock::bta_dm_act::bta_dm_ble_observe(start, duration, p_cback);
-}
void bta_dm_ble_passkey_reply(const RawAddress& bd_addr, bool accept,
uint32_t passkey) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_bta_dm_act.h b/system/test/mock/mock_bta_dm_act.h
index 01d4481..0369a16 100644
--- a/system/test/mock/mock_bta_dm_act.h
+++ b/system/test/mock/mock_bta_dm_act.h
@@ -180,18 +180,6 @@
};
extern struct bta_dm_add_blekey bta_dm_add_blekey;
-// Name: bta_dm_add_device
-// Params: std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg
-// Return: void
-struct bta_dm_add_device {
- std::function<void(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg)> body{
- [](std::unique_ptr<tBTA_DM_API_ADD_DEVICE> /* msg */) {}};
- void operator()(std::unique_ptr<tBTA_DM_API_ADD_DEVICE> msg) {
- body(std::move(msg));
- };
-};
-extern struct bta_dm_add_device bta_dm_add_device;
-
// Name: bta_dm_ble_config_local_privacy
// Params: bool privacy_enable
// Return: void
@@ -238,20 +226,6 @@
};
extern struct bta_dm_ble_get_energy_info bta_dm_ble_get_energy_info;
-// Name: bta_dm_ble_observe
-// Params: bool start, uint8_t duration, tBTA_DM_SEARCH_CBACK* p_cback
-// Return: void
-struct bta_dm_ble_observe {
- std::function<void(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_cback)>
- body{[](bool /* start */, uint8_t /* duration */,
- tBTA_DM_SEARCH_CBACK* /* p_cback */) {}};
- void operator()(bool start, uint8_t duration, tBTA_DM_SEARCH_CBACK* p_cback) {
- body(start, duration, p_cback);
- };
-};
-extern struct bta_dm_ble_observe bta_dm_ble_observe;
-
// Name: bta_dm_clear_event_filter
// Params: None
// Return: void
diff --git a/system/test/mock/mock_bta_dm_api.cc b/system/test/mock/mock_bta_dm_api.cc
index a85004e..d97bc32 100644
--- a/system/test/mock/mock_bta_dm_api.cc
+++ b/system/test/mock/mock_bta_dm_api.cc
@@ -45,7 +45,6 @@
struct BTA_DmBleConfirmReply BTA_DmBleConfirmReply;
struct BTA_DmBleCsisObserve BTA_DmBleCsisObserve;
struct BTA_DmBleGetEnergyInfo BTA_DmBleGetEnergyInfo;
-struct BTA_DmBleObserve BTA_DmBleObserve;
struct BTA_DmBlePasskeyReply BTA_DmBlePasskeyReply;
struct BTA_DmBleRequestMaxTxDataLength BTA_DmBleRequestMaxTxDataLength;
struct BTA_DmBleResetId BTA_DmBleResetId;
@@ -146,11 +145,6 @@
inc_func_call_count(__func__);
test::mock::bta_dm_api::BTA_DmBleGetEnergyInfo(p_cmpl_cback);
}
-void BTA_DmBleObserve(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_results_cb) {
- inc_func_call_count(__func__);
- test::mock::bta_dm_api::BTA_DmBleObserve(start, duration, p_results_cb);
-}
void BTA_DmBlePasskeyReply(const RawAddress& bd_addr, bool accept,
uint32_t passkey) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_bta_dm_api.h b/system/test/mock/mock_bta_dm_api.h
index cfa0c59..39c30ca 100644
--- a/system/test/mock/mock_bta_dm_api.h
+++ b/system/test/mock/mock_bta_dm_api.h
@@ -160,21 +160,6 @@
};
extern struct BTA_DmBleGetEnergyInfo BTA_DmBleGetEnergyInfo;
-// Name: BTA_DmBleObserve
-// Params: bool start, uint8_t duration, tBTA_DM_SEARCH_CBACK* p_results_cb
-// Return: void
-struct BTA_DmBleObserve {
- std::function<void(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_results_cb)>
- body{[](bool /* start */, uint8_t /* duration */,
- tBTA_DM_SEARCH_CBACK* /* p_results_cb */) {}};
- void operator()(bool start, uint8_t duration,
- tBTA_DM_SEARCH_CBACK* p_results_cb) {
- body(start, duration, p_results_cb);
- };
-};
-extern struct BTA_DmBleObserve BTA_DmBleObserve;
-
// Name: BTA_DmBlePasskeyReply
// Params: const RawAddress& bd_addr, bool accept, uint32_t passkey
// Return: void
diff --git a/system/test/mock/mock_device_controller.cc b/system/test/mock/mock_device_controller.cc
deleted file mode 100644
index 6a0ca5e..0000000
--- a/system/test/mock/mock_device_controller.cc
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:1
- *
- * mockcify.pl ver 0.2
- */
-// Mock include file to share data between tests and mock
-#include "test/mock/mock_device_controller.h"
-
-// Original included files, if any
-#include "btcore/include/version.h"
-#include "device/include/controller.h"
-#include "stack/include/btm_api_types.h"
-#include "stack/include/btm_status.h"
-#include "types/raw_address.h"
-
-// Mocked compile conditionals, if any
-// Mocked internal structures, if any
-namespace test {
-namespace mock {
-namespace device_controller {
-
-RawAddress address;
-bt_version_t bt_version = {
- .hci_version = 0,
- .hci_revision = 0,
- .lmp_version = 0,
- .manufacturer = 0,
- .lmp_subversion = 0,
-};
-
-uint8_t supported_commands[HCI_SUPPORTED_COMMANDS_ARRAY_SIZE]{0};
-bt_device_features_t features_classic[MAX_FEATURES_CLASSIC_PAGE_COUNT] = {{
- .as_array{0},
-}};
-uint8_t last_features_classic_page_index{0};
-
-uint8_t ble_acceptlist_size{0};
-uint8_t ble_resolving_list_max_size{0};
-uint8_t ble_supported_states[BLE_SUPPORTED_STATES_SIZE]{0};
-bt_device_features_t features_ble{0};
-uint16_t ble_suggested_default_data_length{0};
-uint16_t ble_supported_max_tx_octets{0};
-uint16_t ble_supported_max_tx_time{0};
-uint16_t ble_supported_max_rx_octets{0};
-uint16_t ble_supported_max_rx_time{0};
-
-uint16_t ble_maximum_advertising_data_length{0};
-uint8_t ble_number_of_supported_advertising_sets{0};
-uint8_t ble_periodic_advertiser_list_size{0};
-uint8_t local_supported_codecs[MAX_LOCAL_SUPPORTED_CODECS_SIZE]{0};
-uint8_t number_of_local_supported_codecs{0};
-
-bool readable{false};
-bool ble_supported{false};
-bool iso_supported{false};
-bool simple_pairing_supported{false};
-bool secure_connections_supported{false};
-bool supports_hold_mode{false};
-bool supports_sniff_mode{true};
-bool supports_park_mode{false};
-
-bool get_is_ready(void) { return readable; }
-
-const RawAddress* get_address(void) { return &address; }
-
-const bt_version_t* get_bt_version(void) { return &bt_version; }
-
-uint8_t* get_local_supported_codecs(uint8_t* number_of_codecs) {
- if (number_of_local_supported_codecs) {
- *number_of_codecs = number_of_local_supported_codecs;
- return local_supported_codecs;
- }
- return NULL;
-}
-
-const uint8_t* get_ble_supported_states(void) { return ble_supported_states; }
-
-uint16_t get_ble_suggested_default_data_length(void) {
- return ble_suggested_default_data_length;
-}
-
-uint16_t get_ble_maximum_tx_data_length(void) {
- return ble_supported_max_tx_octets;
-}
-
-uint16_t get_ble_maximum_tx_time(void) { return ble_supported_max_tx_time; }
-
-uint16_t get_ble_maximum_advertising_data_length(void) {
- return ble_maximum_advertising_data_length;
-}
-
-uint8_t get_ble_number_of_supported_advertising_sets(void) {
- return ble_number_of_supported_advertising_sets;
-}
-
-uint8_t get_ble_periodic_advertiser_list_size(void) {
- return ble_periodic_advertiser_list_size;
-}
-
-uint8_t get_ble_acceptlist_size(void) { return ble_acceptlist_size; }
-
-uint8_t get_ble_resolving_list_max_size(void) {
- return ble_resolving_list_max_size;
-}
-
-void set_ble_resolving_list_max_size(int resolving_list_max_size) {
- ble_resolving_list_max_size = resolving_list_max_size;
-}
-
-uint8_t get_le_all_initiating_phys() {
- uint8_t phy = PHY_LE_1M;
- return phy;
-}
-
-tBTM_STATUS clear_event_filter() { return BTM_SUCCESS; }
-
-tBTM_STATUS clear_event_mask() { return BTM_SUCCESS; }
-
-tBTM_STATUS set_event_filter_connection_setup_all_devices() {
- return BTM_SUCCESS;
-}
-tBTM_STATUS set_event_filter_allow_device_connection(
- std::vector<RawAddress> /* devices */) {
- return BTM_SUCCESS;
-}
-tBTM_STATUS set_default_event_mask_except(uint64_t /* mask */,
- uint64_t /* le_mask */) {
- return BTM_SUCCESS;
-}
-tBTM_STATUS set_event_filter_inquiry_result_all_devices() {
- return BTM_SUCCESS;
-}
-
-const controller_t interface = {
- get_is_ready,
-
- get_address,
- get_bt_version,
-
- get_ble_supported_states,
-
- get_ble_suggested_default_data_length,
- get_ble_maximum_tx_data_length,
- get_ble_maximum_tx_time,
- get_ble_maximum_advertising_data_length,
- get_ble_number_of_supported_advertising_sets,
- get_ble_periodic_advertiser_list_size,
-
- get_ble_acceptlist_size,
-
- get_ble_resolving_list_max_size,
- set_ble_resolving_list_max_size,
- get_local_supported_codecs,
- get_le_all_initiating_phys,
- clear_event_filter,
- clear_event_mask,
- set_event_filter_connection_setup_all_devices,
- set_event_filter_allow_device_connection,
- set_default_event_mask_except,
- set_event_filter_inquiry_result_all_devices,
-};
-
-} // namespace device_controller
-} // namespace mock
-} // namespace test
-
-// Mocked functions, if any
-const controller_t* controller_get_interface() {
- return &test::mock::device_controller::interface;
-}
-
-// END mockcify generation
diff --git a/system/test/mock/mock_device_controller.h b/system/test/mock/mock_device_controller.h
deleted file mode 100644
index e8679c5..0000000
--- a/system/test/mock/mock_device_controller.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:1
- *
- * mockcify.pl ver 0.2
- */
-
-#include <cstddef>
-#include <cstdint>
-
-// Original included files, if any
-
-#include "btcore/include/device_features.h"
-
-// Mocked compile conditionals, if any
-namespace test {
-namespace mock {
-namespace device_controller {
-
-constexpr size_t HCI_SUPPORTED_COMMANDS_ARRAY_SIZE = 64;
-constexpr size_t MAX_FEATURES_CLASSIC_PAGE_COUNT = 3;
-constexpr size_t BLE_SUPPORTED_STATES_SIZE = 8;
-constexpr size_t MAX_LOCAL_SUPPORTED_CODECS_SIZE = 8;
-
-// Shared state between mocked functions and tests
-extern uint8_t supported_commands[HCI_SUPPORTED_COMMANDS_ARRAY_SIZE];
-extern bt_device_features_t features_classic[MAX_FEATURES_CLASSIC_PAGE_COUNT];
-extern uint8_t last_features_classic_page_index;
-
-extern uint16_t acl_buffer_count_classic;
-extern uint8_t acl_buffer_count_ble;
-extern uint8_t iso_buffer_count;
-
-extern uint8_t ble_acceptlist_size;
-extern uint8_t ble_resolving_list_max_size;
-extern uint8_t ble_supported_states[BLE_SUPPORTED_STATES_SIZE];
-extern bt_device_features_t features_ble;
-extern uint16_t ble_suggested_default_data_length;
-extern uint16_t ble_supported_max_tx_octets;
-extern uint16_t ble_supported_max_tx_time;
-extern uint16_t ble_supported_max_rx_octets;
-extern uint16_t ble_supported_max_rx_time;
-
-extern uint16_t ble_maxium_advertising_data_length;
-extern uint8_t ble_number_of_supported_advertising_sets;
-extern uint8_t ble_periodic_advertiser_list_size;
-extern uint8_t local_supported_codecs[MAX_LOCAL_SUPPORTED_CODECS_SIZE];
-extern uint8_t number_of_local_supported_codecs;
-
-extern bool readable;
-extern bool ble_supported;
-extern bool iso_supported;
-extern bool simple_pairing_supported;
-extern bool secure_connections_supported;
-
-} // namespace device_controller
-} // namespace mock
-} // namespace test
-
-// END mockcify generation
diff --git a/system/test/mock/mock_main_shim_acl.cc b/system/test/mock/mock_main_shim_acl.cc
index e9bc4ee..e8d5677 100644
--- a/system/test/mock/mock_main_shim_acl.cc
+++ b/system/test/mock/mock_main_shim_acl.cc
@@ -24,7 +24,6 @@
#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"
@@ -245,3 +244,13 @@
void shim::legacy::Acl::SetSystemSuspendState(bool /* suspended */) {
inc_func_call_count(__func__);
}
+
+void shim::legacy::Acl::UpdateConnectionParameters(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 */) {
+ 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 e679183..6250b8d 100644
--- a/system/test/mock/mock_main_shim_acl_api.cc
+++ b/system/test/mock/mock_main_shim_acl_api.cc
@@ -53,6 +53,9 @@
BT_HDR* /* p_buf */) {
inc_func_call_count(__func__);
}
+void bluetooth::shim::ACL_Flush(uint16_t /* handle */) {
+ inc_func_call_count(__func__);
+}
void bluetooth::shim::ACL_Disconnect(uint16_t /* handle */,
bool /* is_classic */,
tHCI_STATUS /* reason */,
@@ -107,3 +110,11 @@
}
void bluetooth::shim::ACL_Shutdown() { inc_func_call_count(__func__); }
+
+void bluetooth::shim::ACL_SendConnectionParameterUpdateRequest(
+ uint16_t /* hci_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 */) {
+ inc_func_call_count(__func__);
+}
diff --git a/system/test/mock/mock_main_shim_acl_api.h b/system/test/mock/mock_main_shim_acl_api.h
index e436317..aee9dcd 100644
--- a/system/test/mock/mock_main_shim_acl_api.h
+++ b/system/test/mock/mock_main_shim_acl_api.h
@@ -266,6 +266,42 @@
};
extern struct ACL_WriteData ACL_WriteData;
+// Name: ACL_Flush
+// Params: uint16_t handle
+// Return: void
+struct ACL_Flush {
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) {}};
+ void operator()(uint16_t handle) { body(handle); };
+};
+extern struct ACL_Flush ACL_Flush;
+
+// Name: ACL_SendConnectionParameterUpdateRequest
+// Params: uint16_t handle
+// Params: uint16_t conn_int_min
+// Params: uint16_t conn_int_max
+// Params: uint16_t conn_latency
+// Params: uint16_t conn_timeout
+// Params: uint16_t min_ce_len
+// Params: uint16_t max_ce_len
+// Return: void
+struct ACL_SendConnectionParameterUpdateRequest {
+ std::function<void(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) {
+ body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
+ min_ce_len, max_ce_len);
+ };
+};
+extern struct ACL_SendConnectionParameterUpdateRequest
+ ACL_SendConnectionParameterUpdateRequest;
} // namespace main_shim_acl_api
} // namespace mock
} // namespace test
diff --git a/system/test/mock/mock_main_shim_controller.cc b/system/test/mock/mock_main_shim_controller.cc
deleted file mode 100644
index 9d4bffc..0000000
--- a/system/test/mock/mock_main_shim_controller.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2021 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:9
- */
-
-#include "device/include/controller.h"
-#include "main/shim/controller.h"
-#include "test/common/mock_functions.h"
-
-namespace bluetooth {
-namespace testing {
-const controller_t* controller{nullptr};
-}
-} // namespace bluetooth
-
-const controller_t* bluetooth::shim::controller_get_interface() {
- inc_func_call_count(__func__);
- return bluetooth::testing::controller;
-}
-
-void bluetooth::shim::controller_clear_event_mask() {
- inc_func_call_count(__func__);
-}
-
-bool bluetooth::shim::controller_is_write_link_supervision_timeout_supported() {
- inc_func_call_count(__func__);
- return false;
-}
diff --git a/system/test/mock/mock_main_shim_controller.h b/system/test/mock/mock_main_shim_controller.h
deleted file mode 100644
index c15e47f..0000000
--- a/system/test/mock/mock_main_shim_controller.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "device/include/controller.h"
-
-namespace bluetooth {
-namespace testing {
-
-extern const controller_t* controller;
-
-}
-} // namespace bluetooth
diff --git a/system/test/mock/mock_osi_config.h b/system/test/mock/mock_osi_config.h
index ee9dce5..d3b884d 100644
--- a/system/test/mock/mock_osi_config.h
+++ b/system/test/mock/mock_osi_config.h
@@ -30,7 +30,6 @@
#include <base/logging.h>
#include <fcntl.h>
#include <libgen.h>
-#include <log/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
diff --git a/system/test/mock/mock_stack_acl.cc b/system/test/mock/mock_stack_acl.cc
index 83df034..300a8ee 100644
--- a/system/test/mock/mock_stack_acl.cc
+++ b/system/test/mock/mock_stack_acl.cc
@@ -59,6 +59,8 @@
struct acl_send_data_packet_br_edr acl_send_data_packet_br_edr;
struct acl_peer_supports_ble_connection_parameters_request
acl_peer_supports_ble_connection_parameters_request;
+struct acl_ble_connection_parameters_request
+ acl_ble_connection_parameters_request;
struct acl_peer_supports_ble_packet_extension
acl_peer_supports_ble_packet_extension;
struct acl_peer_supports_sniff_subrating acl_peer_supports_sniff_subrating;
@@ -116,6 +118,7 @@
struct btm_acl_created btm_acl_created;
struct btm_acl_device_down btm_acl_device_down;
struct btm_acl_disconnected btm_acl_disconnected;
+struct btm_acl_flush btm_acl_flush;
struct btm_acl_encrypt_change btm_acl_encrypt_change;
struct btm_acl_notif_conn_collision btm_acl_notif_conn_collision;
struct btm_acl_process_sca_cmpl_pkt btm_acl_process_sca_cmpl_pkt;
@@ -245,6 +248,15 @@
return test::mock::stack_acl::
acl_peer_supports_ble_connection_parameters_request(remote_bda);
}
+void acl_ble_connection_parameters_request(
+ 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) {
+ inc_func_call_count(__func__);
+ test::mock::stack_acl::acl_ble_connection_parameters_request(
+ handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
+ min_ce_len, max_ce_len);
+}
bool acl_peer_supports_ble_packet_extension(uint16_t hci_handle) {
inc_func_call_count(__func__);
return test::mock::stack_acl::acl_peer_supports_ble_packet_extension(
@@ -401,9 +413,9 @@
inc_func_call_count(__func__);
test::mock::stack_acl::BTM_RequestPeerSCA(remote_bda, transport);
}
-void BTM_acl_after_controller_started(const controller_t* controller) {
+void BTM_acl_after_controller_started() {
inc_func_call_count(__func__);
- test::mock::stack_acl::BTM_acl_after_controller_started(controller);
+ test::mock::stack_acl::BTM_acl_after_controller_started();
}
void BTM_block_role_switch_for(const RawAddress& peer_addr) {
inc_func_call_count(__func__);
@@ -508,6 +520,10 @@
inc_func_call_count(__func__);
test::mock::stack_acl::btm_acl_removed(handle);
}
+void btm_acl_flush(uint16_t handle) {
+ inc_func_call_count(__func__);
+ test::mock::stack_acl::btm_acl_flush(handle);
+}
void btm_acl_role_changed(tHCI_STATUS hci_status, const RawAddress& bd_addr,
tHCI_ROLE new_role) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_stack_acl.h b/system/test/mock/mock_stack_acl.h
index 57a4563..f02d765 100644
--- a/system/test/mock/mock_stack_acl.h
+++ b/system/test/mock/mock_stack_acl.h
@@ -26,7 +26,6 @@
#include <string>
// Original included files, if any
-#include "device/include/controller.h"
#include "hci/class_of_device.h"
#include "stack/acl/acl.h"
#include "stack/btm/security_device_record.h"
@@ -235,6 +234,27 @@
};
extern struct acl_peer_supports_ble_connection_parameters_request
acl_peer_supports_ble_connection_parameters_request;
+// Name: acl_peer_supports_ble_connection_parameters_request
+// Params: const RawAddress& remote_bda
+// Returns: bool
+struct acl_ble_connection_parameters_request {
+ std::function<void(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) {
+ body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
+ min_ce_len, max_ce_len);
+ };
+};
+extern struct acl_ble_connection_parameters_request
+ acl_ble_connection_parameters_request;
// Name: acl_peer_supports_ble_packet_extension
// Params: uint16_t hci_handle
// Returns: bool
@@ -602,12 +622,10 @@
};
extern struct BTM_RequestPeerSCA BTM_RequestPeerSCA;
// Name: BTM_acl_after_controller_started
-// Params: const controller_t* controller
// Returns: void
struct BTM_acl_after_controller_started {
- std::function<void(const controller_t* controller)> body{
- [](const controller_t* /* controller */) { ; }};
- void operator()(const controller_t* controller) { body(controller); };
+ std::function<void()> body{[]() { ; }};
+ void operator()() { body(); };
};
extern struct BTM_acl_after_controller_started BTM_acl_after_controller_started;
// Name: BTM_block_role_switch_for
@@ -864,6 +882,14 @@
void operator()(uint16_t handle) { body(handle); };
};
extern struct btm_acl_removed btm_acl_removed;
+// Name: btm_acl_flush
+// Params: uint16_t handle
+// Returns: void
+struct btm_acl_flush {
+ std::function<void(uint16_t handle)> body{[](uint16_t /* handle */) { ; }};
+ void operator()(uint16_t handle) { body(handle); };
+};
+extern struct btm_acl_flush btm_acl_flush;
// Name: btm_acl_role_changed
// Params: tHCI_STATUS hci_status, const RawAddress& bd_addr, tHCI_ROLE
// new_role Returns: void
diff --git a/system/test/mock/mock_stack_btm_ble_adv_filter.cc b/system/test/mock/mock_stack_btm_ble_adv_filter.cc
index 95d56bf..5df6fff 100644
--- a/system/test/mock/mock_stack_btm_ble_adv_filter.cc
+++ b/system/test/mock/mock_stack_btm_ble_adv_filter.cc
@@ -23,8 +23,8 @@
#include <memory>
-#include "btm_ble_api.h"
#include "stack/btm/btm_ble_int.h"
+#include "stack/include/btm_ble_api.h"
#include "test/common/mock_functions.h"
void BTM_BleAdvFilterParamSetup(
diff --git a/system/test/mock/mock_stack_btm_ble_scanner.cc b/system/test/mock/mock_stack_btm_ble_scanner.cc
index e65f1f7..05fc257 100644
--- a/system/test/mock/mock_stack_btm_ble_scanner.cc
+++ b/system/test/mock/mock_stack_btm_ble_scanner.cc
@@ -20,9 +20,9 @@
#include <base/memory/weak_ptr.h>
#include <base/strings/string_number_conversions.h>
-#include "ble_scanner.h"
#include "stack/btm/ble_scanner_hci_interface.h"
#include "stack/btm/btm_ble_int.h"
+#include "stack/include/ble_scanner.h"
#include "test/common/mock_functions.h"
void BleScanningManager::CleanUp() { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_stack_btm_dev.cc b/system/test/mock/mock_stack_btm_dev.cc
index e63b216..cdb6265 100644
--- a/system/test/mock/mock_stack_btm_dev.cc
+++ b/system/test/mock/mock_stack_btm_dev.cc
@@ -27,9 +27,9 @@
#include <string>
-#include "btm_api.h"
#include "stack/btm/btm_dev.h"
#include "stack/include/bt_octets.h"
+#include "stack/include/btm_api.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
@@ -45,13 +45,10 @@
} // namespace mock
} // namespace test
-bool BTM_SecAddDevice(const RawAddress& /* bd_addr */,
- const DEV_CLASS /* dev_class */,
- const BD_NAME& /* bd_name */, uint8_t* /* features */,
- LinkKey* /* p_link_key */, uint8_t /* key_type */,
- uint8_t /* pin_length */) {
+void BTM_SecAddDevice(const RawAddress& /* bd_addr */,
+ const DEV_CLASS /* dev_class */, LinkKey /* link_key */,
+ uint8_t /* key_type */, uint8_t /* pin_length */) {
inc_func_call_count(__func__);
- return false;
}
bool BTM_SecDeleteDevice(const RawAddress& /* bd_addr */) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_stack_btm_devctl.cc b/system/test/mock/mock_stack_btm_devctl.cc
index 27a4e5e..374e144 100644
--- a/system/test/mock/mock_stack_btm_devctl.cc
+++ b/system/test/mock/mock_stack_btm_devctl.cc
@@ -24,7 +24,7 @@
#include <stddef.h>
#include <stdlib.h>
-#include "bt_dev_class.h"
+#include "stack/include/bt_dev_class.h"
#include "stack/include/btm_api_types.h"
#include "stack/include/btm_status.h"
#include "test/common/mock_functions.h"
diff --git a/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc b/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc
index 2282445..d277627 100644
--- a/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc
+++ b/system/test/mock/mock_stack_btm_hfp_lc3_decoder.cc
@@ -25,7 +25,7 @@
#include <cstdint>
-#include "hfp_lc3_decoder.h"
+#include "stack/include/hfp_lc3_decoder.h"
#include "test/common/mock_functions.h"
// Original usings
diff --git a/system/test/mock/mock_stack_btm_iso.h b/system/test/mock/mock_stack_btm_iso.h
index 804dfe4..9948f4c 100644
--- a/system/test/mock/mock_stack_btm_iso.h
+++ b/system/test/mock/mock_stack_btm_iso.h
@@ -19,7 +19,7 @@
#include <gmock/gmock.h>
-#include "btm_iso_api.h"
+#include "stack/include/btm_iso_api.h"
struct MockIsoManager {
public:
diff --git a/system/test/mock/mock_stack_btm_sec.h b/system/test/mock/mock_stack_btm_sec.h
index d757592..fcde158 100644
--- a/system/test/mock/mock_stack_btm_sec.h
+++ b/system/test/mock/mock_stack_btm_sec.h
@@ -27,8 +27,8 @@
#include <string>
// Original included files, if any
-#include "bt_dev_class.h"
#include "stack/btm/security_device_record.h"
+#include "stack/include/bt_dev_class.h"
#include "stack/include/bt_device_type.h"
#include "stack/include/btm_status.h"
#include "stack/include/hci_error_code.h"
diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.cc b/system/test/mock/mock_stack_hcic_hciblecmds.cc
index 8d7097f..5b345a2 100644
--- a/system/test/mock/mock_stack_hcic_hciblecmds.cc
+++ b/system/test/mock/mock_stack_hcic_hciblecmds.cc
@@ -85,7 +85,6 @@
struct btsnd_hcic_ble_start_enc btsnd_hcic_ble_start_enc;
struct btsnd_hcic_ble_test_end btsnd_hcic_ble_test_end;
struct btsnd_hcic_ble_transmitter_test btsnd_hcic_ble_transmitter_test;
-struct btsnd_hcic_ble_upd_ll_conn_params btsnd_hcic_ble_upd_ll_conn_params;
struct btsnd_hcic_ble_write_adv_params btsnd_hcic_ble_write_adv_params;
struct btsnd_hcic_create_big btsnd_hcic_create_big;
struct btsnd_hcic_create_cis btsnd_hcic_create_cis;
@@ -329,17 +328,6 @@
test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_transmitter_test(
tx_freq, test_data_len, payload);
}
-void btsnd_hcic_ble_upd_ll_conn_params(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) {
- inc_func_call_count(__func__);
- test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_upd_ll_conn_params(
- handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
- min_ce_len, max_ce_len);
-}
void btsnd_hcic_ble_write_adv_params(uint16_t adv_int_min, uint16_t adv_int_max,
uint8_t adv_type,
tBLE_ADDR_TYPE addr_type_own,
diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.h b/system/test/mock/mock_stack_hcic_hciblecmds.h
index ef68736..b72a427 100644
--- a/system/test/mock/mock_stack_hcic_hciblecmds.h
+++ b/system/test/mock/mock_stack_hcic_hciblecmds.h
@@ -571,29 +571,6 @@
};
extern struct btsnd_hcic_ble_transmitter_test btsnd_hcic_ble_transmitter_test;
-// Name: btsnd_hcic_ble_upd_ll_conn_params
-// Params: 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 Return: void
-struct btsnd_hcic_ble_upd_ll_conn_params {
- std::function<void(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) {
- body(handle, conn_int_min, conn_int_max, conn_latency, conn_timeout,
- min_ce_len, max_ce_len);
- };
-};
-extern struct btsnd_hcic_ble_upd_ll_conn_params
- btsnd_hcic_ble_upd_ll_conn_params;
-
// Name: btsnd_hcic_ble_write_adv_params
// Params: 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&
diff --git a/system/test/mock/mock_stack_hcic_hcicmds.cc b/system/test/mock/mock_stack_hcic_hcicmds.cc
index 1cc2b63..c1b66e2 100644
--- a/system/test/mock/mock_stack_hcic_hcicmds.cc
+++ b/system/test/mock/mock_stack_hcic_hcicmds.cc
@@ -44,7 +44,6 @@
struct btsnd_hcic_enable_test_mode btsnd_hcic_enable_test_mode;
struct btsnd_hcic_enhanced_accept_synchronous_connection
btsnd_hcic_enhanced_accept_synchronous_connection;
-struct btsnd_hcic_enhanced_flush btsnd_hcic_enhanced_flush;
struct btsnd_hcic_enhanced_set_up_synchronous_connection
btsnd_hcic_enhanced_set_up_synchronous_connection;
struct btsnd_hcic_exit_park_mode btsnd_hcic_exit_park_mode;
@@ -153,11 +152,6 @@
test::mock::stack_hcic_hcicmds::
btsnd_hcic_enhanced_accept_synchronous_connection(bd_addr, p_params);
}
-void btsnd_hcic_enhanced_flush(uint16_t handle, uint8_t packet_type) {
- inc_func_call_count(__func__);
- test::mock::stack_hcic_hcicmds::btsnd_hcic_enhanced_flush(handle,
- packet_type);
-}
void btsnd_hcic_enhanced_set_up_synchronous_connection(
uint16_t conn_handle, enh_esco_params_t* p_params) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_stack_hcic_hcicmds.h b/system/test/mock/mock_stack_hcic_hcicmds.h
index 232a60f..e7ef2b3 100644
--- a/system/test/mock/mock_stack_hcic_hcicmds.h
+++ b/system/test/mock/mock_stack_hcic_hcicmds.h
@@ -148,18 +148,6 @@
extern struct btsnd_hcic_enhanced_accept_synchronous_connection
btsnd_hcic_enhanced_accept_synchronous_connection;
-// Name: btsnd_hcic_enhanced_flush
-// Params: uint16_t handle, uint8_t packet_type
-// 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 */) {}};
- void operator()(uint16_t handle, uint8_t packet_type) {
- body(handle, packet_type);
- };
-};
-extern struct btsnd_hcic_enhanced_flush btsnd_hcic_enhanced_flush;
-
// Name: btsnd_hcic_enhanced_set_up_synchronous_connection
// Params: uint16_t conn_handle, enh_esco_params_t* p_params
// Return: void
diff --git a/system/udrv/ulinux/uipc.cc b/system/udrv/ulinux/uipc.cc
index 06a0e48..7de87c9 100644
--- a/system/udrv/ulinux/uipc.cc
+++ b/system/udrv/ulinux/uipc.cc
@@ -24,6 +24,11 @@
*
*****************************************************************************/
+#define LOG_TAG "uipc"
+
+#include "udrv/include/uipc.h"
+
+#include <bluetooth/log.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
@@ -40,14 +45,12 @@
#include <cerrno>
#include <mutex>
-// Define before including log.h
-#define LOG_TAG "uipc"
-
#include "audio_a2dp_hw/include/audio_a2dp_hw.h"
#include "os/log.h"
#include "osi/include/osi.h"
#include "osi/include/socket_utils/sockets.h"
-#include "udrv/include/uipc.h"
+
+using namespace bluetooth;
/*****************************************************************************
* Constants & Macros
@@ -106,7 +109,7 @@
int s = socket(AF_LOCAL, SOCK_STREAM, 0);
if (s < 0) return -1;
- LOG_DEBUG("create_server_socket %s", name);
+ log::debug("create_server_socket {}", name);
if (osi_socket_local_server_bind(s, name,
#ifdef __ANDROID__
@@ -115,18 +118,18 @@
ANDROID_SOCKET_NAMESPACE_FILESYSTEM
#endif // __ANDROID__
) < 0) {
- LOG_DEBUG("socket failed to create (%s)", strerror(errno));
+ log::debug("socket failed to create ({})", strerror(errno));
close(s);
return -1;
}
if (listen(s, 5) < 0) {
- LOG_DEBUG("listen failed: %s", strerror(errno));
+ log::debug("listen failed: {}", strerror(errno));
close(s);
return -1;
}
- LOG_DEBUG("created socket fd %d", s);
+ log::debug("created socket fd {}", s);
return s;
}
@@ -136,7 +139,7 @@
int fd;
socklen_t len = sizeof(struct sockaddr_un);
- LOG_DEBUG("accept fd %d", sfd);
+ log::debug("accept fd {}", sfd);
/* make sure there is data to process */
pfd.fd = sfd;
@@ -145,13 +148,13 @@
int poll_ret;
OSI_NO_INTR(poll_ret = poll(&pfd, 1, 0));
if (poll_ret == 0) {
- LOG_WARN("accept poll timeout");
+ log::warn("accept poll timeout");
return -1;
}
OSI_NO_INTR(fd = accept(sfd, (struct sockaddr*)&remote, &len));
if (fd == -1) {
- LOG_ERROR("sock accept failed (%s)", strerror(errno));
+ log::error("sock accept failed ({})", strerror(errno));
return -1;
}
@@ -160,7 +163,7 @@
int ret =
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&size, (int)sizeof(size));
if (ret < 0) {
- LOG_ERROR("setsockopt failed (%s)", strerror(errno));
+ log::error("setsockopt failed ({})", strerror(errno));
}
return fd;
@@ -175,7 +178,7 @@
static int uipc_main_init(tUIPC_STATE& uipc) {
int i;
- LOG_DEBUG("### uipc_main_init ###");
+ log::debug("### uipc_main_init ###");
uipc.tid = 0;
uipc.running = 0;
@@ -207,7 +210,7 @@
void uipc_main_cleanup(tUIPC_STATE& uipc) {
int i;
- LOG_DEBUG("uipc_main_cleanup");
+ log::debug("uipc_main_cleanup");
close(uipc.signal_fds[0]);
close(uipc.signal_fds[1]);
@@ -234,11 +237,11 @@
if (ch_id >= UIPC_CH_NUM) return -1;
if (SAFE_FD_ISSET(uipc.ch[ch_id].srvfd, &uipc.read_set)) {
- LOG_DEBUG("INCOMING CONNECTION ON CH %d", ch_id);
+ log::debug("INCOMING CONNECTION ON CH {}", ch_id);
// Close the previous connection
if (uipc.ch[ch_id].fd != UIPC_DISCONNECTED) {
- LOG_DEBUG("CLOSE CONNECTION (FD %d)", uipc.ch[ch_id].fd);
+ log::debug("CLOSE CONNECTION (FD {})", uipc.ch[ch_id].fd);
close(uipc.ch[ch_id].fd);
FD_CLR(uipc.ch[ch_id].fd, &uipc.active_set);
uipc.ch[ch_id].fd = UIPC_DISCONNECTED;
@@ -246,18 +249,18 @@
uipc.ch[ch_id].fd = accept_server_socket(uipc.ch[ch_id].srvfd);
- LOG_DEBUG("NEW FD %d", uipc.ch[ch_id].fd);
+ log::debug("NEW FD {}", uipc.ch[ch_id].fd);
if ((uipc.ch[ch_id].fd >= 0) && uipc.ch[ch_id].cback) {
/* if we have a callback we should add this fd to the active set
and notify user with callback event */
- LOG_DEBUG("ADD FD %d TO ACTIVE SET", uipc.ch[ch_id].fd);
+ log::debug("ADD FD {} TO ACTIVE SET", uipc.ch[ch_id].fd);
FD_SET(uipc.ch[ch_id].fd, &uipc.active_set);
uipc.max_fd = MAX(uipc.max_fd, uipc.ch[ch_id].fd);
}
if (uipc.ch[ch_id].fd < 0) {
- LOG_ERROR("FAILED TO ACCEPT CH %d", ch_id);
+ log::error("FAILED TO ACCEPT CH {}", ch_id);
return -1;
}
@@ -282,7 +285,7 @@
static inline void uipc_wakeup_locked(tUIPC_STATE& uipc) {
char sig_on = 1;
- LOG_DEBUG("UIPC SEND WAKE UP");
+ log::debug("UIPC SEND WAKE UP");
OSI_NO_INTR(send(uipc.signal_fds[1], &sig_on, sizeof(sig_on), 0));
}
@@ -291,7 +294,7 @@
const char* name, tUIPC_RCV_CBACK* cback) {
int fd;
- LOG_DEBUG("SETUP CHANNEL SERVER %d", ch_id);
+ log::debug("SETUP CHANNEL SERVER {}", ch_id);
if (ch_id >= UIPC_CH_NUM) return -1;
@@ -300,11 +303,11 @@
fd = create_server_socket(name);
if (fd < 0) {
- LOG_ERROR("failed to setup %s: %s", name, strerror(errno));
+ log::error("failed to setup {}: {}", name, strerror(errno));
return -1;
}
- LOG_DEBUG("ADD SERVER FD TO ACTIVE SET %d", fd);
+ log::debug("ADD SERVER FD TO ACTIVE SET {}", fd);
FD_SET(fd, &uipc.active_set);
uipc.max_fd = MAX(uipc.max_fd, fd);
@@ -326,7 +329,7 @@
pfd.fd = uipc.ch[ch_id].fd;
if (uipc.ch[ch_id].fd == UIPC_DISCONNECTED) {
- LOG_DEBUG("%s() - fd disconnected. Exiting", __func__);
+ log::debug("fd disconnected. Exiting");
return;
}
@@ -334,18 +337,18 @@
int ret;
OSI_NO_INTR(ret = poll(&pfd, 1, 1));
if (ret == 0) {
- LOG_VERBOSE("%s(): poll() timeout - nothing to do. Exiting", __func__);
+ log::verbose("poll() timeout - nothing to do. Exiting");
return;
}
if (ret < 0) {
- LOG_WARN("%s() - poll() failed: return %d errno %d (%s). Exiting",
- __func__, ret, errno, strerror(errno));
+ log::warn("poll() failed: return {} errno {} ({}). Exiting", ret, errno,
+ strerror(errno));
return;
}
- LOG_VERBOSE("%s() - polling fd %d, revents: 0x%x, ret %d", __func__, pfd.fd,
- pfd.revents, ret);
+ log::verbose("polling fd {}, revents: 0x{:x}, ret {}", pfd.fd, pfd.revents,
+ ret);
if (pfd.revents & (POLLERR | POLLHUP)) {
- LOG_WARN("%s() - POLLERR or POLLHUP. Exiting", __func__);
+ log::warn("POLLERR or POLLHUP. Exiting");
return;
}
@@ -372,12 +375,12 @@
static int uipc_close_ch_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) {
int wakeup = 0;
- LOG_DEBUG("CLOSE CHANNEL %d", ch_id);
+ log::debug("CLOSE CHANNEL {}", ch_id);
if (ch_id >= UIPC_CH_NUM) return -1;
if (uipc.ch[ch_id].srvfd != UIPC_DISCONNECTED) {
- LOG_DEBUG("CLOSE SERVER (FD %d)", uipc.ch[ch_id].srvfd);
+ log::debug("CLOSE SERVER (FD {})", uipc.ch[ch_id].srvfd);
close(uipc.ch[ch_id].srvfd);
FD_CLR(uipc.ch[ch_id].srvfd, &uipc.active_set);
uipc.ch[ch_id].srvfd = UIPC_DISCONNECTED;
@@ -385,7 +388,7 @@
}
if (uipc.ch[ch_id].fd != UIPC_DISCONNECTED) {
- LOG_DEBUG("CLOSE CONNECTION (FD %d)", uipc.ch[ch_id].fd);
+ log::debug("CLOSE CONNECTION (FD {})", uipc.ch[ch_id].fd);
close(uipc.ch[ch_id].fd);
FD_CLR(uipc.ch[ch_id].fd, &uipc.active_set);
uipc.ch[ch_id].fd = UIPC_DISCONNECTED;
@@ -403,7 +406,7 @@
void uipc_close_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) {
if (uipc.ch[ch_id].srvfd == UIPC_DISCONNECTED) {
- LOG_DEBUG("CHANNEL %d ALREADY CLOSED", ch_id);
+ log::debug("CHANNEL {} ALREADY CLOSED", ch_id);
return;
}
@@ -425,12 +428,12 @@
result = select(uipc.max_fd + 1, &uipc.read_set, NULL, NULL, NULL);
if (result == 0) {
- LOG_DEBUG("select timeout");
+ log::debug("select timeout");
continue;
}
if (result < 0) {
if (errno != EINTR) {
- LOG_DEBUG("select failed %s", strerror(errno));
+ log::debug("select failed {}", strerror(errno));
}
continue;
}
@@ -454,13 +457,13 @@
}
}
- LOG_DEBUG("UIPC READ THREAD EXITING");
+ log::debug("UIPC READ THREAD EXITING");
uipc_main_cleanup(uipc);
uipc.tid = 0;
- LOG_DEBUG("UIPC READ THREAD DONE");
+ log::debug("UIPC READ THREAD DONE");
return nullptr;
}
@@ -470,7 +473,7 @@
if (pthread_create(&uipc.tid, (const pthread_attr_t*)NULL, uipc_read_task,
&uipc) != 0) {
- LOG_ERROR("uipc_thread_create pthread_create failed:%d", errno);
+ log::error("uipc_thread_create pthread_create failed:{}", errno);
return -1;
}
@@ -504,7 +507,7 @@
******************************************************************************/
std::unique_ptr<tUIPC_STATE> UIPC_Init() {
std::unique_ptr<tUIPC_STATE> uipc = std::make_unique<tUIPC_STATE>();
- LOG_DEBUG("UIPC_Init");
+ log::debug("UIPC_Init");
std::lock_guard<std::recursive_mutex> lock(uipc->mutex);
@@ -525,7 +528,7 @@
******************************************************************************/
bool UIPC_Open(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, tUIPC_RCV_CBACK* p_cback,
const char* socket_path) {
- LOG_DEBUG("UIPC_Open : ch_id %d", ch_id);
+ log::debug("UIPC_Open : ch_id {}", ch_id);
std::lock_guard<std::recursive_mutex> lock(uipc.mutex);
@@ -534,7 +537,7 @@
}
if (uipc.ch[ch_id].srvfd != UIPC_DISCONNECTED) {
- LOG_DEBUG("CHANNEL %d ALREADY OPEN", ch_id);
+ log::debug("CHANNEL {} ALREADY OPEN", ch_id);
return 0;
}
@@ -553,7 +556,7 @@
**
******************************************************************************/
void UIPC_Close(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) {
- LOG_DEBUG("UIPC_Close : ch_id %d", ch_id);
+ log::debug("UIPC_Close : ch_id {}", ch_id);
/* special case handling uipc shutdown */
if (ch_id != UIPC_CH_ID_ALL) {
@@ -562,9 +565,9 @@
return;
}
- LOG_DEBUG("UIPC_Close : waiting for shutdown to complete");
+ log::debug("UIPC_Close : waiting for shutdown to complete");
uipc_stop_main_server_thread(uipc);
- LOG_DEBUG("UIPC_Close : shutdown complete");
+ log::debug("UIPC_Close : shutdown complete");
}
/*******************************************************************************
@@ -579,14 +582,14 @@
bool UIPC_Send(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id,
UNUSED_ATTR uint16_t msg_evt, const uint8_t* p_buf,
uint16_t msglen) {
- LOG_VERBOSE("UIPC_Send : ch_id:%d %d bytes", ch_id, msglen);
+ log::verbose("UIPC_Send : ch_id:{} {} bytes", ch_id, msglen);
std::lock_guard<std::recursive_mutex> lock(uipc.mutex);
ssize_t ret;
OSI_NO_INTR(ret = write(uipc.ch[ch_id].fd, p_buf, msglen));
if (ret < 0) {
- LOG_ERROR("failed to write (%s)", strerror(errno));
+ log::error("failed to write ({})", strerror(errno));
return false;
}
@@ -606,7 +609,7 @@
uint32_t UIPC_Read(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint8_t* p_buf,
uint32_t len) {
if (ch_id >= UIPC_CH_NUM) {
- LOG_ERROR("UIPC_Read : invalid ch id %d", ch_id);
+ log::error("UIPC_Read : invalid ch id {}", ch_id);
return 0;
}
@@ -615,7 +618,7 @@
struct pollfd pfd;
if (fd == UIPC_DISCONNECTED) {
- LOG_ERROR("UIPC_Read : channel %d closed", ch_id);
+ log::error("UIPC_Read : channel {} closed", ch_id);
return 0;
}
@@ -629,17 +632,17 @@
int poll_ret;
OSI_NO_INTR(poll_ret = poll(&pfd, 1, uipc.ch[ch_id].read_poll_tmo_ms));
if (poll_ret == 0) {
- LOG_WARN("poll timeout (%d ms)", uipc.ch[ch_id].read_poll_tmo_ms);
+ log::warn("poll timeout ({} ms)", uipc.ch[ch_id].read_poll_tmo_ms);
break;
}
if (poll_ret < 0) {
- LOG_ERROR("%s(): poll() failed: return %d errno %d (%s)", __func__,
- poll_ret, errno, strerror(errno));
+ log::error("poll() failed: return {} errno {} ({})", poll_ret, errno,
+ strerror(errno));
break;
}
if (pfd.revents & (POLLHUP | POLLNVAL)) {
- LOG_WARN("poll : channel detached remotely");
+ log::warn("poll : channel detached remotely");
std::lock_guard<std::recursive_mutex> lock(uipc.mutex);
uipc_close_locked(uipc, ch_id);
return 0;
@@ -649,14 +652,14 @@
OSI_NO_INTR(n = recv(fd, p_buf + n_read, len - n_read, 0));
if (n == 0) {
- LOG_WARN("UIPC_Read : channel detached remotely");
+ log::warn("UIPC_Read : channel detached remotely");
std::lock_guard<std::recursive_mutex> lock(uipc.mutex);
uipc_close_locked(uipc, ch_id);
return 0;
}
if (n < 0) {
- LOG_WARN("UIPC_Read : read failed (%s)", strerror(errno));
+ log::warn("UIPC_Read : read failed ({})", strerror(errno));
return 0;
}
@@ -678,7 +681,7 @@
bool UIPC_Ioctl(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id, uint32_t request,
void* param) {
- LOG_DEBUG("#### UIPC_Ioctl : ch_id %d, request %d ####", ch_id, request);
+ log::debug("#### UIPC_Ioctl : ch_id {}, request {} ####", ch_id, request);
std::lock_guard<std::recursive_mutex> lock(uipc.mutex);
switch (request) {
@@ -699,12 +702,12 @@
case UIPC_SET_READ_POLL_TMO:
uipc.ch[ch_id].read_poll_tmo_ms = (intptr_t)param;
- LOG_DEBUG("UIPC_SET_READ_POLL_TMO : CH %d, TMO %d ms", ch_id,
- uipc.ch[ch_id].read_poll_tmo_ms);
+ log::debug("UIPC_SET_READ_POLL_TMO : CH {}, TMO {} ms", ch_id,
+ uipc.ch[ch_id].read_poll_tmo_ms);
break;
default:
- LOG_DEBUG("UIPC_Ioctl : request not handled (%d)", request);
+ log::debug("UIPC_Ioctl : request not handled ({})", request);
break;
}
diff --git a/system/vendor_libs/Android.bp b/system/vendor_libs/Android.bp
index 1239ba8..c9adc29 100644
--- a/system/vendor_libs/Android.bp
+++ b/system/vendor_libs/Android.bp
@@ -6,7 +6,6 @@
// SPDX-license-identifier-Apache-2.0
default_applicable_licenses: ["system_bt_license"],
default_visibility: [
- "//device:__subpackages__",
"//packages/modules/Bluetooth:__subpackages__",
],
}
diff --git a/system/vendor_libs/linux/interface/bluetooth_hci.cc b/system/vendor_libs/linux/interface/bluetooth_hci.cc
index a437b6c..560e6a0 100644
--- a/system/vendor_libs/linux/interface/bluetooth_hci.cc
+++ b/system/vendor_libs/linux/interface/bluetooth_hci.cc
@@ -18,12 +18,12 @@
#include "bluetooth_hci.h"
#include <fcntl.h>
+#include <log/log.h>
#include <poll.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
-#include <utils/Log.h>
#include <cerrno>
diff --git a/system/vendor_libs/linux/interface/h4_protocol.cc b/system/vendor_libs/linux/interface/h4_protocol.cc
index 2ff11fe..6ba1664 100644
--- a/system/vendor_libs/linux/interface/h4_protocol.cc
+++ b/system/vendor_libs/linux/interface/h4_protocol.cc
@@ -14,14 +14,14 @@
// limitations under the License.
//
+#define LOG_TAG "android.hardware.bluetooth-hci-h4"
+
#include "h4_protocol.h"
-#define LOG_TAG "android.hardware.bluetooth-hci-h4"
-#include <android-base/logging.h>
#include <assert.h>
#include <fcntl.h>
+#include <log/log.h>
#include <sys/uio.h>
-#include <utils/Log.h>
namespace android {
namespace hardware {
diff --git a/system/vendor_libs/linux/interface/h4_protocol_unittest.cc b/system/vendor_libs/linux/interface/h4_protocol_unittest.cc
index 882b4b5..64f095c 100644
--- a/system/vendor_libs/linux/interface/h4_protocol_unittest.cc
+++ b/system/vendor_libs/linux/interface/h4_protocol_unittest.cc
@@ -31,7 +31,6 @@
#include <vector>
#include "async_fd_watcher.h"
-#include "log/log.h"
using android::hardware::bluetooth::async::AsyncFdWatcher;
using android::hardware::bluetooth::hci::H4Protocol;
diff --git a/system/vendor_libs/linux/interface/hci_packetizer.cc b/system/vendor_libs/linux/interface/hci_packetizer.cc
index f3460aa..aeccb06 100644
--- a/system/vendor_libs/linux/interface/hci_packetizer.cc
+++ b/system/vendor_libs/linux/interface/hci_packetizer.cc
@@ -19,7 +19,6 @@
#define LOG_TAG "android.hardware.bluetooth.hci_packetizer"
#include <dlfcn.h>
#include <fcntl.h>
-#include <log/log.h>
namespace {
diff --git a/system/vendor_libs/linux/interface/service.cc b/system/vendor_libs/linux/interface/service.cc
index 4efd5e7..ed18bd6 100644
--- a/system/vendor_libs/linux/interface/service.cc
+++ b/system/vendor_libs/linux/interface/service.cc
@@ -19,7 +19,7 @@
#include <android/hardware/bluetooth/1.1/IBluetoothHci.h>
#include <hidl/HidlSupport.h>
#include <hidl/HidlTransportSupport.h>
-#include <utils/Log.h>
+#include <log/log.h>
#include "bluetooth_hci.h"
diff --git a/tools/rootcanal/hal/bluetooth_hci.cc b/tools/rootcanal/hal/bluetooth_hci.cc
index d63b870..34cda65 100644
--- a/tools/rootcanal/hal/bluetooth_hci.cc
+++ b/tools/rootcanal/hal/bluetooth_hci.cc
@@ -24,7 +24,6 @@
#include <string.h>
#include "hci_internals.h"
-#include "log/log.h"
#include "model/devices/hci_device.h"
#include "model/devices/link_layer_socket_device.h"
#include "model/hci/hci_socket_transport.h"
diff --git a/tools/rootcanal/rust/Android.bp b/tools/rootcanal/rust/Android.bp
index 8b63450..1287188 100644
--- a/tools/rootcanal/rust/Android.bp
+++ b/tools/rootcanal/rust/Android.bp
@@ -31,7 +31,7 @@
"librand",
"libthiserror",
],
- include_dirs: ["include"],
+ export_include_dirs: ["include"],
}
genrule {