From 12e4107742ee0ac8d9ea8d090e60b3236a58366c Mon Sep 17 00:00:00 2001 From: chenjie Date: Thu, 20 Mar 2025 14:45:18 +0800 Subject: [PATCH 01/45] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=BC=80=E5=90=AF?= =?UTF-8?q?=E6=89=AB=E6=8F=8F=E8=BF=94=E5=9B=9E=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: chenjie --- frameworks/inner/c_adapter/ohos_bt_gatt.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/frameworks/inner/c_adapter/ohos_bt_gatt.cpp b/frameworks/inner/c_adapter/ohos_bt_gatt.cpp index 240576a7..3cb7a22f 100644 --- a/frameworks/inner/c_adapter/ohos_bt_gatt.cpp +++ b/frameworks/inner/c_adapter/ohos_bt_gatt.cpp @@ -979,8 +979,7 @@ int BleStartScanEx(int32_t scannerId, const BleScanConfigs *configs, const BleSc BleScanSettings settings; settings.SetScanMode(configs->scanMode); - bleCentralManager->StartScan(settings, scanFilters); - return OHOS_BT_STATUS_SUCCESS; + return bleCentralManager->StartScan(settings, scanFilters); } /** -- Gitee From 722ba7ac4d166397e7ec73bb8cd5a8fe76d04ddd Mon Sep 17 00:00:00 2001 From: fengyong Date: Fri, 28 Mar 2025 09:37:06 +0800 Subject: [PATCH 02/45] =?UTF-8?q?write=E6=97=B6=E8=AE=BE=E7=BD=AE50s?= =?UTF-8?q?=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: fengyong --- .../inner/src/bluetooth_socket_outputstream.cpp | 13 +++++++++++++ .../include/bluetooth_socket_outputstream.h | 1 + 2 files changed, 14 insertions(+) diff --git a/frameworks/inner/src/bluetooth_socket_outputstream.cpp b/frameworks/inner/src/bluetooth_socket_outputstream.cpp index d6946ffb..d07a273c 100644 --- a/frameworks/inner/src/bluetooth_socket_outputstream.cpp +++ b/frameworks/inner/src/bluetooth_socket_outputstream.cpp @@ -29,6 +29,7 @@ namespace Bluetooth { static constexpr int32_t SOCKET_PACKET_HEAD_LENGTH = 1512; static constexpr int32_t AAM_UID = 7878; static constexpr int32_t AAM_BAD_RET = -978974; +static constexpr int32_t SOFTBUS_UID = 1024; OutputStream::OutputStream(int socketFd) : socketFd_(socketFd) {} @@ -61,11 +62,23 @@ int OutputStream::Write(const uint8_t *buf, size_t length) } } } + + if (getuid() == SOFTBUS_UID && setTimeoutFlag_ == false) { + HILOGD("Softbus write set timeout."); + timeval timeVals; + if (setsockopt(socketFd_, SOL_SOCKET, SO_SNDTIMEO, &) == -1) { + HILOGE("setsockopt failed"); + return -1; + } + setTimeoutFlag_ == true; + } + auto ret = send(socketFd_, buf, length, MSG_NOSIGNAL); HILOGD("ret: %{public}zd", ret); if (ret <= 0) { + setTimeoutFlag_ == false; HILOGE("socket write exception! ret:%{public}zd errno:%{public}d", ret, errno); } return ret; diff --git a/interfaces/inner_api/include/bluetooth_socket_outputstream.h b/interfaces/inner_api/include/bluetooth_socket_outputstream.h index 37de05b9..36344c57 100644 --- a/interfaces/inner_api/include/bluetooth_socket_outputstream.h +++ b/interfaces/inner_api/include/bluetooth_socket_outputstream.h @@ -75,6 +75,7 @@ public: private: int socketFd_; + bool setTimeoutFlag_ = false; OutputStream() = delete; }; } // namespace Bluetooth -- Gitee From 8595a725a03364978937f7e4ef698d24a4619e41 Mon Sep 17 00:00:00 2001 From: fengyong Date: Fri, 28 Mar 2025 01:48:44 +0000 Subject: [PATCH 03/45] update frameworks/inner/src/bluetooth_socket_outputstream.cpp. Signed-off-by: fengyong --- .../inner/src/bluetooth_socket_outputstream.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/frameworks/inner/src/bluetooth_socket_outputstream.cpp b/frameworks/inner/src/bluetooth_socket_outputstream.cpp index d07a273c..84097574 100644 --- a/frameworks/inner/src/bluetooth_socket_outputstream.cpp +++ b/frameworks/inner/src/bluetooth_socket_outputstream.cpp @@ -30,7 +30,7 @@ static constexpr int32_t SOCKET_PACKET_HEAD_LENGTH = 1512; static constexpr int32_t AAM_UID = 7878; static constexpr int32_t AAM_BAD_RET = -978974; static constexpr int32_t SOFTBUS_UID = 1024; - +static constexpr int32_t SOCKET_WRITE_TIMEOUT_50_SEC = 50; OutputStream::OutputStream(int socketFd) : socketFd_(socketFd) {} @@ -62,15 +62,16 @@ int OutputStream::Write(const uint8_t *buf, size_t length) } } } - if (getuid() == SOFTBUS_UID && setTimeoutFlag_ == false) { - HILOGD("Softbus write set timeout."); - timeval timeVals; - if (setsockopt(socketFd_, SOL_SOCKET, SO_SNDTIMEO, &) == -1) { - HILOGE("setsockopt failed"); + HILOGD("SOFTBUS write data set 50s tiemout."); + timeval timeout; + timeout.tv_sec = SOCKET_WRITE_TIMEOUT_50_SEC; + timeout.tv_usec = 0; + if (setsockopt(socketFd_, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0) { + HILOGW("Failed to set send timeout"); return -1; } - setTimeoutFlag_ == true; + setTimeoutFlag_ = true; } auto ret = send(socketFd_, buf, length, MSG_NOSIGNAL); -- Gitee From f2c545861d1eea4750f9c23c2a4dd621f02e5300 Mon Sep 17 00:00:00 2001 From: lee Date: Thu, 27 Mar 2025 22:40:21 +0800 Subject: [PATCH 04/45] add dlclose clear bluetoothSystemAbility_ Signed-off-by: lee --- .../inner/include/bluetooth_profile_manager.h | 9 +++++++++ frameworks/inner/src/bluetooth_host.cpp | 5 +++++ .../inner/src/bluetooth_profile_manager.cpp | 15 +++++++++++++++ interfaces/inner_api/include/bluetooth_host.h | 2 ++ 4 files changed, 31 insertions(+) diff --git a/frameworks/inner/include/bluetooth_profile_manager.h b/frameworks/inner/include/bluetooth_profile_manager.h index 169154b8..a6f88694 100644 --- a/frameworks/inner/include/bluetooth_profile_manager.h +++ b/frameworks/inner/include/bluetooth_profile_manager.h @@ -87,6 +87,15 @@ public: * @brief check bluetooth service is on or not */ bool IsBluetoothServiceOn(); + /** + * @brief clear resource when dlclose + */ + static void ClearSystemAbility(); + + /** + * @brief clear resource when dlclose + */ + void Close(); static BluetoothProfileManager &GetInstance(); diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index de33b352..e12535e9 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1311,5 +1311,10 @@ int32_t BluetoothHost::ProcessRandomDeviceIdCommand( CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); return proxy->ProcessRandomDeviceIdCommand(command, deviceIdVec, isValid); } + +void BluetoothHost::CleanResourceWhenDlclose() +{ + BluetoothProfileManager::GetInstance().Close(); +} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/src/bluetooth_profile_manager.cpp b/frameworks/inner/src/bluetooth_profile_manager.cpp index a44fcbd6..c68ffcf7 100644 --- a/frameworks/inner/src/bluetooth_profile_manager.cpp +++ b/frameworks/inner/src/bluetooth_profile_manager.cpp @@ -50,6 +50,21 @@ BluetoothProfileManager &BluetoothProfileManager::GetInstance() return *instance; } +extern "C" __attribute__((destructor)) void BluetoothProfileManager::ClearSystemAbility() +{ + BluetoothHost::GetDefaultHost().CleanResourceWhenDlclose(); +} + +void BluetoothProfileManager::Close() +{ + sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + CHECK_AND_RETURN_LOG(samgrProxy != nullptr, "[BLUETOOTH_PROFILE_MANAGER] failed to get samgrProxy"); + int32_t ret = samgrProxy->UnSubscribeSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, bluetoothSystemAbility_); + CHECK_AND_RETURN_LOG(ret == ERR_OK, + "[BLUETOOTH_PROFILE_MANAGER] Unsubscribe systemAbilityId: bluetooth service failed!"); + bluetoothSystemAbility_ = nullptr; +} + void BluetoothProfileManager::SubScribeBluetoothSystemAbility() { sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 04feabfe..2b2dd7d4 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -855,6 +855,8 @@ public: int64_t GetRefusePolicyProhibitedTime(); int32_t ProcessRandomDeviceIdCommand(int32_t command, std::vector &deviceIdVec, bool &isValid); + + void CleanResourceWhenDlclose(); private: /** * @brief A constructor used to create a BluetoothHost instance. -- Gitee From 18f57e9d49774bdd2d47a76e0d2b03bf0740f98e Mon Sep 17 00:00:00 2001 From: yexiaokang Date: Fri, 28 Mar 2025 16:10:43 +0800 Subject: [PATCH 05/45] Revert "add collaboration msg defination between AP and lpdevice" This reverts commit 395add7263b1ed7e04e9e567a8933691c0cbfcfc. Signed-off-by: yexiaokang --- frameworks/inner/ipc/common/bt_def.h | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index db04e00f..3efb5669 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -457,7 +457,6 @@ typedef enum { SCAN_MODE_OP_P2_30_1500 = 0x09, SCAN_MODE_OP_P75_30_40 = 0x0A, SCAN_MODE_OP_P50_30_60 = 0x0B, - SCAN_MODE_OP_MAX, } SCAN_MODE; // Scan callback type @@ -520,17 +519,6 @@ constexpr int8_t BLE_LPDEVICE_MSG_UUID_DATA = 0x0a; constexpr int8_t BLE_LPDEVICE_MSG_ADV_HANDLE = 0x0b; constexpr int8_t BLE_LPDEVICE_MSG_SCAN_STATUS = 0x0c; constexpr int8_t BLE_LPDEVICE_MSG_SCAN_PARAM = 0x0d; -constexpr int8_t BLE_LPDEVICE_MSG_CAPABILITY_QUERY = 0x13; -constexpr int8_t BLE_LPDEVICE_MSG_SCAN_COLLABORATION_QUERY = 0x14; -constexpr int8_t BLE_LPDEVICE_MSG_SCAN_COLLABORATION_RESULT = 0x15; -constexpr int8_t BLE_LPDEVICE_MSG_GATT_CONN_COLLABORATION_QUERY = 0x16; -constexpr int8_t BLE_LPDEVICE_MSG_GATT_CONN_COLLABORATION_RESULT = 0x17; -constexpr int8_t BLE_LPDEVICE_MSG_SET_BLE_BUFFER_SIZE_AND_NUM = 0x18; - -// collaboration msg from lpdevice -constexpr uint8_t BLE_LPDEVICE_MSG_CAPABILITY = 0x01; -constexpr uint8_t BLE_LPDEVICE_MSG_SCAN_COLLABORATION_NOTIFY_STATUS = 0x02; -constexpr uint8_t BLE_LPDEVICE_MSG_GATT_CONN_COLLABORATION_NOTIFY_STATUS = 0x03; constexpr uint8_t BLE_LPDEVICE_MSG_TYPE_NOTICE_UP_DATA = 0x02; -- Gitee From e67075ed49a3de1fc8e0b357195d568be04d6231 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Sat, 29 Mar 2025 17:10:15 +0800 Subject: [PATCH 06/45] add GetDeviceId for spp Signed-off-by: linzlinz <2495670683@qq.com> --- frameworks/inner/src/bluetooth_host.cpp | 6 ++-- frameworks/inner/src/bluetooth_socket.cpp | 6 +++- .../napi/include/napi_bluetooth_spp_client.h | 1 + .../src/socket/napi_bluetooth_spp_client.cpp | 28 +++++++++++++++++++ .../src/socket/napi_bluetooth_spp_server.cpp | 1 + 5 files changed, 39 insertions(+), 3 deletions(-) diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index de33b352..1fc67eeb 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1165,8 +1165,10 @@ int BluetoothHost::SetFastScan(bool isEnable) int BluetoothHost::GetRandomAddress(const std::string &realAddr, std::string &randomAddr) const { - randomAddr = realAddr; - return BT_NO_ERROR; + CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); + sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); + CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr"); + return proxy->GetRandomAddress(realAddr, randomAddr); } int BluetoothHost::ConnectAllowedProfiles(const std::string &remoteAddr) const diff --git a/frameworks/inner/src/bluetooth_socket.cpp b/frameworks/inner/src/bluetooth_socket.cpp index 57963c34..28c04279 100644 --- a/frameworks/inner/src/bluetooth_socket.cpp +++ b/frameworks/inner/src/bluetooth_socket.cpp @@ -721,7 +721,11 @@ struct ServerSocket::impl { (void)sprintf_s(token, sizeof(token), "%02X:%02X:%02X:%02X:%02X:%02X", buf[0x05], buf[0x04], buf[0x03], buf[0x02], buf[0x01], buf[0x00]); BluetoothRawAddress rawAddr {token}; - acceptAddress_ = rawAddr.GetAddress().c_str(); + // If the random address fails to be obtained, the actual address is returned by default. + std::string randomAddr = rawAddr.GetAddress(); + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + host->GetRandomAddress(rawAddr.GetAddress(), randomAddr); + acceptAddress_ = randomAddr; maxTxPacketSize_ = GetPacketSizeFromBuf(recvBuf + TX_OFFSET, rv - TX_OFFSET); maxRxPacketSize_ = GetPacketSizeFromBuf(recvBuf + RX_OFFSET, rv - RX_OFFSET); diff --git a/frameworks/js/napi/include/napi_bluetooth_spp_client.h b/frameworks/js/napi/include/napi_bluetooth_spp_client.h index 5bf300f2..34d25d0b 100644 --- a/frameworks/js/napi/include/napi_bluetooth_spp_client.h +++ b/frameworks/js/napi/include/napi_bluetooth_spp_client.h @@ -69,6 +69,7 @@ struct NapiSppClient { static void SppRead(int id); static napi_value SppWriteAsync(napi_env env, napi_callback_info info); static napi_value SppReadAsync(napi_env env, napi_callback_info info); + static napi_value GetDeviceId(napi_env env, napi_callback_info info); static int count; static std::map> clientMap; 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 fb84a463..19d3bad2 100644 --- a/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp +++ b/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp @@ -28,6 +28,7 @@ #include #include #include +#include "../parser/napi_parser_utils.h" namespace OHOS { namespace Bluetooth { @@ -577,5 +578,32 @@ napi_value NapiSppClient::SppReadAsync(napi_env env, napi_callback_info info) asyncWork->Run(); return asyncWork->GetRet(); } + +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_CALL_RETURN(NapiParseInt32(env, argv[PARAM0], id)); + return napi_ok; +} + +napi_value NapiSppClient::GetDeviceId(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 client = clientMap[id]; + NAPI_BT_ASSERT_RETURN_UNDEF(env, client != nullptr, BT_ERR_INVALID_PARAM); + NAPI_BT_ASSERT_RETURN_UNDEF(env, client->client_ != nullptr, BT_ERR_INVALID_PARAM); + BluetoothRemoteDevice remoteDevice = client->client_->GetRemoteDevice(); + std::string addr = remoteDevice.GetDeviceAddr(); + napi_value result = nullptr; + napi_create_string_utf8(env, addr.c_str(), addr.size(), &result); + return result; +} } // namespace Bluetooth } // namespace OHOS 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 02693778..ae275f01 100644 --- a/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp +++ b/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp @@ -39,6 +39,7 @@ void DefineSppFunctions(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("sppCloseServerSocket", NapiSppServer::SppCloseServerSocket), DECLARE_NAPI_FUNCTION("sppCloseClientSocket", NapiSppClient::SppCloseClientSocket), DECLARE_NAPI_FUNCTION("sppWrite", NapiSppClient::SppWrite), + DECLARE_NAPI_FUNCTION("getDeviceId", NapiSppClient::GetDeviceId), #ifdef BLUETOOTH_API_SINCE_10 DECLARE_NAPI_FUNCTION("on", NapiSppServer::RegisterSocketObserver), DECLARE_NAPI_FUNCTION("off", NapiSppServer::DeRegisterSocketObserver), -- Gitee From 0d6ea11f47e410ee79edc7509449ec5453b2e98b Mon Sep 17 00:00:00 2001 From: c00429280 Date: Mon, 31 Mar 2025 20:55:56 +0800 Subject: [PATCH 07/45] * avoid cloud dev when bluetooth off Signed-off-by: c00429280 --- 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 90a3a6c5..c62586e5 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1274,6 +1274,7 @@ void BluetoothHost::Close(void) int32_t BluetoothHost::UpdateCloudBluetoothDevice(const std::vector &cloudDevices) { + CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); HILOGI("[CLOUD_DEV] UpdateCloudBluetoothDevice enter"); sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr"); -- Gitee From d5b5a616dda60f5f9b5b12bae0860f6ea54ffbad Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Tue, 1 Apr 2025 15:01:26 +0800 Subject: [PATCH 08/45] ble advertising handle Signed-off-by: linzlinz <2495670683@qq.com> --- frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h b/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h index 96a397ab..6e56e32f 100644 --- a/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h @@ -36,7 +36,7 @@ public: int DisableAdvertising(uint8_t advHandle) override; int StopAdvertising(int32_t advHandle) override; void Close(int32_t advHandle) override; - int32_t GetAdvertiserHandle(int32_t &advHandle) override; + int32_t GetAdvertiserHandle(int32_t &advHandle, const sptr &callback) override; void SetAdvertisingData(const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle) override; int ChangeAdvertisingParams(uint8_t advHandle, const BluetoothBleAdvertiserSettings &settings) override; -- Gitee From a520b5433d0d5b0c8483f61693cd415cd63b4233 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Tue, 1 Apr 2025 15:11:24 +0800 Subject: [PATCH 09/45] ble advertising handle Signed-off-by: linzlinz <2495670683@qq.com> --- .../inner/ipc/include/bluetooth_ble_advertiser_proxy.h | 2 +- .../inner/ipc/interface/i_bluetooth_ble_advertiser.h | 2 +- .../inner/ipc/src/bluetooth_ble_advertiser_proxy.cpp | 7 ++++++- frameworks/inner/src/bluetooth_ble_advertiser.cpp | 4 ++-- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h b/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h index 96a397ab..6e56e32f 100644 --- a/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_ble_advertiser_proxy.h @@ -36,7 +36,7 @@ public: int DisableAdvertising(uint8_t advHandle) override; int StopAdvertising(int32_t advHandle) override; void Close(int32_t advHandle) override; - int32_t GetAdvertiserHandle(int32_t &advHandle) override; + int32_t GetAdvertiserHandle(int32_t &advHandle, const sptr &callback) override; void SetAdvertisingData(const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle) override; int ChangeAdvertisingParams(uint8_t advHandle, const BluetoothBleAdvertiserSettings &settings) override; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_ble_advertiser.h b/frameworks/inner/ipc/interface/i_bluetooth_ble_advertiser.h index 8185ec2f..d8a62673 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_ble_advertiser.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_ble_advertiser.h @@ -39,7 +39,7 @@ public: virtual int DisableAdvertising(uint8_t advHandle) = 0; virtual int StopAdvertising(int32_t advHandle) = 0; virtual void Close(int32_t advHandle) = 0; - virtual int32_t GetAdvertiserHandle(int32_t &advHandle) = 0; + virtual int32_t GetAdvertiserHandle(int32_t &advHandle, const sptr &callback) = 0; virtual void SetAdvertisingData(const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle) = 0; virtual int ChangeAdvertisingParams(uint8_t advHandle, const BluetoothBleAdvertiserSettings &settings) = 0; diff --git a/frameworks/inner/ipc/src/bluetooth_ble_advertiser_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_ble_advertiser_proxy.cpp index b9654c7e..94ff3853 100644 --- a/frameworks/inner/ipc/src/bluetooth_ble_advertiser_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_ble_advertiser_proxy.cpp @@ -216,13 +216,18 @@ void BluetoothBleAdvertiserProxy::Close(int32_t advHandle) } } -int32_t BluetoothBleAdvertiserProxy::GetAdvertiserHandle(int32_t &advHandle) +int32_t BluetoothBleAdvertiserProxy::GetAdvertiserHandle(int32_t &advHandle, + const sptr &callback) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothBleAdvertiserProxy::GetDescriptor())) { HILOGW("[GetAdvertiserHandle] fail: write interface token failed."); return BT_ERR_INTERNAL_ERROR; } + if (!data.WriteRemoteObject(callback->AsObject())) { + HILOGW("[GetAdvertiserHandle] fail: write callback failed."); + return BT_ERR_INTERNAL_ERROR; + } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; diff --git a/frameworks/inner/src/bluetooth_ble_advertiser.cpp b/frameworks/inner/src/bluetooth_ble_advertiser.cpp index d3bba56e..91805659 100644 --- a/frameworks/inner/src/bluetooth_ble_advertiser.cpp +++ b/frameworks/inner/src/bluetooth_ble_advertiser.cpp @@ -365,7 +365,7 @@ int BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const if (pimpl->callbacks_.IsExistAdvertiserCallback(callback, advHandle)) { ret = proxy->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, duration, false); } else { - ret = proxy->GetAdvertiserHandle(advHandle); + ret = proxy->GetAdvertiserHandle(advHandle, pimpl->callbackImp_); if (ret != BT_NO_ERROR || advHandle == BLE_INVALID_ADVERTISING_HANDLE) { HILOGE("Invalid advertising handle"); callback->OnStartResultEvent(BT_ERR_INTERNAL_ERROR, static_cast(BLE_INVALID_ADVERTISING_HANDLE)); @@ -413,7 +413,7 @@ int BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const if (pimpl->callbacks_.IsExistAdvertiserCallback(callback, advHandle)) { ret = proxy->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, duration, true); } else { - ret = proxy->GetAdvertiserHandle(advHandle); + ret = proxy->GetAdvertiserHandle(advHandle, pimpl->callbackImp_); if (ret != BT_NO_ERROR || advHandle == BLE_INVALID_ADVERTISING_HANDLE) { HILOGE("Invalid advertising handle"); callback->OnStartResultEvent(BT_ERR_INTERNAL_ERROR, BLE_INVALID_ADVERTISING_HANDLE); -- Gitee From cbe043beb98f3807cea106b619214cdd8c9a6b3f Mon Sep 17 00:00:00 2001 From: lee Date: Tue, 1 Apr 2025 18:45:24 +0800 Subject: [PATCH 10/45] fix TDD CRASH Signed-off-by: lee --- frameworks/inner/include/bluetooth_profile_manager.h | 7 +------ frameworks/inner/src/bluetooth_host.cpp | 5 ----- frameworks/inner/src/bluetooth_profile_manager.cpp | 7 ++----- interfaces/inner_api/include/bluetooth_host.h | 2 -- 4 files changed, 3 insertions(+), 18 deletions(-) diff --git a/frameworks/inner/include/bluetooth_profile_manager.h b/frameworks/inner/include/bluetooth_profile_manager.h index a6f88694..6aca4a0b 100644 --- a/frameworks/inner/include/bluetooth_profile_manager.h +++ b/frameworks/inner/include/bluetooth_profile_manager.h @@ -92,11 +92,6 @@ public: */ static void ClearSystemAbility(); - /** - * @brief clear resource when dlclose - */ - void Close(); - static BluetoothProfileManager &GetInstance(); private: @@ -116,7 +111,7 @@ private: SafeMap profileIdFuncMap_; std::atomic_bool isBluetoothServiceOn_ = false; std::atomic_bool isNeedCheckBluetoothServiceOn_ = true; - sptr bluetoothSystemAbility_ = nullptr; + static sptr bluetoothSystemAbility_; int32_t registerValidId_ = BEGIN_ID; std::mutex idMutex_; std::mutex getProfileRemoteMutex_; diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index e12535e9..de33b352 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1311,10 +1311,5 @@ int32_t BluetoothHost::ProcessRandomDeviceIdCommand( CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); return proxy->ProcessRandomDeviceIdCommand(command, deviceIdVec, isValid); } - -void BluetoothHost::CleanResourceWhenDlclose() -{ - BluetoothProfileManager::GetInstance().Close(); -} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/src/bluetooth_profile_manager.cpp b/frameworks/inner/src/bluetooth_profile_manager.cpp index c68ffcf7..d95fed46 100644 --- a/frameworks/inner/src/bluetooth_profile_manager.cpp +++ b/frameworks/inner/src/bluetooth_profile_manager.cpp @@ -33,6 +33,8 @@ namespace OHOS { namespace Bluetooth { +sptr BluetoothProfileManager::bluetoothSystemAbility_ = nullptr; + BluetoothProfileManager::BluetoothProfileManager() { bluetoothSystemAbility_ = new BluetoothSystemAbility(); @@ -51,11 +53,6 @@ BluetoothProfileManager &BluetoothProfileManager::GetInstance() } extern "C" __attribute__((destructor)) void BluetoothProfileManager::ClearSystemAbility() -{ - BluetoothHost::GetDefaultHost().CleanResourceWhenDlclose(); -} - -void BluetoothProfileManager::Close() { sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); CHECK_AND_RETURN_LOG(samgrProxy != nullptr, "[BLUETOOTH_PROFILE_MANAGER] failed to get samgrProxy"); diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 2b2dd7d4..04feabfe 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -855,8 +855,6 @@ public: int64_t GetRefusePolicyProhibitedTime(); int32_t ProcessRandomDeviceIdCommand(int32_t command, std::vector &deviceIdVec, bool &isValid); - - void CleanResourceWhenDlclose(); private: /** * @brief A constructor used to create a BluetoothHost instance. -- Gitee From 47694150d7d398da7cd70989c9579d92c2f85f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=96=B9=E6=A3=8B?= <724869575@qq.com> Date: Wed, 2 Apr 2025 14:34:52 +0800 Subject: [PATCH 11/45] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=9B=9E=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘方棋 <724869575@qq.com> --- frameworks/js/napi/include/napi_bluetooth_hid_host.h | 1 - frameworks/js/napi/src/hid/napi_bluetooth_hid_host.cpp | 9 ++------- .../js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp | 2 -- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/frameworks/js/napi/include/napi_bluetooth_hid_host.h b/frameworks/js/napi/include/napi_bluetooth_hid_host.h index c3d3742b..2afdab87 100644 --- a/frameworks/js/napi/include/napi_bluetooth_hid_host.h +++ b/frameworks/js/napi/include/napi_bluetooth_hid_host.h @@ -43,7 +43,6 @@ public: static std::shared_ptr observer_; static thread_local napi_ref consRef_; - static bool isRegistered_; }; } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/hid/napi_bluetooth_hid_host.cpp b/frameworks/js/napi/src/hid/napi_bluetooth_hid_host.cpp index c3abdcda..131b5a55 100644 --- a/frameworks/js/napi/src/hid/napi_bluetooth_hid_host.cpp +++ b/frameworks/js/napi/src/hid/napi_bluetooth_hid_host.cpp @@ -34,7 +34,6 @@ using namespace std; std::shared_ptr NapiBluetoothHidHost::observer_ = std::make_shared(); thread_local napi_ref NapiBluetoothHidHost::consRef_ = nullptr; -bool NapiBluetoothHidHost::isRegistered_ = false; void NapiBluetoothHidHost::DefineHidHostJSClass(napi_env env, napi_value exports) { @@ -64,6 +63,8 @@ void NapiBluetoothHidHost::DefineHidHostJSClass(napi_env env, napi_value exports napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); NapiProfile::SetProfile(env, ProfileId::PROFILE_HID_HOST, napiProfile); + HidHost *profile = HidHost::GetProfile(); + profile->RegisterObserver(observer_); #endif } @@ -106,12 +107,6 @@ napi_value NapiBluetoothHidHost::On(napi_env env, napi_callback_info info) auto status = observer_->eventSubscribe_.Register(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); } - - if (!isRegistered_) { - HidHost *profile = HidHost::GetProfile(); - profile->RegisterObserver(observer_); - isRegistered_ = true; - } return NapiGetUndefinedRet(env); } diff --git a/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp b/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp index 20f9019c..f3d3f95a 100644 --- a/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp +++ b/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp @@ -34,8 +34,6 @@ NapiBluetoothHidHostObserver::NapiBluetoothHidHostObserver() void NapiBluetoothHidHostObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state, int cause) { - HILOGD("enter, remote device address: %{public}s, state: %{public}d, cause: %{public}d", - GET_ENCRYPT_ADDR(device), state, cause); auto nativeObject = std::make_shared(device.GetDeviceAddr(), state, cause); eventSubscribe_.PublishEvent(STR_BT_HID_HOST_OBSERVER_CONNECTION_STATE_CHANGE, nativeObject); } -- Gitee From 0fb1c3470fa8b8af644df356dc8ccac03c086865 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=96=B9=E6=A3=8B?= <724869575@qq.com> Date: Wed, 2 Apr 2025 06:47:33 +0000 Subject: [PATCH 12/45] update frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘方棋 <724869575@qq.com> --- frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp b/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp index f3d3f95a..20f9019c 100644 --- a/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp +++ b/frameworks/js/napi/src/hid/napi_bluetooth_hid_host_observer.cpp @@ -34,6 +34,8 @@ NapiBluetoothHidHostObserver::NapiBluetoothHidHostObserver() void NapiBluetoothHidHostObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state, int cause) { + HILOGD("enter, remote device address: %{public}s, state: %{public}d, cause: %{public}d", + GET_ENCRYPT_ADDR(device), state, cause); auto nativeObject = std::make_shared(device.GetDeviceAddr(), state, cause); eventSubscribe_.PublishEvent(STR_BT_HID_HOST_OBSERVER_CONNECTION_STATE_CHANGE, nativeObject); } -- Gitee From cd161d88c66e0087cb6623dafefe6504402be2fc Mon Sep 17 00:00:00 2001 From: hui Date: Mon, 7 Apr 2025 17:12:39 +0800 Subject: [PATCH 13/45] bugfix Signed-off-by: hui --- frameworks/inner/ipc/common/ble_service_data.cpp | 6 +++--- frameworks/inner/src/bluetooth_device_class.cpp | 8 ++++---- frameworks/inner/src/bluetooth_gatt_characteristic.cpp | 4 +++- frameworks/inner/src/bluetooth_gatt_server.cpp | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/frameworks/inner/ipc/common/ble_service_data.cpp b/frameworks/inner/ipc/common/ble_service_data.cpp index dba04a6d..508488aa 100644 --- a/frameworks/inner/ipc/common/ble_service_data.cpp +++ b/frameworks/inner/ipc/common/ble_service_data.cpp @@ -550,7 +550,7 @@ void BleAdvertiserDataImpl::AddServiceData(const Uuid &uuid, const std::string & cdata[0] = data.length() + BLE_UUID_LEN_128 + 1; cdata[1] = BLE_AD_TYPE_128SERVICE_DATA; /// 0x21 uint8_t uuidData[BLE_UUID_LEN_128]; - uuid.ConvertToBytesLE(uuidData); + uuid.ConvertToBytesLE(uuidData, BLE_UUID_LEN_128); AddData(std::string(cdata, BLE_ADV_DATA_FIELD_TYPE_AND_LEN) + std::string(reinterpret_cast(uuidData), BLE_UUID_LEN_128) + data); break; @@ -612,7 +612,7 @@ void BleAdvertiserDataImpl::AddServiceUuids(const std::vector &uuidVec) serviceUuid32.append(std::string(reinterpret_cast(&uuid32), BLE_UUID_LEN_32)); } else { uint8_t uuidData[BLE_UUID_LEN_128]; - uuid.ConvertToBytesLE(uuidData); + uuid.ConvertToBytesLE(uuidData, BLE_UUID_LEN_128); serviceUuid128.append(std::string(reinterpret_cast(uuidData), BLE_UUID_LEN_128)); } } @@ -684,7 +684,7 @@ void BleAdvertiserDataImpl::SetCompleteServices(const Uuid &uuid) cdata[0] = BLE_UUID_LEN_128 + 1; cdata[1] = BLE_AD_TYPE_128SRV_CMPL; /// 0x07 uint8_t uuidData[BLE_UUID_LEN_128]; - uuid.ConvertToBytesLE(uuidData); + uuid.ConvertToBytesLE(uuidData, BLE_UUID_LEN_128); AddData(std::string(cdata, BLE_ADV_DATA_FIELD_TYPE_AND_LEN) + std::string(reinterpret_cast(uuidData), BLE_UUID_LEN_128)); break; diff --git a/frameworks/inner/src/bluetooth_device_class.cpp b/frameworks/inner/src/bluetooth_device_class.cpp index f244e36a..4ebb632b 100644 --- a/frameworks/inner/src/bluetooth_device_class.cpp +++ b/frameworks/inner/src/bluetooth_device_class.cpp @@ -60,15 +60,15 @@ bool BluetoothDeviceClass::IsProfileSupported(int profileId) const } else if (profileId == BluetoothDevice::PROFILE_OPP) { return IsOppSupported(); } else if (profileId == BluetoothDevice::PROFILE_HID) { - return (GetMajorMinorClass() & BluetoothDevice::MAJOR_PERIPHERAL) == - BluetoothDevice::MAJOR_PERIPHERAL; + return (static_cast(GetMajorMinorClass()) & + BluetoothDevice::MAJOR_PERIPHERAL) == BluetoothDevice::MAJOR_PERIPHERAL; } else if (profileId == BluetoothDevice::PROFILE_PANU || profileId == BluetoothDevice::PROFILE_NAP) { if (IsServiceSupported(BluetoothDevice::SERVICE_NETWORKING)) { return true; } - return (GetMajorMinorClass() & BluetoothDevice::MAJOR_NETWORKING) == - BluetoothDevice::MAJOR_NETWORKING; + return (static_cast(GetMajorMinorClass()) & + BluetoothDevice::MAJOR_NETWORKING) == BluetoothDevice::MAJOR_NETWORKING; } else { return false; } diff --git a/frameworks/inner/src/bluetooth_gatt_characteristic.cpp b/frameworks/inner/src/bluetooth_gatt_characteristic.cpp index c3b57a65..a63d0149 100644 --- a/frameworks/inner/src/bluetooth_gatt_characteristic.cpp +++ b/frameworks/inner/src/bluetooth_gatt_characteristic.cpp @@ -106,7 +106,7 @@ GattCharacteristic::GattCharacteristic(GattCharacteristic &&src) handle_(src.handle_), permissions_(src.permissions_), properties_(src.properties_), - service_(src.service_), + service_(nullptr), value_(std::move(src.value_)), length_(src.length_), descriptors_(), @@ -115,6 +115,8 @@ GattCharacteristic::GattCharacteristic(GattCharacteristic &&src) for (auto &desc : src.descriptors_) { descriptors_.insert(descriptors_.end(), std::move(desc))->characteristic_ = this; } + service_ = src.service_; + src.service_ = nullptr; } void GattCharacteristic::AddDescriptor(const GattDescriptor &descriptor) diff --git a/frameworks/inner/src/bluetooth_gatt_server.cpp b/frameworks/inner/src/bluetooth_gatt_server.cpp index 2239b412..04c535a7 100644 --- a/frameworks/inner/src/bluetooth_gatt_server.cpp +++ b/frameworks/inner/src/bluetooth_gatt_server.cpp @@ -823,8 +823,8 @@ int GattServer::SendResponse( } int result = BT_ERR_INTERNAL_ERROR; - uint8_t requestType = requestId >> EIGHT_BITS; - uint8_t transport = requestId & 0xFF; + uint8_t requestType = static_cast(requestId) >> EIGHT_BITS; + uint8_t transport = static_cast(requestId) & 0xFF; if (transport != GATT_TRANSPORT_TYPE_CLASSIC && transport != GATT_TRANSPORT_TYPE_LE) { return result; } -- Gitee From 6cf4721260dd8b1fff336ac6faed44a3fd21aaad Mon Sep 17 00:00:00 2001 From: shinezxy Date: Mon, 7 Apr 2025 21:49:13 +0800 Subject: [PATCH 14/45] add get device uuid check bt enable Signed-off-by: shinezxy --- frameworks/inner/src/bluetooth_remote_device.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/inner/src/bluetooth_remote_device.cpp b/frameworks/inner/src/bluetooth_remote_device.cpp index 35cf7683..13c5904d 100644 --- a/frameworks/inner/src/bluetooth_remote_device.cpp +++ b/frameworks/inner/src/bluetooth_remote_device.cpp @@ -275,6 +275,7 @@ int BluetoothRemoteDevice::GetDeviceUuids(std::vector &uuids) const { HILOGI("enter"); CHECK_AND_RETURN_LOG_RET(IsValidBluetoothRemoteDevice(), BT_ERR_INTERNAL_ERROR, "Invalid remote device"); + CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); sptr hostProxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(hostProxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr."); return hostProxy->GetDeviceUuids(address_, uuids); -- Gitee From 94f10c62f93c3915b90474105f270254f4a565c4 Mon Sep 17 00:00:00 2001 From: yangkuo <1041733144@qq.com> Date: Sun, 13 Apr 2025 22:25:51 +0800 Subject: [PATCH 15/45] L2HC support Signed-off-by: yangkuo <1041733144@qq.com> --- frameworks/inner/ipc/common/bt_def.h | 29 ++ frameworks/inner/src/bluetooth_a2dp_src.cpp | 8 + .../js/napi/include/napi_bluetooth_a2dp_src.h | 20 ++ .../napi/src/a2dp/napi_bluetooth_a2dp_src.cpp | 306 +++++++++++++++++- interfaces/inner_api/include/bluetooth_def.h | 29 ++ .../inner_api/include/bluetooth_errorcode.h | 1 + 6 files changed, 391 insertions(+), 2 deletions(-) diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index 3efb5669..e2d79381 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -1451,6 +1451,35 @@ enum A2dpUserCodecChannelMode : uint8_t { A2DP_AAC_CHANNEL_MODE_OCTET2_MSK_USER = 0x0C, }; +/** + * @brief A2dp codec bit rate enum. + * + * @since 19 + */ +enum A2dpUserCodecBitRate : uint8_t { + A2DP_L2HCST_BIT_RATE_DEFAULT = 0x0, + A2DP_L2HCST_BIT_RATE_320K = 0x01, + A2DP_L2HCST_BIT_RATE_640K = 0x01 << 1, + A2DP_L2HCST_BIT_RATE_960K = 0x01 << 2, + A2DP_L2HCST_BIT_RATE_AUTO_RATE = 0x01 << 3, + A2DP_L2HCST_BIT_RATE_96K = 0x01 << 4, + A2DP_L2HCST_BIT_RATE_LOSSLESS = 0x01 << 5, + A2DP_L2HCST_BIT_RATE_128K = 0x01 << 6, + A2DP_L2HCST_BIT_RATE_192K = 0x01 << 7, + A2DP_L2HCST_BIT_RATE_256K = 0x01 << 8, + A2DP_L2HCST_BIT_RATE_480K = 0x01 << 9, +}; + +/** + * @brief A2dp codec frame length enum. + * + * @since 19 + */ +enum A2dpUserCodecFramelength : uint8_t { + A2DP_L2HCST_FRAME_LENGTH_5MS = 0x01, + A2DP_L2HCST_FRAME_LENGTH_10MS = 0x01 << 1, +}; + /** * @brief A2dp codec bits per sample enum. * diff --git a/frameworks/inner/src/bluetooth_a2dp_src.cpp b/frameworks/inner/src/bluetooth_a2dp_src.cpp index 80b73c03..3b9b5a3b 100644 --- a/frameworks/inner/src/bluetooth_a2dp_src.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_src.cpp @@ -411,6 +411,8 @@ A2dpCodecStatus A2dpSource::GetCodecStatus(const BluetoothRemoteDevice &device) ret.codecInfo.channelMode = codecStatus.codecInfo.channelMode; ret.codecInfo.codecPriority = codecStatus.codecInfo.codecPriority; ret.codecInfo.bitsPerSample = codecStatus.codecInfo.bitsPerSample; + ret.codecInfo.codecSpecific3 = codecStatus.codecInfo.codecSpecific3; + ret.codecInfo.codecSpecific4 = codecStatus.codecInfo.codecSpecific4; A2dpCodecInfo serviceInfo; for (auto it = codecStatus.codecInfoConfirmCap.begin(); it != codecStatus.codecInfoConfirmCap.end(); it++) { @@ -419,6 +421,8 @@ A2dpCodecStatus A2dpSource::GetCodecStatus(const BluetoothRemoteDevice &device) serviceInfo.channelMode = it->channelMode; serviceInfo.codecPriority = it->codecPriority; serviceInfo.bitsPerSample = it->bitsPerSample; + serviceInfo.codecSpecific3 = it->codecSpecific3; + serviceInfo.codecSpecific4 = it->codecSpecific4; ret.codecInfoConfirmedCap.push_back(serviceInfo); } @@ -428,6 +432,8 @@ A2dpCodecStatus A2dpSource::GetCodecStatus(const BluetoothRemoteDevice &device) serviceInfo.channelMode = it->channelMode; serviceInfo.codecPriority = it->codecPriority; serviceInfo.bitsPerSample = it->bitsPerSample; + serviceInfo.codecSpecific3 = it->codecSpecific3; + serviceInfo.codecSpecific4 = it->codecSpecific4; ret.codecInfoLocalCap.push_back(serviceInfo); } return ret; @@ -458,6 +464,8 @@ int A2dpSource::GetCodecPreference(const BluetoothRemoteDevice &device, A2dpCode info.sampleRate = serviceInfo.sampleRate; info.channelMode = serviceInfo.channelMode; info.bitsPerSample = serviceInfo.bitsPerSample; + info.codecSpecific3 = serviceInfo.codecSpecific3; + info.codecSpecific4 = serviceInfo.codecSpecific4; return ret; } diff --git a/frameworks/js/napi/include/napi_bluetooth_a2dp_src.h b/frameworks/js/napi/include/napi_bluetooth_a2dp_src.h index f972b83d..67b66d1f 100644 --- a/frameworks/js/napi/include/napi_bluetooth_a2dp_src.h +++ b/frameworks/js/napi/include/napi_bluetooth_a2dp_src.h @@ -56,11 +56,30 @@ enum CodecSampleRate { CODEC_SAMPLE_RATE_192000 = 6, }; +enum CodecBitRate { + CODEC_BIT_RATE_96000 = 0, + CODEC_BIT_RATE_128000 = 1, + CODEC_BIT_RATE_192000 = 2, + CODEC_BIT_RATE_256000 = 3, + CODEC_BIT_RATE_320000 = 4, + CODEC_BIT_RATE_480000 = 5, + CODEC_BIT_RATE_640000 = 6, + CODEC_BIT_RATE_960000 = 7, + CODEC_BIT_RATE_ABR = 8, +}; + +enum CodecFrameLength { + CODEC_FRAME_LENGTH_5MS = 0, + CODEC_FRAME_LENGTH_10MS = 1, +}; + struct CodecInfo { CodecType codecType; CodecBitsPerSample codecBitsPerSample; CodecChannelMode codecChannelMode; CodecSampleRate codecSampleRate; + CodecBitRate codecBitRate; + CodecFrameLength codecFrameLength; }; class NapiA2dpSource { @@ -89,6 +108,7 @@ public: static napi_value DisableAbsoluteVolume(napi_env env, napi_callback_info info); static napi_value SetCurrentCodecInfo(napi_env env, napi_callback_info info); static napi_value GetCurrentCodecInfo(napi_env env, napi_callback_info info); + static napi_value GetCurrentFullCodecInfo(napi_env env, napi_callback_info info); static napi_value EnableAutoPlay(napi_env env, napi_callback_info info); static napi_value DisableAutoPlay(napi_env env, napi_callback_info info); static napi_value GetAutoPlayDisabledDuration(napi_env env, napi_callback_info info); diff --git a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp index 8b7f318e..7e377401 100644 --- a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp +++ b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp @@ -69,6 +69,23 @@ const static std::map g_codecSampleRateMap = { {CODEC_SAMPLE_RATE_192000, A2DP_SAMPLE_RATE_NONE_USER}, }; +const static std::map g_codecBitRateMap = { + {CODEC_BIT_RATE_96000, A2DP_L2HCST_BIT_RATE_96K}, + {CODEC_BIT_RATE_128000, A2DP_L2HCST_BIT_RATE_128K}, + {CODEC_BIT_RATE_192000, A2DP_L2HCST_BIT_RATE_192K}, + {CODEC_BIT_RATE_256000, A2DP_L2HCST_BIT_RATE_256K}, + {CODEC_BIT_RATE_320000, A2DP_L2HCST_BIT_RATE_320K}, + {CODEC_BIT_RATE_480000, A2DP_L2HCST_BIT_RATE_480K}, + {CODEC_BIT_RATE_640000, A2DP_L2HCST_BIT_RATE_640K}, + {CODEC_BIT_RATE_960000, A2DP_L2HCST_BIT_RATE_960K}, + {CODEC_BIT_RATE_ABR, A2DP_L2HCST_BIT_RATE_AUTO_RATE}, +}; + +const static std::map g_codecFrameLengthMap = { + {CODEC_FRAME_LENGTH_5MS, A2DP_L2HCST_FRAME_LENGTH_5MS}, + {CODEC_FRAME_LENGTH_10MS, A2DP_L2HCST_FRAME_LENGTH_10MS}, +}; + const static std::map g_a2dpCodecTypeMap = { {A2DP_CODEC_TYPE_SBC_USER, CODEC_TYPE_SBC}, {A2DP_CODEC_TYPE_AAC_USER, CODEC_TYPE_AAC}, @@ -99,6 +116,23 @@ const static std::map g_a2dpCodecSampleRateMap = { {A2DP_L2HCV2_SAMPLE_RATE_96000_USER, CODEC_SAMPLE_RATE_96000}, }; +const static std::map g_a2dpCodecBitRateMap = { + {A2DP_L2HCST_BIT_RATE_96K, CODEC_BIT_RATE_96000}, + {A2DP_L2HCST_BIT_RATE_128K, CODEC_BIT_RATE_128000}, + {A2DP_L2HCST_BIT_RATE_192K, CODEC_BIT_RATE_192000}, + {A2DP_L2HCST_BIT_RATE_256K, CODEC_BIT_RATE_256000}, + {A2DP_L2HCST_BIT_RATE_320K, CODEC_BIT_RATE_320000}, + {A2DP_L2HCST_BIT_RATE_480K, CODEC_BIT_RATE_480000}, + {A2DP_L2HCST_BIT_RATE_640K, CODEC_BIT_RATE_640000}, + {A2DP_L2HCST_BIT_RATE_960K, CODEC_BIT_RATE_960000}, + {A2DP_L2HCST_BIT_RATE_AUTO_RATE, CODEC_BIT_RATE_ABR}, +}; + +const static std::map g_a2dpCodecFrameLengthMap = { + {A2DP_L2HCST_FRAME_LENGTH_5MS, CODEC_FRAME_LENGTH_5MS}, + {A2DP_L2HCST_FRAME_LENGTH_10MS, CODEC_FRAME_LENGTH_10MS}, +}; + napi_value NapiA2dpSource::DefineA2dpSourceJSClass(napi_env env, napi_value exports) { A2dpPropertyValueInit(env, exports); @@ -126,6 +160,7 @@ napi_value NapiA2dpSource::DefineA2dpSourceJSClass(napi_env env, napi_value expo DECLARE_NAPI_FUNCTION("enableAutoPlay", EnableAutoPlay), DECLARE_NAPI_FUNCTION("disableAutoPlay", DisableAutoPlay), DECLARE_NAPI_FUNCTION("getAutoPlayDisabledDuration", GetAutoPlayDisabledDuration), + DECLARE_NAPI_FUNCTION("getCurrentFullCodecInfo", GetCurrentFullCodecInfo), #endif }; @@ -304,6 +339,42 @@ napi_value CodecSampleRateInit(napi_env env) return codecSampleRate; } +napi_value CodecBitRateInit(napi_env env) +{ + napi_value codecBitRate = nullptr; + napi_create_object(env, &codecBitRate); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_96000, "CODEC_BIT_RATE_96000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_128000, "CODEC_BIT_RATE_128000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_192000, "CODEC_BIT_RATE_192000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_256000, "CODEC_BIT_RATE_256000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_320000, "CODEC_BIT_RATE_320000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_480000, "CODEC_BIT_RATE_480000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_640000, "CODEC_BIT_RATE_640000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_960000, "CODEC_BIT_RATE_960000"); + SetNamedPropertyByInteger(env, codecBitRate, + CodecBitRate::CODEC_BIT_RATE_ABR, "CODEC_BIT_RATE_ABR"); + return codecBitRate; +} + +napi_value CodecFrameLengthInit(napi_env env) +{ + napi_value codecFrameLength = nullptr; + napi_create_object(env, &codecFrameLength); + SetNamedPropertyByInteger(env, codecFrameLength, + CodecFrameLength::CODEC_FRAME_LENGTH_5MS, "CODEC_FRAME_LENGTH_5MS"); + SetNamedPropertyByInteger(env, codecFrameLength, + CodecFrameLength::CODEC_FRAME_LENGTH_10MS, "CODEC_FRAME_LENGTH_10MS"); + return codecFrameLength; +} + napi_value NapiA2dpSource::A2dpPropertyValueInit(napi_env env, napi_value exports) { napi_value playingStateObj = PlayingStateInit(env); @@ -311,12 +382,16 @@ napi_value NapiA2dpSource::A2dpPropertyValueInit(napi_env env, napi_value export napi_value codecBitsPerSampleObj = CodecBitsPerSampleInit(env); napi_value codecChannelModeObj = CodecChannelModeInit(env); napi_value codecSampleRateObj = CodecSampleRateInit(env); + napi_value codecBitRateObj = CodecBitRateInit(env); + napi_value codecFrameLengthObj = CodecFrameLengthInit(env); napi_property_descriptor exportProps[] = { DECLARE_NAPI_PROPERTY("PlayingState", playingStateObj), DECLARE_NAPI_PROPERTY("CodecType", codecTypeObj), DECLARE_NAPI_PROPERTY("CodecBitsPerSample", codecBitsPerSampleObj), DECLARE_NAPI_PROPERTY("CodecChannelMode", codecChannelModeObj), DECLARE_NAPI_PROPERTY("CodecSampleRate", codecSampleRateObj), + DECLARE_NAPI_PROPERTY("CodecBitRate", codecBitRateObj), + DECLARE_NAPI_PROPERTY("CodecFrameLength", codecFrameLengthObj), }; HITRACE_METER_NAME(HITRACE_TAG_OHOS, "a2dp_src:napi_define_properties"); napi_define_properties(env, exports, sizeof(exportProps) / sizeof(*exportProps), exportProps); @@ -573,6 +648,14 @@ static void ConvertCodecSampleRate(A2dpCodecInfo &a2dpCodecInfo, int32_t codecSa } } +static void ConvertCodecBitRate(A2dpCodecInfo &a2dpCodecInfo, int32_t codecBitRate) +{ + auto iter = g_codecBitRateMap.find(codecBitRate); + if (iter != g_codecBitRateMap.end()) { + a2dpCodecInfo.codecSpecific3 = iter->second; + } +} + static void ConvertCodecTypeToCodecInfo(CodecInfo &codecInfo, int32_t codecType) { auto iter = g_a2dpCodecTypeMap.find(codecType); @@ -605,6 +688,14 @@ static void ConvertCodecSampleRateToCodecInfo(CodecInfo &codecInfo, int32_t code } } +static void ConvertCodecBitRateToCodecInfo(CodecInfo &codecInfo, int32_t codecBitRate) +{ + auto iter = g_a2dpCodecBitRateMap.find(codecBitRate); + if (iter != g_a2dpCodecBitRateMap.end()) { + codecInfo.codecBitRate = iter->second; + } +} + static void ConvertCodecInfoToJs(napi_env env, napi_value &object, const A2dpCodecInfo &a2dpCodecInfo) { // convert A2dpCodecInfo to CodecInfo @@ -613,6 +704,7 @@ static void ConvertCodecInfoToJs(napi_env env, napi_value &object, const A2dpCod ConvertCodecChannelModeToCodecInfo(codecInfo, a2dpCodecInfo.channelMode); ConvertCodecBitsPerSampleToCodecInfo(codecInfo, a2dpCodecInfo.bitsPerSample); ConvertCodecTypeToCodecInfo(codecInfo, a2dpCodecInfo.codecType); + ConvertCodecBitRateToCodecInfo(codecInfo, a2dpCodecInfo.codecSpecific3); // convert CodecInfo to JS napi_value value = nullptr; napi_create_int32(env, codecInfo.codecType, &value); @@ -623,6 +715,194 @@ static void ConvertCodecInfoToJs(napi_env env, napi_value &object, const A2dpCod napi_set_named_property(env, object, "codecChannelMode", value); napi_create_int32(env, codecInfo.codecSampleRate, &value); napi_set_named_property(env, object, "codecSampleRate", value); + napi_create_int32(env, codecInfo.codecBitRate, &value); + napi_set_named_property(env, object, "codecBitRate", value); + napi_create_int32(env, CODEC_FRAME_LENGTH_10MS, &value); // only 10ms frame length is supported + napi_set_named_property(env, object, "codecFrameLength", value); +} + +static void ConvertCodecType(napi_env env, napi_value &object, int32_t codecType) +{ + auto iter = g_a2dpCodecTypeMap.find(codecType); + int codecType_ = -1; + if (iter != g_a2dpCodecTypeMap.end()) { + codecType_ = iter->second; + } else { + HILOGE("not find valid codec type"); + } + napi_value value = nullptr; + napi_create_int32(env, codecType_, &value); + napi_set_named_property(env, object, "codecType", value); +} + +static void ConvertCodecBitsPerSampleVector(napi_env env, napi_value &object, int32_t codecSampleRate) +{ + int count = 0; + napi_value value = nullptr; + napi_value codecBitsPerSampleArray = nullptr; + napi_create_array(env, &codecBitsPerSampleArray); + + if (codecSampleRate == A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_NONE_USER) { + napi_create_int32(env, CODEC_BITS_PER_SAMPLE_NONE, &value); + napi_set_element(env, codecBitsPerSampleArray, count, value); + count++; + } + if (codecSampleRate & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_16_USER) { + napi_create_int32(env, CODEC_BITS_PER_SAMPLE_16, &value); + napi_set_element(env, codecBitsPerSampleArray, count, value); + count++; + } + if (codecSampleRate & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_24_USER) { + napi_create_int32(env, CODEC_BITS_PER_SAMPLE_24, &value); + napi_set_element(env, codecBitsPerSampleArray, count, value); + count++; + } + if (codecSampleRate & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_32_USER) { + napi_create_int32(env, CODEC_BITS_PER_SAMPLE_32, &value); + napi_set_element(env, codecBitsPerSampleArray, count, value); + count++; + } + + napi_set_named_property(env, object, "codecBitsPerSampleArray", codecBitsPerSampleArray); +} + +static void ConvertCodecChannelModeVector(napi_env env, napi_value &object, int32_t channelMode) +{ + int count = 0; + napi_value value = nullptr; + napi_value codecChannelModeArray = nullptr; + napi_create_array(env, &codecChannelModeArray); + if (channelMode == A2dpUserCodecChannelMode::A2DP_CHANNEL_MODE_NONE_USER) { + napi_create_int32(env, CODEC_CHANNEL_MODE_NONE, &value); + napi_set_element(env, codecChannelModeArray, count, value); + count++; + } + if (channelMode & A2dpUserCodecChannelMode::A2DP_SBC_CHANNEL_MODE_MONO_USER) { + napi_create_int32(env, CODEC_CHANNEL_MODE_MONO, &value); + napi_set_element(env, codecChannelModeArray, count, value); + count++; + } + if (channelMode & A2dpUserCodecChannelMode::A2DP_SBC_CHANNEL_MODE_MONO_STEREO_USER) { + napi_create_int32(env, CODEC_CHANNEL_MODE_STEREO, &value); + napi_set_element(env, codecChannelModeArray, count, value); + count++; + } + + napi_set_named_property(env, object, "codecChannelModeArray", codecChannelModeArray); +} + +static void ConvertCodecSampleRateVector(napi_env env, napi_value &object, int32_t codecSampleRate) +{ + int count = 0; + napi_value value = nullptr; + napi_value codecSampleRateArray = nullptr; + napi_create_array(env, &codecSampleRateArray); + if (codecSampleRate == A2dpUserCodecSampleRate::A2DP_SAMPLE_RATE_NONE_USER) { + napi_create_int32(env, CODEC_SAMPLE_RATE_NONE, &value); + napi_set_element(env, codecSampleRateArray, count, value); + count++; + } + if (codecSampleRate & A2dpUserCodecSampleRate::A2DP_SBC_SAMPLE_RATE_44100_USER) { + napi_create_int32(env, CODEC_SAMPLE_RATE_44100, &value); + napi_set_element(env, codecSampleRateArray, count, value); + count++; + } + if (codecSampleRate & A2dpUserCodecSampleRate::A2DP_L2HCV2_SAMPLE_RATE_48000_USER) { + napi_create_int32(env, CODEC_SAMPLE_RATE_48000, &value); + napi_set_element(env, codecSampleRateArray, count, value); + count++; + } + if (codecSampleRate & A2dpUserCodecSampleRate::A2DP_L2HCV2_SAMPLE_RATE_96000_USER) { + napi_create_int32(env, CODEC_SAMPLE_RATE_96000, &value); + napi_set_element(env, codecSampleRateArray, count, value); + count++; + } + + napi_set_named_property(env, object, "codecSampleRateArray", codecSampleRateArray); +} + +static void ConvertCodecBitRateVector(napi_env env, napi_value &object, int32_t codecBitRate) +{ + int count = 0; + napi_value value = nullptr; + napi_value codecBitRateArray = nullptr; + napi_create_array(env, &codecBitRateArray); + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_96K) { + napi_create_int32(env, CODEC_BIT_RATE_96000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_192K) { + napi_create_int32(env, CODEC_BIT_RATE_192000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_256K) { + napi_create_int32(env, CODEC_BIT_RATE_256000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_320K) { + napi_create_int32(env, CODEC_BIT_RATE_320000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_480K) { + napi_create_int32(env, CODEC_BIT_RATE_480000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_640K) { + napi_create_int32(env, CODEC_BIT_RATE_640000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_960K) { + napi_create_int32(env, CODEC_BIT_RATE_960000, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_AUTO_RATE) { + napi_create_int32(env, CODEC_BIT_RATE_ABR, &value); + napi_set_element(env, codecBitRateArray, count, value); + count++; + } + napi_set_named_property(env, object, "codecBitRateArray", codecBitRateArray); +} + +static void ConvertCodecFrameLengthVector(napi_env env, napi_value &object, int32_t codecSampleRate) +{ + + napi_value codecFrameLengthArray = nullptr; + napi_create_array(env, &codecFrameLengthArray); + int count = 0; + napi_value value = nullptr; + napi_create_int32(env, CODEC_FRAME_LENGTH_10MS, &value); // only 10ms frame length is supported + napi_set_element(env, codecFrameLengthArray, count, value); + napi_set_named_property(env, object, "codecFrameLengthArray", codecFrameLengthArray); +} + +static void ConvertCodecInfoListToJS(napi_env env, napi_value &object, const A2dpCodecInfo &a2dpCodecInfo) +{ + ConvertCodecType(env, object, a2dpCodecInfo.codecType); + ConvertCodecBitsPerSampleVector(env, object, a2dpCodecInfo.bitsPerSample); + ConvertCodecChannelModeVector(env, object, a2dpCodecInfo.channelMode); + ConvertCodecSampleRateVector(env, object, a2dpCodecInfo.sampleRate); + ConvertCodecBitRateVector(env, object, a2dpCodecInfo.codecSpecific3); + ConvertCodecFrameLengthVector(env, object, a2dpCodecInfo.codecSpecific2); +} + +static void ConvertCodecInfoConfirmedCapToJs(napi_env env, napi_value &object, + const std::vector &codecInfoConfirmedCap) +{ + size_t count = 0; + for (auto &iter : codecInfoConfirmedCap) { + napi_value temp = nullptr; + napi_create_object(env, &temp); + ConvertCodecInfoListToJS(env, temp, iter); + napi_set_element(env, object, count, temp); + count++; + } } static napi_status CheckSetCodecPreferenceParam(napi_env env, napi_callback_info info, @@ -633,8 +913,8 @@ static napi_status CheckSetCodecPreferenceParam(napi_env env, napi_callback_info NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); NAPI_BT_CALL_RETURN(NapiParseBdAddr(env, argv[PARAM0], addr)); - NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName( - env, argv[PARAM1], {"codecType", "codecBitsPerSample", "codecChannelMode", "codecSampleRate"})); + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, argv[PARAM1], {"codecType", + "codecBitsPerSample", "codecChannelMode", "codecSampleRate", "codecBitRate", "codecFrameLength"})); // parse codecInfo int32_t codecType = 0; NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, argv[PARAM1], "codecType", codecType)); @@ -648,6 +928,10 @@ static napi_status CheckSetCodecPreferenceParam(napi_env env, napi_callback_info int32_t codecSampleRate = 0; NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, argv[PARAM1], "codecSampleRate", codecSampleRate)); ConvertCodecSampleRate(a2dpCodecInfo, codecSampleRate); + if (NapiIsObjectPropertyExist(env, argv[PARAM1], "codecBitRate")) { + int32_t codecBitRate = 0; + ConvertCodecBitRate(a2dpCodecInfo, codecBitRate); + } return napi_ok; } @@ -684,6 +968,24 @@ napi_value NapiA2dpSource::GetCurrentCodecInfo(napi_env env, napi_callback_info return ret; } +napi_value NapiA2dpSource::GetCurrentFullCodecInfo(napi_env env, napi_callback_info info) +{ + HILOGI("start"); + napi_value ret = nullptr; + napi_create_array(env, &ret); + + std::string remoteAddr{}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN(env, checkRet, BT_ERR_INVALID_PARAM, ret); + A2dpCodecStatus a2dpCodecStatus; + int transport = BT_TRANSPORT_BREDR; + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr, transport); + A2dpSource *profile = A2dpSource::GetProfile(); + a2dpCodecStatus = profile->GetCodecStatus(remoteDevice); + ConvertCodecInfoConfirmedCapToJs(env, ret, a2dpCodecStatus.codecInfoConfirmedCap); + return ret; +} + napi_value NapiA2dpSource::EnableAutoPlay(napi_env env, napi_callback_info info) { std::string deviceId = INVALID_MAC_ADDRESS; diff --git a/interfaces/inner_api/include/bluetooth_def.h b/interfaces/inner_api/include/bluetooth_def.h index a111f450..9707fb7c 100644 --- a/interfaces/inner_api/include/bluetooth_def.h +++ b/interfaces/inner_api/include/bluetooth_def.h @@ -1399,6 +1399,35 @@ enum A2dpUserCodecBitsPerSample : uint8_t { A2DP_AAC_SAMPLE_BITS_OCTET5_BIT7_USER = 0x01 << 7, /* octet5 b6 */ }; +/** + * @brief A2dp codec bit rate enum. + * + * @since 19 + */ +enum A2dpUserCodecBitRate : uint8_t { + A2DP_L2HCST_BIT_RATE_DEFAULT = 0x0, + A2DP_L2HCST_BIT_RATE_320K = 0x01, + A2DP_L2HCST_BIT_RATE_640K = 0x01 << 1, + A2DP_L2HCST_BIT_RATE_960K = 0x01 << 2, + A2DP_L2HCST_BIT_RATE_AUTO_RATE = 0x01 << 3, + A2DP_L2HCST_BIT_RATE_96K = 0x01 << 4, + A2DP_L2HCST_BIT_RATE_LOSSLESS = 0x01 << 5, + A2DP_L2HCST_BIT_RATE_128K = 0x01 << 6, + A2DP_L2HCST_BIT_RATE_192K = 0x01 << 7, + A2DP_L2HCST_BIT_RATE_256K = 0x01 << 8, + A2DP_L2HCST_BIT_RATE_480K = 0x01 << 9, +}; + +/** + * @brief A2dp codec frame length enum. + * + * @since 19 + */ +enum A2dpUserCodecFrameLength : uint8_t { + A2DP_L2HCST_FRAME_LENGTH_5MS = 0x01, + A2DP_L2HCST_FRAME_LENGTH_10MS = 0x01 << 1, +}; + /** * @brief Pbap action Type. * diff --git a/interfaces/inner_api/include/bluetooth_errorcode.h b/interfaces/inner_api/include/bluetooth_errorcode.h index 286d8a66..47cceb11 100644 --- a/interfaces/inner_api/include/bluetooth_errorcode.h +++ b/interfaces/inner_api/include/bluetooth_errorcode.h @@ -63,6 +63,7 @@ enum BtErrCode { BT_ERR_AUDIO_NOT_IDLE = BT_ERR_BASE_SYSCAP + 2005, BT_ERR_VIRTUAL_CALL_NOT_STARTED = BT_ERR_BASE_SYSCAP + 2006, BT_ERR_DISCONNECT_SCO_FAILED = BT_ERR_BASE_SYSCAP + 2007, + BT_ERR_NO_ACTIVE_A2DP_DEVICE = BT_ERR_BASE_SYSCAP + 2008, BT_ERR_BLE_SCAN_ALREADY_STARTED = BT_ERR_BASE_SYSCAP + 2050, BT_ERR_BLE_SCAN_MAX_FILTER = BT_ERR_BASE_SYSCAP + 2051, -- Gitee From 7381714963cd380ec0df12960ee39f43324aebaa Mon Sep 17 00:00:00 2001 From: yangkuo <1041733144@qq.com> Date: Mon, 14 Apr 2025 18:49:38 +0800 Subject: [PATCH 16/45] fix space Signed-off-by: yangkuo <1041733144@qq.com> --- frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp index 7e377401..834ad2ce 100644 --- a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp +++ b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp @@ -872,7 +872,6 @@ static void ConvertCodecBitRateVector(napi_env env, napi_value &object, int32_t static void ConvertCodecFrameLengthVector(napi_env env, napi_value &object, int32_t codecSampleRate) { - napi_value codecFrameLengthArray = nullptr; napi_create_array(env, &codecFrameLengthArray); int count = 0; -- Gitee From 41fc52b7703d2db32b6e3e3b1b004e140a56b91c Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Mon, 14 Apr 2025 18:47:46 +0800 Subject: [PATCH 17/45] getDeviceName bugfix Signed-off-by: linzlinz <2495670683@qq.com> --- .../js/napi/src/ble/napi_bluetooth_gatt_client.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp index 6f5c3459..c9c812e9 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp @@ -551,10 +551,13 @@ napi_value NapiGattClient::GetDeviceName(napi_env env, napi_callback_info info) auto status = CheckGattClientGetDeviceName(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); - - auto func = []() { + NapiGattClient *napiGattClient = NapiGetGattClient(env, info); + std::string deviceAddr = ""; + if (napiGattClient && napiGattClient->GetDevice()) { + deviceAddr = napiGattClient->GetDevice()->GetDeviceAddr(); + } + auto func = [deviceAddr]() { std::string deviceName = ""; - std::string deviceAddr = GetGattClientDeviceId(); int32_t err = BluetoothHost::GetDefaultHost().GetRemoteDevice( deviceAddr, BT_TRANSPORT_BLE).GetDeviceName(deviceName); -- Gitee From 9411a371909a61395bc44ec6fc6d3a11dc98101e Mon Sep 17 00:00:00 2001 From: lee Date: Thu, 24 Apr 2025 10:47:52 +0800 Subject: [PATCH 18/45] revert change Signed-off-by: lee Change-Id: I30a1a28770b07af014916ac6517dae5f1ef08815 --- .../js/napi/include/napi_bluetooth_error.h | 4 +- .../napi/src/common/napi_bluetooth_error.cpp | 64 ++----------------- 2 files changed, 6 insertions(+), 62 deletions(-) diff --git a/frameworks/js/napi/include/napi_bluetooth_error.h b/frameworks/js/napi/include/napi_bluetooth_error.h index 54ce10ab..ba995d24 100644 --- a/frameworks/js/napi/include/napi_bluetooth_error.h +++ b/frameworks/js/napi/include/napi_bluetooth_error.h @@ -61,8 +61,8 @@ do { \ NAPI_BT_ASSERT_RETURN((env), (cond), (errCode), res); \ } while (0) -std::string GetNapiErrMsg(napi_env env, int32_t errCode); -void HandleSyncErr(napi_env env, int32_t errCode); +std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode); +void HandleSyncErr(const napi_env &env, int32_t errCode); } } #endif \ No newline at end of file diff --git a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp index 30347639..049f95b6 100644 --- a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp +++ b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp @@ -20,11 +20,6 @@ #include "bluetooth_errorcode.h" #include "napi_bluetooth_utils.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" -#include "bundle_mgr_proxy.h" - -static const int SDK_VERSION_13 = 13; namespace OHOS { namespace Bluetooth { @@ -61,52 +56,7 @@ static std::map napiErrMsgMap { { BtErrCode::BT_ERR_DISCONNECT_SCO_FAILED, "Disconnect sco failed." }, }; -static int GetSdkVersion(void) -{ - int version = SDK_VERSION_13; // default sdk version is api 13 - - auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (!systemAbilityManager) { - HILOGE("fail to get system ability mgr."); - return version; - } - auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (!remoteObject) { - HILOGE("fail to get bundle manager proxy."); - return version; - } - sptr bundleMgrProxy = iface_cast(remoteObject); - if (bundleMgrProxy == nullptr) { - HILOGE("Failed to get bundle manager proxy."); - return version; - } - AppExecFwk::BundleInfo bundleInfo; - auto flags = AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION; - auto ret = bundleMgrProxy->GetBundleInfoForSelf(static_cast(flags), bundleInfo); - if (ret != ERR_OK) { - HILOGE("GetBundleInfoForSelf: get fail."); - return version; - } - - version = bundleInfo.targetVersion % 100; // %100 to get the real version - return version; -} - -static napi_value GenerateBusinessError(napi_env env, int32_t errCode, const std::string &errMsg) -{ - napi_value businessError = nullptr; - napi_value code = nullptr; - napi_create_int32(env, errCode, &code); - - napi_value message = nullptr; - napi_create_string_utf8(env, errMsg.c_str(), NAPI_AUTO_LENGTH, &message); - - napi_create_error(env, nullptr, message, &businessError); - napi_set_named_property(env, businessError, "code", code); - return businessError; -} - -std::string GetNapiErrMsg(napi_env env, int32_t errCode) +std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode) { auto iter = napiErrMsgMap.find(errCode); if (iter != napiErrMsgMap.end()) { @@ -117,21 +67,15 @@ std::string GetNapiErrMsg(napi_env env, int32_t errCode) return "Inner error."; } -void HandleSyncErr(napi_env env, int32_t errCode) +void HandleSyncErr(const napi_env &env, int32_t errCode) { if (errCode == BtErrCode::BT_NO_ERROR) { return; } - - int ret = -1; std::string errMsg = GetNapiErrMsg(env, errCode); - // In API13 version, the error code type is changed from string to number. - if (GetSdkVersion() >= SDK_VERSION_13) { - ret = napi_throw(env, GenerateBusinessError(env, errCode, errMsg)); - } else { - ret = napi_throw_error(env, std::to_string(errCode).c_str(), errMsg.c_str()); + if (errMsg != "") { + napi_throw_error(env, std::to_string(errCode).c_str(), errMsg.c_str()); } - CHECK_AND_RETURN_LOG(ret == napi_ok, "napi_throw failed, ret: %{public}d", ret); } } } \ No newline at end of file -- Gitee From ff2aacd4eabe5c0ddf6ef95f58a8aa063074ac18 Mon Sep 17 00:00:00 2001 From: dengguanghong <2228266166@qq.com> Date: Thu, 24 Apr 2025 16:28:07 +0800 Subject: [PATCH 19/45] Signed-off-by:dengguanghong<2228266166@qq.com> --- frameworks/inner/ipc/src/bluetooth_host_proxy.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp index 64a12712..c7fee8a7 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -1553,8 +1553,11 @@ int32_t BluetoothHostProxy::GetRandomAddress(const std::string &realAddr, std::s HILOGE("BluetoothHostProxy::GetRandomAddress fail, error: %{public}d", error); return BT_ERR_IPC_TRANS_FAILED; } - randomAddr = reply.ReadString(); - return reply.ReadInt32(); + int32_t exception = reply.ReadInt32(); + if (exception == BT_NO_ERROR) { + randomAddr = reply.ReadString(); + } + return exception; } int32_t BluetoothHostProxy::SyncRandomAddress(const std::string &realAddr, const std::string &randomAddr) -- Gitee From 345d17259b3dc9ab9e478812d7a03fe62f190750 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Sun, 27 Apr 2025 11:12:47 +0800 Subject: [PATCH 20/45] bugfix xts Signed-off-by: linzlinz <2495670683@qq.com> --- .../ipc/include/bluetooth_ble_central_manager_proxy.h | 2 +- .../inner/ipc/interface/i_bluetooth_ble_central_manager.h | 2 +- .../inner/ipc/src/bluetooth_ble_central_manager_proxy.cpp | 7 ++++++- frameworks/inner/src/bluetooth_ble_central_manager.cpp | 7 ++++++- frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp | 1 + .../inner_api/include/bluetooth_ble_central_manager.h | 2 ++ 6 files changed, 17 insertions(+), 4 deletions(-) diff --git a/frameworks/inner/ipc/include/bluetooth_ble_central_manager_proxy.h b/frameworks/inner/ipc/include/bluetooth_ble_central_manager_proxy.h index 7ae2a8d8..c3356a0c 100644 --- a/frameworks/inner/ipc/include/bluetooth_ble_central_manager_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_ble_central_manager_proxy.h @@ -33,7 +33,7 @@ public: void DeregisterBleCentralManagerCallback(int32_t scannerId, const sptr &callback) override; int StartScan(int32_t scannerId, const BluetoothBleScanSettings &settings, - const std::vector &filters) override; + const std::vector &filters, bool isNewApi) override; int StopScan(int32_t scannerId) override; void RemoveScanFilter(int32_t scannerId) override; bool FreezeByRss(std::set pidSet, bool isProxy) override; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_ble_central_manager.h b/frameworks/inner/ipc/interface/i_bluetooth_ble_central_manager.h index b5313703..a078247b 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_ble_central_manager.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_ble_central_manager.h @@ -54,7 +54,7 @@ public: virtual void DeregisterBleCentralManagerCallback(int32_t scannerId, const sptr &callback) = 0; virtual int StartScan(int32_t scannerId, const BluetoothBleScanSettings &settings, - const std::vector &filters) = 0; + const std::vector &filters, bool isNewApi) = 0; virtual int StopScan(int32_t scannerId) = 0; virtual void RemoveScanFilter(int32_t scannerId) = 0; virtual bool FreezeByRss(std::set pidSet, bool isProxy) = 0; diff --git a/frameworks/inner/ipc/src/bluetooth_ble_central_manager_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_ble_central_manager_proxy.cpp index e009a057..726d1c8d 100644 --- a/frameworks/inner/ipc/src/bluetooth_ble_central_manager_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_ble_central_manager_proxy.cpp @@ -85,7 +85,7 @@ void BluetoothBleCentralManagerProxy::DeregisterBleCentralManagerCallback(int32_ } int BluetoothBleCentralManagerProxy::StartScan(int32_t scannerId, const BluetoothBleScanSettings &settings, - const std::vector &filters) + const std::vector &filters, bool isNewApi) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothBleCentralManagerProxy::GetDescriptor())) { @@ -114,6 +114,11 @@ int BluetoothBleCentralManagerProxy::StartScan(int32_t scannerId, const Bluetoot } } + if (!data.WriteBool(isNewApi)) { + HILOGE("[StartScan] fail: write isNewApi failed"); + return BT_ERR_INTERNAL_ERROR; + } + MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t result = InnerTransact(BLE_START_SCAN, option, data, reply); diff --git a/frameworks/inner/src/bluetooth_ble_central_manager.cpp b/frameworks/inner/src/bluetooth_ble_central_manager.cpp index d847b577..d576208e 100644 --- a/frameworks/inner/src/bluetooth_ble_central_manager.cpp +++ b/frameworks/inner/src/bluetooth_ble_central_manager.cpp @@ -371,7 +371,7 @@ int BleCentralManager::StartScan(const BleScanSettings &settings, const std::vec sptr proxy = GetRemoteProxy(BLE_CENTRAL_MANAGER_SERVER); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "failed: no proxy"); - return proxy->StartScan(pimpl->scannerId_, parcelSettings, parcelFilters); + return proxy->StartScan(pimpl->scannerId_, parcelSettings, parcelFilters, isNewApi_); } int BleCentralManager::StopScan() @@ -562,6 +562,11 @@ int BleCentralManager::ChangeScanParams(const BleScanSettings &settings, const s return proxy->ChangeScanParams(pimpl->scannerId_, parcelSetting, parcelFilters, filterAction); } +void BleCentralManager::SetNewApiFlag() +{ + isNewApi_ = true; +} + BleScanResult::BleScanResult() {} diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp index 3dc4db6b..f5264855 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp @@ -108,6 +108,7 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, napiBleScanner->GetCallback() != nullptr, BT_ERR_INVALID_PARAM); auto func = [napiBleScanner, settings, scanFilters]() { + napiBleScanner->GetBleCentralManager()->SetNewApiFlag(); int ret = napiBleScanner->GetBleCentralManager()->StartScan(settings, scanFilters); return NapiAsyncWorkRet(ret); }; diff --git a/interfaces/inner_api/include/bluetooth_ble_central_manager.h b/interfaces/inner_api/include/bluetooth_ble_central_manager.h index df620de2..7513196d 100644 --- a/interfaces/inner_api/include/bluetooth_ble_central_manager.h +++ b/interfaces/inner_api/include/bluetooth_ble_central_manager.h @@ -692,9 +692,11 @@ public: int ChangeScanParams(const BleScanSettings &settings, const std::vector &filter, uint32_t filterAction); + void SetNewApiFlag(); private: BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BleCentralManager); BLUETOOTH_DECLARE_IMPL(); + bool isNewApi_ = false; }; } // namespace Bluetooth } // namespace OHOS -- Gitee From 7b5b29ad4d97e9564e044e4d25e06fecf1ef146e Mon Sep 17 00:00:00 2001 From: dutianyi Date: Wed, 7 May 2025 08:35:40 +0000 Subject: [PATCH 21/45] fix gatt handle Signed-off-by: dutianyi --- frameworks/inner/src/bluetooth_gatt_client.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 84e2958b..e1bcaa52 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -462,7 +462,7 @@ void GattClient::impl::BuildServiceList(const std::vector HILOGI("enter"); for (auto &svc : src) { GattService svcTmp(UUID::ConvertFrom128Bits(svc.uuid_.ConvertTo128Bits()), - svc.handle_, + svc.startHandle_, svc.endHandle_, svc.isPrimary_ ? GattServiceType::PRIMARY : GattServiceType::SECONDARY); for (auto &character : svc.characteristics_) { -- Gitee From 7c09d284c84ee23584d977971fa92d722ceb66c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E9=98=94?= Date: Thu, 8 May 2025 21:24:08 +0800 Subject: [PATCH 22/45] fix codecheck MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 杨阔 --- .../napi/src/a2dp/napi_bluetooth_a2dp_src.cpp | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp index 834ad2ce..b07a45f3 100644 --- a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp +++ b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp @@ -652,7 +652,7 @@ static void ConvertCodecBitRate(A2dpCodecInfo &a2dpCodecInfo, int32_t codecBitRa { auto iter = g_codecBitRateMap.find(codecBitRate); if (iter != g_codecBitRateMap.end()) { - a2dpCodecInfo.codecSpecific3 = iter->second; + a2dpCodecInfo.codecSpecific4 = iter->second; } } @@ -704,7 +704,7 @@ static void ConvertCodecInfoToJs(napi_env env, napi_value &object, const A2dpCod ConvertCodecChannelModeToCodecInfo(codecInfo, a2dpCodecInfo.channelMode); ConvertCodecBitsPerSampleToCodecInfo(codecInfo, a2dpCodecInfo.bitsPerSample); ConvertCodecTypeToCodecInfo(codecInfo, a2dpCodecInfo.codecType); - ConvertCodecBitRateToCodecInfo(codecInfo, a2dpCodecInfo.codecSpecific3); + ConvertCodecBitRateToCodecInfo(codecInfo, a2dpCodecInfo.codecSpecific4); // convert CodecInfo to JS napi_value value = nullptr; napi_create_int32(env, codecInfo.codecType, &value); @@ -747,17 +747,17 @@ static void ConvertCodecBitsPerSampleVector(napi_env env, napi_value &object, in napi_set_element(env, codecBitsPerSampleArray, count, value); count++; } - if (codecSampleRate & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_16_USER) { + if (static_cast(codecSampleRate) & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_16_USER) { napi_create_int32(env, CODEC_BITS_PER_SAMPLE_16, &value); napi_set_element(env, codecBitsPerSampleArray, count, value); count++; } - if (codecSampleRate & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_24_USER) { + if (static_cast(codecSampleRate) & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_24_USER) { napi_create_int32(env, CODEC_BITS_PER_SAMPLE_24, &value); napi_set_element(env, codecBitsPerSampleArray, count, value); count++; } - if (codecSampleRate & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_32_USER) { + if (static_cast(codecSampleRate) & A2dpUserCodecBitsPerSample::A2DP_SAMPLE_BITS_32_USER) { napi_create_int32(env, CODEC_BITS_PER_SAMPLE_32, &value); napi_set_element(env, codecBitsPerSampleArray, count, value); count++; @@ -777,12 +777,12 @@ static void ConvertCodecChannelModeVector(napi_env env, napi_value &object, int3 napi_set_element(env, codecChannelModeArray, count, value); count++; } - if (channelMode & A2dpUserCodecChannelMode::A2DP_SBC_CHANNEL_MODE_MONO_USER) { + if (static_cast(channelMode) & A2dpUserCodecChannelMode::A2DP_SBC_CHANNEL_MODE_MONO_USER) { napi_create_int32(env, CODEC_CHANNEL_MODE_MONO, &value); napi_set_element(env, codecChannelModeArray, count, value); count++; } - if (channelMode & A2dpUserCodecChannelMode::A2DP_SBC_CHANNEL_MODE_MONO_STEREO_USER) { + if (static_cast(channelMode) & A2dpUserCodecChannelMode::A2DP_SBC_CHANNEL_MODE_MONO_STEREO_USER) { napi_create_int32(env, CODEC_CHANNEL_MODE_STEREO, &value); napi_set_element(env, codecChannelModeArray, count, value); count++; @@ -802,17 +802,17 @@ static void ConvertCodecSampleRateVector(napi_env env, napi_value &object, int32 napi_set_element(env, codecSampleRateArray, count, value); count++; } - if (codecSampleRate & A2dpUserCodecSampleRate::A2DP_SBC_SAMPLE_RATE_44100_USER) { + if (static_cast(codecSampleRate) & A2dpUserCodecSampleRate::A2DP_SBC_SAMPLE_RATE_44100_USER) { napi_create_int32(env, CODEC_SAMPLE_RATE_44100, &value); napi_set_element(env, codecSampleRateArray, count, value); count++; } - if (codecSampleRate & A2dpUserCodecSampleRate::A2DP_L2HCV2_SAMPLE_RATE_48000_USER) { + if (static_cast(codecSampleRate) & A2dpUserCodecSampleRate::A2DP_L2HCV2_SAMPLE_RATE_48000_USER) { napi_create_int32(env, CODEC_SAMPLE_RATE_48000, &value); napi_set_element(env, codecSampleRateArray, count, value); count++; } - if (codecSampleRate & A2dpUserCodecSampleRate::A2DP_L2HCV2_SAMPLE_RATE_96000_USER) { + if (static_cast(codecSampleRate) & A2dpUserCodecSampleRate::A2DP_L2HCV2_SAMPLE_RATE_96000_USER) { napi_create_int32(env, CODEC_SAMPLE_RATE_96000, &value); napi_set_element(env, codecSampleRateArray, count, value); count++; @@ -827,42 +827,42 @@ static void ConvertCodecBitRateVector(napi_env env, napi_value &object, int32_t napi_value value = nullptr; napi_value codecBitRateArray = nullptr; napi_create_array(env, &codecBitRateArray); - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_96K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_96K) { napi_create_int32(env, CODEC_BIT_RATE_96000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_192K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_192K) { napi_create_int32(env, CODEC_BIT_RATE_192000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_256K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_256K) { napi_create_int32(env, CODEC_BIT_RATE_256000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_320K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_320K) { napi_create_int32(env, CODEC_BIT_RATE_320000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_480K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_480K) { napi_create_int32(env, CODEC_BIT_RATE_480000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_640K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_640K) { napi_create_int32(env, CODEC_BIT_RATE_640000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_960K) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_960K) { napi_create_int32(env, CODEC_BIT_RATE_960000, &value); napi_set_element(env, codecBitRateArray, count, value); count++; } - if (codecBitRate & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_AUTO_RATE) { + if (static_cast(codecBitRate) & A2dpUserCodecBitRate::A2DP_L2HCST_BIT_RATE_AUTO_RATE) { napi_create_int32(env, CODEC_BIT_RATE_ABR, &value); napi_set_element(env, codecBitRateArray, count, value); count++; -- Gitee From 917eea0482389241ff8c65417380a0e15b060462 Mon Sep 17 00:00:00 2001 From: yangyang Date: Mon, 12 May 2025 17:45:03 +0800 Subject: [PATCH 23/45] Reapply "add collaboration msg defination between AP and lpdevice" This reverts commit 18f57e9d49774bdd2d47a76e0d2b03bf0740f98e. Signed-off-by: yangyang --- frameworks/inner/ipc/common/bt_def.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index e2d79381..3a4d2e28 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -457,6 +457,7 @@ typedef enum { SCAN_MODE_OP_P2_30_1500 = 0x09, SCAN_MODE_OP_P75_30_40 = 0x0A, SCAN_MODE_OP_P50_30_60 = 0x0B, + SCAN_MODE_OP_MAX, } SCAN_MODE; // Scan callback type @@ -519,6 +520,17 @@ constexpr int8_t BLE_LPDEVICE_MSG_UUID_DATA = 0x0a; constexpr int8_t BLE_LPDEVICE_MSG_ADV_HANDLE = 0x0b; constexpr int8_t BLE_LPDEVICE_MSG_SCAN_STATUS = 0x0c; constexpr int8_t BLE_LPDEVICE_MSG_SCAN_PARAM = 0x0d; +constexpr int8_t BLE_LPDEVICE_MSG_CAPABILITY_QUERY = 0x13; +constexpr int8_t BLE_LPDEVICE_MSG_SCAN_COLLABORATION_QUERY = 0x14; +constexpr int8_t BLE_LPDEVICE_MSG_SCAN_COLLABORATION_RESULT = 0x15; +constexpr int8_t BLE_LPDEVICE_MSG_GATT_CONN_COLLABORATION_QUERY = 0x16; +constexpr int8_t BLE_LPDEVICE_MSG_GATT_CONN_COLLABORATION_RESULT = 0x17; +constexpr int8_t BLE_LPDEVICE_MSG_SET_BLE_BUFFER_SIZE_AND_NUM = 0x18; + +// collaboration msg from lpdevice +constexpr uint8_t BLE_LPDEVICE_MSG_CAPABILITY = 0x01; +constexpr uint8_t BLE_LPDEVICE_MSG_SCAN_COLLABORATION_NOTIFY_STATUS = 0x02; +constexpr uint8_t BLE_LPDEVICE_MSG_GATT_CONN_COLLABORATION_NOTIFY_STATUS = 0x03; constexpr uint8_t BLE_LPDEVICE_MSG_TYPE_NOTICE_UP_DATA = 0x02; -- Gitee From 300ab8d605810fd4f5af5973205c58a07f3c8d2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=B9=BF=E7=94=9F?= Date: Thu, 15 May 2025 03:27:16 +0000 Subject: [PATCH 24/45] fix format for arm64 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马广生 --- frameworks/js/napi/src/opp/napi_bluetooth_opp.cpp | 4 ++-- frameworks/js/napi/src/parser/napi_parser_utils.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/frameworks/js/napi/src/opp/napi_bluetooth_opp.cpp b/frameworks/js/napi/src/opp/napi_bluetooth_opp.cpp index c341ff61..c8a354e9 100644 --- a/frameworks/js/napi/src/opp/napi_bluetooth_opp.cpp +++ b/frameworks/js/napi/src/opp/napi_bluetooth_opp.cpp @@ -136,7 +136,7 @@ napi_value NapiBluetoothOpp::SendFile(napi_env env, napi_callback_info info) auto status = CheckSendFileParam(env, info, device, fileHolders); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); - HILOGI("fileHolders size is %{public}u", fileHolders.size()); + HILOGI("fileHolders size is %{public}zu", fileHolders.size()); auto func = [device, fileHolders]() { Opp *profile = Opp::GetProfile(); @@ -146,7 +146,7 @@ napi_value NapiBluetoothOpp::SendFile(napi_env env, napi_callback_info info) oppFileHolders.push_back(BluetoothOppFileHolder(fileHolder.filePath, fileHolder.fileSize, fileHolder.fileFd)); } - HILOGI("oppFileHolders size is %{public}u", oppFileHolders.size()); + HILOGI("oppFileHolders size is %{public}zu", oppFileHolders.size()); int32_t errorCode = profile->SendFile(device, oppFileHolders, result); HILOGI("err: %{public}d result: %{public}d", errorCode, result); return NapiAsyncWorkRet(errorCode); diff --git a/frameworks/js/napi/src/parser/napi_parser_utils.cpp b/frameworks/js/napi/src/parser/napi_parser_utils.cpp index b052f0af..d9f35e5c 100644 --- a/frameworks/js/napi/src/parser/napi_parser_utils.cpp +++ b/frameworks/js/napi/src/parser/napi_parser_utils.cpp @@ -22,7 +22,7 @@ #include #include "napi_async_callback.h" - +#include namespace OHOS { namespace Bluetooth { @@ -368,7 +368,7 @@ napi_status NapiParseFileHolder(napi_env env, napi_value object, FileHolder &out NAPI_BT_CALL_RETURN(NapiParseObjectString(env, object, "filePath", filePath)); NAPI_BT_CALL_RETURN(NapiParseObjectInt64(env, object, "fileSize", fileSize)); NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, object, "fileFd", fileFd)); - HILOGI("fileSize: %{public}lld fileFd: %{public}d", fileSize, fileFd); + HILOGI("fileSize: %{public}" PRId64 "fileFd: %{public}d", fileSize, fileFd); FileHolder fileHolder; fileHolder.filePath = filePath; -- Gitee From e2440d8d524ba2f06229b8de07189a5e6f74ffa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=AC=E5=A3=AB=E8=BE=B0?= Date: Thu, 15 May 2025 16:48:36 +0800 Subject: [PATCH 25/45] Umetrip_master MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 马士辰 --- frameworks/inner/c_adapter/ohos_bt_socket.cpp | 40 ++++++++++++++++++- .../inner/ipc/include/bluetooth_host_proxy.h | 2 +- .../inner/ipc/interface/i_bluetooth_host.h | 2 +- .../inner/ipc/src/bluetooth_host_proxy.cpp | 6 ++- frameworks/inner/src/bluetooth_host.cpp | 4 +- frameworks/inner/src/bluetooth_socket.cpp | 2 +- .../inner_api/include/bluetooth_errorcode.h | 1 + interfaces/inner_api/include/bluetooth_host.h | 3 +- .../include/c_header/ohos_bt_socket.h | 11 +++++ 9 files changed, 63 insertions(+), 8 deletions(-) diff --git a/frameworks/inner/c_adapter/ohos_bt_socket.cpp b/frameworks/inner/c_adapter/ohos_bt_socket.cpp index 8c42d92b..87e1a310 100644 --- a/frameworks/inner/c_adapter/ohos_bt_socket.cpp +++ b/frameworks/inner/c_adapter/ohos_bt_socket.cpp @@ -92,7 +92,16 @@ static bool GetSocketUuidPara(const BluetoothCreateSocketPara *socketPara, UUID } serverUuid = UUID::FromString(tmpUuid); } else if (socketPara->socketType == OHOS_SOCKET_L2CAP_LE) { - serverUuid = UUID::RandomUUID(); + if (socketPara->uuid.uuid == nullptr || strlen(socketPara->uuid.uuid) != socketPara->uuid.uuidLen) { + serverUuid = UUID::RandomUUID(); + } else { + string tmpUuid(socketPara->uuid.uuid); + if (!IsValidUuid(tmpUuid)) { + HILOGE("match the UUID faild."); + return false; + } + serverUuid = UUID::FromString(tmpUuid); + } } else { HILOGE("param socketType invalid. socketType: %{public}d", socketPara->socketType); return false; @@ -260,6 +269,9 @@ int SocketConnect(const BluetoothCreateSocketPara *socketPara, const BdAddr *bdA HILOGE("SocketConnect fail, result: %{public}d", result); client->Close(); HILOGE("SocketConnect closed."); + if (result == BT_ERR_SPP_CONNECT_FAILED) { + return BT_SOCEKET_CONNECT_FAILED; + } return BT_SOCKET_INVALID_ID; } int clientId = g_clientMap.AddObject(client); @@ -267,6 +279,32 @@ int SocketConnect(const BluetoothCreateSocketPara *socketPara, const BdAddr *bdA return clientId; } +/** + * @brief Obtain the device random address based on the device real address and tokenId. + * + * @param realAddr The remote device real address. + * @param randomAddr The remote device random address. + * @param tokenId The relative ID used to identify the current client socket. + * @return Returns the operation result status {@link BtStatus}. + */ +int GetRandomAddress(const BdAddr *realAddr, BdAddr *randomAddr, uint64_t tokenId) +{ + if (realAddr == nullptr || randomAddr == nullptr) { + HILOGE("realAddr is nullptr, or randomAddr is nullptr"); + return OHOS_BT_STATUS_FAIL; + } + + string strRealAddr; + ConvertAddr(realAddr->addr, strRealAddr); + string strRandomAddr; + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + int result = host->GetRandomAddress(strRealAddr, strRandomAddr, tokenId); + if (result == OHOS_BT_STATUS_SUCCESS) { + GetAddrFromString(strRandomAddr, randomAddr->addr); + } + return result; +} + /** * @brief Connects to a remote device over the socket. * This method will block until a connection is made or the connection fails. diff --git a/frameworks/inner/ipc/include/bluetooth_host_proxy.h b/frameworks/inner/ipc/include/bluetooth_host_proxy.h index 39727f8b..7f4165f6 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_host_proxy.h @@ -96,7 +96,7 @@ public: void RegisterBlePeripheralCallback(const sptr &observer) override; void DeregisterBlePeripheralCallback(const sptr &observer) override; int32_t SetFastScan(bool isEnable) override; - int32_t GetRandomAddress(const std::string &realAddr, std::string &randomAddr) override; + int32_t GetRandomAddress(const std::string &realAddr, std::string &randomAddr, uint64_t tokenId = 0) override; int32_t SyncRandomAddress(const std::string &realAddr, const std::string &randomAddr) override; int32_t ConnectAllowedProfiles(const std::string &remoteAddr) override; int32_t DisconnectAllowedProfiles(const std::string &remoteAddr) override; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_host.h b/frameworks/inner/ipc/interface/i_bluetooth_host.h index f455d567..2a188243 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host.h @@ -123,7 +123,7 @@ public: virtual void RegisterBlePeripheralCallback(const sptr &observer) = 0; virtual void DeregisterBlePeripheralCallback(const sptr &observer) = 0; virtual int32_t SetFastScan(bool isEnable) = 0; - virtual int32_t GetRandomAddress(const std::string &realAddr, std::string &randomAddr) = 0; + virtual int32_t GetRandomAddress(const std::string &realAddr, std::string &randomAddr, uint64_t tokenId = 0) = 0; virtual int32_t SyncRandomAddress(const std::string &realAddr, const std::string &randomAddr) = 0; virtual int32_t ConnectAllowedProfiles(const std::string &remoteAddr) = 0; virtual int32_t DisconnectAllowedProfiles(const std::string &remoteAddr) = 0; diff --git a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp index c7fee8a7..f8f76899 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -1535,7 +1535,7 @@ int32_t BluetoothHostProxy::SetFastScan(bool isEnable) return reply.ReadInt32(); } -int32_t BluetoothHostProxy::GetRandomAddress(const std::string &realAddr, std::string &randomAddr) +int32_t BluetoothHostProxy::GetRandomAddress(const std::string &realAddr, std::string &randomAddr, uint64_t tokenId) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { @@ -1546,6 +1546,10 @@ int32_t BluetoothHostProxy::GetRandomAddress(const std::string &realAddr, std::s HILOGE("BluetoothHostProxy::GetRandomAddress Write realAddr error"); return BT_ERR_IPC_TRANS_FAILED; } + if (!data.WriteUint64(tokenId)) { + HILOGE("BluetoothHostProxy::GetRandomAddress Write tokenId error"); + return BT_ERR_IPC_TRANS_FAILED; + } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(BluetoothHostInterfaceCode::GET_RANDOM_ADDRESS, option, data, reply); diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index efacb698..25415031 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1163,12 +1163,12 @@ int BluetoothHost::SetFastScan(bool isEnable) return proxy->SetFastScan(isEnable); } -int BluetoothHost::GetRandomAddress(const std::string &realAddr, std::string &randomAddr) const +int BluetoothHost::GetRandomAddress(const std::string &realAddr, std::string &randomAddr, uint64_t tokenId) const { CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr"); - return proxy->GetRandomAddress(realAddr, randomAddr); + return proxy->GetRandomAddress(realAddr, randomAddr, tokenId); } int BluetoothHost::ConnectAllowedProfiles(const std::string &remoteAddr) const diff --git a/frameworks/inner/src/bluetooth_socket.cpp b/frameworks/inner/src/bluetooth_socket.cpp index 28c04279..6db02798 100644 --- a/frameworks/inner/src/bluetooth_socket.cpp +++ b/frameworks/inner/src/bluetooth_socket.cpp @@ -465,7 +465,7 @@ int ClientSocket::Connect(int psm) HILOGI("fd_: %{public}d", pimpl->fd_); CHECK_AND_RETURN_LOG_RET(pimpl->fd_ != -1, BtStatus::BT_FAILURE, "connect failed!"); - CHECK_AND_RETURN_LOG_RET(pimpl->RecvSocketPsmOrScn(), BT_ERR_INVALID_STATE, "recv psm or scn failed"); + CHECK_AND_RETURN_LOG_RET(pimpl->RecvSocketPsmOrScn(), BT_ERR_SPP_CONNECT_FAILED, "recv psm or scn failed"); bool recvret = pimpl->RecvSocketSignal(); HILOGI("recvret: %{public}d", recvret); diff --git a/interfaces/inner_api/include/bluetooth_errorcode.h b/interfaces/inner_api/include/bluetooth_errorcode.h index 47cceb11..22762de4 100644 --- a/interfaces/inner_api/include/bluetooth_errorcode.h +++ b/interfaces/inner_api/include/bluetooth_errorcode.h @@ -42,6 +42,7 @@ enum BtErrCode { BT_ERR_UNAVAILABLE_PROXY = BT_ERR_BASE_SYSCAP + 8, BT_ERR_DIALOG_FOR_USER_CONFIRM = BT_ERR_BASE_SYSCAP + 9, BT_ERR_MAX_RESOURCES = BT_ERR_BASE_SYSCAP + 10, + BT_ERR_SPP_CONNECT_FAILED = BT_ERR_BASE_SYSCAP + 12, BT_ERR_INTERNAL_ERROR = BT_ERR_BASE_SYSCAP + 99, BT_ERR_IPC_TRANS_FAILED = BT_ERR_BASE_SYSCAP + 100, diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 04feabfe..76886b22 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -751,10 +751,11 @@ public: * the interface needs to be used for address translation. * @param realAddr real address. * @param[out] randomAddr random address. + * @param tokenId tokenId. * @return Returns {@link BT_NO_ERROR} if get random address success; * returns an error code defined in {@link BtErrCode} otherwise. */ - int GetRandomAddress(const std::string &realAddr, std::string &randomAddr) const; + int GetRandomAddress(const std::string &realAddr, std::string &randomAddr, uint64_t tokenId = 0) const; /** * @brief Connects all allowed bluetooth profiles between the local and remote device. diff --git a/interfaces/inner_api/include/c_header/ohos_bt_socket.h b/interfaces/inner_api/include/c_header/ohos_bt_socket.h index f91e2e33..02e1d277 100644 --- a/interfaces/inner_api/include/c_header/ohos_bt_socket.h +++ b/interfaces/inner_api/include/c_header/ohos_bt_socket.h @@ -32,6 +32,7 @@ extern "C" { #define BT_SOCKET_INVALID_SCN (-1) #define BT_SOCKET_INVALID_TYPE (-2) #define BT_SOCKET_LIMITED_RESOURCES (-3) +#define BT_SOCEKET_CONNECT_FAILED (-4) typedef enum { OHOS_SOCKET_SPP_RFCOMM = 0x0, @@ -221,6 +222,16 @@ int SetSocketBufferSize(int clientId, uint32_t bufferSize); */ int SocketUpdateCocConnectionParams(BluetoothCocUpdateSocketParam* param, const BdAddr *bdAddr); +/** + * @brief Obtain the device random address based on the device real address and tokenId. + * + * @param realAddr The remote device real address. + * @param randomAddr The remote device random address. + * @param tokenId The relative ID used to identify the current client socket. + * @return Returns the operation result status {@link BtStatus}. + */ +int GetRandomAddress(const BdAddr *realAddr, BdAddr *randomAddr, uint64_t tokenId); + #ifdef __cplusplus } #endif -- Gitee From 66c686482086b9a9df0237949a0a410979482f4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Thu, 15 May 2025 12:46:29 +0000 Subject: [PATCH 26/45] add ha event in napi MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- bundle.json | 1 + frameworks/js/napi/include/napi_async_work.h | 11 +- .../js/napi/include/napi_ha_event_utils.h | 49 +++++++ .../js/napi/src/ble/napi_bluetooth_ble.cpp | 30 +++- .../src/ble/napi_bluetooth_ble_scanner.cpp | 9 +- .../src/ble/napi_bluetooth_gatt_client.cpp | 7 + frameworks/js/napi/src/common/BUILD.gn | 2 + .../js/napi/src/common/napi_async_work.cpp | 24 +++- .../napi/src/common/napi_ha_event_utils.cpp | 133 ++++++++++++++++++ .../connection/napi_bluetooth_connection.cpp | 17 ++- 10 files changed, 268 insertions(+), 15 deletions(-) create mode 100644 frameworks/js/napi/include/napi_ha_event_utils.h create mode 100644 frameworks/js/napi/src/common/napi_ha_event_utils.cpp diff --git a/bundle.json b/bundle.json index b77272fd..f6b8e5b9 100644 --- a/bundle.json +++ b/bundle.json @@ -63,6 +63,7 @@ "hicollie", "hilog", "hisysevent", + "hiappevent", "hitrace", "init", "ipc", diff --git a/frameworks/js/napi/include/napi_async_work.h b/frameworks/js/napi/include/napi_async_work.h index 023d12f7..2084e224 100644 --- a/frameworks/js/napi/include/napi_async_work.h +++ b/frameworks/js/napi/include/napi_async_work.h @@ -19,6 +19,7 @@ #include #include #include "napi_bluetooth_utils.h" +#include "napi_ha_event_utils.h" #include "napi_native_object.h" namespace OHOS { @@ -56,13 +57,15 @@ struct NapiAsyncWorkRet { class NapiAsyncWork : public std::enable_shared_from_this { public: NapiAsyncWork(napi_env env, std::function func, - std::shared_ptr asyncCallback, bool needCallback = false) - : env_(env), func_(func), napiAsyncCallback_(asyncCallback), needCallback_(needCallback) {} + std::shared_ptr asyncCallback, bool needCallback = false, + std::shared_ptr haUtils = nullptr) + : env_(env), func_(func), napiAsyncCallback_(asyncCallback), needCallback_(needCallback), haUtils_(haUtils) {} ~NapiAsyncWork() = default; void Run(void); void CallFunction(int errorCode, std::shared_ptr object); napi_value GetRet(void); + std::shared_ptr GetHaUtilsPtr(void) const; struct Info { void Execute(void); @@ -86,12 +89,14 @@ private: std::shared_ptr napiAsyncCallback_ = nullptr; std::atomic_bool needCallback_ = false; // Indicates whether an asynchronous work needs to wait for callback. std::atomic_bool triggered_ = false; // Indicates whether the asynchronous callback is called. + std::shared_ptr haUtils_; }; class NapiAsyncWorkFactory { public: static std::shared_ptr CreateAsyncWork(napi_env env, napi_callback_info info, - std::function asyncWork, bool needCallback = ASYNC_WORK_NO_NEED_CALLBACK); + std::function asyncWork, bool needCallback = ASYNC_WORK_NO_NEED_CALLBACK, + std::shared_ptr haUtils = nullptr); }; class NapiAsyncWorkMap { diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h new file mode 100644 index 00000000..47b5dcca --- /dev/null +++ b/frameworks/js/napi/include/napi_ha_event_utils.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) Huawei Technologies Co 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 + * + * 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_HA_EVENT_UTILS_H +#define NAPI_HA_EVENT_UTILS_H + +#include +#include + +namespace OHOS { +namespace Bluetooth { + +class NapiHaEventUtils { +public: + explicit NapiHaEventUtils(const std::string &apiName); + ~NapiHaEventUtils(); + void WriteParam(const int32_t errCode); + +private: + NapiHaEventUtils() = delete; + static void GenerateProcessorId(); + static int64_t AddProcessor(); + int64_t GetNowTimeMs() const; + void WriteEndEvent() const; + +private: + static int64_t processorId_; + static std::mutex processorLock_; + std::mutex errCodeLock_; + std::string apiName_; + int64_t beginTime_; + int32_t errCode_; +}; + +} // namespace Bluetooth +} // namespace OHOS +#endif /* NAPI_HA_EVENT_UTILS_H */ diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 16b32573..9280f40d 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -26,6 +26,7 @@ #include "napi_bluetooth_ble_scanner.h" #include "napi_bluetooth_utils.h" #include "napi_bluetooth_ble_utils.h" +#include "napi_ha_event_utils.h" #include "bluetooth_ble_advertiser.h" #include "bluetooth_ble_central_manager.h" @@ -684,12 +685,14 @@ napi_status CheckBleScanParams(napi_env env, napi_callback_info info, std::vecto napi_value StartBLEScan(napi_env env, napi_callback_info info) { HILOGD("enter"); + NapiHaEventUtils haUtils("StartBLEScan"); std::vector scanfilters; BleScanSettings settings; auto status = CheckBleScanParams(env, info, scanfilters, settings); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = BleCentralManagerGetInstance()->StartScan(settings, scanfilters); + haUtils.WriteParam(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR || ret == BT_ERR_BLE_SCAN_ALREADY_STARTED, ret); return NapiGetUndefinedRet(env); @@ -698,10 +701,12 @@ napi_value StartBLEScan(napi_env env, napi_callback_info info) napi_value StopBLEScan(napi_env env, napi_callback_info info) { HILOGD("enter"); + NapiHaEventUtils haUtils("StopBLEScan"); auto status = CheckEmptyParam(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = BleCentralManagerGetInstance()->StopScan(); + haUtils.WriteParam(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR, ret); return NapiGetUndefinedRet(env); } @@ -885,6 +890,7 @@ napi_status CheckAdvertisingData(napi_env env, napi_callback_info info, BleAdver napi_value StartAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("StartAdvertising"); size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {nullptr}; napi_value thisVar = nullptr; @@ -892,6 +898,7 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRes == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, bleAdvertiser, BT_ERR_INTERNAL_ERROR); BleAdvertiserSettings settings; @@ -900,6 +907,7 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) if (argc != 0 && NapiIsObjectPropertyExist(env, argv[PARAM0], "advertisingSettings")) { uint16_t duration = 0; auto status = CheckAdvertisingDataWithDuration(env, argv[PARAM0], settings, advData, rspData, duration); + haUtils->WriteParam(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); auto callback = std::make_shared(); auto func = [settings, advData, rspData, duration, bleAdvertiser, callback]() { @@ -908,7 +916,8 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = callback->asyncWorkMap_.TryPush( NapiAsyncType::GET_ADVERTISING_HANDLE, asyncWork); @@ -918,9 +927,11 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) return asyncWork->GetRet(); } else { auto status = CheckAdvertisingData(env, info, settings, advData, rspData); + haUtils->WriteParam(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = bleAdvertiser->StartAdvertising( settings, advData, rspData, 0, NapiBluetoothBleAdvertiseCallback::GetInstance()); + haUtils->WriteParam(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); return NapiGetUndefinedRet(env); } @@ -964,12 +975,14 @@ napi_status CheckAdvertisingEnableParams(napi_env env, napi_callback_info info, napi_value EnableAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("EnableAdvertising"); uint32_t advHandle = 0xFF; uint16_t duration = 0; std::shared_ptr baseCallback; auto status = CheckAdvertisingEnableParams(env, info, advHandle, duration, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); std::shared_ptr callback = std::static_pointer_cast(baseCallback); @@ -984,7 +997,7 @@ napi_value EnableAdvertising(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = callback->asyncWorkMap_.TryPush( NapiAsyncType::BLE_ENABLE_ADVERTISING, asyncWork); @@ -1019,11 +1032,13 @@ napi_status CheckAdvertisingDisableParams(napi_env env, napi_callback_info info, napi_value DisableAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("DisableAdvertising"); uint32_t advHandle = 0xFF; std::shared_ptr baseCallback; auto status = CheckAdvertisingDisableParams(env, info, advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); std::shared_ptr callback = std::static_pointer_cast(baseCallback); @@ -1038,7 +1053,7 @@ napi_value DisableAdvertising(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = callback->asyncWorkMap_.TryPush( NapiAsyncType::BLE_DISABLE_ADVERTISING, asyncWork); @@ -1075,6 +1090,7 @@ static napi_status CheckEmptyArgs(napi_env env, napi_callback_info info) napi_value StopAdvertising(napi_env env, napi_callback_info info) { HILOGD("enter"); + std::shared_ptr haUtils = std::make_shared("StopAdvertising"); size_t argc = ARGS_SIZE_TWO; napi_value argv[ARGS_SIZE_TWO] = {nullptr}; napi_value thisVar = nullptr; @@ -1082,6 +1098,7 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRes == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, bleAdvertiser, BT_ERR_INTERNAL_ERROR); if (argc != ARGS_SIZE_ZERO) { @@ -1089,12 +1106,14 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) if (argc != ARGS_SIZE_ONE && argc != ARGS_SIZE_TWO) { status = napi_invalid_arg; } + haUtils->WriteParam(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); uint32_t advHandle = 0xFF; std::shared_ptr baseCallback; status = CheckStopAdvWithAdvId(env, argv[PARAM0], advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); std::shared_ptr callback = std::static_pointer_cast(baseCallback); @@ -1103,7 +1122,7 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = callback->asyncWorkMap_.TryPush( NapiAsyncType::BLE_STOP_ADVERTISING, asyncWork); @@ -1113,15 +1132,18 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) return asyncWork->GetRet(); } else { auto status = CheckEmptyArgs(env, info); + haUtils->WriteParam(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::vector> callbacks = bleAdvertiser->GetAdvObservers(); if (callbacks.empty()) { // compatible with XTS int ret = bleAdvertiser->StopAdvertising(NapiBluetoothBleAdvertiseCallback::GetInstance()); + haUtils->WriteParam(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } else { for (auto &callback : callbacks) { int ret = bleAdvertiser->StopAdvertising(callback); + haUtils->WriteParam(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } } diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp index f5264855..7e9db1bc 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp @@ -21,6 +21,7 @@ #include "bluetooth_errorcode.h" #include "napi_bluetooth_utils.h" #include "napi_bluetooth_error.h" +#include "napi_ha_event_utils.h" namespace OHOS { namespace Bluetooth { @@ -97,6 +98,7 @@ static NapiBleScanner *NapiGetBleScanner(napi_env env, napi_callback_info info) napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("StartScan"); std::vector scanFilters; BleScanSettings settings; auto status = CheckBleScanParams(env, info, scanFilters, settings); @@ -113,7 +115,8 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = napiBleScanner->GetCallback()->asyncWorkMap_.TryPush(NapiAsyncType::BLE_START_SCAN, asyncWork); @@ -126,6 +129,7 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) napi_value NapiBleScanner::StopScan(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("StopScan"); auto status = CheckEmptyParam(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); @@ -139,7 +143,8 @@ napi_value NapiBleScanner::StopScan(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = napiBleScanner->GetCallback()->asyncWorkMap_.TryPush(NapiAsyncType::BLE_STOP_SCAN, asyncWork); diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp index c9c812e9..ff31f8b2 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp @@ -27,6 +27,7 @@ #include "napi_bluetooth_event.h" #include "napi_bluetooth_host.h" #include "napi_bluetooth_utils.h" +#include "napi_ha_event_utils.h" #include "napi_event_subscribe_module.h" #include "../parser/napi_parser_utils.h" @@ -268,9 +269,11 @@ static napi_status CheckGattClientNoArgc(napi_env env, napi_callback_info info, napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) { HILOGI("enter"); + NapiHaEventUtils haUtils("ble.GattClientDevice.Connect"); NapiGattClient *gattClient = nullptr; auto status = CheckGattClientNoArgc(env, info, &gattClient); NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); + haUtils.WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, gattClient->GetCallback() != nullptr, BT_ERR_INTERNAL_ERROR); std::shared_ptr client = gattClient->GetClient(); @@ -278,6 +281,7 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) int ret = client->Connect(gattClient->GetCallback(), false, GATT_TRANSPORT_TYPE_LE); HILOGI("ret: %{public}d", ret); + haUtils->WriteParam(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } @@ -285,15 +289,18 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) napi_value NapiGattClient::Disconnect(napi_env env, napi_callback_info info) { HILOGI("enter"); + NapiHaEventUtils haUtils("ble.GattClientDevice.Disconnect"); NapiGattClient* gattClient = nullptr; auto status = CheckGattClientNoArgc(env, info, &gattClient); NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr client = gattClient->GetClient(); + haUtils.WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); int ret = client->Disconnect(); HILOGI("ret: %{public}d", ret); + haUtils->WriteParam(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } diff --git a/frameworks/js/napi/src/common/BUILD.gn b/frameworks/js/napi/src/common/BUILD.gn index bd65c61e..39a42ab1 100644 --- a/frameworks/js/napi/src/common/BUILD.gn +++ b/frameworks/js/napi/src/common/BUILD.gn @@ -49,6 +49,7 @@ ohos_shared_library("bt_napi_common") { "$BT_NAPI_DIR/src/common/napi_bluetooth_error.cpp", "$BT_NAPI_DIR/src/common/napi_bluetooth_event.cpp", "$BT_NAPI_DIR/src/common/napi_bluetooth_utils.cpp", + "$BT_NAPI_DIR/src/common/napi_ha_event_utils.cpp", "$BT_NAPI_DIR/src/common/napi_event_subscribe_module.cpp", "$BT_NAPI_DIR/src/common/napi_native_object.cpp", "$BT_NAPI_DIR/src/common/napi_timer.cpp", @@ -65,6 +66,7 @@ ohos_shared_library("bt_napi_common") { "hitrace:hitrace_meter", "ipc:ipc_single", "libuv:uv", + "hiappevent:hiappevent_innerapi", "napi:ace_napi", ] diff --git a/frameworks/js/napi/src/common/napi_async_work.cpp b/frameworks/js/napi/src/common/napi_async_work.cpp index 74a21c5d..a53b05ec 100644 --- a/frameworks/js/napi/src/common/napi_async_work.cpp +++ b/frameworks/js/napi/src/common/napi_async_work.cpp @@ -27,14 +27,14 @@ namespace OHOS { namespace Bluetooth { std::shared_ptr NapiAsyncWorkFactory::CreateAsyncWork(napi_env env, napi_callback_info info, - std::function asyncWork, bool needCallback) + std::function asyncWork, bool needCallback, std::shared_ptr haUtils) { auto asyncCallback = NapiParseAsyncCallback(env, info); if (!asyncCallback) { HILOGE("asyncCallback is nullptr!"); return nullptr; } - auto napiAsyncWork = std::make_shared(env, asyncWork, asyncCallback, needCallback); + auto napiAsyncWork = std::make_shared(env, asyncWork, asyncCallback, needCallback, haUtils); return napiAsyncWork; } @@ -73,6 +73,10 @@ void NapiAsyncWork::Info::Complete(void) HILOGE("asyncWorkSptr is nullptr"); return; } + auto haUtils = asyncWorkSptr->GetHaUtilsPtr(); + if (haUtils) { + haUtils->WriteParam(BT_ERR_TIMEOUT); + } asyncWorkSptr->TimeoutCallback(); }; NapiTimer::GetInstance()->Register(func, napiAsyncWork->timerId_); @@ -86,6 +90,10 @@ void NapiAsyncWork::Info::Complete(void) if (napiAsyncWork->napiAsyncCallback_) { napiAsyncWork->triggered_ = true; + auto haUtils = napiAsyncWork->GetHaUtilsPtr(); + if (haUtils) { + haUtils->WriteParam(errCode); + } napiAsyncWork->napiAsyncCallback_->CallFunction(errCode, object); } } @@ -134,6 +142,11 @@ void NapiAsyncWork::Run(void) } } +std::shared_ptr NapiAsyncWork::GetHaUtilsPtr(void) const +{ + return haUtils; +} + void NapiAsyncWork::TimeoutCallback(void) { HILOGI("enter"); @@ -144,6 +157,9 @@ void NapiAsyncWork::CallFunction(int errCode, std::shared_ptr { if (!needCallback_.load()) { HILOGE("Unsupported in no needCallback mode"); + if (haUtils_) { + haUtils_->WriteParam(BT_ERR_INTERNAL_ERROR); + } return; } @@ -159,6 +175,10 @@ void NapiAsyncWork::CallFunction(int errCode, std::shared_ptr triggered_ = true; auto func = [errCode, nativeObj, asyncWorkPtr = shared_from_this()]() { if (asyncWorkPtr && asyncWorkPtr->napiAsyncCallback_) { + auto haUtils = asyncWorkPtr->GetHaUtilsPtr(); + if (haUtils) { + haUtils->WriteParam(errCode); + } asyncWorkPtr->napiAsyncCallback_->CallFunction(errCode, nativeObj); } }; diff --git a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp new file mode 100644 index 00000000..9911d7c3 --- /dev/null +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -0,0 +1,133 @@ +/* + * Copyright (C) Huawei Technologies Co 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 + * + * 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 LOG_TAG +#define LOG_TAG "bt_ha_event_utils" +#endif + +#include "napi_ha_event_utils.h" +#include "bluetooth_log.h" +#include "bluetooth_errorcode.h" +#include "app_event.h" +#include "app_event_processor_mgr.h" + +namespace OHOS { +namespace Bluetooth { + +constexpr int64_t INVALID_PROCESSOR_ID = -200; +const std::string SDK_NAME = "ConnectivityKit"; +constexpr int32_t TIMEOUT = 90; // 每90s触发上报一次 +constexpr int32_t ROW = 30; // 或30条数据触发一次上报 +constexpr int32_t TIME_MS_PER_SECOND = 1000; +constexpr int32_t TIME_NS_PER_MS = 1000000; + +int64_t ApiEventUtil::processorId_ = -1; +std::mutex ApiEventUtil::processorLock_; + +ApiEventUtil::ApiEventUtil(const std::string &apiName): apiName_(apiName) +{ + beginTime_ = GetNowTimeMs(); + errCode_ = BT_ERR_INVALID_PARAM; + GenerateProcessorId(); +} + +ApiEventUtil::~ApiEventUtil() +{ + WriteEndEvent(); +} + +void ApiEventUtil::WriteEndEvent(const int32_t result, const int32_t errCode) +{ + std::lock_guard lock(errCodeLock_); + errCode_ = errCode; +} + +void ApiEventUtil::GenerateProcessorId() +{ + std::lock_guard lock(processorLock_); + if (processorId_ == -1) { + processorId_ = AddProcessor(); + HILOGW("add processorId:%{public}lld", processorId_); + } + + if (processorId_ == INVALID_PROCESSOR_ID) { + HILOGE("invaild processorId !!!"); + return; + } +} + +int64_t ApiEventUtil::GetNowTimeMs() const +{ + struct timespec ts = {}; + clock_gettime(CLOCK_BOOTTIME, &ts); + return (int64_t)ts.tv_sec * TIME_MS_PER_SECOND + (int64_t)ts.tv_nsec / TIME_NS_PER_MS; +} + +int64_t ApiEventUtil::AddProcessor() +{ + HiviewDFX::HiAppEvent::ReportConfig config; + config.name = "ha_app_event"; // 系统预制so,实现上报功能,由HA提供 + config.appId = "com_huawei_hmos_sdk_ocg"; + config.routeInfo = "AUTO"; + config.triggerCond.timeout = TIMEOUT; + config.triggerCond.row = ROW; + config.eventConfigs.clear(); + { // 固定内容,所有Kit全量完整复制,不允许修改 + OHOS::HiviewDFX::HiAppEvent::EventConfig event1; + event1.domain = "api_diagnostic"; + event1.name = "api_exec_end"; + event1.isRealTime = false; + config.eventConfigs.push_back(event1); + } + { // 固定内容,所有Kit全量完整复制,不允许修改 + OHOS::HiviewDFX::HiAppEvent::EventConfig event2; + event2.domain = "api_diagnostic"; + event2.name = "api_called_stat"; + event2.isRealTime = true; + config.eventConfigs.push_back(event2); + } + { // 固定内容,所有Kit全量完整复制,不允许修改 + OHOS::HiviewDFX::HiAppEvent::EventConfig event3; + event3.domain = "api_diagnostic"; + event3.name = "api_called_stat_cnt"; + event3.isRealTime = true; + config.eventConfigs.push_back(event3); + } + return HiviewDFX::HiAppEvent::AppEventProcessorMgr::AddProcessor(config); +} + +std::string ApiEventUtil::RandomTransId() const +{ + return std::string("transId_") + std::to_string(std::rand()); +} + +void ApiEventUtil::WriteEndEvent() const +{ + HiviewDFX::HiAppEvent::Event event("api_diagnostic", "api_exec_end", HiviewDFX::HiAppEvent::BEHAVIOR); + std::string transId = RandomTransId(); + event.AddParam("trans_id", transId); + event.AddParam("api_name", apiName_); + event.AddParam("sdk_name", SDK_NAME); + event.AddParam("begin_time", beginTime_); + event.AddParam("end_time", GetNowTimeMs()); + event.AddParam("result", (errCode_ == BT_NO_ERROR ? 0 : 1)); + event.AddParam("error_code", errCode_); + int ret = Write(event); + HILOGD("WriteEndEvent transId:%{public}s, apiName:%{public}s, sdkName:%{public}s, errCode:%{public}d," + "ret:%{public}d", transId.c_str(), apiName_.c_str(), SDK_NAME.c_str(), errCode_, ret); +} + +} // namespace Bluetooth +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp index d15065f9..40a4dd17 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp @@ -27,6 +27,7 @@ #include "napi_bluetooth_error.h" #include "napi_async_work.h" #include "napi_bluetooth_utils.h" +#include "napi_ha_event_utils.h" #include "parser/napi_parser_utils.h" #include "hitrace_meter.h" #include "bluetooth_utils.h" @@ -502,6 +503,7 @@ napi_status CheckDeviceAsyncParam(napi_env env, napi_callback_info info, std::st napi_value PairDeviceAsync(napi_env env, napi_callback_info info) { HILOGD("enter"); + std::shared_ptr haUtils = std::make_shared("PairDeviceAsync"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -512,7 +514,8 @@ napi_value PairDeviceAsync(napi_env env, napi_callback_info info) HILOGI("err: %{public}d", err); return NapiAsyncWorkRet(err); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -572,6 +575,7 @@ napi_status CheckPairCredibleDeviceParam(napi_env env, napi_callback_info info, napi_value PairCredibleDevice(napi_env env, napi_callback_info info) { HILOGD("enter"); + std::shared_ptr haUtils = std::make_shared("PairCredibleDevice"); std::string remoteAddr = INVALID_MAC_ADDRESS; int transport = BT_TRANSPORT_NONE; auto status = CheckPairCredibleDeviceParam(env, info, remoteAddr, transport); @@ -583,7 +587,8 @@ napi_value PairCredibleDevice(napi_env env, napi_callback_info info) HILOGI("err: %{public}d", err); return NapiAsyncWorkRet(err); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -667,6 +672,7 @@ napi_value GetPairState(napi_env env, napi_callback_info info) napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("ConnectAllowedProfiles"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -677,7 +683,8 @@ napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) HILOGI("ret: %{public}d", ret); return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -686,6 +693,7 @@ napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) napi_value DisconnectAllowedProfiles(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::shared_ptr haUtils = std::make_shared("DisconnectAllowedProfiles"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -696,7 +704,8 @@ napi_value DisconnectAllowedProfiles(napi_env env, napi_callback_info info) HILOGI("ret: %{public}d", ret); return NapiAsyncWorkRet(ret); }; - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK); + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); + haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); -- Gitee From 3c63f250465b99ef2c19a26965e480bde9212015 Mon Sep 17 00:00:00 2001 From: shinezxy Date: Thu, 15 May 2025 21:07:18 +0800 Subject: [PATCH 27/45] add car key dfx interface Signed-off-by: shinezxy --- .../inner/ipc/include/bluetooth_host_proxy.h | 2 + .../bluetooth_service_ipc_interface_code.h | 2 + .../inner/ipc/interface/i_bluetooth_host.h | 2 + .../inner/ipc/src/bluetooth_host_proxy.cpp | 42 +++++++++++++++++++ frameworks/inner/src/bluetooth_host.cpp | 16 +++++++ .../connection/napi_bluetooth_connection.cpp | 42 +++++++++++++++++++ .../connection/napi_bluetooth_connection.h | 2 + interfaces/inner_api/include/bluetooth_host.h | 4 ++ 8 files changed, 112 insertions(+) diff --git a/frameworks/inner/ipc/include/bluetooth_host_proxy.h b/frameworks/inner/ipc/include/bluetooth_host_proxy.h index 39727f8b..162c23b8 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_host_proxy.h @@ -118,6 +118,8 @@ public: int32_t UpdateRefusePolicy(const int32_t pid, const int64_t prohibitedSecondsTime) override; int32_t ProcessRandomDeviceIdCommand( int32_t command, std::vector &deviceIdVec, bool &isValid) override; + int32_t GetCarKeyDfxData(std::string &dfxData) override; + int32_t SetCarKeyCardData(const std::string &address, int32_t action) 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 0798f7b9..f3bd374d 100644 --- a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h +++ b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h @@ -288,6 +288,8 @@ enum BluetoothHostInterfaceCode { GET_CLOUD_BOND_STATE, BT_UPDATE_REFUSE_POLICY, PROCESS_RANDOM_DEVICE_ID_COMMAND, + BT_GET_CAR_KEY_DFX_DATA, + BT_SET_CAR_KEY_CARD_DATA, // 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 f455d567..07ed8119 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host.h @@ -145,6 +145,8 @@ public: virtual int32_t UpdateRefusePolicy(const int32_t pid, const int64_t prohibitedSecondsTime) = 0; virtual int32_t ProcessRandomDeviceIdCommand( int32_t command, std::vector &deviceIdVec, bool &isValid) = 0; + virtual int32_t GetCarKeyDfxData(std::string &dfxData) = 0; + virtual int32_t SetCarKeyCardData(const std::string &address, int32_t action) = 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 c7fee8a7..1d2a5925 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -1926,5 +1926,47 @@ int32_t BluetoothHostProxy::ProcessRandomDeviceIdCommand( isValid = reply.ReadBool(); return BT_NO_ERROR; } + +int32_t BluetoothHostProxy::GetCarKeyDfxData(std::string &dfxData) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { + HILOGE("BluetoothHostProxy::GetCarKeyDfxData WriteInterfaceToken error"); + return BT_ERR_IPC_TRANS_FAILED; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + int32_t error = InnerTransact( + BluetoothHostInterfaceCode::BT_GET_CAR_KEY_DFX_DATA, option, data, reply); + if (error != BT_NO_ERROR) { + HILOGE("BluetoothHostProxy::GetCarKeyDfxData done fail error: %{public}d", error); + return BT_ERR_IPC_TRANS_FAILED; + } + int32_t exception = reply.ReadInt32(); + if (exception == BT_NO_ERROR) { + dfxData = reply.ReadString(); + } + return dfxData; +} + +int32_t BluetoothHostProxy::SetCarKeyCardData(const std::string &address, int32_t action) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { + HILOGE("BluetoothHostProxy::SetCarKeyCardData WriteInterfaceToken error"); + return BT_ERR_IPC_TRANS_FAILED; + } + CHECK_AND_RETURN_LOG_RET(data.WriteString(address), BT_ERR_IPC_TRANS_FAILED, "write address error"); + CHECK_AND_RETURN_LOG_RET(data.WriteUint32(action), BT_ERR_IPC_TRANS_FAILED, "write action error"); + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + int32_t error = InnerTransact( + BluetoothHostInterfaceCode::BT_SET_CAR_KEY_CARD_DATA, option, data, reply); + if (error != BT_NO_ERROR) { + HILOGE("BluetoothHostProxy::SetCarKeyCardData done fail error: %{public}d", error); + return BT_ERR_IPC_TRANS_FAILED; + } + return reply.ReadInt32(); +} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index efacb698..c86a6b67 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -1314,5 +1314,21 @@ int32_t BluetoothHost::ProcessRandomDeviceIdCommand( CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); return proxy->ProcessRandomDeviceIdCommand(command, deviceIdVec, isValid); } + +int BluetoothHost::GetCarKeyDfxData(std::string &dfxData) const +{ + HILOGI("enter"); + sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); + CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr"); + return proxy->GetCarKeyDfxData(dfxData); +} + +int BluetoothHost::SetCarKeyCardData(const std::string &address, int32_t action) +{ + HILOGI("enter"); + sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); + CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr"); + return proxy->SetCarKeyCardData(address, action); +} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp index d15065f9..5f65c695 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp @@ -112,6 +112,8 @@ napi_value DefineConnectionFunctions(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("controlDeviceAction", ControlDeviceAction), DECLARE_NAPI_FUNCTION("getLastConnectionTime", GetRemoteDeviceConnectionTime), DECLARE_NAPI_FUNCTION("updateCloudBluetoothDevice", UpdateCloudBluetoothDevice), + DECLARE_NAPI_FUNCTION("getCarKeyDfxData", GetCarKeyDfxData), + DECLARE_NAPI_FUNCTION("setCarKeyDfxData", SetCarKeyCardData), }; HITRACE_METER_NAME(HITRACE_TAG_OHOS, "connection:napi_define_properties"); @@ -275,6 +277,46 @@ napi_value GetRemoteDeviceName(napi_env env, napi_callback_info info) return result; } +napi_value GetCarKeyDfxData(napi_env env, napi_callback_info info) +{ + HILOGD("enter"); + napi_value result = nullptr; + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + std::string dfxData; + int32_t err = host->GetCarKeyDfxData(dfxData); + napi_create_string_utf8(env, dfxData.c_str(), dfxData.size(), &result); + NAPI_BT_ASSERT_RETURN(env, err == BT_NO_ERROR, err, result); + return result; +} + +napi_status ParseSetCarKeyCardDataParameters(napi_env env, napi_callback_info info, + std::string &outRemoteAddr, int32_t &outAction) +{ + HILOGD("enter"); + std::string remoteAddr{}; + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); + NAPI_BT_CALL_RETURN(NapiParseBdAddr(env, argv[PARAM0], remoteAddr)); + outRemoteAddr = remoteAddr; + NAPI_BT_RETURN_IF(!ParseInt32(env, outAction, argv[PARAM1]), "action ParseInt32 failed", napi_invalid_arg); + return napi_ok; +} + +napi_value SetCarKeyCardData(napi_env env, napi_callback_info info) +{ + HILOGD("enter"); + std::string remoteAddr; + int32_t action = 0; + auto status = ParseSetCarKeyCardDataParameters(env, info, remoteAddr, action); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + int ret = host->SetCarKeyCardData(remoteAddr, action); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); + return NapiGetBooleanTrue(env); +} + napi_value GetRemoteDeviceClass(napi_env env, napi_callback_info info) { HILOGD("start"); diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.h b/frameworks/js/napi/src/connection/napi_bluetooth_connection.h index 6fd98811..a13b674c 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.h +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.h @@ -100,6 +100,8 @@ napi_value UpdateCloudBluetoothDevice(napi_env env, napi_callback_info info); void RegisterObserverToHost(); void DealPairStatus(const int &status, int &bondStatus); +napi_value GetCarKeyDfxData(napi_env env, napi_callback_info info); +napi_value SetCarKeyCardData(napi_env env, napi_callback_info info); } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 04feabfe..886da083 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -855,6 +855,10 @@ public: int64_t GetRefusePolicyProhibitedTime(); int32_t ProcessRandomDeviceIdCommand(int32_t command, std::vector &deviceIdVec, bool &isValid); + + int GetCarKeyDfxData(std::string &dfxData) const; + + int SetCarKeyCardData(const std::string &address, int32_t action); private: /** * @brief A constructor used to create a BluetoothHost instance. -- Gitee From a8315b16ea08a58fb058f2a6a954c2a8005ea3f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Thu, 15 May 2025 13:38:45 +0000 Subject: [PATCH 28/45] bug fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- .../js/napi/include/napi_ha_event_utils.h | 1 + .../src/ble/napi_bluetooth_gatt_client.cpp | 4 ++-- .../js/napi/src/common/napi_async_work.cpp | 2 +- .../napi/src/common/napi_ha_event_utils.cpp | 20 +++++++++---------- 4 files changed, 14 insertions(+), 13 deletions(-) diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h index 47b5dcca..43f5d701 100644 --- a/frameworks/js/napi/include/napi_ha_event_utils.h +++ b/frameworks/js/napi/include/napi_ha_event_utils.h @@ -32,6 +32,7 @@ private: NapiHaEventUtils() = delete; static void GenerateProcessorId(); static int64_t AddProcessor(); + std::string RandomTransId() const; int64_t GetNowTimeMs() const; void WriteEndEvent() const; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp index ff31f8b2..7c3cac31 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp @@ -281,7 +281,7 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) int ret = client->Connect(gattClient->GetCallback(), false, GATT_TRANSPORT_TYPE_LE); HILOGI("ret: %{public}d", ret); - haUtils->WriteParam(ret); + haUtils.WriteParam(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } @@ -300,7 +300,7 @@ napi_value NapiGattClient::Disconnect(napi_env env, napi_callback_info info) int ret = client->Disconnect(); HILOGI("ret: %{public}d", ret); - haUtils->WriteParam(ret); + haUtils.WriteParam(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } diff --git a/frameworks/js/napi/src/common/napi_async_work.cpp b/frameworks/js/napi/src/common/napi_async_work.cpp index a53b05ec..0837fded 100644 --- a/frameworks/js/napi/src/common/napi_async_work.cpp +++ b/frameworks/js/napi/src/common/napi_async_work.cpp @@ -144,7 +144,7 @@ void NapiAsyncWork::Run(void) std::shared_ptr NapiAsyncWork::GetHaUtilsPtr(void) const { - return haUtils; + return haUtils_; } void NapiAsyncWork::TimeoutCallback(void) 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 9911d7c3..7f409d6f 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -33,28 +33,28 @@ constexpr int32_t ROW = 30; // 或30条数据触发一次上报 constexpr int32_t TIME_MS_PER_SECOND = 1000; constexpr int32_t TIME_NS_PER_MS = 1000000; -int64_t ApiEventUtil::processorId_ = -1; -std::mutex ApiEventUtil::processorLock_; +int64_t NapiHaEventUtils::processorId_ = -1; +std::mutex NapiHaEventUtils::processorLock_; -ApiEventUtil::ApiEventUtil(const std::string &apiName): apiName_(apiName) +NapiHaEventUtils::NapiHaEventUtils(const std::string &apiName): apiName_(apiName) { beginTime_ = GetNowTimeMs(); errCode_ = BT_ERR_INVALID_PARAM; GenerateProcessorId(); } -ApiEventUtil::~ApiEventUtil() +NapiHaEventUtils::~NapiHaEventUtils() { WriteEndEvent(); } -void ApiEventUtil::WriteEndEvent(const int32_t result, const int32_t errCode) +void NapiHaEventUtils::WriteParam(const int32_t errCode) { std::lock_guard lock(errCodeLock_); errCode_ = errCode; } -void ApiEventUtil::GenerateProcessorId() +void NapiHaEventUtils::GenerateProcessorId() { std::lock_guard lock(processorLock_); if (processorId_ == -1) { @@ -68,14 +68,14 @@ void ApiEventUtil::GenerateProcessorId() } } -int64_t ApiEventUtil::GetNowTimeMs() const +int64_t NapiHaEventUtils::GetNowTimeMs() const { struct timespec ts = {}; clock_gettime(CLOCK_BOOTTIME, &ts); return (int64_t)ts.tv_sec * TIME_MS_PER_SECOND + (int64_t)ts.tv_nsec / TIME_NS_PER_MS; } -int64_t ApiEventUtil::AddProcessor() +int64_t NapiHaEventUtils::AddProcessor() { HiviewDFX::HiAppEvent::ReportConfig config; config.name = "ha_app_event"; // 系统预制so,实现上报功能,由HA提供 @@ -108,12 +108,12 @@ int64_t ApiEventUtil::AddProcessor() return HiviewDFX::HiAppEvent::AppEventProcessorMgr::AddProcessor(config); } -std::string ApiEventUtil::RandomTransId() const +std::string NapiHaEventUtils::RandomTransId() const { return std::string("transId_") + std::to_string(std::rand()); } -void ApiEventUtil::WriteEndEvent() const +void NapiHaEventUtils::WriteEndEvent() const { HiviewDFX::HiAppEvent::Event event("api_diagnostic", "api_exec_end", HiviewDFX::HiAppEvent::BEHAVIOR); std::string transId = RandomTransId(); -- Gitee From 61e7a52348cbeea5521e590e4fa075f35d5a1319 Mon Sep 17 00:00:00 2001 From: shinezxy Date: Thu, 15 May 2025 22:04:13 +0800 Subject: [PATCH 29/45] add car key dfx data Signed-off-by: shinezxy --- frameworks/inner/ipc/src/bluetooth_host_proxy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp index 1d2a5925..744da120 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -1946,7 +1946,7 @@ int32_t BluetoothHostProxy::GetCarKeyDfxData(std::string &dfxData) if (exception == BT_NO_ERROR) { dfxData = reply.ReadString(); } - return dfxData; + return exception; } int32_t BluetoothHostProxy::SetCarKeyCardData(const std::string &address, int32_t action) -- Gitee From 4c0ca58c8a7d203f48c61fab0811206a0cc868b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Fri, 16 May 2025 02:45:11 +0000 Subject: [PATCH 30/45] review fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/js/napi/include/napi_async_work.h | 2 +- .../js/napi/include/napi_ha_event_utils.h | 2 +- .../js/napi/src/ble/napi_bluetooth_ble.cpp | 30 +++++++++---------- .../src/ble/napi_bluetooth_ble_scanner.cpp | 4 +-- .../src/ble/napi_bluetooth_gatt_client.cpp | 8 ++--- .../js/napi/src/common/napi_async_work.cpp | 10 ++----- .../napi/src/common/napi_ha_event_utils.cpp | 4 +-- .../connection/napi_bluetooth_connection.cpp | 8 ++--- 8 files changed, 32 insertions(+), 36 deletions(-) diff --git a/frameworks/js/napi/include/napi_async_work.h b/frameworks/js/napi/include/napi_async_work.h index 2084e224..151d7c9d 100644 --- a/frameworks/js/napi/include/napi_async_work.h +++ b/frameworks/js/napi/include/napi_async_work.h @@ -89,7 +89,7 @@ private: std::shared_ptr napiAsyncCallback_ = nullptr; std::atomic_bool needCallback_ = false; // Indicates whether an asynchronous work needs to wait for callback. std::atomic_bool triggered_ = false; // Indicates whether the asynchronous callback is called. - std::shared_ptr haUtils_; + std::shared_ptr haUtils_; // HA report tool, which is transferred fron the original API interface }; class NapiAsyncWorkFactory { diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h index 43f5d701..f6bd97ab 100644 --- a/frameworks/js/napi/include/napi_ha_event_utils.h +++ b/frameworks/js/napi/include/napi_ha_event_utils.h @@ -26,7 +26,7 @@ class NapiHaEventUtils { public: explicit NapiHaEventUtils(const std::string &apiName); ~NapiHaEventUtils(); - void WriteParam(const int32_t errCode); + void WriteErrCode(const int32_t errCode); private: NapiHaEventUtils() = delete; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 9280f40d..28d57b57 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -692,7 +692,7 @@ napi_value StartBLEScan(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = BleCentralManagerGetInstance()->StartScan(settings, scanfilters); - haUtils.WriteParam(ret); + haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR || ret == BT_ERR_BLE_SCAN_ALREADY_STARTED, ret); return NapiGetUndefinedRet(env); @@ -706,7 +706,7 @@ napi_value StopBLEScan(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = BleCentralManagerGetInstance()->StopScan(); - haUtils.WriteParam(ret); + haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR, ret); return NapiGetUndefinedRet(env); } @@ -898,7 +898,7 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRes == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, bleAdvertiser, BT_ERR_INTERNAL_ERROR); BleAdvertiserSettings settings; @@ -907,7 +907,7 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) if (argc != 0 && NapiIsObjectPropertyExist(env, argv[PARAM0], "advertisingSettings")) { uint16_t duration = 0; auto status = CheckAdvertisingDataWithDuration(env, argv[PARAM0], settings, advData, rspData, duration); - haUtils->WriteParam(BT_ERR_INVALID_PARAM); + haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); auto callback = std::make_shared(); auto func = [settings, advData, rspData, duration, bleAdvertiser, callback]() { @@ -917,7 +917,7 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = callback->asyncWorkMap_.TryPush( NapiAsyncType::GET_ADVERTISING_HANDLE, asyncWork); @@ -927,11 +927,11 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) return asyncWork->GetRet(); } else { auto status = CheckAdvertisingData(env, info, settings, advData, rspData); - haUtils->WriteParam(BT_ERR_INVALID_PARAM); + haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = bleAdvertiser->StartAdvertising( settings, advData, rspData, 0, NapiBluetoothBleAdvertiseCallback::GetInstance()); - haUtils->WriteParam(ret); + haUtils->WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); return NapiGetUndefinedRet(env); } @@ -982,7 +982,7 @@ napi_value EnableAdvertising(napi_env env, napi_callback_info info) auto status = CheckAdvertisingEnableParams(env, info, advHandle, duration, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); std::shared_ptr callback = std::static_pointer_cast(baseCallback); @@ -1038,7 +1038,7 @@ napi_value DisableAdvertising(napi_env env, napi_callback_info info) auto status = CheckAdvertisingDisableParams(env, info, advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); std::shared_ptr callback = std::static_pointer_cast(baseCallback); @@ -1098,7 +1098,7 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRes == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, bleAdvertiser, BT_ERR_INTERNAL_ERROR); if (argc != ARGS_SIZE_ZERO) { @@ -1106,14 +1106,14 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) if (argc != ARGS_SIZE_ONE && argc != ARGS_SIZE_TWO) { status = napi_invalid_arg; } - haUtils->WriteParam(BT_ERR_INVALID_PARAM); + haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); uint32_t advHandle = 0xFF; std::shared_ptr baseCallback; status = CheckStopAdvWithAdvId(env, argv[PARAM0], advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); std::shared_ptr callback = std::static_pointer_cast(baseCallback); @@ -1132,18 +1132,18 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) return asyncWork->GetRet(); } else { auto status = CheckEmptyArgs(env, info); - haUtils->WriteParam(BT_ERR_INVALID_PARAM); + haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::vector> callbacks = bleAdvertiser->GetAdvObservers(); if (callbacks.empty()) { // compatible with XTS int ret = bleAdvertiser->StopAdvertising(NapiBluetoothBleAdvertiseCallback::GetInstance()); - haUtils->WriteParam(ret); + haUtils->WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } else { for (auto &callback : callbacks) { int ret = bleAdvertiser->StopAdvertising(callback); - haUtils->WriteParam(ret); + haUtils->WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } } diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp index 7e9db1bc..104877a5 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp @@ -116,7 +116,7 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = napiBleScanner->GetCallback()->asyncWorkMap_.TryPush(NapiAsyncType::BLE_START_SCAN, asyncWork); @@ -144,7 +144,7 @@ napi_value NapiBleScanner::StopScan(napi_env env, napi_callback_info info) }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = napiBleScanner->GetCallback()->asyncWorkMap_.TryPush(NapiAsyncType::BLE_STOP_SCAN, asyncWork); diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp index 7c3cac31..bdfa74a2 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp @@ -273,7 +273,7 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) NapiGattClient *gattClient = nullptr; auto status = CheckGattClientNoArgc(env, info, &gattClient); NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); - haUtils.WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils.WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, gattClient->GetCallback() != nullptr, BT_ERR_INTERNAL_ERROR); std::shared_ptr client = gattClient->GetClient(); @@ -281,7 +281,7 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) int ret = client->Connect(gattClient->GetCallback(), false, GATT_TRANSPORT_TYPE_LE); HILOGI("ret: %{public}d", ret); - haUtils.WriteParam(ret); + haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } @@ -295,12 +295,12 @@ napi_value NapiGattClient::Disconnect(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr client = gattClient->GetClient(); - haUtils.WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils.WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); int ret = client->Disconnect(); HILOGI("ret: %{public}d", ret); - haUtils.WriteParam(ret); + haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } diff --git a/frameworks/js/napi/src/common/napi_async_work.cpp b/frameworks/js/napi/src/common/napi_async_work.cpp index 0837fded..881266fe 100644 --- a/frameworks/js/napi/src/common/napi_async_work.cpp +++ b/frameworks/js/napi/src/common/napi_async_work.cpp @@ -73,10 +73,6 @@ void NapiAsyncWork::Info::Complete(void) HILOGE("asyncWorkSptr is nullptr"); return; } - auto haUtils = asyncWorkSptr->GetHaUtilsPtr(); - if (haUtils) { - haUtils->WriteParam(BT_ERR_TIMEOUT); - } asyncWorkSptr->TimeoutCallback(); }; NapiTimer::GetInstance()->Register(func, napiAsyncWork->timerId_); @@ -92,7 +88,7 @@ void NapiAsyncWork::Info::Complete(void) napiAsyncWork->triggered_ = true; auto haUtils = napiAsyncWork->GetHaUtilsPtr(); if (haUtils) { - haUtils->WriteParam(errCode); + haUtils->WriteErrCode(errCode); } napiAsyncWork->napiAsyncCallback_->CallFunction(errCode, object); } @@ -158,7 +154,7 @@ void NapiAsyncWork::CallFunction(int errCode, std::shared_ptr if (!needCallback_.load()) { HILOGE("Unsupported in no needCallback mode"); if (haUtils_) { - haUtils_->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils_->WriteErrCode(BT_ERR_INTERNAL_ERROR); } return; } @@ -177,7 +173,7 @@ void NapiAsyncWork::CallFunction(int errCode, std::shared_ptr if (asyncWorkPtr && asyncWorkPtr->napiAsyncCallback_) { auto haUtils = asyncWorkPtr->GetHaUtilsPtr(); if (haUtils) { - haUtils->WriteParam(errCode); + haUtils->WriteErrCode(errCode); } asyncWorkPtr->napiAsyncCallback_->CallFunction(errCode, nativeObj); } 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 7f409d6f..9f813706 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -39,7 +39,7 @@ std::mutex NapiHaEventUtils::processorLock_; NapiHaEventUtils::NapiHaEventUtils(const std::string &apiName): apiName_(apiName) { beginTime_ = GetNowTimeMs(); - errCode_ = BT_ERR_INVALID_PARAM; + errCode_ = BT_ERR_INVALID_PARAM; // 考虑到NAPI接口会优先校验入参,这里直接默认初始化为401错误码 GenerateProcessorId(); } @@ -48,7 +48,7 @@ NapiHaEventUtils::~NapiHaEventUtils() WriteEndEvent(); } -void NapiHaEventUtils::WriteParam(const int32_t errCode) +void NapiHaEventUtils::WriteErrCode(const int32_t errCode) { std::lock_guard lock(errCodeLock_); errCode_ = errCode; diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp index 40a4dd17..d9ffffe4 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp @@ -515,7 +515,7 @@ napi_value PairDeviceAsync(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(err); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -588,7 +588,7 @@ napi_value PairCredibleDevice(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(err); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -684,7 +684,7 @@ napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -705,7 +705,7 @@ napi_value DisconnectAllowedProfiles(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteParam(BT_ERR_INTERNAL_ERROR); + haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); -- Gitee From 421cc0e486198fc7efb502856b70b42bdfba940c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Fri, 16 May 2025 03:34:20 +0000 Subject: [PATCH 31/45] codecheck fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- .../js/napi/include/napi_ha_event_utils.h | 2 +- .../js/napi/src/ble/napi_bluetooth_ble.cpp | 36 +++++++++++-------- .../napi/src/common/napi_ha_event_utils.cpp | 2 +- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h index f6bd97ab..7ce373d1 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 Co., Ltd. 2025-2025. All rights reserved. + * Copyright (C) Huawei Technologies 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/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 28d57b57..71e1cb74 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -1087,6 +1087,26 @@ static napi_status CheckEmptyArgs(napi_env env, napi_callback_info info) return napi_ok; } +napi_value ProcessStopAdvertisingAsyncWork(napi_env env, napi_callback_info info, + std::shared_ptr bleAdvertiser, std::shared_ptr baseCallback, + std::shared_ptr haUtils) +{ + std::shared_ptr callback = + std::static_pointer_cast(baseCallback); + auto func = [bleAdvertiser, callback]() { + int ret = bleAdvertiser->StopAdvertising(callback); + return NapiAsyncWorkRet(ret); + }; + + auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); + NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); + bool success = callback->asyncWorkMap_.TryPush(NapiAsyncType::BLE_STOP_ADVERTISING, asyncWork); + NAPI_BT_ASSERT_RETURN_UNDEF(env, success, BT_ERR_INTERNAL_ERROR); + + asyncWork->Run(); + return asyncWork->GetRet(); +} + napi_value StopAdvertising(napi_env env, napi_callback_info info) { HILOGD("enter"); @@ -1115,21 +1135,7 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) // compatible with XTS haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); - std::shared_ptr callback = - std::static_pointer_cast(baseCallback); - auto func = [bleAdvertiser, callback]() { - int ret = bleAdvertiser->StopAdvertising(callback); - return NapiAsyncWorkRet(ret); - }; - - auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); - bool success = callback->asyncWorkMap_.TryPush( - NapiAsyncType::BLE_STOP_ADVERTISING, asyncWork); - NAPI_BT_ASSERT_RETURN_UNDEF(env, success, BT_ERR_INTERNAL_ERROR); - - asyncWork->Run(); - return asyncWork->GetRet(); + return ProcessStopAdvertisingAsyncWork(env, info, bleAdvertiser, baseCallback, haUtils); } else { auto status = CheckEmptyArgs(env, info); haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); 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 9f813706..062bfd12 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 Co., Ltd. 2025-2025. All rights reserved. + * Copyright (C) Huawei Technologies 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 -- Gitee From 65325f87656b096b73366bd258650809a8313612 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Tue, 6 May 2025 20:16:15 +0800 Subject: [PATCH 32/45] add errorCode for gatt ble Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I136257edc5b9dbc9938abac83c1b0571f6e15b87 add errorCode for adv 0327 Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I6066b9b8d87449d6b9e1b8760b20a94842d6cbf5 --- frameworks/inner/ipc/common/bt_def.h | 2 + .../inner/src/bluetooth_ble_advertiser.cpp | 16 +++-- .../inner/src/bluetooth_gatt_client.cpp | 24 ++++---- .../napi/include/napi_bluetooth_gatt_client.h | 3 + .../js/napi/include/napi_bluetooth_utils.h | 5 ++ .../js/napi/src/ble/napi_bluetooth_ble.cpp | 15 ++++- .../napi_bluetooth_ble_advertise_callback.cpp | 4 ++ .../src/ble/napi_bluetooth_gatt_client.cpp | 39 +++++++++++++ .../napi_bluetooth_gatt_client_callback.cpp | 6 ++ frameworks/js/napi/src/common/BUILD.gn | 1 + .../napi/src/common/napi_bluetooth_utils.cpp | 58 +++++++++++++++++++ interfaces/inner_api/include/bluetooth_def.h | 4 ++ .../inner_api/include/bluetooth_errorcode.h | 8 +++ 13 files changed, 165 insertions(+), 20 deletions(-) diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index 3a4d2e28..cff6c92a 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -342,6 +342,8 @@ enum class GattPermission : uint16_t { enum class GattConnectionPriority : int { BALANCED, HIGH, LOW_POWER }; enum GattStatus { + AUTHENTICATION_FAILED = -33, + GATT_CONGESTION = -32, EMPTY_FILTER = -31, MAX_FILTERS = -30, INVALID_REMOTE_DEVICE = -29, diff --git a/frameworks/inner/src/bluetooth_ble_advertiser.cpp b/frameworks/inner/src/bluetooth_ble_advertiser.cpp index 91805659..1c106984 100644 --- a/frameworks/inner/src/bluetooth_ble_advertiser.cpp +++ b/frameworks/inner/src/bluetooth_ble_advertiser.cpp @@ -316,12 +316,12 @@ int32_t BleAdvertiser::impl::CheckAdvertiserData(const BluetoothBleAdvertiserSet uint32_t size = GetAdvertiserTotalBytes(advData, setting.IsConnectable()); if (size > maxSize) { HILOGE("bleAdvertiserData size = %{public}d, maxSize = %{public}d", size, maxSize); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_BLE_ADV_DATA_EXCEED_LIMIT; } size = GetAdvertiserTotalBytes(scanResponse, false); if (size > maxSize) { HILOGE("bleScanResponse size = %{public}d, maxSize = %{public}d,", size, maxSize); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_BLE_ADV_DATA_EXCEED_LIMIT; } return BT_NO_ERROR; } @@ -366,7 +366,13 @@ int BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const ret = proxy->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, duration, false); } else { ret = proxy->GetAdvertiserHandle(advHandle, pimpl->callbackImp_); + // ret will be BT_ERR_MAX_RESOURCES or BT_ERR_INTERNAL_ERROR. if (ret != BT_NO_ERROR || advHandle == BLE_INVALID_ADVERTISING_HANDLE) { + if (ret == BT_ERR_MAX_RESOURCES) { + HILOGE("The number of adv handle reaches the maximum."); + callback->OnStartResultEvent(BT_ERR_MAX_RESOURCES, static_cast(BLE_INVALID_ADVERTISING_HANDLE)); + return ret; + } HILOGE("Invalid advertising handle"); callback->OnStartResultEvent(BT_ERR_INTERNAL_ERROR, static_cast(BLE_INVALID_ADVERTISING_HANDLE)); return ret; @@ -486,7 +492,7 @@ int BleAdvertiser::EnableAdvertising(uint8_t advHandle, uint16_t duration, uint8_t tmpAdvHandle = pimpl->callbacks_.GetAdvertiserHandle(callback); if (tmpAdvHandle == BLE_INVALID_ADVERTISING_HANDLE) { HILOGE("Invalid advertising callback"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_BLE_INVALID_ADV_ID; } std::shared_ptr observer = pimpl->callbacks_.GetAdvertiserObserver(advHandle); @@ -513,7 +519,7 @@ int BleAdvertiser::DisableAdvertising(uint8_t advHandle, std::shared_ptrcallbacks_.GetAdvertiserHandle(callback); if (tmpAdvHandle == BLE_INVALID_ADVERTISING_HANDLE) { HILOGE("Invalid advertising callback"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_BLE_INVALID_ADV_ID; } std::shared_ptr observer = pimpl->callbacks_.GetAdvertiserObserver(advHandle); @@ -541,7 +547,7 @@ int BleAdvertiser::StopAdvertising(std::shared_ptr callbac uint8_t advHandle = pimpl->callbacks_.GetAdvertiserHandle(callback); if (advHandle == BLE_INVALID_ADVERTISING_HANDLE) { HILOGE("Invalid advertising handle"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_BLE_INVALID_ADV_ID; } int ret = proxy->StopAdvertising(advHandle); diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index e1bcaa52..68a0b957 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -797,12 +797,12 @@ int GattClient::ReadCharacteristic(GattCharacteristic &characteristic) std::lock_guard lock(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED; } std::lock_guard lck(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_OPERATION_BUSY; } int result = GattStatus::GATT_FAILURE; HILOGI("applicationId: %{public}d, handle: 0x%{public}04X", pimpl->applicationId_, characteristic.GetHandle()); @@ -834,12 +834,12 @@ int GattClient::ReadDescriptor(GattDescriptor &descriptor) std::lock_guard lck(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED; } std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_OPERATION_BUSY; } int result = BT_ERR_INTERNAL_ERROR; HILOGI("applicationId: %{public}d, handle: 0x%{public}04X", pimpl->applicationId_, descriptor.GetHandle()); @@ -903,12 +903,12 @@ int GattClient::SetNotifyCharacteristicInner(GattCharacteristic &characteristic, std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED; } std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGI("Remote device busy"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_OPERATION_BUSY; } auto descriptor = characteristic.GetDescriptor(UUID::FromString("00002902-0000-1000-8000-00805F9B34FB")); if (descriptor == nullptr) { @@ -996,7 +996,7 @@ int GattClient::WriteCharacteristic(GattCharacteristic &characteristic, std::vec std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED; } size_t length = value.size(); HILOGD("length:%{public}zu", length); @@ -1007,7 +1007,7 @@ int GattClient::WriteCharacteristic(GattCharacteristic &characteristic, std::vec std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_OPERATION_BUSY; } BluetoothGattCharacteristic character( bluetooth::Characteristic(characteristic.GetHandle(), value.data(), length)); @@ -1050,7 +1050,7 @@ int GattClient::WriteDescriptor(GattDescriptor &descriptor) std::lock_guard lck(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED; } size_t length = 0; auto &characterValue = descriptor.GetValue(&length); @@ -1061,7 +1061,7 @@ int GattClient::WriteDescriptor(GattDescriptor &descriptor) std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_OPERATION_BUSY; } int result = BT_ERR_INTERNAL_ERROR; sptr proxy = GetRemoteProxy(PROFILE_GATT_CLIENT); @@ -1141,12 +1141,12 @@ int GattClient::ReadRemoteRssiValue() std::lock_guard lock(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED; } std::lock_guard lck(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return BT_ERR_INTERNAL_ERROR; + return BT_ERR_OPERATION_BUSY; } int result = GattStatus::GATT_FAILURE; HILOGI("applicationId: %{public}d", pimpl->applicationId_); diff --git a/frameworks/js/napi/include/napi_bluetooth_gatt_client.h b/frameworks/js/napi/include/napi_bluetooth_gatt_client.h index bd6dd933..b652f028 100644 --- a/frameworks/js/napi/include/napi_bluetooth_gatt_client.h +++ b/frameworks/js/napi/include/napi_bluetooth_gatt_client.h @@ -58,6 +58,7 @@ public: static napi_value SetBLEMtuSize(napi_env env, napi_callback_info info); static napi_value GetRssiValue(napi_env env, napi_callback_info info); static napi_value GetDeviceName(napi_env env, napi_callback_info info); + static int GattStatusFromService(int status); std::shared_ptr &GetClient() { @@ -87,6 +88,8 @@ public: static thread_local napi_ref consRef_; + // napi (first) <-> service (second) + static const std::vector> g_gattStatusSrvToNapi; private: std::shared_ptr client_ = nullptr; std::shared_ptr callback_; diff --git a/frameworks/js/napi/include/napi_bluetooth_utils.h b/frameworks/js/napi/include/napi_bluetooth_utils.h index f291f7f7..f8a219ae 100644 --- a/frameworks/js/napi/include/napi_bluetooth_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_utils.h @@ -62,6 +62,8 @@ constexpr int32_t BLE_DEVICE_FIND_TYPE = 5; constexpr uint32_t INVALID_REF_COUNT = 0xFF; +constexpr int SDK_VERSION_20 = 20; + struct ServerResponse { std::string deviceId = ""; int transId = 0; @@ -521,6 +523,9 @@ napi_status CheckDeviceAddressParam(napi_env env, napi_callback_info info, std:: napi_status CheckAccessAuthorizationParam(napi_env env, napi_callback_info info, std::string &addr, int32_t &accessAuthorization); napi_status NapiGetOnOffCallbackName(napi_env env, napi_callback_info info, std::string &name); + +int GetCurrentSdkVersion(void); +int GetSDKAdaptedStatusCode(int status); } // namespace Bluetooth } // namespace OHOS #endif // NAPI_BLUETOOTH_UTILS_H diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 16b32573..cb7e6d59 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -905,6 +905,7 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) auto func = [settings, advData, rspData, duration, bleAdvertiser, callback]() { int ret = bleAdvertiser->StartAdvertising( settings, advData, rspData, duration, callback); + ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk return NapiAsyncWorkRet(ret); }; @@ -970,7 +971,8 @@ napi_value EnableAdvertising(napi_env env, napi_callback_info info) auto status = CheckAdvertisingEnableParams(env, info, advHandle, duration, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); + NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, + GetSDKAdaptedStatusCode(BT_ERR_BLE_INVALID_ADV_ID)); // Adaptation for old sdk std::shared_ptr callback = std::static_pointer_cast(baseCallback); auto func = [advHandle, duration, callback]() { @@ -981,6 +983,7 @@ napi_value EnableAdvertising(napi_env env, napi_callback_info info) } int ret = bleAdvertiser->EnableAdvertising( advHandle, duration, callback); + ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk return NapiAsyncWorkRet(ret); }; @@ -1024,7 +1027,8 @@ napi_value DisableAdvertising(napi_env env, napi_callback_info info) auto status = CheckAdvertisingDisableParams(env, info, advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); + NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, + GetSDKAdaptedStatusCode(BT_ERR_BLE_INVALID_ADV_ID)); // Adaptation for old sdk std::shared_ptr callback = std::static_pointer_cast(baseCallback); auto func = [advHandle, callback]() { @@ -1035,6 +1039,7 @@ napi_value DisableAdvertising(napi_env env, napi_callback_info info) } int ret = bleAdvertiser->DisableAdvertising( advHandle, callback); + ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk return NapiAsyncWorkRet(ret); }; @@ -1095,11 +1100,13 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) status = CheckStopAdvWithAdvId(env, argv[PARAM0], advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, BT_ERR_INTERNAL_ERROR); + NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, + GetSDKAdaptedStatusCode(BT_ERR_BLE_INVALID_ADV_ID)); // Adaptation for old sdk std::shared_ptr callback = std::static_pointer_cast(baseCallback); auto func = [bleAdvertiser, callback]() { int ret = bleAdvertiser->StopAdvertising(callback); + ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk return NapiAsyncWorkRet(ret); }; @@ -1118,10 +1125,12 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) if (callbacks.empty()) { // compatible with XTS int ret = bleAdvertiser->StopAdvertising(NapiBluetoothBleAdvertiseCallback::GetInstance()); + ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } else { for (auto &callback : callbacks) { int ret = bleAdvertiser->StopAdvertising(callback); + ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } } diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_advertise_callback.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_advertise_callback.cpp index bcabdfbf..21dfef1b 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_advertise_callback.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_advertise_callback.cpp @@ -42,6 +42,7 @@ void NapiBluetoothBleAdvertiseCallback::OnStartResultEvent(int result, int advHa HILOGI("enter, result: %{public}d advHandle: %{public}d", result, advHandle); if (advHandle_ == advHandle) { HILOGI("OnStartResultEvent, advHandle is same, advHandle: %{public}d", advHandle_); + result = GetSDKAdaptedStatusCode(result); // Adaptation for old sdk auto napiAdvHandle = std::make_shared(advHandle); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GET_ADVERTISING_HANDLE, napiAdvHandle, result); } @@ -55,6 +56,7 @@ void NapiBluetoothBleAdvertiseCallback::OnEnableResultEvent(int result, int advH HILOGI("enter, result: %{public}d advHandle: %{public}d", result, advHandle); if (advHandle_ == advHandle) { HILOGI("OnEnableResultEvent, advHandle is same, advHandle: %{public}d", advHandle_); + result = GetSDKAdaptedStatusCode(result); // Adaptation for old sdk auto napiAdvResult = std::make_shared(result); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::BLE_ENABLE_ADVERTISING, napiAdvResult, result); } @@ -68,6 +70,7 @@ void NapiBluetoothBleAdvertiseCallback::OnDisableResultEvent(int result, int adv HILOGI("enter, result: %{public}d advHandle: %{public}d", result, advHandle); if (advHandle_ == advHandle) { HILOGI("OnDisableResultEvent, advHandle is same, advHandle: %{public}d", advHandle_); + result = GetSDKAdaptedStatusCode(result); // Adaptation for old sdk auto napiAdvResult = std::make_shared(result); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::BLE_DISABLE_ADVERTISING, napiAdvResult, result); } @@ -81,6 +84,7 @@ void NapiBluetoothBleAdvertiseCallback::OnStopResultEvent(int result, int advHan HILOGI("enter, result: %{public}d advHandle: %{public}d", result, advHandle); if (advHandle_ == advHandle) { HILOGI("OnStopResultEvent, advHandle is same, advHandle: %{public}d", advHandle_); + result = GetSDKAdaptedStatusCode(result); // Adaptation for old sdk auto napiAdvResult = std::make_shared(result); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::BLE_STOP_ADVERTISING, napiAdvResult, result); advHandle_ = -1; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp index c9c812e9..b987ce0f 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp @@ -37,6 +37,15 @@ using namespace std; thread_local napi_ref NapiGattClient::consRef_ = nullptr; +const std::vector> NapiGattClient::g_gattStatusSrvToNapi = { + { Bluetooth::BT_NO_ERROR, GATT_SUCCESS }, + { Bluetooth::BT_ERR_GATT_WRITE_NOT_PERMITTED, WRITE_NOT_PERMITTED }, + { Bluetooth::BT_ERR_GATT_READ_NOT_PERMITTED, READ_NOT_PERMITTED }, + { Bluetooth::BT_ERR_GATT_CONNECTION_CONGESTED, GATT_CONGESTION }, + { Bluetooth::BT_ERR_GATT_CONNECTION_NOT_ENCRYPTED, INSUFFICIENT_ENCRYPTION }, + { Bluetooth::BT_ERR_GATT_CONNECTION_NOT_AUTHENTICATED, AUTHENTICATION_FAILED }, + { Bluetooth::BT_ERR_GATT_CONNECTION_NOT_AUTHORIZED, INSUFFICIENT_AUTHORIZATION }, +}; static napi_status CheckCreateGattClientDeviceParams(napi_env env, napi_callback_info info, napi_value &outResult) { size_t expectedArgsCount = ARGS_SIZE_ONE; @@ -338,6 +347,7 @@ napi_value NapiGattClient::ReadCharacteristicValue(napi_env env, napi_callback_i int ret = BT_ERR_INTERNAL_ERROR; if (gattClient) { ret = gattClient->ReadCharacteristic(*character); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk } return NapiAsyncWorkRet(ret); }; @@ -391,6 +401,7 @@ napi_value NapiGattClient::ReadDescriptorValue(napi_env env, napi_callback_info int ret = BT_ERR_INTERNAL_ERROR; if (gattClient) { ret = gattClient->ReadDescriptor(*descriptor); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk } return NapiAsyncWorkRet(ret); }; @@ -524,6 +535,7 @@ napi_value NapiGattClient::GetRssiValue(napi_env env, napi_callback_info info) int ret = BT_ERR_INTERNAL_ERROR; if (gattClient) { ret = gattClient->ReadRemoteRssiValue(); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk } return NapiAsyncWorkRet(ret); }; @@ -571,6 +583,27 @@ napi_value NapiGattClient::GetDeviceName(napi_env env, napi_callback_info info) return asyncWork->GetRet(); } +int NapiGattClient::GattStatusFromService(int status) +{ + // if status is from napi, do not deal with. + if (status > 0) { + return status; + } + int ret = BT_ERR_INTERNAL_ERROR; + // statusCode srv -> napi + auto iter = g_gattStatusSrvToNapi.begin(); + for (; iter != g_gattStatusSrvToNapi.end(); iter++) { + if (iter->second == status) { + ret = iter->first; // transfer to napi errorCode. + break; + } + } + if (iter == g_gattStatusSrvToNapi.end()) { + HILOGW("Unsupported error code conversion, status: %{public}d", status); + } + return ret; +} + #ifdef BLUETOOTH_API_SINCE_10 static napi_status CheckWriteCharacteristicValueEx(napi_env env, napi_callback_info info, @@ -619,6 +652,7 @@ napi_value NapiGattClient::WriteCharacteristicValueEx(napi_env env, napi_callbac int ret = BT_ERR_INTERNAL_ERROR; if (gattClient) { ret = gattClient->WriteCharacteristic(*character); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk } return NapiAsyncWorkRet(ret); }; @@ -675,6 +709,7 @@ napi_value NapiGattClient::WriteDescriptorValueEx(napi_env env, napi_callback_in int ret = BT_ERR_INTERNAL_ERROR; if (gattClient) { ret = gattClient->WriteDescriptor(*descriptor); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk } return NapiAsyncWorkRet(ret); }; @@ -731,6 +766,7 @@ static napi_value setCharacteristicChangeInner(napi_env env, napi_callback_info } else { ret = gattClient->SetIndicateCharacteristic(*character, enable); } + ret = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(ret)); // Adaptation for old sdk } return NapiAsyncWorkRet(ret); }; @@ -793,6 +829,7 @@ napi_value NapiGattClient::WriteCharacteristicValue(napi_env env, napi_callback_ std::shared_ptr client = gattClient->GetClient(); NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); int ret = client->WriteCharacteristic(*characteristic, std::move(value)); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk HILOGI("ret: %{public}d", ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); @@ -833,6 +870,7 @@ napi_value NapiGattClient::WriteDescriptorValue(napi_env env, napi_callback_info NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); int ret = client->WriteDescriptor(*descriptor); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk HILOGI("ret: %{public}d", ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); @@ -875,6 +913,7 @@ napi_value NapiGattClient::SetNotifyCharacteristicChanged(napi_env env, napi_cal NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); int ret = client->SetNotifyCharacteristic(*characteristic, enableNotify); + ret = GetSDKAdaptedStatusCode(GattStatusFromService(ret)); // Adaptation for old sdk HILOGI("ret: %{public}d", ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); 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 5e900374..ad348355 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 @@ -43,6 +43,7 @@ void NapiGattClientCallback::OnCharacteristicChanged(const GattCharacteristic &c void NapiGattClientCallback::OnCharacteristicReadResult(const GattCharacteristic &characteristic, int ret) { HILOGI("UUID: %{public}s, ret: %{public}d", characteristic.GetUuid().ToString().c_str(), ret); + ret = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(ret)); // Adaptation for old sdk auto napiCharacter = std::make_shared(characteristic); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GATT_CLIENT_READ_CHARACTER, napiCharacter, ret); } @@ -50,6 +51,7 @@ void NapiGattClientCallback::OnCharacteristicReadResult(const GattCharacteristic void NapiGattClientCallback::OnDescriptorReadResult(const GattDescriptor &descriptor, int ret) { HILOGI("UUID: %{public}s, ret: %{public}d", descriptor.GetUuid().ToString().c_str(), ret); + ret = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(ret)); // Adaptation for old sdk auto napiDescriptor = std::make_shared(descriptor); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GATT_CLIENT_READ_DESCRIPTOR, napiDescriptor, ret); } @@ -69,6 +71,7 @@ void NapiGattClientCallback::OnServicesDiscovered(int status) void NapiGattClientCallback::OnReadRemoteRssiValueResult(int rssi, int ret) { HILOGI("rssi: %{public}d, ret: %{public}d", rssi, ret); + ret = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(ret)); // Adaptation for old sdk auto napiRssi = std::make_shared(rssi); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GATT_CLIENT_READ_REMOTE_RSSI_VALUE, napiRssi, ret); } @@ -77,6 +80,7 @@ void NapiGattClientCallback::OnCharacteristicWriteResult(const GattCharacteristi { #ifdef BLUETOOTH_API_SINCE_10 HILOGI("UUID: %{public}s, ret: %{public}d", characteristic.GetUuid().ToString().c_str(), ret); + ret = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(ret)); // Adaptation for old sdk auto napiCharacter = std::make_shared(characteristic); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GATT_CLIENT_WRITE_CHARACTER, napiCharacter, ret); #endif @@ -86,6 +90,7 @@ void NapiGattClientCallback::OnDescriptorWriteResult(const GattDescriptor &descr { #ifdef BLUETOOTH_API_SINCE_10 HILOGI("UUID: %{public}s, ret: %{public}d", descriptor.GetUuid().ToString().c_str(), ret); + ret = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(ret)); // Adaptation for old sdk auto napiDescriptor = std::make_shared(descriptor); AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GATT_CLIENT_WRITE_DESCRIPTOR, napiDescriptor, ret); #endif @@ -95,6 +100,7 @@ void NapiGattClientCallback::OnSetNotifyCharacteristic(const GattCharacteristic { #ifdef BLUETOOTH_API_SINCE_10 HILOGI("UUID: %{public}s, status: %{public}d", characteristic.GetUuid().ToString().c_str(), status); + status = GetSDKAdaptedStatusCode(NapiGattClient::GattStatusFromService(status)); // Adaptation for old sdk AsyncWorkCallFunction(asyncWorkMap_, NapiAsyncType::GATT_CLIENT_ENABLE_CHARACTER_CHANGED, nullptr, status); #endif } diff --git a/frameworks/js/napi/src/common/BUILD.gn b/frameworks/js/napi/src/common/BUILD.gn index bd65c61e..c608319b 100644 --- a/frameworks/js/napi/src/common/BUILD.gn +++ b/frameworks/js/napi/src/common/BUILD.gn @@ -66,6 +66,7 @@ ohos_shared_library("bt_napi_common") { "ipc:ipc_single", "libuv:uv", "napi:ace_napi", + "samgr:samgr_proxy", ] part_name = "bluetooth" diff --git a/frameworks/js/napi/src/common/napi_bluetooth_utils.cpp b/frameworks/js/napi/src/common/napi_bluetooth_utils.cpp index 2439159c..4d99e6cf 100644 --- a/frameworks/js/napi/src/common/napi_bluetooth_utils.cpp +++ b/frameworks/js/napi/src/common/napi_bluetooth_utils.cpp @@ -28,6 +28,9 @@ #include "napi_bluetooth_spp_client.h" #include "../parser/napi_parser_utils.h" #include "securec.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "bundle_mgr_proxy.h" namespace OHOS { namespace Bluetooth { @@ -821,5 +824,60 @@ napi_status NapiGetOnOffCallbackName(napi_env env, napi_callback_info info, std: name = type; return napi_ok; } + +int GetCurrentSdkVersion(void) +{ + int version = SDK_VERSION_20; // default sdk version is api 20 + + auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + HILOGE("fail to get system ability mgr."); + return version; + } + auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (!remoteObject) { + HILOGE("fail to get bundle manager proxy."); + return version; + } + sptr bundleMgrProxy = iface_cast(remoteObject); + if (bundleMgrProxy == nullptr) { + HILOGE("Failed to get bundle manager proxy."); + return version; + } + AppExecFwk::BundleInfo bundleInfo; + auto flags = AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION; + auto ret = bundleMgrProxy->GetBundleInfoForSelf(static_cast(flags), bundleInfo); + if (ret != ERR_OK) { + HILOGE("GetBundleInfoForSelf: get fail."); + return version; + } + + version = bundleInfo.targetVersion % 100; // %100 to get the real version + return version; +} + +int GetSDKAdaptedStatusCode(int status) +{ + std::set statusCodeForNewSdk = { + BT_ERR_MAX_RESOURCES, + BT_ERR_OPERATION_BUSY, + BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED, + BT_ERR_GATT_CONNECTION_CONGESTED, + BT_ERR_GATT_CONNECTION_NOT_ENCRYPTED, + BT_ERR_GATT_CONNECTION_NOT_AUTHENTICATED, + BT_ERR_GATT_CONNECTION_NOT_AUTHORIZED, + BT_ERR_BLE_ADV_DATA_EXCEED_LIMIT, + BT_ERR_BLE_INVALID_ADV_ID, + }; + bool isNewStatusCode = false; + if (statusCodeForNewSdk.find(status) != statusCodeForNewSdk.end()) { + isNewStatusCode = true; + } + // If sdk version is lower than SDK_VERSION_20, the status code is changed to old version. + if (GetCurrentSdkVersion() < SDK_VERSION_20 && isNewStatusCode) { + return BT_ERR_INTERNAL_ERROR; + } + return status; +} } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_def.h b/interfaces/inner_api/include/bluetooth_def.h index 9707fb7c..f832e376 100644 --- a/interfaces/inner_api/include/bluetooth_def.h +++ b/interfaces/inner_api/include/bluetooth_def.h @@ -320,6 +320,10 @@ enum class GattConnectionPriority : int { }; enum GattStatus { + AUTHENTICATION_FAILED = -33, + GATT_CONGESTION = -32, + EMPTY_FILTER = -31, + MAX_FILTERS = -30, INVALID_REMOTE_DEVICE = -29, INCLUDE_SERVICE_NOT_FOUND, REFERENCED_BY_OTHER_SERVICE, diff --git a/interfaces/inner_api/include/bluetooth_errorcode.h b/interfaces/inner_api/include/bluetooth_errorcode.h index 47cceb11..74ed0389 100644 --- a/interfaces/inner_api/include/bluetooth_errorcode.h +++ b/interfaces/inner_api/include/bluetooth_errorcode.h @@ -42,6 +42,7 @@ enum BtErrCode { BT_ERR_UNAVAILABLE_PROXY = BT_ERR_BASE_SYSCAP + 8, BT_ERR_DIALOG_FOR_USER_CONFIRM = BT_ERR_BASE_SYSCAP + 9, BT_ERR_MAX_RESOURCES = BT_ERR_BASE_SYSCAP + 10, + BT_ERR_OPERATION_BUSY = BT_ERR_BASE_SYSCAP + 11, BT_ERR_INTERNAL_ERROR = BT_ERR_BASE_SYSCAP + 99, BT_ERR_IPC_TRANS_FAILED = BT_ERR_BASE_SYSCAP + 100, @@ -49,6 +50,11 @@ enum BtErrCode { BT_ERR_GATT_READ_NOT_PERMITTED = BT_ERR_BASE_SYSCAP + 1000, BT_ERR_GATT_WRITE_NOT_PERMITTED = BT_ERR_BASE_SYSCAP + 1001, BT_ERR_GATT_MAX_SERVER = BT_ERR_BASE_SYSCAP + 1002, + BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED = BT_ERR_BASE_SYSCAP + 1003, + BT_ERR_GATT_CONNECTION_CONGESTED = BT_ERR_BASE_SYSCAP + 1004, + BT_ERR_GATT_CONNECTION_NOT_ENCRYPTED = BT_ERR_BASE_SYSCAP + 1005, + BT_ERR_GATT_CONNECTION_NOT_AUTHENTICATED = BT_ERR_BASE_SYSCAP + 1006, + BT_ERR_GATT_CONNECTION_NOT_AUTHORIZED = BT_ERR_BASE_SYSCAP + 1007, BT_ERR_SPP_SERVER_STATE = BT_ERR_BASE_SYSCAP + 1050, BT_ERR_SPP_BUSY = BT_ERR_BASE_SYSCAP + 1051, @@ -69,6 +75,8 @@ enum BtErrCode { BT_ERR_BLE_SCAN_MAX_FILTER = BT_ERR_BASE_SYSCAP + 2051, BT_ERR_BLE_CHANGE_SCAN_FILTER_FAIL = BT_ERR_BASE_SYSCAP + 2052, BT_ERR_BLE_CHANGE_SCAN_WRONG_STATE = BT_ERR_BASE_SYSCAP + 2053, + BT_ERR_BLE_ADV_DATA_EXCEED_LIMIT = BT_ERR_BASE_SYSCAP + 2054, + BT_ERR_BLE_INVALID_ADV_ID = BT_ERR_BASE_SYSCAP + 2055, // will deprected NO_ERROR = BT_NO_ERROR, -- Gitee From d02377c628dd956920450daa935ec3427d56b35f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E9=98=94?= Date: Fri, 16 May 2025 16:24:21 +0800 Subject: [PATCH 33/45] add l2hc bitrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 杨阔 --- frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp index 834ad2ce..e9af0a7f 100644 --- a/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp +++ b/frameworks/js/napi/src/a2dp/napi_bluetooth_a2dp_src.cpp @@ -929,6 +929,7 @@ static napi_status CheckSetCodecPreferenceParam(napi_env env, napi_callback_info ConvertCodecSampleRate(a2dpCodecInfo, codecSampleRate); if (NapiIsObjectPropertyExist(env, argv[PARAM1], "codecBitRate")) { int32_t codecBitRate = 0; + NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, argv[PARAM1], "codecBitRate", codecBitRate)); ConvertCodecBitRate(a2dpCodecInfo, codecBitRate); } return napi_ok; -- Gitee From 84e95d55a7be8e56ea77a50dd6a1c5a1c67f440f Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Fri, 16 May 2025 19:01:17 +0800 Subject: [PATCH 34/45] add permission and property Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I3c31bc928d7747f9943861b4dceab64b4f52891a --- .../napi/src/ble/napi_bluetooth_ble_utils.cpp | 57 +++++++++++++++++++ .../js/napi/src/parser/napi_parser_utils.cpp | 53 ++++++++++++++--- .../js/napi/src/parser/napi_parser_utils.h | 9 ++- .../include/bluetooth_gatt_characteristic.h | 14 +++++ 4 files changed, 123 insertions(+), 10 deletions(-) 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 f0a1c638..ec78b59c 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp @@ -122,6 +122,57 @@ napi_value ConvertGattPropertiesToJs(napi_env env, int properties) napi_get_boolean(env, HasProperty(properties, GattCharacteristic::INDICATE), &value); napi_set_named_property(env, object, "indicate", value); + + napi_get_boolean(env, HasProperty(properties, GattCharacteristic::BROADCAST), &value); + napi_set_named_property(env, object, "broadcast", value); + + napi_get_boolean(env, HasProperty(properties, GattCharacteristic::AUTHENTICATED_SIGNED_WRITES), &value); + napi_set_named_property(env, object, "authenticatedSignedWrite", value); + + napi_get_boolean(env, HasProperty(properties, GattCharacteristic::EXTENDED_PROPERTIES), &value); + napi_set_named_property(env, object, "extendedProperties", value); + return object; +} + +bool HasPermission(int permissions, int permissionMask) +{ + if (permissions < 0 || permissionMask < 0) { + HILOGE("permissions or permissionMask is less than 0"); + return false; + } + return (static_cast(permissions) & static_cast(permissionMask)) != 0; +} + +napi_value ConvertGattPermissionsToJs(napi_env env, int permissions) +{ + napi_value object; + napi_create_object(env, &object); + + napi_value value; + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::READABLE), &value); + napi_set_named_property(env, object, "read", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::READ_ENCRYPTED), &value); + napi_set_named_property(env, object, "readEncrypted", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::READ_ENCRYPTED_MITM), &value); + napi_set_named_property(env, object, "readEncryptedMitm", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::WRITEABLE), &value); + napi_set_named_property(env, object, "write", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::WRITE_ENCRYPTED), &value); + napi_set_named_property(env, object, "writeEncrypted", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::WRITE_ENCRYPTED_MITM), &value); + napi_set_named_property(env, object, "writeEncryptedMitm", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::WRITE_SIGNED), &value); + napi_set_named_property(env, object, "writeSigned", value); + + napi_get_boolean(env, HasPermission(permissions, GattCharacteristic::WRITE_SIGNED_MITM), &value); + napi_set_named_property(env, object, "writeSignedMitm", value); + return object; } @@ -155,6 +206,9 @@ void ConvertBLECharacteristicToJS(napi_env env, napi_value result, GattCharacter napi_value propertiesValue = ConvertGattPropertiesToJs(env, characteristic.GetProperties()); napi_set_named_property(env, result, "properties", propertiesValue); + napi_value permissionsValue = ConvertGattPermissionsToJs(env, characteristic.GetPermissions()); + napi_set_named_property(env, result, "permissions", permissionsValue); + napi_value descriptors; napi_create_array(env, &descriptors); ConvertBLEDescriptorVectorToJS(env, descriptors, characteristic.GetDescriptors()); @@ -218,6 +272,9 @@ void ConvertBLEDescriptorToJS(napi_env env, napi_value result, GattDescriptor& d napi_value descriptorHandle; napi_create_uint32(env, static_cast(descriptor.GetHandle()), &descriptorHandle); napi_set_named_property(env, result, "descriptorHandle", descriptorHandle); + + napi_value permissionsValue = ConvertGattPermissionsToJs(env, descriptor.GetPermissions()); + napi_set_named_property(env, result, "permissions", permissionsValue); } void ConvertCharacteristicReadReqToJS(napi_env env, napi_value result, const std::string &device, diff --git a/frameworks/js/napi/src/parser/napi_parser_utils.cpp b/frameworks/js/napi/src/parser/napi_parser_utils.cpp index b052f0af..0845fab1 100644 --- a/frameworks/js/napi/src/parser/napi_parser_utils.cpp +++ b/frameworks/js/napi/src/parser/napi_parser_utils.cpp @@ -83,15 +83,27 @@ uint16_t ConvertGattPermissions(const NapiGattPermission &napiPermissions) if (napiPermissions.readable) { permissions |= static_cast(GattPermission::READABLE); } - if (napiPermissions.writeable) { - permissions |= static_cast(GattPermission::WRITEABLE); - } if (napiPermissions.readEncrypted) { + permissions |= static_cast(GattPermission::READ_ENCRYPTED); + } + if (napiPermissions.readEncryptedMitm) { permissions |= static_cast(GattPermission::READ_ENCRYPTED_MITM); } + if (napiPermissions.writeable) { + permissions |= static_cast(GattPermission::WRITEABLE); + } if (napiPermissions.writeEncrypted) { + permissions |= static_cast(GattPermission::WRITE_ENCRYPTED); + } + if (napiPermissions.writeEncryptedMitm) { permissions |= static_cast(GattPermission::WRITE_ENCRYPTED_MITM); } + if (napiPermissions.writeSigned) { + permissions |= static_cast(GattPermission::WRITE_SIGNED); + } + if (napiPermissions.writeSignedMitm) { + permissions |= static_cast(GattPermission::WRITE_SIGNED_MITM); + } return permissions; } uint16_t ConvertGattProperties(const NapiGattProperties &napiProperties) @@ -112,6 +124,15 @@ uint16_t ConvertGattProperties(const NapiGattProperties &napiProperties) if (napiProperties.indicate) { properties |= static_cast(GattCharacteristic::INDICATE); } + if (napiProperties.broadcast) { + properties |= static_cast(GattCharacteristic::BROADCAST); + } + if (napiProperties.authenticatedSignedWrite) { + properties |= static_cast(GattCharacteristic::AUTHENTICATED_SIGNED_WRITES); + } + if (napiProperties.extendedProperties) { + properties |= static_cast(GattCharacteristic::EXTENDED_PROPERTIES); + } return properties; } } // namespace {} @@ -243,19 +264,27 @@ napi_status NapiParseObjectGattPermissions(napi_env env, napi_value object, cons NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, permissionObject)); // Parse permission object - NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, permissionObject, {"readable", "writeable", - "readEncrypted", "writeEncrypted"})); + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, permissionObject, {"read", "readEncrypted", + "readEncryptedMitm", "write", "writeEncrypted", "writeEncryptedMitm", "writeSigned", "writeSignedMitm"})); bool isExist; NapiGattPermission permissions {}; NAPI_BT_CALL_RETURN( - NapiParseObjectBooleanOptional(env, permissionObject, "readable", permissions.readable, isExist)); - NAPI_BT_CALL_RETURN( - NapiParseObjectBooleanOptional(env, permissionObject, "writeable", permissions.writeable, isExist)); + NapiParseObjectBooleanOptional(env, permissionObject, "read", permissions.readable, isExist)); NAPI_BT_CALL_RETURN( NapiParseObjectBooleanOptional(env, permissionObject, "readEncrypted", permissions.readEncrypted, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, permissionObject, "readEncryptedMitm", permissions.readEncryptedMitm, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, permissionObject, "write", permissions.writeable, isExist)); NAPI_BT_CALL_RETURN( NapiParseObjectBooleanOptional(env, permissionObject, "writeEncrypted", permissions.writeEncrypted, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, permissionObject, "writeEncryptedMitm", permissions.writeEncryptedMitm, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, permissionObject, "writeSigned", permissions.writeSigned, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, permissionObject, "writeSignedMitm", permissions.writeSignedMitm, isExist)); outPermissions = permissions; return napi_ok; } @@ -268,7 +297,7 @@ napi_status NapiParseObjectGattProperties(napi_env env, napi_value object, const NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, propertiesObject)); // Parse properties object NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, propertiesObject, {"write", "writeNoResponse", - "read", "notify", "indicate"})); + "read", "notify", "indicate", "broadcast", "authenticatedSignedWrite", "extendedProperties"})); bool isExist; NapiGattProperties properties {}; @@ -282,6 +311,12 @@ napi_status NapiParseObjectGattProperties(napi_env env, napi_value object, const NapiParseObjectBooleanOptional(env, propertiesObject, "notify", properties.notify, isExist)); NAPI_BT_CALL_RETURN( NapiParseObjectBooleanOptional(env, propertiesObject, "indicate", properties.indicate, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, propertiesObject, "broadcast", properties.broadcast, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, propertiesObject, "authenticatedSignedWrite", properties.authenticatedSignedWrite, isExist)); + NAPI_BT_CALL_RETURN( + NapiParseObjectBooleanOptional(env, propertiesObject, "extendedProperties", properties.extendedProperties, isExist)); outProperties = properties; return napi_ok; } diff --git a/frameworks/js/napi/src/parser/napi_parser_utils.h b/frameworks/js/napi/src/parser/napi_parser_utils.h index 69d1d74f..24f00c42 100644 --- a/frameworks/js/napi/src/parser/napi_parser_utils.h +++ b/frameworks/js/napi/src/parser/napi_parser_utils.h @@ -56,9 +56,13 @@ struct NapiGattService { struct NapiGattPermission { bool readable = false; - bool writeable = false; bool readEncrypted = false; + bool readEncryptedMitm = false; + bool writeable = false; bool writeEncrypted = false; + bool writeEncryptedMitm = false; + bool writeSigned = false; + bool writeSignedMitm = false; }; struct NapiGattProperties { @@ -67,6 +71,9 @@ struct NapiGattProperties { bool read = false; bool notify = false; bool indicate = false; + bool broadcast = false; + bool authenticatedSignedWrite = false; + bool extendedProperties = false; }; bool NapiIsObjectPropertyExist(napi_env env, napi_value object, const char *name); diff --git a/interfaces/inner_api/include/bluetooth_gatt_characteristic.h b/interfaces/inner_api/include/bluetooth_gatt_characteristic.h index 8fb78c7f..207de9bb 100644 --- a/interfaces/inner_api/include/bluetooth_gatt_characteristic.h +++ b/interfaces/inner_api/include/bluetooth_gatt_characteristic.h @@ -85,6 +85,20 @@ public: EXTENDED_PROPERTIES = 0x80 }; + /** A GATT characteristic permission. + * Define GATT characteristic permission. + */ + enum Permission { + READABLE = 0x01, + READ_ENCRYPTED = 0x02, + READ_ENCRYPTED_MITM = 0x04, + WRITEABLE = 0x08, + WRITE_ENCRYPTED = 0x10, + WRITE_ENCRYPTED_MITM = 0x20, + WRITE_SIGNED = 0x40, + WRITE_SIGNED_MITM = 0x80 + }; + /** * @brief The function to delete constructor of GattCharacteristic. * -- Gitee From 1cf6c55ef374ee0a5c0235061571d15d494fabf2 Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Fri, 16 May 2025 17:59:36 +0800 Subject: [PATCH 35/45] error bugfix Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I561d03580c3e270304ce2b825f996ab0c9121c7a --- frameworks/js/napi/src/common/napi_bluetooth_error.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp index 049f95b6..a484fa40 100644 --- a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp +++ b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp @@ -54,6 +54,15 @@ static std::map napiErrMsgMap { { BtErrCode::BT_ERR_AUDIO_NOT_IDLE, "Audio is not idle." }, { BtErrCode::BT_ERR_VIRTUAL_CALL_NOT_STARTED, "Virtual call is not started." }, { BtErrCode::BT_ERR_DISCONNECT_SCO_FAILED, "Disconnect sco failed." }, + { BtErrCode::BT_ERR_MAX_RESOURCES, "The number of resources reaches the upper limit." }, + { BtErrCode::BT_ERR_BLE_ADV_DATA_EXCEED_LIMIT, "The length of the advertising data exceeds the upper limit." }, + { BtErrCode::BT_ERR_BLE_INVALID_ADV_ID, "Invalid advertising id." }, + { BtErrCode::BT_ERR_OPERATION_BUSY, "The operation is busy. The last operation is not complete." }, + { BtErrCode::BT_ERR_GATT_CONNECTION_NOT_ESTABILISHED, "The connection is not established." }, + { BtErrCode::BT_ERR_GATT_CONNECTION_CONGESTED, "The connection is congested." }, + { BtErrCode::BT_ERR_GATT_CONNECTION_NOT_ENCRYPTED, "The connection is not encrypted." }, + { BtErrCode::BT_ERR_GATT_CONNECTION_NOT_AUTHENTICATED, "The connection is not authenticated." }, + { BtErrCode::BT_ERR_GATT_CONNECTION_NOT_AUTHORIZED, "The connection is not authorized." }, }; std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode) -- Gitee From 1c486237a3a6e0d31078447addc6ef44799d87e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Sat, 17 May 2025 03:56:29 +0000 Subject: [PATCH 36/45] bugfix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/js/napi/src/common/napi_ha_event_utils.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) 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 062bfd12..b6681a48 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -20,8 +20,10 @@ #include "napi_ha_event_utils.h" #include "bluetooth_log.h" #include "bluetooth_errorcode.h" +#ifndef CROSS_PLATFORM #include "app_event.h" #include "app_event_processor_mgr.h" +#endif namespace OHOS { namespace Bluetooth { @@ -77,6 +79,7 @@ int64_t NapiHaEventUtils::GetNowTimeMs() const int64_t NapiHaEventUtils::AddProcessor() { +#ifndef CROSS_PLATFORM HiviewDFX::HiAppEvent::ReportConfig config; config.name = "ha_app_event"; // 系统预制so,实现上报功能,由HA提供 config.appId = "com_huawei_hmos_sdk_ocg"; @@ -106,6 +109,9 @@ int64_t NapiHaEventUtils::AddProcessor() config.eventConfigs.push_back(event3); } return HiviewDFX::HiAppEvent::AppEventProcessorMgr::AddProcessor(config); +#else + return -1; +#endif } std::string NapiHaEventUtils::RandomTransId() const @@ -115,6 +121,7 @@ std::string NapiHaEventUtils::RandomTransId() const void NapiHaEventUtils::WriteEndEvent() const { +#ifndef CROSS_PLATFORM HiviewDFX::HiAppEvent::Event event("api_diagnostic", "api_exec_end", HiviewDFX::HiAppEvent::BEHAVIOR); std::string transId = RandomTransId(); event.AddParam("trans_id", transId); @@ -127,6 +134,7 @@ void NapiHaEventUtils::WriteEndEvent() const int ret = Write(event); HILOGD("WriteEndEvent transId:%{public}s, apiName:%{public}s, sdkName:%{public}s, errCode:%{public}d," "ret:%{public}d", transId.c_str(), apiName_.c_str(), SDK_NAME.c_str(), errCode_, ret); +#endif } } // namespace Bluetooth -- Gitee From ac918f90fa196a551282e50f7e2e853f4059b47b Mon Sep 17 00:00:00 2001 From: linzlinz <2495670683@qq.com> Date: Sat, 17 May 2025 13:05:13 +0800 Subject: [PATCH 37/45] codecheck bugfix Signed-off-by: linzlinz <2495670683@qq.com> Change-Id: I18438dc4c848d9c33a277a86cfe0aaa963d73f41 --- frameworks/inner/src/bluetooth_gatt_client.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 68a0b957..c14b786a 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -885,15 +885,9 @@ int GattClient::RequestBleMtuSize(int mtu) int GattClient::SetNotifyCharacteristicInner(GattCharacteristic &characteristic, bool enable, const std::vector &descriptorValue) { - if (!IS_BLE_ENABLED()) { - HILOGE("bluetooth is off."); - return BT_ERR_INVALID_STATE; - } - - if (pimpl == nullptr || !pimpl->Init(weak_from_this())) { - HILOGE("pimpl or gatt client proxy is nullptr"); - return BT_ERR_INTERNAL_ERROR; - } + 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"); sptr proxy = GetRemoteProxy(PROFILE_GATT_CLIENT); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "failed: no proxy"); int ret = proxy->RequestNotification(pimpl->applicationId_, characteristic.GetHandle(), enable); -- Gitee From e6009c2211013b297335836dc28f6b581f88e091 Mon Sep 17 00:00:00 2001 From: shinezxy Date: Sat, 17 May 2025 15:56:35 +0800 Subject: [PATCH 38/45] add car key dfx data Signed-off-by: shinezxy --- frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp index 5f65c695..d736630b 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp @@ -313,7 +313,7 @@ napi_value SetCarKeyCardData(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); int ret = host->SetCarKeyCardData(remoteAddr, action); - NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } -- Gitee From d0d6e88d6cf3009cfc511653a6445e350d2e99d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Sat, 17 May 2025 09:21:56 +0000 Subject: [PATCH 39/45] =?UTF-8?q?=E9=80=9A=E8=BF=87=E5=85=A8=E5=B1=80?= =?UTF-8?q?=E5=AD=98=E5=82=A8env=E5=92=8CerrCode=E7=9A=84=E6=98=A0?= =?UTF-8?q?=E5=B0=84=E5=85=B3=E7=B3=BB=EF=BC=8C=E4=BC=98=E5=8C=96HA?= =?UTF-8?q?=E6=89=93=E7=82=B9=E9=80=BB=E8=BE=91=E5=92=8Cutils=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E4=BD=93=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- .../js/napi/include/napi_ha_event_utils.h | 9 ++++--- .../js/napi/src/ble/napi_bluetooth_ble.cpp | 27 +++++-------------- .../src/ble/napi_bluetooth_ble_scanner.cpp | 6 ++--- .../src/ble/napi_bluetooth_gatt_client.cpp | 8 ++---- .../napi/src/common/napi_bluetooth_error.cpp | 2 ++ .../napi/src/common/napi_ha_event_utils.cpp | 21 ++++++++++----- .../connection/napi_bluetooth_connection.cpp | 12 +++------ 7 files changed, 36 insertions(+), 49 deletions(-) diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h index 7ce373d1..93266fe5 100644 --- a/frameworks/js/napi/include/napi_ha_event_utils.h +++ b/frameworks/js/napi/include/napi_ha_event_utils.h @@ -18,15 +18,18 @@ #include #include +#include "safe_map.h" +#include "napi/native_api.h" namespace OHOS { namespace Bluetooth { class NapiHaEventUtils { public: - explicit NapiHaEventUtils(const std::string &apiName); + NapiHaEventUtils(napi_env env, const std::string &apiName); ~NapiHaEventUtils(); void WriteErrCode(const int32_t errCode); + static void WriteErrCode(napi_env env, const int32_t errCode); private: NapiHaEventUtils() = delete; @@ -39,10 +42,10 @@ private: private: static int64_t processorId_; static std::mutex processorLock_; - std::mutex errCodeLock_; + static SafeMap envErrCodeMap_; // mapping between napi_env and errCode + napi_env env_; std::string apiName_; int64_t beginTime_; - int32_t errCode_; }; } // namespace Bluetooth diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index af027a9e..08698824 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -685,14 +685,13 @@ napi_status CheckBleScanParams(napi_env env, napi_callback_info info, std::vecto napi_value StartBLEScan(napi_env env, napi_callback_info info) { HILOGD("enter"); - NapiHaEventUtils haUtils("StartBLEScan"); + NapiHaEventUtils haUtils(env, "StartBLEScan"); std::vector scanfilters; BleScanSettings settings; auto status = CheckBleScanParams(env, info, scanfilters, settings); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = BleCentralManagerGetInstance()->StartScan(settings, scanfilters); - haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR || ret == BT_ERR_BLE_SCAN_ALREADY_STARTED, ret); return NapiGetUndefinedRet(env); @@ -701,12 +700,11 @@ napi_value StartBLEScan(napi_env env, napi_callback_info info) napi_value StopBLEScan(napi_env env, napi_callback_info info) { HILOGD("enter"); - NapiHaEventUtils haUtils("StopBLEScan"); + NapiHaEventUtils haUtils(env, "StopBLEScan"); auto status = CheckEmptyParam(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = BleCentralManagerGetInstance()->StopScan(); - haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR, ret); return NapiGetUndefinedRet(env); } @@ -890,7 +888,7 @@ napi_status CheckAdvertisingData(napi_env env, napi_callback_info info, BleAdver napi_value StartAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("StartAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "StartAdvertising"); size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {nullptr}; napi_value thisVar = nullptr; @@ -898,7 +896,6 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRes == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, bleAdvertiser, BT_ERR_INTERNAL_ERROR); BleAdvertiserSettings settings; @@ -907,7 +904,6 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) if (argc != 0 && NapiIsObjectPropertyExist(env, argv[PARAM0], "advertisingSettings")) { uint16_t duration = 0; auto status = CheckAdvertisingDataWithDuration(env, argv[PARAM0], settings, advData, rspData, duration); - haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); auto callback = std::make_shared(); auto func = [settings, advData, rspData, duration, bleAdvertiser, callback]() { @@ -918,7 +914,6 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = callback->asyncWorkMap_.TryPush( NapiAsyncType::GET_ADVERTISING_HANDLE, asyncWork); @@ -928,11 +923,9 @@ napi_value StartAdvertising(napi_env env, napi_callback_info info) return asyncWork->GetRet(); } else { auto status = CheckAdvertisingData(env, info, settings, advData, rspData); - haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); int ret = bleAdvertiser->StartAdvertising( settings, advData, rspData, 0, NapiBluetoothBleAdvertiseCallback::GetInstance()); - haUtils->WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); return NapiGetUndefinedRet(env); } @@ -976,14 +969,13 @@ napi_status CheckAdvertisingEnableParams(napi_env env, napi_callback_info info, napi_value EnableAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("EnableAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "EnableAdvertising"); uint32_t advHandle = 0xFF; uint16_t duration = 0; std::shared_ptr baseCallback; auto status = CheckAdvertisingEnableParams(env, info, advHandle, duration, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, GetSDKAdaptedStatusCode(BT_ERR_BLE_INVALID_ADV_ID)); // Adaptation for old sdk std::shared_ptr callback = @@ -1035,13 +1027,12 @@ napi_status CheckAdvertisingDisableParams(napi_env env, napi_callback_info info, napi_value DisableAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("DisableAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "DisableAdvertising"); uint32_t advHandle = 0xFF; std::shared_ptr baseCallback; auto status = CheckAdvertisingDisableParams(env, info, advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, GetSDKAdaptedStatusCode(BT_ERR_BLE_INVALID_ADV_ID)); // Adaptation for old sdk std::shared_ptr callback = @@ -1116,7 +1107,7 @@ napi_value ProcessStopAdvertisingAsyncWork(napi_env env, napi_callback_info info napi_value StopAdvertising(napi_env env, napi_callback_info info) { HILOGD("enter"); - std::shared_ptr haUtils = std::make_shared("StopAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "StopAdvertising"); size_t argc = ARGS_SIZE_TWO; napi_value argv[ARGS_SIZE_TWO] = {nullptr}; napi_value thisVar = nullptr; @@ -1124,7 +1115,6 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRes == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, bleAdvertiser, BT_ERR_INTERNAL_ERROR); if (argc != ARGS_SIZE_ZERO) { @@ -1132,32 +1122,27 @@ napi_value StopAdvertising(napi_env env, napi_callback_info info) if (argc != ARGS_SIZE_ONE && argc != ARGS_SIZE_TWO) { status = napi_invalid_arg; } - haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); uint32_t advHandle = 0xFF; std::shared_ptr baseCallback; status = CheckStopAdvWithAdvId(env, argv[PARAM0], advHandle, baseCallback); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); // compatible with XTS - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, advHandle != BLE_INVALID_ADVERTISING_HANDLE, GetSDKAdaptedStatusCode(BT_ERR_BLE_INVALID_ADV_ID)); // Adaptation for old sdk return ProcessStopAdvertisingAsyncWork(env, info, bleAdvertiser, baseCallback, haUtils); } else { auto status = CheckEmptyArgs(env, info); - haUtils->WriteErrCode(BT_ERR_INVALID_PARAM); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::vector> callbacks = bleAdvertiser->GetAdvObservers(); if (callbacks.empty()) { // compatible with XTS int ret = bleAdvertiser->StopAdvertising(NapiBluetoothBleAdvertiseCallback::GetInstance()); - haUtils->WriteErrCode(ret); ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } else { for (auto &callback : callbacks) { int ret = bleAdvertiser->StopAdvertising(callback); - haUtils->WriteErrCode(ret); ret = GetSDKAdaptedStatusCode(ret); // Adaptation for old sdk NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_NO_ERROR, ret); } diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp index 104877a5..06fb1732 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp @@ -98,7 +98,7 @@ static NapiBleScanner *NapiGetBleScanner(napi_env env, napi_callback_info info) napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("StartScan"); + std::shared_ptr haUtils = std::make_shared(env, "StartScan"); std::vector scanFilters; BleScanSettings settings; auto status = CheckBleScanParams(env, info, scanFilters, settings); @@ -116,7 +116,6 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = napiBleScanner->GetCallback()->asyncWorkMap_.TryPush(NapiAsyncType::BLE_START_SCAN, asyncWork); @@ -129,7 +128,7 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) napi_value NapiBleScanner::StopScan(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("StopScan"); + std::shared_ptr haUtils = std::make_shared(env, "StopScan"); auto status = CheckEmptyParam(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); @@ -144,7 +143,6 @@ napi_value NapiBleScanner::StopScan(napi_env env, napi_callback_info info) }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); bool success = napiBleScanner->GetCallback()->asyncWorkMap_.TryPush(NapiAsyncType::BLE_STOP_SCAN, asyncWork); diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp index f7e4832f..5994e722 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client.cpp @@ -278,11 +278,10 @@ static napi_status CheckGattClientNoArgc(napi_env env, napi_callback_info info, napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiHaEventUtils haUtils("ble.GattClientDevice.Connect"); + NapiHaEventUtils haUtils(env, "ble.GattClientDevice.Connect"); NapiGattClient *gattClient = nullptr; auto status = CheckGattClientNoArgc(env, info, &gattClient); NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); - haUtils.WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, gattClient->GetCallback() != nullptr, BT_ERR_INTERNAL_ERROR); std::shared_ptr client = gattClient->GetClient(); @@ -290,7 +289,6 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) int ret = client->Connect(gattClient->GetCallback(), false, GATT_TRANSPORT_TYPE_LE); HILOGI("ret: %{public}d", ret); - haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } @@ -298,18 +296,16 @@ napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) napi_value NapiGattClient::Disconnect(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiHaEventUtils haUtils("ble.GattClientDevice.Disconnect"); + NapiHaEventUtils haUtils(env, "ble.GattClientDevice.Disconnect"); NapiGattClient* gattClient = nullptr; auto status = CheckGattClientNoArgc(env, info, &gattClient); NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::shared_ptr client = gattClient->GetClient(); - haUtils.WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); int ret = client->Disconnect(); HILOGI("ret: %{public}d", ret); - haUtils.WriteErrCode(ret); NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_NO_ERROR, ret); return NapiGetBooleanTrue(env); } diff --git a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp index a484fa40..f14ab5be 100644 --- a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp +++ b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp @@ -20,6 +20,7 @@ #include "bluetooth_errorcode.h" #include "napi_bluetooth_utils.h" +#include "napi_ha_event_utils.h" namespace OHOS { namespace Bluetooth { @@ -81,6 +82,7 @@ void HandleSyncErr(const napi_env &env, int32_t errCode) if (errCode == BtErrCode::BT_NO_ERROR) { return; } + NapiHaEventUtils::WriteErrCode(env, errCode); std::string errMsg = GetNapiErrMsg(env, errCode); if (errMsg != "") { napi_throw_error(env, std::to_string(errCode).c_str(), errMsg.c_str()); 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 b6681a48..561546fb 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -37,11 +37,11 @@ constexpr int32_t TIME_NS_PER_MS = 1000000; int64_t NapiHaEventUtils::processorId_ = -1; std::mutex NapiHaEventUtils::processorLock_; +SafeMap NapiHaEventUtils::envErrCodeMap_ = {}; -NapiHaEventUtils::NapiHaEventUtils(const std::string &apiName): apiName_(apiName) +NapiHaEventUtils::NapiHaEventUtils(napi_env env, const std::string &apiName): env_(env), apiName_(apiName) { beginTime_ = GetNowTimeMs(); - errCode_ = BT_ERR_INVALID_PARAM; // 考虑到NAPI接口会优先校验入参,这里直接默认初始化为401错误码 GenerateProcessorId(); } @@ -50,10 +50,14 @@ NapiHaEventUtils::~NapiHaEventUtils() WriteEndEvent(); } +void NapiHaEventUtils::WriteErrCode(napi_env env, const int32_t errCode) +{ + envErrCodeMap_.EnsureInsert(env_, errCode); +} + void NapiHaEventUtils::WriteErrCode(const int32_t errCode) { - std::lock_guard lock(errCodeLock_); - errCode_ = errCode; + NapiHaEventUtils::WriteErrCode(env_, errCode); } void NapiHaEventUtils::GenerateProcessorId() @@ -124,16 +128,19 @@ void NapiHaEventUtils::WriteEndEvent() const #ifndef CROSS_PLATFORM HiviewDFX::HiAppEvent::Event event("api_diagnostic", "api_exec_end", HiviewDFX::HiAppEvent::BEHAVIOR); std::string transId = RandomTransId(); + int32_t errCode = BT_NO_ERROR; // 默认API调用成功 + errCode = envErrCodeMap_.ReadVal(env_); + envErrCodeMap_.Erase(env_); event.AddParam("trans_id", transId); event.AddParam("api_name", apiName_); event.AddParam("sdk_name", SDK_NAME); event.AddParam("begin_time", beginTime_); event.AddParam("end_time", GetNowTimeMs()); - event.AddParam("result", (errCode_ == BT_NO_ERROR ? 0 : 1)); - event.AddParam("error_code", errCode_); + event.AddParam("result", (errCode == BT_NO_ERROR ? 0 : 1)); + event.AddParam("error_code", errCode); int ret = Write(event); HILOGD("WriteEndEvent transId:%{public}s, apiName:%{public}s, sdkName:%{public}s, errCode:%{public}d," - "ret:%{public}d", transId.c_str(), apiName_.c_str(), SDK_NAME.c_str(), errCode_, ret); + "ret:%{public}d", transId.c_str(), apiName_.c_str(), SDK_NAME.c_str(), errCode, ret); #endif } diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp index d9ffffe4..a80e320c 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp @@ -503,7 +503,7 @@ napi_status CheckDeviceAsyncParam(napi_env env, napi_callback_info info, std::st napi_value PairDeviceAsync(napi_env env, napi_callback_info info) { HILOGD("enter"); - std::shared_ptr haUtils = std::make_shared("PairDeviceAsync"); + std::shared_ptr haUtils = std::make_shared(env, "PairDeviceAsync"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -515,7 +515,6 @@ napi_value PairDeviceAsync(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(err); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -575,7 +574,7 @@ napi_status CheckPairCredibleDeviceParam(napi_env env, napi_callback_info info, napi_value PairCredibleDevice(napi_env env, napi_callback_info info) { HILOGD("enter"); - std::shared_ptr haUtils = std::make_shared("PairCredibleDevice"); + std::shared_ptr haUtils = std::make_shared(env, "PairCredibleDevice"); std::string remoteAddr = INVALID_MAC_ADDRESS; int transport = BT_TRANSPORT_NONE; auto status = CheckPairCredibleDeviceParam(env, info, remoteAddr, transport); @@ -588,7 +587,6 @@ napi_value PairCredibleDevice(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(err); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -672,7 +670,7 @@ napi_value GetPairState(napi_env env, napi_callback_info info) napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("ConnectAllowedProfiles"); + std::shared_ptr haUtils = std::make_shared(env, "ConnectAllowedProfiles"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -684,7 +682,6 @@ napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); @@ -693,7 +690,7 @@ napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) napi_value DisconnectAllowedProfiles(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared("DisconnectAllowedProfiles"); + std::shared_ptr haUtils = std::make_shared(env, "DisconnectAllowedProfiles"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -705,7 +702,6 @@ napi_value DisconnectAllowedProfiles(napi_env env, napi_callback_info info) return NapiAsyncWorkRet(ret); }; auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK, haUtils); - haUtils->WriteErrCode(BT_ERR_INTERNAL_ERROR); NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR); asyncWork->Run(); return asyncWork->GetRet(); -- Gitee From a323c43878bd1ca474e62154fb6d3d560f4b6c18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Mon, 19 May 2025 01:41:57 +0000 Subject: [PATCH 40/45] update frameworks/js/napi/src/common/napi_ha_event_utils.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/js/napi/src/common/napi_ha_event_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 561546fb..934c7ea8 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -52,7 +52,7 @@ NapiHaEventUtils::~NapiHaEventUtils() void NapiHaEventUtils::WriteErrCode(napi_env env, const int32_t errCode) { - envErrCodeMap_.EnsureInsert(env_, errCode); + envErrCodeMap_.EnsureInsert(env, errCode); } void NapiHaEventUtils::WriteErrCode(const int32_t errCode) -- Gitee From 2562774d1b980df571246c98917eff41ea7fbfe5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Mon, 19 May 2025 02:55:01 +0000 Subject: [PATCH 41/45] update frameworks/js/napi/src/common/napi_ha_event_utils.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/js/napi/src/common/napi_ha_event_utils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 934c7ea8..54ac53d3 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -65,7 +65,7 @@ void NapiHaEventUtils::GenerateProcessorId() std::lock_guard lock(processorLock_); if (processorId_ == -1) { processorId_ = AddProcessor(); - HILOGW("add processorId:%{public}lld", processorId_); + HILOGW("add processorId:%{public}" PRId64, processorId_); } if (processorId_ == INVALID_PROCESSOR_ID) { -- Gitee From f0771c9360546aefa380d660fe682d5e53347390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Mon, 19 May 2025 03:14:39 +0000 Subject: [PATCH 42/45] update frameworks/js/napi/src/common/napi_ha_event_utils.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/js/napi/src/common/napi_ha_event_utils.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 54ac53d3..cfce9604 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -65,10 +65,9 @@ void NapiHaEventUtils::GenerateProcessorId() std::lock_guard lock(processorLock_); if (processorId_ == -1) { processorId_ = AddProcessor(); - HILOGW("add processorId:%{public}" PRId64, processorId_); } - if (processorId_ == INVALID_PROCESSOR_ID) { + if (processorId_ == INVALID_PROCESSOR_ID) { // 非应用不支持打点 HILOGE("invaild processorId !!!"); return; } -- Gitee From 879a105dc9764f3fac818643d1bf8af719a3a6e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E5=BF=97=E6=B5=A9?= Date: Mon, 19 May 2025 03:51:53 +0000 Subject: [PATCH 43/45] review fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 解志浩 --- frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp | 12 ++++++------ .../js/napi/src/ble/napi_bluetooth_ble_scanner.cpp | 4 ++-- .../src/connection/napi_bluetooth_connection.cpp | 11 +++++++---- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 08698824..d322696c 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -685,7 +685,7 @@ napi_status CheckBleScanParams(napi_env env, napi_callback_info info, std::vecto napi_value StartBLEScan(napi_env env, napi_callback_info info) { HILOGD("enter"); - NapiHaEventUtils haUtils(env, "StartBLEScan"); + NapiHaEventUtils haUtils(env, "ble.StartBLEScan"); std::vector scanfilters; BleScanSettings settings; auto status = CheckBleScanParams(env, info, scanfilters, settings); @@ -700,7 +700,7 @@ napi_value StartBLEScan(napi_env env, napi_callback_info info) napi_value StopBLEScan(napi_env env, napi_callback_info info) { HILOGD("enter"); - NapiHaEventUtils haUtils(env, "StopBLEScan"); + NapiHaEventUtils haUtils(env, "ble.StopBLEScan"); auto status = CheckEmptyParam(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); @@ -888,7 +888,7 @@ napi_status CheckAdvertisingData(napi_env env, napi_callback_info info, BleAdver napi_value StartAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "StartAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "ble.StartAdvertising"); size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {nullptr}; napi_value thisVar = nullptr; @@ -969,7 +969,7 @@ napi_status CheckAdvertisingEnableParams(napi_env env, napi_callback_info info, napi_value EnableAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "EnableAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "ble.EnableAdvertising"); uint32_t advHandle = 0xFF; uint16_t duration = 0; std::shared_ptr baseCallback; @@ -1027,7 +1027,7 @@ napi_status CheckAdvertisingDisableParams(napi_env env, napi_callback_info info, napi_value DisableAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "DisableAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "ble.DisableAdvertising"); uint32_t advHandle = 0xFF; std::shared_ptr baseCallback; auto status = CheckAdvertisingDisableParams(env, info, advHandle, baseCallback); @@ -1107,7 +1107,7 @@ napi_value ProcessStopAdvertisingAsyncWork(napi_env env, napi_callback_info info napi_value StopAdvertising(napi_env env, napi_callback_info info) { HILOGD("enter"); - std::shared_ptr haUtils = std::make_shared(env, "StopAdvertising"); + std::shared_ptr haUtils = std::make_shared(env, "ble.StopAdvertising"); size_t argc = ARGS_SIZE_TWO; napi_value argv[ARGS_SIZE_TWO] = {nullptr}; napi_value thisVar = nullptr; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp index 06fb1732..72a994e6 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_scanner.cpp @@ -98,7 +98,7 @@ static NapiBleScanner *NapiGetBleScanner(napi_env env, napi_callback_info info) napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "StartScan"); + std::shared_ptr haUtils = std::make_shared(env, "ble.BleScanner.StartScan"); std::vector scanFilters; BleScanSettings settings; auto status = CheckBleScanParams(env, info, scanFilters, settings); @@ -128,7 +128,7 @@ napi_value NapiBleScanner::StartScan(napi_env env, napi_callback_info info) napi_value NapiBleScanner::StopScan(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "StopScan"); + std::shared_ptr haUtils = std::make_shared(env, "ble.BleScanner.StopScan"); auto status = CheckEmptyParam(env, info); NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); diff --git a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp index a80e320c..3d0686b3 100644 --- a/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp +++ b/frameworks/js/napi/src/connection/napi_bluetooth_connection.cpp @@ -503,7 +503,7 @@ napi_status CheckDeviceAsyncParam(napi_env env, napi_callback_info info, std::st napi_value PairDeviceAsync(napi_env env, napi_callback_info info) { HILOGD("enter"); - std::shared_ptr haUtils = std::make_shared(env, "PairDeviceAsync"); + std::shared_ptr haUtils = std::make_shared(env, "connection.PairDeviceAsync"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -574,7 +574,8 @@ napi_status CheckPairCredibleDeviceParam(napi_env env, napi_callback_info info, napi_value PairCredibleDevice(napi_env env, napi_callback_info info) { HILOGD("enter"); - std::shared_ptr haUtils = std::make_shared(env, "PairCredibleDevice"); + std::shared_ptr haUtils = + std::make_shared(env, "connection.PairCredibleDevice"); std::string remoteAddr = INVALID_MAC_ADDRESS; int transport = BT_TRANSPORT_NONE; auto status = CheckPairCredibleDeviceParam(env, info, remoteAddr, transport); @@ -670,7 +671,8 @@ napi_value GetPairState(napi_env env, napi_callback_info info) napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "ConnectAllowedProfiles"); + std::shared_ptr haUtils = + std::make_shared(env, "connection.ConnectAllowedProfiles"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); @@ -690,7 +692,8 @@ napi_value ConnectAllowedProfiles(napi_env env, napi_callback_info info) napi_value DisconnectAllowedProfiles(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::shared_ptr haUtils = std::make_shared(env, "DisconnectAllowedProfiles"); + std::shared_ptr haUtils = + std::make_shared(env, "connection.DisconnectAllowedProfiles"); std::string remoteAddr = INVALID_MAC_ADDRESS; auto checkRet = CheckDeviceAsyncParam(env, info, remoteAddr); NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); -- Gitee From ba9e7eeb835f8a84de2f0e485f0fbd6ac1abf174 Mon Sep 17 00:00:00 2001 From: hui Date: Mon, 19 May 2025 20:32:54 +0800 Subject: [PATCH 44/45] enum_state Signed-off-by: hui --- frameworks/inner/ipc/common/bt_def.h | 7 +++++++ frameworks/js/napi/include/napi_bluetooth_utils.h | 7 ------- interfaces/inner_api/include/bluetooth_def.h | 7 +++++++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index cff6c92a..2788dfba 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -1780,6 +1780,13 @@ enum class RandomDeviceIdCommand { IS_VALID }; +enum ProfileConnectionState { + STATE_DISCONNECTED = 0, // the current profile is disconnected + STATE_CONNECTING = 1, // the current profile is being connected + STATE_CONNECTED = 2, // the current profile is connected + STATE_DISCONNECTING = 3 // the current profile is being disconnected +}; + #ifdef BLUETOOTH_EXPORT #define BLUETOOTH_API __attribute__((visibility("default"))) #else diff --git a/frameworks/js/napi/include/napi_bluetooth_utils.h b/frameworks/js/napi/include/napi_bluetooth_utils.h index f8a219ae..6f1994a4 100644 --- a/frameworks/js/napi/include/napi_bluetooth_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_utils.h @@ -271,13 +271,6 @@ struct NapiGattsServerResponse { std::vector value; }; -enum ProfileConnectionState { - STATE_DISCONNECTED = 0, // the current profile is disconnected - STATE_CONNECTING = 1, // the current profile is being connected - STATE_CONNECTED = 2, // the current profile is connected - STATE_DISCONNECTING = 3 // the current profile is being disconnected -}; - enum ScoState { SCO_DISCONNECTED, SCO_CONNECTING, diff --git a/interfaces/inner_api/include/bluetooth_def.h b/interfaces/inner_api/include/bluetooth_def.h index f832e376..01be242f 100644 --- a/interfaces/inner_api/include/bluetooth_def.h +++ b/interfaces/inner_api/include/bluetooth_def.h @@ -1680,6 +1680,13 @@ enum class RandomDeviceIdCommand { IS_VALID }; +enum ProfileConnectionState { + STATE_DISCONNECTED = 0, // the current profile is disconnected + STATE_CONNECTING = 1, // the current profile is being connected + STATE_CONNECTED = 2, // the current profile is connected + STATE_DISCONNECTING = 3 // the current profile is being disconnected +}; + #ifdef BLUETOOTH_EXPORT #define BLUETOOTH_API __attribute__((visibility("default"))) #else -- Gitee From d408bed8af0785801c111b1d694f9095191701a9 Mon Sep 17 00:00:00 2001 From: guoxiadi Date: Wed, 21 May 2025 10:15:11 +0800 Subject: [PATCH 45/45] bluetooth fwk taihe Signed-off-by: guoxiadi --- bundle.json | 13 +- frameworks/ets/taihe/bluetooth_a2dp/BUILD.gn | 93 +++++ .../idl/ohos.bluetooth.a2dp.taihe | 25 ++ .../bluetooth_a2dp/src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.a2dp.impl.cpp | 34 ++ .../ets/taihe/bluetooth_access/BUILD.gn | 92 +++++ .../idl/ohos.bluetooth.access.taihe | 44 +++ .../bluetooth_access/src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.access.impl.cpp | 59 ++++ .../ets/taihe/bluetooth_baseProfile/BUILD.gn | 92 +++++ .../idl/ohos.bluetooth.baseProfile.taihe | 41 +++ .../src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.baseProfile.impl.cpp | 26 ++ frameworks/ets/taihe/bluetooth_ble/BUILD.gn | 93 +++++ .../idl/ohos.bluetooth.ble.taihe | 330 ++++++++++++++++++ .../taihe_bluetooth_ble_advertise_callback.h | 32 ++ .../bluetooth_ble/src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.ble.impl.cpp | 268 ++++++++++++++ ...taihe_bluetooth_ble_advertise_callback.cpp | 19 + .../ets/taihe/bluetooth_connection/BUILD.gn | 102 ++++++ .../idl/ohos.bluetooth.connection.taihe | 168 +++++++++ .../src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.connection.impl.cpp | 181 ++++++++++ .../ets/taihe/bluetooth_constant/BUILD.gn | 87 +++++ .../idl/ohos.bluetooth.constant.taihe | 129 +++++++ .../src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.constant.impl.cpp | 15 + frameworks/ets/taihe/bluetooth_hfp/BUILD.gn | 93 +++++ .../idl/ohos.bluetooth.hfp.taihe | 21 ++ .../bluetooth_hfp/src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.hfp.impl.cpp | 33 ++ frameworks/ets/taihe/bluetooth_hid/BUILD.gn | 93 +++++ .../idl/ohos.bluetooth.hid.taihe | 20 ++ .../bluetooth_hid/src/ani_constructor.cpp | 13 + .../src/ohos.bluetooth.hid.impl.cpp | 33 ++ 35 files changed, 2338 insertions(+), 2 deletions(-) create mode 100644 frameworks/ets/taihe/bluetooth_a2dp/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_a2dp/idl/ohos.bluetooth.a2dp.taihe create mode 100644 frameworks/ets/taihe/bluetooth_a2dp/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_a2dp/src/ohos.bluetooth.a2dp.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_access/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_access/idl/ohos.bluetooth.access.taihe create mode 100644 frameworks/ets/taihe/bluetooth_access/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_access/src/ohos.bluetooth.access.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_baseProfile/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_baseProfile/idl/ohos.bluetooth.baseProfile.taihe create mode 100644 frameworks/ets/taihe/bluetooth_baseProfile/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_baseProfile/src/ohos.bluetooth.baseProfile.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_ble/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_ble/idl/ohos.bluetooth.ble.taihe create mode 100644 frameworks/ets/taihe/bluetooth_ble/include/taihe_bluetooth_ble_advertise_callback.h create mode 100644 frameworks/ets/taihe/bluetooth_ble/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_ble/src/ohos.bluetooth.ble.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_ble/src/taihe_bluetooth_ble_advertise_callback.cpp create mode 100644 frameworks/ets/taihe/bluetooth_connection/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_connection/idl/ohos.bluetooth.connection.taihe create mode 100644 frameworks/ets/taihe/bluetooth_connection/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_connection/src/ohos.bluetooth.connection.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_constant/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_constant/idl/ohos.bluetooth.constant.taihe create mode 100644 frameworks/ets/taihe/bluetooth_constant/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_constant/src/ohos.bluetooth.constant.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_hfp/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_hfp/idl/ohos.bluetooth.hfp.taihe create mode 100644 frameworks/ets/taihe/bluetooth_hfp/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_hfp/src/ohos.bluetooth.hfp.impl.cpp create mode 100644 frameworks/ets/taihe/bluetooth_hid/BUILD.gn create mode 100644 frameworks/ets/taihe/bluetooth_hid/idl/ohos.bluetooth.hid.taihe create mode 100644 frameworks/ets/taihe/bluetooth_hid/src/ani_constructor.cpp create mode 100644 frameworks/ets/taihe/bluetooth_hid/src/ohos.bluetooth.hid.impl.cpp diff --git a/bundle.json b/bundle.json index f6b8e5b9..7e504e49 100644 --- a/bundle.json +++ b/bundle.json @@ -70,7 +70,8 @@ "libuv", "napi", "samgr", - "resource_schedule_service" + "resource_schedule_service", + "runtime_core" ], "third_party": [] }, @@ -82,7 +83,15 @@ "//foundation/communication/bluetooth/frameworks/inner:btcommon", "//foundation/communication/bluetooth/frameworks/js/napi:bluetooth_napi", "//foundation/communication/bluetooth/frameworks/c_api:bluetooth_ndk", - "//foundation/communication/bluetooth/frameworks/cj:bluetooth_ffi" + "//foundation/communication/bluetooth/frameworks/cj:bluetooth_ffi", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_a2dp:bluetoothA2dp_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_access:bluetoothAccess_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_baseProfile:bluetoothBaseProfile_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_ble:bluetoothBle_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_connection:bluetoothConnection_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_constant:bluetoothConstant_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_hfp:bluetoothHfp_taihe", + "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_hid:bluetoothHid_taihe" ], "service_group": [ ] diff --git a/frameworks/ets/taihe/bluetooth_a2dp/BUILD.gn b/frameworks/ets/taihe/bluetooth_a2dp/BUILD.gn new file mode 100644 index 00000000..0e99c3f2 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_a2dp/BUILD.gn @@ -0,0 +1,93 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_a2dp_taihe") { + sources = [ + "idl/ohos.bluetooth.a2dp.taihe", + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_baseProfile:bluetooth_baseProfile_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_a2dp_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.a2dp.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.a2dp.abi.c", + ] +} + +taihe_shared_library("bluetoothA2dp_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.a2dp.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + "../bluetooth_baseProfile:bluetoothBaseProfile_taihe_native" + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothA2dp_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.a2dp.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothA2dp_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothA2dp_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothA2dp_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothA2dp_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothA2dp_taihe") { + deps = [ + ":bluetoothA2dp_etc", + ":bluetoothA2dp_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_a2dp/idl/ohos.bluetooth.a2dp.taihe b/frameworks/ets/taihe/bluetooth_a2dp/idl/ohos.bluetooth.a2dp.taihe new file mode 100644 index 00000000..704e6fae --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_a2dp/idl/ohos.bluetooth.a2dp.taihe @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.a2dp", "a2dp") +@!sts_inject(""" +static { loadLibrary("bluetoothA2dp_taihe_native.z") } +""") + +from ohos.bluetooth.baseProfile use BaseProfile; +interface A2dpSourceProfile : BaseProfile { +} + +function createA2dpSrcProfile(): A2dpSourceProfile; diff --git a/frameworks/ets/taihe/bluetooth_a2dp/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_a2dp/src/ani_constructor.cpp new file mode 100644 index 00000000..feee0f11 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_a2dp/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.a2dp.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::a2dp::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::a2dp::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_a2dp/src/ohos.bluetooth.a2dp.impl.cpp b/frameworks/ets/taihe/bluetooth_a2dp/src/ohos.bluetooth.a2dp.impl.cpp new file mode 100644 index 00000000..4236ab69 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_a2dp/src/ohos.bluetooth.a2dp.impl.cpp @@ -0,0 +1,34 @@ +#include "ohos.bluetooth.a2dp.proj.hpp" +#include "ohos.bluetooth.a2dp.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" + +using namespace taihe; +using namespace ohos::bluetooth::a2dp; +using namespace ohos::bluetooth::baseProfile; + +namespace { +// To be implemented. + +class A2dpSourceProfileImpl { +public: + A2dpSourceProfileImpl() { + // Don't forget to implement the constructor. + } + + void onConnectionStateChange(callback_view callback) { + std::cout<< "onConnectionStateChange" << std::endl; + } +}; + +A2dpSourceProfile createA2dpSrcProfile() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_createA2dpSrcProfile(createA2dpSrcProfile); +// NOLINTEND diff --git a/frameworks/ets/taihe/bluetooth_access/BUILD.gn b/frameworks/ets/taihe/bluetooth_access/BUILD.gn new file mode 100644 index 00000000..3a70a617 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_access/BUILD.gn @@ -0,0 +1,92 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_access_taihe") { + sources = [ + "idl/ohos.bluetooth.access.taihe" + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_baseProfile:bluetooth_baseProfile_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_access_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.access.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.access.abi.c", + ] +} + +taihe_shared_library("bluetoothAccess_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.access.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothAccess_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.access.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothAccess_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothAccess_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothAccess_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothAccess_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothAccess_taihe") { + deps = [ + ":bluetoothAccess_etc", + ":bluetoothAccess_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_access/idl/ohos.bluetooth.access.taihe b/frameworks/ets/taihe/bluetooth_access/idl/ohos.bluetooth.access.taihe new file mode 100644 index 00000000..b6b30040 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_access/idl/ohos.bluetooth.access.taihe @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.access", "access") +@!sts_inject(""" +static { loadLibrary("bluetoothAccess_taihe_native.z") } +""") + +from ohos.bluetooth.baseProfile use BaseProfile; + +enum BluetoothState: i32{ + STATE_OFF = 0, + STATE_TURNING_ON = 1, + STATE_ON = 2, + STATE_TURNING_OFF = 3, + STATE_BLE_TURNING_ON = 4, + STATE_BLE_ON = 5, + STATE_BLE_TURNING_OFF = 6 +} + +@on_off("stateChange") +function onStateChange(callback: (a: BluetoothState) => void): void; +@on_off("stateChange") +function offStateChange(callback:Optional<(a: BluetoothState)=> void>): void; + +@gen_promise("restrictBluetooth") +function restrictBluetoothSync(): void; + +function getState(): BluetoothState; + +function enableBluetooth(): void; +function disableBluetooth(): void; \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_access/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_access/src/ani_constructor.cpp new file mode 100644 index 00000000..0b9eb630 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_access/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.access.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::access::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::access::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_access/src/ohos.bluetooth.access.impl.cpp b/frameworks/ets/taihe/bluetooth_access/src/ohos.bluetooth.access.impl.cpp new file mode 100644 index 00000000..49acd1e4 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_access/src/ohos.bluetooth.access.impl.cpp @@ -0,0 +1,59 @@ +#include "ohos.bluetooth.access.proj.hpp" +#include "ohos.bluetooth.access.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" +#include "bluetooth_remote_device.h" +#include "bluetooth_host.h" +#include "bluetooth_log.h" +#include "bluetooth_errorcode.h" + +using namespace taihe; +using namespace ohos::bluetooth::access; +using namespace OHOS::Bluetooth; + +namespace { +// To be implemented. + +void onStateChange(callback_view callback) { + std::cout<< "onStateChange" << std::endl; +} + +void offStateChange(optional_view> callback) { + std::cout<< "onStateChange" << std::endl; +} + +void restrictBluetoothSync() { + std::cout<< "restrictBluetoothSync" << std::endl; +} + +::ohos::bluetooth::access::BluetoothState getState() { + int32_t state = static_cast(BluetoothHost::GetDefaultHost().GetBluetoothState()); + return {static_cast<::ohos::bluetooth::access::BluetoothState::key_t>(state)}; +} + +void enableBluetooth() { + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + int32_t ret = host->EnableBle(); + if (ret != BT_NO_ERROR) { + std::cerr<< "enableBluetooth failed." << std::endl; + } +} + +void disableBluetooth() { + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + int ret = host->DisableBt(); + if (ret != BT_NO_ERROR) { + std::cerr<< "disableBluetooth failed." << std::endl; + } +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_onStateChange(onStateChange); +TH_EXPORT_CPP_API_offStateChange(offStateChange); +TH_EXPORT_CPP_API_restrictBluetoothSync(restrictBluetoothSync); +TH_EXPORT_CPP_API_getState(getState); +TH_EXPORT_CPP_API_enableBluetooth(enableBluetooth); +TH_EXPORT_CPP_API_disableBluetooth(disableBluetooth); +// NOLINTEND diff --git a/frameworks/ets/taihe/bluetooth_baseProfile/BUILD.gn b/frameworks/ets/taihe/bluetooth_baseProfile/BUILD.gn new file mode 100644 index 00000000..8864be86 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_baseProfile/BUILD.gn @@ -0,0 +1,92 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_baseProfile_taihe") { + sources = [ + "idl/ohos.bluetooth.baseProfile.taihe", + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_constant:bluetooth_constant_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_baseProfile_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.baseProfile.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.baseProfile.abi.c", + ] +} + +taihe_shared_library("bluetoothBaseProfile_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.baseProfile.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothBaseProfile_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.baseProfile.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothBaseProfile_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothBaseProfile_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothBaseProfile_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothBaseProfile_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothBaseProfile_taihe") { + deps = [ + ":bluetoothBaseProfile_etc", + ":bluetoothBaseProfile_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_baseProfile/idl/ohos.bluetooth.baseProfile.taihe b/frameworks/ets/taihe/bluetooth_baseProfile/idl/ohos.bluetooth.baseProfile.taihe new file mode 100644 index 00000000..e080422d --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_baseProfile/idl/ohos.bluetooth.baseProfile.taihe @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.baseProfile", "baseProfile") +@!sts_inject(""" +static { loadLibrary("bluetoothBaseProfile_taihe_native.z") } +""") + +from ohos.bluetooth.constant use ProfileConnectionState; + +struct StateChangeParam { + deviceId: String; + state: ProfileConnectionState; + cause: DisconnectCause; +} + +enum DisconnectCause: i32{ + USER_DISCONNECT = 0, + CONNECT_FROM_KEYBOARD = 1, + CONNECT_FROM_MOUSE = 2, + CONNECT_FROM_CAR = 3, + TOO_MANY_CONNECTED_DEVICES = 4, + CONNECT_FAIL_INTERNAL = 5 +} + +interface BaseProfile { + @on_off("connectionStateChange") + onConnectionStateChange(callback: (a: StateChangeParam) => void): void; +} diff --git a/frameworks/ets/taihe/bluetooth_baseProfile/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_baseProfile/src/ani_constructor.cpp new file mode 100644 index 00000000..34dd86a5 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_baseProfile/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.baseProfile.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::baseProfile::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::baseProfile::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_baseProfile/src/ohos.bluetooth.baseProfile.impl.cpp b/frameworks/ets/taihe/bluetooth_baseProfile/src/ohos.bluetooth.baseProfile.impl.cpp new file mode 100644 index 00000000..2a7e8ab4 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_baseProfile/src/ohos.bluetooth.baseProfile.impl.cpp @@ -0,0 +1,26 @@ +#include "ohos.bluetooth.baseProfile.proj.hpp" +#include "ohos.bluetooth.baseProfile.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" + +using namespace taihe; +using namespace ohos::bluetooth::baseProfile; + +namespace { +// To be implemented. + +class BaseProfileImpl { +public: + BaseProfileImpl() { + // Don't forget to implement the constructor. + } + + void onConnectionStateChange(callback_view callback) { + std::cout<< "onConnectionStateChange" << std::endl; + } +}; +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +// NOLINTEND diff --git a/frameworks/ets/taihe/bluetooth_ble/BUILD.gn b/frameworks/ets/taihe/bluetooth_ble/BUILD.gn new file mode 100644 index 00000000..0401e622 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_ble/BUILD.gn @@ -0,0 +1,93 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_ble_taihe") { + sources = [ + "idl/ohos.bluetooth.ble.taihe", + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_constant:bluetooth_constant_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_ble_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.ble.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.ble.abi.c", + ] +} + +taihe_shared_library("bluetoothBle_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include", + "src/taihe_bluetooth_ble_advertise_callback.cpp" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.ble.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothBle_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.ble.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothBle_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothBle_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothBle_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothBle_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothBle_taihe") { + deps = [ + ":bluetoothBle_etc", + ":bluetoothBle_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_ble/idl/ohos.bluetooth.ble.taihe b/frameworks/ets/taihe/bluetooth_ble/idl/ohos.bluetooth.ble.taihe new file mode 100644 index 00000000..4580e24f --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_ble/idl/ohos.bluetooth.ble.taihe @@ -0,0 +1,330 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.ble", "ble") +@!sts_inject(""" +static { loadLibrary("bluetoothBle_taihe_native.z") } +""") +from ohos.bluetooth.constant use ProfileConnectionState; + +struct ScanReport { + reportType: ScanReportType; + scanResult: Array; +} +enum ScanReportType: i32{ + ON_FOUND = 1, + ON_LOST = 2, +} +struct ScanResult { + deviceId: String; + rssi: i32; + data: @arraybuffer Array; + deviceName: String; + connectable: bool; +} +@on_off("BLEDeviceFind") +function onBLEDeviceFind(callback: (a: ScanReport) => void): void; +@on_off("BLEDeviceFind") +function offBLEDeviceFind(callback:Optional<(a: ScanReport)=> void>): void; + +@on_off("advertisingStateChange") +function onAdvertisingStateChange(callback: (a: AdvertisingStateChangeInfo) => void): void; +@on_off("advertisingStateChange") +function offAdvertisingStateChange(callback:Optional<(a: AdvertisingStateChangeInfo)=> void>): void; + + +enum MatchMode: i32{ + MATCH_MODE_AGGRESSIVE = 1, + MATCH_MODE_STICKY = 2 +} + +struct AdvertisingEnableParams { + advertisingId: i32; + duration: Optional; +} + + +struct DescriptorWriteRequest { + deviceId: String; + transId: i32; + offset: i32; + isPrepared: bool; + needRsp: bool; + value: @arraybuffer Array; + descriptorUuid: String; + characteristicUuid: String; + serviceUuid: String; +} + +struct DescriptorReadRequest { + deviceId: String; + transId: i32; + offset: i32; + descriptorUuid: String; + characteristicUuid: String; + serviceUuid: String; +} + +struct AdvertiseSetting { + interval: Optional; + txPower: Optional; + connectable: Optional; +} + +struct NotifyCharacteristic { + serviceUuid: String; + characteristicUuid: String; + characteristicValue: @arraybuffer Array; + confirm: bool; +} + +struct ScanFilter { + deviceId: Optional; + name: Optional; + serviceUuid: Optional; + serviceUuidMask: Optional; + serviceSolicitationUuid: Optional; + serviceSolicitationUuidMask: Optional; + serviceData: Optional<@arraybuffer Array>; + serviceDataMask: Optional<@arraybuffer Array>; + manufactureId: Optional; + manufactureData: Optional<@arraybuffer Array>; + manufactureDataMask: Optional<@arraybuffer Array>; +} + +struct CharacteristicReadRequest { + deviceId: String; + transId: i32; + offset: i32; + characteristicUuid: String; + serviceUuid: String; +} + +struct CharacteristicWriteRequest { + deviceId: String; + transId: i32; + offset: i32; + isPrepared: bool; + needRsp: bool; + value: @arraybuffer Array; + characteristicUuid: String; + serviceUuid: String; +} + + +function createGattClientDevice(deviceId: String): GattClientDevice; + +function stopBLEScan(): void; + +struct ServerResponse { + deviceId: String; + transId: i32; + status: i32; + offset: i32; + value: @arraybuffer Array; +} + +struct ScanOptions { + interval: Optional; + dutyMode: Optional; + matchMode: Optional; + phyType: Optional; + reportMode: Optional; +} + +enum ScanDuty: i32{ + SCAN_MODE_LOW_POWER = 0, + SCAN_MODE_BALANCED = 1, + SCAN_MODE_LOW_LATENCY = 2 +} + +enum PhyType: i32{ + PHY_LE_1M = 1, + PHY_LE_ALL_SUPPORTED = 255 +} + +enum ScanReportMode: i32{ + NORMAL = 1, + FENCE_SENSITIVITY_LOW = 10, + FENCE_SENSITIVITY_HIGH = 11, +} + +struct BLECharacteristic { + serviceUuid: String; + characteristicUuid: String; + characteristicValue: @arraybuffer Array; + descriptors: Array; + properties: Optional; + characteristicValueHandle: Optional; +} + +struct AdvertisingStateChangeInfo { + advertisingId: i32; + state: AdvertisingState; +} + +enum AdvertisingState: i32{ + STARTED = 1, + ENABLED = 2, + DISABLED = 3, + STOPPED = 4 +} + +struct BLEDescriptor { + serviceUuid: String; + characteristicUuid: String; + descriptorUuid: String; + descriptorValue: @arraybuffer Array; + descriptorHandle: Optional; +} + +struct GattProperties { + write: Optional; + writeNoResponse: Optional; + read: Optional; + notify: Optional; + indicate: Optional; +} + +enum GattWriteType: i32{ + WRITE = 1, + WRITE_NO_RESPONSE = 2 +} + +function stopAdvertising(): void; + +@gen_async("stopAdvertising") +@gen_promise("stopAdvertising") +function stopAdvertisingSync(advertisingId: f64): void; + +interface GattClientDevice { + @on_off("BLECharacteristicChange") + onBLECharacteristicChange(callback: (a: BLECharacteristic) => void): void; + @on_off("BLECharacteristicChange") + offBLECharacteristicChange(callback:Optional<(a: BLECharacteristic)=> void>): void; + + @gen_async("setCharacteristicChangeNotification") + @gen_promise("setCharacteristicChangeNotification") + setCharacteristicChangeNotificationSync(characteristic: BLECharacteristic, enable: bool): void; + + @gen_async("getRssiValue") + @gen_promise("getRssiValue") + getRssiValueSync(): f64; + + @gen_async("writeCharacteristicValue") + @gen_promise("writeCharacteristicValue") + writeCharacteristicValueSync(characteristic: BLECharacteristic, writeType: GattWriteType): void; + + @gen_async("getServices") + @gen_promise("getServices") + getServicesSync(): void; + + @gen_async("writeDescriptorValue") + @gen_promise("writeDescriptorValue") + writeDescriptorValueSync(descriptor: BLEDescriptor): void; + + @on_off("BLEMtuChange") + onBLEMtuChange(callback: (a: i32) => void): void; + @on_off("BLEMtuChange") + offBLEMtuChange(callback:Optional<(a: i32)=> void>): void; + + @on_off("BLEConnectionStateChange") + onBLEConnectionStateChange(callback: (a: BLEConnectionChangeState) => void): void; + @on_off("BLEConnectionStateChange") + offBLEConnectionStateChange(callback:Optional<(a: BLEConnectionChangeState)=> void>): void; + + setBLEMtuSize(mtu: f64): void; + connect(): void; + disconnect(): void; + + close(): void; +} + +function createGattServer(): GattServer; + +interface GattServer { + @on_off("characteristicRead") + onCharacteristicRead(callback: (a: CharacteristicReadRequest) => void): void; + @on_off("characteristicRead") + offCharacteristicRead(callback:Optional<(a: CharacteristicReadRequest)=> void>): void; + + @on_off("BLEMtuChange") + onBLEMtuChange(callback: (a: i32) => void): void; + @on_off("BLEMtuChange") + offBLEMtuChange(callback:Optional<(a: i32)=> void>): void; + + @on_off("descriptorRead") + onDescriptorRead(callback: (a: DescriptorReadRequest) => void): void; + @on_off("descriptorRead") + offDescriptorRead(callback:Optional<(a: DescriptorReadRequest)=> void>): void; + + @on_off("descriptorWrite") + onDescriptorWrite(callback: (a: DescriptorWriteRequest) => void): void; + @on_off("descriptorWrite") + offDescriptorWrite(callback:Optional<(a: DescriptorWriteRequest)=> void>): void; + + @on_off("connectionStateChange") + onConnectionStateChange(callback: (a: BLEConnectionChangeState) => void): void; + @on_off("connectionStateChange") + offConnectionStateChange(callback:Optional<(a: BLEConnectionChangeState)=> void>): void; + + close(): void; +} + +struct AdvertiseData { + serviceUuids: Array; + manufactureData: Array; + serviceData: Array; + includeDeviceName: Optional; + includeTxPower: Optional; +} + +struct AdvertisingParams { + advertisingSettings: AdvertiseSetting; + advertisingData: AdvertiseData; + advertisingResponse: Optional; + duration: Optional; +} +struct ManufactureData { + manufactureId: i16; + manufactureValue: @arraybuffer Array; +} + +struct ServiceData { + serviceUuid: String; + serviceValue: @arraybuffer Array; +} + +struct GattService { + serviceUuid: String; + isPrimary: bool; + characteristics: Array; + includeServices: Optional>; +} + +struct BLEConnectionChangeState { + deviceId: String; + state: ProfileConnectionState; +} + +function createBleScanner(): BleScanner; + +interface BleScanner { + @on_off("BLEDeviceFind") + onBLEDeviceFind(callback: (a: ScanReport) => void): void; + @on_off("BLEDeviceFind") + offBLEDeviceFind(callback:Optional<(a: ScanReport)=> void>): void; +} + diff --git a/frameworks/ets/taihe/bluetooth_ble/include/taihe_bluetooth_ble_advertise_callback.h b/frameworks/ets/taihe/bluetooth_ble/include/taihe_bluetooth_ble_advertise_callback.h new file mode 100644 index 00000000..fd1f3383 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_ble/include/taihe_bluetooth_ble_advertise_callback.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2021 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 TAIHE_BLUETOOTH_BLE_ADVERTISE_CALLBACK_H +#define TAIHE_BLUETOOTH_BLE_ADVERTISE_CALLBACK_H + +#include "bluetooth_ble_advertiser.h" + +namespace OHOS { +namespace Bluetooth { +class TaiheBluetoothBleAdvertiseCallback : public BleAdvertiseCallback { +public: + TaiheBluetoothBleAdvertiseCallback(); + ~TaiheBluetoothBleAdvertiseCallback() override = default; + + static std::shared_ptr GetInstance(void); +}; +} // namespace Bluetooth +} // namespace OHOS +#endif // TAIHE_BLUETOOTH_BLE_ADVERTISE_CALLBACK_H diff --git a/frameworks/ets/taihe/bluetooth_ble/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_ble/src/ani_constructor.cpp new file mode 100644 index 00000000..18960115 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_ble/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.ble.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::ble::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::ble::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_ble/src/ohos.bluetooth.ble.impl.cpp b/frameworks/ets/taihe/bluetooth_ble/src/ohos.bluetooth.ble.impl.cpp new file mode 100644 index 00000000..71a7fd7e --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_ble/src/ohos.bluetooth.ble.impl.cpp @@ -0,0 +1,268 @@ +#include "ohos.bluetooth.ble.proj.hpp" +#include "ohos.bluetooth.ble.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" +#include "bluetooth_ble_advertiser.h" +#include "bluetooth_ble_central_manager.h" +#include "bluetooth_errorcode.h" +#include "bluetooth_utils.h" +#include "taihe_bluetooth_ble_advertise_callback.h" +// #include "taihe_bluetooth_gatt_client.h" + +using namespace taihe; +using namespace ohos::bluetooth::ble; +using namespace OHOS::Bluetooth; + + +namespace { +// To be implemented. +std::shared_ptr BleAdvertiserGetInstance(void) +{ + static auto instance = BleAdvertiser::CreateInstance(); + return instance; +} + +class GattClientDeviceImpl { +private: + // std::shared_ptr client_ = nullptr; + // std::shared_ptr callback_; + // std::shared_ptr device_ = nullptr; + +public: + // GattClientDeviceImpl(std::string &deviceId) { + // device_ = std::make_shared(deviceId, 1); + // client_ = std::make_shared(*device_); + // client_->Init(); + // callback_ = std::make_shared(); + // callback_->deviceAddr_ = deviceId; + // } + + // ~GattClientDeviceImpl() = default; + + void onBLECharacteristicChange(callback_view callback) { + std::cout<< "onBLECharacteristicChange" << std::endl; + } + + void offBLECharacteristicChange(optional_view> callback) { + std::cout<< "offBLECharacteristicChange" << std::endl; + } + + void setCharacteristicChangeNotificationSync(BLECharacteristic const& characteristic, bool enable) { + std::cout<< "setCharacteristicChangeNotificationSync" << std::endl; + + } + + int64_t getRssiValueSync() { + std::cout<< "getRssiValueSync" << std::endl; + return 1; + } + + void writeCharacteristicValueSync(BLECharacteristic const& characteristic, GattWriteType writeType) { + std::cout<< "writeCharacteristicValueSync" << std::endl; + } + + void getServicesSync() { + std::cout<< "getServicesSync" << std::endl; + } + + void writeDescriptorValueSync(BLEDescriptor const& descriptor) { + std::cout<< "writeDescriptorValueSync" << std::endl; + } + + void onBLEMtuChange(callback_view callback) { + std::cout<< "onBLEMtuChange" << std::endl; + } + + void offBLEMtuChange(optional_view> callback) { + std::cout<< "offBLEMtuChange" << std::endl; + } + + void onBLEConnectionStateChange(callback_view callback) { + std::cout<< "onBLEConnectionStateChange" << std::endl; + } + + void offBLEConnectionStateChange(optional_view> callback) { + std::cout<< "offBLEConnectionStateChange" << std::endl; + } + + void setBLEMtuSize(int32_t mtu) { + std::cout<< "setBLEMtuSize" << std::endl; + // NapiGattClient* gattClient = nullptr; + // int32_t mtuSize = 0; + + // auto status = CheckSetBLEMtuSize(env, info, mtuSize, &gattClient); + // NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); + + // std::shared_ptr client = gattClient->GetClient(); + // NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); + // if (client == nullptr) { + // std::cerr<< "client is null." << std::endl; + // } + + // int ret = client->RequestBleMtuSize(mtuSize); + // if (ret != BT_NO_ERROR) { + // std::cerr<< "setBLEMtuSize failed." << std::endl; + // } + // return NapiGetBooleanTrue(env); + } + + void connect() { + std::cout<< "connect" << std::endl; + } + + void disconnect() { + std::cout<< "disconnect" << std::endl; + } + + void close() { + std::cout<< "close GattClientDevice" << std::endl; + } +}; + +class GattServerImpl { +public: + GattServerImpl() { + // Don't forget to implement the constructor. + } + + void onCharacteristicRead(callback_view callback) { + std::cout<< "onCharacteristicRead GattServer" << std::endl; + } + + void offCharacteristicRead(optional_view> callback) { + std::cout<< "onCharacteristicRead GattServer" << std::endl; + } + + void onBLEMtuChange(callback_view callback) { + std::cout<< "onBLEMtuChange GattServer" << std::endl; + } + + void offBLEMtuChange(optional_view> callback) { + std::cout<< "offBLEMtuChange GattServer" << std::endl; + } + + void onDescriptorRead(callback_view callback) { + std::cout<< "onDescriptorRead GattServer" << std::endl; + } + + void offDescriptorRead(optional_view> callback) { + std::cout<< "offDescriptorRead GattServer" << std::endl; + } + + void onDescriptorWrite(callback_view callback) { + std::cout<< "onDescriptorWrite GattServer" << std::endl; + } + + void offDescriptorWrite(optional_view> callback) { + std::cout<< "offDescriptorWrite GattServer" << std::endl; + } + + void onConnectionStateChange(callback_view callback) { + std::cout<< "onConnectionStateChange GattServer" << std::endl; + } + + void offConnectionStateChange(optional_view> callback) { + std::cout<< "offConnectionStateChange GattServer" << std::endl; + } + + void close() { + std::cout<< "close GattServer" << std::endl; + } +}; + +class BleScannerImpl { +public: + BleScannerImpl() { + // Don't forget to implement the constructor. + } + + void onBLEDeviceFind(callback_view callback) { + std::cout<< "BleScanner onBLEDeviceFind" << std::endl; + } + + void offBLEDeviceFind(optional_view> callback) { + std::cout<< "BleScanner offBLEDeviceFind" << std::endl; + } +}; + +void onBLEDeviceFind(callback_view callback) { + std::cout<< "onBLEDeviceFind" << std::endl; +} + +void offBLEDeviceFind(optional_view> callback) { + std::cout<< "offBLEDeviceFind" << std::endl; +} + +void onAdvertisingStateChange(callback_view callback) { + std::cout<< "onAdvertisingStateChange" << std::endl; +} + +void offAdvertisingStateChange(optional_view> callback) { + std::cout<< "offAdvertisingStateChange" << std::endl; +} + +void stopAdvertising() { + std::cout<< "stopAdvertising" << std::endl; + std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); + // std::vector> callbacks = bleAdvertiser->GetAdvObservers(); + // if (callbacks.empty()) { + std::shared_ptr callback = nullptr; + int ret = bleAdvertiser->StopAdvertising(callback); + // int ret = bleAdvertiser->StopAdvertising(TaiheBluetoothBleAdvertiseCallback::GetInstance()); + if (ret != BT_NO_ERROR) { + std::cerr<< "stopAdvertising failed." << std::endl; + } +} + + +void stopAdvertisingSync(uint32_t advertisingId) { + std::shared_ptr bleAdvertiser = BleAdvertiserGetInstance(); + // std::shared_ptr baseCallback; + // std::shared_ptr callback = + // std::static_pointer_cast(baseCallback); + // // auto func = [bleAdvertiser, callback]() { + // int ret = bleAdvertiser->StopAdvertising(callback); + // if (ret != BT_NO_ERROR) { + // std::cerr<< "stopAdvertising failed." << std::endl; + // } + // return NapiAsyncWorkRet(ret); + // }; +} + +void stopBLEScan() { + std::cout<< "stopBLEScan" << std::endl; +} + +GattClientDevice createGattClientDevice(string_view deviceId) { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} + +GattServer createGattServer() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} + +BleScanner createBleScanner() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_onBLEDeviceFind(onBLEDeviceFind); +TH_EXPORT_CPP_API_offBLEDeviceFind(offBLEDeviceFind); +TH_EXPORT_CPP_API_onAdvertisingStateChange(onAdvertisingStateChange); +TH_EXPORT_CPP_API_offAdvertisingStateChange(offAdvertisingStateChange); +TH_EXPORT_CPP_API_createGattClientDevice(createGattClientDevice); +TH_EXPORT_CPP_API_createGattServer(createGattServer); +TH_EXPORT_CPP_API_createBleScanner(createBleScanner); +TH_EXPORT_CPP_API_stopAdvertising(stopAdvertising); +TH_EXPORT_CPP_API_stopAdvertisingSync(stopAdvertisingSync); +TH_EXPORT_CPP_API_stopBLEScan(stopBLEScan); +// NOLINTEND + diff --git a/frameworks/ets/taihe/bluetooth_ble/src/taihe_bluetooth_ble_advertise_callback.cpp b/frameworks/ets/taihe/bluetooth_ble/src/taihe_bluetooth_ble_advertise_callback.cpp new file mode 100644 index 00000000..53054f4a --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_ble/src/taihe_bluetooth_ble_advertise_callback.cpp @@ -0,0 +1,19 @@ +#ifndef TAIHE_BLUETOOTH_BLE_ADVERTISE_CALLBACK_H +#define TAIHE_BLUETOOTH_BLE_ADVERTISE_CALLBACK_H + +#include "taihe_bluetooth_ble_advertise_callback.h" + +namespace OHOS { +namespace Bluetooth { +TaiheBluetoothBleAdvertiseCallback::TaiheBluetoothBleAdvertiseCallback() +{} + +std::shared_ptr TaiheBluetoothBleAdvertiseCallback::GetInstance(void) +{ + static std::shared_ptr instance = + std::make_shared(); + return instance; +} +} // namespace Bluetooth +} // namespace OHOS +#endif // TAIHE_BLUETOOTH_BLE_ADVERTISE_CALLBACK_H \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_connection/BUILD.gn b/frameworks/ets/taihe/bluetooth_connection/BUILD.gn new file mode 100644 index 00000000..a5a728c4 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_connection/BUILD.gn @@ -0,0 +1,102 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_connection_taihe") { + sources = [ + "idl/ohos.bluetooth.connection.taihe" + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_constant:bluetooth_constant_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_connection_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.connection.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.connection.abi.c", + ] +} + +taihe_shared_library("bluetoothConnection_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.connection.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothConnection_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.connection.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothConnection_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothConnection_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothConnection_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothConnection_abc" ] #拷贝abc依赖编译abc +} + +generate_static_abc("main") { #调用generate_static_abc编译abc + base_url = "//foundation/communication/bluetooth/frameworks/ets/taihe/bluetooth_connection/test" #base_url直接设置为taihe_generated_file_path + files = [ "$base_url/main.ets" ] + #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/main" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} + +group("bluetoothConnection_taihe") { + deps = [ + ":bluetoothConnection_etc", + ":bluetoothConnection_taihe_native", + ":main" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_connection/idl/ohos.bluetooth.connection.taihe b/frameworks/ets/taihe/bluetooth_connection/idl/ohos.bluetooth.connection.taihe new file mode 100644 index 00000000..91f417ad --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_connection/idl/ohos.bluetooth.connection.taihe @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.connection", "connection") +@!sts_inject(""" +static { loadLibrary("bluetoothConnection_taihe_native.z") } +""") +from ohos.bluetooth.constant use MajorClass, MajorMinorClass; + +enum BluetoothTransport: i32 { + TRANSPORT_BR_EDR = 0, + TRANSPORT_LE = 1 +} + +enum ScanMode: i32 { + SCAN_MODE_NONE = 0, + SCAN_MODE_CONNECTABLE = 1, + SCAN_MODE_GENERAL_DISCOVERABLE = 2, + SCAN_MODE_LIMITED_DISCOVERABLE = 3, + SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE = 4, + SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE = 5 +} + +struct DeviceClass { + majorClass: MajorClass; + majorMinorClass: MajorMinorClass; + classOfDevice: i32; +} + +struct DiscoveryResult { + deviceId: String; + rssi: i32; + deviceName: String; + deviceClass: DeviceClass; +} + +struct PinRequiredParam { + deviceId: String; + pinCode: String; + pinType: PinType; +} + +enum PinType: i32{ + PIN_TYPE_ENTER_PIN_CODE = 0, + PIN_TYPE_ENTER_PASSKEY = 1, + PIN_TYPE_CONFIRM_PASSKEY = 2, + PIN_TYPE_NO_PASSKEY_CONSENT = 3, + PIN_TYPE_NOTIFY_PASSKEY = 4, + PIN_TYPE_DISPLAY_PIN_CODE = 5, + PIN_TYPE_OOB_CONSENT = 6, + PIN_TYPE_PIN_16_DIGITS = 7 +} + +struct BatteryInfo { + deviceId: String; + batteryLevel: i32; + leftEarBatteryLevel: i32; + leftEarChargeState: DeviceChargeState; + rightEarBatteryLevel: i32; + deviceClass: DeviceClass; + rightEarChargeState: DeviceChargeState; + boxBatteryLevel: i32; + boxChargeState: DeviceChargeState; +} + +enum DeviceChargeState: i32{ + DEVICE_NORMAL_CHARGE_NOT_CHARGED = 0, + DEVICE_NORMAL_CHARGE_IN_CHARGING = 1, + DEVICE_SUPER_CHARGE_NOT_CHARGED = 2, + DEVICE_SUPER_CHARGE_IN_CHARGING = 3 +} + +struct BondStateParam { + deviceId: String; + state: BondState; + cause: UnbondCause; +} + +enum BondState: i32{ + BOND_STATE_INVALID = 0, + BOND_STATE_BONDING = 1, + BOND_STATE_BONDED = 2 +} + +enum UnbondCause: i32{ + USER_REMOVED = 0, + REMOTE_DEVICE_DOWN = 1, + AUTH_FAILURE = 2, + AUTH_REJECTED = 3, + INTERNAL_ERROR = 4 +} + +struct ControlDeviceActionParams { + deviceId: String; + type: ControlType; + typeValue: ControlTypeValue; + controlObject: ControlObject; +} + +enum ControlType: i32{ + PLAY = 0, + VIBRATE = 1, + FLASH = 2, + LOCK = 3, + ERASE = 4, +} + +enum ControlTypeValue: i32{ + DISABLE = 0, + ENABLE = 1, + QUERY = 2, +} + +enum ControlObject: i32{ + LEFT_EAR = 0, + RIGHT_EAR = 1, + LEFT_RIGHT_EAR = 2, +} + +function getRemoteProductId(deviceId: String): String; + +@overload("getRemoteDeviceName") +function getRemoteDeviceName_two(deviceId: String, alias: Optional): String; +@overload("getRemoteDeviceName") +function getRemoteDeviceName_one(deviceId: String): String; + +function getPairedDevices(): Array; + +function setBluetoothScanMode(mode: ScanMode, duration: f64): void; + +@on_off("discoveryResult") +function onDiscoveryResult(callback: (a: Array) => void): void; +@on_off("discoveryResult") +function offDiscoveryResult(callback:Optional<(a: Array)=> void>): void; + +@on_off("batteryChange") +function onBatteryChange(callback: (a: BatteryInfo) => void): void; +@on_off("batteryChange") +function offBatteryChange(callback:Optional<(a: BatteryInfo)=> void>): void; + +@on_off("bluetoothDeviceFind") +function onBluetoothDeviceFind(callback: (a: Array) => void): void; +@on_off("bluetoothDeviceFind") +function offBluetoothDeviceFind(callback:Optional<(a: Array)=> void>): void; + +@on_off("bondStateChange") +function onBondStateChange(callback: (a: BondStateParam) => void): void; +@on_off("bondStateChange") +function offBondStateChange(callback:Optional<(a: BondStateParam)=> void>): void; + +@on_off("pinRequired") +function onPinRequired(callback: (a: PinRequiredParam) => void): void; +@on_off("pinRequired") +function offPinRequired(callback:Optional<(a: PinRequiredParam)=> void>): void; + +function getRemoteDeviceClass(deviceId: String): DeviceClass; diff --git a/frameworks/ets/taihe/bluetooth_connection/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_connection/src/ani_constructor.cpp new file mode 100644 index 00000000..420d1aba --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_connection/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.connection.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::connection::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::connection::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_connection/src/ohos.bluetooth.connection.impl.cpp b/frameworks/ets/taihe/bluetooth_connection/src/ohos.bluetooth.connection.impl.cpp new file mode 100644 index 00000000..532be999 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_connection/src/ohos.bluetooth.connection.impl.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2025-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 "ohos.bluetooth.connection.proj.hpp" +#include "ohos.bluetooth.connection.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" +#include "bluetooth_remote_device.h" +#include "bluetooth_host.h" +#include "bluetooth_log.h" +#include "bluetooth_errorcode.h" + +using namespace taihe; +using namespace ohos::bluetooth::connection; +using namespace ohos::bluetooth::constant; +using namespace OHOS::Bluetooth; + + +namespace { + +string getRemoteProductId(string_view deviceId) { + // 数据类型转换 + std::string remoteAddr = std::string(deviceId); + // 业务逻辑实现 + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr); + std::string productId; + int32_t err = remoteDevice.GetDeviceProductId(productId); + if (err != BT_NO_ERROR) { + std::cerr<< "getRemoteProductId failed." << std::endl; + } + // 返回值 + return productId; +} + +string getRemoteDeviceName_one(string_view deviceId) { + std::string remoteAddr = std::string(deviceId); + std::string name = INVALID_NAME; + bool device_alias = false; + + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr); + int32_t err = remoteDevice.GetDeviceName(name, device_alias); + if (err != BT_NO_ERROR) { + std::cerr<< "getRemoteDeviceName failed." << std::endl; + } + return name; +} + +string getRemoteDeviceName_two(string_view deviceId, optional_view alias) { + std::string remoteAddr = std::string(deviceId); + std::string name = INVALID_NAME; + bool device_alias = bool(alias); + + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr); + int32_t err = remoteDevice.GetDeviceName(name, device_alias); + if (err != BT_NO_ERROR) { + std::cerr<< "getRemoteDeviceName failed." << std::endl; + } + return name; +} + +array getPairedDevices() { + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + std::vector remoteDeviceLists; + std::vector dstDevicesvec; + int32_t ret = host->GetPairedDevices(BT_TRANSPORT_BREDR, remoteDeviceLists); + if (ret != BT_NO_ERROR) { + std::cerr<< "getPairedDevices failed." << std::endl; + } + for (auto vec : remoteDeviceLists) { + dstDevicesvec.push_back(vec.GetDeviceAddr().c_str()); + } + + std::cout<< "getPairedDevices" << std::endl; + array result(taihe::copy_data_t{}, dstDevicesvec.data(), dstDevicesvec.size()); + return result; +} + +void setBluetoothScanMode(ScanMode mode, double duration) { + BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + int32_t ret = host->SetBtScanMode(mode, duration); + if (ret != BT_NO_ERROR) { + std::cerr<< "setBluetoothScanMode failed." << std::endl; + } + host->SetBondableMode(BT_TRANSPORT_BREDR, 1); +} + +void onDiscoveryResult(callback_view)> callback) { + std::cout<< "onDiscoveryResult" << std::endl; +} + +void offDiscoveryResult(optional_view)>> callback) { + std::cout<< "offDiscoveryResult" << std::endl; +} + +void onBatteryChange(callback_view callback) { + std::cout<< "onBatteryChange" << std::endl; + // RegisterConnectionObserver + // auto connectionObserverFunc = [](napi_env env, napi_callback_info info) { + // return g_connectionObserver->eventSubscribe_.Register(env, info); + // }; + // auto remoteDeviceObserverFunc = [](napi_env env, napi_callback_info info) { + // return g_remoteDeviceObserver->eventSubscribe_.Register(env, info); + // }; + + // auto status = NapiConnectionOnOffExecute(env, info, connectionObserverFunc, remoteDeviceObserverFunc); + // NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + // return NapiGetUndefinedRet(env); +} + +void offBatteryChange(optional_view> callback) { + std::cout<< "offBatteryChange" << std::endl; +} +void onBluetoothDeviceFind(callback_view)> callback) { + std::cout<< "onBluetoothDeviceFind" << std::endl; +} + +void offBluetoothDeviceFind(optional_view)>> callback) { + std::cout<< "offBluetoothDeviceFind" << std::endl; +} + +void onBondStateChange(callback_view callback) { + std::cout<< "onBondStateChange" << std::endl; +} + +void offBondStateChange(optional_view> callback) { + std::cout<< "offBondStateChange" << std::endl; +} +void onPinRequired(callback_view callback) { + std::cout<< "onPinRequired" << std::endl; +} + +void offPinRequired(optional_view> callback) { + std::cout<< "offPinRequired" << std::endl; +} + +DeviceClass getRemoteDeviceClass(string_view deviceId) { + std::string remoteAddr = std::string(deviceId); + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr); + int tmpCod = int(MajorClass::key_t::MAJOR_UNCATEGORIZED); + int tmpMajorClass = int(MajorClass::key_t::MAJOR_UNCATEGORIZED); + int tmpMajorMinorClass = int(MajorClass::key_t::MAJOR_UNCATEGORIZED); + int32_t err = remoteDevice.GetDeviceProductType(tmpCod, tmpMajorClass, tmpMajorMinorClass); + if (err != BT_NO_ERROR) { + std::cerr<< "getRemoteDeviceClass failed." << std::endl; + } + return {static_cast(tmpMajorClass), static_cast(tmpMajorMinorClass), tmpCod}; +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_getRemoteProductId(getRemoteProductId); +TH_EXPORT_CPP_API_getRemoteDeviceName_one(getRemoteDeviceName_one); +TH_EXPORT_CPP_API_getRemoteDeviceName_two(getRemoteDeviceName_two); +TH_EXPORT_CPP_API_getPairedDevices(getPairedDevices); +TH_EXPORT_CPP_API_setBluetoothScanMode(setBluetoothScanMode); +TH_EXPORT_CPP_API_onDiscoveryResult(onDiscoveryResult); +TH_EXPORT_CPP_API_offDiscoveryResult(offDiscoveryResult); +TH_EXPORT_CPP_API_onBatteryChange(onBatteryChange); +TH_EXPORT_CPP_API_offBatteryChange(offBatteryChange); +TH_EXPORT_CPP_API_onBluetoothDeviceFind(onBluetoothDeviceFind); +TH_EXPORT_CPP_API_offBluetoothDeviceFind(offBluetoothDeviceFind); +TH_EXPORT_CPP_API_onBondStateChange(onBondStateChange); +TH_EXPORT_CPP_API_offBondStateChange(offBondStateChange); +TH_EXPORT_CPP_API_onPinRequired(onPinRequired); +TH_EXPORT_CPP_API_offPinRequired(offPinRequired); +TH_EXPORT_CPP_API_getRemoteDeviceClass(getRemoteDeviceClass); +// NOLINTEND \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_constant/BUILD.gn b/frameworks/ets/taihe/bluetooth_constant/BUILD.gn new file mode 100644 index 00000000..8ac4c070 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_constant/BUILD.gn @@ -0,0 +1,87 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_constant_taihe") { + sources = [ "idl/ohos.bluetooth.constant.taihe" ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_constant_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.constant.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.constant.abi.c", + ] +} + +taihe_shared_library("bluetoothConstant_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.constant.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothConstant_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.constant.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothConstant_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothConstant_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothConstant_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothConstant_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothConstant_taihe") { + deps = [ + ":bluetoothConstant_etc", + ":bluetoothConstant_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_constant/idl/ohos.bluetooth.constant.taihe b/frameworks/ets/taihe/bluetooth_constant/idl/ohos.bluetooth.constant.taihe new file mode 100644 index 00000000..935419e0 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_constant/idl/ohos.bluetooth.constant.taihe @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.constant", "constant") +@!sts_inject(""" +static { loadLibrary("bluetoothConstant_taihe_native.z") } +""") + +enum ProfileConnectionState: i32{ + STATE_DISCONNECTED = 0, + STATE_CONNECTING = 1, + STATE_CONNECTED = 2, + STATE_DISCONNECTING = 3 +} + +enum MajorClass: i32 { + MAJOR_MISC = 0x0000, + MAJOR_COMPUTER = 0x0100, + MAJOR_PHONE = 0x0200, + MAJOR_NETWORKING = 0x0300, + MAJOR_AUDIO_VIDEO = 0x0400, + MAJOR_PERIPHERAL = 0x0500, + MAJOR_IMAGING = 0x0600, + MAJOR_WEARABLE = 0x0700, + MAJOR_TOY = 0x0800, + MAJOR_HEALTH = 0x0900, + MAJOR_UNCATEGORIZED = 0x1F00 +} + +enum MajorMinorClass: i32 { + COMPUTER_UNCATEGORIZED = 0x0100, + COMPUTER_DESKTOP = 0x0104, + COMPUTER_SERVER = 0x0108, + COMPUTER_LAPTOP = 0x010C, + COMPUTER_HANDHELD_PC_PDA = 0x0110, + COMPUTER_PALM_SIZE_PC_PDA = 0x0114, + COMPUTER_WEARABLE = 0x0118, + COMPUTER_TABLET = 0x011C, + PHONE_UNCATEGORIZED = 0x0200, + PHONE_CELLULAR = 0x0204, + PHONE_CORDLESS = 0x0208, + PHONE_SMART = 0x020C, + PHONE_MODEM_OR_GATEWAY = 0x0210, + PHONE_ISDN = 0x0214, + NETWORK_FULLY_AVAILABLE = 0x0300, + NETWORK_1_TO_17_UTILIZED = 0x0320, + NETWORK_17_TO_33_UTILIZED = 0x0340, + NETWORK_33_TO_50_UTILIZED = 0x0360, + NETWORK_60_TO_67_UTILIZED = 0x0380, + NETWORK_67_TO_83_UTILIZED = 0x03A0, + NETWORK_83_TO_99_UTILIZED = 0x03C0, + NETWORK_NO_SERVICE = 0x03E0, + AUDIO_VIDEO_UNCATEGORIZED = 0x0400, + AUDIO_VIDEO_WEARABLE_HEADSET = 0x0404, + AUDIO_VIDEO_HANDSFREE = 0x0408, + AUDIO_VIDEO_MICROPHONE = 0x0410, + AUDIO_VIDEO_LOUDSPEAKER = 0x0414, + AUDIO_VIDEO_HEADPHONES = 0x0418, + AUDIO_VIDEO_PORTABLE_AUDIO = 0x041C, + AUDIO_VIDEO_CAR_AUDIO = 0x0420, + AUDIO_VIDEO_SET_TOP_BOX = 0x0424, + AUDIO_VIDEO_HIFI_AUDIO = 0x0428, + AUDIO_VIDEO_VCR = 0x042C, + AUDIO_VIDEO_VIDEO_CAMERA = 0x0430, + AUDIO_VIDEO_CAMCORDER = 0x0434, + AUDIO_VIDEO_VIDEO_MONITOR = 0x0438, + AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER = 0x043C, + AUDIO_VIDEO_VIDEO_CONFERENCING = 0x0440, + AUDIO_VIDEO_VIDEO_GAMING_TOY = 0x0448, + PERIPHERAL_NON_KEYBOARD_NON_POINTING = 0x0500, + PERIPHERAL_KEYBOARD = 0x0540, + PERIPHERAL_POINTING_DEVICE = 0x0580, + PERIPHERAL_KEYBOARD_POINTING = 0x05C0, + PERIPHERAL_UNCATEGORIZED = 0x0500, + PERIPHERAL_JOYSTICK = 0x0504, + PERIPHERAL_GAMEPAD = 0x0508, + PERIPHERAL_REMOTE_CONTROL = 0x05C0, + PERIPHERAL_SENSING_DEVICE = 0x0510, + PERIPHERAL_DIGITIZER_TABLET = 0x0514, + PERIPHERAL_CARD_READER = 0x0518, + PERIPHERAL_DIGITAL_PEN = 0x051C, + PERIPHERAL_SCANNER_RFID = 0x0520, + PERIPHERAL_GESTURAL_INPUT = 0x0522, + IMAGING_UNCATEGORIZED = 0x0600, + IMAGING_DISPLAY = 0x0610, + IMAGING_CAMERA = 0x0620, + IMAGING_SCANNER = 0x0640, + IMAGING_PRINTER = 0x0680, + WEARABLE_UNCATEGORIZED = 0x0700, + WEARABLE_WRIST_WATCH = 0x0704, + WEARABLE_PAGER = 0x0708, + WEARABLE_JACKET = 0x070C, + WEARABLE_HELMET = 0x0710, + WEARABLE_GLASSES = 0x0714, + TOY_UNCATEGORIZED = 0x0800, + TOY_ROBOT = 0x0804, + TOY_VEHICLE = 0x0808, + TOY_DOLL_ACTION_FIGURE = 0x080C, + TOY_CONTROLLER = 0x0810, + TOY_GAME = 0x0814, + HEALTH_UNCATEGORIZED = 0x0900, + HEALTH_BLOOD_PRESSURE = 0x0904, + HEALTH_THERMOMETER = 0x0908, + HEALTH_WEIGHING = 0x090C, + HEALTH_GLUCOSE = 0x0910, + HEALTH_PULSE_OXIMETER = 0x0914, + HEALTH_PULSE_RATE = 0x0918, + HEALTH_DATA_DISPLAY = 0x091C, + HEALTH_STEP_COUNTER = 0x0920, + HEALTH_BODY_COMPOSITION_ANALYZER = 0x0924, + HEALTH_PEAK_FLOW_MONITOR = 0x0928, + HEALTH_MEDICATION_MONITOR = 0x092C, + HEALTH_KNEE_PROSTHESIS = 0x0930, + HEALTH_ANKLE_PROSTHESIS = 0x0934, + HEALTH_GENERIC_HEALTH_MANAGER = 0x0938, + HEALTH_PERSONAL_MOBILITY_DEVICE = 0x093C +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_constant/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_constant/src/ani_constructor.cpp new file mode 100644 index 00000000..66278a9b --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_constant/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.constant.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::constant::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::constant::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_constant/src/ohos.bluetooth.constant.impl.cpp b/frameworks/ets/taihe/bluetooth_constant/src/ohos.bluetooth.constant.impl.cpp new file mode 100644 index 00000000..52020ce4 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_constant/src/ohos.bluetooth.constant.impl.cpp @@ -0,0 +1,15 @@ +#include "ohos.bluetooth.constant.proj.hpp" +#include "ohos.bluetooth.constant.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" + +using namespace taihe; +using namespace ohos::bluetooth::constant; + +namespace { +// To be implemented. +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +// NOLINTEND diff --git a/frameworks/ets/taihe/bluetooth_hfp/BUILD.gn b/frameworks/ets/taihe/bluetooth_hfp/BUILD.gn new file mode 100644 index 00000000..c85833cc --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hfp/BUILD.gn @@ -0,0 +1,93 @@ +# Copyright (C) 2025-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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_hfp_taihe") { + sources = [ + "idl/ohos.bluetooth.hfp.taihe" + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_baseProfile:bluetooth_baseProfile_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_hfp_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.hfp.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.hfp.abi.c", + ] +} + +taihe_shared_library("bluetoothHfp_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.hfp.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + "../bluetooth_baseProfile:bluetoothBaseProfile_taihe_native" + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothHfp_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.hfp.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothHfp_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothHfp_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothHfp_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothHfp_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothHfp_taihe") { + deps = [ + ":bluetoothHfp_etc", + ":bluetoothHfp_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_hfp/idl/ohos.bluetooth.hfp.taihe b/frameworks/ets/taihe/bluetooth_hfp/idl/ohos.bluetooth.hfp.taihe new file mode 100644 index 00000000..ec2bb920 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hfp/idl/ohos.bluetooth.hfp.taihe @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.hfp", "hfp") +from ohos.bluetooth.baseProfile use BaseProfile; +interface HandsFreeAudioGatewayProfile : BaseProfile { +} + +function createHfpAgProfile(): HandsFreeAudioGatewayProfile; \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_hfp/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_hfp/src/ani_constructor.cpp new file mode 100644 index 00000000..75035f2b --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hfp/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.hfp.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::hfp::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::hfp::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_hfp/src/ohos.bluetooth.hfp.impl.cpp b/frameworks/ets/taihe/bluetooth_hfp/src/ohos.bluetooth.hfp.impl.cpp new file mode 100644 index 00000000..f3c38ccd --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hfp/src/ohos.bluetooth.hfp.impl.cpp @@ -0,0 +1,33 @@ +#include "ohos.bluetooth.hfp.proj.hpp" +#include "ohos.bluetooth.hfp.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" + +using namespace taihe; +using namespace ohos::bluetooth::hfp; + +namespace { +// To be implemented. + +class HandsFreeAudioGatewayProfileImpl { +public: + HandsFreeAudioGatewayProfileImpl() { + // Don't forget to implement the constructor. + } + + void onConnectionStateChange(callback_view callback) { + std::cout<< "onConnectionStateChange" << std::endl; + } +}; + +HandsFreeAudioGatewayProfile createHfpAgProfile() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_createHfpAgProfile(createHfpAgProfile); +// NOLINTEND diff --git a/frameworks/ets/taihe/bluetooth_hid/BUILD.gn b/frameworks/ets/taihe/bluetooth_hid/BUILD.gn new file mode 100644 index 00000000..1e8da32f --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hid/BUILD.gn @@ -0,0 +1,93 @@ +# 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/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +SUBSYSTEM_DIR = "//foundation/communication" + +copy_taihe_idl("bluetooth_hid_taihe") { + sources = [ + "idl/ohos.bluetooth.hid.taihe" + ] + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/ets/taihe/bluetooth_baseProfile:bluetooth_baseProfile_taihe" + ] +} + +subsystem_name = "communication" #子系统名 +part_name = "bluetooth" #部件名 +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":bluetooth_hid_taihe" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.bluetooth.hid.ani.cpp", + "$taihe_generated_file_path/src/ohos.bluetooth.hid.abi.c", + ] +} + +taihe_shared_library("bluetoothHid_taihe_native") { #调用taihe_shared_library模板编译so + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + include_dirs = [ + "include", + "src", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner/include", + "$SUBSYSTEM_DIR/bluetooth/interfaces/inner_api/include" + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.bluetooth.hid.impl.cpp", + ] + deps = [ + ":run_taihe", + "$SUBSYSTEM_DIR/bluetooth/frameworks/inner:btframework", + "../bluetooth_baseProfile:bluetoothBaseProfile_taihe_native" + ] + sanitize = { + cfi = true # Enable/disable control flow integrity detection + boundary_sanitize = true # Enable boundary san detection + cfi_cross_dso = true # Cross-SO CFI Checks + integer_overflow = true # Enable integer overflow detection + ubsan = true # Enable some Ubsan options + debug = false + } +} + +generate_static_abc("bluetoothHid_abc") { #调用generate_static_abc编译abc + base_url = "$taihe_generated_file_path" #base_url直接设置为taihe_generated_file_path + files = [ "$taihe_generated_file_path/@ohos.bluetooth.hid.ets" ] #files传入生成的ets文件 + is_boot_abc = "True" + device_dst_file = "/system/framework/bluetoothHid_abc.abc" + dependencies = [ ":run_taihe" ] #编译abc依赖太和工具链调用 +} +ohos_prebuilt_etc("bluetoothHid_etc") { #调用ohos_prebuilt_etc将abc拷贝到/system/framework下 + source = "$target_out_dir/bluetoothHid_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":bluetoothHid_abc" ] #拷贝abc依赖编译abc +} + +group("bluetoothHid_taihe") { + deps = [ + ":bluetoothHid_etc", + ":bluetoothHid_taihe_native" + ] + # deps = [":run_taihe"] #单独运行run_taihe目标即可只调用工具链并生成对应代码 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_hid/idl/ohos.bluetooth.hid.taihe b/frameworks/ets/taihe/bluetooth_hid/idl/ohos.bluetooth.hid.taihe new file mode 100644 index 00000000..88c1d0de --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hid/idl/ohos.bluetooth.hid.taihe @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2025-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. + */ + +@!namespace("@ohos.bluetooth.hid", "hid") +from ohos.bluetooth.baseProfile use BaseProfile; +interface HidHostProfile : BaseProfile { +} +function createHidHostProfile(): HidHostProfile; \ No newline at end of file diff --git a/frameworks/ets/taihe/bluetooth_hid/src/ani_constructor.cpp b/frameworks/ets/taihe/bluetooth_hid/src/ani_constructor.cpp new file mode 100644 index 00000000..ebc734b8 --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hid/src/ani_constructor.cpp @@ -0,0 +1,13 @@ +#include "ohos.bluetooth.hid.ani.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) { + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::bluetooth::hid::ANIRegister(env)) { + std::cerr << "Error from ohos::bluetooth::hid::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/bluetooth_hid/src/ohos.bluetooth.hid.impl.cpp b/frameworks/ets/taihe/bluetooth_hid/src/ohos.bluetooth.hid.impl.cpp new file mode 100644 index 00000000..f23212be --- /dev/null +++ b/frameworks/ets/taihe/bluetooth_hid/src/ohos.bluetooth.hid.impl.cpp @@ -0,0 +1,33 @@ +#include "ohos.bluetooth.hid.proj.hpp" +#include "ohos.bluetooth.hid.impl.hpp" +#include "taihe/runtime.hpp" +#include "stdexcept" + +using namespace taihe; +using namespace ohos::bluetooth::hid; +using namespace ohos::bluetooth::baseProfile; +namespace { +// To be implemented. + +class HidHostProfileImpl { +public: + HidHostProfileImpl() { + // Don't forget to implement the constructor. + } + + void onConnectionStateChange(callback_view callback) { + std::cout<< "onConnectionStateChange" << std::endl; + } +}; + +HidHostProfile createHidHostProfile() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_createHidHostProfile(createHidHostProfile); +// NOLINTEND -- Gitee