From 34a542ff71856945f52a7ef70fce10347e8850a5 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Wed, 6 Aug 2025 20:20:28 +0800 Subject: [PATCH 01/26] add l2cap Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I389135ddeded381300c6a2d7937e175707352eea --- .../inner/ipc/interface/i_bluetooth_socket.h | 1 + .../inner/ipc/src/bluetooth_socket_proxy.cpp | 1 + frameworks/inner/src/bluetooth_socket.cpp | 20 ++++++++---- .../napi/include/napi_bluetooth_spp_server.h | 1 + .../js/napi/include/napi_bluetooth_utils.h | 5 ++- .../src/socket/napi_bluetooth_spp_client.cpp | 20 ++++++++++-- .../src/socket/napi_bluetooth_spp_server.cpp | 32 ++++++++++++++++++- .../inner_api/include/bluetooth_socket.h | 12 +++++++ 8 files changed, 81 insertions(+), 11 deletions(-) diff --git a/frameworks/inner/ipc/interface/i_bluetooth_socket.h b/frameworks/inner/ipc/interface/i_bluetooth_socket.h index 338c8aa2..c33d25e3 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_socket.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_socket.h @@ -32,6 +32,7 @@ struct ListenSocketParam { int32_t securityFlag; int32_t type; sptr observer; + int32_t psm; }; struct ConnectSocketParam { diff --git a/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp index 946a20a9..49fa5734 100644 --- a/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp @@ -61,6 +61,7 @@ int BluetoothSocketProxy::Listen(ListenSocketParam ¶m, int &fd) CHECK_AND_RETURN_LOG_RET( data.WriteInt32(param.securityFlag), BT_ERR_IPC_TRANS_FAILED, "write param.securityFlag error"); CHECK_AND_RETURN_LOG_RET(data.WriteInt32(param.type), BT_ERR_IPC_TRANS_FAILED, "write param.type error"); + CHECK_AND_RETURN_LOG_RET(data.WriteInt32(param.psm), BT_ERR_IPC_TRANS_FAILED, "write param.psm error"); CHECK_AND_RETURN_LOG_RET( data.WriteRemoteObject(param.observer->AsObject()), BT_ERR_IPC_TRANS_FAILED, "write object errorr"); diff --git a/frameworks/inner/src/bluetooth_socket.cpp b/frameworks/inner/src/bluetooth_socket.cpp index 6db02798..2cfe8f86 100644 --- a/frameworks/inner/src/bluetooth_socket.cpp +++ b/frameworks/inner/src/bluetooth_socket.cpp @@ -569,7 +569,7 @@ bool ClientSocket::IsAllowSocketConnect(int socketType) } struct ServerSocket::impl { - impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt); + impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm); ~impl() { if (fd_ > 0) { @@ -604,7 +604,8 @@ struct ServerSocket::impl { .uuid = bluetooth::Uuid::ConvertFrom128Bits(uuid_.ConvertTo128Bits()), .securityFlag = (int32_t)getSecurityFlags(), .type = (int32_t)type_, - .observer = observer_ + .observer = observer_, + .psm = psm_ }; int ret = proxy->Listen(param, fd_); if (ret != BT_NO_ERROR) { @@ -821,6 +822,7 @@ struct ServerSocket::impl { bool encrypt_; int fd_; int socketStatus_; + int psm_; std::string name_ { "" }; @@ -834,15 +836,21 @@ struct ServerSocket::impl { std::atomic maxRxPacketSize_{ 0 }; }; -ServerSocket::impl::impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt) - : uuid_(uuid), type_(type), encrypt_(encrypt), fd_(-1), socketStatus_(SOCKET_INIT), name_(name) +ServerSocket::impl::impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm) + : uuid_(uuid), type_(type), encrypt_(encrypt), fd_(-1), socketStatus_(SOCKET_INIT), psm_(psm), name_(name) { - HILOGD("(4 parameters) starts"); + HILOGD("(5 parameters) starts"); observer_ = new BluetoothServerSocketObserverStub(); } +ServerSocket::ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm) + : pimpl(new ServerSocket::impl(name, uuid, type, encrypt, psm)) +{ + HILOGD("type:%{public}d encrypt:%{public}d psm:%{public}d", type, encrypt, psm); +} + ServerSocket::ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt) - : pimpl(new ServerSocket::impl(name, uuid, type, encrypt)) + : pimpl(new ServerSocket::impl(name, uuid, type, encrypt, -1)) { HILOGD("type:%{public}d encrypt:%{public}d", type, encrypt); } diff --git a/frameworks/js/napi/include/napi_bluetooth_spp_server.h b/frameworks/js/napi/include/napi_bluetooth_spp_server.h index 5ecbfe19..2b20619d 100644 --- a/frameworks/js/napi/include/napi_bluetooth_spp_server.h +++ b/frameworks/js/napi/include/napi_bluetooth_spp_server.h @@ -42,6 +42,7 @@ struct NapiSppServer { static napi_value SppCloseServerSocket(napi_env env, napi_callback_info info); static napi_value RegisterSocketObserver(napi_env env, napi_callback_info info); static napi_value DeRegisterSocketObserver(napi_env env, napi_callback_info info); + static napi_value getL2capPsm(napi_env env, napi_callback_info info); static std::map> serverMap; static int count; diff --git a/frameworks/js/napi/include/napi_bluetooth_utils.h b/frameworks/js/napi/include/napi_bluetooth_utils.h index 6f5287ff..da173ebd 100644 --- a/frameworks/js/napi/include/napi_bluetooth_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_utils.h @@ -87,6 +87,7 @@ struct SppOption { std::string uuid_ = ""; bool secure_ = false; BtSocketType type_; + int32_t psm_ = SPP_SOCKET_PSM_VALUE; }; const char * const REGISTER_STATE_CHANGE_TYPE = "stateChange"; @@ -410,7 +411,9 @@ enum MajorMinorClass { enum SppType { /** RFCOMM */ - SPP_RFCOMM = 0 + SPP_RFCOMM = 0, + SPP_L2CAP = 1, + SPP_L2CAP_BLE = 2, }; enum PlayingState { diff --git a/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp b/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp index abd062da..15cd9b0f 100644 --- a/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp +++ b/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp @@ -56,7 +56,10 @@ static napi_status CheckSppConnectParams( callbackInfo->env_ = env; callbackInfo->sppOption_ = GetSppOptionFromJS(env, argv[PARAM1]); - NAPI_BT_RETURN_IF((callbackInfo->sppOption_ == nullptr), "GetSppOptionFromJS faild.", napi_invalid_arg); + NAPI_BT_RETURN_IF((callbackInfo->sppOption_ == nullptr), "GetSppOptionFromJS failed.", napi_invalid_arg); + NAPI_BT_RETURN_IF(( + (callbackInfo->sppOption_->type_ == TYPE_L2CAP || callbackInfo->sppOption_->type_ == TYPE_L2CAP_LE) && + callbackInfo->sppOption_->psm_ <= 0), "GetSppOptionFromJS failed", napi_invalid_arg); callbackInfo->deviceId_ = deviceId; napi_value promise = nullptr; @@ -89,7 +92,7 @@ std::shared_ptr GetSppOptionFromJS(napi_env env, napi_value object) napi_create_string_utf8(env, "uuid", NAPI_AUTO_LENGTH, &propertyNameValue); napi_get_property(env, object, propertyNameValue, &value); bool isSuccess = ParseString(env, sppOption->uuid_, value); - if (!isSuccess || (!IsValidUuid(sppOption->uuid_))) { + if (sppOption->uuid_ != "" && (!isSuccess || (!IsValidUuid(sppOption->uuid_)))) { HILOGE("Parse UUID faild."); return nullptr; } @@ -107,6 +110,17 @@ std::shared_ptr GetSppOptionFromJS(napi_env env, napi_value object) sppOption->type_ = BtSocketType(type); HILOGI("uuid: %{public}s, secure: %{public}d, type: %{public}d", sppOption->uuid_.c_str(), sppOption->secure_, sppOption->type_); + if (sppOption->type_ == TYPE_RFCOMM && sppOption->uuid_ == "") { + HILOGE("RFCOMM type but uuid is nullptr"); + return nullptr; + } + int psm = -1; + napi_create_string_utf8(env, "psm", NAPI_AUTO_LENGTH, &propertyNameValue); + napi_get_property(env, object, propertyNameValue, &value); + ParseInt32(env, psm, value); + sppOption->psm_ = psm; + HILOGI("uuid: %{public}s, secure: %{public}d, type: %{public}d, psm: %{public}d", + sppOption->uuid_.c_str(), sppOption->secure_, sppOption->type_, sppOption->psm_); return sppOption; } @@ -135,7 +149,7 @@ napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) UUID::FromString(callbackInfo->sppOption_->uuid_), callbackInfo->sppOption_->type_, callbackInfo->sppOption_->secure_); HILOGI("SppConnect client_ constructed"); - callbackInfo->errorCode_ = callbackInfo->client_->Connect(SPP_SOCKET_PSM_VALUE); + callbackInfo->errorCode_ = callbackInfo->client_->Connect(callbackInfo->sppOption_->psm_); if (callbackInfo->errorCode_ == BtStatus::BT_SUCCESS) { HILOGI("SppConnect successfully"); callbackInfo->errorCode_ = CODE_SUCCESS; diff --git a/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp b/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp index ae275f01..60c3ee43 100644 --- a/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp +++ b/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp @@ -40,6 +40,7 @@ void DefineSppFunctions(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("sppCloseClientSocket", NapiSppClient::SppCloseClientSocket), DECLARE_NAPI_FUNCTION("sppWrite", NapiSppClient::SppWrite), DECLARE_NAPI_FUNCTION("getDeviceId", NapiSppClient::GetDeviceId), + DECLARE_NAPI_FUNCTION("getL2capPsm", NapiSppServer::getL2capPsm), #ifdef BLUETOOTH_API_SINCE_10 DECLARE_NAPI_FUNCTION("on", NapiSppServer::RegisterSocketObserver), DECLARE_NAPI_FUNCTION("off", NapiSppServer::DeRegisterSocketObserver), @@ -67,6 +68,8 @@ napi_value SppTypeInit(napi_env env) napi_value sppType = nullptr; napi_create_object(env, &sppType); SetNamedPropertyByInteger(env, sppType, SppType::SPP_RFCOMM, "SPP_RFCOMM"); + SetNamedPropertyByInteger(env, sppType, SppType::SPP_L2CAP, "SPP_L2CAP"); + SetNamedPropertyByInteger(env, sppType, SppType::SPP_L2CAP_BLE, "SPP_L2CAP_BLE"); return sppType; } @@ -137,7 +140,7 @@ napi_value NapiSppServer::SppListen(napi_env env, napi_callback_info info) SppListenCallbackInfo* callbackInfo = static_cast(data); callbackInfo->server_ = std::make_shared(callbackInfo->name_, UUID::FromString(callbackInfo->sppOption_->uuid_), callbackInfo->sppOption_->type_, - callbackInfo->sppOption_->secure_); + callbackInfo->sppOption_->secure_, callbackInfo->sppOption_->psm_); int errorCode = callbackInfo->server_->Listen(); HILOGI("SppListen ServerSocket constructor end"); if (callbackInfo->server_ ->GetStringTag() != "") { @@ -352,5 +355,32 @@ napi_value NapiSppServer::SppCloseServerSocket(napi_env env, napi_callback_info return NapiGetBooleanRet(env, isOK); } + +static napi_status CheckSppFdParams(napi_env env, napi_callback_info info, int &id) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {0}; + + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Requires 1 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM0]), "Wrong argument type. int expected.", napi_invalid_arg); + return napi_ok; +} + +napi_value NapiSppServer::getL2capPsm(napi_env env, napi_callback_info info) +{ + HILOGD("enter"); + int id = -1; + auto status = CheckSppFdParams(env, info, id); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + auto server = serverMap[id]; + NAPI_BT_ASSERT_RETURN_UNDEF(env, server != nullptr, BT_ERR_INVALID_PARAM); + NAPI_BT_ASSERT_RETURN_UNDEF(env, server->server_ != nullptr, BT_ERR_INVALID_PARAM); + int32_t l2capPsm = server->server_->GetL2capPsm(); + napi_value result = nullptr; + napi_create_int32(env, l2capPsm, &result); + return result; +} + } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_socket.h b/interfaces/inner_api/include/bluetooth_socket.h index 906f11f5..d44bbc33 100644 --- a/interfaces/inner_api/include/bluetooth_socket.h +++ b/interfaces/inner_api/include/bluetooth_socket.h @@ -287,6 +287,18 @@ public: */ ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt); + /** + * @brief A constructor used to create an ServerSocket instance. + * + * @param name Server name. + * @param uuid Uuid. + * @param type Socket type. + * @param encrypt Remote device auth and encrypt connection. + * @param psm L2CAP socket psm. + * @since 20 + */ + ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm); + /** * @brief Destroy the ServerSocket object. * -- Gitee From 3d19547483d31c5439f857ba93064011295bc134 Mon Sep 17 00:00:00 2001 From: hui Date: Thu, 14 Aug 2025 11:24:49 +0800 Subject: [PATCH 02/26] bugfix Signed-off-by: hui --- frameworks/inner/src/bluetooth_socket.cpp | 21 ------------------- .../src/bluetooth_socket_outputstream.cpp | 19 ++++++++++++++--- .../js/napi/include/napi_ha_event_utils.h | 2 +- .../napi/src/common/napi_ha_event_utils.cpp | 2 +- .../inner_api/include/bluetooth_gatt_client.h | 2 +- 5 files changed, 19 insertions(+), 27 deletions(-) diff --git a/frameworks/inner/src/bluetooth_socket.cpp b/frameworks/inner/src/bluetooth_socket.cpp index 6db02798..48ba830d 100644 --- a/frameworks/inner/src/bluetooth_socket.cpp +++ b/frameworks/inner/src/bluetooth_socket.cpp @@ -90,7 +90,6 @@ struct ClientSocket::impl { std::shared_ptr observer); ~impl() { - HILOGI("ClientSocket::impl ~impl"); if (fd_ > 0) { shutdown(fd_, SHUT_RD); shutdown(fd_, SHUT_WR); @@ -422,14 +421,12 @@ ClientSocket::~ClientSocket() bool ClientSocket::Init() { HILOGI("ClientSocket Init"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, false, "pimpl is nullptr!"); return pimpl->Init(weak_from_this()); } int ClientSocket::Connect(int psm) { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); if (pimpl->type_ == TYPE_L2CAP_LE) { CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_ERR_INVALID_STATE, "BLE is not TURN_ON"); } else { @@ -484,21 +481,18 @@ int ClientSocket::Connect(int psm) void ClientSocket::Close() { HILOGD("enter"); - CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is nullptr!"); return pimpl->Close(); } std::shared_ptr ClientSocket::GetInputStream() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, nullptr, "pimpl is nullptr!"); return pimpl->GetInputStream(); } std::shared_ptr ClientSocket::GetOutputStream() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, nullptr, "pimpl is nullptr!"); return pimpl->GetOutputStream(); } @@ -511,48 +505,41 @@ BluetoothRemoteDevice &ClientSocket::GetRemoteDevice() bool ClientSocket::IsConnected() const { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, false, "pimpl is nullptr!"); return pimpl->IsConnected(); } int ClientSocket::SetBufferSize(int bufferSize) { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, false, "pimpl is nullptr!"); return pimpl->SetBufferSize(bufferSize); } int ClientSocket::GetSocketFd() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); return pimpl->fd_; } int ClientSocket::GetL2capPsm() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("psm:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } int ClientSocket::GetRfcommScn() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("scn:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } uint32_t ClientSocket::GetMaxTransmitPacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxTransmitPacketSize:%{public}d", pimpl->maxTxPacketSize_.load()); return pimpl->maxTxPacketSize_; } uint32_t ClientSocket::GetMaxReceivePacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxReceivePacketSize:%{public}d", pimpl->maxRxPacketSize_.load()); return pimpl->maxRxPacketSize_; } @@ -853,21 +840,18 @@ ServerSocket::~ServerSocket() int ServerSocket::Listen() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); return pimpl->Listen(); } std::shared_ptr ServerSocket::Accept(int timeout) { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, nullptr, "pimpl is nullptr!"); return pimpl->Accept(timeout); } void ServerSocket::Close() { HILOGD("enter"); - CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is nullptr!"); return pimpl->Close(); } @@ -879,35 +863,30 @@ const std::string &ServerSocket::GetStringTag() int ServerSocket::GetL2capPsm() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("psm:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } int ServerSocket::GetRfcommScn() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("scn:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } uint32_t ServerSocket::GetMaxTransmitPacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxTransmitPacketSize:%{public}d", pimpl->maxTxPacketSize_.load()); return pimpl->maxTxPacketSize_; } uint32_t ServerSocket::GetMaxReceivePacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxReceivePacketSize:%{public}d", pimpl->maxRxPacketSize_.load()); return pimpl->maxRxPacketSize_; } int ServerSocket::GetSocketFd() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); return pimpl->fd_; } diff --git a/frameworks/inner/src/bluetooth_socket_outputstream.cpp b/frameworks/inner/src/bluetooth_socket_outputstream.cpp index 84097574..a7715c64 100644 --- a/frameworks/inner/src/bluetooth_socket_outputstream.cpp +++ b/frameworks/inner/src/bluetooth_socket_outputstream.cpp @@ -18,6 +18,7 @@ #include #include +#include #include "bluetooth_socket_outputstream.h" #include "bluetooth_log.h" #include "sys/socket.h" @@ -26,7 +27,15 @@ namespace OHOS { namespace Bluetooth { +static constexpr int32_t SOCKET_SEND_TIME_THRESHOLD = 1000; // 1000ms static constexpr int32_t SOCKET_PACKET_HEAD_LENGTH = 1512; +static int64_t GetNowTimestamp(void) +{ + struct timeval tv; + gettimeofday(&tv, nullptr); + int64_t timestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; + return timestamp; +} static constexpr int32_t AAM_UID = 7878; static constexpr int32_t AAM_BAD_RET = -978974; static constexpr int32_t SOFTBUS_UID = 1024; @@ -52,7 +61,7 @@ int OutputStream::Write(const uint8_t *buf, size_t length) if (sockOptRet != -1 && ioctlRet != -1 && static_cast(bufSize) > bytesInBuffer) { // -1代表无权限获取发送队列大小 // 该方法是跟踪send前socket发送通道是否占满导致发包阻塞 unsigned long availableLength = static_cast(bufSize) - bytesInBuffer; - int32_t sendLength = static_cast (length) + SOCKET_PACKET_HEAD_LENGTH; + int32_t sendLength = static_cast(length) + SOCKET_PACKET_HEAD_LENGTH; if (availableLength < static_cast(sendLength)) { HILOGW("send queue is full, availableLength is %{public}lu, sendlength is %{public}d", availableLength, sendLength); @@ -73,13 +82,17 @@ int OutputStream::Write(const uint8_t *buf, size_t length) } setTimeoutFlag_ = true; } - + int64_t beginTimestamp = GetNowTimestamp(); auto ret = send(socketFd_, buf, length, MSG_NOSIGNAL); + int64_t endTimestamp = GetNowTimestamp(); + if (endTimestamp - beginTimestamp > SOCKET_SEND_TIME_THRESHOLD) { + HILOGE("socket send time %{public}" PRId64, endTimestamp - beginTimestamp); + } HILOGD("ret: %{public}zd", ret); if (ret <= 0) { - setTimeoutFlag_ == false; + setTimeoutFlag_ = false; HILOGE("socket write exception! ret:%{public}zd errno:%{public}d", ret, errno); } return ret; diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h index 93266fe5..70f2832d 100644 --- a/frameworks/js/napi/include/napi_ha_event_utils.h +++ b/frameworks/js/napi/include/napi_ha_event_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (C) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved. + * Copyright (C) Huawei Device Co., Ltd. 2025-2025. All rights reserved. * 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 diff --git a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp index 20f0aa30..c40ed339 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved. + * Copyright (C) Huawei Device Co., Ltd. 2025-2025. All rights reserved. * 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 diff --git a/interfaces/inner_api/include/bluetooth_gatt_client.h b/interfaces/inner_api/include/bluetooth_gatt_client.h index edff2a0c..9e03b67a 100644 --- a/interfaces/inner_api/include/bluetooth_gatt_client.h +++ b/interfaces/inner_api/include/bluetooth_gatt_client.h @@ -100,7 +100,7 @@ public: /** * @brief The function to OnCharacteristicWriteResult. * - * @param characteristic Characteristic object. + * @param characteristic Characteristic object. The value attribute is the initial value 0. * @param ret ret of GattClientCallback. * @since 6 * -- Gitee From f8686d388faee727d09053c26a4583ac722a9631 Mon Sep 17 00:00:00 2001 From: lee Date: Mon, 18 Aug 2025 16:45:31 +0800 Subject: [PATCH 03/26] Add multi switch Signed-off-by: lee Change-Id: Ifc1416ffef8f2055226794477ce386f3e76e4885 --- frameworks/inner/ipc/common/bt_def.h | 6 +++ .../include/bluetooth_host_observer_stub.h | 2 + .../inner/ipc/include/bluetooth_host_proxy.h | 6 +-- .../bluetooth_service_ipc_interface_code.h | 1 + .../inner/ipc/interface/i_bluetooth_host.h | 6 +-- .../ipc/interface/i_bluetooth_host_observer.h | 1 + .../ipc/src/bluetooth_host_observer_stub.cpp | 11 +++++ .../inner/ipc/src/bluetooth_host_proxy.cpp | 15 ++++-- frameworks/inner/src/bluetooth_host.cpp | 49 +++++++++++++------ .../inner/src/bluetooth_switch_module.cpp | 32 ++++++------ .../inner/src/bluetooth_switch_module.h | 14 +++--- .../napi/src/access/napi_bluetooth_access.cpp | 4 +- .../inner_api/include/bluetooth_errorcode.h | 1 + interfaces/inner_api/include/bluetooth_host.h | 13 +++-- 14 files changed, 109 insertions(+), 52 deletions(-) diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index c455c1e7..a565fd42 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -1800,6 +1800,12 @@ enum BluetoothSwitchState { STATE_HALF, }; +enum BluetoothTransferredSwitchAction { + TRANS_ACTION_ENABLE_BLUETOOTH = 0, + TRANS_ACTION_DISABLE_BLUETOOTH, + TRANS_ACTION_ENABLE_BLUETOOTH_TO_RESTRICT_MODE, +}; + enum ControlType { PLAY = 0, VIBRATE = 1, diff --git a/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h b/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h index 5a76da0a..75bd63ae 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h +++ b/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h @@ -51,6 +51,8 @@ private: MessageParcel &data, MessageParcel &reply); static int32_t OnBluetoothStateChangedInner(BluetoothHostObserverStub *stub, MessageParcel &data, MessageParcel &reply); + static int32_t OnBluetoothSwitchActionInner(BluetoothHostObserverStub *stub, + MessageParcel &data, MessageParcel &reply); static int32_t OnBluetoothRefusePolicyChangedInner(BluetoothHostObserverStub *stub, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/inner/ipc/include/bluetooth_host_proxy.h b/frameworks/inner/ipc/include/bluetooth_host_proxy.h index 5e71b4d6..0c76674b 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_host_proxy.h @@ -34,7 +34,7 @@ public: void RegisterObserver(const sptr &observer) override; void DeregisterObserver(const sptr &observer) override; int32_t EnableBt() override; - int32_t DisableBt(bool isAsync) override; + int32_t DisableBt(bool isAsync, const std::string &callingName) override; int32_t SatelliteControl(int type, int state) override; sptr GetProfile(const std::string &name) override; sptr GetBleRemote(const std::string &name) override; @@ -42,7 +42,7 @@ public: int32_t GetBtState(int &state) override; int32_t GetLocalAddress(std::string &addr) override; int32_t DisableBle() override; - int32_t EnableBle(bool noAutoConnect, bool isAsync) override; + int32_t EnableBle(bool noAutoConnect, bool isAsync, const std::string &callingName) override; std::vector GetProfileList() override; int32_t GetMaxNumConnectedAudioDevices() override; int32_t GetBtConnectionState(int &state) override; @@ -109,7 +109,7 @@ public: int32_t SetVirtualAutoConnectType(const std::string &address, int connType, int businessType) override; int32_t SetFastScanLevel(int level) override; void UpdateVirtualDevice(int32_t action, const std::string &address) override; - int32_t EnableBluetoothToRestrictMode(void) override; + int32_t EnableBluetoothToRestrictMode(const std::string &callingName) override; int32_t ControlDeviceAction(const std::string &deviceId, uint32_t controlType, uint32_t controlTypeVal, uint32_t controlObject) override; int32_t GetLastConnectionTime(const std::string &address, int64_t &connectionTime) override; diff --git a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h index 51975363..6ce3a02d 100644 --- a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h +++ b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h @@ -196,6 +196,7 @@ enum BluetoothHostObserverInterfaceCode { BT_HOST_OBSERVER_DEVICE_ADDR_CHANGED, BT_HOST_OBSERVER_STATE_CHANGE_V2, BT_HOST_OBSERVER_REFUSE_POLICY_CHANGE, + BT_HOST_OBSERVER_SWITCH_ACTION_TRANSFER, // The last code, if you want to add a new code, please add it before this BT_HOST_OBSERVER_BUTT }; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_host.h b/frameworks/inner/ipc/interface/i_bluetooth_host.h index 878b606b..245b3170 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host.h @@ -60,7 +60,7 @@ public: virtual void RegisterObserver(const sptr &observer) = 0; virtual void DeregisterObserver(const sptr &observer) = 0; virtual int32_t EnableBt() = 0; - virtual int32_t DisableBt(bool isAsync) = 0; + virtual int32_t DisableBt(bool isAsync, const std::string &callingName) = 0; virtual int32_t SatelliteControl(int type, int state) = 0; virtual sptr GetProfile(const std::string &name) = 0; virtual sptr GetBleRemote(const std::string &name) = 0; @@ -68,7 +68,7 @@ public: virtual int32_t GetBtState(int &state) = 0; virtual int32_t GetLocalAddress(std::string &addr) = 0; virtual int32_t DisableBle() = 0; - virtual int32_t EnableBle(bool noAutoConnect, bool isAsync) = 0; + virtual int32_t EnableBle(bool noAutoConnect, bool isAsync, const std::string &callingName) = 0; virtual std::vector GetProfileList() = 0; virtual int32_t GetMaxNumConnectedAudioDevices() = 0; virtual int32_t GetBtConnectionState(int &state) = 0; @@ -136,7 +136,7 @@ public: virtual int32_t SetVirtualAutoConnectType(const std::string &address, int connType, int businessType) = 0; virtual int32_t SetFastScanLevel(int level) = 0; virtual void UpdateVirtualDevice(int32_t action, const std::string &address) = 0; - virtual int32_t EnableBluetoothToRestrictMode(void) = 0; + virtual int32_t EnableBluetoothToRestrictMode(const std::string &callingName) = 0; virtual int32_t ControlDeviceAction(const std::string &deviceId, uint32_t controlType, uint32_t controlTypeVal, uint32_t controlObject) = 0; virtual int32_t GetLastConnectionTime(const std::string &address, int64_t &connectionTime) = 0; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h b/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h index a92ce1f3..4c54492e 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h @@ -39,6 +39,7 @@ public: virtual void OnDeviceNameChanged(const std::string &deviceName) = 0; virtual void OnDeviceAddrChanged(const std::string &address) = 0; virtual void OnBluetoothStateChanged(int32_t state) = 0; + virtual void OnBluetoothSwitchAction(int32_t action, const std::string &callingName) = 0; virtual void OnRefusePolicyChanged(const int32_t pid, const int64_t prohibitedSecondsTime) = 0; }; } // namespace Bluetooth diff --git a/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp b/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp index 3251493c..a423022f 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp @@ -42,6 +42,8 @@ BluetoothHostObserverStub::BluetoothHostObserverStub() BluetoothHostObserverStub::OnDeviceAddrChangedInner; memberFuncMap_[static_cast(BluetoothHostObserverInterfaceCode::BT_HOST_OBSERVER_STATE_CHANGE_V2)] = BluetoothHostObserverStub::OnBluetoothStateChangedInner; + memberFuncMap_[static_cast(BluetoothHostObserverInterfaceCode::BT_HOST_OBSERVER_SWITCH_ACTION_TRANSFER)] = + BluetoothHostObserverStub::OnBluetoothSwitchActionInner; memberFuncMap_[static_cast(BluetoothHostObserverInterfaceCode::BT_HOST_OBSERVER_REFUSE_POLICY_CHANGE)] = BluetoothHostObserverStub::OnBluetoothRefusePolicyChangedInner; } @@ -187,6 +189,15 @@ int32_t BluetoothHostObserverStub::OnBluetoothStateChangedInner(BluetoothHostObs return NO_ERROR; } +int32_t BluetoothHostObserverStub::OnBluetoothSwitchActionInner(BluetoothHostObserverStub *stub, + MessageParcel &data, MessageParcel &reply) +{ + int32_t action = data.ReadInt32(); + std::string name = data.ReadString(); + stub->OnBluetoothSwitchAction(action, name); + return NO_ERROR; +} + int32_t BluetoothHostObserverStub::OnBluetoothRefusePolicyChangedInner( BluetoothHostObserverStub *stub, MessageParcel &data, MessageParcel &reply) { diff --git a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp index 85ca100d..850ff8cc 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -85,7 +85,7 @@ int32_t BluetoothHostProxy::EnableBt() return reply.ReadInt32(); } -int32_t BluetoothHostProxy::DisableBt(bool isAsync) +int32_t BluetoothHostProxy::DisableBt(bool isAsync, const std::string &callingName) { HILOGI("BluetoothHostProxy::DisableBt starts"); MessageParcel data; @@ -97,6 +97,9 @@ int32_t BluetoothHostProxy::DisableBt(bool isAsync) HILOGE("BluetoothHostProxy::DisableBt WriteBool isAsync error"); return BT_ERR_IPC_TRANS_FAILED; } + if (!data.WriteString(callingName)) { + return BT_ERR_IPC_TRANS_FAILED; + } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; @@ -243,7 +246,7 @@ int32_t BluetoothHostProxy::DisableBle() return reply.ReadInt32(); } -int32_t BluetoothHostProxy::EnableBle(bool noAutoConnect, bool isAsync) +int32_t BluetoothHostProxy::EnableBle(bool noAutoConnect, bool isAsync, const std::string &callingName) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { @@ -258,6 +261,9 @@ int32_t BluetoothHostProxy::EnableBle(bool noAutoConnect, bool isAsync) HILOGE("BluetoothHostProxy::EnableBle WriteBool isAsync error"); return BT_ERR_IPC_TRANS_FAILED; } + if (!data.WriteString(callingName)) { + return BT_ERR_IPC_TRANS_FAILED; + } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; @@ -1764,13 +1770,16 @@ void BluetoothHostProxy::UpdateVirtualDevice(int32_t action, const std::string & return; } -int32_t BluetoothHostProxy::EnableBluetoothToRestrictMode(void) +int32_t BluetoothHostProxy::EnableBluetoothToRestrictMode(const std::string &callingName) { MessageParcel data; CHECK_AND_RETURN_LOG_RET(data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor()), BT_ERR_IPC_TRANS_FAILED, "WriteInterfaceToken error"); MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; + if (!data.WriteString(callingName)) { + return BT_ERR_IPC_TRANS_FAILED; + } int32_t error = InnerTransact( BluetoothHostInterfaceCode::BT_ENABLE_BLUETOOTH_TO_RESTRICT_MODE, option, data, reply); CHECK_AND_RETURN_LOG_RET((error == BT_NO_ERROR), BT_ERR_INTERNAL_ERROR, "error: %{public}d", error); diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index 575293c2..dfdda385 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -145,6 +145,23 @@ public: } } + void OnBluetoothSwitchAction(int32_t action, const std::string &callingName) override + { + HILOGI("bluetooth switch action: %{public}d, callingName: %{public}s", action, callingName.c_str()); + std::lock_guard lock(host_.switchModuleMutex_); + CHECK_AND_RETURN_LOG(host_.switchModule_, "switchModule is nullptr"); + if (action == bluetooth::TRANS_ACTION_ENABLE_BLUETOOTH) { + host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH, callingName); + } + if (action == bluetooth::TRANS_ACTION_DISABLE_BLUETOOTH) { + host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, callingName); + } + if (action == bluetooth::TRANS_ACTION_ENABLE_BLUETOOTH_TO_RESTRICT_MODE) { + host_.switchModule_->ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE, callingName); + } + } + void OnDiscoveryStateChanged(int32_t status) override { HILOGD("enter, status: %{public}d", status); @@ -439,7 +456,7 @@ public: BluetoothSwitchAction() = default; ~BluetoothSwitchAction() override = default; - int EnableBluetooth(bool noAutoConnect, bool isAsync) override + int EnableBluetooth(bool noAutoConnect, std::string callingName, bool isAsync) override { CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(), BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !"); @@ -448,17 +465,17 @@ public: sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); - return proxy->EnableBle(noAutoConnect, isAsync); + return proxy->EnableBle(noAutoConnect, isAsync, callingName); } - int DisableBluetooth(bool isAsync) override + int DisableBluetooth(std::string callingName, bool isAsync) override { sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); - return proxy->DisableBt(isAsync); + return proxy->DisableBt(isAsync, callingName); } - int EnableBluetoothToRestrictMode(void) override + int EnableBluetoothToRestrictMode(std::string callingName) override { CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(), BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !"); @@ -467,7 +484,7 @@ public: sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); - return proxy->EnableBluetoothToRestrictMode(); + return proxy->EnableBluetoothToRestrictMode(callingName); } }; @@ -640,12 +657,12 @@ int BluetoothHost::EnableBt() return proxy->EnableBt(); } -int BluetoothHost::DisableBt(bool isAsync) +int BluetoothHost::DisableBt(std::string name, bool isAsync) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, isAsync); + return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, name, isAsync); } static void PublishBtSwitchRestrictBluetoothEvent(void) @@ -665,17 +682,18 @@ static void PublishBtSwitchRestrictBluetoothEvent(void) } } -int BluetoothHost::RestrictBluetooth() +int BluetoothHost::RestrictBluetooth(std::string name) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); PublishBtSwitchRestrictBluetoothEvent(); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - int ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH); + int ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, name); if (ret != BT_NO_ERROR) { return ret; } - ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE); + ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE, name); return ret; } @@ -790,12 +808,12 @@ BluetoothRemoteDevice BluetoothHost::GetRemoteDevice(const std::string &addr, in return remoteDevice; } -int BluetoothHost::EnableBle(bool isAsync) +int BluetoothHost::EnableBle(std::string name, bool isAsync) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH, isAsync); + return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH, name, isAsync); } int BluetoothHost::EnableBluetoothNoAutoConnect() @@ -814,12 +832,13 @@ int BluetoothHost::DisableBle() return proxy->DisableBle(); } -int BluetoothHost::EnableBluetoothToRestrictMode(void) +int BluetoothHost::EnableBluetoothToRestrictMode(std::string name) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE); + return pimpl->switchModule_->ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE, name); } bool BluetoothHost::IsBrEnabled() const diff --git a/frameworks/inner/src/bluetooth_switch_module.cpp b/frameworks/inner/src/bluetooth_switch_module.cpp index 2f9b30fd..2ce69d90 100644 --- a/frameworks/inner/src/bluetooth_switch_module.cpp +++ b/frameworks/inner/src/bluetooth_switch_module.cpp @@ -48,7 +48,8 @@ void BluetoothSwitchModule::LogBluetoothSwitchEvent(BluetoothSwitchEvent event) } } -int BluetoothSwitchModule::ProcessBluetoothSwitchEvent(BluetoothSwitchEvent event, bool isAsync) +int BluetoothSwitchModule::ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent event, std::string callingName, bool isAsync) { CHECK_AND_RETURN_LOG_RET(switchAction_, BT_ERR_INTERNAL_ERROR, "switchAction is nullptr"); @@ -56,11 +57,11 @@ int BluetoothSwitchModule::ProcessBluetoothSwitchEvent(BluetoothSwitchEvent even LogBluetoothSwitchEvent(event); switch (event) { case BluetoothSwitchEvent::ENABLE_BLUETOOTH: - return ProcessEnableBluetoothEvent(isAsync); + return ProcessEnableBluetoothEvent(callingName, isAsync); case BluetoothSwitchEvent::DISABLE_BLUETOOTH: - return ProcessDisableBluetoothEvent(isAsync); + return ProcessDisableBluetoothEvent(callingName, isAsync); case BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE: - return ProcessEnableBluetoothToRestrictModeEvent(); + return ProcessEnableBluetoothToRestrictModeEvent(callingName); case BluetoothSwitchEvent::BLUETOOTH_ON: return ProcessBluetoothOnEvent(); case BluetoothSwitchEvent::BLUETOOTH_OFF: @@ -107,38 +108,41 @@ int BluetoothSwitchModule::ProcessBluetoothSwitchAction( isBtSwitchProcessing_ = false; ffrtQueue_.cancel(taskTimeoutHandle_); } - // Considering interface compatibility, when a thiry party app invokes the Bluetooth switch interface, - // a dialog box is displayed, indicating that the call is success. - if (ret == BT_ERR_DIALOG_FOR_USER_CONFIRM) { + // Considering interface compatibility, + // 1) when a thiry party app invokes the Bluetooth switch interface, a dialog box is displayed, + // indicating that the call is success. + // 2) when the switch operation of the system application is transferred to another module, + // the interface call is considered successful. + if (ret == BT_ERR_DIALOG_FOR_USER_CONFIRM || ret == BT_ERR_SWITCH_OP_TRANSFERRED) { ret = BT_NO_ERROR; } return ret; } -int BluetoothSwitchModule::ProcessEnableBluetoothEvent(bool isAsync) +int BluetoothSwitchModule::ProcessEnableBluetoothEvent(const std::string &callingName, bool isAsync) { return ProcessBluetoothSwitchAction( - [this, isAsync]() { + [this, callingName, isAsync]() { bool noAutoConnect = noAutoConnect_.load(); if (noAutoConnect) { SetNoAutoConnect(false); } - return switchAction_->EnableBluetooth(noAutoConnect, isAsync); + return switchAction_->EnableBluetooth(noAutoConnect, callingName, isAsync); }, BluetoothSwitchEvent::ENABLE_BLUETOOTH); } -int BluetoothSwitchModule::ProcessDisableBluetoothEvent(bool isAsync) +int BluetoothSwitchModule::ProcessDisableBluetoothEvent(const std::string &callingName, bool isAsync) { return ProcessBluetoothSwitchAction( - [this, isAsync]() { return switchAction_->DisableBluetooth(isAsync); }, + [this, callingName, isAsync]() { return switchAction_->DisableBluetooth(callingName, isAsync); }, BluetoothSwitchEvent::DISABLE_BLUETOOTH); } -int BluetoothSwitchModule::ProcessEnableBluetoothToRestrictModeEvent(void) +int BluetoothSwitchModule::ProcessEnableBluetoothToRestrictModeEvent(const std::string &callingName) { return ProcessBluetoothSwitchAction( - [this]() { return switchAction_->EnableBluetoothToRestrictMode(); }, + [this, callingName]() { return switchAction_->EnableBluetoothToRestrictMode(callingName); }, BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE); } diff --git a/frameworks/inner/src/bluetooth_switch_module.h b/frameworks/inner/src/bluetooth_switch_module.h index 90191dc3..ccd9cb1d 100644 --- a/frameworks/inner/src/bluetooth_switch_module.h +++ b/frameworks/inner/src/bluetooth_switch_module.h @@ -30,9 +30,9 @@ public: IBluetoothSwitchAction() = default; virtual ~IBluetoothSwitchAction() = default; - virtual int EnableBluetooth(bool, bool) = 0; - virtual int DisableBluetooth(bool) = 0; - virtual int EnableBluetoothToRestrictMode(void) = 0; + virtual int EnableBluetooth(bool, std::string, bool) = 0; + virtual int DisableBluetooth(std::string, bool) = 0; + virtual int EnableBluetoothToRestrictMode(std::string) = 0; }; enum class BluetoothSwitchEvent : int { @@ -51,13 +51,13 @@ public: : ffrtQueue_("bt_switch"), switchAction_(std::move(switchAction)) {} ~BluetoothSwitchModule() = default; - int ProcessBluetoothSwitchEvent(BluetoothSwitchEvent event, bool isAsync = false); + int ProcessBluetoothSwitchEvent(BluetoothSwitchEvent event, std::string callingName = "", bool isAsync = false); void SetNoAutoConnect(bool noAutoConnect); private: - int ProcessEnableBluetoothEvent(bool isAsync = false); - int ProcessDisableBluetoothEvent(bool isAsync = false); - int ProcessEnableBluetoothToRestrictModeEvent(void); + int ProcessEnableBluetoothEvent(const std::string &callingName, bool isAsync); + int ProcessDisableBluetoothEvent(const std::string &callingName, bool isAsync); + int ProcessEnableBluetoothToRestrictModeEvent(const std::string &callingName); int ProcessBluetoothOnEvent(void); int ProcessBluetoothOffEvent(void); int ProcessBluetoothHalfEvent(void); diff --git a/frameworks/js/napi/src/access/napi_bluetooth_access.cpp b/frameworks/js/napi/src/access/napi_bluetooth_access.cpp index 62a02201..2ebae858 100644 --- a/frameworks/js/napi/src/access/napi_bluetooth_access.cpp +++ b/frameworks/js/napi/src/access/napi_bluetooth_access.cpp @@ -276,7 +276,7 @@ napi_value NapiAccess::EnableBluetoothAsync(napi_env env, napi_callback_info inf HILOGI("enter"); auto func = []() { bool isAsync = true; - int32_t ret = BluetoothHost::GetDefaultHost().EnableBle(isAsync); + int32_t ret = BluetoothHost::GetDefaultHost().EnableBle("", isAsync); HILOGI("EnableBluetoothAsync ret: %{public}d", ret); return NapiAsyncWorkRet(ret); }; @@ -291,7 +291,7 @@ napi_value NapiAccess::DisableBluetoothAsync(napi_env env, napi_callback_info in HILOGI("enter"); auto func = []() { bool isAsync = true; - int32_t ret = BluetoothHost::GetDefaultHost().DisableBt(isAsync); + int32_t ret = BluetoothHost::GetDefaultHost().DisableBt("", isAsync); HILOGI("DisableBluetoothAsync ret: %{public}d", ret); return NapiAsyncWorkRet(ret); }; diff --git a/interfaces/inner_api/include/bluetooth_errorcode.h b/interfaces/inner_api/include/bluetooth_errorcode.h index c40eadd8..f40d2017 100644 --- a/interfaces/inner_api/include/bluetooth_errorcode.h +++ b/interfaces/inner_api/include/bluetooth_errorcode.h @@ -88,6 +88,7 @@ enum BtErrCode { // errorCode for inner BT_ERR_DIALOG_FOR_USER_CONFIRM = -100, + BT_ERR_SWITCH_OP_TRANSFERRED = -101, }; } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 86f82950..9d5f73c8 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -341,12 +341,13 @@ public: /** * @brief Disable classic. * + * @param name Indicate the calling application to disable bluetooth. The default value is current application. * @param isAsync Indicate Async function flag. * @return Returns true if the operation is accepted; * returns false if the operation is rejected. * @since 6 */ - int DisableBt(bool isAsync = false); + int DisableBt(std::string name = "", bool isAsync = false); /** * @brief Get classic enable/disable state. @@ -404,12 +405,13 @@ public: /** * @brief Enable ble. * + * @param name Indicate the calling application to enable bluetooth. The default value is current application. * @param isAsync Indicate Async function flag. * @return Returns true if the operation is accepted; * returns false if the operation is rejected. * @since 6 */ - int EnableBle(bool isAsync = false); + int EnableBle(std::string name = "", bool isAsync = false); /** * @brief Enable bluetooth without AutoConnect. @@ -423,11 +425,12 @@ public: /** * @brief Enable bluetooth to restrict mode. * + * @param name Indicate the calling application to enable bluetooth. The default value is current application. * @return Returns BT_NO_ERROR if the operation is accepted; * returns others if the operation is rejected. * @since 12 */ - int EnableBluetoothToRestrictMode(void); + int EnableBluetoothToRestrictMode(std::string name = ""); /** * @brief Get br/edr enable/disable state. @@ -784,12 +787,12 @@ public: /** * @brief Restrict Bluetooth BR/EDR ability, just BLE ability available. * - * @param remoteAddr remote device addr. + * @param name Indicate the calling application to restrict bluetooth. The default value is current application. * @return Returns {@link BT_NO_ERROR} if the operation is successful; * returns an error code defined in {@link BtErrCode} otherwise. * @since 12 */ - int RestrictBluetooth(); + int RestrictBluetooth(std::string name = ""); /** * @brief update virtual device * -- Gitee From 86e8c74f8f1684b5a70c519d830ceb48aed30851 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=84=A4=E4=B8=96=E7=8C=AA?= <1546432050@qq.com> Date: Mon, 18 Aug 2025 14:09:42 +0000 Subject: [PATCH 04/26] update frameworks/inner/src/bluetooth_host.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 愤世猪 <1546432050@qq.com> --- frameworks/inner/src/bluetooth_host.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index dfdda385..d436324b 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1292,6 +1292,7 @@ void BluetoothHost::Close(void) { std::lock_guard lock(pimpl->switchModuleMutex_); pimpl->switchModule_ = nullptr; + BluetoothProfileManager::ClearSystemAbility(); } int32_t BluetoothHost::UpdateCloudBluetoothDevice(const std::vector &cloudDevices) -- Gitee From ef30da236b1c575acd6c3a9f105c34de479f8bad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Wed, 20 Aug 2025 03:31:18 +0000 Subject: [PATCH 05/26] add SetCallingPackageName api MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- .../inner/ipc/include/bluetooth_host_proxy.h | 1 + .../bluetooth_service_ipc_interface_code.h | 1 + .../inner/ipc/interface/i_bluetooth_host.h | 1 + .../inner/ipc/src/bluetooth_host_proxy.cpp | 19 +++++++++++++++++++ frameworks/inner/src/bluetooth_host.cpp | 8 ++++++++ interfaces/inner_api/include/bluetooth_host.h | 9 +++++++++ 6 files changed, 39 insertions(+) diff --git a/frameworks/inner/ipc/include/bluetooth_host_proxy.h b/frameworks/inner/ipc/include/bluetooth_host_proxy.h index 0c76674b..73ba1fdb 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_host_proxy.h @@ -123,6 +123,7 @@ public: int32_t GetCarKeyDfxData(std::string &dfxData) override; int32_t SetCarKeyCardData(const std::string &address, int32_t action) override; int32_t NotifyDialogResult(uint32_t dialogType, bool dialogResult) override; + void SetCallingPackageName(const std::string &address, const std::string &packageName) override; private: int32_t InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); static inline BrokerDelegator delegator_; diff --git a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h index 6ce3a02d..2dc8d621 100644 --- a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h +++ b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h @@ -294,6 +294,7 @@ enum BluetoothHostInterfaceCode { BT_GET_CAR_KEY_DFX_DATA, BT_SET_CAR_KEY_CARD_DATA, BT_NOTIFY_DIALOG_RESULT, + BT_SET_CALLING_PACKAGE_NAME, // The last code, if you want to add a new code, please add it before this BT_HOST_BUTT }; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_host.h b/frameworks/inner/ipc/interface/i_bluetooth_host.h index 245b3170..45ccf736 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host.h @@ -150,6 +150,7 @@ public: virtual int32_t GetCarKeyDfxData(std::string &dfxData) = 0; virtual int32_t SetCarKeyCardData(const std::string &address, int32_t action) = 0; virtual int32_t NotifyDialogResult(uint32_t dialogType, bool dialogResult) = 0; + virtual void SetCallingPackageName(const std::string &address, const std::string &packageName) = 0; }; } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp index 850ff8cc..7d9b6e69 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -2038,5 +2038,24 @@ int32_t BluetoothHostProxy::NotifyDialogResult(uint32_t dialogType, bool dialogR } return reply.ReadInt32(); } + +void BluetoothHostProxy::SetCallingPackageName(const std::string &address, const std::string &packageName) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { + HILOGE("BluetoothHostProxy::SetCallingPackageName WriteInterfaceToken error"); + return; + } + CHECK_AND_RETURN_LOG(data.WriteString(address), "write address error"); + CHECK_AND_RETURN_LOG(data.WriteString(packageName), "write packageName error"); + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + int32_t error = InnerTransact( + BluetoothHostInterfaceCode::BT_SET_CALLING_PACKAGE_NAME, option, data, reply); + if (error != BT_NO_ERROR) { + HILOGE("BluetoothHostProxy::SetCallingPackageName done fail error: %{public}d", error); + return; + } +} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index d436324b..d88ca221 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1362,5 +1362,13 @@ int BluetoothHost::NotifyDialogResult(uint32_t dialogType, bool dialogResult) CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr"); return proxy->NotifyDialogResult(dialogType, dialogResult); } + +void BluetoothHost::SetCallingPackageName(const std::string &address, const std::string &packageName) +{ + HILOGI("enter"); + sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); + CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr"); + proxy->SetCallingPackageName(address, packageName); +} } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 9d5f73c8..6c7578f5 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -883,6 +883,15 @@ public: * @since 20 */ int NotifyDialogResult(uint32_t dialogType, bool dialogResult); + + /** + * @brief set the package name of calling app which is pairing or connecting remote bluetooth device. + * + * @param address The address of remote bluetooth device. + * @param packageName The package name of calling app. + * @since 21 + */ + void SetCallingPackageName(const std::string &address, const std::string &packageName); private: /** * @brief A constructor used to create a BluetoothHost instance. -- Gitee From 3c0e596e2b8cec718b0649c4c7f42855970b8313 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Wed, 20 Aug 2025 18:49:37 +0800 Subject: [PATCH 06/26] add gatt reason enum Signed-off-by: linzlinz <2495670683@qq.com> --- .../js/napi/include/napi_bluetooth_ble_utils.h | 1 + frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp | 2 ++ .../js/napi/src/ble/napi_bluetooth_ble_utils.cpp | 15 +++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/frameworks/js/napi/include/napi_bluetooth_ble_utils.h b/frameworks/js/napi/include/napi_bluetooth_ble_utils.h index 5a692ad5..ced77c70 100644 --- a/frameworks/js/napi/include/napi_bluetooth_ble_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_ble_utils.h @@ -72,6 +72,7 @@ napi_value ScanDutyInit(napi_env env); napi_value MatchModeInit(napi_env env); napi_value PhyTypeInit(napi_env env); napi_value ScanReportModeInit(napi_env env); +napi_value GattDisconnectReasonInit(napi_env env); void SetGattClientDeviceId(const std::string &deviceId); std::string GetGattClientDeviceId(); diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 42f0cf8c..20802047 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -1216,6 +1216,7 @@ napi_value PropertyInit(napi_env env, napi_value exports) SetNamedPropertyByInteger(env, advertisingStateObj, static_cast(AdvertisingState::STOPPED), "STOPPED"); napi_value scanReportTypeObj = ScanReportTypeInit(env); + napi_value gattDisconnectReasonObj = GattDisconnectReasonInit(env); #endif napi_property_descriptor exportFuncs[] = { @@ -1228,6 +1229,7 @@ napi_value PropertyInit(napi_env env, napi_value exports) DECLARE_NAPI_PROPERTY("GattWriteType", gattWriteTypeObj), DECLARE_NAPI_PROPERTY("AdvertisingState", advertisingStateObj), DECLARE_NAPI_PROPERTY("ScanReportType", scanReportTypeObj), + DECLARE_NAPI_PROPERTY("GattDisconnectReason", gattDisconnectReasonObj), #endif }; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp index a4c81c8a..d5d0ad60 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp @@ -511,6 +511,21 @@ napi_value ScanReportModeInit(napi_env env) return reportModeObj; } +napi_value GattDisconnectReasonInit(napi_env env) +{ + napi_value gattDisconnectReasonObj = nullptr; + napi_create_object(env, &gattDisconnectReasonObj); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_TIMEOUT), "CONN_TIMEOUT"); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_TERMINATE_PEER_USER), "CONN_TERMINATE_PEER_USER"); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_TERMINATE_LOCAL_HOST), "CONN_TERMINATE_LOCAL_HOST"); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_UNKNOWN), "CONN_UNKNOWN"); + return gattDisconnectReasonObj; +} + void SetGattClientDeviceId(const std::string &deviceId) { deviceAddr = deviceId; -- Gitee From 81d98d362be0adfc0c37136ad5e95ba71b321f3b Mon Sep 17 00:00:00 2001 From: guoxiadi Date: Thu, 21 Aug 2025 15:49:48 +0800 Subject: [PATCH 07/26] add errmsg Bt Signed-off-by: guoxiadi --- frameworks/js/napi/src/common/napi_bluetooth_error.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp index 31550532..e29dc216 100644 --- a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp +++ b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp @@ -66,6 +66,8 @@ static std::map napiErrMsgMap { { BtErrCode::BT_ERR_GATT_CONNECTION_NOT_AUTHORIZED, "The connection is not authorized." }, { BtErrCode::BT_ERR_BLE_SCAN_NO_RESOURCE, "Fails to start scan as it is out of hardware resources."}, { BtErrCode::BT_ERR_BLE_SCAN_ALREADY_STARTED, "Failed to start scan as Ble scan is already started by the app."}, + { BtErrCode::BT_ERR_DIALOG_FOR_USER_NOT_RESPOND, "The user does not respond."}, + { BtErrCode::BT_ERR_DIALOG_FOR_USER_REFUSE, "User refuse the action."}, }; std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode) -- Gitee From d7e4cd7a4929f148b4958f18908a40359f1e51c3 Mon Sep 17 00:00:00 2001 From: yuanchen13 Date: Thu, 21 Aug 2025 16:08:58 +0800 Subject: [PATCH 08/26] fix DiscoverComplete crash Signed-off-by: yuanchen13 --- frameworks/inner/src/bluetooth_gatt_client.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 5999b16e..0375b7be 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -455,7 +455,9 @@ void GattClient::impl::DiscoverComplete(int state) } if (ret) { std::shared_ptr clientSptr = (callback_).lock(); - clientSptr->OnServicesDiscovered(state); + if (!clientSptr) { + clientSptr->OnServicesDiscovered(state); + } } } -- Gitee From ca671d298e1816beb693a5ba263dd1c8d38f7dcc Mon Sep 17 00:00:00 2001 From: yuanchen13 Date: Thu, 21 Aug 2025 16:18:03 +0800 Subject: [PATCH 09/26] fix DiscoverComplete crash Signed-off-by: yuanchen13 --- frameworks/inner/src/bluetooth_gatt_client.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 0375b7be..97a9df06 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -456,8 +456,10 @@ void GattClient::impl::DiscoverComplete(int state) if (ret) { std::shared_ptr clientSptr = (callback_).lock(); if (!clientSptr) { - clientSptr->OnServicesDiscovered(state); + HILOGE("callback is nullptr"); + return; } + clientSptr->OnServicesDiscovered(state); } } -- Gitee From 9ce8091462ea815080052108b4eb48935910a7c8 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Thu, 21 Aug 2025 21:41:58 +0800 Subject: [PATCH 10/26] bugfix for napi cause Signed-off-by: linzlinz <2495670683@qq.com> --- frameworks/js/napi/include/napi_native_object.h | 12 ++++++------ .../src/ble/napi_bluetooth_gatt_client_callback.cpp | 2 +- .../src/ble/napi_bluetooth_gatt_server_callback.cpp | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/frameworks/js/napi/include/napi_native_object.h b/frameworks/js/napi/include/napi_native_object.h index 010b3189..6f1b7ff4 100644 --- a/frameworks/js/napi/include/napi_native_object.h +++ b/frameworks/js/napi/include/napi_native_object.h @@ -140,18 +140,18 @@ private: class NapiNativeStateChangeParam : public NapiNativeObject { public: NapiNativeStateChangeParam(std::string deviceAddr, int connectState, - bool isDisconnected = false, int disconnectReason = -1, int cause = 0) - : deviceAddr_(deviceAddr), connectState_(connectState), isDisconnected_(isDisconnected), - disconnectReason_(disconnectReason), stateChangeCause_(cause) {} + int cause = 0, bool isDisconnected = false, int disconnectReason = -1) + : deviceAddr_(deviceAddr), connectState_(connectState), stateChangeCause_(cause), + isDisconnected_(isDisconnected), disconnectReason_(disconnectReason) {} virtual ~NapiNativeStateChangeParam() override = default; napi_value ToNapiValue(napi_env env) const override; private: std::string deviceAddr_ = ""; int connectState_ = -1; + int stateChangeCause_ = -1; bool isDisconnected_ = false; int disconnectReason_ = -1; - int stateChangeCause_ = -1; }; class NapiNativeBleConnectionStateChangeParam : public NapiNativeStateChangeParam { @@ -159,8 +159,8 @@ public: NapiNativeBleConnectionStateChangeParam(std::string deviceAddr, int connectState) : NapiNativeStateChangeParam(deviceAddr, connectState) {} NapiNativeBleConnectionStateChangeParam( - std::string deviceAddr, int connectState, bool isDisconnected, int disconnectReason) - : NapiNativeStateChangeParam(deviceAddr, connectState, isDisconnected, disconnectReason) {} + std::string deviceAddr, int connectState, int cause, bool isDisconnected, int disconnectReason) + : NapiNativeStateChangeParam(deviceAddr, connectState, cause, isDisconnected, disconnectReason) {} ~NapiNativeBleConnectionStateChangeParam() override = default; }; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp index f8904600..80bf70ac 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp @@ -62,7 +62,7 @@ void NapiGattClientCallback::OnConnectionStateChangedWithReason(int connectionSt connectionState, disconnectReason, ret); if (connectionState == static_cast(BTConnectState::DISCONNECTED)) { auto nativeObject = std::make_shared( - deviceAddr_, connectionState, true, disconnectReason); + deviceAddr_, connectionState, 0, true, disconnectReason); eventSubscribe_.PublishEvent(STR_BT_GATT_CLIENT_CALLBACK_BLE_CONNECTIION_STATE_CHANGE, nativeObject); return; } diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp index d84d681c..8d0a6046 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp @@ -88,7 +88,7 @@ void NapiGattServerCallback::OnConnectionStateUpdateWithReason( } } auto nativeObject = std::make_shared( - device.GetDeviceAddr(), state, true, disconnectReason); + device.GetDeviceAddr(), state, 0, true, disconnectReason); eventSubscribe_.PublishEvent(STR_BT_GATT_SERVER_CALLBACK_CONNECT_STATE_CHANGE, nativeObject); } } -- Gitee From 3506b214f7b92c91a95b0e9b7c6af4d2ed4d8581 Mon Sep 17 00:00:00 2001 From: guoxiadi Date: Sat, 23 Aug 2025 10:53:22 +0800 Subject: [PATCH 11/26] modify makeshared Signed-off-by: guoxiadi --- frameworks/js/napi/src/common/napi_event_subscribe_module.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp b/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp index 70d5980c..99b103a0 100644 --- a/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp +++ b/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp @@ -75,9 +75,6 @@ napi_status NapiEventSubscribeModule::Register(napi_env env, napi_callback_info callbackVec.end()); auto napiCallback = std::make_shared(env, callback); - if (napiCallback) { - callbackVec.push_back(napiCallback); - } HILOGI("Register one %{public}s callback in %{public}s module, %{public}s, %{public}zu callback left", name.c_str(), moduleName_.c_str(), napiCallback->ToLogString().c_str(), callbackVec.size()); }); -- Gitee From a597085b1a600da5fa66232b1c5f21f8e46ab627 Mon Sep 17 00:00:00 2001 From: lee Date: Sat, 23 Aug 2025 15:00:49 +0800 Subject: [PATCH 12/26] condition_variable Signed-off-by: lee --- frameworks/inner/src/bluetooth_gatt_client.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 5999b16e..3fc0d3c7 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -415,12 +415,12 @@ int GattClient::impl::DiscoverStart() { std::unique_lock lock(discoverInformation_.mutex_); - while (discoverInformation_.isDiscovering_) { - auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT)); - if (ret == std::cv_status::timeout) { - HILOGE("timeout"); - return BT_ERR_INTERNAL_ERROR; - } + auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT), [this] { + return !discoverInformation_.isDiscovering_; + }); + if (ret == false) { + HILOGE("timeout"); + return BT_ERR_INTERNAL_ERROR; } discoverInformation_.isDiscovering_ = true; } @@ -890,7 +890,7 @@ int GattClient::SetNotifyCharacteristicInner(GattCharacteristic &characteristic, CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); bool isValid = (pimpl != nullptr && pimpl->Init(weak_from_this())); CHECK_AND_RETURN_LOG_RET(isValid, BT_ERR_INTERNAL_ERROR, "pimpl or gatt client proxy is nullptr"); - + std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); -- Gitee From cfd9f471ead88d9ac59dde7dbf122b969daabdd0 Mon Sep 17 00:00:00 2001 From: guoxiadi Date: Mon, 25 Aug 2025 09:11:28 +0800 Subject: [PATCH 13/26] add vec modify Signed-off-by: guoxiadi --- frameworks/js/napi/src/common/napi_event_subscribe_module.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp b/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp index 99b103a0..90f5604a 100644 --- a/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp +++ b/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp @@ -75,6 +75,7 @@ napi_status NapiEventSubscribeModule::Register(napi_env env, napi_callback_info callbackVec.end()); auto napiCallback = std::make_shared(env, callback); + callbackVec.push_back(napiCallback); HILOGI("Register one %{public}s callback in %{public}s module, %{public}s, %{public}zu callback left", name.c_str(), moduleName_.c_str(), napiCallback->ToLogString().c_str(), callbackVec.size()); }); -- Gitee From 8fe44d3e49c1797188e48803c123b21de88e85e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0?= Date: Tue, 10 Jun 2025 15:41:49 +0800 Subject: [PATCH 14/26] =?UTF-8?q?add=20tdd=20Signed-off-by:=20=E9=A9=AC?= =?UTF-8?q?=E5=A3=AB=E8=BE=B0=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bundle.json | 3 + test/BUILD.gn | 20 + test/unittest/napi/BUILD.gn | 76 +++ test/unittest/napi/napi/native_api.h | 55 +++ test/unittest/napi/napi/native_node_api.h | 19 + .../napi/napi_event_subscribe_module_test.cpp | 443 ++++++++++++++++++ test/unittest/napi/nv.h | 19 + 7 files changed, 635 insertions(+) create mode 100644 test/BUILD.gn create mode 100644 test/unittest/napi/BUILD.gn create mode 100644 test/unittest/napi/napi/native_api.h create mode 100644 test/unittest/napi/napi/native_node_api.h create mode 100644 test/unittest/napi/napi_event_subscribe_module_test.cpp create mode 100644 test/unittest/napi/nv.h diff --git a/bundle.json b/bundle.json index c52eef0a..1a1b3552 100644 --- a/bundle.json +++ b/bundle.json @@ -272,6 +272,9 @@ }, "name": "//foundation/communication/bluetooth/frameworks/js/napi/src/common:bt_napi_common" } + ], + "test": [ + "//foundation/communication/bluetooth/test:unit_test" ] } } diff --git a/test/BUILD.gn b/test/BUILD.gn new file mode 100644 index 00000000..00c39c84 --- /dev/null +++ b/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (C) 2025 Huawei Device Co., Ltd. +# 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. + +import("//foundation/communication/bluetooth/bluetooth.gni") +group("unit_test") { + testonly = true + deps = [ + "unittest/napi:unittest", + ] +} \ No newline at end of file diff --git a/test/unittest/napi/BUILD.gn b/test/unittest/napi/BUILD.gn new file mode 100644 index 00000000..fbc53f89 --- /dev/null +++ b/test/unittest/napi/BUILD.gn @@ -0,0 +1,76 @@ +# Copyright (C) 2025 Huawei Device Co., Ltd. +# 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. + +import("//build/test.gni") +import("//foundation/communication/bluetooth/bluetooth.gni") + +module_output_path = "bluetooth/bluetooth" +FRAMWORK_DIR = "//foundation/communication/bluetooth" + +config("module_private_config") { + cflags = [ + "-Werror", + "-Wno-macro-redefined", + "-Wno-non-c-typedef-for-linkage", + "-Wno-unused-const-variable", + "-Wno-deprecated-builtins", + "-Wno-defaulted-function-deleted", + "-Woverloaded-virtual", + ] + include_dirs = [ + ".", + "$FRAMWORK_DIR/frameworks/inner/include", + "$FRAMWORK_DIR/frameworks/js/napi/include", + "$FRAMWORK_DIR/interfaces/inner_api/include", + "$FRAMWORK_DIR/interfaces/inner_api/include/c_header", + ] + defines = [ + "BTFW_LOG_TAG = \"bluetooth_test\"", + "BTFW_LOG_DOMAIN = 0xD005300", + "private = public", + "protected = public", + ] +} + +ohos_unittest("bluetooth_napi_event_subscribe_module_test") { + module_out_path = module_output_path + + sources = [ + "$FRAMWORK_DIR/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp", + "napi_event_subscribe_module_test.cpp", + ] + + configs = [ + ":module_private_config", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "googletest:gmock_main", + "googletest:gtest_main", + ] +} + +################################################################################ +group("unittest") { + testonly = true + + deps = [] + + if (is_phone_product) { + deps += [ + ":bluetooth_napi_event_subscribe_module_test", + ] + } +} \ No newline at end of file diff --git a/test/unittest/napi/napi/native_api.h b/test/unittest/napi/napi/native_api.h new file mode 100644 index 00000000..65bc3d6e --- /dev/null +++ b/test/unittest/napi/napi/native_api.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef NAPI_NATIVE_API_H +#define NAPI_NATIVE_API_H + +struct napi_env {}; +using napi_value = void *; +enum napi_status { + napi_ok = 0, + napi_invalid_arg, +}; +struct napi_async_work {}; +struct napi_deferred {}; +using napi_ref = int; +struct uv_work_t { + void *data; +}; +struct napi_callback_info {}; +using napi_handle_scope = void *; +typedef enum { + napi_undefined, + napi_null, +} napi_valuetype; + +napi_status napi_create_reference(napi_env env, napi_value value, uint32_t initial_refcount, napi_ref* result); +napi_status napi_get_reference_value(napi_env env, napi_ref ref, napi_value* result); +napi_status napi_call_function(napi_env env, napi_value recv, napi_value func, size_t argc, + const napi_value* argv, napi_value* result); +napi_status napi_is_exception_pending(napi_env env, bool* result); +napi_status napi_delete_reference(napi_env env, napi_ref ref); +napi_status napi_get_and_clear_last_exception(napi_env env, napi_value* result); +napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, bool* result); +napi_status napi_create_promise(napi_env env, napi_deferred* deferred, napi_value* promise); +napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, napi_value resolution); +napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, napi_value rejection); +napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result); +napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, size_t* argc, napi_value* argv, + napi_value* this_arg, void** data); +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope); + +using napi_threadsafe_function = void *; +#endif // NAPI_NATIVE_API_H \ No newline at end of file diff --git a/test/unittest/napi/napi/native_node_api.h b/test/unittest/napi/napi/native_node_api.h new file mode 100644 index 00000000..9cdd1c25 --- /dev/null +++ b/test/unittest/napi/napi/native_node_api.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef NATIVE_NODE_API_H +#define NATIVE_NODE_API_H + +#endif // NATIVE_NODE_API_H \ No newline at end of file diff --git a/test/unittest/napi/napi_event_subscribe_module_test.cpp b/test/unittest/napi/napi_event_subscribe_module_test.cpp new file mode 100644 index 00000000..5b6bff84 --- /dev/null +++ b/test/unittest/napi/napi_event_subscribe_module_test.cpp @@ -0,0 +1,443 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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 +#include + +#include "bluetooth_log.h" +#include "napi_event_subscribe_module.h" + +using namespace testing; +using namespace testing::ext; + +static size_t g_napiGetCbInfoArgc = 0; +void NapiGetCbInfoMockSetArgc(size_t argc) +{ + g_napiGetCbInfoArgc = argc; +} +napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, size_t* argc, napi_value* argv, + napi_value* this_arg, void** data) +{ + *argc = g_napiGetCbInfoArgc; + return napi_ok; +} +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) +{ + return napi_ok; +} + +namespace OHOS { +namespace Bluetooth { +void NapiMockClear(void); + +class NapiEventSubscribeModuleTest : public testing::Test { +public: + NapiEventSubscribeModuleTest() = default; + ~NapiEventSubscribeModuleTest() = default; + + static void SetUpTestSuite(void) {} + static void TearDownTestSuite(void) {} + void SetUp() + { + NapiMockClear(); + } + void TearDown() {} + + napi_env env_; + napi_callback_info info_; +}; + +static std::string g_napiParseStringStr = ""; +static bool g_napiParseStringIsString = false; + +void NapiParseStringMock(std::string str, bool isString) +{ + g_napiParseStringStr = str; + g_napiParseStringIsString = isString; +} + +napi_status NapiParseString(napi_env env, napi_value value, std::string &outStr) +{ + outStr = g_napiParseStringStr; + return g_napiParseStringIsString ? napi_ok : napi_invalid_arg; +} + +static bool g_napiIsFunction = false; + +napi_status NapiIsFunctionMock(bool isFunction) +{ + g_napiIsFunction = isFunction; + return napi_ok; +} + +napi_status NapiIsFunction(napi_env env, napi_value value) +{ + return g_napiIsFunction ? napi_ok : napi_invalid_arg; +} + +NapiCallback::NapiCallback(napi_env env, napi_value callback) {} +NapiCallback::~NapiCallback() {} + +static int g_napiCallFunctionCount = 0; +void NapiCallback::CallFunction(const std::shared_ptr &object) +{ + g_napiCallFunctionCount++; +} +void NapiCallback::CallFunction(int errCode, const std::shared_ptr &object) {} +napi_env NapiCallback::GetNapiEnv(void) +{ + return env_; +} +std::string NapiCallback::ToLogString(void) const +{ + return ""; +} + +static bool g_napiCallbackIsEqual = false; +void NapiCallbackIsEqualMock(bool equal) +{ + g_napiCallbackIsEqual = equal; +} +bool NapiCallback::Equal(napi_env env, napi_value &callback) const +{ + return g_napiCallbackIsEqual; +} + +int DoInJsMainThread(std::function func) +{ + func(); + return 0; +} + +int DoInJsMainThread(napi_env env, std::function func) +{ + func(); + return 0; +} + +void NapiMockClear(void) +{ + g_napiGetCbInfoArgc = 0; + g_napiParseStringStr = ""; + g_napiParseStringIsString = false; + g_napiIsFunction = false; + g_napiCallbackIsEqual = false; + g_napiCallFunctionCount = 0; +} + +static const char * const TEST_CALLBACK_NAME = "testCallback"; + +/** + * @tc.name: NapiEventSubscribeModuleTest_001 + * @tc.desc: Test register and deregister normal + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_001, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_001 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(true); + + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 0); + + HILOGI("NapiEventSubscribeModuleTest_001 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_002 + * @tc.desc: Test register the type callback, and the same callback Repeated + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_002, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_002 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + // Mock the same callback + NapiCallbackIsEqualMock(true); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + HILOGI("NapiEventSubscribeModuleTest_002 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_003 + * @tc.desc: Test register the type callback, and multi callback + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_003, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_003 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 2); + + HILOGI("NapiEventSubscribeModuleTest_003 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_004 + * @tc.desc: Test publish event + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_004, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_004 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + subscribe.PublishEvent(TEST_CALLBACK_NAME, nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 1); + + HILOGI("NapiEventSubscribeModuleTest_004 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_005 + * @tc.desc: Test register failed + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_005, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_005 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + // Invalid params size + NapiGetCbInfoMockSetArgc(1); + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[0] string type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, false); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid type name + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock("errCallbackName", true); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[1] function type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + NapiIsFunctionMock(false); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + HILOGI("NapiEventSubscribeModuleTest_005 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_006 + * @tc.desc: Test register failed + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_006, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_006 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + // Invalid params size + NapiGetCbInfoMockSetArgc(3); + napi_status ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + NapiGetCbInfoMockSetArgc(0); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[0] string type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, false); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid type name + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock("errCallbackName", true); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[1] function type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + NapiIsFunctionMock(false); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // The callback is not registered + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(true); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + + HILOGI("NapiEventSubscribeModuleTest_006 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_007 + * @tc.desc: Test publish event failed + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_007, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_007 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + // Invalid eventName + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + subscribe.PublishEvent("errCallbackName", nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 0); + + // Empty callback in map + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(true); + + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 0); + + subscribe.PublishEvent(TEST_CALLBACK_NAME, nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 0); + + HILOGI("NapiEventSubscribeModuleTest_007 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_008 + * @tc.desc: Test Deregister all callback + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_008, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_008 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 2); + + NapiGetCbInfoMockSetArgc(1); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 0); + + HILOGI("NapiEventSubscribeModuleTest_008 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_009 + * @tc.desc: Test publish a event with multi callback + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_009, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_009 enter"); + napi_env env; + napi_value callback = nullptr; + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + subscribe.eventSubscribeMap_.ChangeValueByLambda(TEST_CALLBACK_NAME, [env, callback](auto & callbackVec) { + auto napiCallback = std::make_shared(env, callback); + callbackVec.push_back(napiCallback); + napiCallback = std::make_shared(env, callback); + callbackVec.push_back(napiCallback); + }); + + subscribe.PublishEvent(TEST_CALLBACK_NAME, nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 2); + + HILOGI("NapiEventSubscribeModuleTest_009 end"); +} +} // namespace Bluetooth +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/napi/nv.h b/test/unittest/napi/nv.h new file mode 100644 index 00000000..48526dc0 --- /dev/null +++ b/test/unittest/napi/nv.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef UV_H +#define UV_H + +#endif // UV_H \ No newline at end of file -- Gitee From d8831456716018e753405e204d500de68461d2a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0?= Date: Sat, 28 Jun 2025 09:50:18 +0800 Subject: [PATCH 15/26] =?UTF-8?q?file=20name=20change=20Signed-off-by:=20?= =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/unittest/napi/{nv.h => uv.h} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test/unittest/napi/{nv.h => uv.h} (100%) diff --git a/test/unittest/napi/nv.h b/test/unittest/napi/uv.h similarity index 100% rename from test/unittest/napi/nv.h rename to test/unittest/napi/uv.h -- Gitee From 51df6377bc6497ab86e5a2e4ff2a9e9ec533c4e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Mon, 25 Aug 2025 03:31:58 +0000 Subject: [PATCH 16/26] change some code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/inner/src/bluetooth_host.cpp | 5 +++-- interfaces/inner_api/include/bluetooth_host.h | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index d88ca221..e62e972e 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1363,12 +1363,13 @@ int BluetoothHost::NotifyDialogResult(uint32_t dialogType, bool dialogResult) return proxy->NotifyDialogResult(dialogType, dialogResult); } -void BluetoothHost::SetCallingPackageName(const std::string &address, const std::string &packageName) +int32_t BluetoothHost::SetCallingPackageName(const std::string &address, const std::string &packageName) { HILOGI("enter"); sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); - CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr"); + CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr"); proxy->SetCallingPackageName(address, packageName); + return BT_NO_ERROR; } } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 6c7578f5..4a2bda65 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -891,7 +891,7 @@ public: * @param packageName The package name of calling app. * @since 21 */ - void SetCallingPackageName(const std::string &address, const std::string &packageName); + int32_t SetCallingPackageName(const std::string &address, const std::string &packageName); private: /** * @brief A constructor used to create a BluetoothHost instance. -- Gitee From fc21bf33c791375aff58aeb99777b05ebae4111c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Mon, 25 Aug 2025 03:34:09 +0000 Subject: [PATCH 17/26] change some code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- interfaces/inner_api/include/bluetooth_host.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 4a2bda65..91ce3ad9 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -889,6 +889,8 @@ public: * * @param address The address of remote bluetooth device. * @param packageName The package name of calling app. + * @return Returns {@link BT_NO_ERROR} if the operation is successful; + * returns an error code defined in {@link BtErrCode} otherwise. * @since 21 */ int32_t SetCallingPackageName(const std::string &address, const std::string &packageName); -- Gitee From 6a344f1fd4a7d9c567a9fdbf85150b430ce0b2cb Mon Sep 17 00:00:00 2001 From: lee Date: Tue, 26 Aug 2025 15:22:36 +0800 Subject: [PATCH 18/26] condition_variable Signed-off-by: lee --- frameworks/inner/src/bluetooth_gatt_client.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 3fc0d3c7..c577ae3f 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -516,12 +516,12 @@ void GattClient::impl::GetServices() } std::unique_lock lock(discoverInformation_.mutex_); - while (discoverInformation_.isDiscovering_) { - auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT)); - if (ret == std::cv_status::timeout) { - HILOGE("timeout"); - return; - } + auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT), [this] { + return !discoverInformation_.isDiscovering_; + }); + if (ret == false) { + HILOGE("timeout"); + return; } if (isGetServiceYet_) { HILOGD("isGetServiceYet_ is true"); -- Gitee From 432c8b3ebbe609d0ab2cd9e9f58bd95efb84a69f Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Sat, 23 Aug 2025 15:51:39 +0800 Subject: [PATCH 19/26] add observer nullptr check Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I07f7b07de42b5c76df9606e5cf343901e3a4920e --- frameworks/inner/src/bluetooth_a2dp_snk.cpp | 1 + frameworks/inner/src/bluetooth_a2dp_src.cpp | 1 + frameworks/inner/src/bluetooth_avrcp_tg.cpp | 3 +-- frameworks/inner/src/bluetooth_hfp_ag.cpp | 1 + frameworks/inner/src/bluetooth_hfp_hf.cpp | 1 + frameworks/inner/src/bluetooth_hid_host.cpp | 1 + frameworks/inner/src/bluetooth_host.cpp | 1 + frameworks/inner/src/bluetooth_pan.cpp | 1 + 8 files changed, 8 insertions(+), 2 deletions(-) diff --git a/frameworks/inner/src/bluetooth_a2dp_snk.cpp b/frameworks/inner/src/bluetooth_a2dp_snk.cpp index feeffc50..6b645bd1 100644 --- a/frameworks/inner/src/bluetooth_a2dp_snk.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_snk.cpp @@ -129,6 +129,7 @@ void A2dpSink::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } diff --git a/frameworks/inner/src/bluetooth_a2dp_src.cpp b/frameworks/inner/src/bluetooth_a2dp_src.cpp index 3b9b5a3b..1d07a2e5 100644 --- a/frameworks/inner/src/bluetooth_a2dp_src.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_src.cpp @@ -171,6 +171,7 @@ void A2dpSource::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } diff --git a/frameworks/inner/src/bluetooth_avrcp_tg.cpp b/frameworks/inner/src/bluetooth_avrcp_tg.cpp index f5d80416..789836cd 100644 --- a/frameworks/inner/src/bluetooth_avrcp_tg.cpp +++ b/frameworks/inner/src/bluetooth_avrcp_tg.cpp @@ -153,15 +153,14 @@ int32_t AvrcpTarget::GetDeviceAbsVolumeAbility(const BluetoothRemoteDevice &devi void AvrcpTarget::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); - std::lock_guard lock(pimpl->observerMutex_); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } void AvrcpTarget::UnregisterObserver(std::shared_ptr observer) { HILOGD("enter"); - std::lock_guard lock(pimpl->observerMutex_); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); pimpl->observers_.Deregister(observer); } diff --git a/frameworks/inner/src/bluetooth_hfp_ag.cpp b/frameworks/inner/src/bluetooth_hfp_ag.cpp index ba01b2e2..0ce3e7f9 100644 --- a/frameworks/inner/src/bluetooth_hfp_ag.cpp +++ b/frameworks/inner/src/bluetooth_hfp_ag.cpp @@ -750,6 +750,7 @@ void HandsFreeAudioGateway::RegisterObserver(std::shared_ptrRegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_hfp_hf.cpp b/frameworks/inner/src/bluetooth_hfp_hf.cpp index 4d5ccc92..bd462290 100644 --- a/frameworks/inner/src/bluetooth_hfp_hf.cpp +++ b/frameworks/inner/src/bluetooth_hfp_hf.cpp @@ -762,6 +762,7 @@ void HandsFreeUnit::RegisterObserver(std::shared_ptr obse { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->RegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_hid_host.cpp b/frameworks/inner/src/bluetooth_hid_host.cpp index 268bc4fd..1bce72d9 100644 --- a/frameworks/inner/src/bluetooth_hid_host.cpp +++ b/frameworks/inner/src/bluetooth_hid_host.cpp @@ -329,6 +329,7 @@ void HidHost::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->RegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index 575293c2..ef0f3bf2 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -620,6 +620,7 @@ void BluetoothHost::RegisterObserver(std::shared_ptr obse { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } diff --git a/frameworks/inner/src/bluetooth_pan.cpp b/frameworks/inner/src/bluetooth_pan.cpp index 02a7b5eb..37ae6de8 100644 --- a/frameworks/inner/src/bluetooth_pan.cpp +++ b/frameworks/inner/src/bluetooth_pan.cpp @@ -233,6 +233,7 @@ void Pan::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->RegisterObserver(observer); } -- Gitee From 35ae5b17941bc77ee38024e8a20629cc8c06d3b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0?= Date: Wed, 27 Aug 2025 06:27:18 +0000 Subject: [PATCH 20/26] update test/unittest/napi/BUILD.gn. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马士辰 --- test/unittest/napi/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/test/unittest/napi/BUILD.gn b/test/unittest/napi/BUILD.gn index fbc53f89..4a740aba 100644 --- a/test/unittest/napi/BUILD.gn +++ b/test/unittest/napi/BUILD.gn @@ -31,6 +31,7 @@ config("module_private_config") { ".", "$FRAMWORK_DIR/frameworks/inner/include", "$FRAMWORK_DIR/frameworks/js/napi/include", + "$FRAMWORK_DIR/frameworks/js/napi/src/parser", "$FRAMWORK_DIR/interfaces/inner_api/include", "$FRAMWORK_DIR/interfaces/inner_api/include/c_header", ] -- Gitee From e22f16665ffd33d82bdf7567ed40b6d81d1bbd00 Mon Sep 17 00:00:00 2001 From: Yiming Lv <2909256199@qq.com> Date: Wed, 27 Aug 2025 09:30:20 +0000 Subject: [PATCH 21/26] add signalhub control mode Signed-off-by: Yiming Lv <2909256199@qq.com> --- frameworks/inner/src/bluetooth_host.cpp | 3 ++- interfaces/inner_api/include/bluetooth_def.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index aeb92f40..7dd77250 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -701,7 +701,8 @@ int BluetoothHost::RestrictBluetooth(std::string name) int BluetoothHost::SatelliteControl(int type, int state) { HILOGI("type: %{public}d, state: %{public}d", type, state); - if (type == static_cast(SATELLITE_CONTROL_MODE::ANTENNA)) { + if (type == static_cast(SATELLITE_CONTROL_MODE::ANTENNA) || + type == static_cast(SATELLITE_CONTROL_MODE::SIGNALHUB_MAC_SWITCH)) { CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); } else if (type == static_cast(SATELLITE_CONTROL_MODE::BLUETOOTH_SWITCH)) { pimpl->LoadBluetoothHostService(); diff --git a/interfaces/inner_api/include/bluetooth_def.h b/interfaces/inner_api/include/bluetooth_def.h index 6e31d242..f3debb73 100644 --- a/interfaces/inner_api/include/bluetooth_def.h +++ b/interfaces/inner_api/include/bluetooth_def.h @@ -1693,6 +1693,7 @@ struct SensingInfo { enum class SATELLITE_CONTROL_MODE { ANTENNA = 0, BLUETOOTH_SWITCH = 1, + SIGNALHUB_MAC_SWITCH = 2, }; struct TrustPairDeviceParam { -- Gitee From 5bcd21601b11cd8136485785bd21a780424217fb Mon Sep 17 00:00:00 2001 From: ChenJie Date: Thu, 28 Aug 2025 10:23:17 +0800 Subject: [PATCH 22/26] return recv errno Signed-off-by: ChenJie --- frameworks/inner/src/bluetooth_socket_outputstream.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/inner/src/bluetooth_socket_outputstream.cpp b/frameworks/inner/src/bluetooth_socket_outputstream.cpp index a7715c64..04502003 100644 --- a/frameworks/inner/src/bluetooth_socket_outputstream.cpp +++ b/frameworks/inner/src/bluetooth_socket_outputstream.cpp @@ -94,6 +94,7 @@ int OutputStream::Write(const uint8_t *buf, size_t length) if (ret <= 0) { setTimeoutFlag_ = false; HILOGE("socket write exception! ret:%{public}zd errno:%{public}d", ret, errno); + return errno; } return ret; } -- Gitee From b3944a7f276129ba8b3b695871e2451b908b3847 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0?= Date: Thu, 28 Aug 2025 19:25:47 +0800 Subject: [PATCH 23/26] log print MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马士辰 --- frameworks/inner/src/bluetooth_hfp_ag.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frameworks/inner/src/bluetooth_hfp_ag.cpp b/frameworks/inner/src/bluetooth_hfp_ag.cpp index 0ce3e7f9..de6b0782 100644 --- a/frameworks/inner/src/bluetooth_hfp_ag.cpp +++ b/frameworks/inner/src/bluetooth_hfp_ag.cpp @@ -257,7 +257,7 @@ struct HandsFreeAudioGateway::impl { bool OpenVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); sptr proxy = GetRemoteProxy(PROFILE_HFP_AG); if (proxy != nullptr && device.IsValidBluetoothRemoteDevice()) { return proxy->OpenVoiceRecognition(BluetoothRawAddress(device.GetDeviceAddr())); @@ -267,7 +267,7 @@ struct HandsFreeAudioGateway::impl { bool CloseVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); sptr proxy = GetRemoteProxy(PROFILE_HFP_AG); if (proxy != nullptr && device.IsValidBluetoothRemoteDevice()) { return proxy->CloseVoiceRecognition(BluetoothRawAddress(device.GetDeviceAddr())); -- Gitee From c1c26ac326f5a46c8a2c0b18090945d609d4d7c4 Mon Sep 17 00:00:00 2001 From: Gala Han <2545202801@qq.com> Date: Mon, 1 Sep 2025 19:02:57 +0800 Subject: [PATCH 24/26] modify interface check Signed-off-by: Gala Han <2545202801@qq.com> --- frameworks/inner/src/bluetooth_host.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index 7dd77250..d0b525e5 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -701,11 +701,12 @@ int BluetoothHost::RestrictBluetooth(std::string name) int BluetoothHost::SatelliteControl(int type, int state) { HILOGI("type: %{public}d, state: %{public}d", type, state); - if (type == static_cast(SATELLITE_CONTROL_MODE::ANTENNA) || - type == static_cast(SATELLITE_CONTROL_MODE::SIGNALHUB_MAC_SWITCH)) { + if (type == static_cast(SATELLITE_CONTROL_MODE::ANTENNA)) { CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); } else if (type == static_cast(SATELLITE_CONTROL_MODE::BLUETOOTH_SWITCH)) { pimpl->LoadBluetoothHostService(); + } else if (type == static_cast(SATELLITE_CONTROL_MODE::SIGNALHUB_MAC_SWITCH)) { + CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_ERR_INVALID_STATE, "ble is off."); } else { HILOGE("Invalid control type: %{public}d", type); return BT_ERR_INVALID_PARAM; -- Gitee From 84b52417ce32c9055a07f5c3e8d64e593591b6d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0?= Date: Mon, 1 Sep 2025 17:23:57 +0800 Subject: [PATCH 25/26] commercial log print MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马士辰 --- frameworks/inner/src/bluetooth_hfp_ag.cpp | 6 +++--- frameworks/inner/src/bluetooth_hfp_hf.cpp | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/frameworks/inner/src/bluetooth_hfp_ag.cpp b/frameworks/inner/src/bluetooth_hfp_ag.cpp index de6b0782..e2d61f06 100644 --- a/frameworks/inner/src/bluetooth_hfp_ag.cpp +++ b/frameworks/inner/src/bluetooth_hfp_ag.cpp @@ -239,7 +239,7 @@ struct HandsFreeAudioGateway::impl { void PhoneStateChanged(BluetoothPhoneState &phoneState) { - HILOGI("numActive: %{public}d, numHeld: %{public}d, callState: %{public}d, type: %{public}d", + HILOG_COMM_INFO("numActive: %{public}d, numHeld: %{public}d, callState: %{public}d, type: %{public}d", phoneState.GetActiveNum(), phoneState.GetHeldNum(), phoneState.GetCallState(), phoneState.GetCallType()); sptr proxy = GetRemoteProxy(PROFILE_HFP_AG); CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is null"); @@ -610,7 +610,7 @@ void HandsFreeAudioGateway::ClccResponse( bool HandsFreeAudioGateway::OpenVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("OpenVoiceRecognition: %{public}s", GET_ENCRYPT_ADDR(device)); if (!IS_BT_ENABLED()) { HILOGE("bluetooth is off."); return false; @@ -624,7 +624,7 @@ bool HandsFreeAudioGateway::OpenVoiceRecognition(const BluetoothRemoteDevice &de bool HandsFreeAudioGateway::CloseVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("CloseVoiceRecognition: %{public}s", GET_ENCRYPT_ADDR(device)); if (!IS_BT_ENABLED()) { HILOGE("bluetooth is off."); return false; diff --git a/frameworks/inner/src/bluetooth_hfp_hf.cpp b/frameworks/inner/src/bluetooth_hfp_hf.cpp index bd462290..07972470 100644 --- a/frameworks/inner/src/bluetooth_hfp_hf.cpp +++ b/frameworks/inner/src/bluetooth_hfp_hf.cpp @@ -54,7 +54,8 @@ public: void OnScoStateChanged(const BluetoothRawAddress &device, int32_t state) override { - HILOGI("enter, device: %{public}s, state: %{public}d", GetEncryptAddr((device).GetAddress()).c_str(), state); + HILOG_COMM_INFO("OnScoStateChanged: %{public}s, state: %{public}d", + GetEncryptAddr((device).GetAddress()).c_str(), state); BluetoothRemoteDevice remoteDevice(device.GetAddress(), 0); observers_.ForEach([remoteDevice, state](std::shared_ptr observer) { observer->OnScoStateChanged(remoteDevice, state); -- Gitee From 41950772d18688ff9fb92b8462ee4fad7db288e7 Mon Sep 17 00:00:00 2001 From: hui Date: Sun, 7 Sep 2025 17:10:47 +0800 Subject: [PATCH 26/26] add dafault value Signed-off-by: hui --- interfaces/inner_api/include/c_header/ohos_bt_gatt.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/inner_api/include/c_header/ohos_bt_gatt.h b/interfaces/inner_api/include/c_header/ohos_bt_gatt.h index fbf00ebb..0e0a17c3 100644 --- a/interfaces/inner_api/include/c_header/ohos_bt_gatt.h +++ b/interfaces/inner_api/include/c_header/ohos_bt_gatt.h @@ -402,7 +402,7 @@ typedef struct { /** Handling advertisments sent by advertisers with specific manufactureId */ unsigned short manufactureId; /** Adv_Ind Report */ - bool advIndReport; + bool advIndReport = false; /** Scan filter identifier index */ uint8_t filterIndex; } BleScanNativeFilter; -- Gitee