From c2b6c209d6e74aae1e1a78ecc8bc61a519a6b6b8 Mon Sep 17 00:00:00 2001 From: lee Date: Wed, 8 Feb 2023 20:18:58 +0800 Subject: [PATCH] add napi throw error code for release Signed-off-by: lee --- bundle.json | 2 +- frameworks/inner/c_adapter/ohos_bt_gap.cpp | 59 +- frameworks/inner/common/bluetooth_errorcode.h | 40 +- frameworks/inner/src/bluetooth_a2dp_snk.cpp | 32 +- frameworks/inner/src/bluetooth_a2dp_src.cpp | 72 +- .../inner/src/bluetooth_ble_advertiser.cpp | 203 +++-- .../src/bluetooth_ble_central_manager.cpp | 200 +++-- .../inner/src/bluetooth_gatt_client.cpp | 212 ++--- .../inner/src/bluetooth_gatt_server.cpp | 137 +-- frameworks/inner/src/bluetooth_hfp_ag.cpp | 123 ++- frameworks/inner/src/bluetooth_hid_host.cpp | 126 +-- frameworks/inner/src/bluetooth_host.cpp | 149 +++- frameworks/inner/src/bluetooth_map_mce.cpp | 2 +- frameworks/inner/src/bluetooth_pan.cpp | 128 +-- .../inner/src/bluetooth_remote_device.cpp | 45 +- frameworks/inner/src/bluetooth_socket.cpp | 16 +- frameworks/inner/src/bluetooth_utils.cpp | 36 + frameworks/js/napi/BUILD.gn | 95 +++ .../napi_bluetooth_a2dp_snk_observer.h | 5 +- .../napi_bluetooth_a2dp_src_observer.h | 3 +- .../napi_bluetooth_avrcp_ct_observer.h | 5 +- .../napi_bluetooth_avrcp_tg_observer.h | 6 +- ...i_bluetooth_ble_central_manager_callback.h | 2 +- .../js/napi/include/napi_bluetooth_error.h | 66 ++ .../js/napi/include/napi_bluetooth_event.h | 6 +- .../napi/include/napi_bluetooth_gatt_client.h | 2 +- .../napi_bluetooth_gatt_client_callback.h | 5 +- .../napi_bluetooth_gatt_server_callback.h | 2 +- .../include/napi_bluetooth_hfp_ag_observer.h | 4 +- .../include/napi_bluetooth_hfp_hf_observer.h | 3 +- .../js/napi/include/napi_bluetooth_host.h | 4 + .../js/napi/include/napi_bluetooth_profile.h | 4 +- .../napi/include/napi_bluetooth_spp_client.h | 4 +- .../js/napi/include/napi_bluetooth_utils.h | 83 +- .../js/napi/src/napi_bluetooth_a2dp_snk.cpp | 64 +- .../src/napi_bluetooth_a2dp_snk_observer.cpp | 40 +- .../js/napi/src/napi_bluetooth_a2dp_src.cpp | 179 +--- .../src/napi_bluetooth_a2dp_src_observer.cpp | 41 +- .../js/napi/src/napi_bluetooth_avrcp_ct.cpp | 66 +- .../src/napi_bluetooth_avrcp_ct_observer.cpp | 41 +- .../js/napi/src/napi_bluetooth_avrcp_tg.cpp | 63 +- .../src/napi_bluetooth_avrcp_tg_observer.cpp | 37 +- frameworks/js/napi/src/napi_bluetooth_ble.cpp | 789 ++++++------------ ...bluetooth_ble_central_manager_callback.cpp | 21 +- .../js/napi/src/napi_bluetooth_error.cpp | 68 ++ .../js/napi/src/napi_bluetooth_event.cpp | 10 +- .../napi/src/napi_bluetooth_gatt_client.cpp | 697 ++++++++-------- .../napi_bluetooth_gatt_client_callback.cpp | 105 +-- .../napi/src/napi_bluetooth_gatt_server.cpp | 455 +++++----- .../js/napi/src/napi_bluetooth_hfp_ag.cpp | 185 ++-- .../src/napi_bluetooth_hfp_ag_observer.cpp | 79 +- .../js/napi/src/napi_bluetooth_hfp_hf.cpp | 58 +- .../src/napi_bluetooth_hfp_hf_observer.cpp | 74 +- .../js/napi/src/napi_bluetooth_hid_host.cpp | 133 ++- .../js/napi/src/napi_bluetooth_host.cpp | 426 +++++----- .../napi/src/napi_bluetooth_host_observer.cpp | 8 +- frameworks/js/napi/src/napi_bluetooth_opp.cpp | 2 +- frameworks/js/napi/src/napi_bluetooth_pan.cpp | 177 ++-- .../js/napi/src/napi_bluetooth_pbap_pce.cpp | 2 +- .../js/napi/src/napi_bluetooth_pbap_pse.cpp | 4 +- .../js/napi/src/napi_bluetooth_profile.cpp | 43 +- .../napi_bluetooth_remote_device_observer.cpp | 2 +- .../js/napi/src/napi_bluetooth_spp_client.cpp | 259 +++--- .../js/napi/src/napi_bluetooth_spp_server.cpp | 131 +-- .../js/napi/src/napi_bluetooth_utils.cpp | 452 ++++++++-- frameworks/js/napi/src/native_module.cpp | 5 + .../js/napi/src/parser/napi_parser_utils.cpp | 497 +++++++++++ .../js/napi/src/parser/napi_parser_utils.h | 83 ++ .../inner_api/include/bluetooth_a2dp_snk.h | 11 + .../inner_api/include/bluetooth_a2dp_src.h | 14 +- .../include/bluetooth_ble_advertiser.h | 6 +- .../include/bluetooth_ble_central_manager.h | 11 +- interfaces/inner_api/include/bluetooth_def.h | 5 +- .../inner_api/include/bluetooth_errorcode.h | 61 ++ .../include/bluetooth_gatt_characteristic.h | 2 +- .../inner_api/include/bluetooth_hfp_ag.h | 16 +- .../inner_api/include/bluetooth_hid_host.h | 8 +- interfaces/inner_api/include/bluetooth_host.h | 65 +- interfaces/inner_api/include/bluetooth_pan.h | 10 +- .../include/bluetooth_remote_device.h | 14 +- .../inner_api/include/bluetooth_utils.h | 13 +- .../inner_api/include/c_header/ohos_bt_spp.h | 8 +- services/bluetooth/common/BUILD.gn | 1 + services/bluetooth/common/ble_parcel_data.cpp | 61 ++ services/bluetooth/common/ble_parcel_data.h | 30 +- .../bluetooth/common/ble_service_data.cpp | 5 + services/bluetooth/common/ble_service_data.h | 2 + .../bluetooth/common/bluetooth_errorcode.h | 61 ++ services/bluetooth/common/bt_def.h | 1 + .../ipc/include/bluetooth_a2dp_sink_proxy.h | 2 +- .../ipc/include/bluetooth_a2dp_src_proxy.h | 2 +- .../include/bluetooth_ble_advertiser_proxy.h | 4 +- .../bluetooth_ble_central_manager_proxy.h | 6 +- .../ipc/include/bluetooth_gatt_client_proxy.h | 3 + .../ipc/include/bluetooth_hfp_ag_proxy.h | 12 +- .../ipc/include/bluetooth_hfp_ag_stub.h | 8 +- .../ipc/include/bluetooth_hid_host_proxy.h | 8 +- .../ipc/include/bluetooth_hid_host_stub.h | 8 +- .../ipc/include/bluetooth_host_proxy.h | 39 +- .../ipc/include/bluetooth_host_stub.h | 35 +- .../ipc/include/bluetooth_pan_proxy.h | 10 +- .../ipc/include/bluetooth_pan_stub.h | 10 +- .../ipc/include/bluetooth_socket_proxy.h | 1 + .../ipc/include/i_bluetooth_a2dp_sink.h | 2 +- .../ipc/include/i_bluetooth_a2dp_src.h | 2 +- .../ipc/include/i_bluetooth_ble_advertiser.h | 4 +- .../include/i_bluetooth_ble_central_manager.h | 6 +- .../ipc/include/i_bluetooth_gatt_client.h | 2 + .../ipc/include/i_bluetooth_hfp_ag.h | 8 +- .../ipc/include/i_bluetooth_hid_host.h | 8 +- .../bluetooth/ipc/include/i_bluetooth_host.h | 38 +- .../bluetooth/ipc/include/i_bluetooth_pan.h | 10 +- services/bluetooth/ipc/ipc_blocklist.txt | 2 + .../ipc/parcel/bluetooth_ble_scan_result.cpp | 6 + .../ipc/parcel/bluetooth_ble_scan_result.h | 9 +- .../ipc/src/bluetooth_a2dp_sink_proxy.cpp | 22 +- .../ipc/src/bluetooth_a2dp_sink_stub.cpp | 22 +- .../ipc/src/bluetooth_a2dp_src_proxy.cpp | 40 +- .../ipc/src/bluetooth_a2dp_src_stub.cpp | 32 +- .../src/bluetooth_avrcp_tg_observer_stub.cpp | 6 +- ...bluetooth_ble_advertise_callback_proxy.cpp | 4 +- .../src/bluetooth_ble_advertiser_proxy.cpp | 45 +- .../ipc/src/bluetooth_ble_advertiser_stub.cpp | 37 +- .../bluetooth_ble_central_manager_proxy.cpp | 38 +- .../bluetooth_ble_central_manager_stub.cpp | 29 +- .../ipc/src/bluetooth_gatt_client_proxy.cpp | 134 ++- .../ipc/src/bluetooth_gatt_client_stub.cpp | 8 +- .../ipc/src/bluetooth_gatt_server_proxy.cpp | 84 +- .../ipc/src/bluetooth_hfp_ag_proxy.cpp | 54 +- .../ipc/src/bluetooth_hfp_ag_stub.cpp | 62 +- .../src/bluetooth_hid_host_observer_stub.cpp | 12 +- .../ipc/src/bluetooth_hid_host_proxy.cpp | 73 +- .../ipc/src/bluetooth_hid_host_stub.cpp | 95 ++- .../ipc/src/bluetooth_host_proxy.cpp | 269 +++--- .../bluetooth/ipc/src/bluetooth_host_stub.cpp | 232 +++-- .../src/bluetooth_map_mse_observer_stub.cpp | 6 +- .../ipc/src/bluetooth_opp_observer_stub.cpp | 8 +- .../ipc/src/bluetooth_pan_observer_stub.cpp | 4 +- .../bluetooth/ipc/src/bluetooth_pan_proxy.cpp | 115 +-- .../bluetooth/ipc/src/bluetooth_pan_stub.cpp | 124 +-- .../ipc/src/bluetooth_socket_proxy.cpp | 26 +- services/bluetooth/server/BUILD.gn | 2 +- .../server/bluetooth_server_blocklist.txt | 16 + .../include/bluetooth_a2dp_sink_server.h | 2 +- .../include/bluetooth_a2dp_source_server.h | 2 +- .../include/bluetooth_ble_advertiser_server.h | 4 +- .../bluetooth_ble_central_manager_server.h | 6 +- .../include/bluetooth_gatt_client_server.h | 3 + .../server/include/bluetooth_hfp_ag_server.h | 14 +- .../include/bluetooth_hid_host_server.h | 17 +- .../server/include/bluetooth_host_server.h | 37 +- .../server/include/bluetooth_pan_server.h | 17 +- .../server/src/bluetooth_a2dp_sink_server.cpp | 4 +- .../src/bluetooth_a2dp_source_server.cpp | 23 +- .../src/bluetooth_ble_advertiser_server.cpp | 70 +- .../bluetooth_ble_central_manager_server.cpp | 81 +- .../src/bluetooth_gatt_client_server.cpp | 80 +- .../src/bluetooth_gatt_server_server.cpp | 66 +- .../server/src/bluetooth_hfp_ag_server.cpp | 36 +- .../server/src/bluetooth_hfp_hf_server.cpp | 4 +- .../server/src/bluetooth_hid_host_server.cpp | 49 +- .../server/src/bluetooth_host_dumper.cpp | 2 +- .../server/src/bluetooth_host_server.cpp | 232 +++-- .../server/src/bluetooth_pan_server.cpp | 61 +- .../service/bluetooth_service_blocklist.txt | 1 + .../include/interface_profile_a2dp_src.h | 2 +- .../src/ble/ble_central_manager_impl.cpp | 2 +- .../src/gatt/gatt_connection_manager.cpp | 2 +- .../service/src/gavdp/a2dp_service.cpp | 6 +- .../service/src/gavdp/a2dp_service.h | 2 +- .../service/src/hfp_ag/hfp_ag_service.cpp | 9 +- .../service/src/hid_host/hid_host_service.cpp | 12 +- .../service/src/permission/auth_center.cpp | 8 + .../service/src/permission/auth_center.h | 8 + .../src/permission/permission_helper.cpp | 9 + .../src/permission/permission_helper.h | 9 + .../src/permission/permission_utils.cpp | 8 +- .../service/src/permission/permission_utils.h | 1 + .../bluetooth/stack/btstack_blocklist.txt | 7 +- .../setbluetoothscanmode_fuzzer.cpp | 2 +- test/unittest/a2dp/a2dp_src_test.cpp | 11 +- test/unittest/ble/ble_test.cpp | 13 +- test/unittest/gatt/gatt_client_test.cpp | 21 +- test/unittest/gatt/gatt_server_test.cpp | 5 +- test/unittest/hfp/hfp_ag_test.cpp | 16 +- test/unittest/hid/hid_host_test.cpp | 16 +- test/unittest/host/host_test.cpp | 136 ++- test/unittest/pan/pan_test.cpp | 13 +- 188 files changed, 5987 insertions(+), 4568 deletions(-) create mode 100644 frameworks/js/napi/include/napi_bluetooth_error.h create mode 100644 frameworks/js/napi/src/napi_bluetooth_error.cpp create mode 100644 frameworks/js/napi/src/parser/napi_parser_utils.cpp create mode 100644 frameworks/js/napi/src/parser/napi_parser_utils.h create mode 100644 interfaces/inner_api/include/bluetooth_errorcode.h create mode 100644 services/bluetooth/common/ble_parcel_data.cpp create mode 100644 services/bluetooth/common/bluetooth_errorcode.h create mode 100644 services/bluetooth/server/bluetooth_server_blocklist.txt mode change 100755 => 100644 services/bluetooth/server/src/bluetooth_a2dp_sink_server.cpp mode change 100755 => 100644 services/bluetooth/server/src/bluetooth_a2dp_source_server.cpp mode change 100755 => 100644 services/bluetooth/server/src/bluetooth_hid_host_server.cpp mode change 100755 => 100644 services/bluetooth/server/src/bluetooth_host_server.cpp mode change 100755 => 100644 services/bluetooth/service/src/permission/auth_center.cpp mode change 100755 => 100644 services/bluetooth/service/src/permission/permission_helper.cpp mode change 100755 => 100644 services/bluetooth/service/src/permission/permission_helper.h diff --git a/bundle.json b/bundle.json index 57850482..de322a9a 100644 --- a/bundle.json +++ b/bundle.json @@ -77,7 +77,7 @@ "base_group": [], "fwk_group": [ "//foundation/communication/bluetooth/frameworks/inner:btframework", - "//foundation/communication/bluetooth/frameworks/js/napi:bluetooth" + "//foundation/communication/bluetooth/frameworks/js/napi:bluetooth_napi" ], "service_group": [ "//foundation/communication/bluetooth/sa_profile:communication_bluetooth_sa_profile", diff --git a/frameworks/inner/c_adapter/ohos_bt_gap.cpp b/frameworks/inner/c_adapter/ohos_bt_gap.cpp index 4e1dd1bd..1d2463ba 100644 --- a/frameworks/inner/c_adapter/ohos_bt_gap.cpp +++ b/frameworks/inner/c_adapter/ohos_bt_gap.cpp @@ -194,10 +194,13 @@ bool EnableBle(void) HILOGI("ble enabled already"); return true; } - - bool ret = g_BluetoothHost->EnableBle(); + bool isEnabled = false; + int32_t ret = g_BluetoothHost->EnableBle(); HILOGI("result: %{public}d", ret); - return ret; + if (ret == BT_SUCCESS) { + isEnabled = true; + } + return isEnabled; } bool DisableBle(void) @@ -211,10 +214,13 @@ bool DisableBle(void) HILOGI("ble disabled already"); return true; } - - bool ret = g_BluetoothHost->DisableBle(); + bool isEnabled = false; + int ret = g_BluetoothHost->DisableBle(); HILOGI("result: %{public}d", ret); - return ret; + if (ret == BT_SUCCESS) { + isEnabled = true; + } + return isEnabled; } bool EnableBt(void) @@ -224,15 +230,20 @@ bool EnableBt(void) g_BluetoothHost = &BluetoothHost::GetDefaultHost(); } - int state = g_BluetoothHost->GetBtState(); + int state; + g_BluetoothHost->GetBtState(state); if (state == BTStateID::STATE_TURNING_ON || state == BTStateID::STATE_TURN_ON) { HILOGI("br state is %{public}d", state); return true; } - bool ret = g_BluetoothHost->EnableBt(); + bool isEnabled = false; + int ret = g_BluetoothHost->EnableBt(); HILOGI("result: %{public}d", ret); - return ret; + if (ret == BT_SUCCESS) { + isEnabled = true; + } + return isEnabled; } bool DisableBt(void) @@ -242,7 +253,8 @@ bool DisableBt(void) g_BluetoothHost = &BluetoothHost::GetDefaultHost(); } - int state = g_BluetoothHost->GetBtState(); + int state; + g_BluetoothHost->GetBtState(state); if (state == BTStateID::STATE_TURNING_OFF || state == BTStateID::STATE_TURN_OFF) { HILOGI("br state is %{public}d", state); @@ -260,7 +272,8 @@ int GetBtState() g_BluetoothHost = &BluetoothHost::GetDefaultHost(); } - int state = g_BluetoothHost->GetBtState(); + int state; + g_BluetoothHost->GetBtState(state); HILOGI("br state: %{public}d", state); return state; } @@ -306,9 +319,13 @@ bool SetLocalName(unsigned char *localName, unsigned char length) } string newName(reinterpret_cast(localName)); - bool ret = g_BluetoothHost->SetLocalName(newName); + bool isSuccess = false; + int ret = g_BluetoothHost->SetLocalName(newName); + if (ret == BT_SUCCESS) { + isSuccess = true; + } HILOGI("result %{public}d: LocalName : %{public}s", ret, g_BluetoothHost->GetLocalName().c_str()); - return ret; + return isSuccess; } bool SetBtScanMode(int mode, int duration) @@ -317,9 +334,13 @@ bool SetBtScanMode(int mode, int duration) if (g_BluetoothHost == nullptr) { g_BluetoothHost = &BluetoothHost::GetDefaultHost(); } - bool ret = g_BluetoothHost->SetBtScanMode(mode, duration); + bool isSuccess = false; + int ret = g_BluetoothHost->SetBtScanMode(mode, duration); + if (ret == BT_SUCCESS) { + isSuccess = true; + } g_BluetoothHost->SetBondableMode(BT_TRANSPORT_BREDR, BONDABLE_MODE_ON); - return ret; + return isSuccess; } bool PairRequestReply(const BdAddr *bdAddr, int transport, bool accept) @@ -355,9 +376,13 @@ bool SetDevicePairingConfirmation(const BdAddr *bdAddr, int transport, bool acce HILOGE("transport: %{public}d is invalid", transport); return false; } - bool ret = remoteDevice.SetDevicePairingConfirmation(accept); + bool isSuccess = false; + int ret = remoteDevice.SetDevicePairingConfirmation(accept); HILOGI("ret: %{public}d", ret); - return ret; + if (ret == BT_SUCCESS) { + isSuccess = true; + } + return isSuccess; } int GapRegisterCallbacks(BtGapCallBacks *func) diff --git a/frameworks/inner/common/bluetooth_errorcode.h b/frameworks/inner/common/bluetooth_errorcode.h index d057b6a1..33e98690 100644 --- a/frameworks/inner/common/bluetooth_errorcode.h +++ b/frameworks/inner/common/bluetooth_errorcode.h @@ -20,13 +20,43 @@ namespace OHOS { namespace Bluetooth { /* Bluetooth errcode defines */ -enum ErrCode { - NO_ERROR = 0, - ERR_INVALID_STATE, - ERR_INVALID_VALUE, - ERROR, +enum BtErrCode { + // Common error codes + BT_ERR_PERMISSION_FAILED = 201, + BT_ERR_SYSTEM_PERMISSION_FAILED = 202, + BT_ERR_INVALID_PARAM = 401, + BT_ERR_API_NOT_SUPPORT = 801, + + // Customized error codes + BT_SUCCESS = 0, + + BT_ERR_BASE_SYSCAP = 2900000, + BT_ERR_SERVICE_DISCONNECTED = BT_ERR_BASE_SYSCAP + 1, + BT_ERR_UNBONDED_DEVICE = BT_ERR_BASE_SYSCAP + 2, + BT_ERR_INVALID_STATE = BT_ERR_BASE_SYSCAP + 3, + BT_ERR_PROFILE_DISABLED = BT_ERR_BASE_SYSCAP + 4, + BT_ERR_DEVICE_DISCONNECTED = BT_ERR_BASE_SYSCAP + 5, + BT_ERR_MAX_CONNECTION = BT_ERR_BASE_SYSCAP + 6, + + BT_ERR_INTERNAL_ERROR = BT_ERR_BASE_SYSCAP + 99, + BT_ERR_IPC_TRANS_FAILED = BT_ERR_BASE_SYSCAP + 100, + 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_SPP_SERVER_STATE = BT_ERR_BASE_SYSCAP + 1050, + BT_ERR_SPP_BUSY = BT_ERR_BASE_SYSCAP + 1051, + BT_ERR_SPP_DEVICE_NOT_FOUND = BT_ERR_BASE_SYSCAP + 1052, + BT_ERR_SPP_IO = BT_ERR_BASE_SYSCAP + 1054, + + // will deprected + NO_ERROR = 0, + ERR_INVALID_STATE = 1, + ERR_INVALID_VALUE = 2, + ERROR = 3, }; + } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/src/bluetooth_a2dp_snk.cpp b/frameworks/inner/src/bluetooth_a2dp_snk.cpp index b96084f4..506efd18 100644 --- a/frameworks/inner/src/bluetooth_a2dp_snk.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_snk.cpp @@ -251,7 +251,7 @@ int A2dpSink::GetPlayingState(const BluetoothRemoteDevice &device) const int ret = RET_BAD_STATUS; if (pimpl->proxy_ != nullptr && IS_BT_ENABLED()) { - ret = pimpl->proxy_->GetPlayingState(RawAddress(device.GetDeviceAddr())); + pimpl->proxy_->GetPlayingState(RawAddress(device.GetDeviceAddr()), ret); } else { HILOGI("proxy or bt disable."); } @@ -259,6 +259,23 @@ int A2dpSink::GetPlayingState(const BluetoothRemoteDevice &device) const return ret; } +int A2dpSink::GetPlayingState(const BluetoothRemoteDevice &device, int &state) const +{ + HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + + if (!device.IsValidBluetoothRemoteDevice()) { + HILOGI("input parameter error."); + return BT_ERR_INVALID_PARAM; + } + + if (pimpl->proxy_ != nullptr && IS_BT_ENABLED()) { + return pimpl->proxy_->GetPlayingState(RawAddress(device.GetDeviceAddr()), state); + } else { + HILOGI("proxy or bt disable."); + return BT_ERR_SERVICE_DISCONNECTED; + } +} + bool A2dpSink::Connect(const BluetoothRemoteDevice &device) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); @@ -275,7 +292,7 @@ bool A2dpSink::Connect(const BluetoothRemoteDevice &device) HILOGI("proxy or bt disable."); return false; } - return (RET_NO_ERROR == ret); + return (ret == RET_NO_ERROR); } bool A2dpSink::Disconnect(const BluetoothRemoteDevice &device) @@ -294,7 +311,7 @@ bool A2dpSink::Disconnect(const BluetoothRemoteDevice &device) HILOGI("proxy or bt disable."); return false; } - return (RET_NO_ERROR == ret); + return (ret == RET_NO_ERROR); } A2dpSink *A2dpSink::GetProfile() @@ -308,8 +325,9 @@ bool A2dpSink::SetConnectStrategy(const BluetoothRemoteDevice &device, int strat { HILOGI("enter, device: %{public}s, strategy: %{public}d", GET_ENCRYPT_ADDR(device), strategy); - if ((!device.IsValidBluetoothRemoteDevice()) || (((int)BTStrategyType::CONNECTION_ALLOWED != strategy) && - ((int)BTStrategyType::CONNECTION_FORBIDDEN != strategy))) { + if ((!device.IsValidBluetoothRemoteDevice()) || ( + (strategy != static_cast(BTStrategyType::CONNECTION_ALLOWED)) && + (strategy != static_cast(BTStrategyType::CONNECTION_FORBIDDEN)))) { HILOGI("input parameter error."); return false; } @@ -322,7 +340,7 @@ bool A2dpSink::SetConnectStrategy(const BluetoothRemoteDevice &device, int strat return false; } - return (RET_NO_ERROR == ret); + return (ret == RET_NO_ERROR); } int A2dpSink::GetConnectStrategy(const BluetoothRemoteDevice &device) const @@ -361,7 +379,7 @@ bool A2dpSink::SendDelay(const BluetoothRemoteDevice &device, uint16_t delayValu return false; } - return (RET_NO_ERROR == ret); + return (ret == RET_NO_ERROR); } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/inner/src/bluetooth_a2dp_src.cpp b/frameworks/inner/src/bluetooth_a2dp_src.cpp index 7c680b8f..ead99bcf 100644 --- a/frameworks/inner/src/bluetooth_a2dp_src.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_src.cpp @@ -269,7 +269,7 @@ int A2dpSource::GetDeviceState(const BluetoothRemoteDevice &device) const return ret; } -int A2dpSource::GetPlayingState(const BluetoothRemoteDevice &device) const +int32_t A2dpSource::GetPlayingState(const BluetoothRemoteDevice &device) const { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); @@ -280,7 +280,7 @@ int A2dpSource::GetPlayingState(const BluetoothRemoteDevice &device) const int ret = RET_NO_ERROR; if (pimpl->proxy_ != nullptr && IS_BT_ENABLED()) { - ret = pimpl->proxy_->GetPlayingState(RawAddress(device.GetDeviceAddr())); + pimpl->proxy_->GetPlayingState(RawAddress(device.GetDeviceAddr()), ret); } else { HILOGI("proxy or bt disable."); return RET_BAD_STATUS; @@ -289,47 +289,77 @@ int A2dpSource::GetPlayingState(const BluetoothRemoteDevice &device) const return ret; } -bool A2dpSource::Connect(const BluetoothRemoteDevice &device) +int32_t A2dpSource::GetPlayingState(const BluetoothRemoteDevice &device, int &state) const +{ + HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + + if (!device.IsValidBluetoothRemoteDevice()) { + HILOGI("input parameter error."); + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth if off."); + return BT_ERR_INVALID_STATE; + } + if (pimpl->proxy_ != nullptr) { + return pimpl->proxy_->GetPlayingState(RawAddress(device.GetDeviceAddr()), state); + } else { + HILOGI("proxy is nullptr."); + return BT_ERR_INTERNAL_ERROR; + } +} + +int32_t A2dpSource::Connect(const BluetoothRemoteDevice &device) { HILOGI("a2dp connect remote device: %{public}s", GET_ENCRYPT_ADDR(device)); if (!device.IsValidBluetoothRemoteDevice()) { HILOGI("input parameter error."); - return false; + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth if off."); + return BT_ERR_INVALID_STATE; } - if (!device.GetDeviceClass().IsProfileSupported(BluetoothDevice::PROFILE_A2DP)) { + int cod = 0; + int32_t err = device.GetDeviceClass(cod); + if (err != BT_SUCCESS) { + HILOGE("GetDeviceClass Failed."); + return BT_ERR_INTERNAL_ERROR; + } + BluetoothDeviceClass devClass = BluetoothDeviceClass(cod); + if (!devClass.IsProfileSupported(BluetoothDevice::PROFILE_A2DP)) { HILOGE("a2dp connect failed. The remote device does not support A2DP service."); - return false; + return BT_ERR_INTERNAL_ERROR; } - int ret = RET_NO_ERROR; - if (pimpl->proxy_ != nullptr && IS_BT_ENABLED()) { - ret= pimpl->proxy_->Connect(RawAddress(device.GetDeviceAddr())); + if (pimpl->proxy_ != nullptr) { + return pimpl->proxy_->Connect(RawAddress(device.GetDeviceAddr())); } else { - HILOGI("a2dp connect failed. proxy_ is null or bt is disabled."); - return false; + HILOGI("a2dp connect failed. proxy_ is nullptr."); + return BT_ERR_INTERNAL_ERROR; } - return (RET_NO_ERROR == ret); } -bool A2dpSource::Disconnect(const BluetoothRemoteDevice &device) +int32_t A2dpSource::Disconnect(const BluetoothRemoteDevice &device) { HILOGI("a2dp disconnect remote device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (!device.IsValidBluetoothRemoteDevice()) { HILOGI("input parameter error."); - return false; + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth if off."); + return BT_ERR_INVALID_STATE; } - int ret = RET_NO_ERROR; if (pimpl->proxy_ != nullptr && IS_BT_ENABLED()) { - ret = pimpl->proxy_->Disconnect(RawAddress(device.GetDeviceAddr())); + return pimpl->proxy_->Disconnect(RawAddress(device.GetDeviceAddr())); } else { - HILOGI("a2dp disconnect failed. proxy_ is null or bt is disabled."); - return false; + HILOGI("a2dp disconnect failed. proxy_ is nullptr."); + return BT_ERR_INTERNAL_ERROR; } - return (RET_NO_ERROR == ret); } A2dpSource *A2dpSource::GetProfile() @@ -353,7 +383,7 @@ int A2dpSource::SetActiveSinkDevice(const BluetoothRemoteDevice &device) ret = pimpl->proxy_->SetActiveSinkDevice(RawAddress(device.GetDeviceAddr())); } else { HILOGI("proxy or bt disable."); - return false; + return RET_BAD_STATUS; } return ret; diff --git a/frameworks/inner/src/bluetooth_ble_advertiser.cpp b/frameworks/inner/src/bluetooth_ble_advertiser.cpp index d0b057c0..85fbd565 100644 --- a/frameworks/inner/src/bluetooth_ble_advertiser.cpp +++ b/frameworks/inner/src/bluetooth_ble_advertiser.cpp @@ -16,8 +16,11 @@ #include "bluetooth_ble_advertise_callback_stub.h" #include "bluetooth_def.h" +#include "bluetooth_errorcode.h" +#include "bluetooth_host.h" #include "bluetooth_log.h" #include "bluetooth_observer_map.h" +#include "bluetooth_utils.h" #include "i_bluetooth_ble_advertiser.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -31,9 +34,12 @@ using namespace OHOS::bluetooth; struct BleAdvertiser::impl { impl(); ~impl(); + void ConvertBleAdvertiserData(const BleAdvertiserData &data, BluetoothBleAdvertiserData &outData); + class BluetoothBleAdvertiserCallbackImp : public BluetoothBleAdvertiseCallbackStub { public: - BluetoothBleAdvertiserCallbackImp(BleAdvertiser::impl &bleAdvertiser) : bleAdvertiser_(bleAdvertiser){}; + explicit BluetoothBleAdvertiserCallbackImp(BleAdvertiser::impl &bleAdvertiser) + : bleAdvertiser_(bleAdvertiser){}; ~BluetoothBleAdvertiserCallbackImp() {} @@ -125,117 +131,134 @@ BleAdvertiser::BleAdvertiser() : pimpl(nullptr) BleAdvertiser::~BleAdvertiser() {} -void BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const BleAdvertiserData &advData, - const BleAdvertiserData &scanResponse, BleAdvertiseCallback &callback) +void BleAdvertiser::impl::ConvertBleAdvertiserData(const BleAdvertiserData &data, BluetoothBleAdvertiserData &outData) { - HILOGI("enter"); - if (pimpl->proxy_ != nullptr) { - BluetoothBleAdvertiserSettings setting; - setting.SetConnectable(settings.IsConnectable()); - setting.SetInterval(settings.GetInterval()); - setting.SetLegacyMode(settings.IsLegacyMode()); - setting.SetTxPower(settings.GetTxPower()); - BluetoothBleAdvertiserData bleAdvertiserData; - bleAdvertiserData.SetAdvFlag(advData.GetAdvFlag()); - std::map manufacturerData = advData.GetManufacturerData(); - for (auto iter = manufacturerData.begin(); iter != manufacturerData.end(); iter++) { - bleAdvertiserData.AddManufacturerData(iter->first, iter->second); - } - std::map serviceData = advData.GetServiceData(); - for (auto it = serviceData.begin(); it != serviceData.end(); it++) { - bleAdvertiserData.AddServiceData(Uuid::ConvertFromString(it->first.ToString()), it->second); - } - std::vector serviceUuids = advData.GetServiceUuids(); - for (auto it = serviceUuids.begin(); it != serviceUuids.end(); it++) { - bleAdvertiserData.AddServiceUuid(Uuid::ConvertFromString(it->ToString())); - } - BluetoothBleAdvertiserData bleScanResponse; - manufacturerData = scanResponse.GetManufacturerData(); - for (auto it = manufacturerData.begin(); it != manufacturerData.end(); it++) { - bleScanResponse.AddManufacturerData(it->first, it->second); - } - serviceData = scanResponse.GetServiceData(); - for (auto it = serviceData.begin(); it != serviceData.end(); it++) { - bleScanResponse.AddServiceData(Uuid::ConvertFromString(it->first.ToString()), it->second); - } - serviceUuids = scanResponse.GetServiceUuids(); - for (auto it = serviceUuids.begin(); it != serviceUuids.end(); it++) { - bleScanResponse.AddServiceUuid(Uuid::ConvertFromString(it->ToString())); - } - int32_t advHandle = BLE_INVALID_ADVERTISING_HANDLE; - if (pimpl->callbacks_.IsExistAdvertiserCallback(&callback, advHandle)) { - pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, false); - } else { - advHandle = pimpl->proxy_->GetAdvertiserHandle(); - if (advHandle == BLE_INVALID_ADVERTISING_HANDLE) { - HILOGE("Invalid advertising handle"); - callback.OnStartResultEvent(BLE_INVALID_ADVERTISING_HANDLE); - return; - } - pimpl->callbacks_.Register(advHandle, &callback); - pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, false); - } + std::map manufacturerData = data.GetManufacturerData(); + for (auto iter = manufacturerData.begin(); iter != manufacturerData.end(); iter++) { + outData.AddManufacturerData(iter->first, iter->second); + } + std::map serviceData = data.GetServiceData(); + for (auto it = serviceData.begin(); it != serviceData.end(); it++) { + outData.AddServiceData(Uuid::ConvertFromString(it->first.ToString()), it->second); + } + std::vector serviceUuids = data.GetServiceUuids(); + for (auto it = serviceUuids.begin(); it != serviceUuids.end(); it++) { + outData.AddServiceUuid(Uuid::ConvertFromString(it->ToString())); } } -void BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const std::vector &advData, - const std::vector &scanResponse, BleAdvertiseCallback &callback) +int BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const BleAdvertiserData &advData, + const BleAdvertiserData &scanResponse, BleAdvertiseCallback &callback) { + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; + } + HILOGI("enter"); - if (pimpl->proxy_ != nullptr) { - BluetoothBleAdvertiserSettings setting; - setting.SetConnectable(settings.IsConnectable()); - setting.SetInterval(settings.GetInterval()); - setting.SetLegacyMode(settings.IsLegacyMode()); - setting.SetTxPower(settings.GetTxPower()); - - BluetoothBleAdvertiserData bleAdvertiserData; - std::string dataPayload; - bleAdvertiserData.SetAdvFlag(0); - dataPayload.assign(advData.begin(), advData.end()); - bleAdvertiserData.SetPayload(dataPayload); - - std::string respPayload; - BluetoothBleAdvertiserData bleScanResponse; - respPayload.assign(scanResponse.begin(), scanResponse.end()); - bleScanResponse.SetPayload(respPayload); - int32_t advHandle = BLE_INVALID_ADVERTISING_HANDLE; - if (pimpl->callbacks_.IsExistAdvertiserCallback(&callback, advHandle)) { - pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, true); - } else { - advHandle = pimpl->proxy_->GetAdvertiserHandle(); - if (advHandle == BLE_INVALID_ADVERTISING_HANDLE) { - HILOGE("Invalid advertising handle"); - callback.OnStartResultEvent(BLE_INVALID_ADVERTISING_HANDLE); - return; - } - pimpl->callbacks_.Register(advHandle, &callback); - pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, true); + + BluetoothBleAdvertiserSettings setting; + setting.SetConnectable(settings.IsConnectable()); + setting.SetInterval(settings.GetInterval()); + setting.SetLegacyMode(settings.IsLegacyMode()); + setting.SetTxPower(settings.GetTxPower()); + + BluetoothBleAdvertiserData bleAdvertiserData; + BluetoothBleAdvertiserData bleScanResponse; + bleAdvertiserData.SetAdvFlag(advData.GetAdvFlag()); + pimpl->ConvertBleAdvertiserData(advData, bleAdvertiserData); + pimpl->ConvertBleAdvertiserData(scanResponse, bleScanResponse); + + int ret = 0; + int32_t advHandle = BLE_INVALID_ADVERTISING_HANDLE; + if (pimpl->callbacks_.IsExistAdvertiserCallback(&callback, advHandle)) { + ret = pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, false); + } else { + advHandle = pimpl->proxy_->GetAdvertiserHandle(); + if (advHandle == BLE_INVALID_ADVERTISING_HANDLE) { + HILOGE("Invalid advertising handle"); + callback.OnStartResultEvent(BLE_INVALID_ADVERTISING_HANDLE); + return BT_ERR_INTERNAL_ERROR; } + pimpl->callbacks_.Register(advHandle, &callback); + ret = pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, false); } + return ret; } -void BleAdvertiser::StopAdvertising(BleAdvertiseCallback &callback) +int BleAdvertiser::StartAdvertising(const BleAdvertiserSettings &settings, const std::vector &advData, + const std::vector &scanResponse, BleAdvertiseCallback &callback) { + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; + } + HILOGI("enter"); - if (pimpl->proxy_ != nullptr) { - uint8_t advHandle = pimpl->callbacks_.GetAdvertiserHandle(&callback); + + BluetoothBleAdvertiserSettings setting; + setting.SetConnectable(settings.IsConnectable()); + setting.SetInterval(settings.GetInterval()); + setting.SetLegacyMode(settings.IsLegacyMode()); + setting.SetTxPower(settings.GetTxPower()); + + BluetoothBleAdvertiserData bleAdvertiserData; + bleAdvertiserData.SetPayload(std::string(advData.begin(), advData.end())); + bleAdvertiserData.SetAdvFlag(0); + BluetoothBleAdvertiserData bleScanResponse; + bleScanResponse.SetPayload(std::string(scanResponse.begin(), scanResponse.end())); + + int ret = 0; + int32_t advHandle = BLE_INVALID_ADVERTISING_HANDLE; + if (pimpl->callbacks_.IsExistAdvertiserCallback(&callback, advHandle)) { + ret = pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, true); + } else { + advHandle = pimpl->proxy_->GetAdvertiserHandle(); if (advHandle == BLE_INVALID_ADVERTISING_HANDLE) { HILOGE("Invalid advertising handle"); - return; + callback.OnStartResultEvent(BLE_INVALID_ADVERTISING_HANDLE); + return BT_ERR_INTERNAL_ERROR; } + pimpl->callbacks_.Register(advHandle, &callback); + ret = pimpl->proxy_->StartAdvertising(setting, bleAdvertiserData, bleScanResponse, advHandle, true); + } + return ret; +} - BleAdvertiseCallback *observer = pimpl->callbacks_.GetAdvertiserObserver(advHandle); - if (observer != nullptr) { - pimpl->callbacks_.Deregister(observer); - } +int BleAdvertiser::StopAdvertising(BleAdvertiseCallback &callback) +{ + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; + } - pimpl->proxy_->StopAdvertising(advHandle); + HILOGI("enter"); + int ret = 0; + uint8_t advHandle = pimpl->callbacks_.GetAdvertiserHandle(&callback); + if (advHandle == BLE_INVALID_ADVERTISING_HANDLE) { + HILOGE("Invalid advertising handle"); + return BT_ERR_INTERNAL_ERROR; } + + BleAdvertiseCallback *observer = pimpl->callbacks_.GetAdvertiserObserver(advHandle); + if (observer != nullptr) { + pimpl->callbacks_.Deregister(observer); + } + + ret = pimpl->proxy_->StopAdvertising(advHandle); + return ret; } void BleAdvertiser::Close(BleAdvertiseCallback &callback) { + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return; + } + HILOGI("enter"); if (pimpl->proxy_ != nullptr) { uint8_t advHandle = pimpl->callbacks_.GetAdvertiserHandle(&callback); diff --git a/frameworks/inner/src/bluetooth_ble_central_manager.cpp b/frameworks/inner/src/bluetooth_ble_central_manager.cpp index 749ffa2f..2b2a5e28 100644 --- a/frameworks/inner/src/bluetooth_ble_central_manager.cpp +++ b/frameworks/inner/src/bluetooth_ble_central_manager.cpp @@ -15,8 +15,11 @@ #include "bluetooth_ble_central_manager.h" #include "bluetooth_ble_central_manager_callback_stub.h" #include "bluetooth_def.h" +#include "bluetooth_errorcode.h" +#include "bluetooth_host.h" #include "bluetooth_log.h" #include "bluetooth_observer_list.h" +#include "bluetooth_utils.h" #include "i_bluetooth_ble_central_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -28,34 +31,33 @@ struct BleCentralManager::impl { ~impl(); void BindServer(); - bool MatchesScanFilters(BluetoothBleScanResult result); - bool MatchesScanFilter(BluetoothBleScanFilter filter, BluetoothBleScanResult result); - bool MatchesAddrAndName(BluetoothBleScanFilter filter, BluetoothBleScanResult result); - bool MatchesServiceUuids(BluetoothBleScanFilter filter, BluetoothBleScanResult result); + bool MatchesScanFilters(const BluetoothBleScanResult &result); + bool MatchesScanFilter(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result); + bool MatchesAddrAndName(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result); + bool MatchesServiceUuids(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result); bool MatchesUuid(bluetooth::Uuid filterUuid, bluetooth::Uuid uuid, bluetooth::Uuid uuidMask); - bool MatchesManufacturerDatas(BluetoothBleScanFilter filter, BluetoothBleScanResult result); - bool MatchesServiceDatas(BluetoothBleScanFilter filter, BluetoothBleScanResult result); + bool MatchesManufacturerDatas(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result); + bool MatchesServiceDatas(const BluetoothBleScanFilter &filter, const BluetoothBleScanResult &result); std::string ParseServiceData(bluetooth::Uuid uuid, std::string data); bool MatchesData(std::vector fData, std::string rData, std::vector dataMask); class BluetoothBleCentralManagerCallbackImp : public BluetoothBleCentralManagerCallBackStub { public: - BluetoothBleCentralManagerCallbackImp(BleCentralManager::impl &bleCentralManger) - : bleCentralManger_(bleCentralManger) {}; + explicit BluetoothBleCentralManagerCallbackImp(BleCentralManager::impl &bleCentralManger) + : bleCentralManger_(bleCentralManger){}; ~BluetoothBleCentralManagerCallbackImp() override = default; void OnScanCallback(const BluetoothBleScanResult &result) override { { std::lock_guard lock(bleCentralManger_.blesCanFiltersMutex_); - if (!bleCentralManger_.bleScanFilters_.empty() && bleCentralManger_.IsNeedFilterMatches_ - && !bleCentralManger_.MatchesScanFilters(result)) { - HILOGE("the result does not matche the filter, ignore"); + if (!bleCentralManger_.bleScanFilters_.empty() && bleCentralManger_.IsNeedFilterMatches_ && + !bleCentralManger_.MatchesScanFilters(result)) { return; } } bleCentralManger_.callbacks_.ForEach([&result](std::shared_ptr observer) { - BluetoothBleScanResult tempResult = result; + BluetoothBleScanResult tempResult(result); BleScanResult scanResult; for (auto &manufacturerData : tempResult.GetManufacturerData()) { scanResult.AddManufacturerData(manufacturerData.first, manufacturerData.second); @@ -77,6 +79,7 @@ struct BleCentralManager::impl { BluetoothRemoteDevice device(tempResult.GetPeripheralDevice().GetAddress(), BT_TRANSPORT_BLE); scanResult.SetPeripheralDevice(device); scanResult.SetPayload(tempResult.GetPayload()); + scanResult.SetName(tempResult.GetName()); observer->OnScanCallback(scanResult); }); @@ -171,10 +174,9 @@ BleCentralManager::impl::impl() proxy_->RegisterBleCentralManagerCallback(callbackImp_); } -bool BleCentralManager::impl::MatchesScanFilters(BluetoothBleScanResult result) +bool BleCentralManager::impl::MatchesScanFilters(const BluetoothBleScanResult &result) { - HILOGI("enter"); - for (auto filter : bleScanFilters_) { + for (const auto &filter : bleScanFilters_) { if (!MatchesScanFilter(filter, result)) { continue; } @@ -183,7 +185,8 @@ bool BleCentralManager::impl::MatchesScanFilters(BluetoothBleScanResult result) return false; } -bool BleCentralManager::impl::MatchesScanFilter(BluetoothBleScanFilter filter, BluetoothBleScanResult result) +bool BleCentralManager::impl::MatchesScanFilter(const BluetoothBleScanFilter &filter, + const BluetoothBleScanResult &result) { if (!MatchesAddrAndName(filter, result)) { return false; @@ -204,24 +207,22 @@ bool BleCentralManager::impl::MatchesScanFilter(BluetoothBleScanFilter filter, B return true; } -bool BleCentralManager::impl::MatchesAddrAndName(BluetoothBleScanFilter filter, BluetoothBleScanResult result) +bool BleCentralManager::impl::MatchesAddrAndName(const BluetoothBleScanFilter &filter, + const BluetoothBleScanResult &result) { std::string address = result.GetPeripheralDevice().GetAddress(); if (address.empty()) { return false; } - BluetoothRemoteDevice device(address, BT_TRANSPORT_BLE); - std::string deviceId = filter.GetDeviceId(); if (!deviceId.empty() && deviceId != address) { return false; } std::string name = filter.GetName(); - // To avoid to call IPC if no needed. if (!name.empty()) { - std::string rName = device.GetDeviceName(); + std::string rName = result.GetName(); if (rName.empty() || rName != name) { return false; } @@ -230,7 +231,8 @@ bool BleCentralManager::impl::MatchesAddrAndName(BluetoothBleScanFilter filter, return true; } -bool BleCentralManager::impl::MatchesServiceUuids(BluetoothBleScanFilter filter, BluetoothBleScanResult result) +bool BleCentralManager::impl::MatchesServiceUuids(const BluetoothBleScanFilter &filter, + const BluetoothBleScanResult &result) { std::vector rUuids = result.GetServiceUuids(); if (rUuids.empty()) { @@ -287,7 +289,8 @@ bool BleCentralManager::impl::MatchesUuid(bluetooth::Uuid filterUuid, bluetooth: return true; } -bool BleCentralManager::impl::MatchesManufacturerDatas(BluetoothBleScanFilter filter, BluetoothBleScanResult result) +bool BleCentralManager::impl::MatchesManufacturerDatas(const BluetoothBleScanFilter &filter, + const BluetoothBleScanResult &result) { uint16_t manufacturerId = filter.GetManufacturerId(); std::vector data = filter.GetManufactureData(); @@ -309,7 +312,8 @@ bool BleCentralManager::impl::MatchesManufacturerDatas(BluetoothBleScanFilter fi return false; } -bool BleCentralManager::impl::MatchesServiceDatas(BluetoothBleScanFilter filter, BluetoothBleScanResult result) +bool BleCentralManager::impl::MatchesServiceDatas(const BluetoothBleScanFilter &filter, + const BluetoothBleScanResult &result) { std::vector data = filter.GetServiceData(); if (data.size() == 0) { @@ -411,86 +415,103 @@ BleCentralManager::~BleCentralManager() callback_ = nullptr; } -void BleCentralManager::StartScan() +int BleCentralManager::StartScan() { - HILOGI("StartScan without param."); - if (pimpl->proxy_ != nullptr) { - pimpl->proxy_->StartScan(); + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; } + + HILOGI("StartScan without param."); + return pimpl->proxy_->StartScan(); } -void BleCentralManager::StartScan(const BleScanSettings &settings) +int BleCentralManager::StartScan(const BleScanSettings &settings) { - HILOGI("StartScan with params."); - if (pimpl->proxy_ != nullptr) { - BluetoothBleScanSettings setting; - // not use report delay scan. settings.GetReportDelayMillisValue() - setting.SetReportDelay(0); - setting.SetScanMode(settings.GetScanMode()); - setting.SetLegacy(settings.GetLegacy()); - setting.SetPhy(settings.GetPhy()); - pimpl->proxy_->StartScan(setting); + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; } + + HILOGI("StartScan with params."); + BluetoothBleScanSettings setting; + // not use report delay scan. settings.GetReportDelayMillisValue() + setting.SetReportDelay(0); + setting.SetScanMode(settings.GetScanMode()); + setting.SetLegacy(settings.GetLegacy()); + setting.SetPhy(settings.GetPhy()); + return pimpl->proxy_->StartScan(setting); } -void BleCentralManager::StopScan() +int BleCentralManager::StopScan() { + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; + } + HILOGI("clientId: %{public}d", clientId_); std::lock_guard lock(pimpl->blesCanFiltersMutex_); - if (pimpl->proxy_ != nullptr) { - pimpl->proxy_->StopScan(); - if (clientId_ != 0) { - pimpl->proxy_->RemoveScanFilter(clientId_); - clientId_ = 0; - } - pimpl->bleScanFilters_.clear(); - pimpl->IsNeedFilterMatches_ = true; + + int ret = pimpl->proxy_->StopScan(); + if (clientId_ != 0) { + pimpl->proxy_->RemoveScanFilter(clientId_); + clientId_ = 0; } + pimpl->bleScanFilters_.clear(); + pimpl->IsNeedFilterMatches_ = true; + return ret; } -void BleCentralManager::ConfigScanFilter(const std::vector &filters) +int BleCentralManager::ConfigScanFilter(const std::vector &filters) { - HILOGI("enter"); + CHECK_PROXY_RETURN(pimpl->proxy_); + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled"); + return BT_ERR_INVALID_STATE; + } + std::lock_guard lock(pimpl->blesCanFiltersMutex_); - if (pimpl->proxy_ != nullptr) { - std::vector bluetoothBleScanFilters; - for (auto filter : filters) { - BluetoothBleScanFilter scanFilter; - scanFilter.SetDeviceId(filter.GetDeviceId()); - scanFilter.SetName(filter.GetName()); - if (filter.HasServiceUuid()) { - scanFilter.SetServiceUuid(bluetooth::Uuid::ConvertFromString( - filter.GetServiceUuid().ToString())); - } - if (filter.HasServiceUuidMask()) { - scanFilter.SetServiceUuidMask(bluetooth::Uuid::ConvertFromString( - filter.GetServiceUuidMask().ToString())); - } - if (filter.HasSolicitationUuid()) { - scanFilter.SetServiceSolicitationUuid(bluetooth::Uuid::ConvertFromString( - filter.GetServiceSolicitationUuid().ToString())); - } - if (filter.HasSolicitationUuidMask()) { - scanFilter.SetServiceSolicitationUuidMask(bluetooth::Uuid::ConvertFromString( - filter.GetServiceSolicitationUuidMask().ToString())); - } - scanFilter.SetServiceData(filter.GetServiceData()); - scanFilter.SetServiceDataMask(filter.GetServiceDataMask()); - scanFilter.SetManufacturerId(filter.GetManufacturerId()); - scanFilter.SetManufactureData(filter.GetManufactureData()); - scanFilter.SetManufactureDataMask(filter.GetManufactureDataMask()); - bluetoothBleScanFilters.push_back(scanFilter); - pimpl->bleScanFilters_.push_back(scanFilter); + std::vector bluetoothBleScanFilters; + for (auto filter : filters) { + BluetoothBleScanFilter scanFilter; + scanFilter.SetDeviceId(filter.GetDeviceId()); + scanFilter.SetName(filter.GetName()); + if (filter.HasServiceUuid()) { + scanFilter.SetServiceUuid(bluetooth::Uuid::ConvertFromString( + filter.GetServiceUuid().ToString())); } - clientId_ = pimpl->proxy_->ConfigScanFilter(clientId_, bluetoothBleScanFilters); - - if (filters.empty()) { - HILOGE("filters is empty can not config"); - pimpl->IsNeedFilterMatches_ = false; + if (filter.HasServiceUuidMask()) { + scanFilter.SetServiceUuidMask(bluetooth::Uuid::ConvertFromString( + filter.GetServiceUuidMask().ToString())); } - } else { - HILOGI("proxy_ is nullptr"); + if (filter.HasSolicitationUuid()) { + scanFilter.SetServiceSolicitationUuid(bluetooth::Uuid::ConvertFromString( + filter.GetServiceSolicitationUuid().ToString())); + } + if (filter.HasSolicitationUuidMask()) { + scanFilter.SetServiceSolicitationUuidMask(bluetooth::Uuid::ConvertFromString( + filter.GetServiceSolicitationUuidMask().ToString())); + } + scanFilter.SetServiceData(filter.GetServiceData()); + scanFilter.SetServiceDataMask(filter.GetServiceDataMask()); + scanFilter.SetManufacturerId(filter.GetManufacturerId()); + scanFilter.SetManufactureData(filter.GetManufactureData()); + scanFilter.SetManufactureDataMask(filter.GetManufactureDataMask()); + bluetoothBleScanFilters.push_back(scanFilter); + pimpl->bleScanFilters_.push_back(scanFilter); + } + clientId_ = pimpl->proxy_->ConfigScanFilter(clientId_, bluetoothBleScanFilters); + HILOGI("clientId: %{public}d", clientId_); + + if (filters.empty()) { + HILOGI("filters is empty can not config"); + pimpl->IsNeedFilterMatches_ = false; } + return BT_SUCCESS; } BleScanResult::BleScanResult() @@ -579,6 +600,15 @@ void BleScanResult::SetAdvertiseFlag(uint8_t flag) advertiseFlag_ = flag; } +void BleScanResult::SetName(const std::string &name) +{ + name_ = name; +} +std::string BleScanResult::GetName(void) +{ + return name_; +} + BleScanSettings::BleScanSettings() {} diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 9720d333..45696e83 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -17,6 +17,7 @@ #include #include +#include "bluetooth_errorcode.h" #include "bluetooth_def.h" #include "bluetooth_gatt_client.h" #include "bluetooth_gatt_client_proxy.h" @@ -107,6 +108,7 @@ struct GattClient::impl { void GetServices(); int GetTransport(int &transport); void CleanConnectionInfo(); + int CheckInterface(void); class GattClientDeathRecipient; sptr deathRecipient_; @@ -297,6 +299,19 @@ GattClient::impl::~impl() } } +int GattClient::impl::CheckInterface(void) +{ + if (proxy_ == nullptr) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_INTERNAL_ERROR; + } + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled."); + return BT_ERR_INVALID_STATE; + } + return BT_SUCCESS; +} + int GattClient::impl::DiscoverStart() { { @@ -308,15 +323,15 @@ int GattClient::impl::DiscoverStart() } if (!isRegisterSucceeded_) { - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } - int result = GattStatus::GATT_FAILURE; + int result = BT_ERR_INTERNAL_ERROR; if (!proxy_) { HILOGE("proxy_ is null"); } else { result = proxy_->DiscoveryServices(applicationId_); - if (GattStatus::GATT_SUCCESS != result) { - DiscoverComplete(GattStatus::GATT_FAILURE); + if (result != BT_SUCCESS) { + DiscoverComplete(BT_ERR_INTERNAL_ERROR); } } return result; @@ -467,17 +482,17 @@ GattClient::~GattClient() int GattClient::Connect(GattClientCallback &callback, bool isAutoConnect, int transport) { HILOGI("enter, isAutoConnect: %{public}d, transport: %{public}d", isAutoConnect, transport); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lock(pimpl->connStateMutex_); if (pimpl->connectionState_ == static_cast(BTConnectState::CONNECTED)) { HILOGE("Already connected"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } HILOGI("isRegisterSucceeded: %{public}d", pimpl->isRegisterSucceeded_); if (pimpl->isRegisterSucceeded_) { - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } return pimpl->proxy_->Connect(pimpl->applicationId_, isAutoConnect); } pimpl->callback_ = &callback; @@ -489,30 +504,27 @@ int GattClient::Connect(GattClientCallback &callback, bool isAutoConnect, int tr if ((transport == GATT_TRANSPORT_TYPE_LE && !IS_BLE_ENABLED()) || (transport == GATT_TRANSPORT_TYPE_CLASSIC && !IS_BT_ENABLED())) { HILOGE("Unsupported mode"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } if (transport == GATT_TRANSPORT_TYPE_CLASSIC && isAutoConnect) { HILOGE("Unsupported mode"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } if (!pimpl->device_.IsValidBluetoothRemoteDevice()) { HILOGE("Invalid remote device"); - return GattStatus::INVALID_REMOTE_DEVICE; - } - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } + int appId = 0; result = pimpl->proxy_->RegisterApplication( - pimpl->clientCallback_, bluetooth::RawAddress(pimpl->device_.GetDeviceAddr()), transport); - HILOGI("Proxy register application result: %{public}d", result); - if (result > 0) { - pimpl->applicationId_ = result; + pimpl->clientCallback_, bluetooth::RawAddress(pimpl->device_.GetDeviceAddr()), transport, appId); + HILOGI("Proxy register application : %{public}d", appId); + if (result != BT_SUCCESS) { + HILOGE("register application fail"); + return result; + } + if (appId > 0) { + pimpl->applicationId_ = appId; pimpl->isRegisterSucceeded_ = true; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } result = pimpl->proxy_->Connect(pimpl->applicationId_, isAutoConnect); } return result; @@ -521,16 +533,16 @@ int GattClient::Connect(GattClientCallback &callback, bool isAutoConnect, int tr int GattClient::Disconnect() { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lock(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; - } - int result = GattStatus::GATT_FAILURE; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } + int result = BT_ERR_INTERNAL_ERROR; result = pimpl->proxy_->Disconnect(pimpl->applicationId_); return result; } @@ -538,30 +550,33 @@ int GattClient::Disconnect() int GattClient::Close() { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } if (pimpl->isRegisterSucceeded_) { - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::REQUEST_NOT_SUPPORT; - } else { - int32_t result = pimpl->proxy_->DeregisterApplication(pimpl->applicationId_); - HILOGI("result: %{public}d", result); - if (result == RET_NO_ERROR) { - pimpl->isRegisterSucceeded_ = false; - } - return result; + int32_t result = pimpl->proxy_->DeregisterApplication(pimpl->applicationId_); + HILOGI("result: %{public}d", result); + if (result == BT_SUCCESS) { + pimpl->isRegisterSucceeded_ = false; } + return result; } HILOGI("isRegisterSucceeded_ is false"); - return GattStatus::GATT_SUCCESS; + return BT_SUCCESS; } int GattClient::DiscoverServices() { + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } HILOGI("enter"); std::lock_guard lck(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->DiscoverStart(); } @@ -590,26 +605,26 @@ std::vector &GattClient::GetService() int GattClient::ReadCharacteristic(GattCharacteristic &characteristic) { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lock(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } std::lock_guard lck(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return GattStatus::REMOTE_DEVICE_BUSY; + return BT_ERR_INTERNAL_ERROR; } int result = GattStatus::GATT_FAILURE; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } HILOGI("applicationId: %{public}d, handle: 0x%{public}04X", pimpl->applicationId_, characteristic.GetHandle()); result = pimpl->proxy_->ReadCharacteristic( pimpl->applicationId_, (BluetoothGattCharacteristic)bluetooth::Characteristic(characteristic.GetHandle())); HILOGI("result: %{public}d", result); - if (GattStatus::GATT_SUCCESS == result) { + if (result == BT_SUCCESS) { pimpl->requestInformation_.doing_ = true; pimpl->requestInformation_.type_ = REQUEST_TYPE_CHARACTERISTICS_READ; pimpl->requestInformation_.context_.characteristic_ = &characteristic; @@ -620,26 +635,26 @@ int GattClient::ReadCharacteristic(GattCharacteristic &characteristic) int GattClient::ReadDescriptor(GattDescriptor &descriptor) { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lck(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return GattStatus::REMOTE_DEVICE_BUSY; - } - int result = GattStatus::GATT_FAILURE; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } + int result = BT_ERR_INTERNAL_ERROR; HILOGI("applicationId: %{public}d, handle: 0x%{public}04X", pimpl->applicationId_, descriptor.GetHandle()); result = pimpl->proxy_->ReadDescriptor( pimpl->applicationId_, (BluetoothGattDescriptor)bluetooth::Descriptor(descriptor.GetHandle())); HILOGI("result: %{public}d", result); - if (GattStatus::GATT_SUCCESS == result) { + if (result == BT_SUCCESS) { pimpl->requestInformation_.doing_ = true; pimpl->requestInformation_.type_ = REQUEST_TYPE_DESCRIPTOR_READ; pimpl->requestInformation_.context_.descriptor_ = &descriptor; @@ -650,16 +665,16 @@ int GattClient::ReadDescriptor(GattDescriptor &descriptor) int GattClient::RequestBleMtuSize(int mtu) { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lck(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; - } - int result = GattStatus::GATT_FAILURE; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } + int result = BT_ERR_INTERNAL_ERROR; HILOGI("applicationId: %{public}d, mtu: %{public}d", pimpl->applicationId_, mtu); result = pimpl->proxy_->RequestExchangeMtu(pimpl->applicationId_, mtu); HILOGI("result: %{public}d", result); @@ -669,36 +684,36 @@ int GattClient::RequestBleMtuSize(int mtu) int GattClient::SetNotifyCharacteristic(GattCharacteristic &characteristic, bool enable) { HILOGI("handle: 0x%{public}04X, enable: %{public}d", characteristic.GetHandle(), enable); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } static const uint8_t NOTIFICATION[2] = {1, 0}; static const uint8_t DEFAULT_VALUE[2] = {0}; static const size_t CLIENT_CHARACTERISTIC_CONFIGURATION_VALUE_LENGTH = 0x02; std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } auto descriptor = characteristic.GetDescriptor(UUID::FromString("00002902-0000-1000-8000-00805F9B34FB")); if (descriptor == nullptr) { HILOGE("Invalid parameters"); - return GattStatus::INVALID_PARAMETER; + return BT_ERR_INTERNAL_ERROR; } std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGI("Remote device busy"); - return GattStatus::REMOTE_DEVICE_BUSY; + return BT_ERR_INTERNAL_ERROR; } BluetoothGattDescriptor desc(bluetooth::Descriptor(descriptor->GetHandle(), (enable ? NOTIFICATION : DEFAULT_VALUE), CLIENT_CHARACTERISTIC_CONFIGURATION_VALUE_LENGTH)); int result = GattStatus::GATT_FAILURE; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } HILOGI("applicationId: %{public}d", pimpl->applicationId_); result = pimpl->proxy_->WriteDescriptor(pimpl->applicationId_, &desc); HILOGI("result: %{public}d", result); - if (GattStatus::GATT_SUCCESS == result) { + if (result == BT_SUCCESS) { pimpl->requestInformation_.type_ = REQUEST_TYPE_SET_NOTIFY_CHARACTERISTICS; pimpl->requestInformation_.context_.descriptor_ = descriptor; pimpl->requestInformation_.doing_ = true; @@ -709,44 +724,41 @@ int GattClient::SetNotifyCharacteristic(GattCharacteristic &characteristic, bool int GattClient::WriteCharacteristic(GattCharacteristic &characteristic) { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } size_t length = 0; auto &characterValue = characteristic.GetValue(&length); + HILOGI("length:%{public}zu", length); if (characterValue == nullptr || length == 0) { HILOGE("Invalid parameters"); - return GattStatus::INVALID_PARAMETER; + return BT_ERR_INTERNAL_ERROR; } std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return GattStatus::REMOTE_DEVICE_BUSY; + return BT_ERR_INTERNAL_ERROR; } BluetoothGattCharacteristic character( bluetooth::Characteristic(characteristic.GetHandle(), characterValue.get(), length)); - int result = GattStatus::GATT_FAILURE; + int result = BT_ERR_INTERNAL_ERROR; bool withoutRespond = true; - if (characteristic.GetWriteType() == (int)GattCharacteristic::WriteType::SIGNED) { - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } + if (characteristic.GetWriteType() == static_cast(GattCharacteristic::WriteType::SIGNED)) { HILOGI("Signed write"); result = pimpl->proxy_->SignedWriteCharacteristic(pimpl->applicationId_, &character); } else { - withoutRespond = - ((characteristic.GetWriteType() == (int)GattCharacteristic::WriteType::DEFAULT) ? false : true); - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } + withoutRespond = ((characteristic.GetWriteType() == + static_cast(GattCharacteristic::WriteType::DEFAULT)) ? false : true); HILOGI("Write without response"); result = pimpl->proxy_->WriteCharacteristic(pimpl->applicationId_, &character, withoutRespond); } - if (GattStatus::GATT_SUCCESS == result && !withoutRespond) { + if (result && !withoutRespond == GattStatus::GATT_SUCCESS) { HILOGI("successful"); pimpl->requestInformation_.type_ = REQUEST_TYPE_CHARACTERISTICS_WRITE; pimpl->requestInformation_.context_.characteristic_ = &characteristic; @@ -760,31 +772,31 @@ int GattClient::WriteCharacteristic(GattCharacteristic &characteristic) int GattClient::WriteDescriptor(GattDescriptor &descriptor) { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lck(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED) || !pimpl->isRegisterSucceeded_) { HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } size_t length = 0; auto &characterValue = descriptor.GetValue(&length); if (characterValue == nullptr || length == 0) { HILOGE("Invalid parameters"); - return GattStatus::INVALID_PARAMETER; + return BT_ERR_INTERNAL_ERROR; } std::lock_guard lock(pimpl->requestInformation_.mutex_); if (pimpl->requestInformation_.doing_) { HILOGE("Remote device busy"); - return GattStatus::REMOTE_DEVICE_BUSY; + return BT_ERR_INTERNAL_ERROR; } - int result = GattStatus::GATT_FAILURE; + int result = BT_ERR_INTERNAL_ERROR; BluetoothGattDescriptor desc(bluetooth::Descriptor(descriptor.GetHandle(), characterValue.get(), length)); - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } result = pimpl->proxy_->WriteDescriptor(pimpl->applicationId_, &desc); HILOGI("result: %{public}d", result); - if (GattStatus::GATT_SUCCESS == result) { + if (result == BT_SUCCESS) { pimpl->requestInformation_.doing_ = true; pimpl->requestInformation_.type_ = REQUEST_TYPE_DESCRIPTOR_WRITE; pimpl->requestInformation_.context_.descriptor_ = &descriptor; @@ -794,6 +806,10 @@ int GattClient::WriteDescriptor(GattDescriptor &descriptor) int GattClient::RequestConnectionPriority(int connPriority) { + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Not connected"); @@ -806,10 +822,6 @@ int GattClient::RequestConnectionPriority(int connPriority) return GattStatus::INVALID_PARAMETER; } int result = GattStatus::GATT_FAILURE; - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::GATT_FAILURE; - } result = pimpl->proxy_->RequestConnectionPriority(pimpl->applicationId_, connPriority); HILOGI("result: %{public}d", result); return result; diff --git a/frameworks/inner/src/bluetooth_gatt_server.cpp b/frameworks/inner/src/bluetooth_gatt_server.cpp index c1619dcf..29361089 100644 --- a/frameworks/inner/src/bluetooth_gatt_server.cpp +++ b/frameworks/inner/src/bluetooth_gatt_server.cpp @@ -93,9 +93,10 @@ struct GattServer::impl { std::mutex deviceListMutex_; GattService *GetIncludeService(uint16_t handle); bluetooth::GattDevice *FindConnectedDevice(const BluetoothRemoteDevice &device); - GattService BuildService(const BluetoothGattService &svc); + GattService BuildService(const BluetoothGattService &service); void BuildIncludeService(GattService &svc, const std::vector &iSvcs); impl(GattServerCallback &callback, GattServer &server); + int CheckInterface(void); class BluetoothGattServerDeathRecipient; sptr deathRecipient_; sptr proxy_; @@ -337,6 +338,23 @@ private: GattServer &server_; }; +int GattServer::impl::CheckInterface(void) +{ + if (proxy_ == nullptr) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_INTERNAL_ERROR; + } + if (!BluetoothHost::GetDefaultHost().IsBleEnabled()) { + HILOGE("BLE is not enabled."); + return BT_ERR_INVALID_STATE; + } + if (!isRegisterSucceeded_) { + HILOGE("isRegisterSucceeded_ is false."); + return BT_ERR_INTERNAL_ERROR; + } + return BT_SUCCESS; +} + GattService GattServer::impl::BuildService(const BluetoothGattService &service) { GattService gattService(UUID::ConvertFrom128Bits(service.uuid_.ConvertTo128Bits()), @@ -534,13 +552,9 @@ int GattServer::impl::RespondDescriptorWrite(const bluetooth::GattDevice &device int GattServer::AddService(GattService &service) { HILOGI("enter"); - if (!pimpl->proxy_) { - HILOGE("proxy_ is nullptr"); - return GattStatus::REQUEST_NOT_SUPPORT; - } - if (!pimpl->isRegisterSucceeded_) { - HILOGE("isRegisterSucceeded_ is false"); - return GattStatus::REQUEST_NOT_SUPPORT; + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; } BluetoothGattService svc; @@ -575,19 +589,16 @@ int GattServer::AddService(GattService &service) svc.characteristics_.push_back(std::move(c)); } int appId = pimpl->applicationId_; - int result = pimpl->proxy_->AddService(appId, &svc); - HILOGI("appId = %{public}d, result = %{public}d.", appId, result); - return result; + ret = pimpl->proxy_->AddService(appId, &svc); + HILOGI("appId = %{public}d, ret = %{public}d.", appId, ret); + return ret; } void GattServer::ClearServices() { HILOGI("enter"); - if (!pimpl->proxy_) { - HILOGE("proxy_ is nullptr"); - return; - } - if (!pimpl->isRegisterSucceeded_) { + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { return; } int appId = pimpl->applicationId_; @@ -598,30 +609,27 @@ void GattServer::ClearServices() int GattServer::Close() { HILOGI("enter"); - if (pimpl->isRegisterSucceeded_) { - if (!pimpl->proxy_) { - HILOGE("proxy_ is null"); - return GattStatus::REQUEST_NOT_SUPPORT; - } else { - int32_t result = pimpl->proxy_->DeregisterApplication(pimpl->applicationId_); - HILOGI("result: %{public}d", result); - if (result == RET_NO_ERROR) { - pimpl->isRegisterSucceeded_ = false; - } - return result; - } + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; + } + + ret = pimpl->proxy_->DeregisterApplication(pimpl->applicationId_); + HILOGI("ret: %{public}d", ret); + if (ret == BT_SUCCESS) { + pimpl->isRegisterSucceeded_ = false; } - return GattStatus::REQUEST_NOT_SUPPORT; + return ret; } void GattServer::CancelConnection(const BluetoothRemoteDevice &device) { HILOGI("remote device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (!pimpl->proxy_) { - HILOGE("proxy_ is nullptr"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { return; } - if (!device.IsValidBluetoothRemoteDevice() || !pimpl->isRegisterSucceeded_) { + if (!device.IsValidBluetoothRemoteDevice()) { HILOGE("Request not supported"); return; } @@ -637,6 +645,10 @@ void GattServer::CancelConnection(const BluetoothRemoteDevice &device) std::optional> GattServer::GetService(const UUID &uuid, bool isPrimary) { HILOGI("enter"); + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return std::nullopt; + } std::unique_lock lock(pimpl->serviceListMutex_); for (auto &svc : pimpl->gattServices_) { @@ -652,6 +664,7 @@ std::optional> GattServer::GetService(const std::list &GattServer::GetServices() { HILOGI("enter"); + pimpl->CheckInterface(); std::unique_lock lock(pimpl->serviceListMutex_); return pimpl->gattServices_; } @@ -660,23 +673,17 @@ int GattServer::NotifyCharacteristicChanged( { HILOGI("remote device: %{public}s, handle: 0x%{public}04X, confirm: %{public}d", GET_ENCRYPT_ADDR(device), characteristic.GetHandle(), confirm); - if (!pimpl->proxy_) { - HILOGE("proxy_ is nullptr"); - return GattStatus::REQUEST_NOT_SUPPORT; + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; } - if (!device.IsValidBluetoothRemoteDevice() || !pimpl->isRegisterSucceeded_) { + if (!device.IsValidBluetoothRemoteDevice()) { HILOGE("Invalid remote device"); - return GattStatus::INVALID_REMOTE_DEVICE; + return BT_ERR_INTERNAL_ERROR; } - if (pimpl->FindConnectedDevice(device) == nullptr) { HILOGE("No connection to device: %{public}s", GET_ENCRYPT_ADDR(device)); - return GattStatus::REQUEST_NOT_SUPPORT; - } - - if (!pimpl->proxy_ || !pimpl->isRegisterSucceeded_) { - HILOGE("Request not supported"); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } size_t length = 0; @@ -685,56 +692,50 @@ int GattServer::NotifyCharacteristicChanged( BluetoothGattCharacteristic character( bluetooth::Characteristic(characteristic.GetHandle(), characterValue.get(), length)); std::string address = device.GetDeviceAddr(); - int result = pimpl->proxy_->NotifyClient( + ret = pimpl->proxy_->NotifyClient( bluetooth::GattDevice(bluetooth::RawAddress(address), 0), &character, confirm); - HILOGI("result = %{public}d.", result); - return result; + HILOGI("ret = %{public}d.", ret); + return ret; } int GattServer::RemoveGattService(const GattService &service) { HILOGI("enter"); - if (!pimpl->proxy_) { - HILOGE("proxy_ is nullptr"); - return GattStatus::REQUEST_NOT_SUPPORT; + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; } - if (!pimpl->isRegisterSucceeded_) { - HILOGE("not registered"); - return GattStatus::REQUEST_NOT_SUPPORT; - } - - int result = GattStatus::INVALID_PARAMETER; + ret = BT_ERR_INVALID_PARAM; for (auto sIt = pimpl->gattServices_.begin(); sIt != pimpl->gattServices_.end(); sIt++) { if (sIt->GetHandle() == service.GetHandle()) { - pimpl->proxy_->RemoveService( + ret = pimpl->proxy_->RemoveService( pimpl->applicationId_, (BluetoothGattService)bluetooth::Service(service.GetHandle())); pimpl->gattServices_.erase(sIt); - result = GattStatus::GATT_SUCCESS; break; } } - HILOGI("result = %{public}d.", result); - return result; + HILOGI("ret = %{public}d.", ret); + return ret; } int GattServer::SendResponse( const BluetoothRemoteDevice &device, int requestId, int status, int offset, const uint8_t *value, int length) { HILOGI("remote device: %{public}s, status: %{public}d", GET_ENCRYPT_ADDR(device), status); - if (!pimpl->proxy_) { - HILOGE("proxy_ is nullptr"); - return GattStatus::REQUEST_NOT_SUPPORT; + int ret = pimpl->CheckInterface(); + if (ret != BT_SUCCESS) { + return ret; } - if (!device.IsValidBluetoothRemoteDevice() || !pimpl->isRegisterSucceeded_) { + if (!device.IsValidBluetoothRemoteDevice()) { HILOGE("Invalid remote device"); - return GattStatus::INVALID_REMOTE_DEVICE; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->FindConnectedDevice(device) == nullptr) { HILOGE("No connection to device: %{public}s", GET_ENCRYPT_ADDR(device)); - return GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } - int result = GattStatus::INVALID_PARAMETER; + int result = BT_ERR_INTERNAL_ERROR; uint8_t requestType = requestId >> EIGHT_BITS; uint8_t transport = requestId & 0xFF; if (transport != GATT_TRANSPORT_TYPE_CLASSIC && transport != GATT_TRANSPORT_TYPE_LE) { @@ -765,7 +766,7 @@ int GattServer::SendResponse( HILOGE("Error request Id!"); break; } - if (result == GattStatus::GATT_SUCCESS) { + if (result == BT_SUCCESS) { pimpl->requests_.erase(request); } } diff --git a/frameworks/inner/src/bluetooth_hfp_ag.cpp b/frameworks/inner/src/bluetooth_hfp_ag.cpp index 84839e38..72b1def6 100644 --- a/frameworks/inner/src/bluetooth_hfp_ag.cpp +++ b/frameworks/inner/src/bluetooth_hfp_ag.cpp @@ -16,6 +16,7 @@ #include "bluetooth_hfp_ag.h" #include #include "bluetooth_device.h" +#include "bluetooth_errorcode.h" #include "bluetooth_host.h" #include "bluetooth_log.h" #include "bluetooth_utils.h" @@ -88,18 +89,27 @@ std::string HfpAgServiceName = "bluetooth-hfp-ag-server"; struct HandsFreeAudioGateway::impl { impl(); ~impl(); - std::vector GetConnectedDevices() + int32_t GetConnectedDevices(std::vector& devices) { HILOGI("enter"); - std::vector devices; - if (proxy_ != nullptr && IS_BT_ENABLED()) { - std::vector ori; - proxy_->GetConnectDevices(ori); - for (auto it = ori.begin(); it != ori.end(); it++) { - devices.push_back(BluetoothRemoteDevice(it->GetAddress(), 0)); - } + if (!proxy_) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_SERVICE_DISCONNECTED; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - return devices; + std::vector ori; + int32_t ret = proxy_->GetConnectDevices(ori); + if (ret != BT_SUCCESS) { + HILOGE("inner error."); + return ret; + } + for (auto it = ori.begin(); it != ori.end(); it++) { + devices.push_back(BluetoothRemoteDevice(it->GetAddress(), 0)); + } + return BT_SUCCESS; } std::vector GetDevicesByStates(std::vector states) @@ -122,81 +132,61 @@ struct HandsFreeAudioGateway::impl { return remoteDevices; } - int GetDeviceState(const BluetoothRemoteDevice &device) + int32_t GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (proxy_ == nullptr) { - HILOGE("proxy_ is nullptr"); - return HFP_AG_SLC_STATE_DISCONNECTED; + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; } - if (!IS_BT_ENABLED()) { - HILOGE("Not IS_BT_ENABLED"); - return HFP_AG_SLC_STATE_DISCONNECTED; + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - if (device.IsValidBluetoothRemoteDevice()) { - return proxy_->GetDeviceState(BluetoothRawAddress(device.GetDeviceAddr())); - } - return HFP_AG_SLC_STATE_DISCONNECTED; + return proxy_->GetDeviceState(BluetoothRawAddress(device.GetDeviceAddr()), state); } - bool Connect(const BluetoothRemoteDevice &device) + int32_t Connect(const BluetoothRemoteDevice &device) { HILOGI("hfp connect remote device: %{public}s", GET_ENCRYPT_ADDR(device)); - - if (proxy_ == nullptr) { - HILOGE("proxy_ is nullptr"); - return false; + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; } - if (!IS_BT_ENABLED()) { HILOGE("Not IS_BT_ENABLED"); - return false; + return BT_ERR_INVALID_STATE; } - if (!device.IsValidBluetoothRemoteDevice()) { - HILOGE("Addr is invalid"); - return false; + int cod = 0; + int32_t err = device.GetDeviceClass(cod); + if (err != BT_SUCCESS) { + HILOGE("GetDeviceClass Failed."); + return BT_ERR_INVALID_PARAM; } - - if (!device.GetDeviceClass().IsProfileSupported(BluetoothDevice::PROFILE_HEADSET)) { + BluetoothDeviceClass devClass = BluetoothDeviceClass(cod); + if (!devClass.IsProfileSupported(BluetoothDevice::PROFILE_HEADSET)) { HILOGE("hfp connect failed. The remote device does not support HFP service."); - return false; - } - - if (proxy_->Connect(BluetoothRawAddress(device.GetDeviceAddr())) == NO_ERROR) { - return true; + return BT_ERR_PROFILE_DISABLED; } - - return false; + return proxy_->Connect(BluetoothRawAddress(device.GetDeviceAddr())); } - bool Disconnect(const BluetoothRemoteDevice &device) + int32_t Disconnect(const BluetoothRemoteDevice &device) { HILOGI("hfp disconnect remote device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (proxy_ == nullptr) { - HILOGE("proxy_ == nullptr"); - return false; - } - - if (!IS_BT_ENABLED()) - { - HILOGE("Not IS_BT_ENABLED"); - return false; + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; } - - if (!device.IsValidBluetoothRemoteDevice()) { - HILOGE("Addr is invalid"); - return false; - } - - if (proxy_->Disconnect(BluetoothRawAddress(device.GetDeviceAddr())) == NO_ERROR) { - return true; + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - return false; + return proxy_->Disconnect(BluetoothRawAddress(device.GetDeviceAddr())); } int GetScoState(const BluetoothRemoteDevice &device) @@ -443,9 +433,16 @@ HandsFreeAudioGateway::~HandsFreeAudioGateway() } std::vector HandsFreeAudioGateway::GetConnectedDevices() const +{ + std::vector devices; + pimpl->GetConnectedDevices(devices); + return devices; +} + +int32_t HandsFreeAudioGateway::GetConnectedDevices(std::vector &devices) { HILOGI("enter"); - return pimpl->GetConnectedDevices(); + return pimpl->GetConnectedDevices(devices); } std::vector HandsFreeAudioGateway::GetDevicesByStates(std::vector states) @@ -454,19 +451,19 @@ std::vector HandsFreeAudioGateway::GetDevicesByStates(std return pimpl->GetDevicesByStates(states); } -int HandsFreeAudioGateway::GetDeviceState(const BluetoothRemoteDevice &device) const +int32_t HandsFreeAudioGateway::GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); - return pimpl->GetDeviceState(device); + return pimpl->GetDeviceState(device, state); } -bool HandsFreeAudioGateway::Connect(const BluetoothRemoteDevice &device) +int32_t HandsFreeAudioGateway::Connect(const BluetoothRemoteDevice &device) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); return pimpl->Connect(device); } -bool HandsFreeAudioGateway::Disconnect(const BluetoothRemoteDevice &device) +int32_t HandsFreeAudioGateway::Disconnect(const BluetoothRemoteDevice &device) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); return pimpl->Disconnect(device); diff --git a/frameworks/inner/src/bluetooth_hid_host.cpp b/frameworks/inner/src/bluetooth_hid_host.cpp index ac4b27f8..7391f559 100644 --- a/frameworks/inner/src/bluetooth_hid_host.cpp +++ b/frameworks/inner/src/bluetooth_hid_host.cpp @@ -58,75 +58,91 @@ private: struct HidHost::impl { impl(); ~impl(); - std::vector GetDevicesByStates(std::vector states) + int32_t GetDevicesByStates(std::vector states, std::vector& result) { HILOGI("Enter!"); - std::vector remoteDevices; - if (proxy_ != nullptr && IS_BT_ENABLED()) { - std::vector rawDevices; - std::vector tmpStates; - for (int state : states) { - tmpStates.push_back((int32_t)state); - } - - proxy_->GetDevicesByStates(tmpStates, rawDevices); - for (BluetoothRawAddress rawDevice : rawDevices) { - BluetoothRemoteDevice remoteDevice(rawDevice.GetAddress(), 0); - remoteDevices.push_back(remoteDevice); - } + if (!proxy_) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_SERVICE_DISCONNECTED; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; + } + + std::vector rawDevices; + std::vector tmpStates; + for (int32_t state : states) { + tmpStates.push_back((int32_t)state); + } + + int32_t ret = proxy_->GetDevicesByStates(tmpStates, rawDevices); + if (ret != BT_SUCCESS) { + HILOGE("inner error."); + return ret; + } + + for (BluetoothRawAddress rawDevice : rawDevices) { + BluetoothRemoteDevice remoteDevice(rawDevice.GetAddress(), 1); + result.push_back(remoteDevice); } - return remoteDevices; + + return BT_SUCCESS; } - int GetDeviceState(const BluetoothRemoteDevice &device) + int32_t GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state) { - HILOGI("addr:%{public}s", GET_ENCRYPT_ADDR(device)); - if (proxy_ != nullptr && IS_BT_ENABLED() && device.IsValidBluetoothRemoteDevice()) { - int state; - proxy_->GetDeviceState(BluetoothRawAddress(device.GetDeviceAddr()), state); - HILOGI("addr:%{public}s, state:%{public}d", GET_ENCRYPT_ADDR(device), state); - return state; + HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - HILOGI("failed and fw return DISCONNECTED, addr:%{public}s", GET_ENCRYPT_ADDR(device)); - return (int)BTConnectState::DISCONNECTED; + return proxy_->GetDeviceState(BluetoothRawAddress(device.GetDeviceAddr()), state); } - bool Connect(const BluetoothRemoteDevice &device) + int32_t Connect(const BluetoothRemoteDevice &device) { - if (!device.IsValidBluetoothRemoteDevice()) { - HILOGE("Addr is invalid"); - return false; + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - BluetoothDeviceClass devClass = device.GetDeviceClass(); - int cod = devClass.GetClassOfDevice(); - if (cod != INVALID_VALUE && !devClass.IsProfileSupported(BluetoothDevice::PROFILE_HID)) { - HILOGE("hid connect failed. The remote device does not support HID service."); + int cod = 0; + int32_t err = device.GetDeviceClass(cod); + if (err != BT_SUCCESS) { + HILOGE("GetDeviceClass Failed."); return false; } - - HILOGI("hid connect remote device: %{public}s, cod: %{public}d", GET_ENCRYPT_ADDR(device), cod); - if (proxy_ != nullptr && IS_BT_ENABLED()) { - bool isOk; - proxy_->Connect(BluetoothRawAddress(device.GetDeviceAddr()), isOk); - HILOGI("hid connect. result:%{public}d", isOk); - return isOk; + BluetoothDeviceClass devClass = BluetoothDeviceClass(cod); + if (!devClass.IsProfileSupported(BluetoothDevice::PROFILE_HID)) { + HILOGE("hid connect failed. The remote device does not support HID service."); + return BT_ERR_PROFILE_DISABLED; } - HILOGE("hid connect failed. fw return false!"); - return false; + cod = devClass.GetClassOfDevice(); + HILOGI("hid connect remote device: %{public}s, cod: %{public}d", GET_ENCRYPT_ADDR(device), cod); + return proxy_->Connect(BluetoothRawAddress(device.GetDeviceAddr())); } - bool Disconnect(const BluetoothRemoteDevice &device) + int32_t Disconnect(const BluetoothRemoteDevice &device) { HILOGI("hid disconnect remote device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (proxy_ != nullptr && IS_BT_ENABLED() && device.IsValidBluetoothRemoteDevice()) { - bool isOk; - proxy_->Disconnect(BluetoothRawAddress(device.GetDeviceAddr()), isOk); - HILOGI("end, result:%{public}d", isOk); - return isOk; + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - HILOGE("fw return false!"); - return false; + return proxy_->Disconnect(BluetoothRawAddress(device.GetDeviceAddr())); } void RegisterObserver(std::shared_ptr observer) @@ -295,22 +311,22 @@ HidHost *HidHost::GetProfile() return &instance; } -std::vector HidHost::GetDevicesByStates(std::vector states) +int32_t HidHost::GetDevicesByStates(std::vector states, std::vector &result) { - return pimpl->GetDevicesByStates(states); + return pimpl->GetDevicesByStates(states, result); } -int HidHost::GetDeviceState(const BluetoothRemoteDevice &device) +int32_t HidHost::GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state) { - return pimpl->GetDeviceState(device); + return pimpl->GetDeviceState(device, state); } -bool HidHost::Connect(const BluetoothRemoteDevice &device) +int32_t HidHost::Connect(const BluetoothRemoteDevice &device) { return pimpl->Connect(device); } -bool HidHost::Disconnect(const BluetoothRemoteDevice &device) +int32_t HidHost::Disconnect(const BluetoothRemoteDevice &device) { return pimpl->Disconnect(device); } diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index a964d38f..03ba9996 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -26,6 +26,7 @@ #include "bluetooth_remote_device_observer_stub.h" #include "iservice_registry.h" #include "system_ability_definition.h" +#include "bluetooth_errorcode.h" namespace OHOS { namespace Bluetooth { @@ -451,7 +452,7 @@ bool BluetoothHost::EnableBt() return pimpl->proxy_->EnableBt(); } -bool BluetoothHost::DisableBt() +int BluetoothHost::DisableBt() { HILOGI("enter"); if (!pimpl) { @@ -476,11 +477,28 @@ int BluetoothHost::GetBtState() const HILOGE("failed: no proxy"); return INVALID_VALUE; } - int state = pimpl->proxy_->GetBtState(); + int state = BTStateID::STATE_TURN_OFF; + pimpl->proxy_->GetBtState(state); HILOGI("state: %{public}d", state); return state; } +int BluetoothHost::GetBtState(int &state) const +{ + HILOGI("enter"); + if (!pimpl) { + HILOGE("failed: no pimpl"); + return BT_ERR_INTERNAL_ERROR; + } + if (pimpl->proxy_ == nullptr) { + HILOGE("failed: no proxy"); + return BT_ERR_SERVICE_DISCONNECTED; + } + int ret = pimpl->proxy_->GetBtState(state); + HILOGI("state: %{public}d", state); + return ret; +} + bool BluetoothHost::BluetoothFactoryReset() { HILOGI("enter"); @@ -526,23 +544,36 @@ BluetoothRemoteDevice BluetoothHost::GetRemoteDevice(const std::string &addr, in return remoteDevice; } -bool BluetoothHost::EnableBle() +int BluetoothHost::EnableBle() { HILOGI("enter"); if (!pimpl) { HILOGE("fails: no pimpl"); - return false; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } return pimpl->proxy_->EnableBle(); } -bool BluetoothHost::DisableBle() +int BluetoothHost::DisableBle() { HILOGI("enter"); + if (!pimpl) { + HILOGE("fails: no pimpl"); + return BT_ERR_INTERNAL_ERROR; + } + if (pimpl->proxy_ == nullptr) { + HILOGE("fails: no proxy"); + return BT_ERR_INTERNAL_ERROR; + } + return pimpl->proxy_->DisableBle(); +} + +bool BluetoothHost::IsBrEnabled() const +{ if (!pimpl) { HILOGE("fails: no pimpl"); return false; @@ -551,7 +582,7 @@ bool BluetoothHost::DisableBle() HILOGE("fails: no proxy"); return false; } - return pimpl->proxy_->DisableBle(); + return pimpl->proxy_->IsBrEnabled(); } bool BluetoothHost::IsBleEnabled() const @@ -623,21 +654,40 @@ int BluetoothHost::GetBtConnectionState() const HILOGE("fails: no proxy"); return INVALID_VALUE; } - return pimpl->proxy_->GetBtConnectionState(); + int state = static_cast(BTConnectState::DISCONNECTED); + pimpl->proxy_->GetBtConnectionState(state); + HILOGI("state: %{public}d", state); + return state; } -int BluetoothHost::GetBtProfileConnState(uint32_t profileId) const +int BluetoothHost::GetBtConnectionState(int &state) const +{ + HILOGI("enter"); + if (!pimpl) { + HILOGE("fails: no pimpl"); + return BT_ERR_INTERNAL_ERROR; + } + if (pimpl->proxy_ == nullptr) { + HILOGE("fails: no proxy"); + return BT_ERR_SERVICE_DISCONNECTED; + } + int ret = pimpl->proxy_->GetBtConnectionState(state); + HILOGI("state: %{public}d", state); + return ret; +} + +int BluetoothHost::GetBtProfileConnState(uint32_t profileId, int &state) const { HILOGI("enter, profileId: %{public}d", profileId); if (!pimpl) { HILOGE("fails: no pimpl"); - return INVALID_VALUE; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return INVALID_VALUE; + return BT_ERR_INTERNAL_ERROR; } - return pimpl->proxy_->GetBtProfileConnState(profileId); + return pimpl->proxy_->GetBtProfileConnState(profileId, state); } void BluetoothHost::GetLocalSupportedUuids(std::vector &uuids) @@ -710,47 +760,63 @@ std::string BluetoothHost::GetLocalName() const HILOGE("fails: no proxy"); return std::string(); } - return pimpl->proxy_->GetLocalName(); + std::string name = INVALID_NAME; + pimpl->proxy_->GetLocalName(name); + return name; } -bool BluetoothHost::SetLocalName(const std::string &name) +int BluetoothHost::GetLocalName(std::string &name) const { HILOGI("enter"); if (!pimpl) { HILOGE("fails: no pimpl"); - return false; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; + } + return pimpl->proxy_->GetLocalName(name); +} + +int BluetoothHost::SetLocalName(const std::string &name) +{ + HILOGI("enter"); + if (!pimpl) { + HILOGE("fails: no pimpl"); + return BT_ERR_INTERNAL_ERROR; + } + if (pimpl->proxy_ == nullptr) { + HILOGE("fails: no proxy"); + return BT_ERR_INTERNAL_ERROR; } return pimpl->proxy_->SetLocalName(name); } -int BluetoothHost::GetBtScanMode() const +int BluetoothHost::GetBtScanMode(int32_t &scanMode) const { HILOGI("enter"); if (!pimpl) { HILOGE("fails: no pimpl"); - return INVALID_VALUE; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return INVALID_VALUE; + return BT_ERR_INTERNAL_ERROR; } - return pimpl->proxy_->GetBtScanMode(); + return pimpl->proxy_->GetBtScanMode(scanMode); } -bool BluetoothHost::SetBtScanMode(int mode, int duration) +int BluetoothHost::SetBtScanMode(int mode, int duration) { HILOGI("enter, mode: %{public}d, duration: %{public}d", mode, duration); if (!pimpl) { HILOGE("fails: no pimpl"); - return false; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } return pimpl->proxy_->SetBtScanMode(mode, duration); } @@ -783,30 +849,30 @@ bool BluetoothHost::SetBondableMode(int transport, int mode) return pimpl->proxy_->SetBondableMode(transport, mode); } -bool BluetoothHost::StartBtDiscovery() +int BluetoothHost::StartBtDiscovery() { HILOGI("enter"); if (!pimpl) { HILOGE("fails: no pimpl"); - return false; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } return pimpl->proxy_->StartBtDiscovery(); } -bool BluetoothHost::CancelBtDiscovery() +int BluetoothHost::CancelBtDiscovery() { HILOGI("enter"); if (!pimpl) { HILOGE("fails: no pimpl"); - return false; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } return pimpl->proxy_->CancelBtDiscovery(); } @@ -839,41 +905,41 @@ long BluetoothHost::GetBtDiscoveryEndMillis() const return pimpl->proxy_->GetBtDiscoveryEndMillis(); } -std::vector BluetoothHost::GetPairedDevices(int transport) const +int32_t BluetoothHost::GetPairedDevices(int transport, std::vector &pairedDevices) const { HILOGI("enter, transport: %{public}d", transport); - std::vector pairedDevices; if (!pimpl) { HILOGE("fails: no pimpl"); - return pairedDevices; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return pairedDevices; + return BT_ERR_INTERNAL_ERROR; } - std::vector pairedAddr = pimpl->proxy_->GetPairedDevices(transport); + std::vector pairedAddr; + int32_t ret = pimpl->proxy_->GetPairedDevices(transport, pairedAddr); for (auto it = pairedAddr.begin(); it != pairedAddr.end(); it++) { BluetoothRemoteDevice device((*it).GetAddress(), transport); pairedDevices.emplace_back(device); } - return pairedDevices; + return ret; } -bool BluetoothHost::RemovePair(const BluetoothRemoteDevice &device) +int32_t BluetoothHost::RemovePair(const BluetoothRemoteDevice &device) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); if (!device.IsValidBluetoothRemoteDevice()) { HILOGE("Invalid remote device."); - return false; + return BT_ERR_INTERNAL_ERROR; } if (!pimpl) { HILOGE("fails: no pimpl"); - return false; + return BT_ERR_INTERNAL_ERROR; } if (pimpl->proxy_ == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } sptr rawAddrSptr = new BluetoothRawAddress(device.GetDeviceAddr()); return pimpl->proxy_->RemovePair(device.GetTransportType(), rawAddrSptr); @@ -893,14 +959,13 @@ bool BluetoothHost::RemoveAllPairs() return pimpl->proxy_->RemoveAllPairs(); } -void BluetoothHost::RegisterRemoteDeviceObserver(BluetoothRemoteDeviceObserver &observer) +void BluetoothHost::RegisterRemoteDeviceObserver(std::shared_ptr observer) { if (!pimpl) { HILOGE("fails: no pimpl"); return; } - std::shared_ptr pointer(&observer, [](BluetoothRemoteDeviceObserver *) {}); - pimpl->remoteObservers_.Register(pointer); + pimpl->remoteObservers_.Register(observer); } void BluetoothHost::DeregisterRemoteDeviceObserver(BluetoothRemoteDeviceObserver &observer) diff --git a/frameworks/inner/src/bluetooth_map_mce.cpp b/frameworks/inner/src/bluetooth_map_mce.cpp index f66b4df9..b711a02e 100644 --- a/frameworks/inner/src/bluetooth_map_mce.cpp +++ b/frameworks/inner/src/bluetooth_map_mce.cpp @@ -848,7 +848,7 @@ MapMasInstanceInfoList MapClient::GetMasInstanceInfo(const BluetoothRemoteDevice // process if ((pimpl->proxy_ != nullptr) && IS_BT_ENABLED()) { BluetoothRawAddress rawDevice(device.GetDeviceAddr()); - BluetoothIProfileMasInstanceInfoList infoList = pimpl->proxy_->GetMasInstanceInfo(rawDevice); + infoList = pimpl->proxy_->GetMasInstanceInfo(rawDevice); HILOGI("Test!"); if (infoList.isValid == true) { diff --git a/frameworks/inner/src/bluetooth_pan.cpp b/frameworks/inner/src/bluetooth_pan.cpp index 076d3635..01486f9f 100644 --- a/frameworks/inner/src/bluetooth_pan.cpp +++ b/frameworks/inner/src/bluetooth_pan.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include "bluetooth_errorcode.h" #include "bluetooth_pan.h" #include "bluetooth_host.h" #include "bluetooth_log.h" @@ -56,49 +57,64 @@ struct Pan::impl { impl(); ~impl(); - std::vector GetDevicesByStates(std::vector states) + int32_t GetDevicesByStates(std::vector states, std::vector& result) { HILOGI("enter"); - std::vector remoteDevices; - if (proxy_ != nullptr && IS_BT_ENABLED()) { - std::vector rawDevices; - std::vector tmpStates; - for (int state : states) { - tmpStates.push_back((int32_t)state); - } - if (proxy_ != nullptr) { - HILOGI("proxy_ != nullptr !"); - proxy_->GetDevicesByStates(tmpStates, rawDevices); - } - for (BluetoothRawAddress rawDevice : rawDevices) { - BluetoothRemoteDevice remoteDevice(rawDevice.GetAddress(), 1); - remoteDevices.push_back(remoteDevice); - } + if (!proxy_) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_SERVICE_DISCONNECTED; } - return remoteDevices; + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; + } + + std::vector rawDevices; + std::vector tmpStates; + for (int32_t state : states) { + tmpStates.push_back((int32_t)state); + } + + int32_t ret = proxy_->GetDevicesByStates(tmpStates, rawDevices); + if (ret != BT_SUCCESS) { + HILOGE("inner error."); + return ret; + } + + for (BluetoothRawAddress rawDevice : rawDevices) { + BluetoothRemoteDevice remoteDevice(rawDevice.GetAddress(), 1); + result.push_back(remoteDevice); + } + + return BT_SUCCESS; } - int GetDeviceState(const BluetoothRemoteDevice &device) + int32_t GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state) { HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (proxy_ != nullptr && IS_BT_ENABLED() && device.IsValidBluetoothRemoteDevice()) { - int state; - proxy_->GetDeviceState(BluetoothRawAddress(device.GetDeviceAddr()), state); - return state; + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - return (int)BTConnectState::DISCONNECTED; + return proxy_->GetDeviceState(BluetoothRawAddress(device.GetDeviceAddr()), state); } - bool Disconnect(const BluetoothRemoteDevice &device) + int32_t Disconnect(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); - if (proxy_ != nullptr && IS_BT_ENABLED() && device.IsValidBluetoothRemoteDevice()) { - bool isOk; - proxy_->Disconnect(BluetoothRawAddress(device.GetDeviceAddr()), isOk); - return isOk; + HILOGI("device: %{public}s", GET_ENCRYPT_ADDR(device)); + if (proxy_ == nullptr || !device.IsValidBluetoothRemoteDevice()) { + HILOGE("invalid param."); + return BT_ERR_INVALID_PARAM; } - HILOGE("fw return false!"); - return false; + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; + } + return proxy_->Disconnect(BluetoothRawAddress(device.GetDeviceAddr())); } void RegisterObserver(std::shared_ptr observer) @@ -113,28 +129,34 @@ struct Pan::impl { observers_.Deregister(observer); } - bool SetTethering(bool value) + int32_t SetTethering(bool value) { HILOGI("enter"); - if (proxy_ != nullptr && IS_BT_ENABLED()) { - bool isOk; - proxy_->SetTethering(value, isOk); - return isOk; + if (!proxy_) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_SERVICE_DISCONNECTED; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - HILOGE("fw return false!"); - return false; + int32_t ret = proxy_->SetTethering(value); + HILOGI("fwk ret:%{public}d", ret); + return ret; } - bool IsTetheringOn() + int32_t IsTetheringOn(bool &value) { HILOGI("enter"); - if (proxy_ != nullptr && IS_BT_ENABLED()) { - bool isOk; - proxy_->IsTetheringOn(isOk); - return isOk; + if (!proxy_) { + HILOGE("proxy_ is nullptr."); + return BT_ERR_SERVICE_DISCONNECTED; + } + if (!IS_BT_ENABLED()) { + HILOGE("bluetooth is off."); + return BT_ERR_INVALID_STATE; } - HILOGE("fw return false!"); - return false; + return proxy_->IsTetheringOn(value); } private: @@ -213,17 +235,17 @@ Pan *Pan::GetProfile() return &instance; } -std::vector Pan::GetDevicesByStates(std::vector states) +int32_t Pan::GetDevicesByStates(std::vector states, std::vector &result) { - return pimpl->GetDevicesByStates(states); + return pimpl->GetDevicesByStates(states, result); } -int Pan::GetDeviceState(const BluetoothRemoteDevice &device) +int32_t Pan::GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state) { - return pimpl->GetDeviceState(device); + return pimpl->GetDeviceState(device, state); } -bool Pan::Disconnect(const BluetoothRemoteDevice &device) +int32_t Pan::Disconnect(const BluetoothRemoteDevice &device) { return pimpl->Disconnect(device); } @@ -240,14 +262,14 @@ void Pan::DeregisterObserver(PanObserver *observer) return pimpl->DeregisterObserver(observerPtr); } -bool Pan::SetTethering(bool value) +int32_t Pan::SetTethering(bool value) { return pimpl->SetTethering(value); } -bool Pan::IsTetheringOn() +int32_t Pan::IsTetheringOn(bool &value) { - return pimpl->IsTetheringOn(); + return pimpl->IsTetheringOn(value); } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/inner/src/bluetooth_remote_device.cpp b/frameworks/inner/src/bluetooth_remote_device.cpp index ed9d2331..6d708cc4 100644 --- a/frameworks/inner/src/bluetooth_remote_device.cpp +++ b/frameworks/inner/src/bluetooth_remote_device.cpp @@ -20,6 +20,7 @@ #include "bluetooth_host.h" #include "bluetooth_host_proxy.h" #include "bluetooth_log.h" +#include "bluetooth_utils.h" #include "bluetooth_remote_device.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -62,11 +63,11 @@ int BluetoothRemoteDevice::GetDeviceType() const bool BluetoothRemoteDevice::IsValidBluetoothRemoteDevice() const { if (!BluetoothHost::IsValidBluetoothAddr(address_)) { - HILOGI("invalid bluetooth addr."); + HILOGI("invalid bluetooth addr, address_: %{public}s", GetEncryptAddr(address_).c_str()); return false; } - if ((BT_TRANSPORT_BREDR != transport_) && (BT_TRANSPORT_BLE != transport_)) { + if ((transport_ != BT_TRANSPORT_BREDR) && (transport_ != BT_TRANSPORT_BLE)) { HILOGI("invalid transport type."); return false; } @@ -164,7 +165,23 @@ std::string BluetoothRemoteDevice::GetDeviceName() const HILOGE("fails: no proxy"); return INVALID_NAME; } - return hostProxy->GetDeviceName(transport_, address_); + std::string name = INVALID_NAME; + hostProxy->GetDeviceName(transport_, address_, name); + return name; +} + +int BluetoothRemoteDevice::GetDeviceName(std::string &name) const +{ + if (!IsValidBluetoothRemoteDevice()) { + HILOGW("Invalid remote device"); + return BT_ERR_INTERNAL_ERROR; + } + sptr hostProxy = GetHostProxy(); + if (hostProxy == nullptr) { + HILOGE("fails: no proxy"); + return BT_ERR_INTERNAL_ERROR; + } + return hostProxy->GetDeviceName(transport_, address_, name); } std::string BluetoothRemoteDevice::GetDeviceAlias() const @@ -227,17 +244,17 @@ int BluetoothRemoteDevice::GetPairState() const return hostProxy->GetPairState(transport_, address_); } -bool BluetoothRemoteDevice::StartPair() +int BluetoothRemoteDevice::StartPair() { HILOGI("enter"); if (!IsValidBluetoothRemoteDevice()) { HILOGW("Invalid remote device"); - return false; + return BT_ERR_INTERNAL_ERROR; } sptr hostProxy = GetHostProxy(); if (hostProxy == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } return hostProxy->StartPair(transport_, address_); } @@ -302,20 +319,20 @@ bool BluetoothRemoteDevice::IsAclEncrypted() const return hostProxy->IsAclEncrypted(transport_, address_); } -BluetoothDeviceClass BluetoothRemoteDevice::GetDeviceClass() const +int BluetoothRemoteDevice::GetDeviceClass(int &cod) const { HILOGI("enter"); if (!IsValidBluetoothRemoteDevice()) { HILOGW("Invalid remote device"); - return BluetoothDeviceClass(0); + return BT_ERR_INTERNAL_ERROR; } sptr hostProxy = GetHostProxy(); if (hostProxy == nullptr) { HILOGE("fails: no proxy"); - return BluetoothDeviceClass(0); + return BT_ERR_INTERNAL_ERROR; } - int cod = hostProxy->GetDeviceClass(address_); - return BluetoothDeviceClass(cod); + int ret = hostProxy->GetDeviceClass(address_, cod); + return ret; } std::vector BluetoothRemoteDevice::GetDeviceUuids() const @@ -354,17 +371,17 @@ bool BluetoothRemoteDevice::SetDevicePin(const std::string &pin) return hostProxy->SetDevicePin(address_, pin); } -bool BluetoothRemoteDevice::SetDevicePairingConfirmation(bool accept) +int BluetoothRemoteDevice::SetDevicePairingConfirmation(bool accept) { HILOGI("enter, accept: %{public}d", accept); if (!IsValidBluetoothRemoteDevice()) { HILOGW("Invalid remote device"); - return false; + return BT_ERR_INTERNAL_ERROR; } sptr hostProxy = GetHostProxy(); if (hostProxy == nullptr) { HILOGE("fails: no proxy"); - return false; + return BT_ERR_INTERNAL_ERROR; } return hostProxy->SetDevicePairingConfirmation(transport_, address_, accept); } diff --git a/frameworks/inner/src/bluetooth_socket.cpp b/frameworks/inner/src/bluetooth_socket.cpp index 73fc6856..10b64622 100644 --- a/frameworks/inner/src/bluetooth_socket.cpp +++ b/frameworks/inner/src/bluetooth_socket.cpp @@ -46,7 +46,7 @@ struct SppClientSocket::impl { if (fd_ > 0) { shutdown(fd_, SHUT_RD); shutdown(fd_, SHUT_WR); - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "SPP_CONNECT_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "SPP_CONNECT_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "close", "ID", fd_, "ADDRESS", "empty", "PID", IPCSkeleton::GetCallingPid(), "UID", IPCSkeleton::GetCallingUid()); HILOGI("fd closed, fd_: %{pubilc}d", fd_); @@ -66,7 +66,7 @@ struct SppClientSocket::impl { if (fd_ > 0) { shutdown(fd_, SHUT_RD); shutdown(fd_, SHUT_WR); - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "SPP_CONNECT_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "SPP_CONNECT_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "close", "ID", fd_, "ADDRESS", "empty", "PID", IPCSkeleton::GetCallingPid(), "UID", IPCSkeleton::GetCallingUid()); HILOGI("fd closed, fd_: %{pubilc}d", fd_); @@ -323,10 +323,10 @@ int SppClientSocket::Connect() return BtStatus::BT_FAILURE; } pimpl->socketStatus_ = SOCKET_CONNECTED; - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "SPP_CONNECT_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "SPP_CONNECT_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "connect", "ID", pimpl->fd_, "ADDRESS", tempAddress, "PID", IPCSkeleton::GetCallingPid(), "UID", IPCSkeleton::GetCallingUid()); - return BtStatus::BT_SUCCESS; + return BtStatus::BT_SUCC; } void SppClientSocket::Close() @@ -400,8 +400,8 @@ struct SppServerSocket::impl { } fd_ = proxy_->Listen(name_, serverUuid, (int32_t)getSecurityFlags(), (int32_t)type_); - if (fd_ == -1) { - HILOGE("failed, fd_ is -1"); + if (fd_ == BT_INVALID_SOCKET_FD) { + HILOGE("listen socket failed, fd_ is -1"); socketStatus_ = SOCKET_CLOSED; return BtStatus::BT_FAILURE; } @@ -415,7 +415,7 @@ struct SppServerSocket::impl { return BtStatus::BT_FAILURE; } - return BtStatus::BT_SUCCESS; + return BtStatus::BT_SUCC; } int getSecurityFlags() @@ -452,7 +452,7 @@ struct SppServerSocket::impl { std::unique_ptr clientSocket = std::make_unique(acceptFd_, acceptAddress_); - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "SPP_CONNECT_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "SPP_CONNECT_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "connect", "ID", acceptFd_, "ADDRESS", acceptAddress_, "PID", IPCSkeleton::GetCallingPid(), "UID", IPCSkeleton::GetCallingUid()); diff --git a/frameworks/inner/src/bluetooth_utils.cpp b/frameworks/inner/src/bluetooth_utils.cpp index 872f2062..fc2b51b8 100644 --- a/frameworks/inner/src/bluetooth_utils.cpp +++ b/frameworks/inner/src/bluetooth_utils.cpp @@ -13,7 +13,9 @@ * limitations under the License. */ #include "bluetooth_utils.h" +#include #include "__config" +#include "bluetooth_errorcode.h" #include "bluetooth_def.h" #include "bluetooth_log.h" #include "iosfwd" @@ -84,5 +86,39 @@ std::string GetProfileConnStateName(int state) } } +static std::map BtErrCodeMap { + { BtErrCode::BT_SUCCESS, "BT_SUCCESS" }, + { BtErrCode::BT_ERR_PERMISSION_FAILED, "BT_ERR_PERMISSION_FAILED" }, + { BtErrCode::BT_ERR_SYSTEM_PERMISSION_FAILED, "BT_ERR_SYSTEM_PERMISSION_FAILED" }, + { BtErrCode::BT_ERR_INVALID_PARAM, "BT_ERR_INVALID_PARAM" }, + { BtErrCode::BT_ERR_API_NOT_SUPPORT, "BT_ERR_API_NOT_SUPPORT" }, + { BtErrCode::BT_ERR_SERVICE_DISCONNECTED, "BT_ERR_SERVICE_DISCONNECTED" }, + { BtErrCode::BT_ERR_UNBONDED_DEVICE, "BT_ERR_UNBONDED_DEVICE" }, + { BtErrCode::BT_ERR_INVALID_STATE, "BT_ERR_INVALID_STATE" }, + { BtErrCode::BT_ERR_PROFILE_DISABLED, "BT_ERR_PROFILE_DISABLED" }, + { BtErrCode::BT_ERR_DEVICE_DISCONNECTED, "BT_ERR_DEVICE_DISCONNECTED" }, + { BtErrCode::BT_ERR_MAX_CONNECTION, "BT_ERR_MAX_CONNECTION" }, + { BtErrCode::BT_ERR_INTERNAL_ERROR, "BT_ERR_INTERNAL_ERROR" }, + { BtErrCode::BT_ERR_IPC_TRANS_FAILED, "BT_ERR_IPC_TRANS_FAILED" }, + { BtErrCode::BT_ERR_GATT_READ_NOT_PERMITTED, "BT_ERR_GATT_READ_NOT_PERMITTED" }, + { BtErrCode::BT_ERR_GATT_WRITE_NOT_PERMITTED, "BT_ERR_GATT_WRITE_NOT_PERMITTED" }, + { BtErrCode::BT_ERR_GATT_MAX_SERVER, "BT_ERR_GATT_MAX_SERVER" }, + { BtErrCode::BT_ERR_SPP_SERVER_STATE, "BT_ERR_SPP_SERVER_STATE" }, + { BtErrCode::BT_ERR_SPP_BUSY, "BT_ERR_SPP_BUSY" }, + { BtErrCode::BT_ERR_SPP_DEVICE_NOT_FOUND, "BT_ERR_SPP_DEVICE_NOT_FOUND" }, + { BtErrCode::BT_ERR_SPP_IO, "BT_ERR_SPP_IO" }, +}; + +std::string GetErrorCode(int32_t errCode) +{ + std::string errlog = "unknown error code: "; + auto iter = BtErrCodeMap.find(errCode); + if (iter != BtErrCodeMap.end()) { + errlog = iter->second; + } + errlog.append("(").append(std::to_string(errCode)).append(")"); + return errlog; +} + } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index ca32b499..a12922ff 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -13,6 +13,8 @@ import("//build/ohos.gni") +SUBSYSTEM_DIR = "//foundation/communication" + ohos_shared_library("bluetooth") { sanitize = { cfi = true @@ -76,6 +78,92 @@ ohos_shared_library("bluetooth") { "src/napi_bluetooth_spp_server.cpp", "src/napi_bluetooth_utils.cpp", "src/native_module.cpp", + "src/parser/napi_parser_utils.cpp", + ] + + deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/arkui/napi:ace_napi", + "//foundation/communication/bluetooth/frameworks/inner:btframework", + "//third_party/libuv:uv", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:ability_manager", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + part_name = "bluetooth" + subsystem_name = "communication" +} + +ohos_shared_library("bluetoothmanager") { + #install_enable = true + include_dirs = [ + "include", + "//third_party/node/src", + "//native_engine", + "//commonlibrary/c_utils/base/include", + "//utils/system/safwk/native/include", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/systemabilitymgr/samgr/adapter/interfaces/innerkits/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/communication/bluetooth/frameworks/inner/common", + ] + + defines = [ + "BT_LOG_TAG = \"bluetooth_napi\"", + "BT_LOG_DOMAIN = 0xD000100", + "ENABLE_NAPI_BLUETOOTH_MANAGER", + ] + + sources = [ + "src/napi_bluetooth_a2dp_snk.cpp", + "src/napi_bluetooth_a2dp_snk_observer.cpp", + "src/napi_bluetooth_a2dp_src.cpp", + "src/napi_bluetooth_a2dp_src_observer.cpp", + "src/napi_bluetooth_avrcp_ct.cpp", + "src/napi_bluetooth_avrcp_ct_observer.cpp", + "src/napi_bluetooth_avrcp_tg.cpp", + "src/napi_bluetooth_avrcp_tg_observer.cpp", + "src/napi_bluetooth_ble.cpp", + "src/napi_bluetooth_ble_advertise_callback.cpp", + "src/napi_bluetooth_ble_central_manager_callback.cpp", + "src/napi_bluetooth_error.cpp", + "src/napi_bluetooth_event.cpp", + "src/napi_bluetooth_gatt_client.cpp", + "src/napi_bluetooth_gatt_client_callback.cpp", + "src/napi_bluetooth_gatt_server.cpp", + "src/napi_bluetooth_gatt_server_callback.cpp", + "src/napi_bluetooth_hfp_ag.cpp", + "src/napi_bluetooth_hfp_ag_observer.cpp", + "src/napi_bluetooth_hfp_hf.cpp", + "src/napi_bluetooth_hfp_hf_observer.cpp", + "src/napi_bluetooth_hid_host.cpp", + "src/napi_bluetooth_hid_host_observer.cpp", + "src/napi_bluetooth_host.cpp", + "src/napi_bluetooth_host_observer.cpp", + "src/napi_bluetooth_opp.cpp", + "src/napi_bluetooth_opp_observer.cpp", + "src/napi_bluetooth_pan.cpp", + "src/napi_bluetooth_pan_observer.cpp", + "src/napi_bluetooth_pbap_pce.cpp", + "src/napi_bluetooth_pbap_pce_observer.cpp", + "src/napi_bluetooth_pbap_pse.cpp", + "src/napi_bluetooth_pbap_pse_observer.cpp", + "src/napi_bluetooth_profile.cpp", + "src/napi_bluetooth_remote_device_observer.cpp", + "src/napi_bluetooth_spp_client.cpp", + "src/napi_bluetooth_spp_server.cpp", + "src/napi_bluetooth_utils.cpp", + "src/native_module.cpp", + "src/parser/napi_parser_utils.cpp", ] deps = [ @@ -99,3 +187,10 @@ ohos_shared_library("bluetooth") { part_name = "bluetooth" subsystem_name = "communication" } + +group("bluetooth_napi") { + deps = [ + "$SUBSYSTEM_DIR/bluetooth/frameworks/js/napi:bluetooth", + "$SUBSYSTEM_DIR/bluetooth/frameworks/js/napi:bluetoothmanager", + ] +} diff --git a/frameworks/js/napi/include/napi_bluetooth_a2dp_snk_observer.h b/frameworks/js/napi/include/napi_bluetooth_a2dp_snk_observer.h index a3afb4d3..b2660382 100644 --- a/frameworks/js/napi/include/napi_bluetooth_a2dp_snk_observer.h +++ b/frameworks/js/napi/include/napi_bluetooth_a2dp_snk_observer.h @@ -22,7 +22,7 @@ namespace OHOS { namespace Bluetooth { -static std::shared_mutex g_a2dpSinkCallbackInfosMutex; + const std::string STR_BT_A2DP_SINK_CONNECTION_STATE_CHANGE = "connectionStateChange"; class NapiA2dpSinkObserver : public A2dpSinkObserver{ @@ -30,8 +30,9 @@ public: void OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) override; NapiA2dpSinkObserver() = default; - virtual ~NapiA2dpSinkObserver() = default; + ~NapiA2dpSinkObserver() override = default; + static std::shared_mutex g_a2dpSinkCallbackInfosMutex; std::map> callbackInfos_ = {}; }; diff --git a/frameworks/js/napi/include/napi_bluetooth_a2dp_src_observer.h b/frameworks/js/napi/include/napi_bluetooth_a2dp_src_observer.h index be85e900..842bacb7 100644 --- a/frameworks/js/napi/include/napi_bluetooth_a2dp_src_observer.h +++ b/frameworks/js/napi/include/napi_bluetooth_a2dp_src_observer.h @@ -22,7 +22,7 @@ namespace OHOS { namespace Bluetooth { -static std::shared_mutex g_a2dpSrcCallbackInfosMutex; + const std::string STR_BT_A2DP_SOURCE_CONNECTION_STATE_CHANGE = "connectionStateChange"; class NapiA2dpSourceObserver : public A2dpSourceObserver{ @@ -31,6 +31,7 @@ public: NapiA2dpSourceObserver() = default; virtual ~NapiA2dpSourceObserver() = default; + static std::shared_mutex g_a2dpSrcCallbackInfosMutex; std::map> callbackInfos_ = {}; }; diff --git a/frameworks/js/napi/include/napi_bluetooth_avrcp_ct_observer.h b/frameworks/js/napi/include/napi_bluetooth_avrcp_ct_observer.h index 8870a668..def92172 100644 --- a/frameworks/js/napi/include/napi_bluetooth_avrcp_ct_observer.h +++ b/frameworks/js/napi/include/napi_bluetooth_avrcp_ct_observer.h @@ -22,15 +22,16 @@ namespace OHOS { namespace Bluetooth { -static std::shared_mutex g_avrcpCtCallbackInfosMutex; + const std::string STR_BT_AVRCP_CT_CONNECTION_STATE_CHANGE = "connectionStateChange"; class NapiAvrcpControllerObserver : public AvrcpController::IObserver{ public: void OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) override; void OnActionCompleted(const BluetoothRemoteDevice &device, const AvrcpCtResponse &resp) override {} NapiAvrcpControllerObserver() = default; - virtual ~NapiAvrcpControllerObserver() = default; + ~NapiAvrcpControllerObserver() override = default; + static std::shared_mutex g_avrcpCtCallbackInfosMutex; std::map> callbackInfos_ = {}; }; diff --git a/frameworks/js/napi/include/napi_bluetooth_avrcp_tg_observer.h b/frameworks/js/napi/include/napi_bluetooth_avrcp_tg_observer.h index e76f180a..f748cd50 100644 --- a/frameworks/js/napi/include/napi_bluetooth_avrcp_tg_observer.h +++ b/frameworks/js/napi/include/napi_bluetooth_avrcp_tg_observer.h @@ -16,18 +16,20 @@ #ifndef NAPI_BLUETOOTH_AVRCP_TG_OBSERVER_H_ #define NAPI_BLUETOOTH_AVRCP_TG_OBSERVER_H_ +#include #include "bluetooth_avrcp_tg.h" #include "napi_bluetooth_utils.h" namespace OHOS { namespace Bluetooth { + const std::string STR_BT_AVRCP_TG_CONNECTION_STATE_CHANGE = "connectionStateChange"; class NapiAvrcpTargetObserver : public AvrcpTarget::IObserver{ public: void OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) override; NapiAvrcpTargetObserver() = default; - virtual ~NapiAvrcpTargetObserver() = default; - + ~NapiAvrcpTargetObserver() override = default; + static std::shared_mutex g_avrcpTgCallbackInfosMutex; std::map> callbackInfos_ = {}; }; diff --git a/frameworks/js/napi/include/napi_bluetooth_ble_central_manager_callback.h b/frameworks/js/napi/include/napi_bluetooth_ble_central_manager_callback.h index 6e993786..ae33c3fb 100644 --- a/frameworks/js/napi/include/napi_bluetooth_ble_central_manager_callback.h +++ b/frameworks/js/napi/include/napi_bluetooth_ble_central_manager_callback.h @@ -24,7 +24,7 @@ namespace Bluetooth { class NapiBluetoothBleCentralManagerCallback : public BleCentralManagerCallback { public: NapiBluetoothBleCentralManagerCallback() = default; - virtual ~NapiBluetoothBleCentralManagerCallback() = default; + ~NapiBluetoothBleCentralManagerCallback() override = default; void OnScanCallback(const BleScanResult &result) override; void OnBleBatchScanResultsEvent(const std::vector &results) override; diff --git a/frameworks/js/napi/include/napi_bluetooth_error.h b/frameworks/js/napi/include/napi_bluetooth_error.h new file mode 100644 index 00000000..76261c65 --- /dev/null +++ b/frameworks/js/napi/include/napi_bluetooth_error.h @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NAPI_BLUETOOTH_ERROR_H_ +#define NAPI_BLUETOOTH_ERROR_H_ + + +#include +#include "bluetooth_log.h" +#include "napi/native_api.h" + +namespace OHOS { +namespace Bluetooth { + +#ifdef ENABLE_NAPI_BLUETOOTH_MANAGER +#ifndef NAPI_BT_ASSERT_RETURN +#define NAPI_BT_ASSERT_RETURN(env, cond, errCode, retObj) \ +do { \ + if (!(cond)) { \ + HandleSyncErr((env), (errCode)); \ + HILOGE("bluetoothManager napi assert failed."); \ + return (retObj); \ + } \ +} while (0) +#endif +#else // ENABLE_NAPI_BLUETOOTH_MANAGER +#ifndef NAPI_BT_ASSERT_RETURN +#define NAPI_BT_ASSERT_RETURN(env, cond, errCode, retObj) \ +do { \ + if (!(cond)) { \ + HILOGE("bluetooth napi assert failed."); \ + return (retObj); \ + } \ +} while (0) +#endif +#endif + +#define NAPI_BT_ASSERT_RETURN_UNDEF(env, cond, errCode) \ +do { \ + napi_value res = nullptr; \ + napi_get_undefined((env), &res); \ + NAPI_BT_ASSERT_RETURN((env), (cond), (errCode), res); \ +} while (0) + +#define NAPI_BT_ASSERT_RETURN_FALSE(env, cond, errCode) \ +do { \ + napi_value res = nullptr; \ + napi_get_boolean((env), false, &res); \ + NAPI_BT_ASSERT_RETURN((env), (cond), (errCode), res); \ +} while (0) + +void HandleSyncErr(const napi_env &env, int32_t errCode); +} +} +#endif \ No newline at end of file diff --git a/frameworks/js/napi/include/napi_bluetooth_event.h b/frameworks/js/napi/include/napi_bluetooth_event.h index de011239..63963ae4 100644 --- a/frameworks/js/napi/include/napi_bluetooth_event.h +++ b/frameworks/js/napi/include/napi_bluetooth_event.h @@ -64,9 +64,9 @@ public: } auto func = std::bind( [](const std::shared_ptr &cb, T& obj) -> napi_value { - return NapiEvent::CreateResult(cb, obj); - }, - cb, obj); + return NapiEvent::CreateResult(cb, obj); + }, + cb, obj); AsyncEventData *asyncEvent = new (std::nothrow)AsyncEventData(cb, func); if (asyncEvent == nullptr) { HILOGI("asyncEvent is nullptr!"); diff --git a/frameworks/js/napi/include/napi_bluetooth_gatt_client.h b/frameworks/js/napi/include/napi_bluetooth_gatt_client.h index 1f363d7f..03768733 100644 --- a/frameworks/js/napi/include/napi_bluetooth_gatt_client.h +++ b/frameworks/js/napi/include/napi_bluetooth_gatt_client.h @@ -64,7 +64,7 @@ public: return device_; } - NapiGattClient(std::string &deviceId) + explicit NapiGattClient(std::string &deviceId) { HILOGI("enter"); device_ = std::make_shared(deviceId, 1); diff --git a/frameworks/js/napi/include/napi_bluetooth_gatt_client_callback.h b/frameworks/js/napi/include/napi_bluetooth_gatt_client_callback.h index 20761dd3..3330e718 100644 --- a/frameworks/js/napi/include/napi_bluetooth_gatt_client_callback.h +++ b/frameworks/js/napi/include/napi_bluetooth_gatt_client_callback.h @@ -15,13 +15,13 @@ #ifndef NAPI_BLUETOOTH_GATT_CLIENT_CALLBACK_H_ #define NAPI_BLUETOOTH_GATT_CLIENT_CALLBACK_H_ -#include +#include #include "bluetooth_gatt_client.h" #include "napi_bluetooth_utils.h" namespace OHOS { namespace Bluetooth { -static std::mutex g_gattClientCallbackInfosMutex; + const std::string STR_BT_GATT_CLIENT_CALLBACK_BLE_CHARACTERISTIC_CHANGE = "BLECharacteristicChange"; const std::string STR_BT_GATT_CLIENT_CALLBACK_BLE_CONNECTIION_STATE_CHANGE = "BLEConnectionStateChange"; class NapiGattClient; @@ -53,6 +53,7 @@ public: } NapiGattClientCallback() = default; virtual ~NapiGattClientCallback() = default; + static std::shared_mutex g_gattClientCallbackInfosMutex; private: std::map> callbackInfos_ = {}; diff --git a/frameworks/js/napi/include/napi_bluetooth_gatt_server_callback.h b/frameworks/js/napi/include/napi_bluetooth_gatt_server_callback.h index 703ac5b8..e411c33f 100644 --- a/frameworks/js/napi/include/napi_bluetooth_gatt_server_callback.h +++ b/frameworks/js/napi/include/napi_bluetooth_gatt_server_callback.h @@ -51,7 +51,7 @@ public: } NapiGattServerCallback() = default; - virtual ~NapiGattServerCallback() = default; + ~NapiGattServerCallback() override = default; private: std::map> callbackInfos_ = {}; diff --git a/frameworks/js/napi/include/napi_bluetooth_hfp_ag_observer.h b/frameworks/js/napi/include/napi_bluetooth_hfp_ag_observer.h index bb031635..799765e5 100644 --- a/frameworks/js/napi/include/napi_bluetooth_hfp_ag_observer.h +++ b/frameworks/js/napi/include/napi_bluetooth_hfp_ag_observer.h @@ -16,6 +16,7 @@ #ifndef NAPI_BLUETOOTH_HFP_AG_OBSERVER_H_ #define NAPI_BLUETOOTH_HFP_AG_OBSERVER_H_ +#include #include "bluetooth_hfp_ag.h" #include "napi_bluetooth_utils.h" @@ -33,8 +34,9 @@ public: void OnHfEnhancedDriverSafetyChanged(const BluetoothRemoteDevice &device, int indValue) override{} NapiHandsFreeAudioGatewayObserver() = default; - virtual ~NapiHandsFreeAudioGatewayObserver() = default; + ~NapiHandsFreeAudioGatewayObserver() override = default; + static std::shared_mutex g_handsFreeAudioGatewayCallbackMutex; std::map> callbackInfos_ = {}; }; } // namespace Bluetooth diff --git a/frameworks/js/napi/include/napi_bluetooth_hfp_hf_observer.h b/frameworks/js/napi/include/napi_bluetooth_hfp_hf_observer.h index 49bb8855..c1252e23 100644 --- a/frameworks/js/napi/include/napi_bluetooth_hfp_hf_observer.h +++ b/frameworks/js/napi/include/napi_bluetooth_hfp_hf_observer.h @@ -16,6 +16,7 @@ #ifndef NAPI_BLUETOOTH_HFP_HF_OBSERVER_H_ #define NAPI_BLUETOOTH_HFP_HF_OBSERVER_H_ +#include #include "bluetooth_hfp_hf.h" #include "napi_bluetooth_utils.h" @@ -40,7 +41,7 @@ public: NapiHandsFreeUnitObserver() = default; virtual ~NapiHandsFreeUnitObserver() = default; - + static std::shared_mutex g_handsFreeUnitCallbackInfosMutex; std::map> callbackInfos_ = {}; }; diff --git a/frameworks/js/napi/include/napi_bluetooth_host.h b/frameworks/js/napi/include/napi_bluetooth_host.h index 16af614b..14c50259 100644 --- a/frameworks/js/napi/include/napi_bluetooth_host.h +++ b/frameworks/js/napi/include/napi_bluetooth_host.h @@ -18,6 +18,7 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "bluetooth_remote_device.h" namespace OHOS { namespace Bluetooth { @@ -57,6 +58,9 @@ napi_value NapiGetRemoteDeviceAddr(napi_env env, napi_callback_info info, napi_v void RegisterObserverToHost(); napi_value GetProfileConnState(napi_env env, napi_callback_info info); +void AddDiscoveryDevice(std::shared_ptr &device); +void ClearDiscoveryDevice(); +int GetDeviceTransport(std::string &device); } // namespace Bluetooth } // namespace OHOS #endif /* NAPI_BLUETOOTH_H_ */ diff --git a/frameworks/js/napi/include/napi_bluetooth_profile.h b/frameworks/js/napi/include/napi_bluetooth_profile.h index 19980b18..3a1d8246 100644 --- a/frameworks/js/napi/include/napi_bluetooth_profile.h +++ b/frameworks/js/napi/include/napi_bluetooth_profile.h @@ -28,8 +28,8 @@ namespace Bluetooth { class NapiProfile { public: static void DefineProfileFunctions(napi_env env, napi_value exports); - static thread_local std::map profiles_; - static void SetProfile(ProfileId code, napi_value profile); + static thread_local std::map profiles_; + static void SetProfile(napi_env env, ProfileId code, napi_value profile); static napi_value GetProfile(napi_env env, napi_callback_info info); static void ProfileEnumInit(napi_env env, napi_value exports); static napi_value SppTypeInit(napi_env env); diff --git a/frameworks/js/napi/include/napi_bluetooth_spp_client.h b/frameworks/js/napi/include/napi_bluetooth_spp_client.h index 6ee523ae..20104bf0 100644 --- a/frameworks/js/napi/include/napi_bluetooth_spp_client.h +++ b/frameworks/js/napi/include/napi_bluetooth_spp_client.h @@ -28,8 +28,8 @@ struct NapiSppClient { static napi_value SppConnect(napi_env env, napi_callback_info info); static napi_value SppCloseClientSocket(napi_env env, napi_callback_info info); static napi_value SppWrite(napi_env env, napi_callback_info info); - static void On(napi_env env, napi_callback_info info); - static void Off(napi_env env, napi_callback_info info); + static napi_value On(napi_env env, napi_callback_info info); + static napi_value Off(napi_env env, napi_callback_info info); static void SppRead(int id); static std::map> clientMap; diff --git a/frameworks/js/napi/include/napi_bluetooth_utils.h b/frameworks/js/napi/include/napi_bluetooth_utils.h index c3e301ea..584a5f73 100644 --- a/frameworks/js/napi/include/napi_bluetooth_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_utils.h @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include @@ -91,7 +91,7 @@ struct SppOption { const std::string REGISTER_DEVICE_FIND_TYPE = "bluetoothDeviceFind"; const std::string REGISTER_STATE_CHANGE_TYPE = "stateChange"; const std::string REGISTER_PIN_REQUEST_TYPE = "pinRequired"; -const std::string REGISTER_BONE_STATE_TYPE = "bondStateChange"; +const std::string REGISTER_BOND_STATE_TYPE = "bondStateChange"; const std::string REGISTER_BLE_FIND_DEVICE_TYPE = "BLEDeviceFind"; const std::string REGISTER_SYS_BLE_SCAN_TYPE = "sysBLEScan"; const std::string REGISTER_SYS_BLE_FIND_DEVICE_TYPE = "sysBLEDeviceFonud"; @@ -105,7 +105,7 @@ bool ParseBool(napi_env env, bool ¶m, napi_value args); bool ParseArrayBuffer(napi_env env, uint8_t **data, size_t &size, napi_value args); napi_value GetCallbackErrorValue(napi_env env, int errCode); -void ConvertStringVectorToJS(napi_env env, napi_value result, std::vector &stringVector); +napi_status ConvertStringVectorToJS(napi_env env, napi_value result, std::vector &stringVector); void ConvertGattServiceToJS(napi_env env, napi_value result, GattService &service); void ConvertGattServiceVectorToJS(napi_env env, napi_value result, std::vector &services); @@ -155,6 +155,9 @@ void SetNamedPropertyByInteger(napi_env env, napi_value dstObj, int32_t objName, napi_value NapiGetNull(napi_env env); napi_value NapiGetBooleanFalse(napi_env env); napi_value NapiGetBooleanTrue(napi_env env); +napi_value NapiGetBooleanRet(napi_env env, bool ret); +napi_value NapiGetUndefinedRet(napi_env env); +napi_value NapiGetInt32Ret(napi_env env, int32_t res); napi_value RegisterObserver(napi_env env, napi_callback_info info); napi_value DeregisterObserver(napi_env env, napi_callback_info info); @@ -270,7 +273,6 @@ std::map> GetObserver(); const sysBLEMap &GetSysBLEObserver(); void SetGattClientDeviceId(const std::string &deviceId); std::string GetGattClientDeviceId(); -std::shared_ptr GetCallbackInfoByType(const std::string type); void SetRssiValueCallbackInfo(std::shared_ptr &callback); std::shared_ptr GetRssiValueCallbackInfo(); @@ -279,6 +281,7 @@ void SetCurrentAppOperate(const bool &isCurrentApp); bool GetCurrentAppOperate(); void RegisterSysBLEObserver(const std::shared_ptr &, int32_t, const std::string &); void UnregisterSysBLEObserver(const std::string &); +std::shared_ptr GetCallbackInfoByType(const std::string type); struct ScanFilter { std::string deviceId; // The name of a BLE peripheral device @@ -318,6 +321,32 @@ struct ScanResult { int32_t rssi; // RSSI of the remote device std::vector data; // The raw data of broadcast packet }; + +struct NapiAdvManufactureData { + uint16_t id = 0; + std::string value {}; +}; + +struct NapiAdvServiceData { + std::string uuid {}; + std::vector value {}; +}; + +struct NapiNotifyCharacteristic { + UUID serviceUuid; + UUID characterUuid; + std::vector characterValue {}; + bool confirm; +}; + +struct NapiGattsServerResponse { + std::string deviceId {}; + int transId; + int status; + int offset; + std::vector value; +}; + enum ProfileConnectionState { STATE_DISCONNECTED = 0, // the current profile is disconnected STATE_CONNECTING = 1, // the current profile is being connected @@ -533,6 +562,52 @@ void AfterWorkCallback(uv_work_t *work, int status) delete work; work = nullptr; } + +#define NAPI_BT_CALL_RETURN(func) \ + do { \ + napi_status ret = (func); \ + if (ret != napi_ok) { \ + HILOGE("napi call function failed. ret:%{public}d", ret); \ + return ret; \ + } \ + } while (0) + +#define NAPI_BT_RETURN_IF(condition, msg, ret) \ + do { \ + if ((condition)) { \ + HILOGE(msg); \ + return (ret); \ + } \ + } while (0) + +bool IsValidAddress(std::string bdaddr); +bool IsValidUuid(std::string uuid); +napi_status NapiIsBoolean(napi_env env, napi_value value); +napi_status NapiIsNumber(napi_env env, napi_value value); +napi_status NapiIsString(napi_env env, napi_value value); +napi_status NapiIsFunction(napi_env env, napi_value value); +napi_status NapiIsArray(napi_env env, napi_value value); +napi_status NapiIsArrayBuffer(napi_env env, napi_value value); +napi_status NapiIsObject(napi_env env, napi_value value); +napi_status ParseNumberParams(napi_env env, napi_value object, const char *name, bool &outExist, napi_value &outParam); +napi_status ParseInt32Params(napi_env env, napi_value object, const char *name, bool &outExist, int32_t &outParam); +napi_status ParseUint32Params(napi_env env, napi_value object, const char *name, bool &outExist, uint32_t &outParam); +napi_status ParseBooleanParams(napi_env env, napi_value object, const char *name, bool &outExist, bool &outParam); +napi_status ParseStringParams(napi_env env, napi_value object, const char *name, bool &outExist, + std::string &outParam); +napi_status ParseArrayBufferParams(napi_env env, napi_value object, const char *name, bool &outExist, + std::vector &outParam); +napi_status ParseUuidParams(napi_env env, napi_value object, const char *name, bool &outExist, UUID &outUuid); + +bool CheckDeivceIdParam(napi_env env, napi_callback_info info, std::string &addr); +bool CheckProfileIdParam(napi_env env, napi_callback_info info, int &profileId); +bool CheckSetDevicePairingConfirmationParam(napi_env env, napi_callback_info info, std::string &addr, bool &accept); +bool CheckLocalNameParam(napi_env env, napi_callback_info info, std::string &name); +bool CheckSetBluetoothScanModeParam(napi_env env, napi_callback_info info, int32_t &mode, int32_t &duration); +napi_status CheckDeregisterObserver(napi_env env, napi_callback_info info); +napi_status CheckEmptyParam(napi_env env, napi_callback_info info); +napi_status NapiCheckObjectPropertiesName(napi_env env, napi_value object, const std::vector &names); + } // namespace Bluetooth } // namespace OHOS #endif // NAPI_BLUETOOTH_UTILS_H diff --git a/frameworks/js/napi/src/napi_bluetooth_a2dp_snk.cpp b/frameworks/js/napi/src/napi_bluetooth_a2dp_snk.cpp index d2bdfe1b..4203912a 100644 --- a/frameworks/js/napi/src/napi_bluetooth_a2dp_snk.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_a2dp_snk.cpp @@ -15,6 +15,7 @@ #include "bluetooth_a2dp_snk.h" #include "napi_bluetooth_profile.h" #include "napi_bluetooth_a2dp_snk.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { @@ -40,7 +41,7 @@ void NapiA2dpSink::DefineA2dpSinkJSClass(napi_env env) sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_A2DP_SINK, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_A2DP_SINK, napiProfile); HILOGI("finished"); } @@ -54,76 +55,27 @@ napi_value NapiA2dpSink::A2dpSinkConstructor(napi_env env, napi_callback_info in napi_value NapiA2dpSink::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_a2dpSinkCallbackInfosMutex); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiA2dpSinkObserver::g_a2dpSinkCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - std::shared_ptr callbackInfo = std::make_shared(); - callbackInfo->env_ = env; - - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - observer_.callbackInfos_[type] = callbackInfo; - + ret = NapiEvent::OnEvent(env, info, observer_.callbackInfos_); if (!isRegistered_) { A2dpSink *profile = A2dpSink::GetProfile(); profile->RegisterObserver(&observer_); isRegistered_ = true; } - HILOGI("%{public}s is registered", type.c_str()); + HILOGI("Napi A2dpSink is registered"); return ret; } napi_value NapiA2dpSink::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_a2dpSinkCallbackInfosMutex); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiA2dpSinkObserver::g_a2dpSinkCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(env, observer_.callbackInfos_[type]->callback_, &refCount); - HILOGI("decrements the refernce count, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(env, observer_.callbackInfos_[type]->callback_); - } - observer_.callbackInfos_[type] = nullptr; - HILOGI("%{public}s is unregistered", type.c_str()); + ret = NapiEvent::OffEvent(env, info, observer_.callbackInfos_); + HILOGI("napi A2dpSink is unregistered"); return ret; } diff --git a/frameworks/js/napi/src/napi_bluetooth_a2dp_snk_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_a2dp_snk_observer.cpp index 0a0e1817..a489ed74 100644 --- a/frameworks/js/napi/src/napi_bluetooth_a2dp_snk_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_a2dp_snk_observer.cpp @@ -15,9 +15,12 @@ #include #include "bluetooth_utils.h" #include "napi_bluetooth_a2dp_snk_observer.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { +std::shared_mutex NapiA2dpSinkObserver::g_a2dpSinkCallbackInfosMutex; + void NapiA2dpSinkObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); @@ -33,42 +36,7 @@ void NapiA2dpSinkObserver::OnConnectionStateChanged(const BluetoothRemoteDevice callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_ref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("increments the reference count, refCount: %{public}d", refCount); - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - if (callback != nullptr) { - HILOGI("a2dp snk napi_call_function called"); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("uv_queue_work unref, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(callbackInfo->env_, callbackInfo->callback_); - } - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/napi_bluetooth_a2dp_src.cpp b/frameworks/js/napi/src/napi_bluetooth_a2dp_src.cpp index b682b014..9437233e 100644 --- a/frameworks/js/napi/src/napi_bluetooth_a2dp_src.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_a2dp_src.cpp @@ -13,8 +13,13 @@ * limitations under the License. */ #include "bluetooth_a2dp_src.h" +#include "bluetooth_errorcode.h" #include "napi_bluetooth_profile.h" #include "napi_bluetooth_a2dp_src.h" +#include "napi_bluetooth_event.h" +#include "napi_bluetooth_error.h" +#include "napi_bluetooth_host.h" +#include "napi_bluetooth_utils.h" namespace OHOS { namespace Bluetooth { @@ -41,7 +46,7 @@ void NapiA2dpSource::DefineA2dpSourceJSClass(napi_env env) napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_A2DP_SOURCE, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_A2DP_SOURCE, napiProfile); HILOGI("finished"); } @@ -55,79 +60,27 @@ napi_value NapiA2dpSource::A2dpSourceConstructor(napi_env env, napi_callback_inf napi_value NapiA2dpSource::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_a2dpSrcCallbackInfosMutex); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiA2dpSourceObserver::g_a2dpSrcCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - std::shared_ptr callbackInfo = std::make_shared(); - callbackInfo->env_ = env; - - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - observer_.callbackInfos_[type] = callbackInfo; - + ret = NapiEvent::OnEvent(env, info, observer_.callbackInfos_); if (!isRegistered_) { A2dpSource *profile = A2dpSource::GetProfile(); profile->RegisterObserver(&observer_); isRegistered_ = true; } - - HILOGI("%{public}s is registered", type.c_str()); + HILOGI("napi A2dpSource is registered"); return ret; } napi_value NapiA2dpSource::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_a2dpSrcCallbackInfosMutex); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiA2dpSourceObserver::g_a2dpSrcCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(env, observer_.callbackInfos_[type]->callback_, &refCount); - HILOGI("decrements the refernce count, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(env, observer_.callbackInfos_[type]->callback_); - } - observer_.callbackInfos_[type] = nullptr; - - HILOGI("%{public}s is unregistered", type.c_str()); - + ret = NapiEvent::OffEvent(env, info, observer_.callbackInfos_); + HILOGI("Napi A2dpSource is unregistered"); return ret; } @@ -183,103 +136,55 @@ napi_value NapiA2dpSource::GetDeviceState(napi_env env, napi_callback_info info) napi_value NapiA2dpSource::GetPlayingState(napi_env env, napi_callback_info info) { - HILOGI("enter"); - - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - + HILOGI("start"); + int state = PlayingState::STATE_NOT_PLAYING; napi_value ret = nullptr; - napi_get_undefined(env, &ret); + napi_create_int32(env, state, &ret); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN(env, checkRet, BT_ERR_INVALID_PARAM, ret); + int transport = GetDeviceTransport(remoteAddr); + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr, transport); A2dpSource *profile = A2dpSource::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - int res = profile->GetPlayingState(device); - if (res != PlayingState::STATE_PLAYING) { - res = PlayingState::STATE_NOT_PLAYING; - } - napi_value result = nullptr; - napi_create_int32(env, res, &result); + int32_t res = profile->GetPlayingState(remoteDevice, state); HILOGI("res: %{public}d", res); - return result; + NAPI_BT_ASSERT_RETURN(env, (res == BT_SUCCESS), res, ret); + + return NapiGetInt32Ret(env, state); } napi_value NapiA2dpSource::Connect(napi_env env, napi_callback_info info) { - HILOGI("enter"); - - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + HILOGI("start"); + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + int transport = GetDeviceTransport(remoteAddr); + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr, transport); A2dpSource *profile = A2dpSource::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool res = profile->Connect(device); + int32_t ret = profile->Connect(remoteDevice); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; + return NapiGetBooleanTrue(env); } napi_value NapiA2dpSource::Disconnect(napi_env env, napi_callback_info info) { - HILOGI("enter"); - - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + HILOGI("start"); + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + int transport = GetDeviceTransport(remoteAddr); + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr, transport); A2dpSource *profile = A2dpSource::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool res = profile->Disconnect(device); + int32_t ret = profile->Disconnect(remoteDevice); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; + return NapiGetBooleanTrue(env); } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_bluetooth_a2dp_src_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_a2dp_src_observer.cpp index 87218f9a..b9223f4c 100644 --- a/frameworks/js/napi/src/napi_bluetooth_a2dp_src_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_a2dp_src_observer.cpp @@ -15,9 +15,12 @@ #include #include "bluetooth_utils.h" #include "napi_bluetooth_a2dp_src_observer.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { + +std::shared_mutex NapiA2dpSourceObserver::g_a2dpSrcCallbackInfosMutex; void NapiA2dpSourceObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); @@ -29,47 +32,11 @@ void NapiA2dpSourceObserver::OnConnectionStateChanged(const BluetoothRemoteDevic HILOGW("This callback is not registered by ability."); return; } - std::shared_ptr callbackInfo = it->second; callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_ref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("increments the reference count, refCount: %{public}d", refCount); - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - if (callback != nullptr) { - HILOGI("a2dp src napi_call_function called"); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("uv_queue_work unref, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(callbackInfo->env_, callbackInfo->callback_); - } - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/napi_bluetooth_avrcp_ct.cpp b/frameworks/js/napi/src/napi_bluetooth_avrcp_ct.cpp index 27cb5a9c..32700aa6 100644 --- a/frameworks/js/napi/src/napi_bluetooth_avrcp_ct.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_avrcp_ct.cpp @@ -15,6 +15,7 @@ #include "bluetooth_avrcp_ct.h" #include "napi_bluetooth_avrcp_ct.h" #include "napi_bluetooth_profile.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { @@ -29,7 +30,7 @@ void NapiAvrcpController::DefineAvrcpControllerJSClass(napi_env env) napi_property_descriptor properties[] = { DECLARE_NAPI_FUNCTION("connect", Connect), DECLARE_NAPI_FUNCTION("disconnect", Disconnect), - DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("on", On), DECLARE_NAPI_FUNCTION("off", Off), DECLARE_NAPI_FUNCTION("getConnectionDevices", GetConnectionDevices), DECLARE_NAPI_FUNCTION("getDeviceState", GetDeviceState), @@ -39,7 +40,7 @@ void NapiAvrcpController::DefineAvrcpControllerJSClass(napi_env env) sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_AVRCP_CT, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_AVRCP_CT, napiProfile); HILOGI("finished"); } @@ -53,77 +54,28 @@ napi_value NapiAvrcpController::AvrcpControllerConstructor(napi_env env, napi_ca napi_value NapiAvrcpController::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_avrcpCtCallbackInfosMutex); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiAvrcpControllerObserver::g_avrcpCtCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - std::shared_ptr callbackInfo = std::make_shared(); - callbackInfo->env_ = env; - - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - observer_.callbackInfos_[type] = callbackInfo; - + ret = NapiEvent::OnEvent(env, info, observer_.callbackInfos_); if (!isRegistered_) { AvrcpController *profile = AvrcpController::GetProfile(); profile->RegisterObserver(&observer_); isRegistered_ = true; } - HILOGI("%{public}s is registered", type.c_str()); + HILOGI("Napi Avrcp is registered"); return ret; } napi_value NapiAvrcpController::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_avrcpCtCallbackInfosMutex); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiAvrcpControllerObserver::g_avrcpCtCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(env, observer_.callbackInfos_[type]->callback_, &refCount); - HILOGI("decrements the refernce count, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(env, observer_.callbackInfos_[type]->callback_); - } - observer_.callbackInfos_[type] = nullptr; - HILOGI("%{public}s is unregistered", type.c_str()); + ret = NapiEvent::OffEvent(env, info, observer_.callbackInfos_); + HILOGI("Napi Avrcp is unregistered"); return ret; } diff --git a/frameworks/js/napi/src/napi_bluetooth_avrcp_ct_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_avrcp_ct_observer.cpp index 0d2c1bbd..c3958e4f 100644 --- a/frameworks/js/napi/src/napi_bluetooth_avrcp_ct_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_avrcp_ct_observer.cpp @@ -15,9 +15,13 @@ #include #include "bluetooth_utils.h" #include "napi_bluetooth_avrcp_ct_observer.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { + +std::shared_mutex NapiAvrcpControllerObserver::g_avrcpCtCallbackInfosMutex; + void NapiAvrcpControllerObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); @@ -34,42 +38,7 @@ void NapiAvrcpControllerObserver::OnConnectionStateChanged(const BluetoothRemote callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_ref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("increments the reference count, refCount: %{public}d", refCount); - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - if (callback != nullptr) { - HILOGI("avrcp ct napi_call_function called"); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("uv_queue_work unref, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(callbackInfo->env_, callbackInfo->callback_); - } - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/napi_bluetooth_avrcp_tg.cpp b/frameworks/js/napi/src/napi_bluetooth_avrcp_tg.cpp index 28ef1bc6..5232d520 100644 --- a/frameworks/js/napi/src/napi_bluetooth_avrcp_tg.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_avrcp_tg.cpp @@ -15,6 +15,7 @@ #include "bluetooth_avrcp_tg.h" #include "napi_bluetooth_avrcp_tg.h" #include "napi_bluetooth_profile.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { @@ -27,9 +28,9 @@ void NapiAvrcpTarget::DefineAvrcpTargetJSClass(napi_env env) { napi_value constructor; napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("connect", Connect), + DECLARE_NAPI_FUNCTION("connect", Connect), DECLARE_NAPI_FUNCTION("disconnect", Disconnect), - DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("on", On), DECLARE_NAPI_FUNCTION("off", Off), DECLARE_NAPI_FUNCTION("getConnectionDevices", GetConnectionDevices), DECLARE_NAPI_FUNCTION("getDeviceState", GetDeviceState), @@ -39,7 +40,7 @@ void NapiAvrcpTarget::DefineAvrcpTargetJSClass(napi_env env) sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_AVRCP_TG, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_AVRCP_TG, napiProfile); HILOGI("finished"); } @@ -50,70 +51,30 @@ napi_value NapiAvrcpTarget::AvrcpTargetConstructor(napi_env env, napi_callback_i return thisVar; } -napi_value NapiAvrcpTarget::On(napi_env env, napi_callback_info info) { +napi_value NapiAvrcpTarget::On(napi_env env, napi_callback_info info) +{ HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiAvrcpTargetObserver::g_avrcpTgCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - std::shared_ptr callbackInfo = std::make_shared(); - callbackInfo->env_ = env; - - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - observer_.callbackInfos_[type] = callbackInfo; - + ret = NapiEvent::OnEvent(env, info, observer_.callbackInfos_); if (!isRegistered_) { AvrcpTarget *profile = AvrcpTarget::GetProfile(); profile->RegisterObserver(&observer_); isRegistered_ = true; } - HILOGI("%{public}s is registered", type.c_str()); + HILOGI("Napi Avrcp Target is registered"); return ret; } napi_value NapiAvrcpTarget::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiAvrcpTargetObserver::g_avrcpTgCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - observer_.callbackInfos_[type] = nullptr; - HILOGI("%{public}s is unregistered", type.c_str()); + ret = NapiEvent::OffEvent(env, info, observer_.callbackInfos_); + HILOGI("Napi Avrcp Target is unregistered"); return ret; } diff --git a/frameworks/js/napi/src/napi_bluetooth_avrcp_tg_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_avrcp_tg_observer.cpp index dffea61e..a46ec076 100644 --- a/frameworks/js/napi/src/napi_bluetooth_avrcp_tg_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_avrcp_tg_observer.cpp @@ -15,46 +15,29 @@ #include #include "bluetooth_utils.h" #include "napi_bluetooth_avrcp_tg_observer.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { + +std::shared_mutex NapiAvrcpTargetObserver::g_avrcpTgCallbackInfosMutex; void NapiAvrcpTargetObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); - if (!callbackInfos_[STR_BT_AVRCP_TG_CONNECTION_STATE_CHANGE]) { + std::unique_lock guard(g_avrcpTgCallbackInfosMutex); + + std::map>::iterator it = + callbackInfos_.find(STR_BT_AVRCP_TG_CONNECTION_STATE_CHANGE); + if (it == callbackInfos_.end() || it->second == nullptr) { HILOGW("This callback is not registered by ability."); return; } HILOGI("%{public}s is registered by ability", STR_BT_AVRCP_TG_CONNECTION_STATE_CHANGE.c_str()); - std::shared_ptr callbackInfo = - callbackInfos_[STR_BT_AVRCP_TG_CONNECTION_STATE_CHANGE]; + std::shared_ptr callbackInfo = it->second; callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/napi_bluetooth_ble.cpp index 4dd3424b..a6abdc8b 100644 --- a/frameworks/js/napi/src/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_ble.cpp @@ -16,13 +16,16 @@ #include "napi_bluetooth_ble_advertise_callback.h" #include "napi_bluetooth_ble_central_manager_callback.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_gatt_client.h" #include "napi_bluetooth_gatt_server.h" #include "napi_bluetooth_utils.h" #include "bluetooth_ble_advertiser.h" #include "bluetooth_ble_central_manager.h" +#include "bluetooth_errorcode.h" #include "bluetooth_utils.h" +#include "parser/napi_parser_utils.h" #include namespace OHOS { @@ -297,653 +300,390 @@ static void ConvertDutyMode(ScanOptions ¶ms, int32_t dutyMode) } } -static napi_value ParseScanParameters( +static napi_status ParseScanParameters( const napi_env &env, const napi_callback_info &info, const napi_value &scanArg, ScanOptions ¶ms) { - size_t argc = ARGS_SIZE_THREE; - napi_value argv[ARGS_SIZE_THREE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); - } + (void)info; + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, scanArg, {"interval", "dutyMode", "matchMode"})); - bool hasProperty = false; - napi_valuetype valuetype = napi_undefined; - napi_value result = nullptr; - - NAPI_CALL(env, napi_has_named_property(env, scanArg, "interval", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanArg, "interval", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, result, ¶ms.interval); - HILOGI("Scan interval is %{public}d", params.interval); + bool exist = false; + int32_t interval = 0; + NAPI_BT_CALL_RETURN(ParseInt32Params(env, scanArg, "interval", exist, interval)); + if (exist) { + HILOGI("Scan interval is %{public}d", interval); + params.interval = interval; } - NAPI_CALL(env, napi_has_named_property(env, scanArg, "dutyMode", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanArg, "dutyMode", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int32_t dutyMode = 0; - napi_get_value_int32(env, result, &dutyMode); + int32_t dutyMode = 0; + NAPI_BT_CALL_RETURN(ParseInt32Params(env, scanArg, "dutyMode", exist, dutyMode)); + if (exist) { HILOGI("Scan dutyMode is %{public}d", dutyMode); ConvertDutyMode(params, dutyMode); } - NAPI_CALL(env, napi_has_named_property(env, scanArg, "matchMode", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanArg, "matchMode", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int32_t matchMode = -1; - napi_get_value_int32(env, result, &matchMode); + int32_t matchMode = 0; + NAPI_BT_CALL_RETURN(ParseInt32Params(env, scanArg, "matchMode", exist, matchMode)); + if (exist) { HILOGI("Scan matchMode is %{public}d", matchMode); ConvertMatchMode(params, matchMode); } - return NapiGetNull(env); + return napi_ok; } -static napi_value ParseScanFilterDeviceIdParameters( +static napi_status ParseScanFilterDeviceIdParameters( const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { - napi_value result; - bool hasProperty = false; - ScanFilter filter; - - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "deviceId", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "deviceId", &result); - bool isSuccess = ParseString(env, filter.deviceId, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); + bool exist = false; + std::string deviceId {}; + NAPI_BT_CALL_RETURN(ParseStringParams(env, scanFilter, "deviceId", exist, deviceId)); + if (exist) { + if (!IsValidAddress(deviceId)) { + HILOGE("Invalid deviceId: %{public}s", deviceId.c_str()); + return napi_invalid_arg; } - bleScanFilter.SetDeviceId(filter.deviceId); - HILOGI("Scan filter device id is %{public}s", GetEncryptAddr(filter.deviceId).c_str()); + + HILOGI("Scan filter device id is %{public}s", GetEncryptAddr(deviceId).c_str()); + bleScanFilter.SetDeviceId(deviceId); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseScanFilterLocalNameParameters( +static napi_status ParseScanFilterLocalNameParameters( const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { - napi_value result; - bool hasProperty = false; - ScanFilter filter; - - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "name", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "name", &result); - bool isSuccess = ParseString(env, filter.name, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); + bool exist = false; + std::string name {}; + NAPI_BT_CALL_RETURN(ParseStringParams(env, scanFilter, "name", exist, name)); + if (exist) { + if (name.empty()) { + HILOGE("name is empty"); + return napi_invalid_arg; } - bleScanFilter.SetName(filter.name); - HILOGI("Scan filter name is %{public}s", filter.name.c_str()); + HILOGI("Scan filter name is %{public}s", name.c_str()); + bleScanFilter.SetName(name); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseScanFilterServiceUuidParameters( +static napi_status ParseScanFilterServiceUuidParameters( const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { - napi_value result; - bool hasProperty = false; - ScanFilter filter; - - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "serviceUuid", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "serviceUuid", &result); - std::string serviceUuid; - bool isSuccess = ParseString(env, serviceUuid, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); - } - HILOGI("Scan filter serviceUuid is %{public}s", serviceUuid.c_str()); - if (!serviceUuid.empty()) { - if (!regex_match(serviceUuid, uuidRegex)) { - HILOGE("match the UUID faild."); - return NapiGetBooleanFalse(env); - } - filter.serviceUuid = ParcelUuid::FromString(serviceUuid); - bleScanFilter.SetServiceUuid(filter.serviceUuid); - } + bool exist = false; + UUID uuid {}; + NAPI_BT_CALL_RETURN(ParseUuidParams(env, scanFilter, "serviceUuid", exist, uuid)); + if (exist) { + HILOGI("Scan filter serviceUuid is %{public}s", uuid.ToString().c_str()); + bleScanFilter.SetServiceUuid(uuid); } - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "serviceUuidMask", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "serviceUuidMask", &result); - std::string serviceUuidMask; - bool isSuccess = ParseString(env, serviceUuidMask, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); - } - HILOGI("Scan filter serviceUuidMask is %{public}s", serviceUuidMask.c_str()); - if (!serviceUuidMask.empty()) { - if (!regex_match(serviceUuidMask, uuidRegex)) { - HILOGE("match the UUID faild."); - return NapiGetBooleanFalse(env); - } - filter.serviceUuidMask = ParcelUuid::FromString(serviceUuidMask); - bleScanFilter.SetServiceUuidMask(filter.serviceUuidMask); - } + UUID uuidMask {}; + NAPI_BT_CALL_RETURN(ParseUuidParams(env, scanFilter, "serviceUuidMask", exist, uuidMask)); + if (exist) { + HILOGI("Scan filter serviceUuidMask is %{public}s", uuidMask.ToString().c_str()); + bleScanFilter.SetServiceUuidMask(uuidMask); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseScanFilterSolicitationUuidParameters( +static napi_status ParseScanFilterSolicitationUuidParameters( const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { - napi_value result; - bool hasProperty = false; - ScanFilter filter; - - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "serviceSolicitationUuid", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "serviceSolicitationUuid", &result); - std::string serviceSolicitationUuid; - bool isSuccess = ParseString(env, serviceSolicitationUuid, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); - } - HILOGI("Scan filter serviceSolicitationUuid is %{public}s", serviceSolicitationUuid.c_str()); - if (!serviceSolicitationUuid.empty()) { - if (!regex_match(serviceSolicitationUuid, uuidRegex)) { - HILOGE("match the UUID faild."); - return NapiGetBooleanFalse(env); - } - filter.serviceSolicitationUuid = ParcelUuid::FromString(serviceSolicitationUuid); - bleScanFilter.SetServiceSolicitationUuid(filter.serviceSolicitationUuid); - } + bool exist = false; + UUID uuid {}; + NAPI_BT_CALL_RETURN(ParseUuidParams(env, scanFilter, "serviceSolicitationUuid", exist, uuid)); + if (exist) { + HILOGI("Scan filter serviceSolicitationUuid is %{public}s", uuid.ToString().c_str()); + bleScanFilter.SetServiceSolicitationUuid(uuid); } - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "serviceSolicitationUuidMask", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "serviceSolicitationUuidMask", &result); - std::string serviceSolicitationUuidMask; - bool isSuccess = ParseString(env, serviceSolicitationUuidMask, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); - } - HILOGI("Scan filter serviceSolicitationUuidMask is %{public}s", serviceSolicitationUuidMask.c_str()); - if (!serviceSolicitationUuidMask.empty()) { - if (!regex_match(serviceSolicitationUuidMask, uuidRegex)) { - HILOGE("match the UUID faild."); - return NapiGetBooleanFalse(env); - } - filter.serviceSolicitationUuidMask = ParcelUuid::FromString(serviceSolicitationUuidMask); - bleScanFilter.SetServiceSolicitationUuidMask(filter.serviceSolicitationUuidMask); - } + UUID uuidMask {}; + NAPI_BT_CALL_RETURN(ParseUuidParams(env, scanFilter, "serviceSolicitationUuidMask", exist, uuidMask)); + if (exist) { + HILOGI("Scan filter serviceSolicitationUuidMask is %{public}s", uuidMask.ToString().c_str()); + bleScanFilter.SetServiceSolicitationUuidMask(uuidMask); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseScanFilterServiceDataParameters( +static napi_status ParseScanFilterServiceDataParameters( const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { - napi_value result; - bool hasProperty = false; - ScanFilter filter; - - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "serviceData", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "serviceData", &result); - bool isArrayBuffer = false; - napi_is_arraybuffer(env, result, &isArrayBuffer); - if (isArrayBuffer) { - uint8_t *arrayBufferData = nullptr; - size_t arrayBufferTotal = 0; - bool isSuccess = ParseArrayBuffer(env, &arrayBufferData, arrayBufferTotal, result); - if (!isSuccess) { - HILOGE("ParseArrayBuffer faild."); - return NapiGetBooleanFalse(env); - } - filter.serviceData = std::vector(arrayBufferData, arrayBufferData + arrayBufferTotal); - } - bleScanFilter.SetServiceData(filter.serviceData); + bool exist = false; + std::vector data {}; + NAPI_BT_CALL_RETURN(ParseArrayBufferParams(env, scanFilter, "serviceData", exist, data)); + if (exist) { + bleScanFilter.SetServiceData(std::move(data)); } - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "serviceDataMask", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "serviceDataMask", &result); - bool isArrayBuffer = false; - napi_is_arraybuffer(env, result, &isArrayBuffer); - if (isArrayBuffer) { - uint8_t *arrayBufferData = nullptr; - size_t arrayBufferTotal = 0; - bool isSuccess = ParseArrayBuffer(env, &arrayBufferData, arrayBufferTotal, result); - if (!isSuccess) { - HILOGE("ParseArrayBuffer faild."); - return NapiGetBooleanFalse(env); - } - filter.serviceDataMask = std::vector(arrayBufferData, arrayBufferData + arrayBufferTotal); - } - bleScanFilter.SetServiceDataMask(filter.serviceDataMask); + std::vector dataMask {}; + NAPI_BT_CALL_RETURN(ParseArrayBufferParams(env, scanFilter, "serviceDataMask", exist, dataMask)); + if (exist) { + bleScanFilter.SetServiceDataMask(std::move(dataMask)); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseScanFilterManufactureDataParameters( +static napi_status ParseScanFilterManufactureDataParameters( const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { + bool exist = false; napi_value result; - bool hasProperty = false; - ScanFilter filter; - - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "manufacturerId", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "manufacturerId", &result); + NAPI_BT_CALL_RETURN(ParseNumberParams(env, scanFilter, "manufactureId", exist, result)); + if (exist) { uint32_t manufacturerId = 0; - napi_get_value_uint32(env, result, &manufacturerId); - filter.manufacturerId = manufacturerId; - bleScanFilter.SetManufacturerId(filter.manufacturerId); - HILOGI("Scan filter manufacturerId is %{public}d", filter.manufacturerId); + NAPI_BT_CALL_RETURN(napi_get_value_uint32(env, result, &manufacturerId)); + bleScanFilter.SetManufacturerId(manufacturerId); + HILOGI("Scan filter manufacturerId is %{public}#x", manufacturerId); } - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "manufactureData", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "manufactureData", &result); - bool isArrayBuffer = false; - napi_is_arraybuffer(env, result, &isArrayBuffer); - if (isArrayBuffer) { - uint8_t *arrayBufferData = nullptr; - size_t arrayBufferTotal = 0; - bool isSuccess = ParseArrayBuffer(env, &arrayBufferData, arrayBufferTotal, result); - if (!isSuccess) { - HILOGE("ParseArrayBuffer faild."); - return NapiGetBooleanFalse(env); - } - filter.manufactureData = std::vector(arrayBufferData, arrayBufferData + arrayBufferTotal); - } - bleScanFilter.SetManufactureData(filter.manufactureData); + exist = false; + std::vector data {}; + NAPI_BT_CALL_RETURN(ParseArrayBufferParams(env, scanFilter, "manufactureData", exist, data)); + if (exist) { + bleScanFilter.SetManufactureData(std::move(data)); } - NAPI_CALL(env, napi_has_named_property(env, scanFilter, "manufactureDataMask", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, scanFilter, "manufactureDataMask", &result); - bool isArrayBuffer = false; - napi_is_arraybuffer(env, result, &isArrayBuffer); - if (isArrayBuffer) { - uint8_t *arrayBufferData = nullptr; - size_t arrayBufferTotal = 0; - bool isSuccess = ParseArrayBuffer(env, &arrayBufferData, arrayBufferTotal, result); - if (!isSuccess) { - HILOGE("ParseArrayBuffer faild."); - return NapiGetBooleanFalse(env); - } - filter.manufactureDataMask = - std::vector(arrayBufferData, arrayBufferData + arrayBufferTotal); - } - bleScanFilter.SetManufactureDataMask(filter.manufactureDataMask); + std::vector dataMask {}; + NAPI_BT_CALL_RETURN(ParseArrayBufferParams(env, scanFilter, "manufactureDataMask", exist, dataMask)); + if (exist) { + bleScanFilter.SetManufactureDataMask(std::move(dataMask)); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static bool ParseScanFilter(const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) +static napi_status ParseScanFilter(const napi_env &env, napi_value &scanFilter, BleScanFilter &bleScanFilter) { HILOGI("enter"); - bool isSuccess = true; - napi_get_value_bool(env, ParseScanFilterDeviceIdParameters(env, scanFilter, bleScanFilter), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterDeviceIdParameters faild."); - return false; - } - napi_get_value_bool(env, ParseScanFilterLocalNameParameters(env, scanFilter, bleScanFilter), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterLocalNameParameters faild."); - return false; - } - napi_get_value_bool(env, ParseScanFilterServiceUuidParameters(env, scanFilter, bleScanFilter), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterServiceUuidParameters faild."); - return false; - } - napi_get_value_bool(env, ParseScanFilterSolicitationUuidParameters(env, scanFilter, bleScanFilter), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterSolicitationUuidParameters faild."); - return false; - } - napi_get_value_bool(env, ParseScanFilterServiceDataParameters(env, scanFilter, bleScanFilter), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterServiceDataParameters faild."); - return false; - } - napi_get_value_bool(env, ParseScanFilterManufactureDataParameters(env, scanFilter, bleScanFilter), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterManufactureDataParameters faild."); - return false; - } - return true; + std::vector expectedNames {"deviceId", "name", "serviceUuid", "serviceUuidMask", + "serviceSolicitationUuid", "serviceSolicitationUuidMask", "serviceData", "serviceDataMask", "manufactureId", + "manufactureData", "manufactureDataMask"}; + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, scanFilter, expectedNames)); + + NAPI_BT_CALL_RETURN(ParseScanFilterDeviceIdParameters(env, scanFilter, bleScanFilter)); + NAPI_BT_CALL_RETURN(ParseScanFilterLocalNameParameters(env, scanFilter, bleScanFilter)); + NAPI_BT_CALL_RETURN(ParseScanFilterServiceUuidParameters(env, scanFilter, bleScanFilter)); + NAPI_BT_CALL_RETURN(ParseScanFilterSolicitationUuidParameters(env, scanFilter, bleScanFilter)); + NAPI_BT_CALL_RETURN(ParseScanFilterServiceDataParameters(env, scanFilter, bleScanFilter)); + NAPI_BT_CALL_RETURN(ParseScanFilterManufactureDataParameters(env, scanFilter, bleScanFilter)); + return napi_ok; } -static napi_value ParseScanFilterParameters(const napi_env &env, napi_value &args, std::vector ¶ms) +static napi_status ParseScanFilterParameters(const napi_env &env, napi_value &args, std::vector ¶ms) { HILOGI("enter"); - if (args == nullptr) { - return NapiGetBooleanTrue(env); - } - - bool isArray = false; - napi_is_array(env, args, &isArray); - if (isArray) { - uint32_t length = 0; - napi_get_array_length(env, args, &length); - for (size_t i = 0; i < length; i++) { - napi_value scanFilter; - napi_valuetype valuetype = napi_undefined; - napi_get_element(env, args, i, &scanFilter); - NAPI_CALL(env, napi_typeof(env, scanFilter, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - - BleScanFilter bleScanFilter; - bool isSuccess = ParseScanFilter(env, scanFilter, bleScanFilter); - if (!isSuccess) { - HILOGE("ParseScanFilter faild."); - return NapiGetBooleanFalse(env); - } - - params.push_back(bleScanFilter); - } + NAPI_BT_CALL_RETURN(NapiIsArray(env, args)); + + uint32_t length = 0; + NAPI_BT_CALL_RETURN(napi_get_array_length(env, args, &length)); + NAPI_BT_RETURN_IF(length == 0, "Requires array length > 0", napi_invalid_arg); + for (uint32_t i = 0; i < length; i++) { + napi_value scanFilter; + NAPI_BT_CALL_RETURN(napi_get_element(env, args, i, &scanFilter)); + NAPI_BT_CALL_RETURN(NapiIsObject(env, scanFilter)); + BleScanFilter bleScanFilter; + NAPI_BT_CALL_RETURN(ParseScanFilter(env, scanFilter, bleScanFilter)); + params.push_back(bleScanFilter); } - return NapiGetBooleanTrue(env); + return napi_ok; } -napi_value StartBLEScan(napi_env env, napi_callback_info info) +static napi_status CheckBleScanParams(napi_env env, napi_callback_info info, std::vector &outScanfilters, + BleScanSettings &outSettinngs) { - HILOGI("enter"); size_t argc = ARGS_SIZE_TWO; napi_value argv[ARGS_SIZE_TWO] = {nullptr}; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - HILOGE("Requires 1 or 2 arguments."); - return NapiGetNull(env); - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF((argc == 0 || argc > ARGS_SIZE_TWO), "Requires 1 or 2 arguments.", napi_invalid_arg); std::vector scanfilters; - if (argv[PARAM0] != nullptr) { - bool isSuccess = true; - napi_get_value_bool(env, ParseScanFilterParameters(env, argv[PARAM0], scanfilters), &isSuccess); - if (!isSuccess) { - HILOGE("ParseScanFilterParameters faild."); - return NapiGetNull(env); - } + // Support null param + napi_valuetype type = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, argv[PARAM0], &type)); + if (type == napi_null) { + BleScanFilter emptyFilter; + scanfilters.push_back(emptyFilter); + } else { + NAPI_BT_CALL_RETURN(ParseScanFilterParameters(env, argv[PARAM0], scanfilters)); } - bleCentralManager->ConfigScanFilter(scanfilters); - BleScanSettings settinngs; - if (argv[PARAM1] != nullptr) { + if (argc == ARGS_SIZE_TWO) { ScanOptions scanOptions; - ParseScanParameters(env, info, argv[PARAM1], scanOptions); - settinngs.SetReportDelay(scanOptions.interval); - settinngs.SetScanMode(static_cast(scanOptions.dutyMode)); + NAPI_BT_CALL_RETURN(ParseScanParameters(env, info, argv[PARAM1], scanOptions)); + outSettinngs.SetReportDelay(scanOptions.interval); + outSettinngs.SetScanMode(static_cast(scanOptions.dutyMode)); } - bleCentralManager->StartScan(settinngs); - return NapiGetNull(env); + outScanfilters = std::move(scanfilters); + return napi_ok; } -napi_value StopBLEScan(napi_env env, napi_callback_info info) +napi_value StartBLEScan(napi_env env, napi_callback_info info) { HILOGI("enter"); - bleCentralManager->StopScan(); - return NapiGetNull(env); + std::vector scanfilters; + BleScanSettings settinngs; + auto status = CheckBleScanParams(env, info, scanfilters, settinngs); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + + if (bleCentralManager) { + int ret = bleCentralManager->ConfigScanFilter(scanfilters); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR, ret); + ret = bleCentralManager->StartScan(settinngs); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR, ret); + } + return NapiGetUndefinedRet(env); } -static napi_value ParseAdvertisingSettingsParameters( - const napi_env &env, const napi_callback_info &info, const napi_value &args, BleAdvertiserSettings &settings) +napi_value StopBLEScan(napi_env env, napi_callback_info info) { HILOGI("enter"); - bool hasProperty = false; - napi_valuetype valuetype = napi_undefined; - napi_value result = nullptr; + auto status = CheckEmptyParam(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + int ret = bleCentralManager->StopScan(); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == NO_ERROR, ret); + return NapiGetUndefinedRet(env); +} - NAPI_CALL(env, napi_has_named_property(env, args, "interval", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, args, "interval", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int32_t interval = 0; - napi_get_value_int32(env, result, &interval); - HILOGI("interval is %{public}d", interval); - settings.SetInterval(interval); - } - NAPI_CALL(env, napi_has_named_property(env, args, "txPower", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, args, "txPower", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int32_t txPower = 0; - napi_get_value_int32(env, result, &txPower); +static napi_status ParseAdvertisingSettingsParameters( + const napi_env &env, const napi_callback_info &info, const napi_value &object, BleAdvertiserSettings &outSettings) +{ + HILOGI("enter"); + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"interval", "txPower", "connectable"})); + + bool exist = false; + uint32_t interval = 0; + NAPI_BT_CALL_RETURN(NapiParseObjectUint32Optional(env, object, "interval", interval, exist)); + if (exist) { + HILOGI("interval: %{public}u", interval); + outSettings.SetInterval(interval); + } + + int32_t txPower = 0; + NAPI_BT_CALL_RETURN(NapiParseObjectInt32Optional(env, object, "txPower", txPower, exist)); + if (exist) { + const int32_t minTxPower = -127; + const int32_t maxTxPower = 1; + if (txPower < minTxPower || txPower > maxTxPower) { + HILOGE("Invalid tx power: %{public}d", txPower); + return napi_invalid_arg; + } HILOGI("txPower is %{public}d", txPower); - settings.SetTxPower(txPower); + outSettings.SetTxPower(txPower); } - NAPI_CALL(env, napi_has_named_property(env, args, "connectable", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, args, "connectable", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Boolean expected."); - bool connectable = true; - napi_get_value_bool(env, result, &connectable); - HILOGI("connectable is %{public}d", connectable); - settings.SetConnectable(connectable); + bool connectable = false; + NAPI_BT_CALL_RETURN(NapiParseObjectBooleanOptional(env, object, "connectable", connectable, exist)); + if (exist) { + HILOGI("connectable: %{public}d", connectable); + outSettings.SetConnectable(connectable); } - return NapiGetNull(env); + return napi_ok; } -static napi_value ParseServiceUuidParameters(const napi_env &env, const napi_value &args, BleAdvertiserData &data) +static napi_status ParseServiceUuidParameters(napi_env env, napi_value object, BleAdvertiserData &outData) { HILOGI("enter"); - napi_value result = nullptr; - - napi_get_named_property(env, args, "serviceUuids", &result); - bool isArray = false; - napi_is_array(env, result, &isArray); - NAPI_ASSERT(env, isArray, "Wrong argument type. Array expected."); - uint32_t length = 0; - napi_get_array_length(env, result, &length); - NAPI_ASSERT(env, length > 0, "The array is empty."); - for (size_t serviceUuidIter = 0; serviceUuidIter < length; ++serviceUuidIter) { - napi_value uuid = nullptr; - napi_get_element(env, result, serviceUuidIter, &uuid); - std::string serviceUuid; - bool isSuccess = ParseString(env, serviceUuid, uuid); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); - } - if (!regex_match(serviceUuid, uuidRegex)) { - HILOGE("Match the UUID faild."); - return NapiGetBooleanFalse(env); - } - data.AddServiceUuid(ParcelUuid::FromString(serviceUuid)); - HILOGI("Service Uuid = %{public}s", serviceUuid.c_str()); + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiParseObjectArray(env, object, "serviceUuids", vec)); + for (size_t i = 0; i < vec.size(); ++i) { + outData.AddServiceUuid(vec[i]); + HILOGI("Service Uuid = %{public}s", vec[i].ToString().c_str()); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseManufactureDataParameters(const napi_env &env, const napi_value &args, BleAdvertiserData &data) +static napi_status ParseManufactureDataParameters(napi_env env, napi_value object, BleAdvertiserData &outData) { HILOGI("enter"); - napi_value result = nullptr; - - napi_get_named_property(env, args, "manufactureData", &result); - bool isArray = false; - napi_is_array(env, result, &isArray); - NAPI_ASSERT(env, isArray, "Wrong argument type. Array expected."); - uint32_t length = 0; - napi_get_array_length(env, result, &length); - if (length == 0) { - HILOGE("The array is empty."); - return NapiGetBooleanTrue(env); - } - for (size_t manufactureDataIter = 0; manufactureDataIter < length; ++manufactureDataIter) { - napi_value manufactureData = nullptr; - napi_valuetype valuetype = napi_undefined; - napi_get_element(env, result, manufactureDataIter, &manufactureData); - NAPI_CALL(env, napi_typeof(env, manufactureData, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, manufactureData, "manufactureId", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "manufactureId expected."); - napi_get_named_property(env, manufactureData, "manufactureId", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int32_t manufactureId = 0; - napi_get_value_int32(env, result, &manufactureId); - HILOGI("manufactureId = %{public}d", manufactureId); - NAPI_CALL(env, napi_has_named_property(env, manufactureData, "manufactureValue", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "manufactureValue expected."); - napi_get_named_property(env, manufactureData, "manufactureValue", &result); - bool isArrayBuffer = false; - napi_is_arraybuffer(env, result, &isArrayBuffer); - if (isArrayBuffer) { - uint8_t *arrayBufferData = nullptr; - size_t arrayBufferTotal = 0; - bool isSuccess = ParseArrayBuffer(env, &arrayBufferData, arrayBufferTotal, result); - if (!isSuccess) { - HILOGE("ParseArrayBuffer faild."); - return NapiGetBooleanFalse(env); - } - std::string manuData(arrayBufferData, arrayBufferData + arrayBufferTotal); - data.AddManufacturerData(manufactureId, manuData); - } + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiParseObjectArray(env, object, "manufactureData", vec)); + for (size_t i = 0; i < vec.size(); ++i) { + outData.AddManufacturerData(vec[i].id, vec[i].value); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseServiceDataParameters(const napi_env &env, const napi_value &args, BleAdvertiserData &data) +static napi_status ParseServiceDataParameters(napi_env env, napi_value object, BleAdvertiserData &outData) { HILOGI("enter"); - napi_valuetype valuetype = napi_undefined; - napi_value result = nullptr; - napi_get_named_property(env, args, "serviceData", &result); - bool isArray = false; - napi_is_array(env, result, &isArray); - NAPI_ASSERT(env, isArray, "Wrong argument type. Array expected."); - uint32_t length = 0; - napi_get_array_length(env, result, &length); - if (length == 0) { - HILOGE("The array is empty."); - return NapiGetBooleanTrue(env); - } - for (size_t serviceDataIter = 0; serviceDataIter < length; ++serviceDataIter) { - napi_value serviceData = nullptr; - napi_get_element(env, result, serviceDataIter, &serviceData); - NAPI_CALL(env, napi_typeof(env, serviceData, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, serviceData, "serviceUuid", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "serviceUuid expected."); - napi_get_named_property(env, serviceData, "serviceUuid", &result); - std::string serviceBuffer; - bool isSuccess = ParseString(env, serviceBuffer, result); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); - } - if (!regex_match(serviceBuffer, uuidRegex)) { - HILOGE("Match the UUID faild."); - return NapiGetBooleanFalse(env); - } - ParcelUuid serviceUuid(ParcelUuid::FromString(serviceBuffer)); - HILOGI("serviceUuid = %{public}s", serviceUuid.ToString().c_str()); - - NAPI_CALL(env, napi_has_named_property(env, serviceData, "serviceValue", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "serviceValue expected."); - napi_get_named_property(env, serviceData, "serviceValue", &result); - bool isArrayBuffer = false; - napi_is_arraybuffer(env, result, &isArrayBuffer); - NAPI_ASSERT(env, isArrayBuffer, "Array buffer expected."); - uint8_t *arrayBufferData = nullptr; - size_t arrayBufferTotal; - napi_get_arraybuffer_info(env, result, reinterpret_cast(&arrayBufferData), &arrayBufferTotal); - std::string serviceDataStr(arrayBufferData, arrayBufferData + arrayBufferTotal); - data.AddServiceData(serviceUuid, serviceDataStr); + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiParseObjectArray(env, object, "serviceData", vec)); + for (size_t i = 0; i < vec.size(); ++i) { + outData.AddServiceData( + ParcelUuid::FromString(vec[i].uuid), + std::string(vec[i].value.begin(), vec[i].value.end())); } - return NapiGetBooleanTrue(env); + return napi_ok; } -static napi_value ParseAdvertisDataParameters( - const napi_env &env, const napi_callback_info &info, const napi_value &args, BleAdvertiserData &data) +static napi_status ParseAdvertisDataParameters(const napi_env &env, const napi_callback_info &info, + const napi_value &object, BleAdvertiserData &outData) { - HILOGI("enter"); - bool hasProperty = false; - bool isSuccess = true; - NAPI_CALL(env, napi_has_named_property(env, args, "serviceUuids", &hasProperty)); - if (hasProperty) { - napi_get_value_bool(env, ParseServiceUuidParameters(env, args, data), &isSuccess); - if (!isSuccess) { - HILOGE("ParseServiceUuidParameters faild."); - return NapiGetBooleanFalse(env); - } - } - NAPI_CALL(env, napi_has_named_property(env, args, "manufactureData", &hasProperty)); - if (hasProperty) { - napi_get_value_bool(env, ParseManufactureDataParameters(env, args, data), &isSuccess); - if (!isSuccess) { - HILOGE("ParseManufactureDataParameters faild."); - return NapiGetBooleanFalse(env); - } - } - NAPI_CALL(env, napi_has_named_property(env, args, "serviceData", &hasProperty)); - if (hasProperty) { - napi_get_value_bool(env, ParseServiceDataParameters(env, args, data), &isSuccess); - if (!isSuccess) { - HILOGE("ParseServiceDataParameters faild."); - return NapiGetBooleanFalse(env); - } - } - return NapiGetBooleanTrue(env); + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"serviceUuids", "manufactureData", "serviceData"})); + + NAPI_BT_CALL_RETURN(ParseServiceUuidParameters(env, object, outData)); + NAPI_BT_CALL_RETURN(ParseManufactureDataParameters(env, object, outData)); + NAPI_BT_CALL_RETURN(ParseServiceDataParameters(env, object, outData)); + return napi_ok; } -napi_value StartAdvertising(napi_env env, napi_callback_info info) +napi_status CheckAdvertisingData(napi_env env, napi_callback_info info, BleAdvertiserSettings &outSettings, + BleAdvertiserData &outAdvData, BleAdvertiserData &outRspData) { - HILOGI("enter"); size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {nullptr}; napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - HILOGE("Requires 2 or 3 arguments."); - return NapiGetNull(env); - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_TWO && argc != ARGS_SIZE_THREE), "need 2 or 3 arguments.", napi_invalid_arg); + BleAdvertiserSettings settings; - ParseAdvertisingSettingsParameters(env, info, argv[PARAM0], settings); - BleAdvertiserData AdvData; - bool isSuccess = true; - napi_get_value_bool(env, ParseAdvertisDataParameters(env, info, argv[PARAM1], AdvData), &isSuccess); - if (!isSuccess) { - HILOGE("ParseAdvertisDataParameters faild."); - return NapiGetNull(env); - } - BleAdvertiserData ScanRespData; - if (argv[PARAM2] != nullptr) { - napi_get_value_bool(env, ParseAdvertisDataParameters(env, info, argv[PARAM2], ScanRespData), &isSuccess); - if (!isSuccess) { - HILOGE("ParseAdvertisDataParameters faild."); - return NapiGetNull(env); - } + NAPI_BT_CALL_RETURN(ParseAdvertisingSettingsParameters(env, info, argv[PARAM0], settings)); + BleAdvertiserData advData; + NAPI_BT_CALL_RETURN(ParseAdvertisDataParameters(env, info, argv[PARAM1], advData)); + BleAdvertiserData rspData; + if (argc == ARGS_SIZE_THREE) { + NAPI_BT_CALL_RETURN(ParseAdvertisDataParameters(env, info, argv[PARAM2], rspData)); } - bleAdvertiser.StartAdvertising(settings, AdvData, ScanRespData, bleAdvertiseCallback); - return NapiGetNull(env); + outSettings = std::move(settings); + outAdvData = std::move(advData); + outRspData = std::move(rspData); + return napi_ok; +} + +napi_value StartAdvertising(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + BleAdvertiserSettings settings; + BleAdvertiserData advData; + BleAdvertiserData rspData; + auto status = CheckAdvertisingData(env, info, settings, advData, rspData); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + + int ret = bleAdvertiser.StartAdvertising(settings, advData, rspData, bleAdvertiseCallback); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_SUCCESS, ret); + return NapiGetUndefinedRet(env); +} + +static napi_status CheckEmptyArgs(napi_env env, napi_callback_info info) +{ + size_t argc = 0; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, nullptr, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc > 0, "no needed arguments.", napi_invalid_arg); + return napi_ok; } napi_value StopAdvertising(napi_env env, napi_callback_info info) { HILOGI("enter"); - bleAdvertiser.StopAdvertising(bleAdvertiseCallback); + auto status = CheckEmptyArgs(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); - return NapiGetNull(env); + int ret = bleAdvertiser.StopAdvertising(bleAdvertiseCallback); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_SUCCESS, ret); + return NapiGetUndefinedRet(env); } napi_value GetConnectedBLEDevices(napi_env env, napi_callback_info info) @@ -952,7 +692,8 @@ napi_value GetConnectedBLEDevices(napi_env env, napi_callback_info info) napi_value result = nullptr; napi_create_array(env, &result); - ConvertStringVectorToJS(env, result, NapiGattServer::deviceList); + auto status = ConvertStringVectorToJS(env, result, NapiGattServer::deviceList); + NAPI_BT_ASSERT_RETURN(env, status == napi_ok, BT_ERR_INTERNAL_ERROR, result); return result; } diff --git a/frameworks/js/napi/src/napi_bluetooth_ble_central_manager_callback.cpp b/frameworks/js/napi/src/napi_bluetooth_ble_central_manager_callback.cpp index 8a69f8e8..b1375292 100644 --- a/frameworks/js/napi/src/napi_bluetooth_ble_central_manager_callback.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_ble_central_manager_callback.cpp @@ -195,10 +195,11 @@ void NapiBluetoothBleCentralManagerCallback::UvQueueWorkOnScanCallback( static void OnSysScanCallback(const BleScanResult &result, const std::string type) { std::lock_guard lock(g_sysBLEObserverMutex); - auto sysObservers = GetSysBLEObserver(); - if (sysObservers.find(type) != sysObservers.end()) { - SysOnScanCallBack(sysObservers, result); - } + auto sysObservers = GetSysBLEObserver(); + if (!sysObservers.empty() && + sysObservers.find(type) != sysObservers.end()) { + SysOnScanCallBack(sysObservers, result); + } } void NapiBluetoothBleCentralManagerCallback::OnScanCallback(const BleScanResult &result) @@ -210,6 +211,7 @@ void NapiBluetoothBleCentralManagerCallback::OnScanCallback(const BleScanResult HILOGI("This callback is not registered by ability."); return; } + uv_loop_s *loop = nullptr; napi_get_uv_event_loop(callbackInfo->env_, &loop); if (loop == nullptr) { @@ -330,18 +332,21 @@ void NapiBluetoothBleCentralManagerCallback::OnBleBatchScanResultsEvent(const st void NapiBluetoothBleCentralManagerCallback::OnStartOrStopScanEvent(int resultCode, bool isStartScan) { HILOGI("resultCode: %{public}d, isStartScan: %{public}d", resultCode, isStartScan); - std::array, ARGS_SIZE_THREE> callbackInfos; { std::lock_guard lock(g_sysBLEObserverMutex); auto observers = GetSysBLEObserver(); + if (observers.empty()) { + HILOGI("observers is empty."); + return; + } if (observers.find(REGISTER_SYS_BLE_SCAN_TYPE) == observers.end()) { - HILOGE("sys BEL callback is not registered by ability."); + HILOGI("sys BEL callback is not registered by ability."); return; } callbackInfos = observers[REGISTER_SYS_BLE_SCAN_TYPE]; } - + uv_loop_s *loop = nullptr; napi_get_uv_event_loop(callbackInfos[PARAM0]->env_, &loop); if (loop == nullptr) { @@ -353,14 +358,12 @@ void NapiBluetoothBleCentralManagerCallback::OnStartOrStopScanEvent(int resultCo HILOGE("create uv_work_t failed!"); return; } - SysBLEStartScanCallbackData *data = new (std::nothrow) SysBLEStartScanCallbackData(); if (data == nullptr) { HILOGE("create SysBLECallbackData failed!"); delete work; return; } - data->resultCode = resultCode; data->env = callbackInfos[PARAM0]->env_; data->callbackSuccess = callbackInfos[PARAM0]->callback_; diff --git a/frameworks/js/napi/src/napi_bluetooth_error.cpp b/frameworks/js/napi/src/napi_bluetooth_error.cpp new file mode 100644 index 00000000..13fdca81 --- /dev/null +++ b/frameworks/js/napi/src/napi_bluetooth_error.cpp @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2021-2022 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 "napi_bluetooth_error.h" + +#include "bluetooth_errorcode.h" +#include "napi_bluetooth_utils.h" + +namespace OHOS { +namespace Bluetooth { + +static std::map napiErrMsgMap { + { BtErrCode::BT_ERR_SERVICE_DISCONNECTED, "Service stoped." }, + { BtErrCode::BT_ERR_UNBONDED_DEVICE, "Device is not bonded." }, + { BtErrCode::BT_ERR_INVALID_STATE, "Bluetooth switch is off." }, + { BtErrCode::BT_ERR_PROFILE_DISABLED, "Profile is not supported." }, + { BtErrCode::BT_ERR_DEVICE_DISCONNECTED, "Device is disconnected" }, + { BtErrCode::BT_ERR_MAX_CONNECTION, "Max number connection." }, + { BtErrCode::BT_ERR_INTERNAL_ERROR, "Operation failed" }, + { BtErrCode::BT_ERR_IPC_TRANS_FAILED, "trans exception." }, + { BtErrCode::BT_ERR_PERMISSION_FAILED, "Permission denied." }, + { BtErrCode::BT_ERR_SYSTEM_PERMISSION_FAILED, "Non-system applications are not allowed to use system APIs."}, + { BtErrCode::BT_ERR_INVALID_PARAM, "Invalid parameter." }, + { BtErrCode::BT_ERR_API_NOT_SUPPORT, "Capability is not supported." }, + { BtErrCode::BT_ERR_GATT_READ_NOT_PERMITTED, "Gatt read forbiden." }, + { BtErrCode::BT_ERR_GATT_WRITE_NOT_PERMITTED, "Gatt write forbiden." }, + { BtErrCode::BT_ERR_GATT_MAX_SERVER, "Max gatt server." }, + { BtErrCode::BT_ERR_SPP_SERVER_STATE, "SPP server not running." }, + { BtErrCode::BT_ERR_SPP_BUSY, "SPP translate busy." }, + { BtErrCode::BT_ERR_SPP_DEVICE_NOT_FOUND, "Device is not inquired." }, + { BtErrCode::BT_ERR_SPP_IO, "SPP IO error." }, +}; + +static std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode) +{ + auto iter = napiErrMsgMap.find(errCode); + if (iter != napiErrMsgMap.end()) { + std::string errMessage = "BussinessError "; + errMessage.append(std::to_string(errCode)).append(": ").append(iter->second); + return errMessage; + } + return "Inner error."; +} + +void HandleSyncErr(const napi_env &env, int32_t errCode) +{ + if (errCode == BtErrCode::BT_SUCCESS) { + return; + } + std::string errMsg = GetNapiErrMsg(env, errCode); + if (errMsg != "") { + napi_throw_error(env, std::to_string(errCode).c_str(), errMsg.c_str()); + } +} +} +} \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_bluetooth_event.cpp b/frameworks/js/napi/src/napi_bluetooth_event.cpp index 892107cd..964e4d6b 100644 --- a/frameworks/js/napi/src/napi_bluetooth_event.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_event.cpp @@ -143,17 +143,16 @@ napi_value NapiEvent::OnEvent(napi_env env, napi_callback_info info, napi_value NapiEvent::OffEvent(napi_env env, napi_callback_info info, std::map> &callbackInfos) { - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_TWO] = {0}; napi_value thisVar = nullptr; napi_value ret = nullptr; napi_get_undefined(env, &ret); napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); + if (argc != ARGS_SIZE_ONE && argc != ARGS_SIZE_TWO) { + HILOGE("Requires 1 or 2 argument."); return ret; } std::string type; @@ -166,6 +165,7 @@ napi_value NapiEvent::OffEvent(napi_env env, napi_callback_info info, HILOGE("type %{public}s callbackInfos isn't exist.", type.c_str()); return ret; } + uint32_t refCount = INVALID_REF_COUNT; napi_reference_unref(env, it->second->callback_, &refCount); HILOGI("decrements the refernce count, refCount: %{public}d", refCount); diff --git a/frameworks/js/napi/src/napi_bluetooth_gatt_client.cpp b/frameworks/js/napi/src/napi_bluetooth_gatt_client.cpp index c5303fce..75821d29 100644 --- a/frameworks/js/napi/src/napi_bluetooth_gatt_client.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_gatt_client.cpp @@ -14,10 +14,13 @@ */ #include "napi_bluetooth_gatt_client.h" #include +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_utils.h" #include "napi_bluetooth_host.h" #include "napi_bluetooth_event.h" +#include "parser/napi_parser_utils.h" namespace OHOS { @@ -25,23 +28,38 @@ namespace Bluetooth { using namespace std; thread_local napi_ref NapiGattClient::consRef_ = nullptr; -napi_value NapiGattClient::CreateGattClientDevice(napi_env env, napi_callback_info info) -{ - HILOGI("enter"); +static napi_status CheckCreateGattClientDeviceParams(napi_env env, napi_callback_info info, napi_value &outResult) +{ size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount, "expect 1 args", napi_invalid_arg); - NAPI_ASSERT(env, argc == expectedArgsCount, "Requires 1 arguments."); + std::string deviceId {}; + if (!ParseString(env, deviceId, argv[0])) { + HILOGE("expect string"); + return napi_string_expected; + } + if (!IsValidAddress(deviceId)) { + HILOGE("Invalid deviceId: %{public}s", deviceId.c_str()); + return napi_invalid_arg; + } - napi_value result; napi_value constructor = nullptr; - napi_get_reference_value(env, consRef_, &constructor); - napi_new_instance(env, constructor, argc, argv, &result); + NAPI_BT_CALL_RETURN(napi_get_reference_value(env, NapiGattClient::consRef_, &constructor)); + NAPI_BT_CALL_RETURN(napi_new_instance(env, constructor, argc, argv, &outResult)); + return napi_ok; +} +napi_value NapiGattClient::CreateGattClientDevice(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + napi_value result; + auto status = CheckCreateGattClientDeviceParams(env, info, result); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); return result; } @@ -102,194 +120,225 @@ napi_value NapiGattClient::GattClientConstructor(napi_env env, napi_callback_inf return thisVar; } -napi_value NapiGattClient::On(napi_env env, napi_callback_info info) +static NapiGattClient *NapiGetGattClient(napi_env env, napi_value thisVar) { - HILOGI("enter"); - std::unique_lock guard(g_gattClientCallbackInfosMutex); - NapiGattClient* gattClient = nullptr; - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + NapiGattClient *gattClient = nullptr; + auto status = napi_unwrap(env, thisVar, (void **)&gattClient); + if (status != napi_ok) { + return nullptr; + } + return gattClient; +} - napi_value ret = nullptr; - napi_get_undefined(env, &ret); +static GattCharacteristic *GetCharacteristic(const std::shared_ptr &client, + const UUID &serviceUuid, const UUID &characterUuid) +{ + GattCharacteristic *character = nullptr; + if (client) { + auto service = client->GetService(serviceUuid); + if (service.has_value()) { + character = service->get().GetCharacteristic(characterUuid); + } + } + return character; +} - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; +static GattCharacteristic *GetGattcCharacteristic(const std::shared_ptr &client, + const NapiBleCharacteristic &napiCharacter) +{ + GattCharacteristic *character = GetCharacteristic(client, napiCharacter.serviceUuid, + napiCharacter.characteristicUuid); + if (character) { + character->SetValue(napiCharacter.characteristicValue.data(), napiCharacter.characteristicValue.size()); + } + return character; +} + +static GattDescriptor *GetGattcDescriptor(const std::shared_ptr &client, + const NapiBleDescriptor &napiDescriptor) +{ + GattDescriptor *descriptor = nullptr; + if (client) { + auto *character = GetCharacteristic(client, napiDescriptor.serviceUuid, napiDescriptor.characteristicUuid); + if (character == nullptr) { + HILOGE("character is nullptr"); + return nullptr; + } + descriptor = character->GetDescriptor(napiDescriptor.descriptorUuid); + if (descriptor) { + descriptor->SetValue(napiDescriptor.descriptorValue.data(), napiDescriptor.descriptorValue.size()); + } } - string type; - ParseString(env, type, argv[PARAM0]); - std::shared_ptr callbackInfo; - if (type.c_str() == STR_BT_GATT_CLIENT_CALLBACK_BLE_CHARACTERISTIC_CHANGE) { + return descriptor; +} + +napi_status CheckGattClientOn(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); + + std::string type {}; + NAPI_BT_CALL_RETURN(NapiParseString(env, argv[PARAM0], type)); + std::shared_ptr callbackInfo {nullptr}; + + if (type == STR_BT_GATT_CLIENT_CALLBACK_BLE_CHARACTERISTIC_CHANGE) { callbackInfo = std::make_shared(); } else { callbackInfo = std::make_shared(); } callbackInfo->env_ = env; - napi_unwrap(env, thisVar, (void **)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return ret; - } - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - gattClient->GetCallback().SetCallbackInfo(type, callbackInfo); + auto gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM1])); + std::unique_lock guard(NapiGattClientCallback::g_gattClientCallbackInfosMutex); + NAPI_BT_CALL_RETURN(napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_)); + gattClient->GetCallback().SetCallbackInfo(type, callbackInfo); HILOGI("%{public}s is registered", type.c_str()); - - return ret; + return napi_ok; } -napi_value NapiGattClient::Off(napi_env env, napi_callback_info info) +napi_value NapiGattClient::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - std::unique_lock guard(g_gattClientCallbackInfosMutex); - NapiGattClient* gattClient = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + auto status = CheckGattClientOn(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); +} - napi_value ret = nullptr; - napi_get_undefined(env, &ret); +napi_status CheckGattClientOff(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; // argv[PARAM1] is not used. + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE && argc != ARGS_SIZE_TWO, "Requires 1 or 2 arguments.", napi_invalid_arg); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } + std::string type {}; + NAPI_BT_CALL_RETURN(NapiParseString(env, argv[PARAM0], type)); - string type; - ParseString(env, type, argv[PARAM0]); - napi_unwrap(env, thisVar, (void **)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return ret; - } - if (gattClient->GetCallback().GetCallbackInfo(type) == nullptr) { - HILOGE("type %{public}s callbackInfos isn't exist.", type.c_str()); - return ret; - } + auto gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + // callback_ need unref before, see napi_bluetooth_gatt_client + std::unique_lock guard(NapiGattClientCallback::g_gattClientCallbackInfosMutex); + auto &gattClientCallback = gattClient->GetCallback(); uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(env, gattClient->GetCallback().GetCallbackInfo(type)->callback_, &refCount); + NAPI_BT_CALL_RETURN(napi_reference_unref(env, gattClientCallback.GetCallbackInfo(type)->callback_, &refCount)); HILOGI("decrements the refernce count, refCount: %{public}d", refCount); if (refCount == 0) { - napi_delete_reference(env, gattClient->GetCallback().GetCallbackInfo(type)->callback_); + NAPI_BT_CALL_RETURN(napi_delete_reference(env, gattClientCallback.GetCallbackInfo(type)->callback_)); } - gattClient->GetCallback().SetCallbackInfo(type, nullptr); + gattClientCallback.SetCallbackInfo(type, nullptr); HILOGI("%{public}s is removed", type.c_str()); - return ret; + return napi_ok; +} + +napi_value NapiGattClient::Off(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + auto status = CheckGattClientOff(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); } +static napi_status CheckGattClientNoArgc(napi_env env, napi_callback_info info, NapiGattClient **outGattClient) +{ + size_t argc = 0; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != 0, "No need arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr || outGattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + + *outGattClient = gattClient; + return napi_ok; +} napi_value NapiGattClient::Connect(napi_env env, napi_callback_info info) { HILOGI("enter"); NapiGattClient *gattClient = nullptr; - napi_value thisVar = nullptr; - bool isOK = false; + auto status = CheckGattClientNoArgc(env, info, &gattClient); + NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - napi_unwrap(env, thisVar, (void **)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } - int status = gattClient->GetClient()->Connect(gattClient->GetCallback(), true, GATT_TRANSPORT_TYPE_LE); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } + std::shared_ptr client = gattClient->GetClient(); + NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - return ret; + int ret = client->Connect(gattClient->GetCallback(), true, GATT_TRANSPORT_TYPE_LE); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } napi_value NapiGattClient::Disconnect(napi_env env, napi_callback_info info) { HILOGI("enter"); NapiGattClient* gattClient = nullptr; - napi_value thisVar = nullptr; - bool isOK = false; + auto status = CheckGattClientNoArgc(env, info, &gattClient); + NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } - int status = gattClient->GetClient()->Disconnect(); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } + std::shared_ptr client = gattClient->GetClient(); + NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - return ret; + int ret = client->Disconnect(); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } -napi_value NapiGattClient::ReadCharacteristicValue(napi_env env, napi_callback_info info) +static napi_status ParseGattClientReadCharacteristicValue(napi_env env, napi_callback_info info, + ReadCharacteristicValueCallbackInfo **outCallbackInfo, napi_value &promise) { - HILOGI("enter"); - NapiGattClient *gattClient = nullptr; size_t expectedArgsCount = ARGS_SIZE_TWO; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE) { - HILOGE("Requires 1 or 2 arguments."); - return ret; - } - - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return ret; - } - gattClient->readCharacteristicValueCallbackInfo_ = new ReadCharacteristicValueCallbackInfo(); - ReadCharacteristicValueCallbackInfo *callbackInfo = gattClient->readCharacteristicValueCallbackInfo_; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE, + "Requires 1 or 2 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + + ReadCharacteristicValueCallbackInfo* callbackInfo = new ReadCharacteristicValueCallbackInfo(); + gattClient->readCharacteristicValueCallbackInfo_ = callbackInfo; callbackInfo->env_ = env; callbackInfo->client_ = gattClient->GetClient(); - callbackInfo->inputCharacteristic_ = GetCharacteristicFromJS(env, argv[PARAM0], nullptr, callbackInfo->client_); - napi_value promise = nullptr; + NapiBleCharacteristic napiCharacter; + NAPI_BT_CALL_RETURN(NapiParseGattCharacteristic(env, argv[PARAM0], napiCharacter)); + GattCharacteristic *character = GetGattcCharacteristic(gattClient->GetClient(), napiCharacter); + NAPI_BT_RETURN_IF(character == nullptr, "Not found character", napi_invalid_arg); + callbackInfo->inputCharacteristic_ = character; + + *outCallbackInfo = callbackInfo; if (argc == expectedArgsCount) { // Callback mode HILOGI("callback mode"); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM1])); + NAPI_BT_CALL_RETURN(napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_)); napi_get_undefined(env, &promise); } else { // Promise mode HILOGI("promise mode"); napi_create_promise(env, &callbackInfo->deferred_, &promise); } + return napi_ok; +} + +napi_value NapiGattClient::ReadCharacteristicValue(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + + ReadCharacteristicValueCallbackInfo *callbackInfo = nullptr; + napi_value promise = nullptr; + + auto status = ParseGattClientReadCharacteristicValue(env, info, &callbackInfo, promise); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value resource = nullptr; napi_create_string_utf8(env, "readCharacteristicValue", NAPI_AUTO_LENGTH, &resource); @@ -308,7 +357,7 @@ napi_value NapiGattClient::ReadCharacteristicValue(napi_env env, napi_callback_i status = callbackInfo->client_->ReadCharacteristic(*(callbackInfo->inputCharacteristic_)); } - if (status == GattStatus::GATT_SUCCESS) { + if (status == BT_SUCCESS) { HILOGI("ReadCharacteristicValue(): successful"); callbackInfo->errorCode_ = CODE_SUCCESS; int tryTime = 100; @@ -338,7 +387,7 @@ napi_value NapiGattClient::ReadCharacteristicValue(napi_env env, napi_callback_i napi_get_undefined(env, &undefined); HILOGI("ReadCharacteristicValue(): errorCode: %{public}d", callbackInfo->errorCode_); - if (callbackInfo->errorCode_ == CODE_SUCCESS) { + if (callbackInfo->errorCode_ == BT_SUCCESS) { napi_create_object(env, &result[PARAM1]); ConvertBLECharacteristicToJS(env, result[PARAM1], const_cast(*(callbackInfo->outputCharacteristic_))); @@ -370,53 +419,55 @@ napi_value NapiGattClient::ReadCharacteristicValue(napi_env env, napi_callback_i return promise; } -napi_value NapiGattClient::ReadDescriptorValue(napi_env env, napi_callback_info info) +static napi_status ParseGattClientReadDescriptorValue(napi_env env, napi_callback_info info, + ReadDescriptorValueCallbackInfo **outCallbackInfo, napi_value &promise) { - HILOGI("enter"); - NapiGattClient* gattClient = nullptr; size_t expectedArgsCount = ARGS_SIZE_TWO; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE) { - HILOGE("Requires 1 or 2 arguments."); - return ret; - } - - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return ret; - } - gattClient->readDescriptorValueCallbackInfo_ = new ReadDescriptorValueCallbackInfo(); - ReadDescriptorValueCallbackInfo *callbackInfo = gattClient->readDescriptorValueCallbackInfo_; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE, + "Requires 1 or 2 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + + ReadDescriptorValueCallbackInfo *callbackInfo = new ReadDescriptorValueCallbackInfo(); + gattClient->readDescriptorValueCallbackInfo_ = callbackInfo; callbackInfo->env_ = env; callbackInfo->client_ = gattClient->GetClient(); - callbackInfo->inputDescriptor_ = GetDescriptorFromJS(env, argv[PARAM0], nullptr, gattClient->GetClient()); - napi_value promise = nullptr; + NapiBleDescriptor napiDescriptor; + NAPI_BT_CALL_RETURN(NapiParseGattDescriptor(env, argv[PARAM0], napiDescriptor)); + GattDescriptor *descriptor = GetGattcDescriptor(gattClient->GetClient(), napiDescriptor); + NAPI_BT_RETURN_IF(descriptor == nullptr, "Not found Descriptor", napi_invalid_arg); + callbackInfo->inputDescriptor_ = descriptor; + + *outCallbackInfo = callbackInfo; if (argc == expectedArgsCount) { // Callback mode HILOGI("callback mode"); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM1])); + NAPI_BT_CALL_RETURN(napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_)); napi_get_undefined(env, &promise); } else { // Promise mode HILOGI("promise mode"); napi_create_promise(env, &callbackInfo->deferred_, &promise); } + return napi_ok; +} + +napi_value NapiGattClient::ReadDescriptorValue(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + + ReadDescriptorValueCallbackInfo *callbackInfo = nullptr; + napi_value promise = nullptr; + + auto status = ParseGattClientReadDescriptorValue(env, info, &callbackInfo, promise); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value resource = nullptr; napi_create_string_utf8(env, "readDescriptorValue", NAPI_AUTO_LENGTH, &resource); @@ -431,6 +482,8 @@ napi_value NapiGattClient::ReadDescriptorValue(napi_env env, napi_callback_info if (callbackInfo->inputDescriptor_ != nullptr) { HILOGI("ReadDescriptorValue(): Client read descriptor"); status = callbackInfo->client_->ReadDescriptor(*(callbackInfo->inputDescriptor_)); + } else { + HILOGI("callbackInfo->inputDescriptor_ is nullptr"); } if (status == GattStatus::GATT_SUCCESS) { @@ -496,47 +549,24 @@ napi_value NapiGattClient::ReadDescriptorValue(napi_env env, napi_callback_info return promise; } -napi_value NapiGattClient::GetServices(napi_env env, napi_callback_info info) +static napi_status ParseGattClientAsyncCallback(napi_env env, napi_callback_info info, + GetServiceCallbackInfo *callbackInfo, napi_value &promise) { - HILOGI("enter"); - NapiGattClient* gattClient = nullptr; size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE) { - HILOGE("Requires 0 or 1 arguments."); - return ret; - } - - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return ret; - } - - GetServiceCallbackInfo *callbackInfo = new GetServiceCallbackInfo(); - callbackInfo->env_ = env; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE, + "Requires 0 or 1 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); callbackInfo->client_ = gattClient->GetClient(); - napi_value promise = nullptr; - if (argc == expectedArgsCount) { // Callback mode HILOGI("callback mode"); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM0], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - delete callbackInfo; - callbackInfo = nullptr; - return ret; - } + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM0])); napi_create_reference(env, argv[PARAM0], 1, &callbackInfo->callback_); napi_get_undefined(env, &promise); } else { @@ -544,6 +574,19 @@ napi_value NapiGattClient::GetServices(napi_env env, napi_callback_info info) HILOGI("promise mode"); napi_create_promise(env, &callbackInfo->deferred_, &promise); } + return napi_ok; +} + +napi_value NapiGattClient::GetServices(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + + GetServiceCallbackInfo *callbackInfo = new GetServiceCallbackInfo(); + callbackInfo->env_ = env; + napi_value promise = nullptr; + + auto status = ParseGattClientAsyncCallback(env, info, callbackInfo, promise); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value resource = nullptr; napi_create_string_utf8(env, "getServices", NAPI_AUTO_LENGTH, &resource); @@ -554,7 +597,7 @@ napi_value NapiGattClient::GetServices(napi_env env, napi_callback_info info) HILOGI("GetServices(): execute"); GetServiceCallbackInfo* callbackInfo = (GetServiceCallbackInfo*)data; int status = callbackInfo->client_->DiscoverServices(); - if (status != GattStatus::GATT_SUCCESS) { + if (status != BT_SUCCESS) { HILOGE("GetServices(): failed, status: %{public}d", status); callbackInfo->errorCode_ = CODE_FAILED; } else { @@ -609,195 +652,173 @@ napi_value NapiGattClient::Close(napi_env env, napi_callback_info info) { HILOGI("enter"); NapiGattClient* gattClient = nullptr; - bool isOK = false; - napi_value thisVar = nullptr; + auto status = CheckGattClientNoArgc(env, info, &gattClient); + NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } - - int status = gattClient->GetClient()->Close(); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } + std::shared_ptr client = gattClient->GetClient(); + NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - return ret; + int ret = client->Close(); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } -napi_value NapiGattClient::WriteCharacteristicValue(napi_env env, napi_callback_info info) +static napi_status CheckWriteCharacteristicValue(napi_env env, napi_callback_info info, + GattCharacteristic **outCharacteristic, NapiGattClient **outGattClient) { - HILOGI("enter"); - NapiGattClient* gattClient = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value ret = nullptr; - napi_value thisVar = nullptr; - bool isOK = false; - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount, "Requires 1 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr || outGattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } + NapiBleCharacteristic napiCharacter; + NAPI_BT_CALL_RETURN(NapiParseGattCharacteristic(env, argv[PARAM0], napiCharacter)); + GattCharacteristic *character = GetGattcCharacteristic(gattClient->GetClient(), napiCharacter); + NAPI_BT_RETURN_IF(character == nullptr, "Not found character", napi_invalid_arg); - GattCharacteristic* characteristic = GetCharacteristicFromJS(env, argv[PARAM0], nullptr, gattClient->GetClient()); - if (characteristic != nullptr) { - HILOGI("Client write characteristic"); - int status = gattClient->GetClient()->WriteCharacteristic(*characteristic); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } - } + *outGattClient = gattClient; + *outCharacteristic = character; - napi_get_boolean(env, isOK, &ret); - return ret; + return napi_ok; } -napi_value NapiGattClient::WriteDescriptorValue(napi_env env, napi_callback_info info) +napi_value NapiGattClient::WriteCharacteristicValue(napi_env env, napi_callback_info info) { HILOGI("enter"); + GattCharacteristic* characteristic = nullptr; NapiGattClient* gattClient = nullptr; + auto status = CheckWriteCharacteristicValue(env, info, &characteristic, &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); + int ret = client->WriteCharacteristic(*characteristic); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); +} + +static napi_status CheckWriteDescriptorValue(napi_env env, napi_callback_info info, + GattDescriptor **outDescriptor, NapiGattClient **outGattClient) +{ size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value ret = nullptr; - napi_value thisVar = nullptr; - bool isOK = false; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount, "Requires 1 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr || outGattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + + NapiBleDescriptor napiDescriptor; + NAPI_BT_CALL_RETURN(NapiParseGattDescriptor(env, argv[PARAM0], napiDescriptor)); + GattDescriptor *descriptor = GetGattcDescriptor(gattClient->GetClient(), napiDescriptor); + NAPI_BT_RETURN_IF(descriptor == nullptr, "Not found Descriptor", napi_invalid_arg); + + *outGattClient = gattClient; + *outDescriptor = descriptor; + return napi_ok; +} - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } +napi_value NapiGattClient::WriteDescriptorValue(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + GattDescriptor* descriptor = nullptr; + NapiGattClient* gattClient = nullptr; - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } + auto status = CheckWriteDescriptorValue(env, info, &descriptor, &gattClient); + NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); - GattDescriptor* descriptor = GetDescriptorFromJS(env, argv[PARAM0], nullptr, gattClient->GetClient()); - if (descriptor != nullptr) { - HILOGI("Client write descriptor"); - int status = gattClient->GetClient()->WriteDescriptor(*descriptor); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } - } + std::shared_ptr client = gattClient->GetClient(); + NAPI_BT_ASSERT_RETURN_FALSE(env, client != nullptr, BT_ERR_INTERNAL_ERROR); - napi_get_boolean(env, isOK, &ret); - return ret; + int ret = client->WriteDescriptor(*descriptor); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } -napi_value NapiGattClient::SetBLEMtuSize(napi_env env, napi_callback_info info) +static napi_status CheckSetBLEMtuSize(napi_env env, napi_callback_info info, + int32_t &mtuSize, NapiGattClient **outGattClient) { - HILOGI("enter"); - NapiGattClient* gattClient = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value ret = nullptr; - napi_value thisVar = nullptr; - bool isOK = false; - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount, "Requires 1 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr || outGattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } + NAPI_BT_CALL_RETURN(NapiParseInt32(env, argv[PARAM0], mtuSize)); + *outGattClient = gattClient; - int32_t mtuSize; - ParseInt32(env, mtuSize, argv[PARAM0]); - - int status = gattClient->GetClient()->RequestBleMtuSize(mtuSize); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } - - napi_get_boolean(env, isOK, &ret); - return ret; + return napi_ok; } -napi_value NapiGattClient::SetNotifyCharacteristicChanged(napi_env env, napi_callback_info info) +napi_value NapiGattClient::SetBLEMtuSize(napi_env env, napi_callback_info info) { HILOGI("enter"); 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); + + int ret = client->RequestBleMtuSize(mtuSize); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); +} + +static napi_status CheckSetNotifyCharacteristicChanged(napi_env env, napi_callback_info info, + GattCharacteristic **outCharacteristic, bool &enableNotify, NapiGattClient **outGattClient) +{ size_t expectedArgsCount = ARGS_SIZE_TWO; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value ret = nullptr; - napi_value thisVar = nullptr; - bool isOK = false; - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - - napi_unwrap(env, thisVar, (void**)&gattClient); - if (gattClient == nullptr) { - HILOGE("gattClient is nullptr."); - return NapiGetBooleanFalse(env); - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount, "Requires 2 arguments.", napi_invalid_arg); + NapiGattClient *gattClient = NapiGetGattClient(env, thisVar); + NAPI_BT_RETURN_IF(gattClient == nullptr || outGattClient == nullptr, "gattClient is nullptr.", napi_invalid_arg); + + NapiBleCharacteristic napiCharacter; + NAPI_BT_CALL_RETURN(NapiParseGattCharacteristic(env, argv[PARAM0], napiCharacter)); + GattCharacteristic *character = GetGattcCharacteristic(gattClient->GetClient(), napiCharacter); + NAPI_BT_RETURN_IF(character == nullptr, "Not found character", napi_invalid_arg); + + NAPI_BT_CALL_RETURN(NapiParseBoolean(env, argv[PARAM1], enableNotify)); + *outGattClient = gattClient; + *outCharacteristic = character; + return napi_ok; +} - GattCharacteristic* characteristic = GetCharacteristicFromJS(env, argv[PARAM0], nullptr, gattClient->GetClient()); - if (characteristic == nullptr) { - HILOGI("characteristic is nullptr"); - napi_get_boolean(env, false, &ret); - return ret; - } +napi_value NapiGattClient::SetNotifyCharacteristicChanged(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + GattCharacteristic* characteristic = nullptr; bool enableNotify = false; - ParseBool(env, enableNotify, argv[PARAM1]); + NapiGattClient* gattClient = nullptr; - int status = gattClient->GetClient()->SetNotifyCharacteristic(*characteristic, enableNotify); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } + auto status = CheckSetNotifyCharacteristicChanged(env, info, &characteristic, enableNotify, &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); - napi_get_boolean(env, isOK, &ret); - return ret; + int ret = client->SetNotifyCharacteristic(*characteristic, enableNotify); + HILOGI("ret: %{public}d", ret); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/napi_bluetooth_gatt_client_callback.cpp b/frameworks/js/napi/src/napi_bluetooth_gatt_client_callback.cpp index 2fcb0ecf..06a8a4eb 100644 --- a/frameworks/js/napi/src/napi_bluetooth_gatt_client_callback.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_gatt_client_callback.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include -#include #include "bluetooth_log.h" #include "napi_bluetooth_event.h" #include "napi_bluetooth_gatt_client.h" @@ -21,65 +20,25 @@ namespace OHOS { namespace Bluetooth { +std::shared_mutex NapiGattClientCallback::g_gattClientCallbackInfosMutex; + void NapiGattClientCallback::OnCharacteristicChanged(const GattCharacteristic &characteristic) { - HILOGI("enter"); - std::unique_lock guard(g_gattClientCallbackInfosMutex); - if (!callbackInfos_[STR_BT_GATT_CLIENT_CALLBACK_BLE_CHARACTERISTIC_CHANGE]) { + std::unique_lock guard(g_gattClientCallbackInfosMutex); + std::map>::iterator it = + callbackInfos_.find(STR_BT_GATT_CLIENT_CALLBACK_BLE_CHARACTERISTIC_CHANGE); + if (it == callbackInfos_.end() || it->second == nullptr) { HILOGI("This callback is not registered by ability."); return; } - std::shared_ptr callbackInfo = - std::static_pointer_cast( - callbackInfos_[STR_BT_GATT_CLIENT_CALLBACK_BLE_CHARACTERISTIC_CHANGE]); - + std::shared_ptr callbackInfo = it->second; HILOGI("uuid is %{public}s", characteristic.GetUuid().ToString().c_str()); - callbackInfo->characteristic_ = characteristic; - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - if (work == nullptr) { - HILOGI("uv_work_t work is null."); - return; - } - work->data = (void*)callbackInfo.get(); - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_ref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("increments the reference count, refCount: %{public}d", refCount); - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - GattCharacteristicCallbackInfo *callbackInfo = (GattCharacteristicCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertBLECharacteristicToJS(callbackInfo->env_, result, callbackInfo->characteristic_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - if (callback != nullptr) { - HILOGI("napi_call_function called"); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("uv_queue_work unref, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(callbackInfo->env_, callbackInfo->callback_); - } - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, characteristic); } void NapiGattClientCallback::OnCharacteristicReadResult(const GattCharacteristic &characteristic, int ret) { - HILOGI("enter"); ReadCharacteristicValueCallbackInfo *callbackInfo = client_->readCharacteristicValueCallbackInfo_; if (!callbackInfo) { HILOGE("CallbackInfo does not exist"); @@ -95,7 +54,6 @@ void NapiGattClientCallback::OnCharacteristicReadResult(const GattCharacteristic void NapiGattClientCallback::OnDescriptorReadResult(const GattDescriptor &descriptor, int ret) { - HILOGI("enter"); ReadDescriptorValueCallbackInfo *callbackInfo = client_->readDescriptorValueCallbackInfo_; if (!callbackInfo) { HILOGE("CallbackInfo does not exist"); @@ -111,10 +69,9 @@ void NapiGattClientCallback::OnDescriptorReadResult(const GattDescriptor &descri void NapiGattClientCallback::OnConnectionStateChanged(int connectionState, int ret) { - HILOGI("enter"); - std::unique_lock guard(g_gattClientCallbackInfosMutex); + std::unique_lock guard(g_gattClientCallbackInfosMutex); std::map>::iterator it = - callbackInfos_.find(STR_BT_GATT_CLIENT_CALLBACK_BLE_CONNECTIION_STATE_CHANGE); + callbackInfos_.find(STR_BT_GATT_CLIENT_CALLBACK_BLE_CONNECTIION_STATE_CHANGE); if (it == callbackInfos_.end() || it->second == nullptr) { HILOGI("This callback is not registered by ability."); return; @@ -123,50 +80,12 @@ void NapiGattClientCallback::OnConnectionStateChanged(int connectionState, int r HILOGI("connectionState:%{public}d, ret:%{public}d", connectionState, ret); callbackInfo->state_ = connectionState; callbackInfo->deviceId_ = client_->GetDevice()->GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - if (work == nullptr) { - HILOGI("uv_work_t work is null."); - return; - } - work->data = (void*)callbackInfo.get(); - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_ref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("increments the reference count, refCount: %{public}d", refCount); - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - if (callback != nullptr) { - HILOGI("napi_call_function called"); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - } - uint32_t refCount = INVALID_REF_COUNT; - napi_reference_unref(callbackInfo->env_, callbackInfo->callback_, &refCount); - HILOGI("uv_queue_work unref, refCount: %{public}d", refCount); - if (refCount == 0) { - napi_delete_reference(callbackInfo->env_, callbackInfo->callback_); - } - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, callbackInfo->state_); } void NapiGattClientCallback::OnServicesDiscovered(int status) { - HILOGI("enter"); + HILOGI("status:%{public}d", status); } } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/napi_bluetooth_gatt_server.cpp b/frameworks/js/napi/src/napi_bluetooth_gatt_server.cpp index db227481..984e90ca 100644 --- a/frameworks/js/napi/src/napi_bluetooth_gatt_server.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_gatt_server.cpp @@ -13,12 +13,15 @@ * limitations under the License. */ #include "napi_bluetooth_gatt_server.h" +#include "bluetooth_errorcode.h" #include "bluetooth_gatt_service.h" #include "bluetooth_host.h" #include "bluetooth_log.h" #include "bluetooth_utils.h" #include "napi_bluetooth_ble.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_utils.h" +#include "parser/napi_parser_utils.h" namespace OHOS { namespace Bluetooth { @@ -79,292 +82,294 @@ napi_value NapiGattServer::GattServerConstructor(napi_env env, napi_callback_inf return thisVar; } -napi_value NapiGattServer::On(napi_env env, napi_callback_info info) +static NapiGattServer *NapiGetGattServer(napi_env env, napi_value thisVar) { - HILOGI("enter"); NapiGattServer *gattServer = nullptr; - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; + auto status = napi_unwrap(env, thisVar, (void **)&gattServer); + if (status != napi_ok) { + return nullptr; + } + return gattServer; +} + +napi_status CheckGattsOn(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); - napi_value ret = nullptr; - napi_get_undefined(env, &ret); + std::string type {}; + NAPI_BT_CALL_RETURN(NapiParseString(env, argv[PARAM0], type)); + std::shared_ptr callbackInfo {nullptr}; - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 arguments."); - return ret; - } - string type; - ParseString(env, type, argv[PARAM0]); - std::shared_ptr callbackInfo ; - - if (type.c_str() == STR_BT_GATT_SERVER_CALLBACK_CHARACTERISTIC_READ || - type.c_str() == STR_BT_GATT_SERVER_CALLBACK_CHARACTERISTIC_WRITE) { + if (type == STR_BT_GATT_SERVER_CALLBACK_CHARACTERISTIC_READ || + type == STR_BT_GATT_SERVER_CALLBACK_CHARACTERISTIC_WRITE) { callbackInfo = std::make_shared(); - } else if (type.c_str() == STR_BT_GATT_SERVER_CALLBACK_DESCRIPTOR_WRITE || - type.c_str() == STR_BT_GATT_SERVER_CALLBACK_DESCRIPTOR_READ){ + } else if (type == STR_BT_GATT_SERVER_CALLBACK_DESCRIPTOR_WRITE || + type == STR_BT_GATT_SERVER_CALLBACK_DESCRIPTOR_READ) { callbackInfo = std::make_shared(); } else { - callbackInfo = std::make_shared(); + callbackInfo = std::make_shared(); } callbackInfo->env_ = env; - napi_unwrap(env, thisVar, (void **)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return ret; - } - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - gattServer->GetCallback().SetCallbackInfo(type, callbackInfo); + auto gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM1])); + NAPI_BT_CALL_RETURN(napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_)); + gattServer->GetCallback().SetCallbackInfo(type, callbackInfo); HILOGI("%{public}s is registered", type.c_str()); - return ret; + return napi_ok; } -napi_value NapiGattServer::Off(napi_env env, napi_callback_info info) +napi_value NapiGattServer::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiGattServer *gattServer = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + auto status = CheckGattsOn(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); +} - napi_value ret = nullptr; - napi_get_undefined(env, &ret); +napi_status CheckGattsOff(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; // argv[PARAM1] is not used. + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE && argc != ARGS_SIZE_TWO, "Requires 1 or 2 arguments.", napi_invalid_arg); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - ParseString(env, type, argv[PARAM0]); + std::string type {}; + NAPI_BT_CALL_RETURN(NapiParseString(env, argv[PARAM0], type)); - napi_unwrap(env, thisVar, (void **)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return ret; - } - gattServer->GetCallback().SetCallbackInfo(type, nullptr); + auto gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); + // callback_ need unref before, see napi_bluetooth_gatt_client + auto &gattServerCallback = gattServer->GetCallback(); + gattServerCallback.SetCallbackInfo(type, nullptr); HILOGI("%{public}s is removed", type.c_str()); - return ret; + return napi_ok; } -napi_value NapiGattServer::AddService(napi_env env, napi_callback_info info) +napi_value NapiGattServer::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiGattServer *gattServer = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; + auto status = CheckGattsOff(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); +} + +static napi_status CheckGattsAddService(napi_env env, napi_callback_info info, std::shared_ptr &outServer, + std::unique_ptr &outService) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; napi_value thisVar = nullptr; - bool isOK = false; - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - GattService* gattService = GetServiceFromJS(env, argv[PARAM0], nullptr, nullptr); - if (gattService == nullptr) { - HILOGE("gattService is nullptr."); - return ret; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Requires 1 arguments.", napi_invalid_arg); + + // std::unique_ptr service {nullptr}; + NapiGattService napiGattService; + NAPI_BT_CALL_RETURN(NapiParseGattService(env, argv[PARAM0], napiGattService)); + + NapiGattServer *gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); + outServer = gattServer->GetServer(); + + // Build GattService + using Permission = GattCharacteristic::Permission; + using Propertie = GattCharacteristic::Propertie; + int permissions = Permission::READABLE | Permission::WRITEABLE; + int properties = Propertie::NOTIFY | Propertie::READ | Propertie::WRITE; + GattServiceType type = napiGattService.isPrimary ? GattServiceType::PRIMARY : GattServiceType::SECONDARY; + + outService = std::make_unique(napiGattService.serviceUuid, type); + for (const auto &napiCharacter : napiGattService.characteristics) { + GattCharacteristic character(napiCharacter.characteristicUuid, permissions, properties); + character.SetValue(napiCharacter.characteristicValue.data(), napiCharacter.characteristicValue.size()); + + for (const auto &napiDescriptor : napiCharacter.descriptors) { + GattDescriptor descriptor(napiDescriptor.descriptorUuid, permissions); + descriptor.SetValue(napiDescriptor.descriptorValue.data(), napiDescriptor.descriptorValue.size()); + character.AddDescriptor(descriptor); + } + outService->AddCharacteristic(character); } - napi_unwrap(env, thisVar, (void**)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return ret; - } - int status = gattServer->GetServer()->AddService(*gattService); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } + return napi_ok; +} + +napi_value NapiGattServer::AddService(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + std::shared_ptr server {nullptr}; + std::unique_ptr gattService {nullptr}; + auto status = CheckGattsAddService(env, info, server, gattService); + NAPI_BT_ASSERT_RETURN_FALSE(env, (status == napi_ok && server != nullptr), BT_ERR_INVALID_PARAM); + + int ret = server->AddService(*gattService); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); +} + +static napi_status CheckGattsClose(napi_env env, napi_callback_info info, std::shared_ptr &outServer) +{ + size_t argc = 0; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, nullptr, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc > 0, "no needed arguments.", napi_invalid_arg); + NapiGattServer *gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); - delete gattService; - napi_get_boolean(env, isOK, &ret); - return ret; + outServer = gattServer->GetServer(); + return napi_ok; } napi_value NapiGattServer::Close(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiGattServer* gattServer = nullptr; - bool isOK = false; - napi_value thisVar = nullptr; + std::shared_ptr server {nullptr}; + auto status = CheckGattsClose(env, info, server); + NAPI_BT_ASSERT_RETURN_UNDEF(env, (status == napi_ok && server != nullptr), BT_ERR_INVALID_PARAM); - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - napi_unwrap(env, thisVar, (void**)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return NapiGetBooleanFalse(env); - } + int ret = server->Close(); + NAPI_BT_ASSERT_RETURN_UNDEF(env, ret == BT_SUCCESS, ret); + return NapiGetUndefinedRet(env); +} - int status = gattServer->GetServer()->Close(); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } +static napi_status CheckGattsRemoveService(napi_env env, napi_callback_info info, + std::shared_ptr &outServer, UUID &outUuid) +{ + size_t argc = 1; + napi_value argv[1] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != 1, "Requires 1 arguments.", napi_invalid_arg); - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - return ret; + std::string uuid {}; + NAPI_BT_CALL_RETURN(NapiParseUuid(env, argv[0], uuid)); + + NapiGattServer *gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); + outServer = gattServer->GetServer(); + outUuid = UUID::FromString(uuid); + return napi_ok; } napi_value NapiGattServer::RemoveGattService(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiGattServer* gattServer = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - std::string uuid; - bool isOK = false; - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - NAPI_ASSERT(env, argc == expectedArgsCount, "Requires 1 arguments."); - bool isSuccess = ParseString(env, uuid, argv[PARAM0]); - if (!isSuccess) { - HILOGE("ParseString faild."); - return NapiGetBooleanFalse(env); + std::shared_ptr server {nullptr}; + UUID serviceUuid; + auto status = CheckGattsRemoveService(env, info, server, serviceUuid); + NAPI_BT_ASSERT_RETURN_FALSE(env, (status == napi_ok && server != nullptr), BT_ERR_INVALID_PARAM); + + int ret = BT_ERR_INTERNAL_ERROR; + auto primaryService = server->GetService(serviceUuid, true); + if (primaryService.has_value()) { + ret = server->RemoveGattService(*primaryService); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); } - if (!regex_match(uuid, uuidRegex)) { - HILOGE("match the UUID faild."); - return NapiGetBooleanFalse(env); + auto secondService = server->GetService(serviceUuid, false); + if (secondService.has_value()) { + ret = server->RemoveGattService(*secondService); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); } + NAPI_BT_ASSERT_RETURN_FALSE(env, (primaryService.has_value() || secondService.has_value()), BT_ERR_INVALID_PARAM); + return NapiGetBooleanRet(env, ret == BT_SUCCESS); +} - napi_unwrap(env, thisVar, (void**)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return NapiGetBooleanFalse(env); - } - UUID serviceUuid = UUID::FromString(uuid); - - std::optional> gattService = - gattServer->GetServer()->GetService(serviceUuid, true); - if (gattService != std::nullopt) { - int status = gattServer->GetServer()->RemoveGattService(*gattService); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } - } - gattService = gattServer->GetServer()->GetService(serviceUuid, false); - if (gattService != std::nullopt) { - int status = gattServer->GetServer()->RemoveGattService(*gattService); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } - } +static napi_status CheckGattsSendRsp(napi_env env, napi_callback_info info, std::shared_ptr &outServer, + NapiGattsServerResponse &outRsp) +{ + size_t argc = 1; + napi_value argv[1] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != 1, "Requires 1 arguments.", napi_invalid_arg); + + NapiGattsServerResponse rsp; + NAPI_BT_CALL_RETURN(NapiParseGattsServerResponse(env, argv[0], rsp)); - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - return ret; + NapiGattServer *gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); + outServer = gattServer->GetServer(); + outRsp = std::move(rsp); + return napi_ok; } napi_value NapiGattServer::SendResponse(napi_env env, napi_callback_info info) { HILOGI("enter"); - NapiGattServer* gattServer = nullptr; - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - bool isOK = false; + std::shared_ptr server {nullptr}; + NapiGattsServerResponse rsp; + auto status = CheckGattsSendRsp(env, info, server, rsp); + NAPI_BT_ASSERT_RETURN_FALSE(env, (status == napi_ok && server != nullptr), BT_ERR_INVALID_PARAM); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - NAPI_ASSERT(env, argc == expectedArgsCount, "Requires 1 arguments."); - - ServerResponse serverresponse = GetServerResponseFromJS(env, argv[PARAM0]); - napi_unwrap(env, thisVar, (void**)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return NapiGetBooleanFalse(env); - } - BluetoothRemoteDevice remoteDevice = - BluetoothHost::GetDefaultHost().GetRemoteDevice(serverresponse.deviceId, 1); + BluetoothRemoteDevice remoteDevice(rsp.deviceId, BTTransport::ADAPTER_BLE); HILOGI("Remote device address: %{public}s", GET_ENCRYPT_ADDR(remoteDevice)); - int status = gattServer->GetServer()->SendResponse( - remoteDevice, serverresponse.transId, - serverresponse.status, - serverresponse.offset, - serverresponse.value, - serverresponse.length); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); - } - - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - return ret; + int ret = server->SendResponse(remoteDevice, rsp.transId, rsp.status, rsp.offset, rsp.value.data(), + static_cast(rsp.value.size())); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } -napi_value NapiGattServer::NotifyCharacteristicChanged(napi_env env, napi_callback_info info) +static napi_status CheckGattsNotify(napi_env env, napi_callback_info info, std::shared_ptr &outServer, + std::string &outDeviceId, NapiNotifyCharacteristic &outCharacter) { - HILOGI("enter"); - NapiGattServer* gattServer = nullptr; - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - std::string deviceID; - napi_value argv[ARGS_SIZE_TWO] = {0, 0}; + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; napi_value thisVar = nullptr; - bool isOK = false; - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - napi_unwrap(env, thisVar, (void**)&gattServer); - if (gattServer == nullptr) { - HILOGE("gattServer is nullptr."); - return ret; - } - ParseString(env, deviceID, argv[PARAM0]); - BluetoothRemoteDevice remoteDevice = BluetoothHost::GetDefaultHost().GetRemoteDevice(deviceID, 1); - GattCharacteristic* characteristic = GetCharacteristicFromJS(env, argv[PARAM1], gattServer->GetServer(), nullptr); + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); + + std::string deviceId {}; + NapiNotifyCharacteristic character; + NAPI_BT_CALL_RETURN(NapiParseBdAddr(env, argv[PARAM0], deviceId)); + NAPI_BT_CALL_RETURN(NapiParseNotifyCharacteristic(env, argv[PARAM1], character)); + + NapiGattServer *gattServer = NapiGetGattServer(env, thisVar); + NAPI_BT_RETURN_IF(gattServer == nullptr, "gattServer is nullptr.", napi_invalid_arg); + outServer = gattServer->GetServer(); + outDeviceId = std::move(deviceId); + outCharacter = std::move(character); + return napi_ok; +} - if (characteristic == nullptr) { - HILOGI("characteristic is nullptr"); - return ret; +static GattCharacteristic *GetGattCharacteristic(const std::shared_ptr &server, const UUID &serviceUuid, + const UUID &characterUuid) +{ + auto service = server->GetService(serviceUuid, true); + if (!service.has_value()) { + service = server->GetService(serviceUuid, false); } - int status = gattServer->GetServer()->NotifyCharacteristicChanged(remoteDevice, *characteristic, false); - if (status == GattStatus::GATT_SUCCESS) { - HILOGI("successful"); - isOK = true; - } else { - HILOGE("failed, status: %{public}d", status); + if (!service.has_value()) { + HILOGE("not found service uuid: %{public}s", serviceUuid.ToString().c_str()); + return nullptr; } + GattCharacteristic *character = service.value().get().GetCharacteristic(characterUuid); + return character; +} - napi_get_boolean(env, isOK, &ret); - return ret; +napi_value NapiGattServer::NotifyCharacteristicChanged(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + std::shared_ptr server {nullptr}; + std::string deviceId {}; + NapiNotifyCharacteristic notifyCharacter; + auto status = CheckGattsNotify(env, info, server, deviceId, notifyCharacter); + NAPI_BT_ASSERT_RETURN_FALSE(env, (status == napi_ok && server != nullptr), BT_ERR_INVALID_PARAM); + + auto character = GetGattCharacteristic(server, notifyCharacter.serviceUuid, notifyCharacter.characterUuid); + NAPI_BT_ASSERT_RETURN_FALSE(env, character != nullptr, BT_ERR_INVALID_PARAM); + character->SetValue(notifyCharacter.characterValue.data(), notifyCharacter.characterValue.size()); + + BluetoothRemoteDevice remoteDevice(deviceId, BTTransport::ADAPTER_BLE); + int ret = server->NotifyCharacteristicChanged(remoteDevice, *character, notifyCharacter.confirm); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/napi_bluetooth_hfp_ag.cpp b/frameworks/js/napi/src/napi_bluetooth_hfp_ag.cpp index 6d262f28..3c65bb70 100644 --- a/frameworks/js/napi/src/napi_bluetooth_hfp_ag.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_hfp_ag.cpp @@ -13,8 +13,13 @@ * limitations under the License. */ #include "bluetooth_hfp_ag.h" + +#include "bluetooth_errorcode.h" +#include "bluetooth_utils.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_hfp_ag.h" #include "napi_bluetooth_profile.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { @@ -34,17 +39,17 @@ void NapiHandsFreeAudioGateway::DefineHandsFreeAudioGatewayJSClass(napi_env env) DECLARE_NAPI_FUNCTION("getScoState", GetScoState), DECLARE_NAPI_FUNCTION("connectSco", ConnectSco), DECLARE_NAPI_FUNCTION("disconnectSco", DisconnectSco), - DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("on", On), DECLARE_NAPI_FUNCTION("off", Off), DECLARE_NAPI_FUNCTION("openVoiceRecognition", OpenVoiceRecognition), DECLARE_NAPI_FUNCTION("closeVoiceRecognition", CloseVoiceRecognition), }; - napi_define_class(env, "HandsFreeAudioGateway", NAPI_AUTO_LENGTH, HandsFreeAudioGatewayConstructor, nullptr, + napi_define_class(env, "HandsFreeAudioGateway", NAPI_AUTO_LENGTH, HandsFreeAudioGatewayConstructor, nullptr, sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_HANDS_FREE_AUDIO_GATEWAY, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_HANDS_FREE_AUDIO_GATEWAY, napiProfile); HILOGI("finished"); } @@ -58,68 +63,28 @@ napi_value NapiHandsFreeAudioGateway::HandsFreeAudioGatewayConstructor(napi_env napi_value NapiHandsFreeAudioGateway::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiHandsFreeAudioGatewayObserver::g_handsFreeAudioGatewayCallbackMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - std::shared_ptr callbackInfo = std::make_shared(); - callbackInfo->env_ = env; - - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - observer_.callbackInfos_[type] = callbackInfo; - HILOGI("%{public}s is registered", type.c_str()); - + ret = NapiEvent::OnEvent(env, info, observer_.callbackInfos_); if (!isRegistered_) { HandsFreeAudioGateway *profile = HandsFreeAudioGateway::GetProfile(); profile->RegisterObserver(&observer_); isRegistered_ = true; } + + HILOGI("Hands Free Audio Gateway is registered"); return ret; } napi_value NapiHandsFreeAudioGateway::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiHandsFreeAudioGatewayObserver::g_handsFreeAudioGatewayCallbackMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - observer_.callbackInfos_[type] = nullptr; - HILOGI("%{public}s is unregistered", type.c_str()); + ret = NapiEvent::OffEvent(env, info, observer_.callbackInfos_); + HILOGI("Hands Free Audio Gateway is unregistered"); return ret; } @@ -127,9 +92,18 @@ napi_value NapiHandsFreeAudioGateway::GetConnectionDevices(napi_env env, napi_ca { HILOGI("enter"); napi_value ret = nullptr; - napi_create_array(env, &ret); + if (napi_create_array(env, &ret) != napi_ok) { + HILOGE("napi_create_array failed."); + } + napi_status checkRet = CheckEmptyParam(env, info); + NAPI_BT_ASSERT_RETURN(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM, ret); + HandsFreeAudioGateway *profile = HandsFreeAudioGateway::GetProfile(); - vector devices = profile->GetConnectedDevices(); + vector devices; + int errorCode = profile->GetConnectedDevices(devices); + HILOGI("errorCode:%{public}s, devices size:%{public}zu", GetErrorCode(errorCode).c_str(), devices.size()); + NAPI_BT_ASSERT_RETURN(env, errorCode == BT_SUCCESS, errorCode, ret); + vector deviceVector; for (auto &device: devices) { deviceVector.push_back(device.GetDeviceAddr()); @@ -141,32 +115,27 @@ napi_value NapiHandsFreeAudioGateway::GetConnectionDevices(napi_env env, napi_ca napi_value NapiHandsFreeAudioGateway::GetDeviceState(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; + napi_value result = nullptr; + int32_t profileState = ProfileConnectionState::STATE_DISCONNECTED; + if (napi_create_int32(env, profileState, &result) != napi_ok) { + HILOGE("napi_create_int32 failed."); } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN(env, checkRet, BT_ERR_INVALID_PARAM, result); + HandsFreeAudioGateway *profile = HandsFreeAudioGateway::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - int state = profile->GetDeviceState(device); - int status = GetProfileConnectionState(state); - napi_value result = nullptr; - napi_create_int32(env, status, &result); - HILOGI("status: %{public}d", status); + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t state = static_cast(BTConnectState::DISCONNECTED); + int32_t errorCode = profile->GetDeviceState(device, state); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN(env, errorCode == BT_SUCCESS, errorCode, result); + + profileState = GetProfileConnectionState(state); + if (napi_create_int32(env, profileState, &result) != napi_ok) { + HILOGE("napi_create_int32 failed."); + } return result; } @@ -335,65 +304,31 @@ napi_value NapiHandsFreeAudioGateway::CloseVoiceRecognition(napi_env env, napi_c napi_value NapiHandsFreeAudioGateway::Connect(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); HandsFreeAudioGateway *profile = HandsFreeAudioGateway::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool res = profile->Connect(device); - - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t errorCode = profile->Connect(device); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_SUCCESS, errorCode); + return NapiGetBooleanTrue(env); } napi_value NapiHandsFreeAudioGateway::Disconnect(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); HandsFreeAudioGateway *profile = HandsFreeAudioGateway::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool res = profile->Disconnect(device); - - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t errorCode = profile->Disconnect(device); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_SUCCESS, errorCode); + return NapiGetBooleanTrue(env); } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_bluetooth_hfp_ag_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_hfp_ag_observer.cpp index ccd74dd9..5d4c5a57 100644 --- a/frameworks/js/napi/src/napi_bluetooth_hfp_ag_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_hfp_ag_observer.cpp @@ -15,86 +15,47 @@ #include #include "bluetooth_utils.h" #include "napi_bluetooth_hfp_ag_observer.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { + +std::shared_mutex NapiHandsFreeAudioGatewayObserver::g_handsFreeAudioGatewayCallbackMutex; void NapiHandsFreeAudioGatewayObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); - if (!callbackInfos_[STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_CONNECTION_STATE_CHANGE]) { - HILOGW("callback is not registered by ability."); + std::unique_lock guard(g_handsFreeAudioGatewayCallbackMutex); + std::map>::iterator it = + callbackInfos_.find(STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_CONNECTION_STATE_CHANGE); + if (it == callbackInfos_.end() || it->second == nullptr) { + HILOGW("This callback is not registered by ability."); return; } - - std::shared_ptr callbackInfo = - callbackInfos_[STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_CONNECTION_STATE_CHANGE]; + HILOGI("%{public}s is registered by ability", + STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_CONNECTION_STATE_CHANGE.c_str()); + std::shared_ptr callbackInfo = it->second; callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } void NapiHandsFreeAudioGatewayObserver::OnScoStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); - if (!callbackInfos_[STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_SCO_STATE_CHANGE]) { + std::unique_lock guard(g_handsFreeAudioGatewayCallbackMutex); + std::map>::iterator it = + callbackInfos_.find(STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_SCO_STATE_CHANGE); + if (it == callbackInfos_.end() || it->second == nullptr) { HILOGW("This callback is not registered by ability."); return; } - std::shared_ptr callbackInfo = - callbackInfos_[STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_SCO_STATE_CHANGE]; - + HILOGI("%{public}s is registered by ability", + STR_BT_HANDS_FREE_AUDIO_GATEWAY_OBSERVER_SCO_STATE_CHANGE.c_str()); + std::shared_ptr callbackInfo = it->second; callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - HILOGI("deviceId: %{public}s, state: %{public}d", GetEncryptAddr(callbackInfo->deviceId_).c_str(), state); - - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertScoStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/napi_bluetooth_hfp_hf.cpp b/frameworks/js/napi/src/napi_bluetooth_hfp_hf.cpp index 622eb519..8d484503 100644 --- a/frameworks/js/napi/src/napi_bluetooth_hfp_hf.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_hfp_hf.cpp @@ -15,6 +15,7 @@ #include "napi_bluetooth_hfp_hf.h" #include "napi_bluetooth_profile.h" #include "bluetooth_hfp_hf.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { @@ -44,7 +45,7 @@ void NapiHandsFreeUnit::DefineHandsFreeUnitJSClass(napi_env env) napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_HANDS_FREE_UNIT, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_HANDS_FREE_UNIT, napiProfile); HILOGI("finished"); } @@ -59,69 +60,28 @@ napi_value NapiHandsFreeUnit::HandsFreeUnitConstructor(napi_env env, napi_callba napi_value NapiHandsFreeUnit::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiHandsFreeUnitObserver::g_handsFreeUnitCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 2 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - std::shared_ptr callbackInfo = std::make_shared(); - callbackInfo->env_ = env; - - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - if (valueType != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return ret; - } - napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); - observer_.callbackInfos_[type] = callbackInfo; - - HILOGI("%{public}s is registered", type.c_str()); - + ret = NapiEvent::OnEvent(env, info, observer_.callbackInfos_); if (!isRegistered_) { HandsFreeUnit *profile = HandsFreeUnit::GetProfile(); profile->RegisterObserver(&observer_); isRegistered_ = true; } + + HILOGI("Hands Free Unit is registered"); return ret; } napi_value NapiHandsFreeUnit::Off(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; + std::unique_lock guard(NapiHandsFreeUnitObserver::g_handsFreeUnitCallbackInfosMutex); napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string type; - if (!ParseString(env, type, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } - observer_.callbackInfos_[type] = nullptr; - HILOGI("%{public}s is unregistered", type.c_str()); + ret = NapiEvent::OffEvent(env, info, observer_.callbackInfos_); + HILOGI("Hands Free Unit is unregistered"); return ret; } diff --git a/frameworks/js/napi/src/napi_bluetooth_hfp_hf_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_hfp_hf_observer.cpp index 68410376..1bf5b241 100644 --- a/frameworks/js/napi/src/napi_bluetooth_hfp_hf_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_hfp_hf_observer.cpp @@ -15,85 +15,45 @@ #include #include "bluetooth_utils.h" #include "napi_bluetooth_hfp_hf_observer.h" +#include "napi_bluetooth_event.h" namespace OHOS { namespace Bluetooth { +std::shared_mutex NapiHandsFreeUnitObserver::g_handsFreeUnitCallbackInfosMutex; + void NapiHandsFreeUnitObserver::OnConnectionStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); - if (!callbackInfos_[STR_BT_HANDS_FREE_UNIT_OBSERVER_CONNECTION_STATE_CHANGE]) { + std::unique_lock guard(g_handsFreeUnitCallbackInfosMutex); + std::map>::iterator it = + callbackInfos_.find(STR_BT_HANDS_FREE_UNIT_OBSERVER_CONNECTION_STATE_CHANGE); + if (it == callbackInfos_.end() || it->second == nullptr) { HILOGW("This callback is not registered by ability."); return; } - - std::shared_ptr callbackInfo = - callbackInfos_[STR_BT_HANDS_FREE_UNIT_OBSERVER_CONNECTION_STATE_CHANGE]; + HILOGI("%{public}s is registered by ability", STR_BT_HANDS_FREE_UNIT_OBSERVER_CONNECTION_STATE_CHANGE.c_str()); + std::shared_ptr callbackInfo = it->second; callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } void NapiHandsFreeUnitObserver::OnScoStateChanged(const BluetoothRemoteDevice &device, int state) { HILOGI("enter, remote device address: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); - if (!callbackInfos_[STR_BT_HANDS_FREE_UNIT_OBSERVER_SCO_STATE_CHANGE]) { + std::unique_lock guard(g_handsFreeUnitCallbackInfosMutex); + std::map>::iterator it = + callbackInfos_.find(STR_BT_HANDS_FREE_UNIT_OBSERVER_SCO_STATE_CHANGE); + if (it == callbackInfos_.end() || it->second == nullptr) { HILOGW("This callback is not registered by ability."); return; } - std::shared_ptr callbackInfo = - callbackInfos_[STR_BT_HANDS_FREE_UNIT_OBSERVER_SCO_STATE_CHANGE]; - + HILOGI("%{public}s is registered by ability", STR_BT_HANDS_FREE_UNIT_OBSERVER_SCO_STATE_CHANGE.c_str()); + std::shared_ptr callbackInfo = it->second; callbackInfo->state_ = state; callbackInfo->deviceId_ = device.GetDeviceAddr(); - - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callbackInfo->env_, &loop); - uv_work_t *work = new uv_work_t; - work->data = (void*)callbackInfo.get(); - - uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - BluetoothCallbackInfo *callbackInfo = (BluetoothCallbackInfo *)work->data; - napi_value result = nullptr; - napi_create_object(callbackInfo->env_, &result); - ConvertScoStateChangeParamToJS(callbackInfo->env_, result, callbackInfo->deviceId_, callbackInfo->state_); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value callResult = nullptr; - napi_get_undefined(callbackInfo->env_, &undefined); - napi_get_reference_value(callbackInfo->env_, callbackInfo->callback_, &callback); - napi_call_function(callbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - delete work; - work = nullptr; - } - ); + NapiEvent::CheckAndNotify(callbackInfo, state); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/napi_bluetooth_hid_host.cpp b/frameworks/js/napi/src/napi_bluetooth_hid_host.cpp index 52456327..d643d790 100644 --- a/frameworks/js/napi/src/napi_bluetooth_hid_host.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_hid_host.cpp @@ -14,8 +14,12 @@ */ #include "bluetooth_hid_host.h" + +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" +#include "bluetooth_utils.h" #include "napi_bluetooth_hid_host_observer.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_utils.h" #include "napi_bluetooth_profile.h" #include "napi_bluetooth_hid_host.h" @@ -42,7 +46,7 @@ void NapiBluetoothHidHost::DefineHidHostJSClass(napi_env env) napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_HID_HOST, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_HID_HOST, napiProfile); HidHost *profile = HidHost::GetProfile(); profile->RegisterObserver(&observer_); HILOGI("finished"); @@ -126,23 +130,20 @@ napi_value NapiBluetoothHidHost::GetConnectionDevices(napi_env env, napi_callbac { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ZERO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ZERO] = {}; - napi_value thisVar = nullptr; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("No Requires argument."); - return ret; + if (napi_create_array(env, &ret) != napi_ok) { + HILOGE("napi_create_array failed."); } - napi_create_array(env, &ret); + napi_status checkRet = CheckEmptyParam(env, info); + NAPI_BT_ASSERT_RETURN(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM, ret); + HidHost *profile = HidHost::GetProfile(); vector states = { static_cast(BTConnectState::CONNECTED) }; - vector devices = profile->GetDevicesByStates(states); + vector devices; + int errorCode = profile->GetDevicesByStates(states, devices); + HILOGI("errorCode:%{public}s, devices size:%{public}zu", GetErrorCode(errorCode).c_str(), devices.size()); + NAPI_BT_ASSERT_RETURN(env, errorCode == BT_SUCCESS, errorCode, ret); + vector deviceVector; for (auto &device: devices) { deviceVector.push_back(device.GetDeviceAddr()); @@ -154,31 +155,27 @@ napi_value NapiBluetoothHidHost::GetConnectionDevices(napi_env env, napi_callbac napi_value NapiBluetoothHidHost::GetDeviceState(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; + napi_value result = nullptr; + int32_t profileState = ProfileConnectionState::STATE_DISCONNECTED; + if (napi_create_int32(env, profileState, &result) != napi_ok) { + HILOGE("napi_create_int32 failed."); } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN(env, checkRet, BT_ERR_INVALID_PARAM, result); + HidHost *profile = HidHost::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - int state = profile->GetDeviceState(device); - int profileState = GetProfileConnectionState(state); - napi_value result = nullptr; - napi_create_int32(env, profileState, &result); + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t state = static_cast(BTConnectState::DISCONNECTED); + int32_t errorCode = profile->GetDeviceState(device, state); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN(env, errorCode == BT_SUCCESS, errorCode, result); + + profileState = GetProfileConnectionState(state); + if (napi_create_int32(env, profileState, &result) != napi_ok) { + HILOGE("napi_create_int32 failed."); + } HILOGI("profileState: %{public}d", profileState); return result; } @@ -186,63 +183,31 @@ napi_value NapiBluetoothHidHost::GetDeviceState(napi_env env, napi_callback_info napi_value NapiBluetoothHidHost::Connect(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); HidHost *profile = HidHost::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool isOK = profile->Connect(device); - napi_value result = nullptr; - napi_get_boolean(env, isOK, &result); - HILOGI("isOK: %{public}d", isOK); - return result; + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t errorCode = profile->Connect(device); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_SUCCESS, errorCode); + return NapiGetBooleanTrue(env); } napi_value NapiBluetoothHidHost::Disconnect(napi_env env, napi_callback_info info) { HILOGI("Disconnect called"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); HidHost *profile = HidHost::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool isOK = profile->Disconnect(device); - napi_value result = nullptr; - napi_get_boolean(env, isOK, &result); - HILOGI("isOK: %{public}d", isOK); - return result; + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t errorCode = profile->Disconnect(device); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_SUCCESS, errorCode); + return NapiGetBooleanTrue(env); } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_bluetooth_host.cpp b/frameworks/js/napi/src/napi_bluetooth_host.cpp index bddfc96d..7d524751 100644 --- a/frameworks/js/napi/src/napi_bluetooth_host.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_host.cpp @@ -16,6 +16,8 @@ #include "napi_bluetooth_host.h" #include "bluetooth_host.h" #include "bluetooth_log.h" +#include "bluetooth_errorcode.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_host_observer.h" #include "napi_bluetooth_remote_device_observer.h" #include "napi_bluetooth_utils.h" @@ -24,8 +26,10 @@ namespace OHOS { namespace Bluetooth { namespace { NapiBluetoothHostObserver g_bluetoothHostObserver; -NapiBluetoothRemoteDeviceObserver g_bluetoothRemoteDevice; +std::shared_ptr g_bluetoothRemoteDevice; std::string g_RemoteDeviceAddr; +std::vector> g_DiscoveryDevices; +std::mutex deviceMutex; } // namespace napi_value BluetoothHostInit(napi_env env, napi_value exports) @@ -45,6 +49,7 @@ napi_value BluetoothHostInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getLocalName", GetLocalName), DECLARE_NAPI_FUNCTION("getPairedDevices", GetPairedDevices), DECLARE_NAPI_FUNCTION("getProfileConnState", GetProfileConnState), + DECLARE_NAPI_FUNCTION("getProfileConnectionState", GetProfileConnState), DECLARE_NAPI_FUNCTION("setDevicePairingConfirmation", SetDevicePairingConfirmation), DECLARE_NAPI_FUNCTION("setLocalName", SetLocalName), DECLARE_NAPI_FUNCTION("setBluetoothScanMode", SetBluetoothScanMode), @@ -63,6 +68,11 @@ void RegisterObserverToHost() { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); + g_bluetoothRemoteDevice = std::make_shared(); + if (g_bluetoothRemoteDevice == nullptr) { + HILOGE("g_bluetoothRemoteDevice is null"); + return; + } host->RegisterObserver(g_bluetoothHostObserver); host->RegisterRemoteDeviceObserver(g_bluetoothRemoteDevice); } @@ -71,68 +81,47 @@ napi_value EnableBluetooth(napi_env env, napi_callback_info info) { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool enabled = host->EnableBle(); - if (enabled) { + int32_t ret = host->EnableBle(); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + if (ret == BT_SUCCESS) { SetCurrentAppOperate(true); } - napi_value result = nullptr; - napi_get_boolean(env, enabled, &result); - HILOGI("end"); - return result; + return NapiGetBooleanTrue(env); } napi_value DisableBluetooth(napi_env env, napi_callback_info info) { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool enabled = false; // only ble - if (host->GetBtState() == BTStateID::STATE_TURN_OFF) { - enabled = host->DisableBle(); + int state = BTStateID::STATE_TURN_OFF; + int ret = host->GetBtState(state); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + if (state == BTStateID::STATE_TURN_OFF) { + ret = host->DisableBle(); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); } else { - enabled = host->DisableBt(); + ret = host->DisableBt(); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); } - if (enabled) { + if (ret == BT_SUCCESS) { SetCurrentAppOperate(true); } - napi_value result = nullptr; - napi_get_boolean(env, enabled, &result); - HILOGI("end"); - return result; + return NapiGetBooleanTrue(env); } napi_value SetLocalName(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_ONE; - napi_value argv[ARGS_SIZE_ONE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - HILOGE("The argc is 0"); - return NapiGetBooleanFalse(env); - } - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - size_t bufferSize = 0; - napi_get_value_string_utf8(env, argv[PARAM0], nullptr, 0, &bufferSize); - HILOGI("local name writeChar bufferSize = %{public}d", (int)bufferSize); - if (bufferSize == 0) { - return NapiGetBooleanFalse(env); - } - char buffer[bufferSize + 1]; - size_t strLength = 0; - napi_get_value_string_utf8(env, argv[PARAM0], buffer, bufferSize + 1, &strLength); - std::string localName(buffer); + std::string localName = INVALID_NAME; + bool checkRet = CheckLocalNameParam(env, info, localName); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool enabled = host->SetLocalName(localName); - napi_value result = nullptr; - napi_get_boolean(env, enabled, &result); - HILOGI("end"); - return result; + int32_t ret = host->SetLocalName(localName); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } napi_value GetLocalName(napi_env env, napi_callback_info info) @@ -140,8 +129,10 @@ napi_value GetLocalName(napi_env env, napi_callback_info info) napi_value result = nullptr; HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - std::string localName = host->GetLocalName(); + std::string localName = INVALID_NAME; + int32_t err = host->GetLocalName(localName); napi_create_string_utf8(env, localName.c_str(), localName.size(), &result); + NAPI_BT_ASSERT_RETURN(env, err == BT_SUCCESS, err, result); HILOGI("end"); return result; } @@ -149,18 +140,17 @@ napi_value GetLocalName(napi_env env, napi_callback_info info) napi_value GetRemoteDeviceName(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_ONE; - napi_value argv[ARGS_SIZE_ONE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); - } + std::string remoteAddr = INVALID_MAC_ADDRESS; + std::string name = INVALID_NAME; napi_value result = nullptr; - ParseString(env, g_RemoteDeviceAddr, argv[PARAM0]); - std::string name = - BluetoothHost::GetDefaultHost().GetRemoteDevice(g_RemoteDeviceAddr, BT_TRANSPORT_BREDR).GetDeviceName(); + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + napi_create_string_utf8(env, name.c_str(), name.size(), &result); + NAPI_BT_ASSERT_RETURN(env, checkRet == true, BT_ERR_INVALID_PARAM, result); + + int transport = GetDeviceTransport(remoteAddr); + int32_t err = BluetoothHost::GetDefaultHost().GetRemoteDevice(remoteAddr, transport).GetDeviceName(name); napi_create_string_utf8(env, name.c_str(), name.size(), &result); + NAPI_BT_ASSERT_RETURN(env, err == BT_SUCCESS, err, result); HILOGI("end"); return result; } @@ -168,16 +158,14 @@ napi_value GetRemoteDeviceName(napi_env env, napi_callback_info info) napi_value GetRemoteDeviceClass(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_ONE; - napi_value argv[ARGS_SIZE_ONE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); - } - ParseString(env, g_RemoteDeviceAddr, argv[PARAM0]); - BluetoothDeviceClass deviceClass = - BluetoothHost::GetDefaultHost().GetRemoteDevice(g_RemoteDeviceAddr, BT_TRANSPORT_BREDR).GetDeviceClass(); + std::string remoteAddr = INVALID_MAC_ADDRESS; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + + int transport = GetDeviceTransport(remoteAddr); + int deviceCod = 0; + int32_t err = BluetoothHost::GetDefaultHost().GetRemoteDevice(remoteAddr, transport).GetDeviceClass(deviceCod); + BluetoothDeviceClass deviceClass = BluetoothDeviceClass(deviceCod); int tmpCod = deviceClass.GetClassOfDevice(); int tmpMajorClass = deviceClass.GetMajorClass(); int tmpMajorMinorClass = deviceClass.GetMajorMinorClass(); @@ -200,6 +188,7 @@ napi_value GetRemoteDeviceClass(napi_env env, napi_callback_info info) napi_value cod = 0; napi_create_int32(env, tmpCod, &cod); napi_set_named_property(env, result, "classOfDevice", cod); + NAPI_BT_ASSERT_RETURN(env, err == BT_SUCCESS, err, result); HILOGI("end"); return result; } @@ -207,42 +196,28 @@ napi_value GetRemoteDeviceClass(napi_env env, napi_callback_info info) napi_value SetBluetoothScanMode(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_TWO; - napi_value argv[ARGS_SIZE_TWO] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); - } - napi_valuetype valuetype = napi_undefined; - - NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); int32_t mode = 0; - napi_get_value_int32(env, argv[PARAM0], &mode); - HILOGI("mode = %{public}d", mode); - NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); int32_t duration = 0; - napi_get_value_int32(env, argv[PARAM1], &duration); - HILOGI("duration = %{public}d", duration); + bool checkRet = CheckSetBluetoothScanModeParam(env, info, mode, duration); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + HILOGI("mode = %{public}d,duration = %{public}d", mode, duration); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool enabled = host->SetBtScanMode(mode, duration); + int32_t ret = host->SetBtScanMode(mode, duration); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); host->SetBondableMode(BT_TRANSPORT_BREDR, 1); - napi_value result = nullptr; - napi_get_boolean(env, enabled, &result); - HILOGI("end"); - return result; + return NapiGetBooleanTrue(env); } napi_value GetBluetoothScanMode(napi_env env, napi_callback_info info) { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - int32_t scanMode = host->GetBtScanMode(); + int32_t scanMode = 0; + int32_t err = host->GetBtScanMode(scanMode); napi_value result = nullptr; napi_create_uint32(env, scanMode, &result); + NAPI_BT_ASSERT_RETURN(env, err == BT_SUCCESS, err, result); HILOGI("end"); return result; } @@ -250,30 +225,29 @@ napi_value GetBluetoothScanMode(napi_env env, napi_callback_info info) napi_value StartBluetoothDiscovery(napi_env env, napi_callback_info info) { HILOGI("start"); + ClearDiscoveryDevice(); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool isStart = host->StartBtDiscovery(); - napi_value result = nullptr; - napi_get_boolean(env, isStart, &result); - HILOGI("end"); - return result; + int ret = host->StartBtDiscovery(); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } napi_value StopBluetoothDiscovery(napi_env env, napi_callback_info info) { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool isStart = host->CancelBtDiscovery(); - napi_value result = nullptr; - napi_get_boolean(env, isStart, &result); - HILOGI("end"); - return result; + int ret = host->CancelBtDiscovery(); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } napi_value GetState(napi_env env, napi_callback_info info) { HILOGI("enter"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - int32_t state = host->GetBtState(); + int32_t state = BTStateID::STATE_TURN_OFF; + int32_t err = host->GetBtState(state); + NAPI_BT_ASSERT_RETURN_FALSE(env, err == NO_ERROR, err); int32_t status = static_cast(BluetoothState::STATE_OFF); switch (state) { case BTStateID::STATE_TURNING_ON: @@ -314,10 +288,12 @@ napi_value GetBtConnectionState(napi_env env, napi_callback_info info) { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - int32_t state = host->GetBtConnectionState(); + int state = static_cast(BTConnectState::DISCONNECTED); + int32_t err = host->GetBtConnectionState(state); HILOGI("start state %{public}d", state); napi_value result = nullptr; napi_create_int32(env, GetProfileConnectionState(state), &result); + NAPI_BT_ASSERT_RETURN(env, err == BT_SUCCESS, err, result); HILOGI("end"); return result; } @@ -325,47 +301,46 @@ napi_value GetBtConnectionState(napi_env env, napi_callback_info info) napi_value PairDevice(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_ONE; - napi_value argv[ARGS_SIZE_ONE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); + std::string remoteAddr = INVALID_MAC_ADDRESS; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr, BT_TRANSPORT_BREDR); + int deviceType = remoteDevice.GetDeviceType(); + if (deviceType == INVALID_TYPE) { + HILOGE("device is not discovery or scan, just quick BLE pair"); + remoteDevice = BluetoothRemoteDevice(remoteAddr, BT_TRANSPORT_BLE); } - ParseString(env, g_RemoteDeviceAddr, argv[PARAM0]); - BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(g_RemoteDeviceAddr, BT_TRANSPORT_BREDR); - bool isSuccess = remoteDevice.StartPair(); - napi_value result = nullptr; - napi_get_boolean(env, isSuccess, &result); - HILOGI("end"); - return result; + if (deviceType == DEVICE_TYPE_LE) { + remoteDevice = BluetoothRemoteDevice(remoteAddr, BT_TRANSPORT_BLE); + } + int32_t ret = remoteDevice.StartPair(); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } napi_value CancelPairedDevice(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_ONE; - napi_value argv[ARGS_SIZE_ONE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); - } - ParseString(env, g_RemoteDeviceAddr, argv[PARAM0]); - BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(g_RemoteDeviceAddr, BT_TRANSPORT_BREDR); + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + + int transport = GetDeviceTransport(remoteAddr); + BluetoothRemoteDevice remoteDevice = BluetoothRemoteDevice(remoteAddr, transport); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - bool isSuccess = host->RemovePair(remoteDevice); - napi_value result = nullptr; - napi_get_boolean(env, isSuccess, &result); - HILOGI("end"); - return result; + int32_t ret = host->RemovePair(remoteDevice); + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + + return NapiGetBooleanTrue(env); } napi_value GetPairedDevices(napi_env env, napi_callback_info info) { HILOGI("start"); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - std::vector remoteDeviceLists = host->GetPairedDevices(BT_TRANSPORT_BREDR); + std::vector remoteDeviceLists; + int32_t ret = host->GetPairedDevices(BT_TRANSPORT_BREDR, remoteDeviceLists); napi_value result = nullptr; int count = 0; napi_create_array(env, &result); @@ -375,6 +350,16 @@ napi_value GetPairedDevices(napi_env env, napi_callback_info info) napi_set_element(env, result, count, remoteDeviceResult); count++; } + NAPI_BT_ASSERT_RETURN(env, ret == BT_SUCCESS, ret, result); + std::vector bleDeviceLists; + ret = host->GetPairedDevices(BT_TRANSPORT_BLE, bleDeviceLists); + for (auto vec : bleDeviceLists) { + napi_value remoteDeviceResult; + napi_create_string_utf8(env, vec.GetDeviceAddr().c_str(), vec.GetDeviceAddr().size(), &remoteDeviceResult); + napi_set_element(env, result, count, remoteDeviceResult); + count++; + } + NAPI_BT_ASSERT_RETURN(env, ret == BT_SUCCESS, ret, result); HILOGI("end"); return result; } @@ -382,28 +367,18 @@ napi_value GetPairedDevices(napi_env env, napi_callback_info info) napi_value SetDevicePairingConfirmation(napi_env env, napi_callback_info info) { HILOGI("start"); - size_t argc = ARGS_SIZE_TWO; - napi_value argv[ARGS_SIZE_TWO] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return NapiGetNull(env); - } - ParseString(env, g_RemoteDeviceAddr, argv[PARAM0]); - napi_valuetype valuetype = napi_undefined; - - NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Boolean expected."); + std::string remoteAddr {}; bool accept = false; - napi_get_value_bool(env, argv[PARAM1], &accept); + bool checkRet = CheckSetDevicePairingConfirmationParam(env, info, remoteAddr, accept); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); + HILOGI("SetDevicePairingConfirmation::accept = %{public}d", accept); - bool isSuccess = BluetoothHost::GetDefaultHost() - .GetRemoteDevice(g_RemoteDeviceAddr, BT_TRANSPORT_BREDR) + int transport = GetDeviceTransport(remoteAddr); + int32_t ret = BluetoothHost::GetDefaultHost() + .GetRemoteDevice(remoteAddr, transport) .SetDevicePairingConfirmation(accept); - napi_value result = nullptr; - napi_get_boolean(env, isSuccess, &result); - HILOGI("end"); - return result; + NAPI_BT_ASSERT_RETURN_FALSE(env, ret == BT_SUCCESS, ret); + return NapiGetBooleanTrue(env); } static void SetCallback(const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result) @@ -457,45 +432,6 @@ static void ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo HILOGI("end"); } -static napi_value JSParaError(const napi_env &env, const napi_ref &callback) -{ - if (callback) { - return NapiGetNull(env); - } else { - napi_value promise = nullptr; - napi_deferred deferred = nullptr; - napi_create_promise(env, &deferred, &promise); - SetPromise(env, deferred, NapiGetNull(env)); - return promise; - } -} - -static napi_value GetCallback(const napi_env &env, const napi_value &value, CallbackPromiseInfo ¶ms) -{ - HILOGI("enter"); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, value, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, value, 1, ¶ms.callback); - HILOGI("end"); - return NapiGetNull(env); -} - -static napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, CallbackPromiseInfo ¶ms) -{ - HILOGI("enter"); - size_t argc = ARGS_SIZE_ONE; - napi_value argv[ARGS_SIZE_ONE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argv[PARAM0] != nullptr) { - GetCallback(env, argv[PARAM0], params); - } - HILOGI("end"); - return NapiGetNull(env); -} - static void GetDeviceNameSyncWorkStart(GattGetDeviceNameCallbackInfo *asynccallbackinfo) { HILOGI("enter"); @@ -535,16 +471,34 @@ void AsyncCompleteCallbackGetDeviceName(napi_env env, napi_status status, void * HILOGI("napi_create_async_work complete end"); } +static napi_status ParseAsyncCallbackParameters(napi_env env, napi_callback_info info, CallbackPromiseInfo ¶ms) +{ + HILOGI("enter"); + size_t expectedArgsCount = ARGS_SIZE_ONE; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, NULL)); + NAPI_BT_RETURN_IF(argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE, + "Requires 0 or 1 arguments.", napi_invalid_arg); + if (argc == expectedArgsCount) { + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM0])); + napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); + } + HILOGI("end"); + return napi_ok; +} + napi_value GetDeviceName(napi_env env, napi_callback_info info) { HILOGI("start"); - napi_ref callback = nullptr; GattGetDeviceNameCallbackInfo *asynccallbackinfo = - new (std::nothrow) GattGetDeviceNameCallbackInfo {.env = env, .asyncWork = nullptr}; - if (!asynccallbackinfo) { - return JSParaError(env, callback); + new GattGetDeviceNameCallbackInfo {.env = env, .asyncWork = nullptr}; + auto status = ParseAsyncCallbackParameters(env, info, asynccallbackinfo->promise); + if (status != napi_ok) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } - ParseParameters(env, info, asynccallbackinfo->promise); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value promise = nullptr; PaddingCallbackPromiseInfo(env, asynccallbackinfo->promise.callback, asynccallbackinfo->promise, promise); napi_value resourceName = nullptr; @@ -562,12 +516,12 @@ napi_value GetDeviceName(napi_env env, napi_callback_info info) (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + HILOGI("end"); if (asynccallbackinfo->promise.isCallback) { - return NapiGetNull(env); + return NapiGetUndefinedRet(env); } else { return promise; } - HILOGI("end"); } static void GetRssiValueSyncWorkStart(GattGetRssiValueCallbackInfo *asynccallbackinfo) @@ -623,13 +577,14 @@ void AsyncCompleteCallbackGetRssiValue(napi_env env, napi_status status, void *d napi_value GetRssiValue(napi_env env, napi_callback_info info) { HILOGI("start"); - napi_ref callback = nullptr; GattGetRssiValueCallbackInfo *asynccallbackinfo = new (std::nothrow) GattGetRssiValueCallbackInfo {.env = env, .asyncWork = nullptr}; - if (!asynccallbackinfo) { - return JSParaError(env, callback); + auto status = ParseAsyncCallbackParameters(env, info, asynccallbackinfo->promise); + if (status != napi_ok) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; } - ParseParameters(env, info, asynccallbackinfo->promise); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value promise = nullptr; PaddingCallbackPromiseInfo(env, asynccallbackinfo->promise.callback, asynccallbackinfo->promise, promise); @@ -648,12 +603,12 @@ napi_value GetRssiValue(napi_env env, napi_callback_info info) (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + HILOGI("end"); if (asynccallbackinfo->promise.isCallback) { - return NapiGetNull(env); + return NapiGetUndefinedRet(env); } else { return promise; } - HILOGI("end"); } napi_value PropertyValueInit(napi_env env, napi_value exports) @@ -739,22 +694,17 @@ napi_value ScanModeInit(napi_env env) HILOGI("enter"); napi_value scanMode = nullptr; napi_create_object(env, &scanMode); - SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_NONE), "SCAN_MODE_NONE"); - SetNamedPropertyByInteger( - env, scanMode, static_cast(ScanMode::SCAN_MODE_CONNECTABLE), "SCAN_MODE_CONNECTABLE"); - SetNamedPropertyByInteger( - env, scanMode, static_cast(ScanMode::SCAN_MODE_GENERAL_DISCOVERABLE), "SCAN_MODE_GENERAL_DISCOVERABLE"); - SetNamedPropertyByInteger(env, - scanMode, - static_cast(ScanMode::SCAN_MODE_LIMITED_DISCOVERABLE), + SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_NONE), + "SCAN_MODE_NONE"); + SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_CONNECTABLE), + "SCAN_MODE_CONNECTABLE"); + SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_GENERAL_DISCOVERABLE), + "SCAN_MODE_GENERAL_DISCOVERABLE"); + SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_LIMITED_DISCOVERABLE), "SCAN_MODE_LIMITED_DISCOVERABLE"); - SetNamedPropertyByInteger(env, - scanMode, - static_cast(ScanMode::SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE), + SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE), "SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE"); - SetNamedPropertyByInteger(env, - scanMode, - static_cast(ScanMode::SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE), + SetNamedPropertyByInteger(env, scanMode, static_cast(ScanMode::SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE), "SCAN_MODE_CONNECTABLE_LIMITED_DISCOVERABLE"); return scanMode; } @@ -985,32 +935,48 @@ napi_value MajorMinorClassOfDeviceInit(napi_env env) napi_value GetProfileConnState(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - int profileId = 0; - if (!ParseInt32(env, profileId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + bool checkRet = CheckProfileIdParam(env, info, profileId); + NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet, BT_ERR_INVALID_PARAM); BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - int state = host->GetBtProfileConnState(GetProfileId(profileId)); + int state = static_cast(BTConnectState::DISCONNECTED); + int32_t err = host->GetBtProfileConnState(GetProfileId(profileId), state); int status = GetProfileConnectionState(state); + napi_value ret = nullptr; napi_create_int32(env, status, &ret); + NAPI_BT_ASSERT_RETURN(env, err == BT_SUCCESS, err, ret); HILOGI("status: %{public}d", status); return ret; } + +void AddDiscoveryDevice(std::shared_ptr &device) +{ + std::lock_guard lock(deviceMutex); + for (auto dev : g_DiscoveryDevices) { + if (device->GetDeviceAddr().compare(dev->GetDeviceAddr()) == 0) { + return; + } + } + g_DiscoveryDevices.push_back(device); +} + +void ClearDiscoveryDevice() +{ + std::lock_guard lock(deviceMutex); + g_DiscoveryDevices.clear(); +} + +int GetDeviceTransport(std::string &device) +{ + std::lock_guard lock(deviceMutex); + for (auto dev : g_DiscoveryDevices) { + if (device.compare(dev->GetDeviceAddr()) == 0) { + return dev->GetTransportType(); + } + } + + return BT_TRANSPORT_BREDR; +} } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_bluetooth_host_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_host_observer.cpp index 87350466..ce52bb1c 100644 --- a/frameworks/js/napi/src/napi_bluetooth_host_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_host_observer.cpp @@ -20,6 +20,7 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "napi_bluetooth_host.h" #include @@ -60,13 +61,11 @@ void NapiBluetoothHostObserver::OnStateChanged(const int transport, const int st if (!DealStateChange(transport, status, state)) { return; } - std::shared_ptr callbackInfo = GetCallbackInfoByType(REGISTER_STATE_CHANGE_TYPE); if (callbackInfo == nullptr) { HILOGI("This callback is not registered by ability."); return; } - uv_loop_s *loop = nullptr; napi_get_uv_event_loop(callbackInfo->env_, &loop); if (loop == nullptr) { @@ -183,7 +182,10 @@ void NapiBluetoothHostObserver::OnDiscoveryResult(const BluetoothRemoteDevice &d callbackData->function = &NapiBluetoothHostObserver::UvQueueWorkOnDiscoveryResult; callbackData->env = callbackInfo->env_; callbackData->callback = callbackInfo->callback_; - callbackData->data = std::make_shared(device); + std::shared_ptr remoteDevice = std::make_shared(device); + callbackData->data = remoteDevice; + + AddDiscoveryDevice(remoteDevice); uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { diff --git a/frameworks/js/napi/src/napi_bluetooth_opp.cpp b/frameworks/js/napi/src/napi_bluetooth_opp.cpp index 95f560ce..53558ae1 100644 --- a/frameworks/js/napi/src/napi_bluetooth_opp.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_opp.cpp @@ -46,7 +46,7 @@ void NapiBluetoothOpp::DefineOppJSClass(napi_env env) napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_OPP, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_OPP, napiProfile); Opp *profile = Opp::GetProfile(); profile->RegisterObserver(&observer_); HILOGI("DefineOppJSClass finished"); diff --git a/frameworks/js/napi/src/napi_bluetooth_pan.cpp b/frameworks/js/napi/src/napi_bluetooth_pan.cpp index 69eb12f0..270cc35c 100644 --- a/frameworks/js/napi/src/napi_bluetooth_pan.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_pan.cpp @@ -13,12 +13,15 @@ * limitations under the License. */ -#include "bluetooth_pan.h" +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" +#include "bluetooth_pan.h" +#include "bluetooth_utils.h" +#include "napi_bluetooth_error.h" +#include "napi_bluetooth_pan.h" #include "napi_bluetooth_pan_observer.h" -#include "napi_bluetooth_utils.h" #include "napi_bluetooth_profile.h" -#include "napi_bluetooth_pan.h" +#include "napi_bluetooth_utils.h" namespace OHOS { namespace Bluetooth { @@ -42,7 +45,7 @@ void NapiBluetoothPan::DefinePanJSClass(napi_env env) sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_PAN_NETWORK, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_PAN_NETWORK, napiProfile); Pan *profile = Pan::GetProfile(); profile->RegisterObserver(&NapiBluetoothPan::observer_); HILOGI("finished"); @@ -127,24 +130,21 @@ napi_value NapiBluetoothPan::Off(napi_env env, napi_callback_info info) napi_value NapiBluetoothPan::GetConnectionDevices(napi_env env, napi_callback_info info) { HILOGI("enter"); - - size_t expectedArgsCount = ARGS_SIZE_ZERO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ZERO] = {}; - napi_value thisVar = nullptr; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("No Requires argument."); - return ret; + if (napi_create_array(env, &ret) != napi_ok) { + HILOGE("napi_create_array failed."); } - napi_create_array(env, &ret); + + napi_status checkRet = CheckEmptyParam(env, info); + NAPI_BT_ASSERT_RETURN(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM, ret); + Pan *profile = Pan::GetProfile(); vector states = { static_cast(BTConnectState::CONNECTED) }; - vector devices = profile->GetDevicesByStates(states); + vector devices; + int errorCode = profile->GetDevicesByStates(states, devices); + HILOGI("errorCode:%{public}s, devices size:%{public}zu", GetErrorCode(errorCode).c_str(), devices.size()); + NAPI_BT_ASSERT_RETURN(env, errorCode == BT_SUCCESS, errorCode, ret); + vector deviceVector; for (auto &device : devices) { deviceVector.push_back(device.GetDeviceAddr()); @@ -156,32 +156,27 @@ napi_value NapiBluetoothPan::GetConnectionDevices(napi_env env, napi_callback_in napi_value NapiBluetoothPan::GetDeviceState(napi_env env, napi_callback_info info) { HILOGI("enter"); - - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; + napi_value result = nullptr; + int32_t profileState = ProfileConnectionState::STATE_DISCONNECTED; + if (napi_create_int32(env, profileState, &result) != napi_ok) { + HILOGE("napi_create_int32 failed."); } + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN(env, checkRet, BT_ERR_INVALID_PARAM, result); + Pan *profile = Pan::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - int state = profile->GetDeviceState(device); - int profileState = GetProfileConnectionState(state); - napi_value result = nullptr; - napi_create_int32(env, profileState, &result); + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t state = static_cast(BTConnectState::DISCONNECTED); + int32_t errorCode = profile->GetDeviceState(device, state); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN(env, errorCode == BT_SUCCESS, errorCode, result); + + profileState = GetProfileConnectionState(state); + if (napi_create_int32(env, profileState, &result) != napi_ok) { + HILOGE("napi_create_int32 failed."); + } HILOGI("profileState: %{public}d", profileState); return result; } @@ -189,88 +184,58 @@ napi_value NapiBluetoothPan::GetDeviceState(napi_env env, napi_callback_info inf napi_value NapiBluetoothPan::Disconnect(napi_env env, napi_callback_info info) { HILOGI("enter"); + std::string remoteAddr {}; + bool checkRet = CheckDeivceIdParam(env, info, remoteAddr); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); + Pan *profile = Pan::GetProfile(); + BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR); + int32_t errorCode = profile->Disconnect(device); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_SUCCESS, errorCode); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("string expected."); - return ret; - } + return NapiGetBooleanTrue(env); +} - Pan *profile = Pan::GetProfile(); - BluetoothRemoteDevice device(deviceId, 1); - bool res = profile->Disconnect(device); - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; +static bool CheckSetTetheringParam(napi_env env, napi_callback_info info, bool &out) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + NAPI_BT_RETURN_IF(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok, "call failed.", false); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Requires 1 argument.", false); + NAPI_BT_RETURN_IF(!ParseBool(env, out, argv[PARAM0]), "Bool expected.", false); + return true; } napi_value NapiBluetoothPan::SetTethering(napi_env env, napi_callback_info info) { HILOGI("enter"); - - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ONE] = {0}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } - bool value; - if (!ParseBool(env, value, argv[PARAM0])) { - HILOGE("Bool expected."); - return ret; - } + bool value = false; + bool checkRet = CheckSetTetheringParam(env, info, value); + NAPI_BT_ASSERT_RETURN_UNDEF(env, checkRet, BT_ERR_INVALID_PARAM); Pan *profile = Pan::GetProfile(); - bool res = profile->SetTethering(value); - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; + int32_t errorCode = profile->SetTethering(value); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_UNDEF(env, errorCode == BT_SUCCESS, errorCode); + + return NapiGetUndefinedRet(env); } napi_value NapiBluetoothPan::IsTetheringOn(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ZERO; - size_t argc = expectedArgsCount; - napi_value argv[ARGS_SIZE_ZERO] = {}; - napi_value thisVar = nullptr; - - napi_value ret = nullptr; - napi_get_undefined(env, &ret); + napi_status checkRet = CheckEmptyParam(env, info); + NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("No Requires argument."); - return ret; - } Pan *profile = Pan::GetProfile(); - bool res = profile->IsTetheringOn(); - napi_value result = nullptr; - napi_get_boolean(env, res, &result); - HILOGI("res: %{public}d", res); - return result; + bool result = false; + int32_t errorCode = profile->IsTetheringOn(result); + HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str()); + NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_SUCCESS, errorCode); + + HILOGI("IsTetheringOn: %{public}d", result); + return NapiGetBooleanRet(env, result); } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_bluetooth_pbap_pce.cpp b/frameworks/js/napi/src/napi_bluetooth_pbap_pce.cpp index fe788b44..57115820 100644 --- a/frameworks/js/napi/src/napi_bluetooth_pbap_pce.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_pbap_pce.cpp @@ -39,7 +39,7 @@ void NapiPbapClient::DefinePbapClientJSClass(napi_env env) sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value NapiProfile; napi_new_instance(env, constructor, 0, nullptr, &NapiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_PBAP_CLIENT, NapiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_PBAP_CLIENT, NapiProfile); HILOGI("finished"); } diff --git a/frameworks/js/napi/src/napi_bluetooth_pbap_pse.cpp b/frameworks/js/napi/src/napi_bluetooth_pbap_pse.cpp index 57ced91e..11ea89c5 100644 --- a/frameworks/js/napi/src/napi_bluetooth_pbap_pse.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_pbap_pse.cpp @@ -34,11 +34,11 @@ void NapiPbapServer::DefinePbapServerJSClass(napi_env env) DECLARE_NAPI_FUNCTION("disconnect", Disconnect), }; - napi_define_class(env, "PbapServer", NAPI_AUTO_LENGTH, PbapServerConstructor, nullptr, + napi_define_class(env, "PbapServer", NAPI_AUTO_LENGTH, PbapServerConstructor, nullptr, sizeof(properties) / sizeof(properties[0]), properties, &constructor); napi_value napiProfile; napi_new_instance(env, constructor, 0, nullptr, &napiProfile); - NapiProfile::SetProfile(ProfileId::PROFILE_PBAP_SERVER, napiProfile); + NapiProfile::SetProfile(env, ProfileId::PROFILE_PBAP_SERVER, napiProfile); HILOGI("finished"); } diff --git a/frameworks/js/napi/src/napi_bluetooth_profile.cpp b/frameworks/js/napi/src/napi_bluetooth_profile.cpp index 4a7393f7..f698c916 100644 --- a/frameworks/js/napi/src/napi_bluetooth_profile.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_profile.cpp @@ -17,49 +17,52 @@ namespace OHOS { namespace Bluetooth { -thread_local std::map NapiProfile::profiles_; +thread_local std::map NapiProfile::profiles_; void NapiProfile::DefineProfileFunctions(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("getProfile", GetProfile), DECLARE_NAPI_FUNCTION("getProfileInst", GetProfile), + DECLARE_NAPI_FUNCTION("getProfileInstance", GetProfile), }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); ProfileEnumInit(env, exports); } -void NapiProfile::SetProfile(ProfileId code, napi_value profile) +void NapiProfile::SetProfile(napi_env env, ProfileId code, napi_value profile) { - profiles_[code] = profile; + napi_ref profileRef; + if (napi_create_reference(env, profile, 1, &profileRef) != napi_ok) { + HILOGE("napi create reference failed, profileId:%{public}d", code); + return; + } + profiles_[code] = profileRef; } napi_value NapiProfile::GetProfile(napi_env env, napi_callback_info info) { - HILOGI("enter"); size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = {0}; napi_value thisVar = nullptr; - bool isOK = false; - napi_value ret = nullptr; - napi_get_boolean(env, isOK, &ret); + napi_value ret = NapiGetNull(env); + napi_status funcRet = napi_generic_failure; + + funcRet = napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + NAPI_BT_RETURN_IF(funcRet != napi_ok, "call napi_get_cb_info failed.", ret); + NAPI_BT_RETURN_IF(argc != expectedArgsCount, "Requires 1 argument", ret); - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } int32_t profileId; - if (!ParseInt32(env, profileId, argv[PARAM0])) { - HILOGE("False type! Int32 required."); - return ret; - } + NAPI_BT_RETURN_IF(!ParseInt32(env, profileId, argv[PARAM0]), "False type! Int32 required.", ret); - napi_value profile = profiles_[static_cast(profileId)]; - if (!profile) { - return ret; - } + napi_ref profileRef = profiles_[static_cast(profileId)]; + napi_value profile = nullptr; + funcRet = napi_get_reference_value(env, profileRef, &profile); + NAPI_BT_RETURN_IF(funcRet != napi_ok, "call napi_get_reference_value failed", ret); + NAPI_BT_RETURN_IF(profile == nullptr, "napi get reference failed.", ret); + + HILOGI("profileId:%{public}d", profileId); return profile; } diff --git a/frameworks/js/napi/src/napi_bluetooth_remote_device_observer.cpp b/frameworks/js/napi/src/napi_bluetooth_remote_device_observer.cpp index 8986c7b1..d6a0602f 100644 --- a/frameworks/js/napi/src/napi_bluetooth_remote_device_observer.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_remote_device_observer.cpp @@ -60,7 +60,7 @@ void NapiBluetoothRemoteDeviceObserver::UvQueueWorkOnPairStatusChanged( void NapiBluetoothRemoteDeviceObserver::OnPairStatusChanged(const BluetoothRemoteDevice &device, int status) { - std::shared_ptr callbackInfo = GetCallbackInfoByType(REGISTER_BONE_STATE_TYPE); + std::shared_ptr callbackInfo = GetCallbackInfoByType(REGISTER_BOND_STATE_TYPE); if (callbackInfo == nullptr) { HILOGI("This callback is not registered by ability."); return; diff --git a/frameworks/js/napi/src/napi_bluetooth_spp_client.cpp b/frameworks/js/napi/src/napi_bluetooth_spp_client.cpp index bd400b4e..3d24947f 100644 --- a/frameworks/js/napi/src/napi_bluetooth_spp_client.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_spp_client.cpp @@ -12,9 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include "bluetooth_errorcode.h" #include "napi_bluetooth_spp_client.h" +#include "napi_bluetooth_error.h" +#include "napi_bluetooth_utils.h" #include "securec.h" +#include #include #include @@ -23,41 +26,29 @@ namespace Bluetooth { const int sleepTime = 5; std::map> NapiSppClient::clientMap; int NapiSppClient::count = 0; +const int SOCKET_BUFFER_SIZE = 1024; -napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) +static napi_status CheckSppConnectParams( + napi_env env, napi_callback_info info, std::string &deviceId, SppConnectCallbackInfo *callbackInfo) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_THREE; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {0}; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - if (argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE) { - HILOGE("Requires 2 or 3 arguments."); - return ret; - } - - std::string deviceId; - if (!ParseString(env, deviceId, argv[PARAM0])) { - HILOGE("Wrong argument type. String expected."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_THREE && argc != ARGS_SIZE_THREE - CALLBACK_SIZE), + "Requires 2 or 3 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseString(env, deviceId, argv[PARAM0]), + "Wrong argument type. String expected.", napi_invalid_arg); - SppConnectCallbackInfo *callbackInfo = new SppConnectCallbackInfo(); callbackInfo->env_ = env; callbackInfo->sppOption_ = GetSppOptionFromJS(env, argv[PARAM1]); - if (callbackInfo->sppOption_ == nullptr) { - HILOGE("GetSppOptionFromJS faild."); - return ret; - } + NAPI_BT_RETURN_IF((callbackInfo->sppOption_ == nullptr), "GetSppOptionFromJS faild.", napi_invalid_arg); callbackInfo->deviceId_ = deviceId; napi_value promise = nullptr; - if (argc == expectedArgsCount) { + if (argc == ARGS_SIZE_THREE) { // Callback mode HILOGI("callback mode"); napi_valuetype valueType = napi_undefined; @@ -66,7 +57,7 @@ napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) HILOGE("Wrong argument type. Function expected."); delete callbackInfo; callbackInfo = nullptr; - return ret; + return napi_invalid_arg; } napi_create_reference(env, argv[PARAM2], 1, &callbackInfo->callback_); napi_get_undefined(env, &promise); @@ -75,6 +66,16 @@ napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) HILOGI("promise mode"); napi_create_promise(env, &callbackInfo->deferred_, &promise); } + return napi_ok; +} + +napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + std::string deviceId; + SppConnectCallbackInfo *callbackInfo = new SppConnectCallbackInfo(); + auto status = CheckSppConnectParams(env, info, deviceId, callbackInfo); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value resource = nullptr; napi_create_string_utf8(env, "SppConnect", NAPI_AUTO_LENGTH, &resource); @@ -89,7 +90,7 @@ napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) UUID::FromString(callbackInfo->sppOption_->uuid_), callbackInfo->sppOption_->type_, callbackInfo->sppOption_->secure_); HILOGI("SppConnect client_ constructed"); - if (callbackInfo->client_->Connect() == BtStatus::BT_SUCCESS) { + if (callbackInfo->client_->Connect() == BtStatus::BT_SUCC) { HILOGI("SppConnect successfully"); callbackInfo->errorCode_ = CODE_SUCCESS; } else { @@ -144,34 +145,36 @@ napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) (void*)callbackInfo, &callbackInfo->asyncWork_); napi_queue_async_work(env, callbackInfo->asyncWork_); - return ret; + return NapiGetUndefinedRet(env); } -napi_value NapiSppClient::SppCloseClientSocket(napi_env env, napi_callback_info info) +static napi_status CheckSppCloseClientSocketParams(napi_env env, napi_callback_info info, int &id) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_ONE; napi_value argv[ARGS_SIZE_ONE] = {0}; napi_value thisVar = nullptr; - bool isOK = false; - napi_value ret = nullptr; - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_ONE), "Requires 1 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM0]), "Wrong argument type. int expected.", napi_invalid_arg); + return napi_ok; +} +napi_value NapiSppClient::SppCloseClientSocket(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); std::shared_ptr client = nullptr; int id = -1; - ParseInt32(env, id, argv[PARAM0]); + bool isOK = false; + auto status = CheckSppCloseClientSocketParams(env, info, id); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); if (clientMap[id]) { client = clientMap[id]; } else { HILOGE("no such key in map."); - return ret; + return NapiGetUndefinedRet(env); } if (client->client_) { @@ -179,140 +182,126 @@ napi_value NapiSppClient::SppCloseClientSocket(napi_env env, napi_callback_info isOK = true; } clientMap.erase(id); - napi_get_boolean(env, isOK, &ret); - return ret; + return NapiGetBooleanRet(env, isOK); } -napi_value NapiSppClient::SppWrite(napi_env env, napi_callback_info info) +static napi_status CheckSppWriteParams( + napi_env env, napi_callback_info info, int &id, char** totalBuf, size_t &totalSize) { HILOGI("enter"); - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_TWO; napi_value argv[ARGS_SIZE_TWO] = {0}; napi_value thisVar = nullptr; + + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_TWO), "Requires 2 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM0]), "Wrong argument type. int expected.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseArrayBuffer(env, (uint8_t**)(totalBuf), totalSize, argv[PARAM1]), + "ParseArrayBuffer failed.", napi_invalid_arg); + return napi_ok; +} + +napi_value NapiSppClient::SppWrite(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); char* totalBuf = nullptr; size_t totalSize = 0; bool isOK = false; int id = -1; - napi_get_boolean(env, isOK, &ret); - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 3 argument."); - return ret; - } - ParseInt32(env, id, argv[PARAM0]); - - if (!ParseArrayBuffer(env, (uint8_t**)(&totalBuf), totalSize, argv[PARAM1])) { - HILOGE("ParseArrayBuffer failed"); - return ret; - } - - if (clientMap[id]) { - OutputStream outputStream = clientMap[id]->client_->GetOutputStream(); - while (totalSize) { - int result = outputStream.Write(totalBuf, totalSize); - if (result > 0) { - totalSize = totalSize - result; - totalBuf += result; - isOK = true; - } else if (result < 0) { - HILOGI("Write socket exception!"); - return ret; - } - } - } else { - HILOGI("Client socket not exit!"); + auto status = CheckSppWriteParams(env, info, id, &totalBuf, totalSize); + NAPI_BT_ASSERT_RETURN_FALSE(env, status == napi_ok, BT_ERR_INVALID_PARAM); + NAPI_BT_ASSERT_RETURN_FALSE(env, clientMap[id] > 0, BT_ERR_INTERNAL_ERROR); + OutputStream outputStream = clientMap[id]->client_->GetOutputStream(); + while (totalSize) { + int result = outputStream.Write(totalBuf, totalSize); + NAPI_BT_ASSERT_RETURN_FALSE(env, result > 0, BT_ERR_SPP_IO); + totalSize = totalSize - result; + totalBuf += result; + isOK = true; } - napi_get_boolean(env, isOK, &ret); - return ret; + return NapiGetBooleanRet(env, isOK); } -void NapiSppClient::On(napi_env env, napi_callback_info info) +napi_status CheckSppClientOn(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_THREE; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {0}; napi_value thisVar = nullptr; int id = -1; - - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 3 argument."); - return; - } std::string type; - ParseString(env, type, argv[PARAM0]); std::shared_ptr callbackInfo; - if (type.c_str() == STR_BT_SPP_READ) { - callbackInfo = std::make_shared(); - } else { - HILOGE("Invalid type!"); - return; - } + + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_THREE), "Requires 3 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseString(env, type, argv[PARAM0]), + "Wrong argument type. String expected.", napi_invalid_arg); + NAPI_BT_RETURN_IF(type.c_str() != STR_BT_SPP_READ, "Invalid type.", napi_invalid_arg); + + callbackInfo = std::make_shared(); callbackInfo->env_ = env; napi_valuetype valueType1 = napi_undefined; napi_valuetype valueType2 = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType1); - napi_typeof(env, argv[PARAM2], &valueType2); - if (valueType1 != napi_number && valueType2 != napi_function) { - HILOGE("Wrong argument type. Function expected."); - return; - } + NAPI_BT_CALL_RETURN(napi_typeof(env, argv[PARAM1], &valueType1)); + NAPI_BT_CALL_RETURN(napi_typeof(env, argv[PARAM2], &valueType2)); + NAPI_BT_RETURN_IF(valueType1 != napi_number && valueType2 != napi_function, + "Wrong argument type. Function expected.", napi_invalid_arg); napi_create_reference(env, argv[PARAM2], 1, &callbackInfo->callback_); - ParseInt32(env, id, argv[PARAM1]); - std::shared_ptr client = clientMap[id]; - if (!client) { - HILOGI("client is nullptr"); - return; - } + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM1]), "Wrong argument type. Int expected.", napi_invalid_arg); + + std::shared_ptr client = NapiSppClient::clientMap[id]; + NAPI_BT_RETURN_IF(!client, "client is nullptr.", napi_invalid_arg); client->sppReadFlag = true; client->callbackInfos_[type] = callbackInfo; HILOGI("sppRead begin"); - client->thread_ = std::make_shared(SppRead, id); + client->thread_ = std::make_shared(NapiSppClient::SppRead, id); client->thread_->detach(); - return; + return napi_ok; } -void NapiSppClient::Off(napi_env env, napi_callback_info info) +napi_value NapiSppClient::On(napi_env env, napi_callback_info info) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_THREE; - size_t argc = expectedArgsCount; + auto status = CheckSppClientOn(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); +} + +napi_status CheckSppClientOff(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {0}; napi_value thisVar = nullptr; int id = -1; + std::string type; - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 3 argument."); - return; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_THREE), "Requires 3 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseString(env, type, argv[PARAM0]), + "Wrong argument type. String expected.", napi_invalid_arg); + NAPI_BT_RETURN_IF(type.c_str() != STR_BT_SPP_READ, "Invalid type.", napi_invalid_arg); - std::string type; - ParseString(env, type, argv[PARAM0]); + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM1]), "Wrong argument type. Int expected.", napi_invalid_arg); - ParseInt32(env, id, argv[PARAM1]); - std::shared_ptr client = clientMap[id]; - if (!client) { - HILOGE("client is nullptr"); - return; - } - if (type.c_str() != STR_BT_SPP_READ) { - HILOGE("type is wrong"); - return; - } + std::shared_ptr client = NapiSppClient::clientMap[id]; + NAPI_BT_RETURN_IF(!client, "client is nullptr.", napi_invalid_arg); client->callbackInfos_[type] = nullptr; client->sppReadFlag = false; sleep(sleepTime); - return; + return napi_ok; +} + +napi_value NapiSppClient::Off(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + auto status = CheckSppClientOff(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); } void NapiSppClient::SppRead(int id) @@ -323,7 +312,7 @@ void NapiSppClient::SppRead(int id) return; } InputStream inputStream = clientMap[id]->client_->GetInputStream(); - char buf[1024]; + char buf[SOCKET_BUFFER_SIZE]; int ret = 0; while (true) { @@ -363,7 +352,19 @@ void NapiSppClient::SppRead(int id) [](uv_work_t *work, int status) { BufferCallbackInfo *callbackInfo = (BufferCallbackInfo *)work->data; int size = callbackInfo->info_; + if (size < 0 || size > SOCKET_BUFFER_SIZE) { + HILOGE("malloc size error"); + delete work; + work = nullptr; + return; + } uint8_t* totalBuf = (uint8_t*) malloc(size); + if (totalBuf == nullptr) { + HILOGE("malloc failed"); + delete work; + work = nullptr; + return; + } if (memcpy_s(totalBuf, size, callbackInfo->buffer_, size) != EOK) { HILOGE("memcpy_s failed!"); } diff --git a/frameworks/js/napi/src/napi_bluetooth_spp_server.cpp b/frameworks/js/napi/src/napi_bluetooth_spp_server.cpp index dbe15711..d9df7397 100644 --- a/frameworks/js/napi/src/napi_bluetooth_spp_server.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_spp_server.cpp @@ -12,8 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "napi_bluetooth_error.h" #include "napi_bluetooth_utils.h" #include "napi_bluetooth_spp_server.h" +#include "bluetooth_errorcode.h" namespace OHOS { namespace Bluetooth { @@ -35,48 +37,35 @@ void DefineSppFunctions(napi_env env, napi_value exports) napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); } -napi_value NapiSppServer::SppListen(napi_env env, napi_callback_info info) +static napi_status CheckSppListenParams( + napi_env env, napi_callback_info info, string &name, SppListenCallbackInfo *callbackInfo) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_THREE; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_THREE; napi_value argv[ARGS_SIZE_THREE] = {0}; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - if (argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE) { - HILOGE("Requires 2 or 3 arguments."); - return ret; - } - - string name; - if (!ParseString(env, name, argv[PARAM0])) { - HILOGE("Wrong argument type. String expected."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_THREE && argc != ARGS_SIZE_THREE - CALLBACK_SIZE), + "Requires 2 or 3 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseString(env, name, argv[PARAM0]), + "Wrong argument type. String expected.", napi_invalid_arg); - SppListenCallbackInfo *callbackInfo = new SppListenCallbackInfo(); callbackInfo->env_ = env; callbackInfo->sppOption_ = GetSppOptionFromJS(env, argv[PARAM1]); - if (callbackInfo->sppOption_ == nullptr) { - HILOGE("GetSppOptionFromJS faild."); - return ret; - } + NAPI_BT_RETURN_IF((callbackInfo->sppOption_ == nullptr), "GetSppOptionFromJS faild.", napi_invalid_arg); callbackInfo->name_ = name; napi_value promise = nullptr; - if (argc == expectedArgsCount) { + if (argc == ARGS_SIZE_THREE) { HILOGI("callback mode"); napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM2], &valueType); + NAPI_BT_CALL_RETURN(napi_typeof(env, argv[PARAM2], &valueType)); if (valueType != napi_function) { HILOGE("Wrong argument type. Function expected."); delete callbackInfo; callbackInfo = nullptr; - return ret; + return napi_invalid_arg; } napi_create_reference(env, argv[PARAM2], 1, &callbackInfo->callback_); napi_get_undefined(env, &promise); @@ -84,6 +73,16 @@ napi_value NapiSppServer::SppListen(napi_env env, napi_callback_info info) HILOGI("promise mode"); napi_create_promise(env, &callbackInfo->deferred_, &promise); } + return napi_ok; +} + +napi_value NapiSppServer::SppListen(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + string name; + SppListenCallbackInfo *callbackInfo = new SppListenCallbackInfo(); + auto status = CheckSppListenParams(env, info, name, callbackInfo); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value resource = nullptr; napi_create_string_utf8(env, "SppListen", NAPI_AUTO_LENGTH, &resource); @@ -150,52 +149,41 @@ napi_value NapiSppServer::SppListen(napi_env env, napi_callback_info info) napi_queue_async_work(env, callbackInfo->asyncWork_); - return ret; + return NapiGetUndefinedRet(env); } - -napi_value NapiSppServer::SppAccept(napi_env env, napi_callback_info info) +static napi_status CheckSppAcceptParams( + napi_env env, napi_callback_info info, int32_t &serverSocketNum, SppAcceptCallbackInfo *callbackInfo) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_TWO; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_TWO; napi_value argv[ARGS_SIZE_TWO] = {0}; - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - if (argc != expectedArgsCount && argc != expectedArgsCount - CALLBACK_SIZE) { - HILOGE("Requires 2 or 3 arguments."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_TWO && argc != ARGS_SIZE_TWO - CALLBACK_SIZE), + "Requires 1 or 2 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseInt32(env, serverSocketNum, argv[PARAM0]), + "Wrong argument type. int expected.", napi_invalid_arg); - int32_t serverSocketNum = -1; - if (!ParseInt32(env, serverSocketNum, argv[PARAM0])) { - HILOGE("Wrong argument type. int expected."); - return ret; - } - std::shared_ptr server = serverMap[serverSocketNum]; + std::shared_ptr server = NapiSppServer::serverMap[serverSocketNum]; if (!server) { HILOGE("server is null"); - return ret; + return napi_invalid_arg; } - - SppAcceptCallbackInfo *callbackInfo = new SppAcceptCallbackInfo(); callbackInfo->env_ = env; callbackInfo->server_ = server->server_; napi_value promise = nullptr; - if (argc == expectedArgsCount) { + if (argc == ARGS_SIZE_TWO) { HILOGI("callback mode"); napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); + NAPI_BT_CALL_RETURN(napi_typeof(env, argv[PARAM1], &valueType)); if (valueType != napi_function) { HILOGE("Wrong argument type. Function expected."); delete callbackInfo; callbackInfo = nullptr; - return ret; + return napi_invalid_arg; } napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_); napi_get_undefined(env, &promise); @@ -203,6 +191,16 @@ napi_value NapiSppServer::SppAccept(napi_env env, napi_callback_info info) HILOGI("promise mode"); napi_create_promise(env, &callbackInfo->deferred_, &promise); } + return napi_ok; +} + +napi_value NapiSppServer::SppAccept(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + int32_t serverSocketNum = -1; + SppAcceptCallbackInfo *callbackInfo = new SppAcceptCallbackInfo(); + auto status = CheckSppAcceptParams(env, info, serverSocketNum, callbackInfo); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); napi_value resource = nullptr; napi_create_string_utf8(env, "SppAccept", NAPI_AUTO_LENGTH, &resource); @@ -259,29 +257,33 @@ napi_value NapiSppServer::SppAccept(napi_env env, napi_callback_info info) napi_queue_async_work(env, callbackInfo->asyncWork_); - return ret; + return NapiGetUndefinedRet(env); } -napi_value NapiSppServer::SppCloseServerSocket(napi_env env, napi_callback_info info) +static napi_status CheckSppCloseServerSockeParams(napi_env env, napi_callback_info info, int &id) { HILOGI("enter"); - size_t expectedArgsCount = ARGS_SIZE_ONE; - size_t argc = expectedArgsCount; + size_t argc = ARGS_SIZE_ONE; napi_value argv[ARGS_SIZE_ONE] = {0}; napi_value thisVar = nullptr; - bool isOK = false; - napi_value ret = nullptr; - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - if (argc != expectedArgsCount) { - HILOGE("Requires 1 argument."); - return ret; - } + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + NAPI_BT_RETURN_IF((argc != ARGS_SIZE_ONE), "Requires 1 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM0]), "Wrong argument type. int expected.", napi_invalid_arg); + return napi_ok; +} + +napi_value NapiSppServer::SppCloseServerSocket(napi_env env, napi_callback_info info) +{ + HILOGI("enter"); + int id = -1; + auto status = CheckSppCloseServerSockeParams(env, info, id); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + + bool isOK = false; std::shared_ptr server = nullptr; std::shared_ptr client = nullptr; - int id = -1; - ParseInt32(env, id, argv[PARAM0]); if (NapiSppClient::clientMap[id] != nullptr) { client = NapiSppClient::clientMap[id]; @@ -304,8 +306,7 @@ napi_value NapiSppServer::SppCloseServerSocket(napi_env env, napi_callback_info HILOGE("no such key in serverMap."); } - napi_get_boolean(env, isOK, &ret); - return ret; + return NapiGetBooleanRet(env, isOK); } } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/napi_bluetooth_utils.cpp b/frameworks/js/napi/src/napi_bluetooth_utils.cpp index ba173834..2e49ac25 100644 --- a/frameworks/js/napi/src/napi_bluetooth_utils.cpp +++ b/frameworks/js/napi/src/napi_bluetooth_utils.cpp @@ -14,13 +14,17 @@ */ #include "napi_bluetooth_utils.h" +#include #include #include +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "bluetooth_utils.h" #include "napi/native_api.h" #include "napi/native_node_api.h" +#include "napi_bluetooth_error.h" #include "napi_bluetooth_spp_client.h" +#include "parser/napi_parser_utils.h" #include "securec.h" namespace OHOS { @@ -121,21 +125,22 @@ bool ParseArrayBuffer(napi_env env, uint8_t** data, size_t &size, napi_value arg return true; } -void ConvertStringVectorToJS(napi_env env, napi_value result, std::vector& stringVector) +napi_status ConvertStringVectorToJS(napi_env env, napi_value result, std::vector& stringVector) { HILOGI("vector size: %{public}zu", stringVector.size()); size_t idx = 0; if (stringVector.empty()) { - return; + return napi_ok; } for (auto& str : stringVector) { napi_value obj = nullptr; - napi_create_string_utf8(env, str.c_str(), NAPI_AUTO_LENGTH, &obj); - napi_set_element(env, result, idx, obj); + NAPI_BT_CALL_RETURN(napi_create_string_utf8(env, str.c_str(), NAPI_AUTO_LENGTH, &obj)); + NAPI_BT_CALL_RETURN(napi_set_element(env, result, idx, obj)); idx++; } + return napi_ok; } void ConvertGattServiceVectorToJS(napi_env env, napi_value result, vector& services) @@ -578,19 +583,17 @@ GattService* GetServiceFromJS(napi_env env, napi_value object, std::shared_ptr characteristics; - bool ret = GetCharacteristicVectorFromJS(env, value, characteristics, server, client); - if (!ret) { - HILOGI("GetCharacteristicVectorFromJS faild"); - return nullptr; - } - for (auto& characteristic : characteristics) { - service->AddCharacteristic(characteristic); + if (hasProperty) { + napi_get_property(env, object, propertyNameValue, &value); + vector characteristics; + bool ret = GetCharacteristicVectorFromJS(env, value, characteristics, server, client); + if (!ret) { + HILOGI("GetCharacteristicVectorFromJS faild"); + return nullptr; + } + for (auto& characteristic : characteristics) { + service->AddCharacteristic(characteristic); + } } napi_create_string_utf8(env, "includeServices", NAPI_AUTO_LENGTH, &propertyNameValue); @@ -598,8 +601,8 @@ GattService* GetServiceFromJS(napi_env env, napi_value object, std::shared_ptr services; - bool ret = GetServiceVectorFromJS(env, value, services, server, client); - if (!ret) { + bool res = GetServiceVectorFromJS(env, value, services, server, client); + if (!res) { HILOGI("GetServiceVectorFromJS faild"); return nullptr; } @@ -640,7 +643,7 @@ bool GetCharacteristicVectorFromJS(napi_env env, napi_value object, vector &outpCallbackInfo) +{ + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); + std::string type; + bool ok = ParseString(env, type, argv[PARAM0]); + if (!ok) { + return napi_invalid_arg; + } + napi_valuetype valueType = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, argv[PARAM1], &valueType)); + NAPI_BT_RETURN_IF(valueType != napi_function, "Requires a function argument", napi_function_expected); + NAPI_BT_CALL_RETURN(napi_create_reference(env, argv[PARAM1], 1, &outpCallbackInfo->callback_)); + + outType = type; + outpCallbackInfo->env_ = env; + return napi_ok; +} + napi_value RegisterObserver(napi_env env, napi_callback_info info) { HILOGI("enter"); @@ -796,15 +825,10 @@ napi_value RegisterObserver(napi_env env, napi_callback_info info) if (argc == expectedArgsCount + 1) { NapiSppClient::On(env, info); } else { - NAPI_ASSERT(env, argc == expectedArgsCount, "Requires 2 arguments."); std::string type; - ParseString(env, type, argv[PARAM0]); std::shared_ptr pCallbackInfo = std::make_shared(); - pCallbackInfo->env_ = env; - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - NAPI_ASSERT(env, valueType == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[PARAM1], 1, &pCallbackInfo->callback_); + auto status = CheckObserverParams(env, argc, argv, type, pCallbackInfo); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); std::lock_guard lock(g_observerMutex); g_Observer[type] = pCallbackInfo; HILOGI("%{public}s is registered", type.c_str()); @@ -829,7 +853,7 @@ static std::map registerTypeMap = { {REGISTER_DEVICE_FIND_TYPE, BLUETOOTH_DEVICE_FIND_TYPE}, {REGISTER_STATE_CHANGE_TYPE, STATE_CHANGE_TYPE}, {REGISTER_PIN_REQUEST_TYPE, PIN_REQUEST_TYPE}, - {REGISTER_BONE_STATE_TYPE, BOND_STATE_CHANGE_TYPE}, + {REGISTER_BOND_STATE_TYPE, BOND_STATE_CHANGE_TYPE}, {REGISTER_BLE_FIND_DEVICE_TYPE, BLE_DEVICE_FIND_TYPE} }; @@ -879,47 +903,9 @@ napi_value CallbackObserver(int32_t typeNum, std::shared_ptr pCallbackInfo = std::make_shared(); - pCallbackInfo->env_ = env; - napi_valuetype valueType = napi_undefined; - napi_typeof(env, argv[PARAM1], &valueType); - NAPI_ASSERT(env, valueType == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[PARAM1], 1, &pCallbackInfo->callback_); - if (pCallbackInfo != nullptr) { - napi_value callback = 0; - napi_value undefined = 0; - napi_value callResult = 0; - napi_get_undefined(pCallbackInfo->env_, &undefined); - int32_t typeNum = 0; - if (registerTypeMap.find(type) != registerTypeMap.end()) { - typeNum = registerTypeMap[type]; - } - napi_value result = CallbackObserver(typeNum, pCallbackInfo); - napi_get_reference_value(pCallbackInfo->env_, pCallbackInfo->callback_, &callback); - napi_call_function(pCallbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); - } - - RemoveObserver(type); - } - napi_value ret = nullptr; - napi_get_undefined(env, &ret); - return ret; + auto status = CheckDeregisterObserver(env, info); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + return NapiGetUndefinedRet(env); } std::map> GetObserver() @@ -1235,7 +1221,7 @@ bool GetCurrentAppOperate() void RegisterSysBLEObserver( const std::shared_ptr &info, int32_t callbackIndex, const std::string &type) { - if (callbackIndex >= ARGS_SIZE_THREE) { + if (callbackIndex >= static_cast(ARGS_SIZE_THREE)) { return; } std::lock_guard lock(g_sysBLEObserverMutex); @@ -1251,5 +1237,331 @@ void UnregisterSysBLEObserver(const std::string &type) g_sysBLEObserver.erase(itor); } } + +bool IsValidAddress(std::string bdaddr) +{ + const std::regex deviceIdRegex("^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$"); + return regex_match(bdaddr, deviceIdRegex); +} + +bool IsValidUuid(std::string uuid) +{ + return regex_match(uuid, uuidRegex); +} + +napi_status NapiIsBoolean(napi_env env, napi_value value) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, value, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_boolean, "Wrong argument type. Boolean expected.", napi_boolean_expected); + return napi_ok; +} + +napi_status NapiIsNumber(napi_env env, napi_value value) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, value, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_number, "Wrong argument type. Number expected.", napi_number_expected); + return napi_ok; +} + +napi_status NapiIsString(napi_env env, napi_value value) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, value, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_string, "Wrong argument type. String expected.", napi_string_expected); + return napi_ok; +} + +napi_status NapiIsFunction(napi_env env, napi_value value) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, value, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_function, "Wrong argument type. Function expected.", napi_function_expected); + return napi_ok; +} + +napi_status NapiIsArrayBuffer(napi_env env, napi_value value) +{ + bool isArrayBuffer = false; + NAPI_BT_CALL_RETURN(napi_is_arraybuffer(env, value, &isArrayBuffer)); + NAPI_BT_RETURN_IF(!isArrayBuffer, "Expected arraybuffer type", napi_arraybuffer_expected); + return napi_ok; +} + +napi_status NapiIsArray(napi_env env, napi_value value) +{ + bool isArray = false; + NAPI_BT_CALL_RETURN(napi_is_array(env, value, &isArray)); + NAPI_BT_RETURN_IF(!isArray, "Expected array type", napi_array_expected); + return napi_ok; +} + +napi_status NapiIsObject(napi_env env, napi_value value) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_BT_CALL_RETURN(napi_typeof(env, value, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_object, "Wrong argument type. Object expected.", napi_object_expected); + return napi_ok; +} + +napi_status ParseNumberParams(napi_env env, napi_value object, const char *name, bool &outExist, + napi_value &outParam) +{ + bool hasProperty = false; + NAPI_BT_CALL_RETURN(napi_has_named_property(env, object, name, &hasProperty)); + if (hasProperty) { + napi_value property; + NAPI_BT_CALL_RETURN(napi_get_named_property(env, object, name, &property)); + napi_valuetype valuetype; + NAPI_BT_CALL_RETURN(napi_typeof(env, property, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_number, "Wrong argument type, number expected", napi_number_expected); + outParam = property; + } + outExist = hasProperty; + return napi_ok; +} + +napi_status ParseInt32Params(napi_env env, napi_value object, const char *name, bool &outExist, + int32_t &outParam) +{ + bool exist = false; + napi_value param; + NAPI_BT_CALL_RETURN(ParseNumberParams(env, object, name, exist, param)); + if (exist) { + int32_t num = 0; + NAPI_BT_CALL_RETURN(napi_get_value_int32(env, param, &num)); + outParam = num; + } + outExist = exist; + return napi_ok; +} + +napi_status ParseUint32Params(napi_env env, napi_value object, const char *name, bool &outExist, + uint32_t &outParam) +{ + bool exist = false; + napi_value param; + NAPI_BT_CALL_RETURN(ParseNumberParams(env, object, name, exist, param)); + if (exist) { + uint32_t num = 0; + NAPI_BT_CALL_RETURN(napi_get_value_uint32(env, param, &num)); + outParam = num; + } + outExist = exist; + return napi_ok; +} + +napi_status ParseBooleanParams(napi_env env, napi_value object, const char *name, bool &outExist, bool &outParam) +{ + bool hasProperty = false; + NAPI_BT_CALL_RETURN(napi_has_named_property(env, object, name, &hasProperty)); + if (hasProperty) { + napi_value property; + NAPI_BT_CALL_RETURN(napi_get_named_property(env, object, name, &property)); + napi_valuetype valuetype; + NAPI_BT_CALL_RETURN(napi_typeof(env, property, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_boolean, "Wrong argument type, boolean expected", napi_boolean_expected); + + bool param = false; + NAPI_BT_CALL_RETURN(napi_get_value_bool(env, property, ¶m)); + outParam = param; + } + outExist = hasProperty; + return napi_ok; +} + +// Only used for optional paramters +napi_status ParseStringParams(napi_env env, napi_value object, const char *name, bool &outExist, + std::string &outParam) +{ + bool hasProperty = false; + NAPI_BT_CALL_RETURN(napi_has_named_property(env, object, name, &hasProperty)); + if (hasProperty) { + napi_value property; + NAPI_BT_CALL_RETURN(napi_get_named_property(env, object, name, &property)); + napi_valuetype valuetype; + NAPI_BT_CALL_RETURN(napi_typeof(env, property, &valuetype)); + NAPI_BT_RETURN_IF(valuetype != napi_string, "Wrong argument type, string expected", napi_string_expected); + + std::string param {}; + bool isSuccess = ParseString(env, param, property); + if (!isSuccess) { + return napi_invalid_arg; + } + outParam = std::move(param); + } + outExist = hasProperty; + return napi_ok; +} + +napi_status ParseArrayBufferParams(napi_env env, napi_value object, const char *name, bool &outExist, + std::vector &outParam) +{ + bool hasProperty = false; + NAPI_BT_CALL_RETURN(napi_has_named_property(env, object, name, &hasProperty)); + if (hasProperty) { + napi_value property; + NAPI_BT_CALL_RETURN(napi_get_named_property(env, object, name, &property)); + bool isArrayBuffer = false; + NAPI_BT_CALL_RETURN(napi_is_arraybuffer(env, property, &isArrayBuffer)); + NAPI_BT_RETURN_IF(!isArrayBuffer, "Wrong argument type, arraybuffer expected", napi_arraybuffer_expected); + + uint8_t *data = nullptr; + size_t size = 0; + bool isSuccess = ParseArrayBuffer(env, &data, size, property); + if (!isSuccess) { + HILOGE("ParseArrayBuffer faild."); + return napi_invalid_arg; + } + outParam = std::vector(data, data + size); + } + outExist = hasProperty; + return napi_ok; +} + +napi_status ParseUuidParams(napi_env env, napi_value object, const char *name, bool &outExist, UUID &outUuid) +{ + bool exist = false; + std::string uuid {}; + NAPI_BT_CALL_RETURN(ParseStringParams(env, object, name, exist, uuid)); + if (exist) { + if (!regex_match(uuid, uuidRegex)) { + HILOGE("match the UUID faild."); + return napi_invalid_arg; + } + outUuid = ParcelUuid::FromString(uuid); + } + outExist = exist; + return napi_ok; +} + +// This function applies to interfaces with a single address as a parameter. +bool CheckDeivceIdParam(napi_env env, napi_callback_info info, std::string &addr) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + NAPI_BT_RETURN_IF(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok, "call failed.", false); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Wrong argument type", false); + NAPI_BT_RETURN_IF(!ParseString(env, addr, argv[PARAM0]), "ParseString failed", false); + NAPI_BT_RETURN_IF(!IsValidAddress(addr), "Invalid addr", false); + return true; +} + +bool CheckProfileIdParam(napi_env env, napi_callback_info info, int &profileId) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_BT_RETURN_IF(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr) != napi_ok, "call failed.", false); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Wrong argument type", false); + NAPI_BT_RETURN_IF(!ParseInt32(env, profileId, argv[PARAM0]), "ParseInt32 failed", false); + return true; +} + +bool CheckSetDevicePairingConfirmationParam(napi_env env, napi_callback_info info, std::string &addr, bool &accept) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_BT_RETURN_IF(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr) != napi_ok, "call failed.", false); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Wrong argument type", false); + NAPI_BT_RETURN_IF(!ParseString(env, addr, argv[PARAM0]), "ParseString failed", false); + NAPI_BT_RETURN_IF(!IsValidAddress(addr), "Invalid addr", false); + NAPI_BT_RETURN_IF(!ParseBool(env, accept, argv[PARAM1]), "ParseBool failed", false); + return true; +} + +bool CheckLocalNameParam(napi_env env, napi_callback_info info, std::string &name) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {nullptr}; + NAPI_BT_RETURN_IF(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr) != napi_ok, "call failed.", false); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Wrong argument type", false); + NAPI_BT_RETURN_IF(!ParseString(env, name, argv[PARAM0]), "ParseString failed", false); + return true; +} + +bool CheckSetBluetoothScanModeParam(napi_env env, napi_callback_info info, int32_t &mode, int32_t &duration) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_BT_RETURN_IF(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr) != napi_ok, "call failed.", false); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Wrong argument type", false); + NAPI_BT_RETURN_IF(!ParseInt32(env, mode, argv[PARAM0]), "ParseInt32 failed", false); + NAPI_BT_RETURN_IF(!ParseInt32(env, duration, argv[PARAM1]), "ParseInt32 failed", false); + return true; +} + +napi_status CheckDeregisterObserver(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_TWO; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_TWO] = {0}; + napi_value thisVar = nullptr; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + if (argc == ARGS_SIZE_ONE) { + std::string type; + NAPI_BT_CALL_RETURN(NapiParseString(env, argv[PARAM0], type)); + RemoveObserver(type); + } else if (argc == expectedArgsCount + 1) { + NapiSppClient::Off(env, info); + } else { + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_TWO, "Requires 2 arguments.", napi_invalid_arg); + std::string type; + NAPI_BT_CALL_RETURN(NapiParseString(env, argv[PARAM0], type)); + + std::shared_ptr pCallbackInfo = std::make_shared(); + pCallbackInfo->env_ = env; + NAPI_BT_RETURN_IF(pCallbackInfo == nullptr, "pCallbackInfo is nullptr.", napi_invalid_arg); + NAPI_BT_CALL_RETURN(NapiIsFunction(env, argv[PARAM1])); + NAPI_BT_CALL_RETURN(napi_create_reference(env, argv[PARAM1], 1, &pCallbackInfo->callback_)); + if (pCallbackInfo != nullptr) { + napi_value callback = 0; + napi_value undefined = 0; + napi_value callResult = 0; + napi_get_undefined(pCallbackInfo->env_, &undefined); + int32_t typeNum = 0; + if (registerTypeMap.find(type) != registerTypeMap.end()) { + typeNum = registerTypeMap[type]; + } + napi_value result = CallbackObserver(typeNum, pCallbackInfo); + napi_get_reference_value(pCallbackInfo->env_, pCallbackInfo->callback_, &callback); + napi_call_function(pCallbackInfo->env_, undefined, callback, ARGS_SIZE_ONE, &result, &callResult); + } + RemoveObserver(type); + } + return napi_ok; +} + +napi_status CheckEmptyParam(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ZERO, "Requires 0 argument.", napi_invalid_arg); + return napi_ok; +} + +napi_status NapiCheckObjectPropertiesName(napi_env env, napi_value object, const std::vector &names) +{ + uint32_t len = 0; + napi_value properties; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(napi_get_property_names(env, object, &properties)); + NAPI_BT_CALL_RETURN(napi_get_array_length(env, properties, &len)); + for (uint32_t i = 0; i < len; ++i) { + std::string name {}; + napi_value actualName; + NAPI_BT_CALL_RETURN(napi_get_element(env, properties, i, &actualName)); + NAPI_BT_CALL_RETURN(NapiParseString(env, actualName, name)); + if (std::find(names.begin(), names.end(), name) == names.end()) { + HILOGE("Unexpect object property name: \"%{public}s\"", name.c_str()); + return napi_invalid_arg; + } + } + return napi_ok; +} + } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/js/napi/src/native_module.cpp b/frameworks/js/napi/src/native_module.cpp index 402eade2..58f1c4d6 100644 --- a/frameworks/js/napi/src/native_module.cpp +++ b/frameworks/js/napi/src/native_module.cpp @@ -79,7 +79,11 @@ static napi_module bluetoothModule = {.nm_version = 1, .nm_flags = 0, .nm_filename = NULL, .nm_register_func = Init, +#ifdef ENABLE_NAPI_BLUETOOTH_MANAGER + .nm_modname = "bluetoothMananger", +#else .nm_modname = "bluetooth", +#endif .nm_priv = ((void *)0), .reserved = {0}}; /* @@ -87,6 +91,7 @@ static napi_module bluetoothModule = {.nm_version = 1, */ extern "C" __attribute__((constructor)) void RegisterModule(void) { + HILOGI("Register bluetoothModule nm_modname:%{public}s", bluetoothModule.nm_modname); napi_module_register(&bluetoothModule); } } // namespace Bluetooth diff --git a/frameworks/js/napi/src/parser/napi_parser_utils.cpp b/frameworks/js/napi/src/parser/napi_parser_utils.cpp new file mode 100644 index 00000000..d0364bbe --- /dev/null +++ b/frameworks/js/napi/src/parser/napi_parser_utils.cpp @@ -0,0 +1,497 @@ +/* + * Copyright (C) 2022 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 "napi_parser_utils.h" + +#include +#include + +namespace OHOS { +namespace Bluetooth { + +// shall check object type is napi_object before, if it's other type, return false +// If the 'name' field is not exist, or napi function call error, return false +static bool NapiIsObjectPropertyExist(napi_env env, napi_value object, const char *name) +{ + auto status = NapiIsObject(env, object); + if (status != napi_ok) { + HILOGE("expect object"); + return false; + } + bool exist = false; + status = napi_has_named_property(env, object, name, &exist); + if (status != napi_ok) { + HILOGE("Get object property failed, name: %{public}s", name); + return false; + } + return exist; +} + +napi_status NapiParseGattService(napi_env env, napi_value object, NapiGattService &outService) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"serviceUuid", "isPrimary", "characteristics", + "includeServices"})); + + std::string uuid {}; + bool isPrimary = true; + std::vector characteristics {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "serviceUuid", uuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectBoolean(env, object, "isPrimary", isPrimary)); + NAPI_BT_CALL_RETURN(NapiParseObjectArray(env, object, "characteristics", characteristics)); + if (NapiIsObjectPropertyExist(env, object, "includeServices")) { + std::vector includeServices {}; + NAPI_BT_CALL_RETURN(NapiParseObjectArray(env, object, "includeServices", includeServices)); + outService.includeServices = std::move(includeServices); + } + outService.serviceUuid = UUID::FromString(uuid); + outService.isPrimary = isPrimary; + outService.characteristics = std::move(characteristics); + return napi_ok; +} + +napi_status NapiParseGattCharacteristic(napi_env env, napi_value object, NapiBleCharacteristic &outCharacteristic) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"serviceUuid", "characteristicUuid", + "characteristicValue", "descriptors"})); + + std::string serviceUuid {}; + std::string characterUuid {}; + std::vector characterValue {}; + std::vector descriptors {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "serviceUuid", serviceUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "characteristicUuid", characterUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectArrayBuffer(env, object, "characteristicValue", characterValue)); + NAPI_BT_CALL_RETURN(NapiParseObjectArray(env, object, "descriptors", descriptors)); + + outCharacteristic.serviceUuid = UUID::FromString(serviceUuid); + outCharacteristic.characteristicUuid = UUID::FromString(characterUuid); + outCharacteristic.characteristicValue = std::move(characterValue); + outCharacteristic.descriptors = std::move(descriptors); + return napi_ok; +} + +napi_status NapiParseGattDescriptor(napi_env env, napi_value object, NapiBleDescriptor &outDescriptor) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"serviceUuid", "characteristicUuid", + "descriptorUuid", "descriptorValue"})); + + std::string serviceUuid {}; + std::string characterUuid {}; + std::string descriptorUuid {}; + std::vector descriptorValue {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "serviceUuid", serviceUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "characteristicUuid", characterUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "descriptorUuid", descriptorUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectArrayBuffer(env, object, "descriptorValue", descriptorValue)); + + outDescriptor.serviceUuid = UUID::FromString(serviceUuid); + outDescriptor.characteristicUuid = UUID::FromString(characterUuid); + outDescriptor.descriptorUuid = UUID::FromString(descriptorUuid); + outDescriptor.descriptorValue = std::move(descriptorValue); + return napi_ok; +} + +napi_status NapiParseNotifyCharacteristic(napi_env env, napi_value object, NapiNotifyCharacteristic &outCharacter) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"serviceUuid", "characteristicUuid", + "characteristicValue", "confirm"})); + + std::string serviceUuid {}; + std::string characterUuid {}; + std::vector characterValue {}; + bool confirm = false; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "serviceUuid", serviceUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "characteristicUuid", characterUuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectArrayBuffer(env, object, "characteristicValue", characterValue)); + NAPI_BT_CALL_RETURN(NapiParseObjectBoolean(env, object, "confirm", confirm)); + + outCharacter.serviceUuid = UUID::FromString(serviceUuid); + outCharacter.characterUuid = UUID::FromString(characterUuid); + outCharacter.characterValue = std::move(characterValue); + outCharacter.confirm = confirm; + return napi_ok; +} + +napi_status NapiParseGattsServerResponse(napi_env env, napi_value object, NapiGattsServerResponse &rsp) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"deviceId", "transId", "status", "offset", + "value"})); + + std::string deviceId {}; + int transId = 0; + int status = 0; + int offset = 0; + std::vector value {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectBdAddr(env, object, "deviceId", deviceId)); + NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, object, "transId", transId)); + NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, object, "status", status)); + NAPI_BT_CALL_RETURN(NapiParseObjectInt32(env, object, "offset", offset)); + NAPI_BT_CALL_RETURN(NapiParseObjectArrayBuffer(env, object, "value", value)); + + rsp.deviceId = deviceId; + rsp.transId = transId; + rsp.status = status; + rsp.offset = offset; + rsp.value = std::move(value); + return napi_ok; +} + +napi_status NapiParseBoolean(napi_env env, napi_value value, bool &outBoolean) +{ + bool boolean = false; + NAPI_BT_CALL_RETURN(NapiIsBoolean(env, value)); + NAPI_BT_CALL_RETURN(napi_get_value_bool(env, value, &boolean)); + outBoolean = boolean; + return napi_ok; +} + +napi_status NapiParseInt32(napi_env env, napi_value value, int32_t &outNum) +{ + int32_t num = 0; + NAPI_BT_CALL_RETURN(NapiIsNumber(env, value)); + NAPI_BT_CALL_RETURN(napi_get_value_int32(env, value, &num)); + outNum = num; + return napi_ok; +} + +napi_status NapiParseUint32(napi_env env, napi_value value, uint32_t &outNum) +{ + uint32_t num = 0; + NAPI_BT_CALL_RETURN(NapiIsNumber(env, value)); + NAPI_BT_CALL_RETURN(napi_get_value_uint32(env, value, &num)); + outNum = num; + return napi_ok; +} + +napi_status NapiParseString(napi_env env, napi_value value, std::string &outStr) +{ + std::string str {}; + NAPI_BT_CALL_RETURN(NapiIsString(env, value)); + NAPI_BT_RETURN_IF(!ParseString(env, str, value), "parse string failed", napi_invalid_arg); + outStr = std::move(str); + return napi_ok; +} + +napi_status NapiParseBdAddr(napi_env env, napi_value value, std::string &outAddr) +{ + std::string bdaddr {}; + NAPI_BT_CALL_RETURN(NapiParseString(env, value, bdaddr)); + NAPI_BT_RETURN_IF(!IsValidAddress(bdaddr), "Invalid bdaddr", napi_invalid_arg); + outAddr = std::move(bdaddr); + return napi_ok; +} + +napi_status NapiParseUuid(napi_env env, napi_value value, std::string &outUuid) +{ + std::string uuid {}; + NAPI_BT_CALL_RETURN(NapiParseString(env, value, uuid)); + NAPI_BT_RETURN_IF(!IsValidUuid(uuid), "Invalid uuid", napi_invalid_arg); + outUuid = std::move(uuid); + return napi_ok; +} + +napi_status NapiParseArrayBuffer(napi_env env, napi_value value, std::vector &outVec) +{ + uint8_t *data = nullptr; + size_t size = 0; + NAPI_BT_CALL_RETURN(NapiIsArrayBuffer(env, value)); + bool isSuccess = ParseArrayBuffer(env, &data, size, value); + if (!isSuccess) { + HILOGE("Parse arraybuffer failed"); + return napi_invalid_arg; + } + std::vector vec(data, data + size); + outVec = std::move(vec); + return napi_ok; +} + +static napi_status NapiGetObjectProperty(napi_env env, napi_value object, const char *name, napi_value &outProperty, + bool &outExist) +{ + bool exist = false; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(napi_has_named_property(env, object, name, &exist)); + if (exist) { + napi_value property; + NAPI_BT_CALL_RETURN(napi_get_named_property(env, object, name, &property)); + outProperty = property; + } + outExist = exist; + return napi_ok; +} +napi_status NapiGetObjectProperty(napi_env env, napi_value object, const char *name, napi_value &outProperty) +{ + bool exist = false; + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, outProperty, exist)); + NAPI_BT_RETURN_IF(!exist, "no needed property", napi_invalid_arg); + return napi_ok; +} +napi_status NapiGetObjectPropertyOptional(napi_env env, napi_value object, const char *name, napi_value &outProperty, + bool &outExist) +{ + return NapiGetObjectProperty(env, object, name, outProperty, outExist); +} + +napi_status NapiParseObjectBoolean(napi_env env, napi_value object, const char *name, bool &outBoolean) +{ + napi_value property; + bool boolean = true; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseBoolean(env, property, boolean)); + outBoolean = boolean; + return napi_ok; +} + +napi_status NapiParseObjectUuid(napi_env env, napi_value object, const char *name, std::string &outUuid) +{ + napi_value property; + std::string uuid {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseUuid(env, property, uuid)); + outUuid = std::move(uuid); + return napi_ok; +} + +napi_status NapiParseObjectArrayBuffer(napi_env env, napi_value object, const char *name, std::vector &outVec) +{ + napi_value property; + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseArrayBuffer(env, property, vec)); + outVec = std::move(vec); + return napi_ok; +} + +napi_status NapiParseObjectBdAddr(napi_env env, napi_value object, const char *name, std::string &outAddr) +{ + napi_value property; + std::string bdaddr {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseBdAddr(env, property, bdaddr)); + outAddr = std::move(bdaddr); + return napi_ok; +} + +napi_status NapiParseObjectInt32(napi_env env, napi_value object, const char *name, int32_t &outNum) +{ + napi_value property; + int32_t num = 0; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseInt32(env, property, num)); + outNum = num; + return napi_ok; +} + +napi_status NapiParseObjectUint32(napi_env env, napi_value object, const char *name, uint32_t &outNum) +{ + napi_value property; + uint32_t num = 0; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseUint32(env, property, num)); + outNum = num; + return napi_ok; +} + +napi_status NapiParseObjectBooleanOptional(napi_env env, napi_value object, const char *name, bool &outBoolean, + bool &outExist) +{ + napi_value property; + bool boolean = true; + bool exist = false; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectPropertyOptional(env, object, name, property, exist)); + if (exist) { + NAPI_BT_CALL_RETURN(NapiParseBoolean(env, property, boolean)); + outBoolean = boolean; + } + outExist = exist; + return napi_ok; +} +napi_status NapiParseObjectInt32Optional(napi_env env, napi_value object, const char *name, int32_t &outNum, + bool &outExist) +{ + napi_value property; + int32_t num = 0; + bool exist = false; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property, exist)); + if (exist) { + NAPI_BT_CALL_RETURN(NapiParseInt32(env, property, num)); + outNum = num; + } + outExist = exist; + return napi_ok; +} +napi_status NapiParseObjectUint32Optional(napi_env env, napi_value object, const char *name, uint32_t &outNum, + bool &outExist) +{ + napi_value property; + uint32_t num = 0; + bool exist = false; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property, exist)); + if (exist) { + NAPI_BT_CALL_RETURN(NapiParseUint32(env, property, num)); + outNum = num; + } + outExist = exist; + return napi_ok; +} + +// Parse params template, used for NapiParseArray +template +napi_status NapiParseObject(napi_env env, napi_value object, T &outObj) +{ + HILOGE("Unimpleted type"); + return napi_invalid_arg; +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, std::string &outObj) +{ + return NapiParseString(env, object, outObj); +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, UUID &outObj) +{ + std::string uuid {}; + NAPI_BT_CALL_RETURN(NapiParseUuid(env, object, uuid)); + outObj = UUID::FromString(uuid); + return napi_ok; +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, NapiAdvManufactureData &outObj) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"manufactureId", "manufactureValue"})); + uint32_t num = 0; + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectUint32(env, object, "manufactureId", num)); + NAPI_BT_RETURN_IF(num > 0xFFFF, "Invalid manufactureId", napi_invalid_arg); + NAPI_BT_CALL_RETURN(NapiParseObjectArrayBuffer(env, object, "manufactureValue", vec)); + + outObj.id = static_cast(num); + outObj.value = std::string(vec.begin(), vec.end()); + return napi_ok; +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, NapiAdvServiceData &outObj) +{ + NAPI_BT_CALL_RETURN(NapiCheckObjectPropertiesName(env, object, {"serviceUuid", "serviceValue"})); + std::string uuid {}; + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiIsObject(env, object)); + NAPI_BT_CALL_RETURN(NapiParseObjectUuid(env, object, "serviceUuid", uuid)); + NAPI_BT_CALL_RETURN(NapiParseObjectArrayBuffer(env, object, "serviceValue", vec)); + + outObj.uuid = std::move(uuid); + outObj.value = std::move(vec); + return napi_ok; +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, NapiGattService &outObj) +{ + return NapiParseGattService(env, object, outObj); +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, NapiBleCharacteristic &outObj) +{ + return NapiParseGattCharacteristic(env, object, outObj); +} + +template <> +napi_status NapiParseObject(napi_env env, napi_value object, NapiBleDescriptor &outObj) +{ + return NapiParseGattDescriptor(env, object, outObj); +} + +template +napi_status NapiParseArray(napi_env env, napi_value array, std::vector &outVec) +{ + std::vector vec {}; + + NAPI_BT_CALL_RETURN(NapiIsArray(env, array)); + uint32_t length = 0; + NAPI_BT_CALL_RETURN(napi_get_array_length(env, array, &length)); + for (uint32_t i = 0; i < length; ++i) { + napi_value element; + NAPI_BT_CALL_RETURN(napi_get_element(env, array, i, &element)); + T object; + NAPI_BT_CALL_RETURN(NapiParseObject(env, element, object)); + vec.push_back(std::move(object)); + } + outVec = std::move(vec); + return napi_ok; +} +// // Declaration, ohters will undefined synbol +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); +template napi_status NapiParseArray(napi_env env, napi_value array, + std::vector &outVec); + + +template +napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, std::vector &outVec) +{ + napi_value property; + std::vector vec {}; + NAPI_BT_CALL_RETURN(NapiGetObjectProperty(env, object, name, property)); + NAPI_BT_CALL_RETURN(NapiParseArray(env, property, vec)); + outVec = std::move(vec); + return napi_ok; +} +// Declaration, ohters will undefined synbol +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +template napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, + std::vector &outVec); +} // namespace Bluetooth +} // namespace OHOS diff --git a/frameworks/js/napi/src/parser/napi_parser_utils.h b/frameworks/js/napi/src/parser/napi_parser_utils.h new file mode 100644 index 00000000..c89137ea --- /dev/null +++ b/frameworks/js/napi/src/parser/napi_parser_utils.h @@ -0,0 +1,83 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_PARSER_UTILS_H +#define NAPI_PARSER_UTILS_H + +#include "napi_bluetooth_utils.h" + +namespace OHOS { +namespace Bluetooth { + +struct NapiBleDescriptor { + UUID serviceUuid; + UUID characteristicUuid; + UUID descriptorUuid; + std::vector descriptorValue; +}; + +struct NapiBleCharacteristic { + UUID serviceUuid; + UUID characteristicUuid; + std::vector characteristicValue; + std::vector descriptors; +}; + +struct NapiGattService { + UUID serviceUuid; + bool isPrimary; + std::vector characteristics; + std::vector includeServices; +}; + +napi_status NapiParseBoolean(napi_env env, napi_value value, bool &outBoolean); +napi_status NapiParseInt32(napi_env env, napi_value value, int32_t &outNum); +napi_status NapiParseUint32(napi_env env, napi_value value, uint32_t &outNum); +napi_status NapiParseString(napi_env env, napi_value value, std::string &outStr); +napi_status NapiParseBdAddr(napi_env env, napi_value value, std::string &outAddr); +napi_status NapiParseUuid(napi_env env, napi_value value, std::string &outUuid); +napi_status NapiParseArrayBuffer(napi_env env, napi_value value, std::vector &outVec); +napi_status NapiParseGattService(napi_env env, napi_value object, NapiGattService &outService); +napi_status NapiParseGattCharacteristic(napi_env env, napi_value object, NapiBleCharacteristic &outCharacteristic); +napi_status NapiParseGattDescriptor(napi_env env, napi_value object, NapiBleDescriptor &outDescriptor); +napi_status NapiParseNotifyCharacteristic(napi_env env, napi_value object, NapiNotifyCharacteristic &outCharacter); +napi_status NapiParseGattsServerResponse(napi_env env, napi_value object, NapiGattsServerResponse &rsp); + +// must have the 'name' property +napi_status NapiGetObjectProperty(napi_env env, napi_value object, const char *name, napi_value &outProperty); +napi_status NapiParseObjectBoolean(napi_env env, napi_value object, const char *name, bool &outBoolean); +napi_status NapiParseObjectUuid(napi_env env, napi_value object, const char *name, std::string &outUuid); +napi_status NapiParseObjectArrayBuffer(napi_env env, napi_value value, const char *name, std::vector &outVec); +napi_status NapiParseObjectBdAddr(napi_env env, napi_value object, const char *name, std::string &outAddr); +napi_status NapiParseObjectInt32(napi_env env, napi_value object, const char *name, int32_t &outNum); +napi_status NapiParseObjectUint32(napi_env env, napi_value object, const char *name, uint32_t &outNum); + +napi_status NapiGetObjectPropertyOptional(napi_env env, napi_value object, const char *name, napi_value &outProperty, + bool &outExist); +napi_status NapiParseObjectBooleanOptional(napi_env env, napi_value object, const char *name, bool &outBoolean, + bool &outExist); +napi_status NapiParseObjectInt32Optional(napi_env env, napi_value object, const char *name, int32_t &outNum, + bool &outExist); +napi_status NapiParseObjectUint32Optional(napi_env env, napi_value object, const char *name, uint32_t &outNum, + bool &outExist); + +// Parse type Array, must implete NapiParseObject in napi_parser_utils.cpp. +template +napi_status NapiParseArray(napi_env env, napi_value value, std::vector &outVec); +template +napi_status NapiParseObjectArray(napi_env env, napi_value object, const char *name, std::vector &outVec); +} // namespace Bluetooth +} // namespace OHOS +#endif // NAPI_PARSER_UTILS_H \ No newline at end of file diff --git a/interfaces/inner_api/include/bluetooth_a2dp_snk.h b/interfaces/inner_api/include/bluetooth_a2dp_snk.h index 7be25ab1..7d2bcf9c 100644 --- a/interfaces/inner_api/include/bluetooth_a2dp_snk.h +++ b/interfaces/inner_api/include/bluetooth_a2dp_snk.h @@ -102,6 +102,17 @@ public: */ int GetPlayingState(const BluetoothRemoteDevice &device) const; + /** + * @brief Get device playing state by address when peer device is on connected. + * + * @param device The address of the peer bluetooth device. + * @param state The playing state of the peer bluetooth device. + * @return Returns 1 if device is on playing; + * Returns 0 if device is not on playing. + * @since 6.0 + */ + int GetPlayingState(const BluetoothRemoteDevice &device, int &state) const; + /** * @brief Connect to the peer bluetooth device. * diff --git a/interfaces/inner_api/include/bluetooth_a2dp_src.h b/interfaces/inner_api/include/bluetooth_a2dp_src.h index 5bd49e67..68619f98 100644 --- a/interfaces/inner_api/include/bluetooth_a2dp_src.h +++ b/interfaces/inner_api/include/bluetooth_a2dp_src.h @@ -127,6 +127,16 @@ public: */ int GetPlayingState(const BluetoothRemoteDevice &device) const; + /** + * @brief Get device playing state by address when peer device is on connected. + * + * @param device The address of the peer bluetooth device. + * @param state The playing state of the peer bluetooth device. + * @return Returns operation result; + * @since 6.0 + */ + int GetPlayingState(const BluetoothRemoteDevice &device, int &state) const; + /** * @brief Connect to the peer bluetooth device. * @@ -136,7 +146,7 @@ public: or device is not allowed to connect,or the connection fails. * @since 6.0 */ - bool Connect(const BluetoothRemoteDevice &device); + int32_t Connect(const BluetoothRemoteDevice &device); /** * @brief Disconnect with the peer bluetooth service. @@ -146,7 +156,7 @@ public: * Returns false if target device is on disconnected,or disconnecting,or disconnection fails. * @since 6.0 */ - bool Disconnect(const BluetoothRemoteDevice &device); + int32_t Disconnect(const BluetoothRemoteDevice &device); /** * @brief Set target device as active device. diff --git a/interfaces/inner_api/include/bluetooth_ble_advertiser.h b/interfaces/inner_api/include/bluetooth_ble_advertiser.h index 43d0979a..d5ac6a7b 100644 --- a/interfaces/inner_api/include/bluetooth_ble_advertiser.h +++ b/interfaces/inner_api/include/bluetooth_ble_advertiser.h @@ -314,7 +314,7 @@ public: * @param callback Advertise callback. * @since 6 */ - void StartAdvertising(const BleAdvertiserSettings &settings, const BleAdvertiserData &advData, + int StartAdvertising(const BleAdvertiserSettings &settings, const BleAdvertiserData &advData, const BleAdvertiserData &scanResponse, BleAdvertiseCallback &callback); /** @@ -326,10 +326,10 @@ public: * @param callback Advertise callback. * @since 6 */ - void StartAdvertising(const BleAdvertiserSettings &settings, const std::vector &advData, + int StartAdvertising(const BleAdvertiserSettings &settings, const std::vector &advData, const std::vector &scanResponse, BleAdvertiseCallback &callback); - void StopAdvertising(BleAdvertiseCallback &callback); + int StopAdvertising(BleAdvertiseCallback &callback); /** * @brief Cleans up advertisers. diff --git a/interfaces/inner_api/include/bluetooth_ble_central_manager.h b/interfaces/inner_api/include/bluetooth_ble_central_manager.h index 5b3458be..86c95cf9 100644 --- a/interfaces/inner_api/include/bluetooth_ble_central_manager.h +++ b/interfaces/inner_api/include/bluetooth_ble_central_manager.h @@ -191,6 +191,8 @@ public: */ void SetAdvertiseFlag(uint8_t flag); + void SetName(const std::string &name); + std::string GetName(void); private: std::vector serviceUuids_ {}; @@ -201,6 +203,7 @@ private: bool connectable_ {}; uint8_t advertiseFlag_ {}; std::vector payload_ {}; + std::string name_ {}; }; /** * @brief Represents central manager callback. @@ -454,7 +457,7 @@ public: * * @since 6 */ - void StartScan(); + int StartScan(); /** * @brief Start scan. @@ -462,20 +465,20 @@ public: * @param settings Scan settings. * @since 6 */ - void StartScan(const BleScanSettings &settings); + int StartScan(const BleScanSettings &settings); /** * @brief Stop scan. * * @since 6 */ - void StopScan(); + int StopScan(); /** * @brief Config scan filter. * */ - void ConfigScanFilter(const std::vector &filter); + int ConfigScanFilter(const std::vector &filter); private: BleCentralManagerCallback *callback_ = nullptr; diff --git a/interfaces/inner_api/include/bluetooth_def.h b/interfaces/inner_api/include/bluetooth_def.h index e5bcbd3d..ef8806c2 100644 --- a/interfaces/inner_api/include/bluetooth_def.h +++ b/interfaces/inner_api/include/bluetooth_def.h @@ -18,7 +18,7 @@ #include #include -#include +#include namespace OHOS { namespace Bluetooth { @@ -133,6 +133,7 @@ const uint32_t PROFILE_ID_DI = 0x00002000; const std::string INVALID_MAC_ADDRESS = "00:00:00:00:00:00"; const std::string INVALID_NAME = ""; const int INVALID_VALUE = 0; +const int INVALID_TYPE = -1; const int ADDRESS_LENGTH = 17; const int ADDRESS_COLON_INDEX = 2; const int ADDRESS_SEPARATOR_UNIT = 3; @@ -264,7 +265,7 @@ enum GattStatus { }; enum BtStatus{ - BT_SUCCESS = 0, + BT_SUCC = 0, BT_FAILURE = -1, }; diff --git a/interfaces/inner_api/include/bluetooth_errorcode.h b/interfaces/inner_api/include/bluetooth_errorcode.h new file mode 100644 index 00000000..644e652e --- /dev/null +++ b/interfaces/inner_api/include/bluetooth_errorcode.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022-2022 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 BLUETOOTH_ERRORCODE_H +#define BLUETOOTH_ERRORCODE_H + +namespace OHOS { +namespace Bluetooth { + +/* Bluetooth errcode defines */ +enum BtErrCode { + // Common error codes + BT_ERR_PERMISSION_FAILED = 201, + BT_ERR_SYSTEM_PERMISSION_FAILED = 202, + BT_ERR_INVALID_PARAM = 401, + BT_ERR_API_NOT_SUPPORT = 801, + + // Customized error codes + BT_SUCCESS = 0, + + BT_ERR_BASE_SYSCAP = 2900000, + BT_ERR_SERVICE_DISCONNECTED = BT_ERR_BASE_SYSCAP + 1, + BT_ERR_UNBONDED_DEVICE = BT_ERR_BASE_SYSCAP + 2, + BT_ERR_INVALID_STATE = BT_ERR_BASE_SYSCAP + 3, + BT_ERR_PROFILE_DISABLED = BT_ERR_BASE_SYSCAP + 4, + BT_ERR_DEVICE_DISCONNECTED = BT_ERR_BASE_SYSCAP + 5, + BT_ERR_MAX_CONNECTION = BT_ERR_BASE_SYSCAP + 6, + + BT_ERR_INTERNAL_ERROR = BT_ERR_BASE_SYSCAP + 99, + BT_ERR_IPC_TRANS_FAILED = BT_ERR_BASE_SYSCAP + 100, + + 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_SPP_SERVER_STATE = BT_ERR_BASE_SYSCAP + 1050, + BT_ERR_SPP_BUSY = BT_ERR_BASE_SYSCAP + 1051, + BT_ERR_SPP_DEVICE_NOT_FOUND = BT_ERR_BASE_SYSCAP + 1052, + BT_ERR_SPP_IO = BT_ERR_BASE_SYSCAP + 1054, + + // will deprected + NO_ERROR = BT_SUCCESS, + ERROR = BT_ERR_INTERNAL_ERROR, + ERR_INVALID_STATE = BT_ERR_INVALID_STATE, +}; +} // namespace Bluetooth +} // namespace OHOS + +#endif // BLUETOOTH_ERRORCODE_H \ No newline at end of file diff --git a/interfaces/inner_api/include/bluetooth_gatt_characteristic.h b/interfaces/inner_api/include/bluetooth_gatt_characteristic.h index 11f7906a..7d56dd36 100644 --- a/interfaces/inner_api/include/bluetooth_gatt_characteristic.h +++ b/interfaces/inner_api/include/bluetooth_gatt_characteristic.h @@ -37,7 +37,7 @@ #define BLUETOOTH_GATT_CHARACTERISTIC_H #include -#include +#include #include "bluetooth_def.h" #include "bluetooth_gatt_descriptor.h" #include "cstdint" diff --git a/interfaces/inner_api/include/bluetooth_hfp_ag.h b/interfaces/inner_api/include/bluetooth_hfp_ag.h index 6dcd7e49..f24d47bf 100644 --- a/interfaces/inner_api/include/bluetooth_hfp_ag.h +++ b/interfaces/inner_api/include/bluetooth_hfp_ag.h @@ -121,7 +121,7 @@ public: * @return Returns the list of devices. * @since 6 */ - std::vector GetConnectedDevices() const; + int32_t GetConnectedDevices(std::vector& devices); /** * @brief Get remote HF device list which are in the specified states. @@ -139,7 +139,7 @@ public: * @return Returns the connection state of the remote device. * @since 6 */ - int GetDeviceState(const BluetoothRemoteDevice &device) const; + int32_t GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state); /** * @brief Initiate the establishment of a service level connection to remote HF device. @@ -148,7 +148,7 @@ public: * @return Returns true if the operation is successful; returns false if the operation fails. * @since 6 */ - bool Connect(const BluetoothRemoteDevice &device); + int32_t Connect(const BluetoothRemoteDevice &device); /** * @brief Release the audio connection from remote HF device. @@ -157,7 +157,7 @@ public: * @return Returns true if the operation is successful; returns false if the operation fails. * @since 6 */ - bool Disconnect(const BluetoothRemoteDevice &device); + int32_t Disconnect(const BluetoothRemoteDevice &device); /** * @brief Get the Audio connection state of the specified remote HF device. @@ -269,6 +269,14 @@ public: */ void DeregisterObserver(HandsFreeAudioGatewayObserver *observer); + /** + * @brief Get remote HF device list which are in the connected state. + * + * @return Returns the list of devices. + * @since 6 + */ + std::vector GetConnectedDevices() const; + /** * @brief Static HandsFree AudioGateway observer instance. * diff --git a/interfaces/inner_api/include/bluetooth_hid_host.h b/interfaces/inner_api/include/bluetooth_hid_host.h index d9e3055d..bb6e0a7a 100644 --- a/interfaces/inner_api/include/bluetooth_hid_host.h +++ b/interfaces/inner_api/include/bluetooth_hid_host.h @@ -82,7 +82,7 @@ public: * @param states List of remote device states. * @return Returns the list of devices. */ - std::vector GetDevicesByStates(std::vector states); + int32_t GetDevicesByStates(std::vector states, std::vector &result); /** * @brief Get the connection state of the specified remote Hid device. @@ -90,7 +90,7 @@ public: * @param device Remote device object. * @return Returns the connection state of the remote device. */ - int GetDeviceState(const BluetoothRemoteDevice &device); + int32_t GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state); /** * @brief Initiate the establishment of a service level connection to remote Hid device. @@ -98,7 +98,7 @@ public: * @param device Remote device object. * @return Returns true if the operation is successful; returns false if the operation fails. */ - bool Connect(const BluetoothRemoteDevice &device); + int32_t Connect(const BluetoothRemoteDevice &device); /** * @brief Release the connection from remote Hid device. @@ -106,7 +106,7 @@ public: * @param device Remote device object. * @return Returns true if the operation is successful; returns false if the operation fails. */ - bool Disconnect(const BluetoothRemoteDevice &device); + int32_t Disconnect(const BluetoothRemoteDevice &device); /** * @brief Register Hid Host observer instance. diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index a38f1407..fe4cb5bc 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -269,7 +269,7 @@ public: * returns false if the operation is rejected. * @since 6 */ - bool DisableBt(); + int DisableBt(); /** * @brief Get classic enable/disable state. @@ -283,6 +283,18 @@ public: */ int GetBtState() const; + /** + * @brief Get classic enable/disable state. + * + * @param Returns classic enable/disable state. + * BTStateID::STATE_TURNING_ON; + * BTStateID::STATE_TURN_ON; + * BTStateID::STATE_TURNING_OFF; + * BTStateID::STATE_TURN_OFF. + * @since 6 + */ + int GetBtState(int &state) const; + /** * @brief Disable ble. * @@ -290,7 +302,7 @@ public: * returns false if the operation is rejected. * @since 6 */ - bool DisableBle(); + int DisableBle(); /** * @brief Enable ble. @@ -299,7 +311,16 @@ public: * returns false if the operation is rejected. * @since 6 */ - bool EnableBle(); + int EnableBle(); + + /** + * @brief Get br/edr enable/disable state. + * + * @return Returns true if br is enabled; + * returns false if br is not enabled. + * @since 6 + */ + bool IsBrEnabled() const; /** * @brief Get ble enable/disable state. @@ -347,6 +368,18 @@ public: */ int GetBtConnectionState() const; + /** + * @brief Get bluetooth connects state. + * + * @return Returns bluetooth connects state. + * BTConnectState::CONNECTING; + * BTConnectState::CONNECTED; + * BTConnectState::DISCONNECTING; + * BTConnectState::DISCONNECTED. + * @since 6 + */ + int GetBtConnectionState(int &state) const; + /** * @brief Get profile service connect state. * @@ -358,7 +391,7 @@ public: * BTConnectState::DISCONNECTED. * @since 6 */ - int GetBtProfileConnState(uint32_t profileId) const; + int GetBtProfileConnState(uint32_t profileId, int &state) const; /** * @brief Get local device supported uuids. @@ -419,6 +452,14 @@ public: */ std::string GetLocalName() const; + /** + * @brief Get local device name. + * + * @return Returns local device name. + * @since 6 + */ + int GetLocalName(std::string &name) const; + /** * @brief Set local device name. * @@ -427,7 +468,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool SetLocalName(const std::string &name); + int SetLocalName(const std::string &name); /** * @brief Get device scan mode. @@ -435,7 +476,7 @@ public: * @return Returns bluetooth scan mode. * @since 6 */ - int GetBtScanMode() const; + int GetBtScanMode(int32_t &scanMode) const; /** * @brief Set device scan mode. @@ -446,7 +487,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool SetBtScanMode(int mode, int duration); + int SetBtScanMode(int mode, int duration); /** * @brief Get local device bondable mode. @@ -474,7 +515,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool StartBtDiscovery(); + int StartBtDiscovery(); /** * @brief Cancel device discovery. @@ -483,7 +524,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool CancelBtDiscovery(); + int CancelBtDiscovery(); /** * @brief Check if device is discovering. @@ -509,7 +550,7 @@ public: * @return Returns paired devices vector. * @since 6 */ - std::vector GetPairedDevices(int transport) const; + int32_t GetPairedDevices(int transport, std::vector &pairedDevices) const; /** * @brief Remove pair. @@ -519,7 +560,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool RemovePair(const BluetoothRemoteDevice &device); + int32_t RemovePair(const BluetoothRemoteDevice &device); /** * @brief Remove all pairs. @@ -548,7 +589,7 @@ public: * returns false if the operation fails. * @since 6 */ - void RegisterRemoteDeviceObserver(BluetoothRemoteDeviceObserver &observer); + void RegisterRemoteDeviceObserver(std::shared_ptr observer); /** * @brief Deregister remote device observer. diff --git a/interfaces/inner_api/include/bluetooth_pan.h b/interfaces/inner_api/include/bluetooth_pan.h index ef191c31..dd3d94f3 100644 --- a/interfaces/inner_api/include/bluetooth_pan.h +++ b/interfaces/inner_api/include/bluetooth_pan.h @@ -82,7 +82,7 @@ public: * @param states List of remote device states. * @return Returns the list of devices. */ - std::vector GetDevicesByStates(std::vector states); + int32_t GetDevicesByStates(std::vector states, std::vector &result); /** * @brief Get the connection state of the specified remote Pan device. @@ -90,7 +90,7 @@ public: * @param device Remote device object. * @return Returns the connection state of the remote device. */ - int GetDeviceState(const BluetoothRemoteDevice &device); + int32_t GetDeviceState(const BluetoothRemoteDevice &device, int32_t &state); /** * @brief Release the connection from remote Pan device. @@ -98,7 +98,7 @@ public: * @param device Remote device object. * @return Returns true if the operation is successful; returns false if the operation fails. */ - bool Disconnect(const BluetoothRemoteDevice &device); + int32_t Disconnect(const BluetoothRemoteDevice &device); /** * @brief Register Pan observer instance. @@ -119,13 +119,13 @@ public: * * @param value Set Network Sharing. */ - bool SetTethering(bool value); + int32_t SetTethering(bool value); /** * @brief Is Tethering On. * */ - bool IsTetheringOn(); + int32_t IsTetheringOn(bool &value); /** * @brief Static Pan observer instance. diff --git a/interfaces/inner_api/include/bluetooth_remote_device.h b/interfaces/inner_api/include/bluetooth_remote_device.h index 4f1e8e19..e29d5271 100644 --- a/interfaces/inner_api/include/bluetooth_remote_device.h +++ b/interfaces/inner_api/include/bluetooth_remote_device.h @@ -129,6 +129,14 @@ public: */ std::string GetDeviceName() const; + /** + * @brief Get device name. + * + * @return Returns device name. + * @since 6 + */ + int GetDeviceName(std::string &name) const; + /** * @brief Get device alias. * @@ -178,7 +186,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool StartPair(); + int StartPair(); /** * @brief Cancel pair operation. @@ -222,7 +230,7 @@ public: * @return Returns device class; * @since 6 */ - BluetoothDeviceClass GetDeviceClass() const; + int GetDeviceClass(int &cod) const; /** * @brief Get device uuids. @@ -250,7 +258,7 @@ public: * returns false if the operation fails. * @since 6 */ - bool SetDevicePairingConfirmation(bool accept); + int SetDevicePairingConfirmation(bool accept); /** * @brief Set device pair passkey. diff --git a/interfaces/inner_api/include/bluetooth_utils.h b/interfaces/inner_api/include/bluetooth_utils.h index 130bbee1..958613c3 100644 --- a/interfaces/inner_api/include/bluetooth_utils.h +++ b/interfaces/inner_api/include/bluetooth_utils.h @@ -16,9 +16,19 @@ #ifndef BLUETOOTH_UTILS_H #define BLUETOOTH_UTILS_H -#include +#include #include +#include "bluetooth_errorcode.h" +#include "bluetooth_log.h" + +#define CHECK_PROXY_RETURN(proxy) do { \ + if ((proxy) == nullptr) { \ + HILOGE("proxy_ is nullptr"); \ + return BT_ERR_INTERNAL_ERROR; \ + } \ +} while (0) + namespace OHOS { namespace Bluetooth { static constexpr int GET_PROXY_SLEEP_SEC = 1; // 1s @@ -29,6 +39,7 @@ std::string GetEncryptAddr(std::string addr); std::string GetBtStateName(int state); std::string GetBtTransportName(int transport); std::string GetProfileConnStateName(int state); +std::string GetErrorCode(int32_t errCode); } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/c_header/ohos_bt_spp.h b/interfaces/inner_api/include/c_header/ohos_bt_spp.h index 7fb05530..9dbf01ea 100644 --- a/interfaces/inner_api/include/c_header/ohos_bt_spp.h +++ b/interfaces/inner_api/include/c_header/ohos_bt_spp.h @@ -19,6 +19,10 @@ #include #include "ohos_bt_def.h" +#ifdef __cplusplus +extern "C" { +#endif + #define BT_SPP_READ_SOCKET_CLOSED (0) #define BT_SPP_READ_FAILED (-1) #define BT_SPP_WRITE_FAILED (-1) @@ -121,10 +125,6 @@ int SppRead(int clientId, char *buf, const unsigned int bufLen); */ int SppWrite(int clientId, const char *data, const unsigned int len); -#ifdef __cplusplus -extern "C" { -#endif - #ifdef __cplusplus } #endif diff --git a/services/bluetooth/common/BUILD.gn b/services/bluetooth/common/BUILD.gn index 52b9c83d..2e5a4b0f 100644 --- a/services/bluetooth/common/BUILD.gn +++ b/services/bluetooth/common/BUILD.gn @@ -30,6 +30,7 @@ ohos_static_library("btcommon") { sources = [ "avrcp_media.cpp", + "ble_parcel_data.cpp", "ble_service_data.cpp", "bt_uuid.cpp", "gatt_data.cpp", diff --git a/services/bluetooth/common/ble_parcel_data.cpp b/services/bluetooth/common/ble_parcel_data.cpp new file mode 100644 index 00000000..34d4a892 --- /dev/null +++ b/services/bluetooth/common/ble_parcel_data.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022 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 "ble_parcel_data.h" + +namespace OHOS { +namespace bluetooth { + +ScanResult::ScanResult(const BleScanResultImpl &other) +{ + const auto &device = other.GetPeripheralDevice(); + if (device.IsRSSI()) { + this->SetRssi(device.GetRSSI()); + } + this->SetAdvertiseFlag(device.GetAdFlag()); + + if (device.IsManufacturerData()) { + auto manuData = device.GetManufacturerData(); + for (auto it = manuData.begin(); it != manuData.end(); it++) { + this->AddManufacturerData(it->first, it->second); + } + } + this->SetConnectable(device.IsConnectable()); + + if (device.IsServiceUUID()) { + auto uuids = device.GetServiceUUID(); + for (auto iter = uuids.begin(); iter != uuids.end(); iter++) { + this->AddServiceUuid(*iter); + } + } + + if (device.IsServiceData()) { + auto uuids = device.GetServiceDataUUID(); + int index = 0; + for (auto iter = uuids.begin(); iter != uuids.end(); iter++) { + this->AddServiceData(*iter, device.GetServiceData(index)); + ++index; + } + } + + if (device.IsName()) { + this->SetName(device.GetName()); + } + this->SetPeripheralDevice(device.GetRawAddress()); + this->SetPayload(std::string(device.GetPayload(), device.GetPayload() + device.GetPayloadLen())); +} + +} // namespace bluetooth +} // namespace OHOS \ No newline at end of file diff --git a/services/bluetooth/common/ble_parcel_data.h b/services/bluetooth/common/ble_parcel_data.h index cf2352a2..2257b7f5 100644 --- a/services/bluetooth/common/ble_parcel_data.h +++ b/services/bluetooth/common/ble_parcel_data.h @@ -37,6 +37,7 @@ #include #include +#include "ble_service_data.h" #include "bt_uuid.h" #include "raw_address.h" @@ -56,7 +57,7 @@ public: * * @since 6 */ - ~AdvertiserData(){}; + virtual ~AdvertiserData(){}; std::map GetManufacturerData() const { @@ -190,7 +191,7 @@ public: * * @since 6 */ - ~AdvertiserSettings(){}; + virtual ~AdvertiserSettings(){}; /** * @brief Check if device service is connectable. @@ -344,12 +345,14 @@ public: */ ScanResult(){}; + explicit ScanResult(const BleScanResultImpl &other); + /** * @brief A destructor used to delete the BleScanResult instance. * * @since 6 */ - ~ScanResult(){}; + virtual ~ScanResult(){}; /** * @brief Get service uuids. @@ -390,7 +393,7 @@ public: * @return Returns peripheral device pointer. * @since 6 */ - RawAddress &GetPeripheralDevice() + const RawAddress &GetPeripheralDevice() const { return addr_; } @@ -517,6 +520,16 @@ public: return payload_; } + void SetName(const std::string &name) + { + name_ = name; + } + + std::string GetName(void) const + { + return name_; + } + public: std::vector serviceUuids_ {}; std::map manufacturerSpecificData_ {}; @@ -526,6 +539,7 @@ public: bool connectable_ {}; uint8_t advertiseFlag_ {}; std::string payload_ {}; + std::string name_ {}; }; /** @@ -547,7 +561,7 @@ public: * * @since 6 */ - ~ScanSettings(){}; + virtual ~ScanSettings(){}; /** * @brief Set report delay time. @@ -661,7 +675,7 @@ public: * @brief A destructor used to delete the BleScanFilter instance. * */ - ~ScanFilter() {} + virtual ~ScanFilter() {} /** * @brief Set device id. @@ -699,7 +713,7 @@ public: hasServiceUuid_ = true; } - bool HasServiceUuid() + bool HasServiceUuid() const { return hasServiceUuid_; } @@ -715,7 +729,7 @@ public: hasServiceUuidMask_ = true; } - bool HasServiceUuidMask() + bool HasServiceUuidMask() const { return hasServiceUuidMask_; } diff --git a/services/bluetooth/common/ble_service_data.cpp b/services/bluetooth/common/ble_service_data.cpp index 0eaf40dc..c8a5af7c 100644 --- a/services/bluetooth/common/ble_service_data.cpp +++ b/services/bluetooth/common/ble_service_data.cpp @@ -900,6 +900,11 @@ bool BlePeripheralDevice::IsServiceUUID() const return isServiceUUID_; } +bool BlePeripheralDevice::IsName(void) const +{ + return isName_; +} + /** * @brief Set device address. * diff --git a/services/bluetooth/common/ble_service_data.h b/services/bluetooth/common/ble_service_data.h index 2f58f079..d2f9110f 100644 --- a/services/bluetooth/common/ble_service_data.h +++ b/services/bluetooth/common/ble_service_data.h @@ -730,6 +730,8 @@ public: */ bool IsServiceUUID() const; + bool IsName(void) const; + /** * @brief set device address. * diff --git a/services/bluetooth/common/bluetooth_errorcode.h b/services/bluetooth/common/bluetooth_errorcode.h new file mode 100644 index 00000000..644e652e --- /dev/null +++ b/services/bluetooth/common/bluetooth_errorcode.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022-2022 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 BLUETOOTH_ERRORCODE_H +#define BLUETOOTH_ERRORCODE_H + +namespace OHOS { +namespace Bluetooth { + +/* Bluetooth errcode defines */ +enum BtErrCode { + // Common error codes + BT_ERR_PERMISSION_FAILED = 201, + BT_ERR_SYSTEM_PERMISSION_FAILED = 202, + BT_ERR_INVALID_PARAM = 401, + BT_ERR_API_NOT_SUPPORT = 801, + + // Customized error codes + BT_SUCCESS = 0, + + BT_ERR_BASE_SYSCAP = 2900000, + BT_ERR_SERVICE_DISCONNECTED = BT_ERR_BASE_SYSCAP + 1, + BT_ERR_UNBONDED_DEVICE = BT_ERR_BASE_SYSCAP + 2, + BT_ERR_INVALID_STATE = BT_ERR_BASE_SYSCAP + 3, + BT_ERR_PROFILE_DISABLED = BT_ERR_BASE_SYSCAP + 4, + BT_ERR_DEVICE_DISCONNECTED = BT_ERR_BASE_SYSCAP + 5, + BT_ERR_MAX_CONNECTION = BT_ERR_BASE_SYSCAP + 6, + + BT_ERR_INTERNAL_ERROR = BT_ERR_BASE_SYSCAP + 99, + BT_ERR_IPC_TRANS_FAILED = BT_ERR_BASE_SYSCAP + 100, + + 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_SPP_SERVER_STATE = BT_ERR_BASE_SYSCAP + 1050, + BT_ERR_SPP_BUSY = BT_ERR_BASE_SYSCAP + 1051, + BT_ERR_SPP_DEVICE_NOT_FOUND = BT_ERR_BASE_SYSCAP + 1052, + BT_ERR_SPP_IO = BT_ERR_BASE_SYSCAP + 1054, + + // will deprected + NO_ERROR = BT_SUCCESS, + ERROR = BT_ERR_INTERNAL_ERROR, + ERR_INVALID_STATE = BT_ERR_INVALID_STATE, +}; +} // namespace Bluetooth +} // namespace OHOS + +#endif // BLUETOOTH_ERRORCODE_H \ No newline at end of file diff --git a/services/bluetooth/common/bt_def.h b/services/bluetooth/common/bt_def.h index b09a5795..579fdc73 100644 --- a/services/bluetooth/common/bt_def.h +++ b/services/bluetooth/common/bt_def.h @@ -138,6 +138,7 @@ const uint32_t PROFILE_ID_OPP = 0x00010000; const std::string INVALID_MAC_ADDRESS = "00:00:00:00:00:00"; const std::string INVALID_NAME = ""; const int INVALID_VALUE = 0; +const int INVALID_TYPE = -1; const int ADDRESS_LENGTH = 17; const int ADDRESS_COLON_INDEX = 2; const int ADDRESS_SEPARATOR_UNIT = 3; diff --git a/services/bluetooth/ipc/include/bluetooth_a2dp_sink_proxy.h b/services/bluetooth/ipc/include/bluetooth_a2dp_sink_proxy.h index 80c71912..33bcac79 100644 --- a/services/bluetooth/ipc/include/bluetooth_a2dp_sink_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_a2dp_sink_proxy.h @@ -36,7 +36,7 @@ public: void DeregisterObserver(const sptr &observer) override; std::vector GetDevicesByStates(const std::vector &states) override; int GetDeviceState(const RawAddress &device) override; - int GetPlayingState(const RawAddress &device) override; + int GetPlayingState(const RawAddress &device, int &state) override; int SetConnectStrategy(const RawAddress &device, int32_t strategy) override; int GetConnectStrategy(const RawAddress &device) override; int SendDelay(const RawAddress &device, int32_t delayValue) override; diff --git a/services/bluetooth/ipc/include/bluetooth_a2dp_src_proxy.h b/services/bluetooth/ipc/include/bluetooth_a2dp_src_proxy.h index 44438ed7..bb173736 100644 --- a/services/bluetooth/ipc/include/bluetooth_a2dp_src_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_a2dp_src_proxy.h @@ -36,7 +36,7 @@ public: void DeregisterObserver(const sptr &observer) override; std::vector GetDevicesByStates(const std::vector &states) override; int GetDeviceState(const RawAddress &device) override; - int GetPlayingState(const RawAddress &device) override; + int GetPlayingState(const RawAddress &device, int &state) override; int SetConnectStrategy(const RawAddress &device, int32_t strategy) override; int GetConnectStrategy(const RawAddress &device) override; int SetActiveSinkDevice(const RawAddress &device) override; diff --git a/services/bluetooth/ipc/include/bluetooth_ble_advertiser_proxy.h b/services/bluetooth/ipc/include/bluetooth_ble_advertiser_proxy.h index 4ae37872..66d980f6 100644 --- a/services/bluetooth/ipc/include/bluetooth_ble_advertiser_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_ble_advertiser_proxy.h @@ -30,9 +30,9 @@ public: void RegisterBleAdvertiserCallback(const sptr &callback) override; void DeregisterBleAdvertiserCallback(const sptr &callback) override; - void StartAdvertising(const BluetoothBleAdvertiserSettings &settings, const BluetoothBleAdvertiserData &advData, + int StartAdvertising(const BluetoothBleAdvertiserSettings &settings, const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle, bool isRawData) override; - void StopAdvertising(int32_t advHandle) override; + int StopAdvertising(int32_t advHandle) override; void Close(int32_t advHandle) override; int32_t GetAdvertiserHandle() override; diff --git a/services/bluetooth/ipc/include/bluetooth_ble_central_manager_proxy.h b/services/bluetooth/ipc/include/bluetooth_ble_central_manager_proxy.h index fb8ca2a4..dcf023a8 100644 --- a/services/bluetooth/ipc/include/bluetooth_ble_central_manager_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_ble_central_manager_proxy.h @@ -31,9 +31,9 @@ public: virtual void RegisterBleCentralManagerCallback(const sptr &callback) override; virtual void DeregisterBleCentralManagerCallback( const sptr &callback) override; - virtual void StartScan() override; - virtual void StartScan(const BluetoothBleScanSettings &settings) override; - virtual void StopScan() override; + int StartScan() override; + int StartScan(const BluetoothBleScanSettings &settings) override; + int StopScan() override; virtual int ConfigScanFilter(const int clientId, const std::vector &filters) override; virtual void RemoveScanFilter(const int clientId) override; virtual bool ProxyUid(int32_t uid, bool isProxy) override; diff --git a/services/bluetooth/ipc/include/bluetooth_gatt_client_proxy.h b/services/bluetooth/ipc/include/bluetooth_gatt_client_proxy.h index ef828f7c..5d2f3817 100644 --- a/services/bluetooth/ipc/include/bluetooth_gatt_client_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_gatt_client_proxy.h @@ -30,6 +30,9 @@ public: int RegisterApplication(const sptr &callback, const BluetoothRawAddress &addr, int32_t transport) override; + + int RegisterApplication(const sptr &callback, const BluetoothRawAddress &addr, + int32_t transport, int &appId) override; int DeregisterApplication(int32_t appId) override; int Connect(int32_t appId, bool autoConnect) override; int Disconnect(int32_t appId) override; diff --git a/services/bluetooth/ipc/include/bluetooth_hfp_ag_proxy.h b/services/bluetooth/ipc/include/bluetooth_hfp_ag_proxy.h index 3374f02f..7c82b28a 100644 --- a/services/bluetooth/ipc/include/bluetooth_hfp_ag_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_hfp_ag_proxy.h @@ -25,17 +25,17 @@ public: explicit BluetoothHfpAgProxy(const sptr &impl) : IRemoteProxy(impl) {}; ~BluetoothHfpAgProxy() {}; - int GetConnectDevices(std::vector &devices) override; + int32_t GetConnectDevices(std::vector &devices) override; int GetDevicesByStates(const std::vector &states, std::vector &devices) override; - int GetDeviceState(const BluetoothRawAddress &device) override; - int Connect(const BluetoothRawAddress &device) override; - int Disconnect(const BluetoothRawAddress &device) override; + int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) override; + int32_t Connect(const BluetoothRawAddress &device) override; + int32_t Disconnect(const BluetoothRawAddress &device) override; int GetScoState(const BluetoothRawAddress &device) override; bool ConnectSco() override; bool DisconnectSco() override; - void PhoneStateChanged(int numActive, int numHeld, int callState, const std::string &number, int type, + void PhoneStateChanged(int numActive, int numHeld, int callState, const std::string &number, int type, const std::string &name) override; - void ClccResponse(int index, int direction, int status, int mode, bool mpty, const std::string &number, + void ClccResponse(int index, int direction, int status, int mode, bool mpty, const std::string &number, int type) override; bool OpenVoiceRecognition(const BluetoothRawAddress &device) override; bool CloseVoiceRecognition(const BluetoothRawAddress &device) override; diff --git a/services/bluetooth/ipc/include/bluetooth_hfp_ag_stub.h b/services/bluetooth/ipc/include/bluetooth_hfp_ag_stub.h index c3a62709..bf9de40e 100644 --- a/services/bluetooth/ipc/include/bluetooth_hfp_ag_stub.h +++ b/services/bluetooth/ipc/include/bluetooth_hfp_ag_stub.h @@ -30,11 +30,11 @@ public: uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; private: - ErrCode GetConnectDevicesInner(MessageParcel &data, MessageParcel &reply); + int32_t GetConnectDevicesInner(MessageParcel &data, MessageParcel &reply); ErrCode GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDeviceStateInner(MessageParcel &data, MessageParcel &reply); - ErrCode ConnectInner(MessageParcel &data, MessageParcel &reply); - ErrCode DisconnectInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDeviceStateInner(MessageParcel &data, MessageParcel &reply); + int32_t ConnectInner(MessageParcel &data, MessageParcel &reply); + int32_t DisconnectInner(MessageParcel &data, MessageParcel &reply); ErrCode GetScoStateInner(MessageParcel &data, MessageParcel &reply); ErrCode ConnectScoInner(MessageParcel &data, MessageParcel &reply); ErrCode DisconnectScoInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/bluetooth/ipc/include/bluetooth_hid_host_proxy.h b/services/bluetooth/ipc/include/bluetooth_hid_host_proxy.h index ba47bc9f..2f45c76d 100644 --- a/services/bluetooth/ipc/include/bluetooth_hid_host_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_hid_host_proxy.h @@ -27,10 +27,10 @@ public: virtual ~BluetoothHidHostProxy() {} - ErrCode Connect(const BluetoothRawAddress &device, bool& result) override; - ErrCode Disconnect(const BluetoothRawAddress &device, bool& result) override; - ErrCode GetDeviceState(const BluetoothRawAddress &device, int& result) override; - ErrCode GetDevicesByStates(const std::vector &states, std::vector& result) override; + int32_t Connect(const BluetoothRawAddress &device) override; + int32_t Disconnect(const BluetoothRawAddress &device) override; + int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) override; + int32_t GetDevicesByStates(const std::vector &states, std::vector& result) override; ErrCode RegisterObserver(const sptr observer) override; ErrCode DeregisterObserver(const sptr observer) override; ErrCode HidHostVCUnplug(std::string &device, diff --git a/services/bluetooth/ipc/include/bluetooth_hid_host_stub.h b/services/bluetooth/ipc/include/bluetooth_hid_host_stub.h index 861d981f..a370ca50 100644 --- a/services/bluetooth/ipc/include/bluetooth_hid_host_stub.h +++ b/services/bluetooth/ipc/include/bluetooth_hid_host_stub.h @@ -34,10 +34,10 @@ public: MessageOption& option) override; private: - ErrCode ConnectInner(MessageParcel &data, MessageParcel &reply); - ErrCode DisconnectInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDeviceStateInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply); + int32_t ConnectInner(MessageParcel &data, MessageParcel &reply); + int32_t DisconnectInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDeviceStateInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply); ErrCode RegisterObserverInner(MessageParcel &data, MessageParcel &reply); ErrCode DeregisterObserverInner(MessageParcel &data, MessageParcel &reply); ErrCode HidHostVCUnplugInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/bluetooth/ipc/include/bluetooth_host_proxy.h b/services/bluetooth/ipc/include/bluetooth_host_proxy.h index fe8ab2e1..ee9cccde 100644 --- a/services/bluetooth/ipc/include/bluetooth_host_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_host_proxy.h @@ -32,33 +32,34 @@ public: void RegisterObserver(const sptr &observer) override; void DeregisterObserver(const sptr &observer) override; bool EnableBt() override; - bool DisableBt() override; + int32_t DisableBt() override; sptr GetProfile(const std::string &name) override; sptr GetBleRemote(const std::string &name) override; bool BluetoothFactoryReset() override; - int32_t GetBtState() override; + int32_t GetBtState(int &state) override; std::string GetLocalAddress() override; - bool DisableBle() override; - bool EnableBle() override; + int32_t DisableBle() override; + int32_t EnableBle() override; + bool IsBrEnabled() override; bool IsBleEnabled() override; std::vector GetProfileList() override; int32_t GetMaxNumConnectedAudioDevices() override; - int32_t GetBtConnectionState() override; - int32_t GetBtProfileConnState(uint32_t profileId) override; + int32_t GetBtConnectionState(int &state) override; + int32_t GetBtProfileConnState(uint32_t profileId, int &state) override; int32_t GetLocalDeviceClass() override; bool SetLocalDeviceClass(const int32_t &deviceClass) override; - std::string GetLocalName() override; - bool SetLocalName(const std::string &name) override; - int32_t GetBtScanMode() override; - bool SetBtScanMode(int32_t mode, int32_t duration) override; + int32_t GetLocalName(std::string &name) override; + int32_t SetLocalName(const std::string &name) override; + int32_t GetBtScanMode(int32_t &scanMode) override; + int32_t SetBtScanMode(int32_t mode, int32_t duration) override; int32_t GetBondableMode(const int32_t transport) override; bool SetBondableMode(int32_t transport, int32_t mode) override; - bool StartBtDiscovery() override; - bool CancelBtDiscovery() override; + int32_t StartBtDiscovery() override; + int32_t CancelBtDiscovery() override; bool IsBtDiscovering(const int32_t transport) override; long GetBtDiscoveryEndMillis() override; - std::vector GetPairedDevices(const int32_t transport) override; - bool RemovePair(const int32_t transport, const sptr &device) override; + int32_t GetPairedDevices(const int32_t transport, std::vector &pairedAddr) override; + int32_t RemovePair(const int32_t transport, const sptr &device) override; bool RemoveAllPairs() override; void RegisterRemoteDeviceObserver(const sptr &observer) override; void DeregisterRemoteDeviceObserver(const sptr &observer) override; @@ -69,19 +70,19 @@ public: int32_t GetMessagePermission(const std::string &address) override; bool SetMessagePermission(const std::string &address, int32_t permission) override; int32_t GetPowerMode(const std::string &address) override; - std::string GetDeviceName(int32_t transport, const std::string &address) override; + int32_t GetDeviceName(int32_t transport, const std::string &address, std::string &name) override; std::string GetDeviceAlias(const std::string &address) override; bool SetDeviceAlias(const std::string &address, const std::string &aliasName) override; int32_t GetDeviceBatteryLevel(const std::string &address) override; int32_t GetPairState(int32_t transport, const std::string &address) override; - bool StartPair(int32_t transport, const std::string &address) override; + int32_t StartPair(int32_t transport, const std::string &address) override; bool CancelPairing(int32_t transport, const std::string &address) override; bool IsBondedFromLocal(int32_t transport, const std::string &address) override; bool IsAclConnected(int32_t transport, const std::string &address) override; bool IsAclEncrypted(int32_t transport, const std::string &address) override; - int32_t GetDeviceClass(const std::string &address) override; + int32_t GetDeviceClass(const std::string &address, int &cod) override; bool SetDevicePin(const std::string &address, const std::string &pin) override; - bool SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) override; + int32_t SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) override; bool SetDevicePasskey(int32_t transport, const std::string &address, int32_t passkey, bool accept) override; bool PairRequestReply(int32_t transport, const std::string &address, bool accept) override; bool ReadRemoteRssiValue(const std::string &address) override; @@ -93,7 +94,7 @@ public: void DeregisterBlePeripheralCallback(const sptr &observer) override; private: - ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); + int32_t InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); static inline BrokerDelegator delegator_; }; } // namespace Bluetooth diff --git a/services/bluetooth/ipc/include/bluetooth_host_stub.h b/services/bluetooth/ipc/include/bluetooth_host_stub.h index b80f4e48..c057c427 100644 --- a/services/bluetooth/ipc/include/bluetooth_host_stub.h +++ b/services/bluetooth/ipc/include/bluetooth_host_stub.h @@ -35,33 +35,34 @@ private: ErrCode RegisterObserverInner(MessageParcel &data, MessageParcel &reply); ErrCode DeregisterObserverInner(MessageParcel &data, MessageParcel &reply); ErrCode EnableBtInner(MessageParcel &data, MessageParcel &reply); - ErrCode DisableBtInner(MessageParcel &data, MessageParcel &reply); + int32_t DisableBtInner(MessageParcel &data, MessageParcel &reply); ErrCode GetProfileInner(MessageParcel &data, MessageParcel &reply); ErrCode GetBleRemoteInner(MessageParcel &data, MessageParcel &reply); ErrCode BluetoothFactoryResetInner(MessageParcel &data, MessageParcel &reply); ErrCode GetBtStateInner(MessageParcel &data, MessageParcel &reply); ErrCode GetLocalAddressInner(MessageParcel &data, MessageParcel &reply); - ErrCode DisableBleInner(MessageParcel &data, MessageParcel &reply); - ErrCode EnableBleInner(MessageParcel &data, MessageParcel &reply); + int32_t DisableBleInner(MessageParcel &data, MessageParcel &reply); + int32_t EnableBleInner(MessageParcel &data, MessageParcel &reply); + ErrCode IsBrEnabledInner(MessageParcel &data, MessageParcel &reply); ErrCode IsBleEnabledInner(MessageParcel &data, MessageParcel &reply); ErrCode GetProfileListInner(MessageParcel &data, MessageParcel &reply); ErrCode GetMaxNumConnectedAudioDevicesInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetBtConnectionStateInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetBtProfileConnStateInner(MessageParcel &data, MessageParcel &reply); + int32_t GetBtConnectionStateInner(MessageParcel &data, MessageParcel &reply); + int32_t GetBtProfileConnStateInner(MessageParcel &data, MessageParcel &reply); ErrCode GetLocalDeviceClassInner(MessageParcel &data, MessageParcel &reply); ErrCode SetLocalDeviceClassInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetLocalNameInner(MessageParcel &data, MessageParcel &reply); - ErrCode SetLocalNameInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetBtScanModeInner(MessageParcel &data, MessageParcel &reply); - ErrCode SetBtScanModeInner(MessageParcel &data, MessageParcel &reply); + int32_t GetLocalNameInner(MessageParcel &data, MessageParcel &reply); + int32_t SetLocalNameInner(MessageParcel &data, MessageParcel &reply); + int32_t GetBtScanModeInner(MessageParcel &data, MessageParcel &reply); + int32_t SetBtScanModeInner(MessageParcel &data, MessageParcel &reply); ErrCode GetBondableModeInner(MessageParcel &data, MessageParcel &reply); ErrCode SetBondableModeInner(MessageParcel &data, MessageParcel &reply); - ErrCode StartBtDiscoveryInner(MessageParcel &data, MessageParcel &reply); - ErrCode CancelBtDiscoveryInner(MessageParcel &data, MessageParcel &reply); + int32_t StartBtDiscoveryInner(MessageParcel &data, MessageParcel &reply); + int32_t CancelBtDiscoveryInner(MessageParcel &data, MessageParcel &reply); ErrCode IsBtDiscoveringInner(MessageParcel &data, MessageParcel &reply); ErrCode GetBtDiscoveryEndMillisInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetPairedDevicesInner(MessageParcel &data, MessageParcel &reply); - ErrCode RemovePairInner(MessageParcel &data, MessageParcel &reply); + int32_t GetPairedDevicesInner(MessageParcel &data, MessageParcel &reply); + int32_t RemovePairInner(MessageParcel &data, MessageParcel &reply); ErrCode RemoveAllPairsInner(MessageParcel &data, MessageParcel &reply); ErrCode RegisterRemoteDeviceObserverInner(MessageParcel &data, MessageParcel &reply); ErrCode DeregisterRemoteDeviceObserverInner(MessageParcel &data, MessageParcel &reply); @@ -72,19 +73,19 @@ private: ErrCode GetMessagePermissionInner(MessageParcel &data, MessageParcel &reply); ErrCode SetMessagePermissionInner(MessageParcel &data, MessageParcel &reply); ErrCode GetPowerModeInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDeviceNameInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDeviceNameInner(MessageParcel &data, MessageParcel &reply); ErrCode GetDeviceAliasInner(MessageParcel &data, MessageParcel &reply); ErrCode SetDeviceAliasInner(MessageParcel &data, MessageParcel &reply); ErrCode GetDeviceBatteryLevelInner(MessageParcel &data, MessageParcel &reply); ErrCode GetPairStateInner(MessageParcel &data, MessageParcel &reply); - ErrCode StartPairInner(MessageParcel &data, MessageParcel &reply); + int32_t StartPairInner(MessageParcel &data, MessageParcel &reply); ErrCode CancelPairingInner(MessageParcel &data, MessageParcel &reply); ErrCode IsBondedFromLocalInner(MessageParcel &data, MessageParcel &reply); ErrCode IsAclConnectedInner(MessageParcel &data, MessageParcel &reply); ErrCode IsAclEncryptedInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDeviceClassInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDeviceClassInner(MessageParcel &data, MessageParcel &reply); ErrCode SetDevicePinInner(MessageParcel &data, MessageParcel &reply); - ErrCode SetDevicePairingConfirmationInner(MessageParcel &data, MessageParcel &reply); + int32_t SetDevicePairingConfirmationInner(MessageParcel &data, MessageParcel &reply); ErrCode SetDevicePasskeyInner(MessageParcel &data, MessageParcel &reply); ErrCode PairRequestReplyInner(MessageParcel &data, MessageParcel &reply); ErrCode ReadRemoteRssiValueInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/bluetooth/ipc/include/bluetooth_pan_proxy.h b/services/bluetooth/ipc/include/bluetooth_pan_proxy.h index dff8757b..51b441f5 100644 --- a/services/bluetooth/ipc/include/bluetooth_pan_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_pan_proxy.h @@ -27,13 +27,13 @@ public: virtual ~BluetoothPanProxy() {} - ErrCode Disconnect(const BluetoothRawAddress &device, bool& result) override; - ErrCode GetDeviceState(const BluetoothRawAddress &device, int& result) override; - ErrCode GetDevicesByStates(const std::vector &states, std::vector& result) override; + int32_t Disconnect(const BluetoothRawAddress &device) override; + int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) override; + int32_t GetDevicesByStates(const std::vector &states, std::vector &result) override; ErrCode RegisterObserver(const sptr observer) override; ErrCode DeregisterObserver(const sptr observer) override; - ErrCode SetTethering(const bool value, bool& result) override; - ErrCode IsTetheringOn(bool& result) override; + int32_t SetTethering(const bool value) override; + int32_t IsTetheringOn(bool &result) override; private: static inline BrokerDelegator delegator_; diff --git a/services/bluetooth/ipc/include/bluetooth_pan_stub.h b/services/bluetooth/ipc/include/bluetooth_pan_stub.h index 02db9977..cd437e75 100644 --- a/services/bluetooth/ipc/include/bluetooth_pan_stub.h +++ b/services/bluetooth/ipc/include/bluetooth_pan_stub.h @@ -33,13 +33,13 @@ public: MessageOption& option) override; private: - ErrCode DisconnectInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDeviceStateInner(MessageParcel &data, MessageParcel &reply); - ErrCode GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply); + int32_t DisconnectInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDeviceStateInner(MessageParcel &data, MessageParcel &reply); + int32_t GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply); ErrCode RegisterObserverInner(MessageParcel &data, MessageParcel &reply); ErrCode DeregisterObserverInner(MessageParcel &data, MessageParcel &reply); - ErrCode SetTetheringInner(MessageParcel &data, MessageParcel &reply); - ErrCode IsTetheringOnInner(MessageParcel &data, MessageParcel &reply); + int32_t SetTetheringInner(MessageParcel &data, MessageParcel &reply); + int32_t IsTetheringOnInner(MessageParcel &data, MessageParcel &reply); using BluetoothPanFunc = ErrCode (BluetoothPanStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/services/bluetooth/ipc/include/bluetooth_socket_proxy.h b/services/bluetooth/ipc/include/bluetooth_socket_proxy.h index c9dbdded..81c0f2c3 100644 --- a/services/bluetooth/ipc/include/bluetooth_socket_proxy.h +++ b/services/bluetooth/ipc/include/bluetooth_socket_proxy.h @@ -21,6 +21,7 @@ namespace OHOS { namespace Bluetooth { +constexpr int BT_INVALID_SOCKET_FD = -1; class BluetoothSocketProxy : public IRemoteProxy { public: explicit BluetoothSocketProxy(const sptr &impl) : IRemoteProxy(impl) diff --git a/services/bluetooth/ipc/include/i_bluetooth_a2dp_sink.h b/services/bluetooth/ipc/include/i_bluetooth_a2dp_sink.h index 87a9a7bd..9f3e2da6 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_a2dp_sink.h +++ b/services/bluetooth/ipc/include/i_bluetooth_a2dp_sink.h @@ -50,7 +50,7 @@ public: virtual void DeregisterObserver(const sptr &observer) = 0; virtual std::vector GetDevicesByStates(const std::vector &states) = 0; virtual int GetDeviceState(const RawAddress &device) = 0; - virtual int GetPlayingState(const RawAddress &device) = 0; + virtual int GetPlayingState(const RawAddress &device, int &state) = 0; virtual int SetConnectStrategy(const RawAddress &device, int32_t strategy) = 0; virtual int GetConnectStrategy(const RawAddress &device) = 0; virtual int SendDelay(const RawAddress &device, int32_t delayValue) = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_a2dp_src.h b/services/bluetooth/ipc/include/i_bluetooth_a2dp_src.h index d2d7ea93..2d7bac86 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_a2dp_src.h +++ b/services/bluetooth/ipc/include/i_bluetooth_a2dp_src.h @@ -61,7 +61,7 @@ public: virtual void DeregisterObserver(const sptr &observer) = 0; virtual std::vector GetDevicesByStates(const std::vector &states) = 0; virtual int GetDeviceState(const RawAddress &device) = 0; - virtual int GetPlayingState(const RawAddress &device) = 0; + virtual int GetPlayingState(const RawAddress &device, int &state) = 0; virtual int SetConnectStrategy(const RawAddress &device, int32_t strategy) = 0; virtual int GetConnectStrategy(const RawAddress &device) = 0; virtual int SetActiveSinkDevice(const RawAddress &device) = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_ble_advertiser.h b/services/bluetooth/ipc/include/i_bluetooth_ble_advertiser.h index 8b433521..61259182 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_ble_advertiser.h +++ b/services/bluetooth/ipc/include/i_bluetooth_ble_advertiser.h @@ -41,10 +41,10 @@ public: virtual void RegisterBleAdvertiserCallback(const sptr &callback) = 0; virtual void DeregisterBleAdvertiserCallback(const sptr &callback) = 0; - virtual void StartAdvertising(const BluetoothBleAdvertiserSettings &settings, + virtual int StartAdvertising(const BluetoothBleAdvertiserSettings &settings, const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle, bool isRawData) = 0; - virtual void StopAdvertising(int32_t advHandle) = 0; + virtual int StopAdvertising(int32_t advHandle) = 0; virtual void Close(int32_t advHandle) = 0; virtual int32_t GetAdvertiserHandle() = 0; }; diff --git a/services/bluetooth/ipc/include/i_bluetooth_ble_central_manager.h b/services/bluetooth/ipc/include/i_bluetooth_ble_central_manager.h index e0813894..a0426548 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_ble_central_manager.h +++ b/services/bluetooth/ipc/include/i_bluetooth_ble_central_manager.h @@ -41,9 +41,9 @@ public: virtual void RegisterBleCentralManagerCallback(const sptr &callback) = 0; virtual void DeregisterBleCentralManagerCallback(const sptr &callback) = 0; - virtual void StartScan() = 0; - virtual void StartScan(const BluetoothBleScanSettings &settings) = 0; - virtual void StopScan() = 0; + virtual int StartScan() = 0; + virtual int StartScan(const BluetoothBleScanSettings &settings) = 0; + virtual int StopScan() = 0; virtual int ConfigScanFilter(const int clientId, const std::vector &filters) = 0; virtual void RemoveScanFilter(const int clientId) = 0; virtual bool ProxyUid(int32_t uid, bool isProxy) = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_gatt_client.h b/services/bluetooth/ipc/include/i_bluetooth_gatt_client.h index c410c567..c33ff5dc 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_gatt_client.h +++ b/services/bluetooth/ipc/include/i_bluetooth_gatt_client.h @@ -49,6 +49,8 @@ public: virtual int RegisterApplication( const sptr &callback, const BluetoothRawAddress &addr, int32_t transport) = 0; + virtual int RegisterApplication(const sptr &callback, + const BluetoothRawAddress &addr, int32_t transport, int &appId) = 0; virtual int DeregisterApplication(int32_t appId) = 0; virtual int Connect(int32_t appId, bool autoConnect) = 0; virtual int Disconnect(int32_t appId) = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_hfp_ag.h b/services/bluetooth/ipc/include/i_bluetooth_hfp_ag.h index 9c2b170f..e39719fd 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_hfp_ag.h +++ b/services/bluetooth/ipc/include/i_bluetooth_hfp_ag.h @@ -47,11 +47,11 @@ public: BT_HFP_AG_INTO_MOCK, }; - virtual int GetConnectDevices(std::vector &devices) = 0; + virtual int32_t GetConnectDevices(std::vector &devices) = 0; virtual int GetDevicesByStates(const std::vector &states, std::vector &devices) = 0; - virtual int GetDeviceState(const BluetoothRawAddress &device) = 0; - virtual int Connect(const BluetoothRawAddress &device) = 0; - virtual int Disconnect(const BluetoothRawAddress &device) = 0; + virtual int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) = 0; + virtual int32_t Connect(const BluetoothRawAddress &device) = 0; + virtual int32_t Disconnect(const BluetoothRawAddress &device) = 0; virtual int GetScoState(const BluetoothRawAddress &device) = 0; virtual bool ConnectSco() = 0; virtual bool DisconnectSco() = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_hid_host.h b/services/bluetooth/ipc/include/i_bluetooth_hid_host.h index 952d269a..025a56c7 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_hid_host.h +++ b/services/bluetooth/ipc/include/i_bluetooth_hid_host.h @@ -30,10 +30,10 @@ class IBluetoothHidHost : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Bluetooth.IBluetoothHidHost"); - virtual ErrCode Connect(const BluetoothRawAddress &device, bool& result) = 0; - virtual ErrCode Disconnect(const BluetoothRawAddress &device, bool& result) = 0; - virtual ErrCode GetDeviceState(const BluetoothRawAddress &device, int& result) = 0; - virtual ErrCode GetDevicesByStates(const std::vector &states, + virtual int32_t Connect(const BluetoothRawAddress &device) = 0; + virtual int32_t Disconnect(const BluetoothRawAddress &device) = 0; + virtual int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) = 0; + virtual int32_t GetDevicesByStates(const std::vector &states, std::vector& result) = 0; virtual ErrCode RegisterObserver(const sptr observer) = 0; virtual ErrCode DeregisterObserver(const sptr observer) = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_host.h b/services/bluetooth/ipc/include/i_bluetooth_host.h index 103be7a1..f49f7427 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_host.h +++ b/services/bluetooth/ipc/include/i_bluetooth_host.h @@ -63,6 +63,7 @@ public: BT_FACTORY_RESET, BT_DISABLE_BLE, BT_ENABLE_BLE, + BT_IS_BR_ENABLED, BT_IS_BLE_ENABLED, BT_GET_PROFILE_LIST, BT_GET_MAXNUM_CONNECTED_AUDIODEVICES, @@ -120,33 +121,34 @@ public: virtual void RegisterObserver(const sptr &observer) = 0; virtual void DeregisterObserver(const sptr &observer) = 0; virtual bool EnableBt() = 0; - virtual bool DisableBt() = 0; + virtual int32_t DisableBt() = 0; virtual sptr GetProfile(const std::string &name) = 0; virtual sptr GetBleRemote(const std::string &name) = 0; virtual bool BluetoothFactoryReset() = 0; - virtual int32_t GetBtState() = 0; + virtual int32_t GetBtState(int &state) = 0; virtual std::string GetLocalAddress() = 0; - virtual bool DisableBle() = 0; - virtual bool EnableBle() = 0; + virtual int32_t DisableBle() = 0; + virtual int32_t EnableBle() = 0; + virtual bool IsBrEnabled() = 0; virtual bool IsBleEnabled() = 0; virtual std::vector GetProfileList() = 0; virtual int32_t GetMaxNumConnectedAudioDevices() = 0; - virtual int32_t GetBtConnectionState() = 0; - virtual int32_t GetBtProfileConnState(uint32_t profileId) = 0; + virtual int32_t GetBtConnectionState(int &state) = 0; + virtual int32_t GetBtProfileConnState(uint32_t profileId, int &state) = 0; virtual int32_t GetLocalDeviceClass() = 0; virtual bool SetLocalDeviceClass(const int32_t &deviceClass) = 0; - virtual std::string GetLocalName() = 0; - virtual bool SetLocalName(const std::string &name) = 0; - virtual int32_t GetBtScanMode() = 0; - virtual bool SetBtScanMode(int32_t mode, int32_t duration) = 0; + virtual int32_t GetLocalName(std::string &name) = 0; + virtual int32_t SetLocalName(const std::string &name) = 0; + virtual int32_t GetBtScanMode(int32_t &scanMode) = 0; + virtual int32_t SetBtScanMode(int32_t mode, int32_t duration) = 0; virtual int32_t GetBondableMode(const int32_t transport) = 0; virtual bool SetBondableMode(int32_t transport, int32_t mode) = 0; - virtual bool StartBtDiscovery() = 0; - virtual bool CancelBtDiscovery() = 0; + virtual int32_t StartBtDiscovery() = 0; + virtual int32_t CancelBtDiscovery() = 0; virtual bool IsBtDiscovering(const int32_t transport) = 0; virtual long GetBtDiscoveryEndMillis() = 0; - virtual std::vector GetPairedDevices(const int32_t transport) = 0; - virtual bool RemovePair(const int32_t transport, const sptr &device) = 0; + virtual int32_t GetPairedDevices(const int32_t transport, std::vector &pairedAddr) = 0; + virtual int32_t RemovePair(const int32_t transport, const sptr &device) = 0; virtual bool RemoveAllPairs() = 0; virtual void RegisterRemoteDeviceObserver(const sptr &observer) = 0; virtual void DeregisterRemoteDeviceObserver(const sptr &observer) = 0; @@ -157,19 +159,19 @@ public: virtual int32_t GetMessagePermission(const std::string &address) = 0; virtual bool SetMessagePermission(const std::string &address, int32_t permission) = 0; virtual int32_t GetPowerMode(const std::string &address) = 0; - virtual std::string GetDeviceName(int32_t transport, const std::string &address) = 0; + virtual int32_t GetDeviceName(int32_t transport, const std::string &address, std::string &name) = 0; virtual std::string GetDeviceAlias(const std::string &address) = 0; virtual bool SetDeviceAlias(const std::string &address, const std::string &aliasName) = 0; virtual int32_t GetDeviceBatteryLevel(const std::string &address) = 0; virtual int32_t GetPairState(int32_t transport, const std::string &address) = 0; - virtual bool StartPair(int32_t transport, const std::string &address) = 0; + virtual int32_t StartPair(int32_t transport, const std::string &address) = 0; virtual bool CancelPairing(int32_t transport, const std::string &address) = 0; virtual bool IsBondedFromLocal(int32_t transport, const std::string &address) = 0; virtual bool IsAclConnected(int32_t transport, const std::string &address) = 0; virtual bool IsAclEncrypted(int32_t transport, const std::string &address) = 0; - virtual int32_t GetDeviceClass(const std::string &address) = 0; + virtual int32_t GetDeviceClass(const std::string &address, int &cod) = 0; virtual bool SetDevicePin(const std::string &address, const std::string &pin) = 0; - virtual bool SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) = 0; + virtual int32_t SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) = 0; virtual bool SetDevicePasskey(int32_t transport, const std::string &address, int32_t passkey, bool accept) = 0; virtual bool PairRequestReply(int32_t transport, const std::string &address, bool accept) = 0; virtual bool ReadRemoteRssiValue(const std::string &address) = 0; diff --git a/services/bluetooth/ipc/include/i_bluetooth_pan.h b/services/bluetooth/ipc/include/i_bluetooth_pan.h index 3fa33d81..f5084df1 100644 --- a/services/bluetooth/ipc/include/i_bluetooth_pan.h +++ b/services/bluetooth/ipc/include/i_bluetooth_pan.h @@ -30,14 +30,14 @@ class IBluetoothPan : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Bluetooth.IBluetoothPan"); - virtual ErrCode Disconnect(const BluetoothRawAddress &device, bool& result) = 0; - virtual ErrCode GetDeviceState(const BluetoothRawAddress &device, int& result) = 0; - virtual ErrCode GetDevicesByStates(const std::vector &states, + virtual int32_t Disconnect(const BluetoothRawAddress &device) = 0; + virtual int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) = 0; + virtual int32_t GetDevicesByStates(const std::vector &states, std::vector& result) = 0; virtual ErrCode RegisterObserver(const sptr observer) = 0; virtual ErrCode DeregisterObserver(const sptr observer) = 0; - virtual ErrCode SetTethering(const bool value, bool& result) = 0; - virtual ErrCode IsTetheringOn(bool& result) = 0; + virtual int32_t SetTethering(const bool value) = 0; + virtual int32_t IsTetheringOn(bool &result) = 0; protected: static constexpr int COMMAND_DISCONNECT = MIN_TRANSACTION_ID + 0; diff --git a/services/bluetooth/ipc/ipc_blocklist.txt b/services/bluetooth/ipc/ipc_blocklist.txt index b72a75aa..44731501 100644 --- a/services/bluetooth/ipc/ipc_blocklist.txt +++ b/services/bluetooth/ipc/ipc_blocklist.txt @@ -24,5 +24,7 @@ type:*OHOS::Bluetooth::IBluetoothHfpAgObserver* type:*OHOS::Bluetooth::IBluetoothBleAdvertiseCallback* type:*OHOS::Bluetooth::IBluetoothBleCentralManagerCallback* type:*OHOS::Bluetooth::IBluetoothGattClientCallback* +type:*OHOS::Bluetooth::IBluetoothA2dpSourceObserver* src:*bluetooth_opp_observer_stub.cpp src:*bluetooth_pan_observer_stub.cpp +src:*bluetooth_hid_host_observer_stub.cpp diff --git a/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.cpp b/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.cpp index d4cc8974..536c4c63 100644 --- a/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.cpp +++ b/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.cpp @@ -43,6 +43,9 @@ bool BluetoothBleScanResult::Marshalling(Parcel &parcel) const if (!parcel.WriteString(payload_)) { return false; } + if (!parcel.WriteString(name_)) { + return false; + } return true; } @@ -90,6 +93,9 @@ bool BluetoothBleScanResult::ReadFromParcel(Parcel &parcel) if (!parcel.ReadString(payload_)) { return false; } + if (!parcel.ReadString(name_)) { + return false; + } return true; } diff --git a/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.h b/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.h index 49165ba6..ce5591b3 100644 --- a/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.h +++ b/services/bluetooth/ipc/parcel/bluetooth_ble_scan_result.h @@ -24,11 +24,14 @@ namespace Bluetooth { class BluetoothBleScanResult : public Parcelable, public bluetooth::ScanResult { public: explicit BluetoothBleScanResult() = default; - BluetoothBleScanResult(const bluetooth::ScanResult &other) : bluetooth::ScanResult(other) + explicit BluetoothBleScanResult(const bluetooth::ScanResult &other) : bluetooth::ScanResult(other) {} - BluetoothBleScanResult(const BluetoothBleScanResult &other) : bluetooth::ScanResult(other) + explicit BluetoothBleScanResult(const BluetoothBleScanResult &other) : bluetooth::ScanResult(other) {} - ~BluetoothBleScanResult() = default; + explicit BluetoothBleScanResult(const bluetooth::BleScanResultImpl &other) : bluetooth::ScanResult(other) + {} + + ~BluetoothBleScanResult() override = default; bool Marshalling(Parcel &parcel) const override; static BluetoothBleScanResult *Unmarshalling(Parcel &parcel); diff --git a/services/bluetooth/ipc/src/bluetooth_a2dp_sink_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_a2dp_sink_proxy.cpp index 7660c9b1..9b960db3 100644 --- a/services/bluetooth/ipc/src/bluetooth_a2dp_sink_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_a2dp_sink_proxy.cpp @@ -174,16 +174,16 @@ int BluetoothA2dpSinkProxy::GetDeviceState(const RawAddress &device) return reply.ReadInt32(); } -int BluetoothA2dpSinkProxy::GetPlayingState(const RawAddress &device) +int BluetoothA2dpSinkProxy::GetPlayingState(const RawAddress &device, int &state) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothA2dpSinkProxy::GetDescriptor())) { HILOGE("BluetoothA2dpSinkProxy::GetPlayingState WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(device.GetAddress())) { HILOGE("BluetoothA2dpSinkProxy::GetPlayingState write device error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -194,25 +194,29 @@ int BluetoothA2dpSinkProxy::GetPlayingState(const RawAddress &device) int error = Remote()->SendRequest(IBluetoothA2dpSink::Code::BT_A2DP_SINK_GET_PLAYING_STATE, data, reply, option); if (error != NO_ERROR) { HILOGE("BluetoothA2dpSinkProxy::GetPlayingState done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadInt32(); + int32_t exception = reply.ReadInt32(); + if (exception == NO_ERROR) { + state = reply.ReadInt32(); + } + return exception; } int BluetoothA2dpSinkProxy::SetConnectStrategy(const RawAddress &device, int32_t strategy) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothA2dpSinkProxy::GetDescriptor())) { - HILOGE("BluetoothA2dpSinkProxy::GetPlayingState WriteInterfaceToken error"); + HILOGE("BluetoothA2dpSinkProxy::SetConnectStrategy WriteInterfaceToken error"); return ERROR; } if (!data.WriteString(device.GetAddress())) { - HILOGE("BluetoothA2dpSinkProxy::GetPlayingState write device error"); + HILOGE("BluetoothA2dpSinkProxy::SetConnectStrategy write device error"); return ERROR; } if (!data.WriteInt32(strategy)) { - HILOGE("BluetoothA2dpSinkProxy::GetPlayingState write strategy error"); + HILOGE("BluetoothA2dpSinkProxy::SetConnectStrategy write strategy error"); return ERROR; } @@ -223,7 +227,7 @@ int BluetoothA2dpSinkProxy::SetConnectStrategy(const RawAddress &device, int32_t int error = Remote()->SendRequest(IBluetoothA2dpSink::Code::BT_A2DP_SINK_SET_CONNECT_STRATEGY, data, reply, option); if (error != NO_ERROR) { - HILOGE("BluetoothA2dpSinkProxy::GetPlayingState done fail, error: %{public}d", error); + HILOGE("BluetoothA2dpSinkProxy::SetConnectStrategy done fail, error: %{public}d", error); return ERROR; } diff --git a/services/bluetooth/ipc/src/bluetooth_a2dp_sink_stub.cpp b/services/bluetooth/ipc/src/bluetooth_a2dp_sink_stub.cpp index 2b805f26..65d9710c 100644 --- a/services/bluetooth/ipc/src/bluetooth_a2dp_sink_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_a2dp_sink_stub.cpp @@ -22,6 +22,7 @@ namespace OHOS { namespace Bluetooth { using namespace OHOS::bluetooth; +const int32_t A2DP_MAX_SNK_CONNECTION_NUMS = 0x07; BluetoothA2dpSinkStub::BluetoothA2dpSinkStub() { HILOGD("%{public}s start.", __func__); @@ -56,10 +57,8 @@ BluetoothA2dpSinkStub::~BluetoothA2dpSinkStub() int BluetoothA2dpSinkStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOGD("BluetoothA2dpSinkStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothA2dpSinkStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + HILOGI("BluetoothA2dpSinkStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); + if (BluetoothA2dpSinkStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGI("local descriptor is not equal to remote"); return ERR_INVALID_STATE; } @@ -126,6 +125,9 @@ ErrCode BluetoothA2dpSinkStub::GetDevicesByStatesInner(MessageParcel &data, Mess { std::vector states = {}; int32_t stateSize = data.ReadInt32(); + if (stateSize > A2DP_MAX_SNK_CONNECTION_NUMS) { + return ERR_INVALID_STATE; + } for (int i = 0; i < stateSize; i++) { int32_t state = data.ReadInt32(); @@ -162,15 +164,11 @@ ErrCode BluetoothA2dpSinkStub::GetDeviceStateInner(MessageParcel &data, MessageP ErrCode BluetoothA2dpSinkStub::GetPlayingStateInner(MessageParcel &data, MessageParcel &reply) { std::string addr = data.ReadString(); + int32_t state = 0; + int result = GetPlayingState(RawAddress(addr), state); - int result = GetPlayingState(RawAddress(addr)); - - bool ret = reply.WriteInt32(result); - if (!ret) { - HILOGE("BluetoothA2dpSinkStub: GetPlayingStateInner reply writing failed in: %{public}s.", __func__); - return TRANSACTION_ERR; - } - + (void)reply.WriteInt32(result); + (void)reply.WriteInt32(state); return NO_ERROR; } diff --git a/services/bluetooth/ipc/src/bluetooth_a2dp_src_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_a2dp_src_proxy.cpp index 62a77621..66b8d0e5 100644 --- a/services/bluetooth/ipc/src/bluetooth_a2dp_src_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_a2dp_src_proxy.cpp @@ -20,16 +20,16 @@ namespace OHOS { namespace Bluetooth { -int BluetoothA2dpSrcProxy::Connect(const RawAddress &device) +int32_t BluetoothA2dpSrcProxy::Connect(const RawAddress &device) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothA2dpSrcProxy::GetDescriptor())) { HILOGE("BluetoothA2dpSrcProxy::Connect WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(device.GetAddress())) { HILOGE("BluetoothA2dpSrcProxy::Connect write device error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -38,24 +38,24 @@ int BluetoothA2dpSrcProxy::Connect(const RawAddress &device) }; int error = Remote()->SendRequest(IBluetoothA2dpSrc::Code::BT_A2DP_SRC_CONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothA2dpSrcProxy::Connect done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } -int BluetoothA2dpSrcProxy::Disconnect(const RawAddress &device) +int32_t BluetoothA2dpSrcProxy::Disconnect(const RawAddress &device) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothA2dpSrcProxy::GetDescriptor())) { HILOGE("BluetoothA2dpSrcProxy::Disconnect WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(device.GetAddress())) { HILOGE("BluetoothA2dpSrcProxy::Disconnect write device error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -66,7 +66,7 @@ int BluetoothA2dpSrcProxy::Disconnect(const RawAddress &device) int error = Remote()->SendRequest(IBluetoothA2dpSrc::Code::BT_A2DP_SRC_DISCONNECT, data, reply, option); if (error != NO_ERROR) { HILOGE("BluetoothA2dpSrcProxy::Disconnect done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); @@ -174,16 +174,16 @@ int BluetoothA2dpSrcProxy::GetDeviceState(const RawAddress &device) return reply.ReadInt32(); } -int BluetoothA2dpSrcProxy::GetPlayingState(const RawAddress &device) +int32_t BluetoothA2dpSrcProxy::GetPlayingState(const RawAddress &device, int &state) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothA2dpSrcProxy::GetDescriptor())) { HILOGE("BluetoothA2dpSrcProxy::GetPlayingState WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(device.GetAddress())) { HILOGE("BluetoothA2dpSrcProxy::GetPlayingState write device error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -194,25 +194,29 @@ int BluetoothA2dpSrcProxy::GetPlayingState(const RawAddress &device) int error = Remote()->SendRequest(IBluetoothA2dpSrc::Code::BT_A2DP_SRC_GET_PLAYING_STATE, data, reply, option); if (error != NO_ERROR) { HILOGE("BluetoothA2dpSrcProxy::GetPlayingState done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadInt32(); + int32_t exception = reply.ReadInt32(); + if (exception == NO_ERROR) { + state = reply.ReadInt32(); + } + return exception; } int BluetoothA2dpSrcProxy::SetConnectStrategy(const RawAddress &device, int32_t strategy) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothA2dpSrcProxy::GetDescriptor())) { - HILOGE("BluetoothA2dpSrcProxy::GetPlayingState WriteInterfaceToken error"); + HILOGE("BluetoothA2dpSrcProxy::SetConnectStrategy WriteInterfaceToken error"); return ERROR; } if (!data.WriteString(device.GetAddress())) { - HILOGE("BluetoothA2dpSrcProxy::GetPlayingState write device error"); + HILOGE("BluetoothA2dpSrcProxy::SetConnectStrategy write device error"); return ERROR; } if (!data.WriteInt32(strategy)) { - HILOGE("BluetoothA2dpSrcProxy::GetPlayingState write strategy error"); + HILOGE("BluetoothA2dpSrcProxy::SetConnectStrategy write strategy error"); return ERROR; } @@ -223,7 +227,7 @@ int BluetoothA2dpSrcProxy::SetConnectStrategy(const RawAddress &device, int32_t int error = Remote()->SendRequest(IBluetoothA2dpSrc::Code::BT_A2DP_SRC_SET_CONNECT_STRATEGY, data, reply, option); if (error != NO_ERROR) { - HILOGE("BluetoothA2dpSrcProxy::GetPlayingState done fail, error: %{public}d", error); + HILOGE("BluetoothA2dpSrcProxy::SetConnectStrategy done fail, error: %{public}d", error); return ERROR; } diff --git a/services/bluetooth/ipc/src/bluetooth_a2dp_src_stub.cpp b/services/bluetooth/ipc/src/bluetooth_a2dp_src_stub.cpp index 1decdef2..f9059d22 100644 --- a/services/bluetooth/ipc/src/bluetooth_a2dp_src_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_a2dp_src_stub.cpp @@ -22,6 +22,7 @@ namespace OHOS { namespace Bluetooth { using namespace OHOS::bluetooth; +const int32_t A2DP_MAX_SRC_CONNECTION_NUMS = 0x07; BluetoothA2dpSrcStub::BluetoothA2dpSrcStub() { HILOGD("%{public}s start.", __func__); @@ -76,10 +77,8 @@ BluetoothA2dpSrcStub::~BluetoothA2dpSrcStub() int BluetoothA2dpSrcStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOGD("BluetoothA2dpSrcStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothA2dpSrcStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + HILOGI("BluetoothA2dpSrcStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); + if (BluetoothA2dpSrcStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGI("local descriptor is not equal to remote"); return ERR_INVALID_STATE; } @@ -94,11 +93,11 @@ int BluetoothA2dpSrcStub::OnRemoteRequest( return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } -ErrCode BluetoothA2dpSrcStub::ConnectInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothA2dpSrcStub::ConnectInner(MessageParcel &data, MessageParcel &reply) { std::string addr = data.ReadString(); - int result = Connect(RawAddress(addr)); + int32_t result = Connect(RawAddress(addr)); bool ret = reply.WriteInt32(result); if (!ret) { @@ -109,11 +108,11 @@ ErrCode BluetoothA2dpSrcStub::ConnectInner(MessageParcel &data, MessageParcel &r return NO_ERROR; } -ErrCode BluetoothA2dpSrcStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothA2dpSrcStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) { std::string addr = data.ReadString(); - int result = Disconnect(RawAddress(addr)); + int32_t result = Disconnect(RawAddress(addr)); bool ret = reply.WriteInt32(result); if (!ret) { @@ -146,6 +145,9 @@ ErrCode BluetoothA2dpSrcStub::GetDevicesByStatesInner(MessageParcel &data, Messa { std::vector states = {}; int32_t stateSize = data.ReadInt32(); + if (stateSize > A2DP_MAX_SRC_CONNECTION_NUMS) { + return ERR_INVALID_STATE; + } for (int i = 0; i < stateSize; i++) { int32_t state = data.ReadInt32(); @@ -179,18 +181,14 @@ ErrCode BluetoothA2dpSrcStub::GetDeviceStateInner(MessageParcel &data, MessagePa return NO_ERROR; } -ErrCode BluetoothA2dpSrcStub::GetPlayingStateInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothA2dpSrcStub::GetPlayingStateInner(MessageParcel &data, MessageParcel &reply) { std::string addr = data.ReadString(); + int32_t state = 0; + int32_t result = GetPlayingState(RawAddress(addr), state); - int result = GetPlayingState(RawAddress(addr)); - - bool ret = reply.WriteInt32(result); - if (!ret) { - HILOGE("BluetoothA2dpSrcStub: GetPlayingStateInner reply writing failed in: %{public}s.", __func__); - return TRANSACTION_ERR; - } - + (void)reply.WriteInt32(result); + (void)reply.WriteInt32(state); return NO_ERROR; } diff --git a/services/bluetooth/ipc/src/bluetooth_avrcp_tg_observer_stub.cpp b/services/bluetooth/ipc/src/bluetooth_avrcp_tg_observer_stub.cpp index fd0fdef2..33c54f25 100644 --- a/services/bluetooth/ipc/src/bluetooth_avrcp_tg_observer_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_avrcp_tg_observer_stub.cpp @@ -35,12 +35,10 @@ BluetoothAvrcpTgObserverStub::~BluetoothAvrcpTgObserverStub() int BluetoothAvrcpTgObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOGD("BluetoothAvrcpTgObserverStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", + HILOGI("BluetoothAvrcpTgObserverStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothAvrcpTgObserverStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothAvrcpTgObserverStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGI("local descriptor is not equal to remote"); return ERR_INVALID_STATE; } diff --git a/services/bluetooth/ipc/src/bluetooth_ble_advertise_callback_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_ble_advertise_callback_proxy.cpp index 1404f80a..e7a28378 100644 --- a/services/bluetooth/ipc/src/bluetooth_ble_advertise_callback_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_ble_advertise_callback_proxy.cpp @@ -62,12 +62,12 @@ void BluetoothBleAdvertiseCallbackProxy::OnAutoStopAdvEvent(int32_t advHandle) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothBleAdvertiseCallbackProxy::GetDescriptor())) { - HILOGE("[OnStartResultEvent] fail: write interface token failed."); + HILOGE("[OnAutoStopAdvEvent] fail: write interface token failed."); return; } if (!data.WriteInt32(advHandle)) { - HILOGE("[OnStartResultEvent] fail: write result failed"); + HILOGE("[OnAutoStopAdvEvent] fail: write result failed"); return; } diff --git a/services/bluetooth/ipc/src/bluetooth_ble_advertiser_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_ble_advertiser_proxy.cpp index 6b4364b6..b3e08b94 100644 --- a/services/bluetooth/ipc/src/bluetooth_ble_advertiser_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_ble_advertiser_proxy.cpp @@ -14,6 +14,7 @@ */ #include "bluetooth_ble_advertiser_proxy.h" +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "parcel_bt_uuid.h" @@ -71,68 +72,72 @@ void BluetoothBleAdvertiserProxy::DeregisterBleAdvertiserCallback(const sptr> BluetoothBleAdvertiserStub::interfaces_ = { {IBluetoothBleAdvertiser::Code::BLE_REGISTER_BLE_ADVERTISER_CALLBACK, - std::bind(&BluetoothBleAdvertiserStub::RegisterBleAdvertiserCallbackInner, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BluetoothBleAdvertiserStub::RegisterBleAdvertiserCallbackInner, _1, _2, _3)}, {IBluetoothBleAdvertiser::Code::BLE_DE_REGISTER_BLE_ADVERTISER_CALLBACK, - std::bind(&BluetoothBleAdvertiserStub::DeregisterBleAdvertiserCallbackInner, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BluetoothBleAdvertiserStub::DeregisterBleAdvertiserCallbackInner, _1, _2, _3)}, {IBluetoothBleAdvertiser::Code::BLE_START_ADVERTISING, - std::bind(&BluetoothBleAdvertiserStub::StartAdvertisingInner, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, + std::bind(&BluetoothBleAdvertiserStub::StartAdvertisingInner, _1, _2, _3)}, {IBluetoothBleAdvertiser::Code::BLE_STOP_ADVERTISING, - std::bind(&BluetoothBleAdvertiserStub::StopAdvertisingInner, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, + std::bind(&BluetoothBleAdvertiserStub::StopAdvertisingInner, _1, _2, _3)}, {IBluetoothBleAdvertiser::Code::BLE_CLOSE, - std::bind(&BluetoothBleAdvertiserStub::CloseInner, std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)}, + std::bind(&BluetoothBleAdvertiserStub::CloseInner, _1, _2, _3)}, {IBluetoothBleAdvertiser::Code::BLE_GET_ADVERTISER_HANDLE, - std::bind(&BluetoothBleAdvertiserStub::GetAdvertiserHandleInner, std::placeholders::_1, - std::placeholders::_2, std::placeholders::_3)}, + std::bind(&BluetoothBleAdvertiserStub::GetAdvertiserHandleInner, _1, _2, _3)}, }; BluetoothBleAdvertiserStub::BluetoothBleAdvertiserStub() @@ -53,9 +50,7 @@ BluetoothBleAdvertiserStub::~BluetoothBleAdvertiserStub() int BluetoothBleAdvertiserStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - std::u16string descriptor = BluetoothBleAdvertiserStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothBleAdvertiserStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGW("[OnRemoteRequest] fail: invalid interface token!"); return OBJECT_NULL; } @@ -118,14 +113,22 @@ ErrCode BluetoothBleAdvertiserStub::StartAdvertisingInner(MessageParcel &data, M int32_t advHandle = data.ReadInt32(); bool isRawData = data.ReadBool(); - StartAdvertising(*settings, *advData, *scanResponse, advHandle, isRawData); + int32_t ret = StartAdvertising(*settings, *advData, *scanResponse, advHandle, isRawData); + if (!reply.WriteInt32(ret)) { + HILOGE("reply writing failed."); + return ERR_INVALID_VALUE; + } return NO_ERROR; } ErrCode BluetoothBleAdvertiserStub::StopAdvertisingInner(MessageParcel &data, MessageParcel &reply) { int32_t advHandle = data.ReadInt32(); - StopAdvertising(advHandle); + int32_t ret = StopAdvertising(advHandle); + if (!reply.WriteInt32(ret)) { + HILOGE("reply writing failed."); + return ERR_INVALID_VALUE; + } return NO_ERROR; } diff --git a/services/bluetooth/ipc/src/bluetooth_ble_central_manager_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_ble_central_manager_proxy.cpp index e9a8da16..a1d8bb5b 100644 --- a/services/bluetooth/ipc/src/bluetooth_ble_central_manager_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_ble_central_manager_proxy.cpp @@ -14,6 +14,7 @@ */ #include "bluetooth_ble_central_manager_proxy.h" +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "parcel_bt_uuid.h" @@ -42,7 +43,7 @@ void BluetoothBleCentralManagerProxy::RegisterBleCentralManagerCallback( MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_REGISTER_BLE_CENTRAL_MANAGER_CALLBACK, option, data, reply); + int32_t result = InnerTransact(BLE_REGISTER_BLE_CENTRAL_MANAGER_CALLBACK, option, data, reply); if (result != NO_ERROR) { HILOGW("[RegisterBleCentralManagerCallback] fail: transact ErrCode=%{public}d", result); } @@ -64,63 +65,66 @@ void BluetoothBleCentralManagerProxy::DeregisterBleCentralManagerCallback( MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_DE_REGISTER_BLE_CENTRAL_MANAGER_CALLBACK, option, data, reply); + int32_t result = InnerTransact(BLE_DE_REGISTER_BLE_CENTRAL_MANAGER_CALLBACK, option, data, reply); if (result != NO_ERROR) { HILOGW("[DeregisterBleCentralManagerCallback] fail: transact ErrCode=%{public}d", result); } } -void BluetoothBleCentralManagerProxy::StartScan() +int BluetoothBleCentralManagerProxy::StartScan() { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothBleCentralManagerProxy::GetDescriptor())) { HILOGW("[StartScan] fail: write interface token failed."); - return; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_START_SCAN, option, data, reply); + int32_t result = InnerTransact(BLE_START_SCAN, option, data, reply); if (result != NO_ERROR) { HILOGW("[StartScan] fail: transact ErrCode=%{public}d", result); } + return reply.ReadInt32(); } -void BluetoothBleCentralManagerProxy::StartScan(const BluetoothBleScanSettings &settings) +int BluetoothBleCentralManagerProxy::StartScan(const BluetoothBleScanSettings &settings) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothBleCentralManagerProxy::GetDescriptor())) { HILOGW("[StartScan] fail: write interface token failed."); - return; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteParcelable(&settings)) { HILOGW("[StartScan] fail:write settings failed"); - return; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_START_SCAN_WITH_SETTINGS, option, data, reply); + int32_t result = InnerTransact(BLE_START_SCAN_WITH_SETTINGS, option, data, reply); if (result != NO_ERROR) { HILOGW("[StartScan] fail: transact ErrCode=%{public}d", result); } + return reply.ReadInt32(); } -void BluetoothBleCentralManagerProxy::StopScan() +int BluetoothBleCentralManagerProxy::StopScan() { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothBleCentralManagerProxy::GetDescriptor())) { HILOGW("[StopScan] fail: write interface token failed."); - return; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_STOP_SCAN, option, data, reply); + int32_t result = InnerTransact(BLE_STOP_SCAN, option, data, reply); if (result != NO_ERROR) { HILOGW("[StopScan] fail: transact ErrCode=%{public}d", result); } + return reply.ReadInt32(); } int BluetoothBleCentralManagerProxy::ConfigScanFilter( @@ -150,7 +154,7 @@ int BluetoothBleCentralManagerProxy::ConfigScanFilter( MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_CONFIG_SCAN_FILTER, option, data, reply); + int32_t result = InnerTransact(BLE_CONFIG_SCAN_FILTER, option, data, reply); if (result != NO_ERROR) { HILOGW("[ConfigScanFilter] fail: transact ErrCode=%{public}d", result); return 0; @@ -173,7 +177,7 @@ void BluetoothBleCentralManagerProxy::RemoveScanFilter(const int clientId) MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(BLE_REMOVE_SCAN_FILTER, option, data, reply); + int32_t result = InnerTransact(BLE_REMOVE_SCAN_FILTER, option, data, reply); if (result != NO_ERROR) { HILOGW("[RemoveScanFilter] fail: transact ErrCode=%{public}d", result); } @@ -194,7 +198,7 @@ bool BluetoothBleCentralManagerProxy::ProxyUid(int32_t uid, bool isProxy) MessageParcel reply; MessageOption option = {MessageOption::TF_ASYNC}; - ErrCode result = InnerTransact(BLE_PROXY_UID, option, data, reply); + int32_t result = InnerTransact(BLE_PROXY_UID, option, data, reply); if (result != NO_ERROR) { HILOGW("[ProxyUid] fail: transact ErrCode=%{public}d", result); return false; @@ -212,7 +216,7 @@ bool BluetoothBleCentralManagerProxy::ResetAllProxy() MessageParcel reply; MessageOption option = {MessageOption::TF_ASYNC}; - ErrCode result = InnerTransact(BLE_RESET_ALL_PROXY, option, data, reply); + int32_t result = InnerTransact(BLE_RESET_ALL_PROXY, option, data, reply); if (result != NO_ERROR) { HILOGW("[ResetAllProxy] fail: transact ErrCode=%{public}d", result); return false; @@ -220,7 +224,7 @@ bool BluetoothBleCentralManagerProxy::ResetAllProxy() return true; } -ErrCode BluetoothBleCentralManagerProxy::InnerTransact( +int32_t BluetoothBleCentralManagerProxy::InnerTransact( uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) { auto remote = Remote(); diff --git a/services/bluetooth/ipc/src/bluetooth_ble_central_manager_stub.cpp b/services/bluetooth/ipc/src/bluetooth_ble_central_manager_stub.cpp index 99e276c2..38dd2e30 100644 --- a/services/bluetooth/ipc/src/bluetooth_ble_central_manager_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_ble_central_manager_stub.cpp @@ -22,6 +22,7 @@ namespace OHOS { namespace Bluetooth { +const int32_t BLE_CENTRAL_MANAGER_STUB_READ_DATA_SIZE_MAX_LEN = 0x100; const std::map> BluetoothBleCentralManagerStub::interfaces_ = { {IBluetoothBleCentralManager::Code::BLE_REGISTER_BLE_CENTRAL_MANAGER_CALLBACK, @@ -62,9 +63,7 @@ BluetoothBleCentralManagerStub::~BluetoothBleCentralManagerStub() int BluetoothBleCentralManagerStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - std::u16string descriptor = BluetoothBleCentralManagerStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothBleCentralManagerStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGW("[OnRemoteRequest] fail: invalid interface token!"); return OBJECT_NULL; } @@ -112,7 +111,11 @@ ErrCode BluetoothBleCentralManagerStub::DeregisterBleCentralManagerCallbackInner ErrCode BluetoothBleCentralManagerStub::StartScanInner(MessageParcel &data, MessageParcel &reply) { - StartScan(); + int ret = StartScan(); + if (!reply.WriteInt32(ret)) { + HILOGE("reply writing faileded"); + return ERR_INVALID_VALUE; + } return NO_ERROR; } @@ -124,20 +127,32 @@ ErrCode BluetoothBleCentralManagerStub::StartScanWithSettingsInner(MessageParcel return TRANSACTION_ERR; } - StartScan(*settings); + int ret = StartScan(*settings); + if (!reply.WriteInt32(ret)) { + HILOGE("reply writing faileded"); + return ERR_INVALID_VALUE; + } return NO_ERROR; } ErrCode BluetoothBleCentralManagerStub::StopScanInner(MessageParcel &data, MessageParcel &reply) { - StopScan(); + int ret = StopScan(); + if (!reply.WriteInt32(ret)) { + HILOGE("reply writing faileded"); + return ERR_INVALID_VALUE; + } return NO_ERROR; } ErrCode BluetoothBleCentralManagerStub::ConfigScanFilterInner(MessageParcel &data, MessageParcel &reply) { std::vector filters {}; int32_t clientId = data.ReadInt32(); - int32_t itemsSize = data.ReadInt32(); + int32_t itemsSize = 0; + if (!data.ReadInt32(itemsSize) || itemsSize > BLE_CENTRAL_MANAGER_STUB_READ_DATA_SIZE_MAX_LEN) { + HILOGE("read Parcelable size failed."); + return ERR_INVALID_VALUE; + } for (int i = 0; i < itemsSize; i++) { BluetoothBleScanFilter item = *(data.ReadParcelable()); filters.push_back(item); diff --git a/services/bluetooth/ipc/src/bluetooth_gatt_client_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_gatt_client_proxy.cpp index 89d7f355..d57223d0 100644 --- a/services/bluetooth/ipc/src/bluetooth_gatt_client_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_gatt_client_proxy.cpp @@ -20,6 +20,42 @@ namespace OHOS { namespace Bluetooth { +const int GATT_CLIENT_READ_DATA_SIZE_MAX_LEN = 0xFF; +int BluetoothGattClientProxy::RegisterApplication( + const sptr &callback, const BluetoothRawAddress &addr, int32_t transport, int &appId) +{ + HILOGI("BluetoothGattClientProxy::RegisterApplication start"); + MessageParcel data; + if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { + HILOGE("BluetoothGattClientProxy::RegisterApplication WriteInterfaceToken error"); + return BT_ERR_INTERNAL_ERROR; + } + if (!data.WriteRemoteObject(callback->AsObject())) { + HILOGE("BluetoothGattClientProxy::RegisterApplication transport error"); + return BT_ERR_INTERNAL_ERROR; + } + if (!data.WriteParcelable(&addr)) { + HILOGE("BluetoothGattClientProxy::RegisterApplication transport error"); + return BT_ERR_INTERNAL_ERROR; + } + if (!data.WriteInt32(transport)) { + HILOGE("BluetoothGattClientProxy::RegisterApplication transport error"); + return BT_ERR_INTERNAL_ERROR; + } + MessageParcel reply; + MessageOption option { + MessageOption::TF_SYNC + }; + int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_REGISTER_APP, data, reply, option); + if (error != BT_SUCCESS) { + HILOGE("BluetoothGattClientProxy::RegisterApplication done fail, error: %{public}d", error); + return BT_ERR_INTERNAL_ERROR; + } + int32_t result = reply.ReadInt32(); + appId = reply.ReadInt32(); + return result; +} + int BluetoothGattClientProxy::RegisterApplication( const sptr &callback, const BluetoothRawAddress &addr, int32_t transport) { @@ -59,11 +95,11 @@ int BluetoothGattClientProxy::DeregisterApplication(int32_t appId) MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::DeregisterApplication WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::DeregisterApplication transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { @@ -71,9 +107,9 @@ int BluetoothGattClientProxy::DeregisterApplication(int32_t appId) }; HILOGE("mobaiye2 BluetoothGattClientProxy::DeregisterApplication appId : %{public}d", appId); int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_DEREGISTER_APP, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::DeregisterApplication done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -84,24 +120,24 @@ int BluetoothGattClientProxy::Connect(int32_t appId, bool autoConnect) MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::Connect WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::Connect transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteBool(autoConnect)) { HILOGE("BluetoothGattClientProxy::Connect transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { MessageOption::TF_SYNC }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_CONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::Connect done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -112,20 +148,20 @@ int BluetoothGattClientProxy::Disconnect(int32_t appId) MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::Disconnect WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::Disconnect transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { MessageOption::TF_SYNC }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_DIS_CONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::Disconnect done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -136,11 +172,11 @@ int BluetoothGattClientProxy::DiscoveryServices(int32_t appId) MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::DiscoveryServices WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::DiscoveryServices transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { @@ -148,9 +184,9 @@ int BluetoothGattClientProxy::DiscoveryServices(int32_t appId) }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_DISCOVERY_SERVICES, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::DiscoveryServices done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -161,15 +197,15 @@ int BluetoothGattClientProxy::ReadCharacteristic(int32_t appId, const BluetoothG MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::ReadCharacteristic WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::ReadCharacteristic transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteParcelable(&characteristic)) { HILOGE("BluetoothGattClientProxy::ReadCharacteristic transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { @@ -177,9 +213,9 @@ int BluetoothGattClientProxy::ReadCharacteristic(int32_t appId, const BluetoothG }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_READ_CHARACTERISTIC, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::ReadCharacteristic done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -191,19 +227,19 @@ int BluetoothGattClientProxy::WriteCharacteristic( MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::WriteCharacteristic WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::WriteCharacteristic transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteParcelable(characteristic)) { HILOGE("BluetoothGattClientProxy::WriteCharacteristic transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteBool(withoutRespond)) { HILOGE("BluetoothGattClientProxy::WriteCharacteristic transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { @@ -211,9 +247,9 @@ int BluetoothGattClientProxy::WriteCharacteristic( }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_WRITE_CHARACTERISTIC, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::WriteCharacteristic done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -253,24 +289,24 @@ int BluetoothGattClientProxy::ReadDescriptor(int32_t appId, const BluetoothGattD MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::ReadDescriptor WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::ReadDescriptor transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteParcelable(&descriptor)) { HILOGE("BluetoothGattClientProxy::ReadDescriptor transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { MessageOption::TF_SYNC }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_READ_DESCRIPTOR, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::ReadDescriptor done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -281,24 +317,24 @@ int BluetoothGattClientProxy::WriteDescriptor(int32_t appId, BluetoothGattDescri MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::WriteDescriptor WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::WriteDescriptor transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteParcelable(descriptor)) { HILOGE("BluetoothGattClientProxy::WriteDescriptor transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { MessageOption::TF_SYNC }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_WRITE_DESCRIPTOR, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::WriteDescriptor done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -309,15 +345,15 @@ int BluetoothGattClientProxy::RequestExchangeMtu(int32_t appId, int32_t mtu) MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattClientProxy::GetDescriptor())) { HILOGE("BluetoothGattClientProxy::RequestExchangeMtu WriteInterfaceToken error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattClientProxy::RequestExchangeMtu transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteInt32(mtu)) { HILOGE("BluetoothGattClientProxy::RequestExchangeMtu transport error"); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option { @@ -325,9 +361,9 @@ int BluetoothGattClientProxy::RequestExchangeMtu(int32_t appId, int32_t mtu) }; int error = Remote()->SendRequest(IBluetoothGattClient::Code::BT_GATT_CLIENT_REQUEST_EXCHANGE_MTU, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattClientProxy::RequestExchangeMtu done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_INTERNAL_ERROR; } return reply.ReadInt32(); } @@ -348,7 +384,11 @@ void BluetoothGattClientProxy::GetAllDevice(std::vector &de if (error != NO_ERROR) { HILOGE("BluetoothGattClientProxy::GetAllDevice done fail, error: %d", error); } - int DevNum = reply.ReadInt32(); + int DevNum = 0; + if (!reply.ReadInt32(DevNum) || DevNum > GATT_CLIENT_READ_DATA_SIZE_MAX_LEN) { + HILOGE("read Parcelable size failed."); + return; + } for (int i = DevNum; i > 0; i--) { std::shared_ptr dev(reply.ReadParcelable()); if (!dev) { @@ -407,7 +447,11 @@ void BluetoothGattClientProxy::GetServices(int32_t appId, std::vector GATT_CLIENT_READ_DATA_SIZE_MAX_LEN) { + HILOGE("read Parcelable size failed."); + return; + } for (int i = DevNum; i > 0; i--) { std::shared_ptr dev(reply.ReadParcelable()); if (!dev) { diff --git a/services/bluetooth/ipc/src/bluetooth_gatt_client_stub.cpp b/services/bluetooth/ipc/src/bluetooth_gatt_client_stub.cpp index 76231c5f..b080c15d 100644 --- a/services/bluetooth/ipc/src/bluetooth_gatt_client_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_gatt_client_stub.cpp @@ -90,9 +90,11 @@ ErrCode BluetoothGattClientStub::RegisterApplicationInner(MessageParcel &data, M return TRANSACTION_ERR; } int32_t transport = data.ReadInt32(); - int result = RegisterApplication(callback, *addr, transport); - bool ret = reply.WriteInt32(result); - if (!ret) { + int appId = 0; + int result = RegisterApplication(callback, *addr, transport, appId); + bool resultRet = reply.WriteInt32(result); + bool appIdRet = reply.WriteInt32(appId); + if (!(resultRet && appIdRet)) { HILOGE("BluetoothGattClientStub: reply writing failed in: %{public}s.", __func__); return ERR_INVALID_VALUE; } diff --git a/services/bluetooth/ipc/src/bluetooth_gatt_server_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_gatt_server_proxy.cpp index f8a958c0..87616b75 100644 --- a/services/bluetooth/ipc/src/bluetooth_gatt_server_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_gatt_server_proxy.cpp @@ -24,16 +24,16 @@ int BluetoothGattServerProxy::AddService(int32_t appId, BluetoothGattService *se MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::AddService WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattServerProxy::AddService error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(services)) { HILOGE("BluetoothGattServerProxy::AddService error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -42,9 +42,9 @@ int BluetoothGattServerProxy::AddService(int32_t appId, BluetoothGattService *se }; int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_ADD_SERVICE, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattServerProxy::AddService done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -121,11 +121,11 @@ int BluetoothGattServerProxy::DeregisterApplication(int appId) MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::WriteInterfaceToken WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattServerProxy::DeregisterApplication error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -135,7 +135,7 @@ int BluetoothGattServerProxy::DeregisterApplication(int appId) int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_DEREGISTER, data, reply, option); if (error != NO_ERROR) { HILOGE("BluetoothGattServerProxy::DeregisterApplication done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -145,19 +145,19 @@ int BluetoothGattServerProxy::NotifyClient( MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::WriteInterfaceToken WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothGattServerProxy::NotifyClient error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(characteristic)) { HILOGE("BluetoothGattServerProxy::NotifyClient error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteBool(needConfirm)) { HILOGE("BluetoothGattServerProxy::NotifyClient error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -165,9 +165,9 @@ int BluetoothGattServerProxy::NotifyClient( }; int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_NOTIFY_CLIENT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattServerProxy::NotifyClient done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -176,15 +176,15 @@ int BluetoothGattServerProxy::RemoveService(int32_t appId, const BluetoothGattSe MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::RemoveService WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(appId)) { HILOGE("BluetoothGattServerProxy::RemoveService error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&services)) { HILOGE("BluetoothGattServerProxy::RemoveService error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -194,7 +194,7 @@ int BluetoothGattServerProxy::RemoveService(int32_t appId, const BluetoothGattSe int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_REMOVE_SERVICE, data, reply, option); if (error != NO_ERROR) { HILOGE("BluetoothGattServerProxy::RemoveService done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -204,19 +204,19 @@ int BluetoothGattServerProxy::RespondCharacteristicRead( MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicRead WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicRead error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(characteristic)) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicRead error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(ret)) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicRead error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -224,9 +224,9 @@ int BluetoothGattServerProxy::RespondCharacteristicRead( }; int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_RESPOND_CHARACTERISTIC_READ, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicRead done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -236,19 +236,19 @@ int BluetoothGattServerProxy::RespondCharacteristicWrite( MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicWrite WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicWrite error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&characteristic)) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicWrite error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(ret)) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicWrite error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -256,9 +256,9 @@ int BluetoothGattServerProxy::RespondCharacteristicWrite( }; int error = Remote()->SendRequest( IBluetoothGattServer::Code::GATT_SERVER_RESPOND_CHARACTERISTIC_WRITE, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattServerProxy::RespondCharacteristicWrite done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -268,19 +268,19 @@ int BluetoothGattServerProxy::RespondDescriptorRead( MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::RespondDescriptorRead WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothGattServerProxy::RespondDescriptorRead error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(descriptor)) { HILOGE("BluetoothGattServerProxy::RespondDescriptorRead error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(ret)) { HILOGE("BluetoothGattServerProxy::RespondDescriptorRead error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -288,9 +288,9 @@ int BluetoothGattServerProxy::RespondDescriptorRead( }; int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_RESPOND_DESCRIPTOR_READ, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattServerProxy::RespondDescriptorRead done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } @@ -300,19 +300,19 @@ int BluetoothGattServerProxy::RespondDescriptorWrite( MessageParcel data; if (!data.WriteInterfaceToken(BluetoothGattServerProxy::GetDescriptor())) { HILOGE("BluetoothGattServerProxy::RespondDescriptorWrite WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothGattServerProxy::RespondDescriptorWrite error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&descriptor)) { HILOGE("BluetoothGattServerProxy::RespondDescriptorWrite error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(ret)) { HILOGE("BluetoothGattServerProxy::RespondDescriptorWrite error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -320,9 +320,9 @@ int BluetoothGattServerProxy::RespondDescriptorWrite( }; int error = Remote()->SendRequest(IBluetoothGattServer::Code::GATT_SERVER_RESPOND_DESCRIPTOR_WRITE, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothGattServerProxy::RespondDescriptorWrite done fail, error: %d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } diff --git a/services/bluetooth/ipc/src/bluetooth_hfp_ag_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_hfp_ag_proxy.cpp index 4e08d4c1..287c32c8 100644 --- a/services/bluetooth/ipc/src/bluetooth_hfp_ag_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_hfp_ag_proxy.cpp @@ -19,11 +19,12 @@ namespace OHOS { namespace Bluetooth { -int BluetoothHfpAgProxy::GetConnectDevices(std::vector &devices) { +int32_t BluetoothHfpAgProxy::GetConnectDevices(std::vector &devices) +{ MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHfpAgProxy::GetDescriptor())) { HILOGE("BluetoothHfpAgProxy::GetConnectDevices WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -31,19 +32,19 @@ int BluetoothHfpAgProxy::GetConnectDevices(std::vector &dev }; int error = Remote()->SendRequest( IBluetoothHfpAg::Code::BT_HFP_AG_GET_CONNECT_DEVICES, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHfpAgProxy::GetConnectDevices done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } uint32_t DevNum = reply.ReadUint32(); for (uint32_t i = 0; i < DevNum; i++) { std::shared_ptr dev(reply.ReadParcelable()); if (!dev) { - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } devices.push_back(*dev); } - return NO_ERROR; + return BT_SUCCESS; } int BluetoothHfpAgProxy::GetDevicesByStates(const std::vector &states, std::vector &devices) { @@ -76,15 +77,16 @@ int BluetoothHfpAgProxy::GetDevicesByStates(const std::vector &states, std: } return NO_ERROR; } -int BluetoothHfpAgProxy::GetDeviceState(const BluetoothRawAddress &device) { +int32_t BluetoothHfpAgProxy::GetDeviceState(const BluetoothRawAddress &device, int32_t &state) +{ MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHfpAgProxy::GetDescriptor())) { HILOGE("BluetoothHfpAgProxy::GetDeviceState WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothHfpAgProxy::GetDeviceState WriteParcelable error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -92,22 +94,31 @@ int BluetoothHfpAgProxy::GetDeviceState(const BluetoothRawAddress &device) { }; int error = Remote()->SendRequest( IBluetoothHfpAg::Code::BT_HFP_AG_GET_DEVICE_STATE, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHfpAgProxy::GetDeviceState done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadInt32(); + // read error code + int32_t errCode = reply.ReadInt32(); + if (errCode != BT_SUCCESS) { + HILOGE("reply errCode: %{public}d", errCode); + return errCode; + } + // read state + state = reply.ReadInt32(); + return BT_SUCCESS; } -int BluetoothHfpAgProxy::Connect(const BluetoothRawAddress &device) { +int32_t BluetoothHfpAgProxy::Connect(const BluetoothRawAddress &device) +{ MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHfpAgProxy::GetDescriptor())) { HILOGE("BluetoothHfpAgProxy::Connect WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothHfpAgProxy::Connect WriteParcelable error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -115,22 +126,23 @@ int BluetoothHfpAgProxy::Connect(const BluetoothRawAddress &device) { }; int error = Remote()->SendRequest( IBluetoothHfpAg::Code::BT_HFP_AG_CONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHfpAgProxy::Connect done fail, error: %{public}d", error); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } return reply.ReadInt32(); } -int BluetoothHfpAgProxy::Disconnect(const BluetoothRawAddress &device) { +int32_t BluetoothHfpAgProxy::Disconnect(const BluetoothRawAddress &device) +{ MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHfpAgProxy::GetDescriptor())) { HILOGE("BluetoothHfpAgProxy::Disconnect WriteInterfaceToken error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothHfpAgProxy::Disconnect WriteParcelable error"); - return ERROR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option { @@ -138,7 +150,7 @@ int BluetoothHfpAgProxy::Disconnect(const BluetoothRawAddress &device) { }; int error = Remote()->SendRequest( IBluetoothHfpAg::Code::BT_HFP_AG_DISCONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHfpAgProxy::Disconnect done fail, error: %{public}d", error); return ERROR; } diff --git a/services/bluetooth/ipc/src/bluetooth_hfp_ag_stub.cpp b/services/bluetooth/ipc/src/bluetooth_hfp_ag_stub.cpp index 187b5b39..caa0859f 100644 --- a/services/bluetooth/ipc/src/bluetooth_hfp_ag_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_hfp_ag_stub.cpp @@ -14,6 +14,8 @@ */ #include "bluetooth_hfp_ag_stub.h" + +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" namespace OHOS { @@ -86,9 +88,7 @@ BluetoothHfpAgStub::~BluetoothHfpAgStub() { int BluetoothHfpAgStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { HILOGI("BluetoothHfpAgStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothHfpAgStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothHfpAgStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGI("local descriptor is not equal to remote"); return ERR_INVALID_STATE; } @@ -101,24 +101,24 @@ int BluetoothHfpAgStub::OnRemoteRequest( } } HILOGW("BluetoothHfpAgStub::OnRemoteRequest, default case, need check."); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } -ErrCode BluetoothHfpAgStub::GetConnectDevicesInner(MessageParcel &data, MessageParcel &reply) { +int32_t BluetoothHfpAgStub::GetConnectDevicesInner(MessageParcel &data, MessageParcel &reply) { std::vector devices; GetConnectDevices(devices); uint32_t DevNum = devices.size(); if (!reply.WriteUint32(DevNum)) { HILOGE("BluetoothHfpAgStub:WriteInt32 failed in: %{public}s.", __func__); - return ERR_INVALID_VALUE; + return BT_ERR_IPC_TRANS_FAILED; } for (uint32_t i = 0; i < DevNum; i++) { if (!reply.WriteParcelable(&devices[i])) { HILOGE("BluetoothHfpAgStub:WriteParcelable failed in: %{public}s.", __func__); - return ERR_INVALID_VALUE; + return BT_ERR_IPC_TRANS_FAILED; } } - return NO_ERROR; + return BT_SUCCESS; } ErrCode BluetoothHfpAgStub::GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply) { @@ -143,40 +143,52 @@ ErrCode BluetoothHfpAgStub::GetDevicesByStatesInner(MessageParcel &data, Message ErrCode BluetoothHfpAgStub::GetDeviceStateInner(MessageParcel &data, MessageParcel &reply) { std::shared_ptr device(data.ReadParcelable()); if (!device) { - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - int result = GetDeviceState(*device); - if (!reply.WriteInt32(result)) { + int32_t state; + int32_t errCode = GetDeviceState(*device, state); + if (!reply.WriteInt32(errCode)) { HILOGE("BluetoothHfpAgStub: reply writing failed in: %{public}s.", __func__); - return ERR_INVALID_VALUE; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + if (errCode != BT_SUCCESS) { + HILOGE("internal error."); + return BT_ERR_INTERNAL_ERROR; + } + // write state + if (!reply.WriteInt32(state)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + return BT_SUCCESS; } -ErrCode BluetoothHfpAgStub::ConnectInner(MessageParcel &data, MessageParcel &reply) { +int32_t BluetoothHfpAgStub::ConnectInner(MessageParcel &data, MessageParcel &reply) +{ std::shared_ptr device(data.ReadParcelable()); if (!device) { - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - int result = Connect(*device); - if (!reply.WriteInt32(result)) { + int32_t errCode = Connect(*device); + if (!reply.WriteInt32(errCode)) { HILOGE("BluetoothHfpAgStub: reply writing failed in: %{public}s.", __func__); - return ERR_INVALID_VALUE; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + return BT_SUCCESS; } -ErrCode BluetoothHfpAgStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) { +int32_t BluetoothHfpAgStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) +{ std::shared_ptr device(data.ReadParcelable()); if (!device) { - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - int result = Disconnect(*device); - if (!reply.WriteInt32(result)) { + int32_t errCode = Disconnect(*device); + if (!reply.WriteInt32(errCode)) { HILOGE("BluetoothHfpAgStub: reply writing failed in: %{public}s.", __func__); - return ERR_INVALID_VALUE; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + return BT_SUCCESS; } ErrCode BluetoothHfpAgStub::GetScoStateInner(MessageParcel &data, MessageParcel &reply) { diff --git a/services/bluetooth/ipc/src/bluetooth_hid_host_observer_stub.cpp b/services/bluetooth/ipc/src/bluetooth_hid_host_observer_stub.cpp index ade67e5e..662a4971 100644 --- a/services/bluetooth/ipc/src/bluetooth_hid_host_observer_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_hid_host_observer_stub.cpp @@ -25,15 +25,17 @@ int BluetoothHidHostObserverStub::OnRemoteRequest( { switch (code) { case COMMAND_ON_CONNECTION_STATE_CHANGED: { - std::u16string descriptor = BluetoothHidHostObserverStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothHidHostObserverStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGE("local descriptor is not equal to remote"); return IPC_INVOKER_TRANSLATE_ERR; } - const BluetoothRawAddress *address = data.ReadParcelable(); + std::shared_ptr device(data.ReadParcelable()); + if (!device) { + HILOGE("COMMAND_ON_CONNECTION_STATE_CHANGED device is null"); + return IPC_INVOKER_TRANSLATE_ERR; + } int state = data.ReadInt32(); - OnConnectionStateChanged(*address, state); + OnConnectionStateChanged(*device, state); return NO_ERROR; } default: diff --git a/services/bluetooth/ipc/src/bluetooth_hid_host_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_hid_host_proxy.cpp index 5725d249..b8ed0caf 100644 --- a/services/bluetooth/ipc/src/bluetooth_hid_host_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_hid_host_proxy.cpp @@ -13,21 +13,23 @@ * limitations under the License. */ #include "bluetooth_hid_host_proxy.h" + +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "refbase.h" namespace OHOS { namespace Bluetooth { -ErrCode BluetoothHidHostProxy::Connect(const BluetoothRawAddress &device, bool& result) +int32_t BluetoothHidHostProxy::Connect(const BluetoothRawAddress &device) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHidHostProxy::GetDescriptor())) { HILOGE("BluetoothHidHostProxy::Connect WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothHidHostProxy::Connect write device error"); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -36,25 +38,24 @@ ErrCode BluetoothHidHostProxy::Connect(const BluetoothRawAddress &device, bool& }; int error = Remote()->SendRequest(COMMAND_CONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHidHostProxy::Connect done fail, error: %{public}d", error); - return error; + return BT_ERR_IPC_TRANS_FAILED; } - result = reply.ReadInt32() == NO_ERROR ? true : false; - return ERR_OK; + return reply.ReadInt32(); } -ErrCode BluetoothHidHostProxy::Disconnect(const BluetoothRawAddress &device, bool& result) +int32_t BluetoothHidHostProxy::Disconnect(const BluetoothRawAddress &device) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHidHostProxy::GetDescriptor())) { HILOGE("BluetoothHidHostProxy::Disconnect WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothHidHostProxy::Disconnect write device error"); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -63,25 +64,24 @@ ErrCode BluetoothHidHostProxy::Disconnect(const BluetoothRawAddress &device, boo }; int error = Remote()->SendRequest(COMMAND_DISCONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHidHostProxy::Disconnect done fail, error: %{public}d", error); - return error; + return BT_ERR_IPC_TRANS_FAILED; } - result = reply.ReadInt32() == NO_ERROR ? true : false; - return ERR_OK; + return reply.ReadInt32(); } -ErrCode BluetoothHidHostProxy::GetDeviceState(const BluetoothRawAddress &device, int& result) +int32_t BluetoothHidHostProxy::GetDeviceState(const BluetoothRawAddress &device, int32_t &state) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHidHostProxy::GetDescriptor())) { HILOGE("BluetoothHidHostProxy::GetDeviceState WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothHidHostProxy::GetDeviceState write device error"); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -90,46 +90,59 @@ ErrCode BluetoothHidHostProxy::GetDeviceState(const BluetoothRawAddress &device, }; int error = Remote()->SendRequest(COMMAND_GET_DEVICE_STATE, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHidHostProxy::GetDeviceState done fail, error: %{public}d", error); - return error; + return BT_ERR_IPC_TRANS_FAILED; } - ErrCode ec = reply.ReadInt32(); - if (FAILED(ec)) { - return ec; + // read error code + int32_t errCode = reply.ReadInt32(); + if (errCode != BT_SUCCESS) { + HILOGE("reply errCode: %{public}d", errCode); + return errCode; } - result = reply.ReadInt32(); - return ERR_OK; + // read state + state = reply.ReadInt32(); + return BT_SUCCESS; } -ErrCode BluetoothHidHostProxy::GetDevicesByStates(const std::vector &states, +int32_t BluetoothHidHostProxy::GetDevicesByStates(const std::vector &states, std::vector& result) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHidHostProxy::GetDescriptor())) { HILOGE("BluetoothHidHostProxy::GetDevicesByStates WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } if (!WriteParcelableInt32Vector(states, data)) { HILOGE("[GetDevicesByStates] fail: write result failed"); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int error = Remote()->SendRequest(COMMAND_GET_DEVICES_BY_STATES, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHidHostProxy::GetDevicesByStates done fail, error: %{public}d", error); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; + } + // read error code + int32_t errCode = reply.ReadInt32(); + if (errCode != BT_SUCCESS) { + HILOGE("reply errCode: %{public}d", errCode); + return errCode; } + + // read size int32_t rawAddsSize = reply.ReadInt32(); + + // read devices for (int i = 0; i < rawAddsSize; i++) { std::unique_ptr address(reply.ReadParcelable()); result.push_back(*address); } - return ERR_OK; + return BT_SUCCESS; } ErrCode BluetoothHidHostProxy::RegisterObserver( diff --git a/services/bluetooth/ipc/src/bluetooth_hid_host_stub.cpp b/services/bluetooth/ipc/src/bluetooth_hid_host_stub.cpp index 5df1e4fd..29f92083 100644 --- a/services/bluetooth/ipc/src/bluetooth_hid_host_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_hid_host_stub.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ #include "bluetooth_hid_host_stub.h" + +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" namespace OHOS { @@ -52,10 +54,8 @@ BluetoothHidHostStub::~BluetoothHidHostStub() int BluetoothHidHostStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOGD("BluetoothHidHostStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothHidHostStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + HILOGI("BluetoothHidHostStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); + if (BluetoothHidHostStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGE("local descriptor is not equal to remote"); return IPC_INVOKER_TRANSLATE_ERR; } @@ -70,50 +70,56 @@ int BluetoothHidHostStub::OnRemoteRequest( return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } -ErrCode BluetoothHidHostStub::ConnectInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHidHostStub::ConnectInner(MessageParcel &data, MessageParcel &reply) { - const BluetoothRawAddress *device = data.ReadParcelable(); - bool result; + std::shared_ptr device(data.ReadParcelable()); HILOGD("BluetoothHidHostStub::ConnectInner"); - ErrCode ec = Connect(*device, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - if (result == NO_ERROR) { - reply.WriteInt32(NO_ERROR); - } + int32_t errCode = Connect(*device); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - return ERR_NONE; + return BT_SUCCESS; } -ErrCode BluetoothHidHostStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHidHostStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) { - const BluetoothRawAddress *device = data.ReadParcelable(); - bool result; + std::shared_ptr device(data.ReadParcelable()); HILOGD("BluetoothHidHostStub::DisconnectInner"); - ErrCode ec = Disconnect(*device, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - if (result == NO_ERROR) { - reply.WriteInt32(NO_ERROR); - } + int32_t errCode = Disconnect(*device); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - return ERR_NONE; + return BT_SUCCESS; } -ErrCode BluetoothHidHostStub::GetDeviceStateInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHidHostStub::GetDeviceStateInner(MessageParcel &data, MessageParcel &reply) { - const BluetoothRawAddress *device = data.ReadParcelable(); - int result; + std::shared_ptr device(data.ReadParcelable()); HILOGD("BluetoothHidHostStub::GetDeviceStateInner"); - ErrCode ec = GetDeviceState(*device, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - reply.WriteInt32(result); + int32_t state; + int32_t errCode = GetDeviceState(*device, state); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + if (errCode != BT_SUCCESS) { + HILOGE("internal error."); + return BT_ERR_INTERNAL_ERROR; } - return ERR_NONE; + // write state + if (!reply.WriteInt32(state)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + return BT_SUCCESS; } -ErrCode BluetoothHidHostStub::GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHidHostStub::GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply) { std::vector states = {}; int32_t stateSize = data.ReadInt32(); @@ -123,17 +129,28 @@ ErrCode BluetoothHidHostStub::GetDevicesByStatesInner(MessageParcel &data, Messa states.push_back(state); } std::vector rawAdds; - ErrCode ec = GetDevicesByStates(states, rawAdds); - if (ec != ERR_OK) { - return ec; + int32_t errCode = GetDevicesByStates(states, rawAdds); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + if (errCode != BT_SUCCESS) { + HILOGE("internal error."); + return BT_ERR_INTERNAL_ERROR; + } + // write size + if (!reply.WriteInt32(rawAdds.size())) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - reply.WriteInt32(rawAdds.size()); + // write devices for (auto rawAdd : rawAdds) { if (!reply.WriteParcelable(&rawAdd)) { - return ERR_INVALID_STATE; + return BT_ERR_IPC_TRANS_FAILED; } } - return ERR_NONE; + return BT_SUCCESS; } ErrCode BluetoothHidHostStub::RegisterObserverInner(MessageParcel &data, MessageParcel &reply) diff --git a/services/bluetooth/ipc/src/bluetooth_host_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_host_proxy.cpp index 81a00f65..b0325f88 100644 --- a/services/bluetooth/ipc/src/bluetooth_host_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_host_proxy.cpp @@ -15,6 +15,7 @@ #include "bluetooth_host_proxy.h" #include "bluetooth_log.h" +#include "bluetooth_errorcode.h" namespace OHOS { namespace Bluetooth { void BluetoothHostProxy::RegisterObserver(const sptr &observer) @@ -78,23 +79,23 @@ bool BluetoothHostProxy::EnableBt() return reply.ReadBool(); } -bool BluetoothHostProxy::DisableBt() +int32_t BluetoothHostProxy::DisableBt() { HILOGI("BluetoothHostProxy::DisableBt starts"); MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::DisableBt WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_DISABLE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::DisableBt done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } sptr BluetoothHostProxy::GetProfile(const std::string &name) @@ -156,7 +157,7 @@ bool BluetoothHostProxy::BluetoothFactoryReset() return reply.ReadBool(); } -int32_t BluetoothHostProxy::GetBtState() +int32_t BluetoothHostProxy::GetBtState(int &state) { HILOGI("BluetoothHostProxy::GetBtState starts"); MessageParcel data; @@ -169,9 +170,14 @@ int32_t BluetoothHostProxy::GetBtState() int32_t error = InnerTransact(IBluetoothHost::Code::BT_GETSTATE, option, data, reply); if (error != NO_ERROR) { HILOGE("BluetoothHostProxy::GetBtState done fail, error: %{public}d", error); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadInt32(); + + int32_t exception = reply.ReadInt32(); + if (exception == NO_ERROR) { + state = reply.ReadInt32(); + } + return exception; } std::string BluetoothHostProxy::GetLocalAddress() @@ -191,36 +197,53 @@ std::string BluetoothHostProxy::GetLocalAddress() return reply.ReadString(); } -bool BluetoothHostProxy::DisableBle() +int32_t BluetoothHostProxy::DisableBle() { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::DisableBle WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_DISABLE_BLE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::DisableBle done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } -bool BluetoothHostProxy::EnableBle() +int32_t BluetoothHostProxy::EnableBle() { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::EnableBle WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_ENABLE_BLE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::EnableBle done fail, error: %{public}d", error); + return BT_ERR_IPC_TRANS_FAILED; + } + return reply.ReadInt32(); +} + +bool BluetoothHostProxy::IsBrEnabled() +{ + MessageParcel data; + if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { + HILOGE("BluetoothHostProxy::IsBrEnabled WriteInterfaceToken error"); + return false; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + int32_t error = InnerTransact(IBluetoothHost::Code::BT_IS_BR_ENABLED, option, data, reply); + if (error != NO_ERROR) { + HILOGE("BluetoothHostProxy::IsBrEnabled done fail, error: %{public}d", error); return false; } return reply.ReadBool(); @@ -287,53 +310,52 @@ int32_t BluetoothHostProxy::GetMaxNumConnectedAudioDevices() return maxNum; } -int32_t BluetoothHostProxy::GetBtConnectionState() +int32_t BluetoothHostProxy::GetBtConnectionState(int &state) { - int32_t state; + HILOGI("BluetoothHostProxy::GetBtConnectionState starts"); MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetBtConnectionState WriteInterfaceToken error"); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_GET_BT_STATE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetBtConnectionState done fail, error: %{public}d", error); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } - if (!reply.ReadInt32(state)) { - HILOGE("BluetoothHostProxy::GetBtConnectionState Read reply fail"); - return -1; + int32_t exception = reply.ReadInt32(); + if (exception == BT_SUCCESS) { + state = reply.ReadInt32(); } - return state; + return exception; } -int32_t BluetoothHostProxy::GetBtProfileConnState(uint32_t profileId) +int32_t BluetoothHostProxy::GetBtProfileConnState(uint32_t profileId, int &state) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetBtProfileConnState WriteInterfaceToken error"); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteUint32(profileId)) { HILOGE("BluetoothHostProxy::GetBtProfileConnState WriteInterfaceToken error"); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_GET_BT_PROFILE_CONNSTATE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetBtProfileConnState done fail, error: %{public}d", error); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } - int32_t state; - if (!reply.ReadInt32(state)) { - HILOGE("BluetoothHostProxy::GetBtProfileConnState Read reply fail"); - return -1; + int32_t exception = reply.ReadInt32(); + if (exception == BT_SUCCESS) { + state = reply.ReadInt32(); } - return state; + return exception; } int32_t BluetoothHostProxy::GetLocalDeviceClass() @@ -380,94 +402,92 @@ bool BluetoothHostProxy::SetLocalDeviceClass(const int32_t &deviceClass) return reply.ReadBool(); } -std::string BluetoothHostProxy::GetLocalName() +int32_t BluetoothHostProxy::GetLocalName(std::string &name) { - std::string Name; MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetLocalName WriteInterfaceToken error"); - return ""; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_GET_LOCAL_NAME, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetLocalName done fail, error: %{public}d", error); - return ""; + return BT_ERR_IPC_TRANS_FAILED; } - if (!reply.ReadString(Name)) { - HILOGE("BluetoothHostProxy::GetLocalName Read reply fail"); - return ""; + int32_t exception = reply.ReadInt32(); + if (exception == BT_SUCCESS) { + name = reply.ReadString(); } - return Name; + return exception; } -bool BluetoothHostProxy::SetLocalName(const std::string &name) +int32_t BluetoothHostProxy::SetLocalName(const std::string &name) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::SetLocalName WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(name)) { HILOGE("BluetoothHostProxy::SetLocalName WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_SET_LOCAL_NAME, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::SetLocalName done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } -int32_t BluetoothHostProxy::GetBtScanMode() +int32_t BluetoothHostProxy::GetBtScanMode(int32_t &scanMode) { - int32_t Mode; MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetBtScanMode WriteInterfaceToken error"); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_GET_BT_SCAN_MODE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetBtScanMode done fail, error: %{public}d", error); - return -1; + return BT_ERR_IPC_TRANS_FAILED; } - if (!reply.ReadInt32(Mode)) { - HILOGE("BluetoothHostProxy::GetBtScanMode Read reply fail"); - return -1; + int32_t exception = reply.ReadInt32(); + if (exception == BT_SUCCESS) { + scanMode = reply.ReadInt32(); } - return Mode; + return exception; } -bool BluetoothHostProxy::SetBtScanMode(int32_t mode, int32_t duration) +int32_t BluetoothHostProxy::SetBtScanMode(int32_t mode, int32_t duration) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::SetBtScanMode WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(mode)) { HILOGE("BluetoothHostProxy::SetBtScanMode WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(duration)) { HILOGE("BluetoothHostProxy::SetBtScanMode WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_SET_BT_SCAN_MODE, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::SetBtScanMode done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } int32_t BluetoothHostProxy::GetBondableMode(const int32_t transport) @@ -521,39 +541,39 @@ bool BluetoothHostProxy::SetBondableMode(int32_t transport, int32_t mode) return reply.ReadBool(); } -bool BluetoothHostProxy::StartBtDiscovery() +int32_t BluetoothHostProxy::StartBtDiscovery() { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::StartBtDiscovery WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_START_BT_DISCOVERY, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::StartBtDiscovery done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } -bool BluetoothHostProxy::CancelBtDiscovery() +int32_t BluetoothHostProxy::CancelBtDiscovery() { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::CancelBtDiscovery WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_CANCEL_BT_DISCOVERY, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::CancelBtDiscovery done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } bool BluetoothHostProxy::IsBtDiscovering(const int32_t transport) @@ -596,59 +616,59 @@ long BluetoothHostProxy::GetBtDiscoveryEndMillis() return millis; } -std::vector BluetoothHostProxy::GetPairedDevices(const int32_t transport) +int32_t BluetoothHostProxy::GetPairedDevices(const int32_t transport, std::vector &pairedAddr) { std::vector vec; MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetPairedDevices WriteInterfaceToken error"); - return vec; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(transport)) { HILOGE("BluetoothHostProxy::GetPairedDevices WriteInterfaceToken error"); - return vec; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_GET_PAIRED_DEVICES, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetPairedDevices done fail, error: %{public}d", error); - return vec; + return BT_ERR_IPC_TRANS_FAILED; } int32_t size = reply.ReadInt32(); for (int32_t i = 0; i < size; i++) { std::shared_ptr rawAddress(reply.ReadParcelable()); if (!rawAddress) { - return vec; + return BT_ERR_IPC_TRANS_FAILED; } - vec.push_back(*rawAddress); + pairedAddr.push_back(*rawAddress); } - return vec; + return reply.ReadInt32(); } -bool BluetoothHostProxy::RemovePair(const int32_t transport, const sptr &device) +int32_t BluetoothHostProxy::RemovePair(const int32_t transport, const sptr &device) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::RemovePair WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(transport)) { HILOGE("BluetoothHostProxy::RemovePair WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteStrongParcelable(device)) { HILOGE("BluetoothHostProxy::RemovePair WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::BT_REMOVE_PAIR, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::RemovePair done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } bool BluetoothHostProxy::RemoveAllPairs() @@ -866,29 +886,34 @@ int32_t BluetoothHostProxy::GetPowerMode(const std::string &address) return reply.ReadInt32(); } -std::string BluetoothHostProxy::GetDeviceName(int32_t transport, const std::string &address) +int32_t BluetoothHostProxy::GetDeviceName(int32_t transport, const std::string &address, std::string &name) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetDeviceName WriteInterfaceToken error"); - return std::string(); + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(transport)) { HILOGE("BluetoothHostProxy::GetDeviceName transport error"); - return std::string(); + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(address)) { HILOGE("BluetoothHostProxy::GetDeviceName address error"); - return std::string(); + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::GET_DEVICE_NAME, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetDeviceName done fail, error: %{public}d", error); - return std::string(); + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadString(); + + int32_t exception = reply.ReadInt32(); + if (exception == BT_SUCCESS) { + name = reply.ReadString(); + } + return exception; } std::string BluetoothHostProxy::GetDeviceAlias(const std::string &address) @@ -983,29 +1008,29 @@ int32_t BluetoothHostProxy::GetPairState(int32_t transport, const std::string &a return reply.ReadInt32(); } -bool BluetoothHostProxy::StartPair(int32_t transport, const std::string &address) +int32_t BluetoothHostProxy::StartPair(int32_t transport, const std::string &address) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::StartPair WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(transport)) { HILOGE("BluetoothHostProxy::StartPair transport error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(address)) { HILOGE("BluetoothHostProxy::StartPair address error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::START_PAIR, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::StartPair done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } bool BluetoothHostProxy::CancelPairing(int32_t transport, const std::string &address) @@ -1108,29 +1133,29 @@ bool BluetoothHostProxy::IsAclEncrypted(int32_t transport, const std::string &ad return reply.ReadBool(); } -int32_t BluetoothHostProxy::GetDeviceClass(const std::string &address) +int32_t BluetoothHostProxy::GetDeviceClass(const std::string &address, int &cod) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::GetDeviceClass WriteInterfaceToken error"); - return 0; + return BT_ERR_INTERNAL_ERROR; } if (!data.WriteString(address)) { HILOGE("BluetoothHostProxy::GetDeviceClass address error"); - return 0; + return BT_ERR_INTERNAL_ERROR; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::GET_DEVICE_CLASS, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::GetDeviceClass done fail, error: %{public}d", error); - return 0; + return BT_ERR_IPC_TRANS_FAILED; } - int32_t cod = 0; - if (!reply.ReadInt32(cod)) { - HILOGE("BluetoothHostProxy::GetDeviceClass get cod failed."); + int32_t exception = reply.ReadInt32(); + if (exception == BT_SUCCESS) { + cod = reply.ReadInt32(); } - return cod; + return exception; } bool BluetoothHostProxy::SetDevicePin(const std::string &address, const std::string &pin) @@ -1158,33 +1183,33 @@ bool BluetoothHostProxy::SetDevicePin(const std::string &address, const std::str return reply.ReadBool(); } -bool BluetoothHostProxy::SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) +int32_t BluetoothHostProxy::SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { HILOGE("BluetoothHostProxy::SetDevicePairingConfirmation WriteInterfaceToken error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteInt32(transport)) { HILOGE("BluetoothHostProxy::SetDevicePairingConfirmation transport error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteString(address)) { HILOGE("BluetoothHostProxy::SetDevicePairingConfirmation address error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteBool(accept)) { HILOGE("BluetoothHostProxy::SetDevicePairingConfirmation accept error"); - return false; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int32_t error = InnerTransact(IBluetoothHost::Code::SET_DEVICE_PAIRING_CONFIRMATION, option, data, reply); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothHostProxy::SetDevicePairingConfirmation done fail, error: %{public}d", error); - return false; + return BT_ERR_IPC_TRANS_FAILED; } - return reply.ReadBool(); + return reply.ReadInt32(); } bool BluetoothHostProxy::SetDevicePasskey(int32_t transport, const std::string &address, int32_t passkey, bool accept) diff --git a/services/bluetooth/ipc/src/bluetooth_host_stub.cpp b/services/bluetooth/ipc/src/bluetooth_host_stub.cpp index db4bace4..6951c0f2 100644 --- a/services/bluetooth/ipc/src/bluetooth_host_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_host_stub.cpp @@ -15,6 +15,7 @@ #include "bluetooth_host_stub.h" #include "bluetooth_log.h" +#include "bluetooth_errorcode.h" #include "ipc_types.h" #include "raw_address.h" #include "string_ex.h" @@ -56,6 +57,9 @@ const std::map result = GetPairedDevices(transport); + std::vector pairDevice; + int32_t result = GetPairedDevices(transport, pairDevice); bool ret = true; - if (!reply.WriteInt32(result.size())) { + if (!reply.WriteInt32(pairDevice.size())) { HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); - ret = false; + return BT_ERR_IPC_TRANS_FAILED; } else { - for (auto device : result) { + for (auto device : pairDevice) { reply.WriteParcelable(&device); } } + ret = reply.WriteInt32(result); if (!ret) { HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + return BT_SUCCESS; } -ErrCode BluetoothHostStub::StartPairInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHostStub::StartPairInner(MessageParcel &data, MessageParcel &reply) { int32_t transport; if (!data.ReadInt32(transport)) { HILOGE("BluetoothHostStub::StartPair transport failed"); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } std::string address; if (!data.ReadString(address)) { HILOGE("BluetoothHostStub::StartPair address failed"); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - bool result = StartPair(transport, address); - bool ret = reply.WriteBool(result); + int32_t result = StartPair(transport, address); + bool ret = reply.WriteInt32(result); if (!ret) { HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + return BT_SUCCESS; } -ErrCode BluetoothHostStub::RemovePairInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHostStub::RemovePairInner(MessageParcel &data, MessageParcel &reply) { int32_t transport = data.ReadInt32(); sptr device = data.ReadStrongParcelable(); - bool result = RemovePair(transport, device); + int32_t result = RemovePair(transport, device); bool ret = reply.WriteInt32(result); if (!ret) { HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); @@ -975,46 +1019,52 @@ ErrCode BluetoothHostStub::IsAclEncryptedInner(MessageParcel &data, MessageParce return NO_ERROR; } -ErrCode BluetoothHostStub::GetDeviceClassInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHostStub::GetDeviceClassInner(MessageParcel &data, MessageParcel &reply) { std::string address; if (!data.ReadString(address)) { HILOGE("BluetoothHostStub::GetDeviceClass address failed"); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - int result = GetDeviceClass(address); + int32_t cod = 0; + int result = GetDeviceClass(address, cod); bool ret = reply.WriteInt32(result); if (!ret) { HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + ret = reply.WriteInt32(cod); + if (!ret) { + HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); + return BT_ERR_IPC_TRANS_FAILED; + } + return BT_SUCCESS; } -ErrCode BluetoothHostStub::SetDevicePairingConfirmationInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothHostStub::SetDevicePairingConfirmationInner(MessageParcel &data, MessageParcel &reply) { int32_t transport; if (!data.ReadInt32(transport)) { HILOGE("BluetoothHostStub::SetDevicePairingConfirmation transport failed"); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } std::string address; if (!data.ReadString(address)) { HILOGE("BluetoothHostStub::SetDevicePairingConfirmation address failed"); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } bool accept = false; if (!data.ReadBool(accept)) { HILOGE("BluetoothHostStub::SetDevicePairingConfirmation accept failed"); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - bool result = SetDevicePairingConfirmation(transport, address, accept); - bool ret = reply.WriteBool(result); + int32_t result = SetDevicePairingConfirmation(transport, address, accept); + bool ret = reply.WriteInt32(result); if (!ret) { HILOGE("BluetoothHostStub: reply writing failed in: %{public}s.", __func__); - return TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } - return NO_ERROR; + return BT_SUCCESS; } ErrCode BluetoothHostStub::SetDevicePasskeyInner(MessageParcel &data, MessageParcel &reply) diff --git a/services/bluetooth/ipc/src/bluetooth_map_mse_observer_stub.cpp b/services/bluetooth/ipc/src/bluetooth_map_mse_observer_stub.cpp index 743842a0..4ee978a5 100644 --- a/services/bluetooth/ipc/src/bluetooth_map_mse_observer_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_map_mse_observer_stub.cpp @@ -37,12 +37,10 @@ BluetoothMapMseObserverStub::~BluetoothMapMseObserverStub() int BluetoothMapMseObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOGD("BluetoothMapMseObserverStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", + HILOGI("BluetoothMapMseObserverStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothMapMseObserverStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothMapMseObserverStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGI("local descriptor is not equal to remote"); return ERR_INVALID_STATE; } diff --git a/services/bluetooth/ipc/src/bluetooth_opp_observer_stub.cpp b/services/bluetooth/ipc/src/bluetooth_opp_observer_stub.cpp index 33957268..9a63e5e8 100644 --- a/services/bluetooth/ipc/src/bluetooth_opp_observer_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_opp_observer_stub.cpp @@ -26,9 +26,7 @@ int BluetoothOppObserverStub::OnRemoteRequest( HILOGI("BluetoothOppObserverStub OnRemoteRequest start"); switch (code) { case COMMAND_ON_RECEIVE_INCOMING_FILE_CHANGED: { - std::u16string descriptor = BluetoothOppObserverStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothOppObserverStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGE("local descriptor is not equal to remote"); return IPC_INVOKER_TRANSLATE_ERR; } @@ -42,9 +40,7 @@ int BluetoothOppObserverStub::OnRemoteRequest( return NO_ERROR; } case COMMAND_ON_TRANSFER_STATE_CHANGED: { - std::u16string descriptor = BluetoothOppObserverStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothOppObserverStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGE("local descriptor is not equal to remote"); return IPC_INVOKER_TRANSLATE_ERR; } diff --git a/services/bluetooth/ipc/src/bluetooth_pan_observer_stub.cpp b/services/bluetooth/ipc/src/bluetooth_pan_observer_stub.cpp index 07769af0..7112dc2c 100644 --- a/services/bluetooth/ipc/src/bluetooth_pan_observer_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_pan_observer_stub.cpp @@ -25,9 +25,7 @@ int BluetoothPanObserverStub::OnRemoteRequest( { switch (code) { case COMMAND_ON_CONNECTION_STATE_CHANGED: { - std::u16string descriptor = BluetoothPanObserverStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + if (BluetoothPanObserverStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGE("local descriptor is not equal to remote"); return IPC_INVOKER_TRANSLATE_ERR; } diff --git a/services/bluetooth/ipc/src/bluetooth_pan_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_pan_proxy.cpp index c0f1ccac..cceee436 100644 --- a/services/bluetooth/ipc/src/bluetooth_pan_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_pan_proxy.cpp @@ -12,22 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "bluetooth_errorcode.h" #include "bluetooth_pan_proxy.h" #include "bluetooth_log.h" #include "refbase.h" namespace OHOS { namespace Bluetooth { -ErrCode BluetoothPanProxy::Disconnect(const BluetoothRawAddress &device, bool& result) +int32_t BluetoothPanProxy::Disconnect(const BluetoothRawAddress &device) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothPanProxy::GetDescriptor())) { HILOGE("BluetoothPanProxy::Disconnect WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { HILOGE("BluetoothPanProxy::Disconnect write device error"); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -36,25 +37,23 @@ ErrCode BluetoothPanProxy::Disconnect(const BluetoothRawAddress &device, bool& r }; int error = Remote()->SendRequest(COMMAND_DISCONNECT, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothPanProxy::Disconnect done fail, error: %{public}d", error); - return error; + return BT_ERR_IPC_TRANS_FAILED; } - - result = reply.ReadInt32() == NO_ERROR ? true : false; - return ERR_OK; + return reply.ReadInt32(); } -ErrCode BluetoothPanProxy::GetDeviceState(const BluetoothRawAddress &device, int& result) +int32_t BluetoothPanProxy::GetDeviceState(const BluetoothRawAddress &device, int32_t &state) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothPanProxy::GetDescriptor())) { - HILOGE("BluetoothPanProxy::GetDeviceState WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + HILOGE("WriteInterfaceToken error"); + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteParcelable(&device)) { - HILOGE("BluetoothPanProxy::GetDeviceState write device error"); - return INVALID_DATA; + HILOGE("write device error"); + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -63,46 +62,57 @@ ErrCode BluetoothPanProxy::GetDeviceState(const BluetoothRawAddress &device, int }; int error = Remote()->SendRequest(COMMAND_GET_DEVICE_STATE, data, reply, option); - if (error != NO_ERROR) { - HILOGE("BluetoothPanProxy::GetDeviceState done fail, error: %{public}d", error); - return error; - } - - ErrCode ec = reply.ReadInt32(); - if (FAILED(ec)) { - return ec; - } - - result = reply.ReadInt32(); - return ERR_OK; + if (error != BT_SUCCESS) { + HILOGE("done fail, error: %{public}d", error); + return BT_ERR_IPC_TRANS_FAILED; + } + // read error code + int32_t errCode = reply.ReadInt32(); + if (errCode != BT_SUCCESS) { + HILOGE("reply errCode: %{public}d", errCode); + return errCode; + } + // read state + state = reply.ReadInt32(); + return BT_SUCCESS; } -ErrCode BluetoothPanProxy::GetDevicesByStates(const std::vector &states, +int32_t BluetoothPanProxy::GetDevicesByStates(const std::vector &states, std::vector& result) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothPanProxy::GetDescriptor())) { - HILOGE("BluetoothPanProxy::GetDevicesByStates WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + HILOGE("WriteInterfaceToken error"); + return BT_ERR_IPC_TRANS_FAILED; } if (!WriteParcelableInt32Vector(states, data)) { - HILOGE("[GetDevicesByStates] fail: write result failed"); - return INVALID_DATA; + HILOGE("write result failed"); + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; int error = Remote()->SendRequest(COMMAND_GET_DEVICES_BY_STATES, data, reply, option); - if (error != NO_ERROR) { - HILOGE("BluetoothPanProxy::GetDevicesByStates done fail, error: %{public}d", error); - return INVALID_DATA; + if (error != BT_SUCCESS) { + HILOGE("SendRequest failed, error: %{public}d", error); + return BT_ERR_IPC_TRANS_FAILED; + } + // read error code + int32_t errCode = reply.ReadInt32(); + if (errCode != BT_SUCCESS) { + HILOGE("reply errCode: %{public}d", errCode); + return errCode; } + + // read size int32_t rawAddsSize = reply.ReadInt32(); + + // read devices for (int i = 0; i < rawAddsSize; i++) { std::unique_ptr address(reply.ReadParcelable()); result.push_back(*address); } - return ERR_OK; + return BT_SUCCESS; } ErrCode BluetoothPanProxy::RegisterObserver( @@ -157,17 +167,16 @@ ErrCode BluetoothPanProxy::DeregisterObserver( return error; } -ErrCode BluetoothPanProxy::SetTethering( - const bool value, bool& result) +int32_t BluetoothPanProxy::SetTethering(const bool value) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothPanProxy::GetDescriptor())) { HILOGE("BluetoothPanProxy::SetTethering WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } if (!data.WriteBool(value)) { HILOGE("BluetoothPanProxy::SetTethering error"); - return INVALID_DATA; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -176,26 +185,19 @@ ErrCode BluetoothPanProxy::SetTethering( }; int error = Remote()->SendRequest(COMMAND_SET_TETHERING, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothPanProxy::SetTethering done fail, error: %{public}d", error); - return INVALID_DATA; - } - ErrCode ec = reply.ReadInt32(); - if (FAILED(ec)) { - return ec; + return BT_ERR_IPC_TRANS_FAILED; } - - result = reply.ReadInt32(); - return error; + return reply.ReadInt32(); } -ErrCode BluetoothPanProxy::IsTetheringOn( - bool& result) +int32_t BluetoothPanProxy::IsTetheringOn(bool &result) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothPanProxy::GetDescriptor())) { HILOGE("BluetoothPanProxy::IsTetheringOn WriteInterfaceToken error"); - return IPC_PROXY_TRANSACTION_ERR; + return BT_ERR_IPC_TRANS_FAILED; } MessageParcel reply; @@ -204,18 +206,19 @@ ErrCode BluetoothPanProxy::IsTetheringOn( }; int error = Remote()->SendRequest(COMMAND_IS_TETHERING_ON, data, reply, option); - if (error != NO_ERROR) { + if (error != BT_SUCCESS) { HILOGE("BluetoothPanProxy::IsTetheringOn done fail, error: %{public}d", error); - return error; + return BT_ERR_IPC_TRANS_FAILED; } - ErrCode ec = reply.ReadInt32(); - if (FAILED(ec)) { - return ec; + int32_t ret = reply.ReadInt32(); + if (ret != BT_SUCCESS) { + HILOGE("internal error. ret:%{public}d", ret); + return ret; } result = reply.ReadInt32(); - return ERR_OK; + return BT_SUCCESS; } bool BluetoothPanProxy::WriteParcelableInt32Vector( diff --git a/services/bluetooth/ipc/src/bluetooth_pan_stub.cpp b/services/bluetooth/ipc/src/bluetooth_pan_stub.cpp index 59786922..c845b12b 100644 --- a/services/bluetooth/ipc/src/bluetooth_pan_stub.cpp +++ b/services/bluetooth/ipc/src/bluetooth_pan_stub.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "bluetooth_errorcode.h" #include "bluetooth_pan_stub.h" #include "bluetooth_log.h" @@ -19,7 +20,7 @@ namespace OHOS { namespace Bluetooth { BluetoothPanStub::BluetoothPanStub() { - HILOGD("%{public}s start.", __func__); + HILOGD("start."); memberFuncMap_[static_cast(COMMAND_DISCONNECT)] = &BluetoothPanStub::DisconnectInner; memberFuncMap_[static_cast(COMMAND_GET_DEVICE_STATE)] = @@ -34,22 +35,20 @@ BluetoothPanStub::BluetoothPanStub() &BluetoothPanStub::SetTetheringInner; memberFuncMap_[static_cast(COMMAND_IS_TETHERING_ON)] = &BluetoothPanStub::IsTetheringOnInner; - HILOGD("%{public}s ends.", __func__); + HILOGD("ends."); } BluetoothPanStub::~BluetoothPanStub() { - HILOGD("%{public}s start.", __func__); + HILOGD("start."); memberFuncMap_.clear(); } int BluetoothPanStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - HILOGD("BluetoothPanStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); - std::u16string descriptor = BluetoothPanStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { + HILOGI("BluetoothPanStub::OnRemoteRequest, cmd = %{public}d, flags= %{public}d", code, option.GetFlags()); + if (BluetoothPanStub::GetDescriptor() != data.ReadInterfaceToken()) { HILOGE("local descriptor is not equal to remote"); return IPC_INVOKER_TRANSLATE_ERR; } @@ -64,53 +63,71 @@ int BluetoothPanStub::OnRemoteRequest( return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } -ErrCode BluetoothPanStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothPanStub::DisconnectInner(MessageParcel &data, MessageParcel &reply) { - const BluetoothRawAddress *device = data.ReadParcelable(); - bool result; - HILOGD("BluetoothPanStub::DisconnectInner"); - ErrCode ec = Disconnect(*device, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - reply.WriteInt32(NO_ERROR); + std::shared_ptr device(data.ReadParcelable()); + int32_t errCode = Disconnect(*device); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - return ERR_NONE; + return BT_SUCCESS; } -ErrCode BluetoothPanStub::GetDeviceStateInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothPanStub::GetDeviceStateInner(MessageParcel &data, MessageParcel &reply) { - const BluetoothRawAddress *device = data.ReadParcelable(); - int result; - HILOGD("BluetoothPanStub::GetDeviceStateInner"); - ErrCode ec = GetDeviceState(*device, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - reply.WriteInt32(result); + std::shared_ptr device(data.ReadParcelable()); + int32_t state; + int32_t errCode = GetDeviceState(*device, state); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - return ERR_NONE; + if (errCode != BT_SUCCESS) { + HILOGE("internal error."); + return BT_ERR_INTERNAL_ERROR; + } + // write state + if (!reply.WriteInt32(state)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + return BT_SUCCESS; } -ErrCode BluetoothPanStub::GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothPanStub::GetDevicesByStatesInner(MessageParcel &data, MessageParcel &reply) { std::vector states = {}; int32_t stateSize = data.ReadInt32(); - HILOGD("BluetoothPanStub::GetDevicesByStatesInner"); for (int i = 0; i < stateSize; i++) { int32_t state = data.ReadInt32(); states.push_back(state); } std::vector rawAdds; - ErrCode ec = GetDevicesByStates(states, rawAdds); - if (ec != ERR_OK) { - return ec; + int32_t errCode = GetDevicesByStates(states, rawAdds); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + if (errCode != BT_SUCCESS) { + HILOGE("internal error."); + return BT_ERR_INTERNAL_ERROR; + } + // write size + if (!reply.WriteInt32(rawAdds.size())) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - reply.WriteInt32(rawAdds.size()); + // write devices for (auto rawAdd : rawAdds) { if (!reply.WriteParcelable(&rawAdd)) { - return ERR_INVALID_STATE; + return BT_ERR_IPC_TRANS_FAILED; } } - return ERR_NONE; + return BT_SUCCESS; } ErrCode BluetoothPanStub::RegisterObserverInner(MessageParcel &data, MessageParcel &reply) @@ -131,29 +148,38 @@ ErrCode BluetoothPanStub::DeregisterObserverInner(MessageParcel &data, MessagePa return NO_ERROR; } -ErrCode BluetoothPanStub::SetTetheringInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothPanStub::SetTetheringInner(MessageParcel &data, MessageParcel &reply) { - HILOGD("BluetoothPanStub::SetTetheringInner"); const bool value = data.ReadBool(); - bool result; - ErrCode ec = SetTethering(value, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - reply.WriteInt32(result); + int32_t errCode = SetTethering(value); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - return ERR_NONE; + return BT_SUCCESS; } -ErrCode BluetoothPanStub::IsTetheringOnInner(MessageParcel &data, MessageParcel &reply) +int32_t BluetoothPanStub::IsTetheringOnInner(MessageParcel &data, MessageParcel &reply) { - bool result; - HILOGD("BluetoothPanStub::IsTetheringOnInner"); - ErrCode ec = IsTetheringOn(result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - reply.WriteInt32(result); + bool result = false; + int32_t errCode = IsTetheringOn(result); + // write error code + if (!reply.WriteInt32(errCode)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; } - return ERR_NONE; + if (errCode != BT_SUCCESS) { + HILOGE("internal error."); + return BT_ERR_INTERNAL_ERROR; + } + // write result + if (!reply.WriteInt32(result)) { + HILOGE("reply write failed."); + return BT_ERR_IPC_TRANS_FAILED; + } + + return BT_SUCCESS; } } // namespace Bluetooth } // namespace OHOS \ No newline at end of file diff --git a/services/bluetooth/ipc/src/bluetooth_socket_proxy.cpp b/services/bluetooth/ipc/src/bluetooth_socket_proxy.cpp index c097c8e1..b16836ec 100644 --- a/services/bluetooth/ipc/src/bluetooth_socket_proxy.cpp +++ b/services/bluetooth/ipc/src/bluetooth_socket_proxy.cpp @@ -66,31 +66,31 @@ int BluetoothSocketProxy::Connect(std::string &addr, bluetooth::Uuid &uuid, int3 int BluetoothSocketProxy::Listen(std::string &name, bluetooth::Uuid &uuid, int32_t securityFlag, int32_t type) { - HILOGI("BluetoothSocketProxy::Listen starts"); + HILOGI("Listen starts"); MessageParcel data; if (!data.WriteInterfaceToken(BluetoothSocketProxy::GetDescriptor())) { - HILOGE("BluetoothSocketProxy::Listen WriteInterfaceToken error"); - return ERROR; + HILOGE("WriteInterfaceToken error"); + return BT_INVALID_SOCKET_FD; } if (!data.WriteString(name)) { - HILOGE("BluetoothSocketProxy::Listen write name error"); - return ERROR; + HILOGE("write name error"); + return BT_INVALID_SOCKET_FD; } BluetoothUuid btUuid(uuid); if (!data.WriteParcelable(&btUuid)) { - HILOGE("BluetoothSocketProxy::Listen write uuid error"); - return ERROR; + HILOGE("write uuid error"); + return BT_INVALID_SOCKET_FD; } if (!data.WriteInt32(securityFlag)) { - HILOGE("BluetoothSocketProxy::Listen write securityFlag error"); - return ERROR; + HILOGE("write securityFlag error"); + return BT_INVALID_SOCKET_FD; } if (!data.WriteInt32(type)) { - HILOGE("BluetoothSocketProxy::Listen write type error"); - return ERROR; + HILOGE("write type error"); + return BT_INVALID_SOCKET_FD; } MessageParcel reply; @@ -100,8 +100,8 @@ int BluetoothSocketProxy::Listen(std::string &name, bluetooth::Uuid &uuid, int32 int error = Remote()->SendRequest(BluetoothSocketProxy::Code::SOCKET_LISTEN, data, reply, option); if (error != NO_ERROR) { - HILOGE("BluetoothSocketProxy::Listen done fail, error: %{public}d", error); - return ERROR; + HILOGE("Listen done fail, error: %{public}d", error); + return BT_INVALID_SOCKET_FD; } return reply.ReadFileDescriptor(); diff --git a/services/bluetooth/server/BUILD.gn b/services/bluetooth/server/BUILD.gn index 453c49e7..fb2d622d 100644 --- a/services/bluetooth/server/BUILD.gn +++ b/services/bluetooth/server/BUILD.gn @@ -20,7 +20,7 @@ BT_ROOT = "//foundation/communication/bluetooth/services/bluetooth" ohos_shared_library("bluetooth_server") { sanitize = { cfi = true - # blocklist = "./bluetooth_server_blocklist.txt" + blocklist = "./bluetooth_server_blocklist.txt" } stack_protector_ret = true include_dirs = [ diff --git a/services/bluetooth/server/bluetooth_server_blocklist.txt b/services/bluetooth/server/bluetooth_server_blocklist.txt new file mode 100644 index 00000000..04c41f2b --- /dev/null +++ b/services/bluetooth/server/bluetooth_server_blocklist.txt @@ -0,0 +1,16 @@ +# Copyright (C) 2022-2022 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. + +[cfi] +# xmlFree check failed for CFI. +src:*/bluetooth/services/bluetooth/server/src/bluetooth_a2dp_source_server.cpp diff --git a/services/bluetooth/server/include/bluetooth_a2dp_sink_server.h b/services/bluetooth/server/include/bluetooth_a2dp_sink_server.h index e1184fef..c7f4e424 100644 --- a/services/bluetooth/server/include/bluetooth_a2dp_sink_server.h +++ b/services/bluetooth/server/include/bluetooth_a2dp_sink_server.h @@ -38,7 +38,7 @@ public: int Disconnect(const RawAddress &device) override; int GetDeviceState(const RawAddress &device) override; std::vector GetDevicesByStates(const std::vector &states) override; - int GetPlayingState(const RawAddress &device) override; + int GetPlayingState(const RawAddress &device, int &state) override; int SetConnectStrategy(const RawAddress &device, int strategy) override; int GetConnectStrategy(const RawAddress &device) override; int SendDelay(const RawAddress &device, int32_t delayValue) override; diff --git a/services/bluetooth/server/include/bluetooth_a2dp_source_server.h b/services/bluetooth/server/include/bluetooth_a2dp_source_server.h index 0e2084ea..ffd93a82 100644 --- a/services/bluetooth/server/include/bluetooth_a2dp_source_server.h +++ b/services/bluetooth/server/include/bluetooth_a2dp_source_server.h @@ -38,7 +38,7 @@ public: int Disconnect(const RawAddress &device) override; int GetDeviceState(const RawAddress &device) override; std::vector GetDevicesByStates(const std::vector &states) override; - int GetPlayingState(const RawAddress &device) override; + int GetPlayingState(const RawAddress &device, int &state) override; int SetConnectStrategy(const RawAddress &device, int strategy) override; int GetConnectStrategy(const RawAddress &device) override; int SetActiveSinkDevice(const RawAddress &device) override; diff --git a/services/bluetooth/server/include/bluetooth_ble_advertiser_server.h b/services/bluetooth/server/include/bluetooth_ble_advertiser_server.h index ab182204..b295a844 100644 --- a/services/bluetooth/server/include/bluetooth_ble_advertiser_server.h +++ b/services/bluetooth/server/include/bluetooth_ble_advertiser_server.h @@ -31,10 +31,10 @@ public: virtual void RegisterBleAdvertiserCallback(const sptr &callback) override; virtual void DeregisterBleAdvertiserCallback(const sptr &callback) override; - virtual void StartAdvertising(const BluetoothBleAdvertiserSettings &settings, + virtual int StartAdvertising(const BluetoothBleAdvertiserSettings &settings, const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle, bool isRawData) override; - virtual void StopAdvertising(int32_t advHandle) override; + virtual int StopAdvertising(int32_t advHandle) override; virtual void Close(int32_t advHandle) override; virtual int32_t GetAdvertiserHandle() override; diff --git a/services/bluetooth/server/include/bluetooth_ble_central_manager_server.h b/services/bluetooth/server/include/bluetooth_ble_central_manager_server.h index 89177155..2b52b1d3 100644 --- a/services/bluetooth/server/include/bluetooth_ble_central_manager_server.h +++ b/services/bluetooth/server/include/bluetooth_ble_central_manager_server.h @@ -36,9 +36,9 @@ public: virtual void RegisterBleCentralManagerCallback(const sptr &callback) override; virtual void DeregisterBleCentralManagerCallback( const sptr &callback) override; - virtual void StartScan() override; - virtual void StartScan(const BluetoothBleScanSettings &settings) override; - virtual void StopScan() override; + virtual int StartScan() override; + virtual int StartScan(const BluetoothBleScanSettings &settings) override; + virtual int StopScan() override; virtual int ConfigScanFilter(const int clientId, const std::vector &filters) override; virtual void RemoveScanFilter(const int clientId) override; virtual bool ProxyUid(int32_t uid, bool isProxy) override; diff --git a/services/bluetooth/server/include/bluetooth_gatt_client_server.h b/services/bluetooth/server/include/bluetooth_gatt_client_server.h index bb61a702..afee516e 100644 --- a/services/bluetooth/server/include/bluetooth_gatt_client_server.h +++ b/services/bluetooth/server/include/bluetooth_gatt_client_server.h @@ -31,6 +31,9 @@ public: explicit BluetoothGattClientServer(); ~BluetoothGattClientServer() override; + int RegisterApplication(const sptr &callback, const BluetoothRawAddress &addr, + int32_t transport, int &appId) override; + int RegisterApplication(const sptr &callback, const BluetoothRawAddress &addr, int32_t transport) override; int DeregisterApplication(int32_t appId) override; diff --git a/services/bluetooth/server/include/bluetooth_hfp_ag_server.h b/services/bluetooth/server/include/bluetooth_hfp_ag_server.h index acf04514..8a764d68 100644 --- a/services/bluetooth/server/include/bluetooth_hfp_ag_server.h +++ b/services/bluetooth/server/include/bluetooth_hfp_ag_server.h @@ -24,22 +24,22 @@ namespace OHOS { namespace Bluetooth { -class BluetoothHfpAgServer : public BluetoothHfpAgStub{ +class BluetoothHfpAgServer : public BluetoothHfpAgStub{ public: explicit BluetoothHfpAgServer(); ~BluetoothHfpAgServer() override; - int GetConnectDevices(std::vector &devices) override; + int32_t GetConnectDevices(std::vector &devices) override; int GetDevicesByStates(const std::vector &states, std::vector &devices) override; - int GetDeviceState(const BluetoothRawAddress &device) override; - int Connect(const BluetoothRawAddress &device) override; - int Disconnect(const BluetoothRawAddress &device) override; + int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) override; + int32_t Connect(const BluetoothRawAddress &device) override; + int32_t Disconnect(const BluetoothRawAddress &device) override; int GetScoState(const BluetoothRawAddress &device) override; bool ConnectSco() override; bool DisconnectSco() override; - void PhoneStateChanged(int numActive, int numHeld, int callState, const std::string &number, int type, + void PhoneStateChanged(int numActive, int numHeld, int callState, const std::string &number, int type, const std::string &name) override; - void ClccResponse(int index, int direction, int status, int mode, bool mpty, const std::string &number, + void ClccResponse(int index, int direction, int status, int mode, bool mpty, const std::string &number, int type) override; bool OpenVoiceRecognition(const BluetoothRawAddress &device) override; bool CloseVoiceRecognition(const BluetoothRawAddress &device) override; diff --git a/services/bluetooth/server/include/bluetooth_hid_host_server.h b/services/bluetooth/server/include/bluetooth_hid_host_server.h index b32b082c..c7ca897d 100644 --- a/services/bluetooth/server/include/bluetooth_hid_host_server.h +++ b/services/bluetooth/server/include/bluetooth_hid_host_server.h @@ -35,19 +35,16 @@ public: explicit BluetoothHidHostServer(); ~BluetoothHidHostServer() override; - ErrCode Connect( - const BluetoothRawAddress &device, - bool& result) override; + int32_t Connect( + const BluetoothRawAddress &device) override; - ErrCode Disconnect( - const BluetoothRawAddress &device, - bool& result) override; + int32_t Disconnect( + const BluetoothRawAddress &device) override; - ErrCode GetDeviceState( - const BluetoothRawAddress &device, - int& result) override; + int32_t GetDeviceState( + const BluetoothRawAddress &device, int32_t &state) override; - ErrCode GetDevicesByStates( + int32_t GetDevicesByStates( const std::vector &states, std::vector& result) override; diff --git a/services/bluetooth/server/include/bluetooth_host_server.h b/services/bluetooth/server/include/bluetooth_host_server.h index 8b69ea02..ee96a3a4 100644 --- a/services/bluetooth/server/include/bluetooth_host_server.h +++ b/services/bluetooth/server/include/bluetooth_host_server.h @@ -44,8 +44,8 @@ public: void RegisterObserver(const sptr &observer) override; void DeregisterObserver(const sptr &observer) override; bool EnableBt() override; - bool DisableBt() override; - int32_t GetBtState() override; + int32_t DisableBt() override; + int32_t GetBtState(int32_t &state) override; bool BluetoothFactoryReset() override; int32_t GetDeviceType(int32_t transport, const std::string &address) override; @@ -60,27 +60,28 @@ public: bool Start(); void Stop(); - bool DisableBle() override; - bool EnableBle() override; + int32_t DisableBle() override; + int32_t EnableBle() override; + bool IsBrEnabled() override; bool IsBleEnabled() override; std::vector GetProfileList() override; int32_t GetMaxNumConnectedAudioDevices() override; - int32_t GetBtConnectionState() override; - int32_t GetBtProfileConnState(uint32_t profileId) override; + int32_t GetBtConnectionState(int32_t &state) override; + int32_t GetBtProfileConnState(uint32_t profileId, int &state) override; int32_t GetLocalDeviceClass() override; bool SetLocalDeviceClass(const int32_t &deviceClass) override; - std::string GetLocalName() override; - bool SetLocalName(const std::string &name) override; - int32_t GetBtScanMode() override; - bool SetBtScanMode(int32_t mode, int32_t duration) override; + int32_t GetLocalName(std::string &name) override; + int32_t SetLocalName(const std::string &name) override; + int32_t GetBtScanMode(int32_t &scanMode) override; + int32_t SetBtScanMode(int32_t mode, int32_t duration) override; int32_t GetBondableMode(const int32_t transport) override; bool SetBondableMode(int32_t transport, int32_t mode) override; - bool StartBtDiscovery() override; - bool CancelBtDiscovery() override; + int32_t StartBtDiscovery() override; + int32_t CancelBtDiscovery() override; bool IsBtDiscovering(const int32_t transport) override; long GetBtDiscoveryEndMillis() override; - std::vector GetPairedDevices(const int32_t transport) override; - bool RemovePair(const int32_t transport, const sptr &device) override; + int32_t GetPairedDevices(const int32_t transport, std::vector &pairedAddr) override; + int32_t RemovePair(const int32_t transport, const sptr &device) override; bool RemoveAllPairs() override; void RegisterRemoteDeviceObserver(const sptr &observer) override; void DeregisterRemoteDeviceObserver(const sptr &observer) override; @@ -90,19 +91,19 @@ public: int32_t GetMessagePermission(const std::string &address) override; bool SetMessagePermission(const std::string &address, int32_t permission) override; int32_t GetPowerMode(const std::string &address) override; - std::string GetDeviceName(int32_t transport, const std::string &address) override; + int32_t GetDeviceName(int32_t transport, const std::string &address, std::string &name) override; std::string GetDeviceAlias(const std::string &address) override; bool SetDeviceAlias(const std::string &address, const std::string &aliasName) override; int32_t GetDeviceBatteryLevel(const std::string &address) override; int32_t GetPairState(int32_t transport, const std::string &address) override; - bool StartPair(int32_t transport, const std::string &address) override; + int32_t StartPair(int32_t transport, const std::string &address) override; bool CancelPairing(int32_t transport, const std::string &address) override; bool IsBondedFromLocal(int32_t transport, const std::string &address) override; bool IsAclConnected(int32_t transport, const std::string &address) override; bool IsAclEncrypted(int32_t transport, const std::string &address) override; - int32_t GetDeviceClass(const std::string &address) override; + int32_t GetDeviceClass(const std::string &address, int32_t &cod) override; bool SetDevicePin(const std::string &address, const std::string &pin) override; - bool SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) override; + int32_t SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) override; bool SetDevicePasskey(int32_t transport, const std::string &address, int32_t passkey, bool accept) override; bool PairRequestReply(int32_t transport, const std::string &address, bool accept) override; bool ReadRemoteRssiValue(const std::string &address) override; diff --git a/services/bluetooth/server/include/bluetooth_pan_server.h b/services/bluetooth/server/include/bluetooth_pan_server.h index e667ac08..65307103 100644 --- a/services/bluetooth/server/include/bluetooth_pan_server.h +++ b/services/bluetooth/server/include/bluetooth_pan_server.h @@ -35,15 +35,11 @@ public: BluetoothPanServer(); ~BluetoothPanServer() override; - ErrCode Disconnect( - const BluetoothRawAddress &device, - bool& result) override; + int32_t Disconnect(const BluetoothRawAddress &device) override; - ErrCode GetDeviceState( - const BluetoothRawAddress &device, - int& result) override; + int32_t GetDeviceState(const BluetoothRawAddress &device, int32_t &state) override; - ErrCode GetDevicesByStates( + int32_t GetDevicesByStates( const std::vector &states, std::vector& result) override; @@ -53,12 +49,9 @@ public: ErrCode DeregisterObserver( const sptr observer) override; - ErrCode SetTethering( - const bool enable, - bool& result) override; + int32_t SetTethering(const bool enable) override; - ErrCode IsTetheringOn( - bool& result) override; + int32_t IsTetheringOn(bool& result) override; private: BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothPanServer); diff --git a/services/bluetooth/server/src/bluetooth_a2dp_sink_server.cpp b/services/bluetooth/server/src/bluetooth_a2dp_sink_server.cpp old mode 100755 new mode 100644 index ac312784..6ccb0b2a --- a/services/bluetooth/server/src/bluetooth_a2dp_sink_server.cpp +++ b/services/bluetooth/server/src/bluetooth_a2dp_sink_server.cpp @@ -191,14 +191,14 @@ std::vector BluetoothA2dpSinkServer::GetDevicesByStates(const std::v return rawDevices; } -int BluetoothA2dpSinkServer::GetPlayingState(const RawAddress &device) +int BluetoothA2dpSinkServer::GetPlayingState(const RawAddress &device, int &state) { HILOGI("addr: %{public}s", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); return BT_FAILURE; } - return pimpl->a2dpSnkService_->GetPlayingState(device); + return pimpl->a2dpSnkService_->GetPlayingState(device, state); } int BluetoothA2dpSinkServer::SetConnectStrategy(const RawAddress &device, int strategy) diff --git a/services/bluetooth/server/src/bluetooth_a2dp_source_server.cpp b/services/bluetooth/server/src/bluetooth_a2dp_source_server.cpp old mode 100755 new mode 100644 index b842ea45..de7edce4 --- a/services/bluetooth/server/src/bluetooth_a2dp_source_server.cpp +++ b/services/bluetooth/server/src/bluetooth_a2dp_source_server.cpp @@ -14,6 +14,7 @@ */ #include "bluetooth_def.h" +#include "bluetooth_errorcode.h" #include "bluetooth_hitrace.h" #include "bluetooth_log.h" #include "bluetooth_utils_server.h" @@ -37,7 +38,7 @@ public: HILOGI("addr: %{public}s, state: %{public}d", GET_ENCRYPT_ADDR(device), state); if (state == static_cast(BTConnectState::CONNECTED) || state == static_cast(BTConnectState::DISCONNECTED)) { - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_A2DP_CONNECTED_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "A2DP_CONNECTED_STATE", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "STATE", state); } observers_->ForEach([device, state](sptr observer) { @@ -199,25 +200,25 @@ void BluetoothA2dpSourceServer::DeregisterObserver(const sptra2dpSrcService_->Connect(device); + int32_t result = pimpl->a2dpSrcService_->Connect(device); OHOS::Bluetooth::BluetoothHiTrace::BluetoothFinishAsyncTrace("A2DP_SRC_CONNECT", 1); return result; } -int BluetoothA2dpSourceServer::Disconnect(const RawAddress &device) +int32_t BluetoothA2dpSourceServer::Disconnect(const RawAddress &device) { HILOGI("addr: %{public}s", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("Disconnect error, check permission failed"); - return BT_FAILURE; + return BT_ERR_SYSTEM_PERMISSION_FAILED; } return pimpl->a2dpSrcService_->Disconnect(device); } @@ -250,14 +251,18 @@ std::vector BluetoothA2dpSourceServer::GetDevicesByStates(const std: return rawDevices; } -int BluetoothA2dpSourceServer::GetPlayingState(const RawAddress &device) +int32_t BluetoothA2dpSourceServer::GetPlayingState(const RawAddress &device, int &state) { HILOGI("addr: %{public}s", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return BT_FAILURE; + return BT_ERR_SYSTEM_PERMISSION_FAILED; + } + int ret = pimpl->a2dpSrcService_->GetPlayingState(device, state); + if (ret != BT_SUCCESS) { + return BT_ERR_INTERNAL_ERROR; } - return pimpl->a2dpSrcService_->GetPlayingState(device); + return BT_SUCCESS; } int BluetoothA2dpSourceServer::SetConnectStrategy(const RawAddress &device, int strategy) diff --git a/services/bluetooth/server/src/bluetooth_ble_advertiser_server.cpp b/services/bluetooth/server/src/bluetooth_ble_advertiser_server.cpp index fe39c805..78069dce 100644 --- a/services/bluetooth/server/src/bluetooth_ble_advertiser_server.cpp +++ b/services/bluetooth/server/src/bluetooth_ble_advertiser_server.cpp @@ -16,6 +16,7 @@ #include "bluetooth_ble_advertiser_server.h" #include "bluetooth_ble_central_manager_server.h" +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "interface_adapter_ble.h" #include "interface_adapter_manager.h" @@ -68,6 +69,8 @@ struct BluetoothBleAdvertiserServer::impl { impl(); ~impl(); + BleAdvertiserDataImpl ConvertAdvertisingData(const BluetoothBleAdvertiserData &data) const; + /// sys state observer class SystemStateObserver; std::unique_ptr systemStateObserver_ = nullptr; @@ -133,14 +136,36 @@ BluetoothBleAdvertiserServer::~BluetoothBleAdvertiserServer() IAdapterManager::GetInstance()->DeregisterSystemStateObserver(*(pimpl->systemStateObserver_)); } -void BluetoothBleAdvertiserServer::StartAdvertising(const BluetoothBleAdvertiserSettings &settings, +BleAdvertiserDataImpl BluetoothBleAdvertiserServer::impl::ConvertAdvertisingData( + const BluetoothBleAdvertiserData &data) const +{ + BleAdvertiserDataImpl outData; + + std::map manufacturerData = data.GetManufacturerData(); + for (auto iter = manufacturerData.begin(); iter != manufacturerData.end(); iter++) { + outData.AddManufacturerData(iter->first, iter->second); + } + std::map serviceData = data.GetServiceData(); + for (auto it = serviceData.begin(); it != serviceData.end(); it++) { + outData.AddServiceData(it->first, it->second); + } + std::vector serviceUuids = data.GetServiceUuids(); + for (auto it = serviceUuids.begin(); it != serviceUuids.end(); it++) { + outData.AddServiceUuid(*it); + } + outData.AddData(data.GetPayload()); + + return outData; +} + +int BluetoothBleAdvertiserServer::StartAdvertising(const BluetoothBleAdvertiserSettings &settings, const BluetoothBleAdvertiserData &advData, const BluetoothBleAdvertiserData &scanResponse, int32_t advHandle, bool isRawData) { HILOGI("enter"); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return; + return BT_ERR_PERMISSION_FAILED; } pimpl->bleService_ = @@ -153,51 +178,23 @@ void BluetoothBleAdvertiserServer::StartAdvertising(const BluetoothBleAdvertiser settingsImpl.SetLegacyMode(settings.IsLegacyMode()); settingsImpl.SetTxPower(settings.GetTxPower()); - BleAdvertiserDataImpl bleAdvertiserData; + BleAdvertiserDataImpl bleAdvertiserData = pimpl->ConvertAdvertisingData(advData); if (!isRawData) { bleAdvertiserData.SetFlags(advData.GetAdvFlag()); } - std::map manufacturerData = advData.GetManufacturerData(); - for (auto iter = manufacturerData.begin(); iter != manufacturerData.end(); iter++) { - bleAdvertiserData.AddManufacturerData(iter->first, iter->second); - } - std::map serviceData = advData.GetServiceData(); - for (auto it = serviceData.begin(); it != serviceData.end(); it++) { - bleAdvertiserData.AddServiceData(it->first, it->second); - } - std::vector serviceUuids = advData.GetServiceUuids(); - for (auto it = serviceUuids.begin(); it != serviceUuids.end(); it++) { - bleAdvertiserData.AddServiceUuid(*it); - } - bleAdvertiserData.AddData(advData.GetPayload()); + BleAdvertiserDataImpl bleScanResponse = pimpl->ConvertAdvertisingData(scanResponse); - BleAdvertiserDataImpl bleScanResponse; - manufacturerData = scanResponse.GetManufacturerData(); - for (auto it = manufacturerData.begin(); it != manufacturerData.end(); it++) { - bleScanResponse.AddManufacturerData(it->first, it->second); - } - serviceData = scanResponse.GetServiceData(); - for (auto it = serviceData.begin(); it != serviceData.end(); it++) { - bleScanResponse.AddServiceData(it->first, it->second); - } - serviceUuids = scanResponse.GetServiceUuids(); - for (auto it = serviceUuids.begin(); it != serviceUuids.end(); it++) { - bleScanResponse.AddServiceUuid(*it); - } - bleScanResponse.AddData(scanResponse.GetPayload()); - - if (pimpl->bleService_ != nullptr) { - pimpl->bleService_->StartAdvertising(settingsImpl, bleAdvertiserData, bleScanResponse, advHandle); - } + pimpl->bleService_->StartAdvertising(settingsImpl, bleAdvertiserData, bleScanResponse, advHandle); } + return BT_SUCCESS; } -void BluetoothBleAdvertiserServer::StopAdvertising(int32_t advHandle) +int BluetoothBleAdvertiserServer::StopAdvertising(int32_t advHandle) { HILOGI("enter, advHandle: %{public}d", advHandle); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return; + return BT_ERR_PERMISSION_FAILED; } pimpl->bleService_ = @@ -206,6 +203,7 @@ void BluetoothBleAdvertiserServer::StopAdvertising(int32_t advHandle) if (pimpl->bleService_ != nullptr) { pimpl->bleService_->StopAdvertising(advHandle); } + return BT_SUCCESS; } void BluetoothBleAdvertiserServer::Close(int32_t advHandle) diff --git a/services/bluetooth/server/src/bluetooth_ble_central_manager_server.cpp b/services/bluetooth/server/src/bluetooth_ble_central_manager_server.cpp index ca498bc9..770d41aa 100644 --- a/services/bluetooth/server/src/bluetooth_ble_central_manager_server.cpp +++ b/services/bluetooth/server/src/bluetooth_ble_central_manager_server.cpp @@ -18,6 +18,7 @@ #include "ble_service_data.h" #include "bluetooth_log.h" #include "bluetooth_utils_server.h" +#include "bluetooth_errorcode.h" #include "event_handler.h" #include "event_runner.h" #include "hisysevent.h" @@ -93,43 +94,7 @@ public: if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) { HILOGE("OnScanCallback(): failed, check permission failed, tokenId: %{public}u", tokenId); } else { - BluetoothBleScanResult bleScanResult; - if (result.GetPeripheralDevice().IsRSSI()) { - bleScanResult.SetRssi(result.GetPeripheralDevice().GetRSSI()); - } - - bleScanResult.SetAdvertiseFlag(result.GetPeripheralDevice().GetAdFlag()); - - if (result.GetPeripheralDevice().IsManufacturerData()) { - std::map manuData = result.GetPeripheralDevice().GetManufacturerData(); - for (auto it = manuData.begin(); it != manuData.end(); it++) { - bleScanResult.AddManufacturerData(it->first, it->second); - } - } - - bleScanResult.SetConnectable(result.GetPeripheralDevice().IsConnectable()); - - if (result.GetPeripheralDevice().IsServiceUUID()) { - std::vector uuids = result.GetPeripheralDevice().GetServiceUUID(); - for (auto iter = uuids.begin(); iter != uuids.end(); iter++) { - bleScanResult.AddServiceUuid(*iter); - } - } - - if (result.GetPeripheralDevice().IsServiceData()) { - std::vector uuids = result.GetPeripheralDevice().GetServiceDataUUID(); - int index = 0; - for (auto iter = uuids.begin(); iter != uuids.end(); iter++) { - bleScanResult.AddServiceData(*iter, result.GetPeripheralDevice().GetServiceData(index)); - ++index; - } - } - - bleScanResult.SetPeripheralDevice(result.GetPeripheralDevice().GetRawAddress()); - - bleScanResult.SetPayload(std::string(result.GetPeripheralDevice().GetPayload(), - result.GetPeripheralDevice().GetPayload() + result.GetPeripheralDevice().GetPayloadLen())); - + BluetoothBleScanResult bleScanResult(result); observer->OnScanCallback(bleScanResult); } }); @@ -360,16 +325,20 @@ bool BluetoothBleCentralManagerServer::IsProxyUid(int32_t uid) return proxyUids_.find(uid) != proxyUids_.end(); } -void BluetoothBleCentralManagerServer::StartScan() +int BluetoothBleCentralManagerServer::StartScan() { int32_t pid = IPCSkeleton::GetCallingPid(); int32_t uid = IPCSkeleton::GetCallingUid(); HILOGI("pid: %{public}d, uid: %{public}d", pid, uid); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED || - PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED || - PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) { + PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed."); - return; + return BT_ERR_PERMISSION_FAILED; + } + if (PermissionUtils::VerifyApproximatelyPermission() == PERMISSION_DENIED && + PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) { + HILOGE("No location permission"); + return BT_ERR_PERMISSION_FAILED; } pimpl->eventHandler_->PostSyncTask([&]() { @@ -397,29 +366,29 @@ void BluetoothBleCentralManagerServer::StartScan() HILOGI("start ble scan without params."); pimpl->bleService_->StartScan(); pimpl->isScanning = true; - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_BLE_SCAN_START", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "BLE_SCAN_START", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "TYPE", 0); - } else if (IsNewScanParams()) { - // Stop an ongoing ble scan, and restart the ble scan with default settings in OnStartOrStopScanEvent(). - HILOGI("restart ble scan without params."); - pimpl->bleService_->StopScan(); - pimpl->isScanning = false; } else { HILOGI("scan is already started."); } }); + return NO_ERROR; } -void BluetoothBleCentralManagerServer::StartScan(const BluetoothBleScanSettings &settings) +int BluetoothBleCentralManagerServer::StartScan(const BluetoothBleScanSettings &settings) { int32_t pid = IPCSkeleton::GetCallingPid(); int32_t uid = IPCSkeleton::GetCallingUid(); HILOGI("pid: %{public}d, uid: %{public}d", pid, uid); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED || - PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED || - PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) { + PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed."); - return; + return BT_ERR_PERMISSION_FAILED; + } + if (PermissionUtils::VerifyApproximatelyPermission() == PERMISSION_DENIED && + PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) { + HILOGE("No location permission"); + return BT_ERR_PERMISSION_FAILED; } pimpl->eventHandler_->PostSyncTask([&]() { @@ -447,7 +416,7 @@ void BluetoothBleCentralManagerServer::StartScan(const BluetoothBleScanSettings SetScanParams(settings); pimpl->bleService_->StartScan(pimpl->scanSettingImpl_); pimpl->isScanning = true; - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_BLE_SCAN_START", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "BLE_SCAN_START", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "TYPE", (settings.GetReportDelayMillisValue() > 0) ? 1 : 0); } else if (IsNewScanParams()) { @@ -459,16 +428,17 @@ void BluetoothBleCentralManagerServer::StartScan(const BluetoothBleScanSettings HILOGI("scan is already started and has the same params."); } }); + return NO_ERROR; } -void BluetoothBleCentralManagerServer::StopScan() +int BluetoothBleCentralManagerServer::StopScan() { int32_t pid = IPCSkeleton::GetCallingPid(); int32_t uid = IPCSkeleton::GetCallingUid(); HILOGI("pid: %{public}d, uid: %{public}d", pid, uid); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed."); - return; + return BT_ERR_PERMISSION_FAILED; } pimpl->eventHandler_->PostSyncTask([&]() { @@ -495,10 +465,11 @@ void BluetoothBleCentralManagerServer::StopScan() HILOGI("stop ble scan."); pimpl->bleService_->StopScan(); pimpl->isScanning = false; - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_BLE_SCAN_STOP", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "BLE_SCAN_STOP", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid); } }); + return NO_ERROR; } int BluetoothBleCentralManagerServer::ConfigScanFilter( diff --git a/services/bluetooth/server/src/bluetooth_gatt_client_server.cpp b/services/bluetooth/server/src/bluetooth_gatt_client_server.cpp index e298a28d..ba98c1eb 100644 --- a/services/bluetooth/server/src/bluetooth_gatt_client_server.cpp +++ b/services/bluetooth/server/src/bluetooth_gatt_client_server.cpp @@ -19,6 +19,7 @@ #include "bluetooth_gatt_client_server.h" #include "bluetooth_hitrace.h" +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "hisysevent.h" #include "interface_adapter_ble.h" @@ -94,7 +95,7 @@ public: int32_t uid = IPCSkeleton::GetCallingUid(); if (state == static_cast(BTConnectState::CONNECTED) || state == static_cast(BTConnectState::DISCONNECTED)) { - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_GATT_CLIENT_CONN_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "GATT_CLIENT_CONN_STATE", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", state); } callback_->OnConnectionStateChanged(state, newState); @@ -231,6 +232,11 @@ void BluetoothGattClientServer::impl::GattClientCallbackImpl::CallbackDeathRecip const wptr &remote) { HILOGI("enter"); + if (owner_.pimpl == nullptr || owner_.pimpl->clientService_ == nullptr) { + HILOGE("gattClientServerImpl clientService_ is not support."); + return; + } + std::lock_guard lck(owner_.pimpl->registerMutex_); for (auto it = owner_.pimpl->callbacks_.begin(); it != owner_.pimpl->callbacks_.end(); ++it) { if ((*it)->GetCallback()->AsObject() == remote) { HILOGI("callback is found from callbacks"); @@ -239,10 +245,9 @@ void BluetoothGattClientServer::impl::GattClientCallbackImpl::CallbackDeathRecip HILOGE("Failed to unlink death recipient from callback"); } HILOGI("App id is %{public}d", (*it)->GetAppId()); - owner_.Disconnect((*it)->GetAppId()); - owner_.DeregisterApplication((*it)->GetAppId()); + owner_.pimpl->clientService_->Disconnect((*it)->GetAppId()); + owner_.pimpl->clientService_->DeregisterApplication((*it)->GetAppId()); owner_.pimpl->callbacks_.erase(it); - *it = nullptr; return; } } @@ -269,26 +274,37 @@ BluetoothGattClientServer::~BluetoothGattClientServer() int BluetoothGattClientServer::RegisterApplication( const sptr &callback, const BluetoothRawAddress &addr, int32_t transport) +{ + int appId = 0; + int ret = RegisterApplication(callback, addr, transport, appId); + return (ret == BT_SUCCESS) ? appId : ret; +} + +int BluetoothGattClientServer::RegisterApplication( + const sptr &callback, const BluetoothRawAddress &addr, int32_t transport, int &appId) { HILOGI("address: %{public}s, transport: %{public}d", GetEncryptAddr(addr.GetAddress()).c_str(), transport); std::lock_guard lck(pimpl->registerMutex_); pimpl->clientService_ = pimpl->GetServicePtr(); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } auto it = pimpl->callbacks_.emplace( pimpl->callbacks_.begin(), std::make_unique(callback, *this)); - int appId = pimpl->clientService_->RegisterSharedApplication(*it->get(), (RawAddress)addr, transport); - (*it)->SetAppId(appId); - HILOGI("appId: %{public}d", appId); + appId = pimpl->clientService_->RegisterSharedApplication(*it->get(), (RawAddress)addr, transport); if (appId >= 0) { + HILOGI("appId: %{public}d", appId); + (*it)->SetAppId(appId); OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "GATT_APP_REGISTER", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "register", - "SIDE", "client", "ADDRESS", addr.GetAddress(), "PID", OHOS::IPCSkeleton::GetCallingPid(), + "SIDE", "client", "ADDRESS", GetEncryptAddr(addr.GetAddress()), "PID", OHOS::IPCSkeleton::GetCallingPid(), "UID", OHOS::IPCSkeleton::GetCallingUid(), "APPID", appId); + } else { + HILOGE("RegisterSharedApplication failed, appId: %{public}d", appId); + pimpl->callbacks_.erase(it); } - return appId; + return BT_SUCCESS; } int BluetoothGattClientServer::DeregisterApplication(int32_t appId) @@ -303,11 +319,21 @@ int BluetoothGattClientServer::DeregisterApplication(int32_t appId) HILOGE("request not support."); return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; } - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "GATT_APP_REGISTER", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "GATT_APP_REGISTER", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "deregister", "SIDE", "client", "ADDRESS", "empty", "PID", OHOS::IPCSkeleton::GetCallingPid(), "UID", OHOS::IPCSkeleton::GetCallingUid(), "APPID", appId); - return pimpl->clientService_->DeregisterApplication(appId); + + auto it = std::find_if(pimpl->callbacks_.begin(), pimpl->callbacks_.end(), + [appId](const std::unique_ptr &p) { return p->GetAppId() == appId; }); + if (it == pimpl->callbacks_.end()) { + HILOGE("Unknown appId: %{public}d", appId); + return INVALID_PARAMETER; + } + + int ret = pimpl->clientService_->DeregisterApplication(appId); + pimpl->callbacks_.erase(it); + return ret; } int BluetoothGattClientServer::Connect(int32_t appId, bool autoConnect) @@ -315,12 +341,12 @@ int BluetoothGattClientServer::Connect(int32_t appId, bool autoConnect) HILOGI("appId: %{public}d, autoConnect: %{public}d", appId, autoConnect); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } OHOS::Bluetooth::BluetoothHiTrace::BluetoothStartAsyncTrace("GATT_CLIENT_CONNECT", 1); int result = pimpl->clientService_->Connect(appId, autoConnect); @@ -333,12 +359,12 @@ int BluetoothGattClientServer::Disconnect(int32_t appId) HILOGI("appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->Disconnect(appId); } @@ -349,7 +375,7 @@ int BluetoothGattClientServer::DiscoveryServices(int32_t appId) std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->DiscoveryServices(appId); } @@ -359,12 +385,12 @@ int BluetoothGattClientServer::ReadCharacteristic(int32_t appId, const Bluetooth HILOGI("appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->ReadCharacteristic(appId, (Characteristic)characteristic); } @@ -375,7 +401,7 @@ int BluetoothGattClientServer::WriteCharacteristic( HILOGI("appId: %{public}d, withoutRespond: %{public}d", appId, withoutRespond); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } Characteristic character(characteristic->handle_); character.length_ = characteristic->length_; @@ -384,7 +410,7 @@ int BluetoothGattClientServer::WriteCharacteristic( std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->WriteCharacteristic(appId, character, withoutRespond); } @@ -408,12 +434,12 @@ int BluetoothGattClientServer::ReadDescriptor(int32_t appId, const BluetoothGatt HILOGI("appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->ReadDescriptor(appId, (Descriptor)descriptor); } @@ -423,7 +449,7 @@ int BluetoothGattClientServer::WriteDescriptor(int32_t appId, BluetoothGattDescr HILOGI("appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } Descriptor desc(descriptor->handle_); desc.length_ = descriptor->length_; @@ -432,7 +458,7 @@ int BluetoothGattClientServer::WriteDescriptor(int32_t appId, BluetoothGattDescr std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->WriteDescriptor(appId, desc); } @@ -442,12 +468,12 @@ int BluetoothGattClientServer::RequestExchangeMtu(int32_t appId, int32_t mtu) HILOGI("appId: %{public}d, mtu: %{public}d", appId, mtu); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (pimpl->clientService_ == nullptr) { HILOGE("request not support."); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } return pimpl->clientService_->RequestExchangeMtu(appId, mtu); } diff --git a/services/bluetooth/server/src/bluetooth_gatt_server_server.cpp b/services/bluetooth/server/src/bluetooth_gatt_server_server.cpp index c8675746..6c968159 100644 --- a/services/bluetooth/server/src/bluetooth_gatt_server_server.cpp +++ b/services/bluetooth/server/src/bluetooth_gatt_server_server.cpp @@ -16,6 +16,7 @@ #include #include +#include "bluetooth_errorcode.h" #include "bluetooth_gatt_server_server.h" #include "bluetooth_log.h" #include "bluetooth_utils_server.h" @@ -140,9 +141,13 @@ public: int32_t uid = IPCSkeleton::GetCallingUid(); if (state == static_cast(BTConnectState::CONNECTED) || state == static_cast(BTConnectState::DISCONNECTED)) { - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_GATT_SERVER_CONN_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "GATT_SERVER_CONN_STATE", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", state); } + if (callback_ == nullptr) { + HILOGE("callback is nullptr."); + return; + } callback_->OnConnectionStateChanged((BluetoothGattDevice)device, ret, state); } void OnMtuChanged(const bluetooth::GattDevice &device, int mtu) override @@ -272,16 +277,17 @@ int BluetoothGattServerServer::AddService(int32_t appId, BluetoothGattService *s HILOGI("enter, appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } bluetooth::Service svc = (bluetooth::Service)*services; - return pimpl->serverService_->AddService(appId, svc); + int ret = pimpl->serverService_->AddService(appId, svc); + return (ret == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } void BluetoothGattServerServer::ClearServices(int appId) @@ -312,19 +318,20 @@ int BluetoothGattServerServer::NotifyClient( HILOGI("addr: %{public}s, needConfirm: %{public}d", GET_ENCRYPT_GATT_ADDR(device), needConfirm); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } bluetooth::Characteristic character(characteristic->handle_); character.length_ = characteristic->length_; character.value_ = std::move(characteristic->value_); characteristic->length_ = 0; - return pimpl->serverService_->NotifyClient((bluetooth::GattDevice)device, character, needConfirm); + int ret = pimpl->serverService_->NotifyClient((bluetooth::GattDevice)device, character, needConfirm); + return (ret == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } int BluetoothGattServerServer::RemoveService(int32_t appId, const BluetoothGattService &services) @@ -332,15 +339,16 @@ int BluetoothGattServerServer::RemoveService(int32_t appId, const BluetoothGattS HILOGI("appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } - return pimpl->serverService_->RemoveService(appId, (bluetooth::Service)services); + int ret = pimpl->serverService_->RemoveService(appId, (bluetooth::Service)services); + return (ret == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } int BluetoothGattServerServer::RespondCharacteristicRead( @@ -349,19 +357,20 @@ int BluetoothGattServerServer::RespondCharacteristicRead( HILOGI("addr: %{public}s, ret: %{public}d", GET_ENCRYPT_GATT_ADDR(device), ret); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } bluetooth::Characteristic character(characteristic->handle_); character.length_ = characteristic->length_; character.value_ = std::move(characteristic->value_); characteristic->length_ = 0; - return pimpl->serverService_->RespondCharacteristicRead((bluetooth::GattDevice)device, character, ret); + int result = pimpl->serverService_->RespondCharacteristicRead((bluetooth::GattDevice)device, character, ret); + return (result == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } int BluetoothGattServerServer::RespondCharacteristicWrite( @@ -370,16 +379,17 @@ int BluetoothGattServerServer::RespondCharacteristicWrite( HILOGI("addr: %{public}s, ret: %{public}d", GET_ENCRYPT_GATT_ADDR(device), ret); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } - return pimpl->serverService_->RespondCharacteristicWrite( + int result = pimpl->serverService_->RespondCharacteristicWrite( (bluetooth::GattDevice)device, (bluetooth::Characteristic)characteristic, ret); + return (result == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } int BluetoothGattServerServer::RespondDescriptorRead( @@ -388,19 +398,20 @@ int BluetoothGattServerServer::RespondDescriptorRead( HILOGI("addr: %{public}s, ret: %{public}d", GET_ENCRYPT_GATT_ADDR(device), ret); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } bluetooth::Descriptor desc(descriptor->handle_); desc.length_ = descriptor->length_; desc.value_ = std::move(descriptor->value_); descriptor->length_ = 0; - return pimpl->serverService_->RespondDescriptorRead((bluetooth::GattDevice)device, desc, ret); + int result = pimpl->serverService_->RespondDescriptorRead((bluetooth::GattDevice)device, desc, ret); + return (result == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } int BluetoothGattServerServer::RespondDescriptorWrite( @@ -409,16 +420,17 @@ int BluetoothGattServerServer::RespondDescriptorWrite( HILOGI("addr: %{public}s, ret: %{public}d", GET_ENCRYPT_GATT_ADDR(device), ret); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } - return pimpl->serverService_->RespondDescriptorWrite( + int result = pimpl->serverService_->RespondDescriptorWrite( (bluetooth::GattDevice)device, (bluetooth::Descriptor)descriptor, ret); + return (result == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } int BluetoothGattServerServer::RegisterApplication(const sptr &callback) @@ -437,7 +449,7 @@ int BluetoothGattServerServer::RegisterApplication(const sptr= 0) { HILOGI("appId, %{public}d", ret); (*it)->SetAppId(ret); - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "GATT_APP_REGISTER", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "GATT_APP_REGISTER", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "register", "SIDE", "server", "ADDRESS", "empty", "PID", OHOS::IPCSkeleton::GetCallingPid(), "UID", OHOS::IPCSkeleton::GetCallingUid(), "APPID", ret); @@ -453,12 +465,12 @@ int BluetoothGattServerServer::DeregisterApplication(int32_t appId) HILOGI("appId: %{public}d", appId); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return REQUEST_NOT_SUPPORT; + return BT_ERR_PERMISSION_FAILED; } std::lock_guard lck(pimpl->registerMutex_); if (!pimpl->serverService_) { HILOGE("serverService_ is null"); - return bluetooth::GattStatus::REQUEST_NOT_SUPPORT; + return BT_ERR_INTERNAL_ERROR; } int ret = pimpl->serverService_->DeregisterApplication(appId); HILOGI("list size: %{public}lu", (unsigned long)pimpl->callbacks_.size()); @@ -469,11 +481,11 @@ int BluetoothGattServerServer::DeregisterApplication(int32_t appId) break; } } - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "GATT_APP_REGISTER", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "GATT_APP_REGISTER", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "ACTION", "deregister", "SIDE", "server", "ADDRESS", "empty", "PID", OHOS::IPCSkeleton::GetCallingPid(), "UID", OHOS::IPCSkeleton::GetCallingUid(), "APPID", appId); - return ret; + return (ret == GattStatus::GATT_SUCCESS ? BT_SUCCESS : BT_ERR_INTERNAL_ERROR); } BluetoothGattServerServer::BluetoothGattServerServer() : pimpl(new impl()) { diff --git a/services/bluetooth/server/src/bluetooth_hfp_ag_server.cpp b/services/bluetooth/server/src/bluetooth_hfp_ag_server.cpp index 92827614..f7260c0b 100644 --- a/services/bluetooth/server/src/bluetooth_hfp_ag_server.cpp +++ b/services/bluetooth/server/src/bluetooth_hfp_ag_server.cpp @@ -15,6 +15,7 @@ #include #include "bluetooth_def.h" +#include "bluetooth_errorcode.h" #include "bluetooth_hfp_ag_server.h" #include "bluetooth_hitrace.h" #include "bluetooth_log.h" @@ -42,7 +43,7 @@ public: HILOGI("device:%{public}s, state:%{public}d", GET_ENCRYPT_ADDR(device), state); if (state == static_cast(BTConnectState::CONNECTED) || state == static_cast(BTConnectState::DISCONNECTED)) { - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_HFP_CONNECTED_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "HFP_CONNECTED_STATE", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "STATE", state); } observers_->ForEach([device, state](IBluetoothHfpAgObserver* observer) { @@ -153,18 +154,18 @@ BluetoothHfpAgServer::~BluetoothHfpAgServer() } } -int BluetoothHfpAgServer::GetConnectDevices(std::vector &devices) +int32_t BluetoothHfpAgServer::GetConnectDevices(std::vector &devices) { HILOGI("Enter!"); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("GetConnectDevices() false, check permission failed"); - return BT_FAILURE; + return BT_ERR_PERMISSION_FAILED; } std::list deviceList; if (pimpl->HfpAgService_ != nullptr) { deviceList = pimpl->HfpAgService_->GetConnectDevices(); } else { - return BT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } for (RawAddress device : deviceList) { devices.push_back(BluetoothRawAddress(device)); @@ -188,55 +189,54 @@ int BluetoothHfpAgServer::GetDevicesByStates(const std::vector &states, std for (RawAddress device : rawDevices) { devices.push_back(BluetoothRawAddress(device)); } - return BT_SUCCESS; + return BT_SUCC; } -int BluetoothHfpAgServer::GetDeviceState(const BluetoothRawAddress &device) +int32_t BluetoothHfpAgServer::GetDeviceState(const BluetoothRawAddress &device, int32_t &state) { if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("GetDeviceState() false, check permission failed"); - return BT_FAILURE; + return BT_ERR_PERMISSION_FAILED; } RawAddress addr(device.GetAddress()); - if (pimpl->HfpAgService_ ) { - int state = pimpl->HfpAgService_->GetDeviceState(addr); + if (pimpl->HfpAgService_) { + state = pimpl->HfpAgService_->GetDeviceState(addr); HILOGI("state:%{public}d", state); - return state; } else { - return BT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } return BT_SUCCESS; } -int BluetoothHfpAgServer::Connect(const BluetoothRawAddress &device) +int32_t BluetoothHfpAgServer::Connect(const BluetoothRawAddress &device) { HILOGI("target device:%{public}s()", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("Connect error, check permission failed"); - return BT_FAILURE; + return BT_ERR_PERMISSION_FAILED; } RawAddress addr(device.GetAddress()); if (pimpl->HfpAgService_ != nullptr) { OHOS::Bluetooth::BluetoothHiTrace::BluetoothStartAsyncTrace("HFP_AG_CONNECT", 1); - int result = pimpl->HfpAgService_->Connect(addr); + int32_t result = pimpl->HfpAgService_->Connect(addr); OHOS::Bluetooth::BluetoothHiTrace::BluetoothFinishAsyncTrace("HFP_AG_CONNECT", 1); return result; } - return BT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } -int BluetoothHfpAgServer::Disconnect(const BluetoothRawAddress &device) +int32_t BluetoothHfpAgServer::Disconnect(const BluetoothRawAddress &device) { HILOGI("target device:%{public}s()", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("Disconnect error, check permission failed"); - return BT_FAILURE; + return BT_ERR_PERMISSION_FAILED; } RawAddress addr(device.GetAddress()); if (pimpl->HfpAgService_ != nullptr) { return pimpl->HfpAgService_->Disconnect(addr); } - return BT_FAILURE; + return BT_ERR_INTERNAL_ERROR; } int BluetoothHfpAgServer::GetScoState(const BluetoothRawAddress &device) diff --git a/services/bluetooth/server/src/bluetooth_hfp_hf_server.cpp b/services/bluetooth/server/src/bluetooth_hfp_hf_server.cpp index 2cb1750c..9d92f56a 100644 --- a/services/bluetooth/server/src/bluetooth_hfp_hf_server.cpp +++ b/services/bluetooth/server/src/bluetooth_hfp_hf_server.cpp @@ -229,7 +229,7 @@ int BluetoothHfpHfServer::GetDevicesByStates(const std::vector &states, for (RawAddress device : rawDevices) { devices.push_back(BluetoothRawAddress(device)); } - return BT_SUCCESS; + return BT_SUCC; } int BluetoothHfpHfServer::GetDeviceState(const BluetoothRawAddress &device) { @@ -422,7 +422,7 @@ int BluetoothHfpHfServer::StartDial(const BluetoothRawAddress &device, const std return BT_FAILURE; } else { call = *ret; - return BT_SUCCESS; + return BT_SUCC; } } diff --git a/services/bluetooth/server/src/bluetooth_hid_host_server.cpp b/services/bluetooth/server/src/bluetooth_hid_host_server.cpp old mode 100755 new mode 100644 index 8e1ff628..e185ae6f --- a/services/bluetooth/server/src/bluetooth_hid_host_server.cpp +++ b/services/bluetooth/server/src/bluetooth_hid_host_server.cpp @@ -14,6 +14,7 @@ */ #include "bluetooth_def.h" +#include "bluetooth_errorcode.h" #include "bluetooth_log.h" #include "bluetooth_utils_server.h" #include "interface_profile.h" @@ -171,17 +172,17 @@ ErrCode BluetoothHidHostServer::DeregisterObserver(const sptr &states, std::vector& result) { HILOGI("start"); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } std::vector serviceDeviceList = pimpl->hidHostService_->GetDevicesByStates(states); @@ -190,55 +191,51 @@ ErrCode BluetoothHidHostServer::GetDevicesByStates( result.push_back(bluetoothDevice); HILOGI("%{public}s", GET_ENCRYPT_ADDR(bluetoothDevice)); } - return ERR_OK; + return BT_SUCCESS; } -ErrCode BluetoothHidHostServer::GetDeviceState(const BluetoothRawAddress &device, int& result) +int32_t BluetoothHidHostServer::GetDeviceState(const BluetoothRawAddress &device, int32_t &state) { HILOGI("start, addr:%{public}s", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return BT_FAILURE; + return BT_ERR_PERMISSION_FAILED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } - result = pimpl->hidHostService_->GetDeviceState(device); - HILOGI("end, result:%{public}d", result); - return ERR_OK; + state = pimpl->hidHostService_->GetDeviceState(device); + HILOGI("end, result:%{public}d", state); + return BT_SUCCESS; } -ErrCode BluetoothHidHostServer::Connect(const BluetoothRawAddress &device, bool& result) +int32_t BluetoothHidHostServer::Connect(const BluetoothRawAddress &device) { HILOGI("start, addr:%{public}s", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return ERR_INVALID_VALUE; + return BT_ERR_PERMISSION_FAILED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGE("hidHostService_ is null"); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } - result = pimpl->hidHostService_->Connect(device); - HILOGI("end, result:%{public}d", result); - return ERR_OK; + return pimpl->hidHostService_->Connect(device); } -ErrCode BluetoothHidHostServer::Disconnect(const BluetoothRawAddress &device, bool& result) +int32_t BluetoothHidHostServer::Disconnect(const BluetoothRawAddress &device) { HILOGI("start, addr:%{public}s", GET_ENCRYPT_ADDR(device)); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return ERR_INVALID_VALUE; + return BT_ERR_PERMISSION_FAILED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } - result = pimpl->hidHostService_->Disconnect(device); - HILOGI("end, result:%{public}d", result); - return ERR_OK; + return pimpl->hidHostService_->Disconnect(device); } ErrCode BluetoothHidHostServer::HidHostVCUnplug(std::string &device, @@ -247,7 +244,7 @@ ErrCode BluetoothHidHostServer::HidHostVCUnplug(std::string &device, HILOGI("start"); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return ERR_INVALID_VALUE; + return ERR_PERMISSION_DENIED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); @@ -264,7 +261,7 @@ ErrCode BluetoothHidHostServer::HidHostSendData(std::string &device, HILOGI("start"); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return ERR_INVALID_VALUE; + return ERR_PERMISSION_DENIED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); @@ -281,7 +278,7 @@ ErrCode BluetoothHidHostServer::HidHostSetReport(std::string &device, HILOGI("start"); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return ERR_INVALID_VALUE; + return ERR_PERMISSION_DENIED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); @@ -298,7 +295,7 @@ ErrCode BluetoothHidHostServer::HidHostGetReport(std::string &device, HILOGI("start"); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("check permission failed"); - return ERR_INVALID_VALUE; + return ERR_PERMISSION_DENIED; } if (pimpl == nullptr || pimpl->hidHostService_ == nullptr) { HILOGI("hidHostService_ is null"); diff --git a/services/bluetooth/server/src/bluetooth_host_dumper.cpp b/services/bluetooth/server/src/bluetooth_host_dumper.cpp index 479e9183..4d933923 100644 --- a/services/bluetooth/server/src/bluetooth_host_dumper.cpp +++ b/services/bluetooth/server/src/bluetooth_host_dumper.cpp @@ -60,7 +60,7 @@ void BluetoothHostDumper::BtCommStateDump(std::string& result) { sptr hostServer = BluetoothHostServer::GetInstance(); // bt conn state - std::string btState = hostServer->GetBtState() ? "enabled\n" : "disabled\n"; + std::string btState = hostServer->IsBrEnabled() ? "enabled\n" : "disabled\n"; result.append("Bt enable state: ").append(btState); // ble conn state diff --git a/services/bluetooth/server/src/bluetooth_host_server.cpp b/services/bluetooth/server/src/bluetooth_host_server.cpp old mode 100755 new mode 100644 index de433368..e3dd1908 --- a/services/bluetooth/server/src/bluetooth_host_server.cpp +++ b/services/bluetooth/server/src/bluetooth_host_server.cpp @@ -21,6 +21,7 @@ #include "bluetooth_avrcp_tg_server.h" #include "bluetooth_ble_advertiser_server.h" #include "bluetooth_ble_central_manager_server.h" +#include "bluetooth_errorcode.h" #include "bluetooth_gatt_client_server.h" #include "bluetooth_gatt_server_server.h" #include "bluetooth_hfp_ag_server.h" @@ -202,7 +203,7 @@ public: if (state == BTStateID::STATE_TURN_ON || state == BTStateID::STATE_TURN_OFF) { int32_t pid = IPCSkeleton::GetCallingPid(); int32_t uid = IPCSkeleton::GetCallingUid(); - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_BR_SWITCH_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "BR_SWITCH_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", state); } } else if (transport == BTTransport::ADAPTER_BLE) { @@ -222,7 +223,7 @@ public: if (state == BTStateID::STATE_TURN_ON || state == BTStateID::STATE_TURN_OFF) { int32_t pid = IPCSkeleton::GetCallingPid(); int32_t uid = IPCSkeleton::GetCallingUid(); - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_BLE_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "BLE_SWITCH_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", state); } } @@ -251,7 +252,7 @@ public: if (status == DISCOVERY_STARTED || status == DISCOVERY_STOPED) { int32_t pid = IPCSkeleton::GetCallingPid(); int32_t uid = IPCSkeleton::GetCallingUid(); - HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_DISCOVERY_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "DISCOVERY_STATE", HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", status); } } @@ -705,6 +706,7 @@ void BluetoothHostServer::OnStart() bool BluetoothHostServer::Init() { + pimpl->Init(); if (!registeredToService_) { bool ret = Publish(BluetoothHostServer::GetInstance()); if (!ret) { @@ -714,7 +716,6 @@ bool BluetoothHostServer::Init() registeredToService_ = true; } HILOGI("init success"); - pimpl->Init(); return true; } @@ -773,20 +774,23 @@ bool BluetoothHostServer::EnableBt() return IAdapterManager::GetInstance()->Enable(bluetooth::BTTransport::ADAPTER_BREDR); } -bool BluetoothHostServer::DisableBt() +int32_t BluetoothHostServer::DisableBt() { - return IAdapterManager::GetInstance()->Disable(bluetooth::BTTransport::ADAPTER_BREDR); + if (IAdapterManager::GetInstance()->Disable(bluetooth::BTTransport::ADAPTER_BREDR)) { + return BT_SUCCESS; + } + return BT_ERR_INTERNAL_ERROR; } -int32_t BluetoothHostServer::GetBtState() +int32_t BluetoothHostServer::GetBtState(int32_t &state) { if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return INVALID_VALUE; + return BT_ERR_PERMISSION_FAILED; } - int32_t state = IAdapterManager::GetInstance()->GetState(bluetooth::BTTransport::ADAPTER_BREDR); + state = IAdapterManager::GetInstance()->GetState(bluetooth::BTTransport::ADAPTER_BREDR); HILOGI("state: %{public}d", state); - return state; + return NO_ERROR; } sptr BluetoothHostServer::GetProfile(const std::string &name) @@ -849,16 +853,27 @@ std::string BluetoothHostServer::GetLocalAddress() return INVALID_MAC_ADDRESS; } -bool BluetoothHostServer::EnableBle() +int32_t BluetoothHostServer::EnableBle() { HILOGI("Enter!"); - return IAdapterManager::GetInstance()->Enable(BTTransport::ADAPTER_BLE); + if (IAdapterManager::GetInstance()->Enable(BTTransport::ADAPTER_BLE)) { + return BT_SUCCESS; + } + return BT_ERR_INTERNAL_ERROR; } -bool BluetoothHostServer::DisableBle() +int32_t BluetoothHostServer::DisableBle() { HILOGI("Enter!"); - return IAdapterManager::GetInstance()->Disable(BTTransport::ADAPTER_BLE); + if (IAdapterManager::GetInstance()->Disable(BTTransport::ADAPTER_BLE)) { + return BT_SUCCESS; + } + return BT_ERR_INTERNAL_ERROR; +} + +bool BluetoothHostServer::IsBrEnabled() +{ + return IsBtEnabled(); } bool BluetoothHostServer::IsBleEnabled() @@ -878,24 +893,36 @@ int32_t BluetoothHostServer::GetMaxNumConnectedAudioDevices() return IAdapterManager::GetInstance()->GetMaxNumConnectedAudioDevices(); } -int32_t BluetoothHostServer::GetBtConnectionState() +int32_t BluetoothHostServer::GetBtConnectionState(int32_t &state) { - HILOGI("Enter!"); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return INVALID_VALUE; + return BT_ERR_PERMISSION_FAILED; + } + if (IsBtEnabled()) { + state = (int32_t)IAdapterManager::GetInstance()->GetAdapterConnectState(); + HILOGI("state: %{public}d", state); + return BT_SUCCESS; + } else { + HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return (int32_t)IAdapterManager::GetInstance()->GetAdapterConnectState(); } -int32_t BluetoothHostServer::GetBtProfileConnState(uint32_t profileId) +int32_t BluetoothHostServer::GetBtProfileConnState(uint32_t profileId, int &state) { HILOGI("Enter!"); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return INVALID_VALUE; + return BT_ERR_PERMISSION_FAILED; + } + if (IsBtEnabled()) { + state = (int32_t)IProfileManager::GetInstance()->GetProfileServiceConnectState(profileId); + return BT_SUCCESS; + } else { + HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return (int32_t)IProfileManager::GetInstance()->GetProfileServiceConnectState(profileId); } void BluetoothHostServer::GetLocalSupportedUuids(std::vector &uuids) @@ -926,74 +953,85 @@ bool BluetoothHostServer::SetLocalDeviceClass(const int32_t &deviceClass) return false; } -std::string BluetoothHostServer::GetLocalName() +int32_t BluetoothHostServer::GetLocalName(std::string &name) { HILOGI("Enter!"); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return INVALID_NAME; + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { - return pimpl->classicService_->GetLocalName(); + name = pimpl->classicService_->GetLocalName(); + return BT_SUCCESS; } else if (IsBleEnabled()) { - return pimpl->bleService_->GetLocalName(); + name = pimpl->bleService_->GetLocalName(); + return BT_SUCCESS; } else { HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return INVALID_NAME; } -bool BluetoothHostServer::SetLocalName(const std::string &name) +int32_t BluetoothHostServer::SetLocalName(const std::string &name) { HILOGI("name: %{public}s", name.c_str()); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { bool ret = pimpl->classicService_->SetLocalName(name); if (ret && (IsBleEnabled())) { - return pimpl->bleService_->SetLocalName(name); + if (pimpl->bleService_->SetLocalName(name)) { + return BT_SUCCESS; + } } else { HILOGE("failed!"); - return ret; + return BT_ERR_INTERNAL_ERROR; } } else if (IsBleEnabled()) { - return pimpl->bleService_->SetLocalName(name); + if (pimpl->bleService_->SetLocalName(name)) { + return BT_SUCCESS; + } } else { HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } -int32_t BluetoothHostServer::GetBtScanMode() +int32_t BluetoothHostServer::GetBtScanMode(int32_t &scanMode) { HILOGI("Enter!"); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return SCAN_MODE_NONE; + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { - return pimpl->classicService_->GetBtScanMode(); + scanMode = pimpl->classicService_->GetBtScanMode(); + return BT_SUCCESS; } else { HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return SCAN_MODE_NONE; } -bool BluetoothHostServer::SetBtScanMode(int32_t mode, int32_t duration) +int32_t BluetoothHostServer::SetBtScanMode(int32_t mode, int32_t duration) { HILOGI("mode: %{public}d, duration: %{public}d", mode, duration); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { - return pimpl->classicService_->SetBtScanMode(mode, duration); + if (pimpl->classicService_->SetBtScanMode(mode, duration)) { + return BT_SUCCESS; + } } else { HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } int32_t BluetoothHostServer::GetBondableMode(int32_t transport) @@ -1022,35 +1060,45 @@ bool BluetoothHostServer::SetBondableMode(int32_t transport, int32_t mode) return false; } -bool BluetoothHostServer::StartBtDiscovery() +int32_t BluetoothHostServer::StartBtDiscovery() { HILOGI("Enter!"); - if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED || - PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) { + if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; + } + if (PermissionUtils::VerifyApproximatelyPermission() == PERMISSION_DENIED && + PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) { + HILOGE("No location permission"); + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { - return pimpl->classicService_->StartBtDiscovery(); + if (pimpl->classicService_->StartBtDiscovery()) { + return BT_SUCCESS; + } } else { HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } -bool BluetoothHostServer::CancelBtDiscovery() +int32_t BluetoothHostServer::CancelBtDiscovery() { HILOGI("Enter!"); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { - return pimpl->classicService_->CancelBtDiscovery(); + if (pimpl->classicService_->CancelBtDiscovery()) { + return BT_SUCCESS; + } } else { HILOGW("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } bool BluetoothHostServer::IsBtDiscovering(int32_t transport) @@ -1077,13 +1125,12 @@ long BluetoothHostServer::GetBtDiscoveryEndMillis() return INVALID_VALUE; } -std::vector BluetoothHostServer::GetPairedDevices(int32_t transport) +int32_t BluetoothHostServer::GetPairedDevices(const int32_t transport, std::vector &pairedAddr) { HILOGI("transport: %{public}d", transport); - std::vector rawAddrRetVec; if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return rawAddrRetVec; + return BT_ERR_SYSTEM_PERMISSION_FAILED; } std::vector rawAddrVec; if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled()) { @@ -1092,34 +1139,40 @@ std::vector BluetoothHostServer::GetPairedDevices(int32_t t rawAddrVec = pimpl->bleService_->GetPairedDevices(); } else { HILOGE("transport invalid or BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } for (auto it = rawAddrVec.begin(); it != rawAddrVec.end(); ++it) { BluetoothRawAddress rawAddr = BluetoothRawAddress(*it); - rawAddrRetVec.emplace_back(rawAddr); + pairedAddr.emplace_back(rawAddr); } - return rawAddrRetVec; + return BT_SUCCESS; } -bool BluetoothHostServer::RemovePair(int32_t transport, const sptr &device) +int32_t BluetoothHostServer::RemovePair(int32_t transport, const sptr &device) { if (device == nullptr) { HILOGE("device is nullptr."); - return false; + return BT_ERR_INTERNAL_ERROR; } HILOGI("addr:%{public}s, transport:%{public}d", GET_ENCRYPT_ADDR(*device), transport); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { - HILOGE("check permission failed"); - return false; + HILOGE("check permission failed."); + return BT_ERR_PERMISSION_FAILED; } if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled()) { - return pimpl->classicService_->RemovePair(*device); + if (pimpl->classicService_->RemovePair(*device)) { + return BT_SUCCESS; + } } else if ((transport == BTTransport::ADAPTER_BLE) && IsBleEnabled()) { - return pimpl->bleService_->RemovePair(*device); + if (pimpl->bleService_->RemovePair(*device)) { + return BT_SUCCESS; + } } else { HILOGE("transport invalid or BT/BLE current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } bool BluetoothHostServer::RemoveAllPairs() @@ -1193,21 +1246,23 @@ int32_t BluetoothHostServer::GetPowerMode(const std::string &address) return IAdapterManager::GetInstance()->GetPowerMode(address); } -std::string BluetoothHostServer::GetDeviceName(int32_t transport, const std::string &address) +int32_t BluetoothHostServer::GetDeviceName(int32_t transport, const std::string &address, std::string &name) { if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return INVALID_NAME; + return BT_ERR_PERMISSION_FAILED; } RawAddress addr(address); if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled()) { - return pimpl->classicService_->GetDeviceName(addr); + name = pimpl->classicService_->GetDeviceName(addr); + return BT_SUCCESS; } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled()) { - return pimpl->bleService_->GetDeviceName(addr); + name = pimpl->bleService_->GetDeviceName(addr); + return BT_SUCCESS; } else { HILOGE("transport invalid or BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return INVALID_NAME; } std::string BluetoothHostServer::GetDeviceAlias(const std::string &address) @@ -1268,22 +1323,27 @@ int32_t BluetoothHostServer::GetPairState(int32_t transport, const std::string & return INVALID_VALUE; } -bool BluetoothHostServer::StartPair(int32_t transport, const std::string &address) +int32_t BluetoothHostServer::StartPair(int32_t transport, const std::string &address) { HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str()); if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { HILOGE("StartPair false, check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; } RawAddress addr(address); if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled()) { - return pimpl->classicService_->StartPair(addr); + if (pimpl->classicService_->StartPair(addr)) { + return BT_SUCCESS; + } } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled()) { - return pimpl->bleService_->StartPair(addr); + if (pimpl->bleService_->StartPair(addr)) { + return BT_SUCCESS; + } } else { HILOGE("transport invalid or BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } bool BluetoothHostServer::CancelPairing(int32_t transport, const std::string &address) @@ -1346,20 +1406,21 @@ bool BluetoothHostServer::IsAclEncrypted(int32_t transport, const std::string &a return false; } -int32_t BluetoothHostServer::GetDeviceClass(const std::string &address) +int32_t BluetoothHostServer::GetDeviceClass(const std::string &address, int32_t &cod) { HILOGI("address: %{public}s", GetEncryptAddr(address).c_str()); if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return INVALID_VALUE; + return BT_ERR_PERMISSION_FAILED; } if (IsBtEnabled()) { RawAddress addr(address); - return pimpl->classicService_->GetDeviceClass(addr); + cod = pimpl->classicService_->GetDeviceClass(addr); } else { HILOGE("BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return INVALID_VALUE; + return BT_SUCCESS; } std::vector BluetoothHostServer::GetDeviceUuids(int32_t transport, const std::string &address) @@ -1393,23 +1454,28 @@ bool BluetoothHostServer::SetDevicePin(const std::string &address, const std::st return false; } -bool BluetoothHostServer::SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) +int32_t BluetoothHostServer::SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept) { HILOGI("transport: %{public}d, address: %{public}s, accept: %{public}d", transport, GetEncryptAddr(address).c_str(), accept); if (PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) { HILOGE("false, check permission failed"); - return false; + return BT_ERR_PERMISSION_FAILED; } RawAddress addr(address); if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled()) { - return pimpl->classicService_->SetDevicePairingConfirmation(addr, accept); + if (pimpl->classicService_->SetDevicePairingConfirmation(addr, accept)) { + return BT_SUCCESS; + } } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled()) { - return pimpl->bleService_->SetDevicePairingConfirmation(addr, accept); + if (pimpl->bleService_->SetDevicePairingConfirmation(addr, accept)) { + return BT_SUCCESS; + } } else { HILOGE("transport invalid or BT current state is not enabled!"); + return BT_ERR_INVALID_STATE; } - return false; + return BT_ERR_INTERNAL_ERROR; } bool BluetoothHostServer::SetDevicePasskey(int32_t transport, const std::string &address, int32_t passkey, bool accept) @@ -1505,7 +1571,9 @@ void BluetoothHostServer::DeregisterRemoteDeviceObserver(const sptr(bluetooth::BTStateID::STATE_TURN_ON)) ? true : false; + int32_t state = bluetooth::BTStateID::STATE_TURN_OFF; + GetBtState(state); + bool isEnabled = (state == static_cast(bluetooth::BTStateID::STATE_TURN_ON)) ? true : false; HILOGI("%{public}s", isEnabled ? "true" : "false"); return isEnabled; } diff --git a/services/bluetooth/server/src/bluetooth_pan_server.cpp b/services/bluetooth/server/src/bluetooth_pan_server.cpp index 9728c408..124f26a0 100644 --- a/services/bluetooth/server/src/bluetooth_pan_server.cpp +++ b/services/bluetooth/server/src/bluetooth_pan_server.cpp @@ -13,12 +13,14 @@ * limitations under the License. */ +#include "bluetooth_errorcode.h" #include "bluetooth_pan_server.h" #include "bluetooth_log.h" #include "bluetooth_utils_server.h" #include "interface_profile.h" #include "interface_profile_pan.h" #include "i_bluetooth_host_observer.h" +#include "permission_utils.h" #include "remote_observer_list.h" #include "hilog/log.h" @@ -166,14 +168,13 @@ ErrCode BluetoothPanServer::DeregisterObserver(const sptr return ERR_OK; } -ErrCode BluetoothPanServer::GetDevicesByStates( - const std::vector &states, +int32_t BluetoothPanServer::GetDevicesByStates(const std::vector &states, std::vector& result) { - HILOGI("Triggered!"); + HILOGI("enter"); if (pimpl == nullptr || pimpl->panService_ == nullptr) { HILOGI("not init."); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } std::vector serviceDeviceList = pimpl->panService_->GetDevicesByStates(states); @@ -181,57 +182,57 @@ ErrCode BluetoothPanServer::GetDevicesByStates( BluetoothRawAddress bluetoothDevice(device.GetAddress()); result.push_back(bluetoothDevice); } - return ERR_OK; + return BT_SUCCESS; } -ErrCode BluetoothPanServer::GetDeviceState(const BluetoothRawAddress &device, - int& result) +int32_t BluetoothPanServer::GetDeviceState(const BluetoothRawAddress &device, int32_t &state) { - HILOGI("addr:%{public}s, res:%{public}d", GET_ENCRYPT_ADDR(device), result); if (pimpl == nullptr || pimpl->panService_ == nullptr) { HILOGI("not init."); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } - result = pimpl->panService_->GetDeviceState(device); - return ERR_OK; + state = pimpl->panService_->GetDeviceState(device); + HILOGI("addr:%{public}s, res:%{public}d", GET_ENCRYPT_ADDR(device), state); + return BT_SUCCESS; } -ErrCode BluetoothPanServer::Disconnect( - const BluetoothRawAddress &device, - bool& result) +int32_t BluetoothPanServer::Disconnect(const BluetoothRawAddress &device) { - HILOGI("addr:%{public}s, res:%{public}d", GET_ENCRYPT_ADDR(device), result); + HILOGI("addr:%{public}s", GET_ENCRYPT_ADDR(device)); + if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) { + HILOGE("check permission failed"); + return BT_ERR_PERMISSION_FAILED; + } if (pimpl == nullptr || pimpl->panService_ == nullptr) { HILOGI("not init."); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } - result = pimpl->panService_->Disconnect(device); - return ERR_OK; + return pimpl->panService_->Disconnect(device); } -ErrCode BluetoothPanServer::SetTethering( - const bool enable, - bool& result) +int32_t BluetoothPanServer::SetTethering(const bool enable) { - HILOGI("enable:%{public}d, res:%{public}d", enable, result); + HILOGI("enable:%{public}d", enable); + if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) { + HILOGE("check permission failed"); + return BT_ERR_PERMISSION_FAILED; + } if (pimpl == nullptr || pimpl->panService_ == nullptr) { HILOGI("not init."); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } - result = pimpl->panService_->SetTethering(enable); - return ERR_OK; + return pimpl->panService_->SetTethering(enable); } -ErrCode BluetoothPanServer::IsTetheringOn( - bool& result) +int32_t BluetoothPanServer::IsTetheringOn(bool& result) { - HILOGI("res:%{public}d", result); if (pimpl == nullptr || pimpl->panService_ == nullptr) { HILOGI("not init."); - return ERR_NO_INIT; + return BT_ERR_INTERNAL_ERROR; } result = pimpl->panService_->IsTetheringOn(); - return ERR_OK; + HILOGI("IsTetheringOn:%{public}d", result); + return BT_SUCCESS; } } // namespace Bluetooth } // namespace OHOS diff --git a/services/bluetooth/service/bluetooth_service_blocklist.txt b/services/bluetooth/service/bluetooth_service_blocklist.txt index 2b055b07..8ccf86ef 100644 --- a/services/bluetooth/service/bluetooth_service_blocklist.txt +++ b/services/bluetooth/service/bluetooth_service_blocklist.txt @@ -14,3 +14,4 @@ [cfi] # xmlFree check failed for CFI. src:*/bluetooth/services/bluetooth/service/src/util/xml_parse.cpp +src:*/bluetooth/services/bluetooth/service/src/gavdp/a2dp_codec/sbccodecctrl/src/a2dp_encoder_sbc.cpp diff --git a/services/bluetooth/service/include/interface_profile_a2dp_src.h b/services/bluetooth/service/include/interface_profile_a2dp_src.h index f708c36f..75498df0 100644 --- a/services/bluetooth/service/include/interface_profile_a2dp_src.h +++ b/services/bluetooth/service/include/interface_profile_a2dp_src.h @@ -169,7 +169,7 @@ public: * Returns 0 if device is not on playing; * @since 6.0 */ - virtual int GetPlayingState(const RawAddress &device) const = 0; + virtual int GetPlayingState(const RawAddress &device, int &state) const = 0; /** * @brief Set target device as active device. diff --git a/services/bluetooth/service/src/ble/ble_central_manager_impl.cpp b/services/bluetooth/service/src/ble/ble_central_manager_impl.cpp index a068ebef..966ca799 100644 --- a/services/bluetooth/service/src/ble/ble_central_manager_impl.cpp +++ b/services/bluetooth/service/src/ble/ble_central_manager_impl.cpp @@ -834,7 +834,7 @@ void BleCentralManagerImpl::SetScanModeDuration(int scanMode, int type) const default: break; } - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "BLUETOOTH_BLE_SCAN_DUTY_CYCLE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "BLE_SCAN_DUTY_CYCLE", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "WINDOW", pimpl->scanParams_.scanWindow, "INTERVAL", pimpl->scanParams_.scanInterval, "TYPE", pimpl->callBackType_); } diff --git a/services/bluetooth/service/src/gatt/gatt_connection_manager.cpp b/services/bluetooth/service/src/gatt/gatt_connection_manager.cpp index c0b59ab5..609922cc 100644 --- a/services/bluetooth/service/src/gatt/gatt_connection_manager.cpp +++ b/services/bluetooth/service/src/gatt/gatt_connection_manager.cpp @@ -523,7 +523,7 @@ void GattConnectionManager::impl::NotifyObserver( const GattDevice &device, uint8_t event, uint16_t connectionHandle, int ret) { std::lock_guard lck(registerMutex_); - OHOS::HiviewDFX::HiSysEvent::Write("BLUETOOTH", "GATT_CONNECT_STATE", + HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BLUETOOTH, "GATT_CONNECT_STATE", OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, "ADDRESS", device.addr_.GetAddress(), "STATE", event, "ROLE", device.role_); for (auto &item : observers_) { diff --git a/services/bluetooth/service/src/gavdp/a2dp_service.cpp b/services/bluetooth/service/src/gavdp/a2dp_service.cpp index 6c5b3141..9030dc78 100644 --- a/services/bluetooth/service/src/gavdp/a2dp_service.cpp +++ b/services/bluetooth/service/src/gavdp/a2dp_service.cpp @@ -551,7 +551,7 @@ int A2dpService::GetDeviceState(const RawAddress &device) const return info->GetConnectState(); } -int A2dpService::GetPlayingState(const RawAddress &device) const +int A2dpService::GetPlayingState(const RawAddress &device, int &state) const { A2dpDeviceInfo *info = nullptr; std::lock_guard lock(g_a2dpServiceMutex); @@ -562,8 +562,8 @@ int A2dpService::GetPlayingState(const RawAddress &device) const } else { info = iter->second; } - - return info->GetPlayingState(); + state = info->GetPlayingState() ? A2DP_IS_PLAYING : A2DP_NOT_PLAYING; + return RET_NO_ERROR; } int A2dpService::SetActiveSinkDevice(const RawAddress &device) diff --git a/services/bluetooth/service/src/gavdp/a2dp_service.h b/services/bluetooth/service/src/gavdp/a2dp_service.h index 3a3dc0fb..9f77a027 100644 --- a/services/bluetooth/service/src/gavdp/a2dp_service.h +++ b/services/bluetooth/service/src/gavdp/a2dp_service.h @@ -257,7 +257,7 @@ public: * Returns 0 if device is not on playing; * @since 6.0 */ - int GetPlayingState(const RawAddress &device) const override; + int GetPlayingState(const RawAddress &device, int &state) const override; /** * @brief Set target device as active device. diff --git a/services/bluetooth/service/src/hfp_ag/hfp_ag_service.cpp b/services/bluetooth/service/src/hfp_ag/hfp_ag_service.cpp index 0e286996..48421089 100644 --- a/services/bluetooth/service/src/hfp_ag/hfp_ag_service.cpp +++ b/services/bluetooth/service/src/hfp_ag/hfp_ag_service.cpp @@ -16,6 +16,7 @@ #include "hfp_ag_service.h" #include "adapter_config.h" +#include "bluetooth_errorcode.h" #include "class_creator.h" #include "hfp_ag_defines.h" #include "hfp_ag_system_interface.h" @@ -155,14 +156,14 @@ int HfpAgService::Connect(const RawAddress &device) int state = it->second->GetStateInt(); if ((state >= HFP_AG_STATE_CONNECTED) || (state == HFP_AG_STATE_CONNECTING)) { LOG_INFO("[HFP AG]%{public}s():state:%{public}d", __FUNCTION__, state); - return HFP_AG_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } } int size = GetConnectedDeviceNum(); if (size >= maxConnectedNum_) { LOG_INFO("[HFP AG]%{public}s():Max connection has reached!", __FUNCTION__); - return HFP_AG_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } HfpAgMessage event(HFP_AG_CONNECT_EVT); @@ -178,12 +179,12 @@ int HfpAgService::Disconnect(const RawAddress &device) std::string address = device.GetAddress(); auto it = stateMachines_.find(address); if (it == stateMachines_.end() || it->second == nullptr) { - return HFP_AG_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } int slcState = it->second->GetStateInt(); if ((slcState != HFP_AG_STATE_CONNECTING) && (slcState < HFP_AG_STATE_CONNECTED)) { - return HFP_AG_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } HfpAgMessage event(HFP_AG_DISCONNECT_EVT); diff --git a/services/bluetooth/service/src/hid_host/hid_host_service.cpp b/services/bluetooth/service/src/hid_host/hid_host_service.cpp index aecce7c1..e3d135ce 100644 --- a/services/bluetooth/service/src/hid_host/hid_host_service.cpp +++ b/services/bluetooth/service/src/hid_host/hid_host_service.cpp @@ -15,6 +15,8 @@ #include "hid_host_service.h" +#include "bluetooth_errorcode.h" + namespace OHOS { namespace bluetooth { HidHostService::HidHostService() : utility::Context(PROFILE_NAME_HID_HOST, "1.1.1") @@ -152,13 +154,13 @@ int HidHostService::Connect(const RawAddress &device) if ((it != stateMachines_.end()) && (it->second != nullptr)) { int slcState = it->second->GetDeviceStateInt(); if ((slcState >= HID_HOST_STATE_CONNECTED) || (slcState == HID_HOST_STATE_CONNECTING)) { - return HID_HOST_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } } if (GetConnectionsDeviceNum() >= maxConnectionsNum_) { LOG_INFO("[HIDH Service]%{public}s():Max connection number has reached!", __FUNCTION__); - return HID_HOST_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } HidHostMessage event(HID_HOST_API_OPEN_EVT); @@ -176,13 +178,13 @@ int HidHostService::Disconnect(const RawAddress &device) auto it = stateMachines_.find(address); if (it == stateMachines_.end() || it->second == nullptr) { LOG_DEBUG("[HIDH Service]%{public}s():The state machine is not available!", __FUNCTION__); - return HID_HOST_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } int slcState = it->second->GetDeviceStateInt(); if ((slcState != HID_HOST_STATE_CONNECTING) && (slcState < HID_HOST_STATE_CONNECTED)) { LOG_DEBUG("[HIDH Service]%{public}s():slcState:%{public}d", __FUNCTION__, slcState); - return HID_HOST_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } HidHostMessage event(HID_HOST_API_CLOSE_EVT); @@ -228,7 +230,7 @@ int HidHostService::HidHostSetReport(std::string device, uint8_t type, uint16_t event.data_ = std::make_unique(size); if (memcpy_s(event.data_.get(), size, report, size) != EOK) { LOG_ERROR("[HIDH Service]%{public}s():memcpy error", __FUNCTION__); - return HID_HOST_FAILURE; + return Bluetooth::BT_ERR_INTERNAL_ERROR; } } PostEvent(event); diff --git a/services/bluetooth/service/src/permission/auth_center.cpp b/services/bluetooth/service/src/permission/auth_center.cpp old mode 100755 new mode 100644 index e4e51f7b..7c43b457 --- a/services/bluetooth/service/src/permission/auth_center.cpp +++ b/services/bluetooth/service/src/permission/auth_center.cpp @@ -67,6 +67,14 @@ int AuthCenter::VerifyLocationPermission(const int &pid, const int &uid) return PERMISSION_GRANTED; } +int AuthCenter::VerifyApproximatelyPermission(const int &pid, const int &uid) +{ + if (g_permissionAlwaysGrant) { + return PERMISSION_GRANTED; + } + return PERMISSION_GRANTED; +} + int AuthCenter::VerifyUseBluetoothPermission(const std::uint32_t &tokenID) { if (g_permissionAlwaysGrant) { diff --git a/services/bluetooth/service/src/permission/auth_center.h b/services/bluetooth/service/src/permission/auth_center.h index a9cb527e..caedc435 100644 --- a/services/bluetooth/service/src/permission/auth_center.h +++ b/services/bluetooth/service/src/permission/auth_center.h @@ -60,6 +60,14 @@ public: */ static int VerifyLocationPermission(const int &pid, const int &uid); + /** + * @Description Verify where the app has the permission to Approximately Location + * + * @param pid the app's process id. + * @param uid the app id. + * @return int PERMISSION_DENIED or PERMISSION_GRANTED + */ + static int VerifyApproximatelyPermission(const int &pid, const int &uid); /** * @Description Verify where the app has the permission to use bluetooth * diff --git a/services/bluetooth/service/src/permission/permission_helper.cpp b/services/bluetooth/service/src/permission/permission_helper.cpp old mode 100755 new mode 100644 index 28bc6d85..eb81ca45 --- a/services/bluetooth/service/src/permission/permission_helper.cpp +++ b/services/bluetooth/service/src/permission/permission_helper.cpp @@ -105,6 +105,15 @@ int PermissionHelper::VerifyLocationPermission(const int &pid, const int &uid) return PERMISSION_GRANTED; } +int PermissionHelper::VerifyApproximatelyPermission(const int &pid, const int &uid) +{ + if (VerifyPermission("ohos.permission.APPROXIMATELY_LOCATION", pid, uid) == PERMISSION_DENIED) { + return PERMISSION_DENIED; + } + + return PERMISSION_GRANTED; +} + int PermissionHelper::VerifyUseBluetoothPermission(const std::uint32_t &tokenID) { if (VerifyPermission("ohos.permission.USE_BLUETOOTH", tokenID) == PERMISSION_DENIED) { diff --git a/services/bluetooth/service/src/permission/permission_helper.h b/services/bluetooth/service/src/permission/permission_helper.h old mode 100755 new mode 100644 index bee148dc..a8ff03b3 --- a/services/bluetooth/service/src/permission/permission_helper.h +++ b/services/bluetooth/service/src/permission/permission_helper.h @@ -76,6 +76,15 @@ public: */ static int VerifyLocationPermission(const int &pid, const int &uid); + /** + * @Description Verify where the app has the permission to approximately location + * + * @param pid The app's process id. + * @param uid The app id. + * @return int PERMISSION_DENIED or PERMISSION_GRANTED + */ + static int VerifyApproximatelyPermission(const int &pid, const int &uid); + /** * @Description Verify where the app has the permission to use bluetooth * diff --git a/services/bluetooth/service/src/permission/permission_utils.cpp b/services/bluetooth/service/src/permission/permission_utils.cpp index 9f158c1e..4b182035 100644 --- a/services/bluetooth/service/src/permission/permission_utils.cpp +++ b/services/bluetooth/service/src/permission/permission_utils.cpp @@ -14,8 +14,8 @@ */ #include "permission_utils.h" -#include "ipc_skeleton.h" #include "auth_center.h" +#include "ipc_skeleton.h" namespace OHOS { namespace bluetooth { @@ -45,6 +45,12 @@ int PermissionUtils::VerifyLocationPermission() IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); } +int PermissionUtils::VerifyApproximatelyPermission() +{ + return AuthCenter::GetInstance().VerifyApproximatelyPermission( + IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); +} + int PermissionUtils::VerifyUseBluetoothPermission(const std::uint32_t &tokenID) { return AuthCenter::GetInstance().VerifyUseBluetoothPermission(tokenID); diff --git a/services/bluetooth/service/src/permission/permission_utils.h b/services/bluetooth/service/src/permission/permission_utils.h index 5855e21f..9d172f18 100644 --- a/services/bluetooth/service/src/permission/permission_utils.h +++ b/services/bluetooth/service/src/permission/permission_utils.h @@ -29,6 +29,7 @@ public: static int VerifyDiscoverBluetoothPermission(); static int VerifyManageBluetoothPermission(); static int VerifyLocationPermission(); + static int VerifyApproximatelyPermission(); static int VerifyUseBluetoothPermission(const std::uint32_t &tokenID); static int VerifyDiscoverBluetoothPermission(const std::uint32_t &tokenID); diff --git a/services/bluetooth/stack/btstack_blocklist.txt b/services/bluetooth/stack/btstack_blocklist.txt index 1e003626..0d4a413f 100644 --- a/services/bluetooth/stack/btstack_blocklist.txt +++ b/services/bluetooth/stack/btstack_blocklist.txt @@ -15,8 +15,13 @@ src:*/bluetooth/services/bluetooth/stack/src/btm/btm_sco.c src:*/bluetooth/services/bluetooth/stack/src/btm/btm.c src:*/bluetooth/services/bluetooth/stack/src/l2cap/l2cap_cmn.c + src:*/bluetooth/services/bluetooth/stack/src/l2cap/l2cap_core.c + src:*/bluetooth/services/bluetooth/stack/src/l2cap/l2cap_if.c src:*/bluetooth/services/bluetooth/stack/src/gap/gap_le_sec.c src:*/bluetooth/services/bluetooth/stack/src/gap/gap_le_adv.c + src:*/bluetooth/services/bluetooth/stack/src/gap/gap_le_conn.c + src:*/bluetooth/services/bluetooth/stack/src/gap/gap_br_sec.c src:*/bluetooth/services/bluetooth/stack/src/att/att_receive.c src:*/bluetooth/services/bluetooth/stack/src/att/att_common.c - src:*/bluetooth/services/bluetooth/stack/src/att/att_connect.c \ No newline at end of file + src:*/bluetooth/services/bluetooth/stack/src/att/att_connect.c + src:*/bluetooth/services/bluetooth/stack/platform/src/queue.c \ No newline at end of file diff --git a/test/fuzztest/host/setbluetoothscanmode_fuzzer/setbluetoothscanmode_fuzzer.cpp b/test/fuzztest/host/setbluetoothscanmode_fuzzer/setbluetoothscanmode_fuzzer.cpp index 54e5ecdf..defebfb1 100644 --- a/test/fuzztest/host/setbluetoothscanmode_fuzzer/setbluetoothscanmode_fuzzer.cpp +++ b/test/fuzztest/host/setbluetoothscanmode_fuzzer/setbluetoothscanmode_fuzzer.cpp @@ -30,7 +30,7 @@ namespace OHOS { bool result = false; int scanMode = data[0] % 5; BluetoothHost *host = &BluetoothHost::GetDefaultHost(); - result = host->SetBtScanMode(scanMode, 0); + host->SetBtScanMode(scanMode, 0); return result; } } diff --git a/test/unittest/a2dp/a2dp_src_test.cpp b/test/unittest/a2dp/a2dp_src_test.cpp index eb9d75ed..22ec4b41 100644 --- a/test/unittest/a2dp/a2dp_src_test.cpp +++ b/test/unittest/a2dp/a2dp_src_test.cpp @@ -16,6 +16,7 @@ #include #include "bluetooth_a2dp_src.h" #include "bluetooth_host.h" +#include "bluetooth_errorcode.h" using namespace testing; using namespace testing::ext; @@ -183,8 +184,8 @@ HWTEST_F(A2dpSourceTest, A2dpSource_UnitTest_Connect, TestSize.Level1) profile_ = A2dpSource::GetProfile(); BluetoothRemoteDevice device; - bool isOK = profile_->Connect(device); - EXPECT_EQ(isOK, true); + int32_t ret = profile_->Connect(device); + EXPECT_NE(ret, RET_NO_ERROR); GTEST_LOG_(INFO) << "A2dpSource_UnitTest_Connect end"; } @@ -199,8 +200,8 @@ HWTEST_F(A2dpSourceTest, A2dpSource_UnitTest_Disconnect, TestSize.Level1) profile_ = A2dpSource::GetProfile(); BluetoothRemoteDevice device; - bool isOK = profile_->Disconnect(device); - EXPECT_EQ(isOK, true); + int32_t ret = profile_->Disconnect(device); + EXPECT_NE(ret, RET_NO_ERROR); GTEST_LOG_(INFO) << "A2dpSource_UnitTest_Disconnect end"; } @@ -215,7 +216,7 @@ HWTEST_F(A2dpSourceTest, A2dpSource_UnitTest_SetActiveSinkDevice, TestSize.Level profile_ = A2dpSource::GetProfile(); BluetoothRemoteDevice device; - EXPECT_EQ(profile_->SetActiveSinkDevice(device), 0); + EXPECT_EQ(profile_->SetActiveSinkDevice(device), -3); GTEST_LOG_(INFO) << "A2dpSource_UnitTest_SetActiveSinkDevice end"; } diff --git a/test/unittest/ble/ble_test.cpp b/test/unittest/ble/ble_test.cpp index 63063e62..5a2fd7d6 100644 --- a/test/unittest/ble/ble_test.cpp +++ b/test/unittest/ble/ble_test.cpp @@ -15,6 +15,7 @@ #include "ble_test.h" #include "bluetooth_def.h" +#include "bluetooth_errorcode.h" #include #include #include @@ -64,7 +65,11 @@ bool BleTest::EnableBle() { GTEST_LOG_(INFO) << "enable ble start"; std::unique_lock lock(g_mx); - bool isEnable = host_->EnableBle(); + bool isEnable = false; + int32_t ret = host_->EnableBle(); + if (ret == BT_SUCCESS) { + isEnable = true; + } EXPECT_TRUE(isEnable); while (!g_ready) { g_cv.wait(lock); @@ -79,7 +84,11 @@ bool BleTest::DisableBle() { GTEST_LOG_(INFO) << "disable ble start"; std::unique_lock lock(g_mx); - bool isEnable = host_->DisableBle(); + bool isEnable = false; + int ret = host_->DisableBle(); + if (ret == BT_SUCCESS) { + isEnable = true; + } EXPECT_TRUE(isEnable); while (!g_ready) { g_cv.wait(lock); diff --git a/test/unittest/gatt/gatt_client_test.cpp b/test/unittest/gatt/gatt_client_test.cpp index c3d58c12..0d913ff7 100644 --- a/test/unittest/gatt/gatt_client_test.cpp +++ b/test/unittest/gatt/gatt_client_test.cpp @@ -16,6 +16,7 @@ #include #include +#include "bluetooth_errorcode.h" #include "bluetooth_gatt_client.h" #include "bluetooth_gatt_descriptor.h" #include "bluetooth_host.h" @@ -135,7 +136,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_Connect, TestSize.Level1) bool isAutoConnect = true; int transport = 1; int result = client.Connect(callback_, isAutoConnect, transport); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_Connect end"; } @@ -153,7 +154,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_Disconnect, TestSize.Level1) int transport = 1; client.Connect(callback_, isAutoConnect, transport); int result = client.Disconnect(); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_Disconnect end"; } @@ -171,7 +172,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_DiscoverServices, TestSize.Level1) int transport = 1; client.Connect(callback_, isAutoConnect, transport); int result = client.DiscoverServices(); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_DiscoverServices end"; } @@ -233,7 +234,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_ReadCharacteristic, TestSize.Level1 int properties = 37; GattCharacteristic characteristic = GattCharacteristic(uuid_, permissions, properties); int result = client.ReadCharacteristic(characteristic); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_ReadCharacteristic end"; } @@ -254,7 +255,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_ReadDescriptor, TestSize.Level1) int permissions = 17; GattDescriptor descriptor = GattDescriptor(uuid_, permissions); int result = client.ReadDescriptor(descriptor); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_ReadDescriptor end"; } @@ -273,7 +274,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_RequestBleMtuSize, TestSize.Level1) int result = client.Connect(callback_, isAutoConnect, transport); int mtu = 17; result = client.RequestBleMtuSize(mtu); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_RequestBleMtuSize end"; } @@ -296,7 +297,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_SetNotifyCharacteristic, TestSize.L GattCharacteristic characteristic = GattCharacteristic(uuid_, permissions, properties); bool enable = true; int result = client.SetNotifyCharacteristic(characteristic, enable); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_SetNotifyCharacteristic end"; } @@ -318,7 +319,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_WriteCharacteristic, TestSize.Level int properties = 37; GattCharacteristic characteristic = GattCharacteristic(uuid_, permissions, properties); int result = client.WriteCharacteristic(characteristic); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_WriteCharacteristic end"; } @@ -339,7 +340,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_WriteDescriptor, TestSize.Level1) int permissions = 17; GattDescriptor descriptor = GattDescriptor(uuid_, permissions); int result = client.WriteDescriptor(descriptor); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_WriteDescriptor end"; } @@ -358,7 +359,7 @@ HWTEST_F(GattClientTest, GattClient_UnitTest_RequestConnectionPriority, TestSize client.Connect(callback_, isAutoConnect, transport); int connPriority = 2; int result = client.RequestConnectionPriority(connPriority); - EXPECT_EQ(result, -18); + EXPECT_NE(result, BT_SUCCESS); GTEST_LOG_(INFO) << "GattClient_UnitTest_RequestConnectionPriority end"; } diff --git a/test/unittest/gatt/gatt_server_test.cpp b/test/unittest/gatt/gatt_server_test.cpp index db59628f..cace9c6d 100644 --- a/test/unittest/gatt/gatt_server_test.cpp +++ b/test/unittest/gatt/gatt_server_test.cpp @@ -14,6 +14,7 @@ */ #include +#include "bluetooth_errorcode.h" #include "bluetooth_gatt_server.h" #include "bluetooth_host.h" #include "bluetooth_remote_device.h" @@ -181,7 +182,7 @@ HWTEST_F(GattServerTest, GattServer_ModuleTest_NotifyCharacteristicChanged, Test uuidSerPer = UUID::FromString("00001810-0000-1000-8000-00805F9B34FB"); GattCharacteristic* aa = new GattCharacteristic(uuidSerPer, 1, 1); int res = server.NotifyCharacteristicChanged(deviceBle_, *aa, false); - EXPECT_EQ(res, -18); + EXPECT_NE(res, BT_SUCCESS); GTEST_LOG_(INFO) << "GattServer_ModuleTest_Notify end"; } @@ -204,7 +205,7 @@ HWTEST_F(GattServerTest, GattServer_ModuleTest_SendResponse, TestSize.Level1) 1, (uint8_t *)valueChrTwo.c_str(), valueChrTwo.size()); - EXPECT_EQ(ret, -18); + EXPECT_NE(ret, BT_SUCCESS); GTEST_LOG_(INFO) << "GattServer_ModuleTest_SendResponse end"; } diff --git a/test/unittest/hfp/hfp_ag_test.cpp b/test/unittest/hfp/hfp_ag_test.cpp index e4557371..c251d87f 100644 --- a/test/unittest/hfp/hfp_ag_test.cpp +++ b/test/unittest/hfp/hfp_ag_test.cpp @@ -14,6 +14,7 @@ */ #include #include +#include "bluetooth_errorcode.h" #include "bluetooth_hfp_ag.h" #include "bluetooth_host.h" @@ -105,8 +106,8 @@ HWTEST_F(HandsFreeAudioGatewayTest, HandsFreeAudioGateway_UnitTest_GetConnectedD GTEST_LOG_(INFO) << "HandsFreeAudioGateway_UnitTest_GetConnectedDevices start"; profile_ = HandsFreeAudioGateway::GetProfile(); - vector devices = profile_->GetConnectedDevices(); - + std::vector devices; + profile_->GetConnectedDevices(devices); GTEST_LOG_(INFO) << "HandsFreeAudioGateway_UnitTest_GetConnectedDevices end"; } @@ -122,8 +123,8 @@ HWTEST_F(HandsFreeAudioGatewayTest, HandsFreeAudioGateway_UnitTest_GetDevicesByS profile_ = HandsFreeAudioGateway::GetProfile(); vector states = {static_cast(BTConnectState::CONNECTED)}; - vector devices = profile_->GetDevicesByStates(states); - + std::vector devices; + profile_->GetDevicesByStates(states, devices); GTEST_LOG_(INFO) << "HandsFreeAudioGateway_UnitTest_GetDevicesByStates end"; } @@ -138,7 +139,8 @@ HWTEST_F(HandsFreeAudioGatewayTest, HandsFreeAudioGateway_UnitTest_GetDeviceStat profile_ = HandsFreeAudioGateway::GetProfile(); BluetoothRemoteDevice device; - int state = profile_->GetDeviceState(device); + int32_t state = static_cast(BTConnectState::DISCONNECTED); + int state = profile_->GetDeviceState(device, state); EXPECT_EQ(state, 0); GTEST_LOG_(INFO) << "HandsFreeAudioGateway_UnitTest_GetDeviceState end"; } @@ -155,7 +157,7 @@ HWTEST_F(HandsFreeAudioGatewayTest, HandsFreeAudioGateway_UnitTest_Connect, Test profile_ = HandsFreeAudioGateway::GetProfile(); BluetoothRemoteDevice device; - bool isOK = profile_->Connect(device); + bool isOK = (profile_->Connect(device) == BT_SUCCESS ? true : false); EXPECT_EQ(isOK, true); GTEST_LOG_(INFO) << "HandsFreeAudioGateway_UnitTest_Connect end"; @@ -173,7 +175,7 @@ HWTEST_F(HandsFreeAudioGatewayTest, HandsFreeAudioGateway_UnitTest_Disconnect, T profile_ = HandsFreeAudioGateway::GetProfile(); BluetoothRemoteDevice device; - bool isOK = profile_->Disconnect(device); + bool isOK = (profile_->Disconnect(device) == BT_SUCCESS ? true : false); EXPECT_EQ(isOK, true); GTEST_LOG_(INFO) << "HandsFreeAudioGateway_UnitTest_Disconnect end"; } diff --git a/test/unittest/hid/hid_host_test.cpp b/test/unittest/hid/hid_host_test.cpp index 0c0c1245..efdbd57a 100644 --- a/test/unittest/hid/hid_host_test.cpp +++ b/test/unittest/hid/hid_host_test.cpp @@ -14,6 +14,7 @@ */ #include +#include "bluetooth_errorcode.h" #include "bluetooth_hid_host.h" #include "bluetooth_remote_device.h" @@ -101,8 +102,9 @@ HWTEST_F(HidHostTest, HID_ModuleTest_GetDevicesByStates_00100, TestSize.Level1) profile_ = HidHost::GetProfile(); std::vector states; std::vector bluetoothRemoteDeviceAddr; - std::vector bluetoothRemoteDeviceByState = profile_->GetDevicesByStates(states); - EXPECT_TRUE(CompareDevice(bluetoothRemoteDeviceByState, bluetoothRemoteDeviceAddr)); + std::vector devices; + profile_->GetDevicesByStates(states, devices); + EXPECT_TRUE(CompareDevice(devices, bluetoothRemoteDeviceAddr)); GTEST_LOG_(INFO) << "HID_ModuleTest_GetDevicesByStates_00100 end"; } @@ -122,7 +124,9 @@ HWTEST_F(HidHostTest, HID_ModuleTest_GetDeviceState_00100, TestSize.Level1) int sucess = static_cast(BTConnectState::DISCONNECTED); BluetoothRemoteDevice device; profile_ = HidHost::GetProfile(); - EXPECT_EQ(sucess, profile_->GetDeviceState(device)); + int32_t state = static_cast(BTConnectState::DISCONNECTED); + profile_->GetDeviceState(device, state); + EXPECT_EQ(sucess, state); GTEST_LOG_(INFO) << "HID_ModuleTest_GetDeviceState_00100 end"; } @@ -140,7 +144,8 @@ HWTEST_F(HidHostTest, HID_ModuleTest_Connect_00100, TestSize.Level1) BluetoothRemoteDevice device; profile_ = HidHost::GetProfile(); - EXPECT_FALSE(profile_->Connect(device)); + bool isOK = (profile_->Connect(device) == BT_SUCCESS ? true : false); + EXPECT_FALSE(isOK); GTEST_LOG_(INFO) << "HID_ModuleTest_Connect_00100 end"; } @@ -158,7 +163,8 @@ HWTEST_F(HidHostTest, HID_ModuleTest_Disconnect_00100, TestSize.Level1) BluetoothRemoteDevice device; profile_ = HidHost::GetProfile(); - EXPECT_FALSE(profile_->Disconnect(device)); + bool isOK = (profile_->Disconnect(device) == BT_SUCCESS ? true : false); + EXPECT_FALSE(isOK); GTEST_LOG_(INFO) << "HID_ModuleTest_Disconnect_00100 end"; } diff --git a/test/unittest/host/host_test.cpp b/test/unittest/host/host_test.cpp index c3e60912..a9f254e4 100644 --- a/test/unittest/host/host_test.cpp +++ b/test/unittest/host/host_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 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 @@ -21,6 +21,7 @@ #include "bluetooth_def.h" #include "bluetooth_device_class.h" #include "bluetooth_host.h" +#include "bluetooth_errorcode.h" using namespace testing::ext; @@ -233,7 +234,9 @@ HWTEST_F(HostTest, Host_ModuleTest_GetBtProfileConnState_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_GetBtProfileConnState_00100 start"; host_ = &BluetoothHost::GetDefaultHost(); - EXPECT_EQ(host_->GetBtProfileConnState(PROFILE_ID_GATT_CLIENT), (int)BTConnectState::DISCONNECTED); + int state = static_cast(BTConnectState::DISCONNECTED); + host_->GetBtProfileConnState(PROFILE_ID_GATT_CLIENT, state); + EXPECT_EQ(state, (int)BTConnectState::DISCONNECTED); GTEST_LOG_(INFO) << "Host_ModuleTest_GetBtProfileConnState_00100 end"; } @@ -379,11 +382,37 @@ HWTEST_F(HostTest, Host_ModuleTest_SetBtScanMode_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_SetBtScanMode_00100 start"; host_ = &BluetoothHost::GetDefaultHost(); - EXPECT_TRUE(host_->SetBtScanMode(SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0)); + bool ret = false; + int result = host_->SetBtScanMode(SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0); + if (result == BT_SUCCESS) { + ret = true; + } + EXPECT_TRUE(ret); GTEST_LOG_(INFO) << "Host_ModuleTest_SetBtScanMode_00100 end"; } +/** + * @tc.number: Host_ModuleTest_SetBtScanMode_00200 + * @tc.name: + * @tc.desc: + */ +HWTEST_F(HostTest, Host_ModuleTest_SetBtScanMode_00200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Host_ModuleTest_SetBtScanMode_00200 start"; + + const int scanModeInvalid = -1; + host_ = &BluetoothHost::GetDefaultHost(); + bool ret = false; + int result = host_->SetBtScanMode(scanModeInvalid, 0); + if (result == BT_SUCCESS) { + ret = true; + } + EXPECT_FALSE(ret); + + GTEST_LOG_(INFO) << "Host_ModuleTest_SetBtScanMode_00200 end"; +} + /** * @tc.number: Host_ModuleTest_GetBtScanMode_00100 * @tc.name: @@ -395,7 +424,9 @@ HWTEST_F(HostTest, Host_ModuleTest_GetBtScanMode_00100, TestSize.Level1) sleep(1); host_ = &BluetoothHost::GetDefaultHost(); - EXPECT_EQ(SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, host_->GetBtScanMode()); + int scanmode = 0; + host_->GetBtScanMode(scanmode); + EXPECT_EQ(SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, scanmode); GTEST_LOG_(INFO) << "Host_ModuleTest_GetBtScanMode_00100 end"; } @@ -440,7 +471,12 @@ HWTEST_F(HostTest, Host_ModuleTest_StartBtDiscovery_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_StartBtDiscovery_00100 start"; host_ = &BluetoothHost::GetDefaultHost(); - EXPECT_TRUE(host_->StartBtDiscovery()); + int ret = host_->StartBtDiscovery(); + bool isSuccess = false; + if (ret == BT_SUCCESS) { + isSuccess = true; + } + EXPECT_TRUE(isSuccess); GTEST_LOG_(INFO) << "Host_ModuleTest_StartBtDiscovery_00100 end"; } @@ -470,7 +506,12 @@ HWTEST_F(HostTest, Host_ModuleTest_CancelBtDiscovery_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_CancelBtDiscovery_00100 start"; host_ = &BluetoothHost::GetDefaultHost(); - EXPECT_TRUE(host_->CancelBtDiscovery()); + int ret = host_->CancelBtDiscovery(); + bool isSuccess = false; + if (ret == BT_SUCCESS) { + isSuccess = true; + } + EXPECT_TRUE(isSuccess); GTEST_LOG_(INFO) << "Host_ModuleTest_CancelBtDiscovery_00100 end"; } @@ -500,7 +541,8 @@ HWTEST_F(HostTest, Host_ModuleTest_GetPairedDevices_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_GetPairedDevices_00100 start"; host_ = &BluetoothHost::GetDefaultHost(); - std::vector remotedeviceList = host_->GetPairedDevices(BT_TRANSPORT_BREDR); + std::vector remotedeviceList; + host_->GetPairedDevices(BT_TRANSPORT_BREDR, remotedeviceList); EXPECT_EQ((int)remotedeviceList.size(), 0); GTEST_LOG_(INFO) << "Host_ModuleTest_GetPairedDevices_00100 end"; @@ -719,7 +761,7 @@ HWTEST_F(HostTest, Host_ModuleTest_GetDeviceType_00100, TestSize.Level1) host_ = &BluetoothHost::GetDefaultHost(); BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); - EXPECT_EQ(device_.GetDeviceType(), INVALID_VALUE); + EXPECT_EQ(device_.GetDeviceType(), INVALID_TYPE); GTEST_LOG_(INFO) << "Host_ModuleTest_GetDeviceType_00100 end"; } @@ -765,11 +807,42 @@ HWTEST_F(HostTest, Host_ModuleTest_StartPair_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_StartPair_00100 start"; BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); - EXPECT_FALSE(device_.StartPair()); + EXPECT_TRUE(device_.StartPair()); GTEST_LOG_(INFO) << "Host_ModuleTest_StartPair_00100 end"; } +/** + * @tc.number: Host_ModuleTest_StartPair_00200 + * @tc.name: + * @tc.desc: + */ +HWTEST_F(HostTest, Host_ModuleTest_StartPair_00200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Host_ModuleTest_StartPair_00200 start"; + + BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); + EXPECT_FALSE(device_.StartPair()); + + GTEST_LOG_(INFO) << "Host_ModuleTest_StartPair_00200 end"; +} + +/** + * @tc.number: Host_ModuleTest_StartPair_00300 + * @tc.name: + * @tc.desc: + */ +HWTEST_F(HostTest, Host_ModuleTest_StartPair_00300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Host_ModuleTest_StartPair_00300 start"; + + BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); + std::this_thread::sleep_for(std::chrono::seconds(12)); + EXPECT_TRUE(device_.StartPair()); + + GTEST_LOG_(INFO) << "Host_ModuleTest_StartPair_00300 end"; +} + /** * @tc.number: Host_ModuleTest_CancelPairing_00100 * @tc.name: @@ -780,6 +853,7 @@ HWTEST_F(HostTest, Host_ModuleTest_CancelPairing_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_CancelPairing_00100 start"; BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); + std::this_thread::sleep_for(std::chrono::seconds(12)); EXPECT_FALSE(device_.CancelPairing()); GTEST_LOG_(INFO) << "Host_ModuleTest_CancelPairing_00100 end"; @@ -840,12 +914,31 @@ HWTEST_F(HostTest, Host_ModuleTest_GetDeviceClass_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_GetDeviceClass_00100 start"; BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); - BluetoothDeviceClass getLocalcod = device_.GetDeviceClass(); - EXPECT_EQ(device_.GetDeviceClass().GetMajorClass(), getLocalcod.GetMajorClass()); + int cod = 0; + (void)device_.GetDeviceClass(cod); + BluetoothDeviceClass getLocalcod = BluetoothDeviceClass(cod); + EXPECT_EQ(getLocalcod.GetMajorClass(), getLocalcod.GetMajorClass()); GTEST_LOG_(INFO) << "Host_ModuleTest_GetDeviceClass_00100 end"; } +/** + * @tc.number: Host_ModuleTest_GetDeviceClass_00200 + * @tc.name: + * @tc.desc: + */ +HWTEST_F(HostTest, Host_ModuleTest_GetDeviceClass_00200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "Host_ModuleTest_GetDeviceClass_00200 start"; + + BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); + int cod = 0; + (void)device_.GetDeviceClass(cod); + BluetoothDeviceClass getLocalcod = BluetoothDeviceClass(cod); + EXPECT_EQ(getLocalcod.GetClassOfDevice(), 0); + GTEST_LOG_(INFO) << "Host_ModuleTest_GetDeviceClass_00200 end"; +} + /** * @tc.number: Host_ModuleTest_GetDeviceUuids_00100 * @tc.name: @@ -887,8 +980,18 @@ HWTEST_F(HostTest, Host_ModuleTest_SetDevicePairingConfirmation_00100, TestSize. GTEST_LOG_(INFO) << "Host_ModuleTest_SetDevicePairingConfirmation_00100 start"; BluetoothRemoteDevice device_("00:00:00:00:00:00", BT_TRANSPORT_BREDR); - EXPECT_FALSE(device_.SetDevicePairingConfirmation(true)); - EXPECT_FALSE(device_.SetDevicePairingConfirmation(false)); + bool ret = false; + int result = device_.SetDevicePairingConfirmation(true); + if (result == BT_SUCCESS) { + ret = true; + } + EXPECT_FALSE(ret); + bool isSuccess = false; + result = device_.SetDevicePairingConfirmation(true); + if (result == BT_SUCCESS) { + isSuccess = true; + } + EXPECT_FALSE(isSuccess); GTEST_LOG_(INFO) << "Host_ModuleTest_SetDevicePairingConfirmation_00100 end"; } @@ -986,7 +1089,12 @@ HWTEST_F(HostTest, Host_ModuleTest_DisableBt_00100, TestSize.Level1) GTEST_LOG_(INFO) << "Host_ModuleTest_DisableBt_00100 start"; host_ = &BluetoothHost::GetDefaultHost(); - EXPECT_TRUE(host_->DisableBt()); + bool isSuccess = false; + int ret = host_->DisableBt(); + if (ret == BT_SUCCESS) { + isSuccess = true; + } + EXPECT_TRUE(isSuccess); std::this_thread::sleep_for(std::chrono::seconds(3)); GTEST_LOG_(INFO) << "Host_ModuleTest_DisableBt_00100 end"; diff --git a/test/unittest/pan/pan_test.cpp b/test/unittest/pan/pan_test.cpp index 07ff0648..4d74b870 100644 --- a/test/unittest/pan/pan_test.cpp +++ b/test/unittest/pan/pan_test.cpp @@ -100,8 +100,9 @@ HWTEST_F(PanTest, PAN_ModuleTest_GetDevicesByStates_00100, TestSize.Level1) profile_ = Pan::GetProfile(); std::vector states; std::vector bluetoothRemoteDeviceAddr; - std::vector bluetoothRemoteDeviceByState = profile_->GetDevicesByStates(states); - EXPECT_TRUE(CompareDevice(bluetoothRemoteDeviceByState, bluetoothRemoteDeviceAddr)); + std::vector devices; + profile_->GetDevicesByStates(states, devices); + EXPECT_TRUE(CompareDevice(devices, bluetoothRemoteDeviceAddr)); GTEST_LOG_(INFO) << "PAN_ModuleTest_GetDevicesByStates_00100 end"; } @@ -120,7 +121,9 @@ HWTEST_F(PanTest, PAN_ModuleTest_GetDeviceState_00100, TestSize.Level1) int sucess = static_cast(BTConnectState::DISCONNECTED); BluetoothRemoteDevice device; profile_ = Pan::GetProfile(); - EXPECT_EQ(sucess, profile_->GetDeviceState(device)); + int32_t state = static_cast(BTConnectState::DISCONNECTED); + profile_->GetDeviceState(device, state); + EXPECT_EQ(sucess, state); GTEST_LOG_(INFO) << "PAN_ModuleTest_GetDeviceState_00100 end"; } @@ -225,7 +228,9 @@ HWTEST_F(PanTest, PAN_ModuleTest_IsTetheringOn_00100, TestSize.Level1) GTEST_LOG_(INFO) << "IsTetheringOn function test"; profile_ = Pan::GetProfile(); - EXPECT_FALSE(profile_->IsTetheringOn()); + bool result = false; + profile_->IsTetheringOn(result); + EXPECT_FALSE(result); GTEST_LOG_(INFO) << "PAN_ModuleTest_IsTetheringOn_00100 end"; } -- Gitee