diff --git a/bundle.json b/bundle.json index c52eef0a77e52e28a571d2e8e19e7e35414843a7..1a1b35526ef8f688a4b40c37c31ecfc2bf35df23 100644 --- a/bundle.json +++ b/bundle.json @@ -272,6 +272,9 @@ }, "name": "//foundation/communication/bluetooth/frameworks/js/napi/src/common:bt_napi_common" } + ], + "test": [ + "//foundation/communication/bluetooth/test:unit_test" ] } } diff --git a/frameworks/inner/ipc/common/bt_def.h b/frameworks/inner/ipc/common/bt_def.h index f422586f8b4f04d38738f01e14cf99259cdf1bcf..f338a333348cb916146b4d30f05f0ff1f98fc7aa 100644 --- a/frameworks/inner/ipc/common/bt_def.h +++ b/frameworks/inner/ipc/common/bt_def.h @@ -1815,6 +1815,12 @@ enum BluetoothSwitchState { STATE_HALF, }; +enum BluetoothTransferredSwitchAction { + TRANS_ACTION_ENABLE_BLUETOOTH = 0, + TRANS_ACTION_DISABLE_BLUETOOTH, + TRANS_ACTION_ENABLE_BLUETOOTH_TO_RESTRICT_MODE, +}; + enum ControlType { PLAY = 0, VIBRATE = 1, diff --git a/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h b/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h index 5a76da0a2d2da090c3a81ac70c597e35437a9f79..75bd63aeb72a87625f49d1c08fc53ef9c438b532 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h +++ b/frameworks/inner/ipc/include/bluetooth_host_observer_stub.h @@ -51,6 +51,8 @@ private: MessageParcel &data, MessageParcel &reply); static int32_t OnBluetoothStateChangedInner(BluetoothHostObserverStub *stub, MessageParcel &data, MessageParcel &reply); + static int32_t OnBluetoothSwitchActionInner(BluetoothHostObserverStub *stub, + MessageParcel &data, MessageParcel &reply); static int32_t OnBluetoothRefusePolicyChangedInner(BluetoothHostObserverStub *stub, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/inner/ipc/include/bluetooth_host_proxy.h b/frameworks/inner/ipc/include/bluetooth_host_proxy.h index 5e71b4d6f25f18efc4c507534ba2f355f08b43a9..73ba1fdb61196f5cff8de4d105eae0379cb99c86 100644 --- a/frameworks/inner/ipc/include/bluetooth_host_proxy.h +++ b/frameworks/inner/ipc/include/bluetooth_host_proxy.h @@ -34,7 +34,7 @@ public: void RegisterObserver(const sptr &observer) override; void DeregisterObserver(const sptr &observer) override; int32_t EnableBt() override; - int32_t DisableBt(bool isAsync) override; + int32_t DisableBt(bool isAsync, const std::string &callingName) override; int32_t SatelliteControl(int type, int state) override; sptr GetProfile(const std::string &name) override; sptr GetBleRemote(const std::string &name) override; @@ -42,7 +42,7 @@ public: int32_t GetBtState(int &state) override; int32_t GetLocalAddress(std::string &addr) override; int32_t DisableBle() override; - int32_t EnableBle(bool noAutoConnect, bool isAsync) override; + int32_t EnableBle(bool noAutoConnect, bool isAsync, const std::string &callingName) override; std::vector GetProfileList() override; int32_t GetMaxNumConnectedAudioDevices() override; int32_t GetBtConnectionState(int &state) override; @@ -109,7 +109,7 @@ public: int32_t SetVirtualAutoConnectType(const std::string &address, int connType, int businessType) override; int32_t SetFastScanLevel(int level) override; void UpdateVirtualDevice(int32_t action, const std::string &address) override; - int32_t EnableBluetoothToRestrictMode(void) override; + int32_t EnableBluetoothToRestrictMode(const std::string &callingName) override; int32_t ControlDeviceAction(const std::string &deviceId, uint32_t controlType, uint32_t controlTypeVal, uint32_t controlObject) override; int32_t GetLastConnectionTime(const std::string &address, int64_t &connectionTime) override; @@ -123,6 +123,7 @@ public: int32_t GetCarKeyDfxData(std::string &dfxData) override; int32_t SetCarKeyCardData(const std::string &address, int32_t action) override; int32_t NotifyDialogResult(uint32_t dialogType, bool dialogResult) override; + void SetCallingPackageName(const std::string &address, const std::string &packageName) override; private: int32_t InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); static inline BrokerDelegator delegator_; diff --git a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h index 51975363328577f8126a53be3fa3cba0554984ee..2dc8d62161d3c311cafbe40661cbe7bf513bcc15 100644 --- a/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h +++ b/frameworks/inner/ipc/interface/bluetooth_service_ipc_interface_code.h @@ -196,6 +196,7 @@ enum BluetoothHostObserverInterfaceCode { BT_HOST_OBSERVER_DEVICE_ADDR_CHANGED, BT_HOST_OBSERVER_STATE_CHANGE_V2, BT_HOST_OBSERVER_REFUSE_POLICY_CHANGE, + BT_HOST_OBSERVER_SWITCH_ACTION_TRANSFER, // The last code, if you want to add a new code, please add it before this BT_HOST_OBSERVER_BUTT }; @@ -293,6 +294,7 @@ enum BluetoothHostInterfaceCode { BT_GET_CAR_KEY_DFX_DATA, BT_SET_CAR_KEY_CARD_DATA, BT_NOTIFY_DIALOG_RESULT, + BT_SET_CALLING_PACKAGE_NAME, // The last code, if you want to add a new code, please add it before this BT_HOST_BUTT }; diff --git a/frameworks/inner/ipc/interface/i_bluetooth_host.h b/frameworks/inner/ipc/interface/i_bluetooth_host.h index 878b606bc40e714821d10b0cfc8578e82a06a540..45ccf7367cfafba2b03d3ed0bacead5d34bcfc9b 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host.h @@ -60,7 +60,7 @@ public: virtual void RegisterObserver(const sptr &observer) = 0; virtual void DeregisterObserver(const sptr &observer) = 0; virtual int32_t EnableBt() = 0; - virtual int32_t DisableBt(bool isAsync) = 0; + virtual int32_t DisableBt(bool isAsync, const std::string &callingName) = 0; virtual int32_t SatelliteControl(int type, int state) = 0; virtual sptr GetProfile(const std::string &name) = 0; virtual sptr GetBleRemote(const std::string &name) = 0; @@ -68,7 +68,7 @@ public: virtual int32_t GetBtState(int &state) = 0; virtual int32_t GetLocalAddress(std::string &addr) = 0; virtual int32_t DisableBle() = 0; - virtual int32_t EnableBle(bool noAutoConnect, bool isAsync) = 0; + virtual int32_t EnableBle(bool noAutoConnect, bool isAsync, const std::string &callingName) = 0; virtual std::vector GetProfileList() = 0; virtual int32_t GetMaxNumConnectedAudioDevices() = 0; virtual int32_t GetBtConnectionState(int &state) = 0; @@ -136,7 +136,7 @@ public: virtual int32_t SetVirtualAutoConnectType(const std::string &address, int connType, int businessType) = 0; virtual int32_t SetFastScanLevel(int level) = 0; virtual void UpdateVirtualDevice(int32_t action, const std::string &address) = 0; - virtual int32_t EnableBluetoothToRestrictMode(void) = 0; + virtual int32_t EnableBluetoothToRestrictMode(const std::string &callingName) = 0; virtual int32_t ControlDeviceAction(const std::string &deviceId, uint32_t controlType, uint32_t controlTypeVal, uint32_t controlObject) = 0; virtual int32_t GetLastConnectionTime(const std::string &address, int64_t &connectionTime) = 0; @@ -150,6 +150,7 @@ public: virtual int32_t GetCarKeyDfxData(std::string &dfxData) = 0; virtual int32_t SetCarKeyCardData(const std::string &address, int32_t action) = 0; virtual int32_t NotifyDialogResult(uint32_t dialogType, bool dialogResult) = 0; + virtual void SetCallingPackageName(const std::string &address, const std::string &packageName) = 0; }; } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h b/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h index a92ce1f3bfa9da6a117066a94933cc4f9b924974..4c54492e49490a6336441416ad8670931b8c5171 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_host_observer.h @@ -39,6 +39,7 @@ public: virtual void OnDeviceNameChanged(const std::string &deviceName) = 0; virtual void OnDeviceAddrChanged(const std::string &address) = 0; virtual void OnBluetoothStateChanged(int32_t state) = 0; + virtual void OnBluetoothSwitchAction(int32_t action, const std::string &callingName) = 0; virtual void OnRefusePolicyChanged(const int32_t pid, const int64_t prohibitedSecondsTime) = 0; }; } // namespace Bluetooth diff --git a/frameworks/inner/ipc/interface/i_bluetooth_socket.h b/frameworks/inner/ipc/interface/i_bluetooth_socket.h index 338c8aa210bb080adabfebfbaaf80e046b756683..c33d25e3cbb02f6f44ec6240a1e4e9edbec04776 100644 --- a/frameworks/inner/ipc/interface/i_bluetooth_socket.h +++ b/frameworks/inner/ipc/interface/i_bluetooth_socket.h @@ -32,6 +32,7 @@ struct ListenSocketParam { int32_t securityFlag; int32_t type; sptr observer; + int32_t psm; }; struct ConnectSocketParam { diff --git a/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp b/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp index 3251493c75fc04ed1f91069b309f683d8422bd02..a423022fb1651a3c33250b7eb6a60a725210cdff 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_observer_stub.cpp @@ -42,6 +42,8 @@ BluetoothHostObserverStub::BluetoothHostObserverStub() BluetoothHostObserverStub::OnDeviceAddrChangedInner; memberFuncMap_[static_cast(BluetoothHostObserverInterfaceCode::BT_HOST_OBSERVER_STATE_CHANGE_V2)] = BluetoothHostObserverStub::OnBluetoothStateChangedInner; + memberFuncMap_[static_cast(BluetoothHostObserverInterfaceCode::BT_HOST_OBSERVER_SWITCH_ACTION_TRANSFER)] = + BluetoothHostObserverStub::OnBluetoothSwitchActionInner; memberFuncMap_[static_cast(BluetoothHostObserverInterfaceCode::BT_HOST_OBSERVER_REFUSE_POLICY_CHANGE)] = BluetoothHostObserverStub::OnBluetoothRefusePolicyChangedInner; } @@ -187,6 +189,15 @@ int32_t BluetoothHostObserverStub::OnBluetoothStateChangedInner(BluetoothHostObs return NO_ERROR; } +int32_t BluetoothHostObserverStub::OnBluetoothSwitchActionInner(BluetoothHostObserverStub *stub, + MessageParcel &data, MessageParcel &reply) +{ + int32_t action = data.ReadInt32(); + std::string name = data.ReadString(); + stub->OnBluetoothSwitchAction(action, name); + return NO_ERROR; +} + int32_t BluetoothHostObserverStub::OnBluetoothRefusePolicyChangedInner( BluetoothHostObserverStub *stub, MessageParcel &data, MessageParcel &reply) { diff --git a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp index 85ca100db1417a85b1f200eca26142a6e264dbba..7d9b6e6975dbf5eb45a5145f52d7df231db7bd1d 100644 --- a/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_host_proxy.cpp @@ -85,7 +85,7 @@ int32_t BluetoothHostProxy::EnableBt() return reply.ReadInt32(); } -int32_t BluetoothHostProxy::DisableBt(bool isAsync) +int32_t BluetoothHostProxy::DisableBt(bool isAsync, const std::string &callingName) { HILOGI("BluetoothHostProxy::DisableBt starts"); MessageParcel data; @@ -97,6 +97,9 @@ int32_t BluetoothHostProxy::DisableBt(bool isAsync) HILOGE("BluetoothHostProxy::DisableBt WriteBool isAsync error"); return BT_ERR_IPC_TRANS_FAILED; } + if (!data.WriteString(callingName)) { + return BT_ERR_IPC_TRANS_FAILED; + } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; @@ -243,7 +246,7 @@ int32_t BluetoothHostProxy::DisableBle() return reply.ReadInt32(); } -int32_t BluetoothHostProxy::EnableBle(bool noAutoConnect, bool isAsync) +int32_t BluetoothHostProxy::EnableBle(bool noAutoConnect, bool isAsync, const std::string &callingName) { MessageParcel data; if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { @@ -258,6 +261,9 @@ int32_t BluetoothHostProxy::EnableBle(bool noAutoConnect, bool isAsync) HILOGE("BluetoothHostProxy::EnableBle WriteBool isAsync error"); return BT_ERR_IPC_TRANS_FAILED; } + if (!data.WriteString(callingName)) { + return BT_ERR_IPC_TRANS_FAILED; + } MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; @@ -1764,13 +1770,16 @@ void BluetoothHostProxy::UpdateVirtualDevice(int32_t action, const std::string & return; } -int32_t BluetoothHostProxy::EnableBluetoothToRestrictMode(void) +int32_t BluetoothHostProxy::EnableBluetoothToRestrictMode(const std::string &callingName) { MessageParcel data; CHECK_AND_RETURN_LOG_RET(data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor()), BT_ERR_IPC_TRANS_FAILED, "WriteInterfaceToken error"); MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; + if (!data.WriteString(callingName)) { + return BT_ERR_IPC_TRANS_FAILED; + } int32_t error = InnerTransact( BluetoothHostInterfaceCode::BT_ENABLE_BLUETOOTH_TO_RESTRICT_MODE, option, data, reply); CHECK_AND_RETURN_LOG_RET((error == BT_NO_ERROR), BT_ERR_INTERNAL_ERROR, "error: %{public}d", error); @@ -2029,5 +2038,24 @@ int32_t BluetoothHostProxy::NotifyDialogResult(uint32_t dialogType, bool dialogR } return reply.ReadInt32(); } + +void BluetoothHostProxy::SetCallingPackageName(const std::string &address, const std::string &packageName) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(BluetoothHostProxy::GetDescriptor())) { + HILOGE("BluetoothHostProxy::SetCallingPackageName WriteInterfaceToken error"); + return; + } + CHECK_AND_RETURN_LOG(data.WriteString(address), "write address error"); + CHECK_AND_RETURN_LOG(data.WriteString(packageName), "write packageName error"); + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + int32_t error = InnerTransact( + BluetoothHostInterfaceCode::BT_SET_CALLING_PACKAGE_NAME, option, data, reply); + if (error != BT_NO_ERROR) { + HILOGE("BluetoothHostProxy::SetCallingPackageName done fail error: %{public}d", error); + return; + } +} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp b/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp index 946a20a98904115621df249adb7ab929c4d0540f..49fa5734ac5cea4b91f5cd0601288f7530f33c84 100644 --- a/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp +++ b/frameworks/inner/ipc/src/bluetooth_socket_proxy.cpp @@ -61,6 +61,7 @@ int BluetoothSocketProxy::Listen(ListenSocketParam ¶m, int &fd) CHECK_AND_RETURN_LOG_RET( data.WriteInt32(param.securityFlag), BT_ERR_IPC_TRANS_FAILED, "write param.securityFlag error"); CHECK_AND_RETURN_LOG_RET(data.WriteInt32(param.type), BT_ERR_IPC_TRANS_FAILED, "write param.type error"); + CHECK_AND_RETURN_LOG_RET(data.WriteInt32(param.psm), BT_ERR_IPC_TRANS_FAILED, "write param.psm error"); CHECK_AND_RETURN_LOG_RET( data.WriteRemoteObject(param.observer->AsObject()), BT_ERR_IPC_TRANS_FAILED, "write object errorr"); diff --git a/frameworks/inner/src/bluetooth_a2dp_snk.cpp b/frameworks/inner/src/bluetooth_a2dp_snk.cpp index feeffc507c2a35ead576dd08bc3520564ba39cf6..6b645bd1f771487b12a3f6b86fe7c5c8be575e96 100644 --- a/frameworks/inner/src/bluetooth_a2dp_snk.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_snk.cpp @@ -129,6 +129,7 @@ void A2dpSink::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } diff --git a/frameworks/inner/src/bluetooth_a2dp_src.cpp b/frameworks/inner/src/bluetooth_a2dp_src.cpp index a796d22958ab70b29083efdf177327d93cdab2cc..137a3f616d42ff3458d0fcba30fe7bf23115d003 100644 --- a/frameworks/inner/src/bluetooth_a2dp_src.cpp +++ b/frameworks/inner/src/bluetooth_a2dp_src.cpp @@ -171,6 +171,7 @@ void A2dpSource::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } diff --git a/frameworks/inner/src/bluetooth_avrcp_tg.cpp b/frameworks/inner/src/bluetooth_avrcp_tg.cpp index f5d804168390487cb7dbb504501ddd073c4ef558..789836cda67c69ad4f6046834ff85f2d0cd38f2e 100644 --- a/frameworks/inner/src/bluetooth_avrcp_tg.cpp +++ b/frameworks/inner/src/bluetooth_avrcp_tg.cpp @@ -153,15 +153,14 @@ int32_t AvrcpTarget::GetDeviceAbsVolumeAbility(const BluetoothRemoteDevice &devi void AvrcpTarget::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); - std::lock_guard lock(pimpl->observerMutex_); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } void AvrcpTarget::UnregisterObserver(std::shared_ptr observer) { HILOGD("enter"); - std::lock_guard lock(pimpl->observerMutex_); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); pimpl->observers_.Deregister(observer); } diff --git a/frameworks/inner/src/bluetooth_gatt_client.cpp b/frameworks/inner/src/bluetooth_gatt_client.cpp index 5999b16e0df6ad7af279d4e1e3d3492c5ce32b4f..70a5d76ce36ef75974b59d6cd47041f0533bfabb 100644 --- a/frameworks/inner/src/bluetooth_gatt_client.cpp +++ b/frameworks/inner/src/bluetooth_gatt_client.cpp @@ -415,12 +415,12 @@ int GattClient::impl::DiscoverStart() { std::unique_lock lock(discoverInformation_.mutex_); - while (discoverInformation_.isDiscovering_) { - auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT)); - if (ret == std::cv_status::timeout) { - HILOGE("timeout"); - return BT_ERR_INTERNAL_ERROR; - } + auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT), [this] { + return !discoverInformation_.isDiscovering_; + }); + if (ret == false) { + HILOGE("timeout"); + return BT_ERR_INTERNAL_ERROR; } discoverInformation_.isDiscovering_ = true; } @@ -455,6 +455,10 @@ void GattClient::impl::DiscoverComplete(int state) } if (ret) { std::shared_ptr clientSptr = (callback_).lock(); + if (!clientSptr) { + HILOGE("callback is nullptr"); + return; + } clientSptr->OnServicesDiscovered(state); } } @@ -516,12 +520,12 @@ void GattClient::impl::GetServices() } std::unique_lock lock(discoverInformation_.mutex_); - while (discoverInformation_.isDiscovering_) { - auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT)); - if (ret == std::cv_status::timeout) { - HILOGE("timeout"); - return; - } + auto ret = discoverInformation_.condition_.wait_for(lock, std::chrono::seconds(WAIT_TIMEOUT), [this] { + return !discoverInformation_.isDiscovering_; + }); + if (ret == false) { + HILOGE("timeout"); + return; } if (isGetServiceYet_) { HILOGD("isGetServiceYet_ is true"); @@ -890,7 +894,7 @@ int GattClient::SetNotifyCharacteristicInner(GattCharacteristic &characteristic, CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); bool isValid = (pimpl != nullptr && pimpl->Init(weak_from_this())); CHECK_AND_RETURN_LOG_RET(isValid, BT_ERR_INTERNAL_ERROR, "pimpl or gatt client proxy is nullptr"); - + std::lock_guard lockConn(pimpl->connStateMutex_); if (pimpl->connectionState_ != static_cast(BTConnectState::CONNECTED)) { HILOGE("Request not supported"); diff --git a/frameworks/inner/src/bluetooth_hfp_ag.cpp b/frameworks/inner/src/bluetooth_hfp_ag.cpp index ba01b2e21545db9e79cc240c10c871b4b683800f..e2d61f06fe6cdd87db5a0a23a57a4095506bac69 100644 --- a/frameworks/inner/src/bluetooth_hfp_ag.cpp +++ b/frameworks/inner/src/bluetooth_hfp_ag.cpp @@ -239,7 +239,7 @@ struct HandsFreeAudioGateway::impl { void PhoneStateChanged(BluetoothPhoneState &phoneState) { - HILOGI("numActive: %{public}d, numHeld: %{public}d, callState: %{public}d, type: %{public}d", + HILOG_COMM_INFO("numActive: %{public}d, numHeld: %{public}d, callState: %{public}d, type: %{public}d", phoneState.GetActiveNum(), phoneState.GetHeldNum(), phoneState.GetCallState(), phoneState.GetCallType()); sptr proxy = GetRemoteProxy(PROFILE_HFP_AG); CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is null"); @@ -257,7 +257,7 @@ struct HandsFreeAudioGateway::impl { bool OpenVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); sptr proxy = GetRemoteProxy(PROFILE_HFP_AG); if (proxy != nullptr && device.IsValidBluetoothRemoteDevice()) { return proxy->OpenVoiceRecognition(BluetoothRawAddress(device.GetDeviceAddr())); @@ -267,7 +267,7 @@ struct HandsFreeAudioGateway::impl { bool CloseVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); sptr proxy = GetRemoteProxy(PROFILE_HFP_AG); if (proxy != nullptr && device.IsValidBluetoothRemoteDevice()) { return proxy->CloseVoiceRecognition(BluetoothRawAddress(device.GetDeviceAddr())); @@ -610,7 +610,7 @@ void HandsFreeAudioGateway::ClccResponse( bool HandsFreeAudioGateway::OpenVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("OpenVoiceRecognition: %{public}s", GET_ENCRYPT_ADDR(device)); if (!IS_BT_ENABLED()) { HILOGE("bluetooth is off."); return false; @@ -624,7 +624,7 @@ bool HandsFreeAudioGateway::OpenVoiceRecognition(const BluetoothRemoteDevice &de bool HandsFreeAudioGateway::CloseVoiceRecognition(const BluetoothRemoteDevice &device) { - HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device)); + HILOG_COMM_INFO("CloseVoiceRecognition: %{public}s", GET_ENCRYPT_ADDR(device)); if (!IS_BT_ENABLED()) { HILOGE("bluetooth is off."); return false; @@ -750,6 +750,7 @@ void HandsFreeAudioGateway::RegisterObserver(std::shared_ptrRegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_hfp_hf.cpp b/frameworks/inner/src/bluetooth_hfp_hf.cpp index 4d5ccc9280ff51490f1e775fd19342f65beaa9a4..07972470bd7c6de31d84ab1f8e4c1d33a1da8aee 100644 --- a/frameworks/inner/src/bluetooth_hfp_hf.cpp +++ b/frameworks/inner/src/bluetooth_hfp_hf.cpp @@ -54,7 +54,8 @@ public: void OnScoStateChanged(const BluetoothRawAddress &device, int32_t state) override { - HILOGI("enter, device: %{public}s, state: %{public}d", GetEncryptAddr((device).GetAddress()).c_str(), state); + HILOG_COMM_INFO("OnScoStateChanged: %{public}s, state: %{public}d", + GetEncryptAddr((device).GetAddress()).c_str(), state); BluetoothRemoteDevice remoteDevice(device.GetAddress(), 0); observers_.ForEach([remoteDevice, state](std::shared_ptr observer) { observer->OnScoStateChanged(remoteDevice, state); @@ -762,6 +763,7 @@ void HandsFreeUnit::RegisterObserver(std::shared_ptr obse { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->RegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_hid_host.cpp b/frameworks/inner/src/bluetooth_hid_host.cpp index 268bc4fd8718973256044f562388e12fdf9a4727..1bce72d94edcb5ff4eb179830cbb80895a45fc79 100644 --- a/frameworks/inner/src/bluetooth_hid_host.cpp +++ b/frameworks/inner/src/bluetooth_hid_host.cpp @@ -329,6 +329,7 @@ void HidHost::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->RegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_host.cpp b/frameworks/inner/src/bluetooth_host.cpp index 575293c2965765f39abba0070ce2c83487078c4a..d0b525e5b5d6ba60fea99ba69b5d28f1b5d4b59c 100644 --- a/frameworks/inner/src/bluetooth_host.cpp +++ b/frameworks/inner/src/bluetooth_host.cpp @@ -145,6 +145,23 @@ public: } } + void OnBluetoothSwitchAction(int32_t action, const std::string &callingName) override + { + HILOGI("bluetooth switch action: %{public}d, callingName: %{public}s", action, callingName.c_str()); + std::lock_guard lock(host_.switchModuleMutex_); + CHECK_AND_RETURN_LOG(host_.switchModule_, "switchModule is nullptr"); + if (action == bluetooth::TRANS_ACTION_ENABLE_BLUETOOTH) { + host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH, callingName); + } + if (action == bluetooth::TRANS_ACTION_DISABLE_BLUETOOTH) { + host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, callingName); + } + if (action == bluetooth::TRANS_ACTION_ENABLE_BLUETOOTH_TO_RESTRICT_MODE) { + host_.switchModule_->ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE, callingName); + } + } + void OnDiscoveryStateChanged(int32_t status) override { HILOGD("enter, status: %{public}d", status); @@ -439,7 +456,7 @@ public: BluetoothSwitchAction() = default; ~BluetoothSwitchAction() override = default; - int EnableBluetooth(bool noAutoConnect, bool isAsync) override + int EnableBluetooth(bool noAutoConnect, std::string callingName, bool isAsync) override { CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(), BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !"); @@ -448,17 +465,17 @@ public: sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); - return proxy->EnableBle(noAutoConnect, isAsync); + return proxy->EnableBle(noAutoConnect, isAsync, callingName); } - int DisableBluetooth(bool isAsync) override + int DisableBluetooth(std::string callingName, bool isAsync) override { sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); - return proxy->DisableBt(isAsync); + return proxy->DisableBt(isAsync, callingName); } - int EnableBluetoothToRestrictMode(void) override + int EnableBluetoothToRestrictMode(std::string callingName) override { CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(), BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !"); @@ -467,7 +484,7 @@ public: sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr"); - return proxy->EnableBluetoothToRestrictMode(); + return proxy->EnableBluetoothToRestrictMode(callingName); } }; @@ -620,6 +637,7 @@ void BluetoothHost::RegisterObserver(std::shared_ptr obse { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->observers_.Register(observer); } @@ -640,12 +658,12 @@ int BluetoothHost::EnableBt() return proxy->EnableBt(); } -int BluetoothHost::DisableBt(bool isAsync) +int BluetoothHost::DisableBt(std::string name, bool isAsync) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, isAsync); + return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, name, isAsync); } static void PublishBtSwitchRestrictBluetoothEvent(void) @@ -665,17 +683,18 @@ static void PublishBtSwitchRestrictBluetoothEvent(void) } } -int BluetoothHost::RestrictBluetooth() +int BluetoothHost::RestrictBluetooth(std::string name) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); PublishBtSwitchRestrictBluetoothEvent(); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - int ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH); + int ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH, name); if (ret != BT_NO_ERROR) { return ret; } - ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE); + ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE, name); return ret; } @@ -686,6 +705,8 @@ int BluetoothHost::SatelliteControl(int type, int state) CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off."); } else if (type == static_cast(SATELLITE_CONTROL_MODE::BLUETOOTH_SWITCH)) { pimpl->LoadBluetoothHostService(); + } else if (type == static_cast(SATELLITE_CONTROL_MODE::SIGNALHUB_MAC_SWITCH)) { + CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_ERR_INVALID_STATE, "ble is off."); } else { HILOGE("Invalid control type: %{public}d", type); return BT_ERR_INVALID_PARAM; @@ -790,12 +811,12 @@ BluetoothRemoteDevice BluetoothHost::GetRemoteDevice(const std::string &addr, in return remoteDevice; } -int BluetoothHost::EnableBle(bool isAsync) +int BluetoothHost::EnableBle(std::string name, bool isAsync) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH, isAsync); + return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH, name, isAsync); } int BluetoothHost::EnableBluetoothNoAutoConnect() @@ -814,12 +835,13 @@ int BluetoothHost::DisableBle() return proxy->DisableBle(); } -int BluetoothHost::EnableBluetoothToRestrictMode(void) +int BluetoothHost::EnableBluetoothToRestrictMode(std::string name) { HILOGI("enter"); std::lock_guard lock(pimpl->switchModuleMutex_); CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr"); - return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE); + return pimpl->switchModule_->ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE, name); } bool BluetoothHost::IsBrEnabled() const @@ -1273,6 +1295,7 @@ void BluetoothHost::Close(void) { std::lock_guard lock(pimpl->switchModuleMutex_); pimpl->switchModule_ = nullptr; + BluetoothProfileManager::ClearSystemAbility(); } int32_t BluetoothHost::UpdateCloudBluetoothDevice(const std::vector &cloudDevices) @@ -1342,5 +1365,14 @@ int BluetoothHost::NotifyDialogResult(uint32_t dialogType, bool dialogResult) CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr"); return proxy->NotifyDialogResult(dialogType, dialogResult); } + +int32_t BluetoothHost::SetCallingPackageName(const std::string &address, const std::string &packageName) +{ + HILOGI("enter"); + sptr proxy = GetRemoteProxy(BLUETOOTH_HOST); + CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr"); + proxy->SetCallingPackageName(address, packageName); + return BT_NO_ERROR; +} } // namespace Bluetooth } // namespace OHOS diff --git a/frameworks/inner/src/bluetooth_pan.cpp b/frameworks/inner/src/bluetooth_pan.cpp index 02a7b5eb895301b1aa54bba5bde07aaa4268c7cc..37ae6de8d3c3938944bb6ca4c701e6479ea200cd 100644 --- a/frameworks/inner/src/bluetooth_pan.cpp +++ b/frameworks/inner/src/bluetooth_pan.cpp @@ -233,6 +233,7 @@ void Pan::RegisterObserver(std::shared_ptr observer) { HILOGD("enter"); CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null."); + CHECK_AND_RETURN_LOG(observer != nullptr, "observer is null."); pimpl->RegisterObserver(observer); } diff --git a/frameworks/inner/src/bluetooth_socket.cpp b/frameworks/inner/src/bluetooth_socket.cpp index 6db02798126b23c7d288ec456a63b8aa467e7c96..2c6b8a82f2de7b30180fea46f6f1b5bddb9850cb 100644 --- a/frameworks/inner/src/bluetooth_socket.cpp +++ b/frameworks/inner/src/bluetooth_socket.cpp @@ -90,7 +90,6 @@ struct ClientSocket::impl { std::shared_ptr observer); ~impl() { - HILOGI("ClientSocket::impl ~impl"); if (fd_ > 0) { shutdown(fd_, SHUT_RD); shutdown(fd_, SHUT_WR); @@ -422,14 +421,12 @@ ClientSocket::~ClientSocket() bool ClientSocket::Init() { HILOGI("ClientSocket Init"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, false, "pimpl is nullptr!"); return pimpl->Init(weak_from_this()); } int ClientSocket::Connect(int psm) { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); if (pimpl->type_ == TYPE_L2CAP_LE) { CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_ERR_INVALID_STATE, "BLE is not TURN_ON"); } else { @@ -484,21 +481,18 @@ int ClientSocket::Connect(int psm) void ClientSocket::Close() { HILOGD("enter"); - CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is nullptr!"); return pimpl->Close(); } std::shared_ptr ClientSocket::GetInputStream() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, nullptr, "pimpl is nullptr!"); return pimpl->GetInputStream(); } std::shared_ptr ClientSocket::GetOutputStream() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, nullptr, "pimpl is nullptr!"); return pimpl->GetOutputStream(); } @@ -511,48 +505,41 @@ BluetoothRemoteDevice &ClientSocket::GetRemoteDevice() bool ClientSocket::IsConnected() const { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, false, "pimpl is nullptr!"); return pimpl->IsConnected(); } int ClientSocket::SetBufferSize(int bufferSize) { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, false, "pimpl is nullptr!"); return pimpl->SetBufferSize(bufferSize); } int ClientSocket::GetSocketFd() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); return pimpl->fd_; } int ClientSocket::GetL2capPsm() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("psm:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } int ClientSocket::GetRfcommScn() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("scn:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } uint32_t ClientSocket::GetMaxTransmitPacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxTransmitPacketSize:%{public}d", pimpl->maxTxPacketSize_.load()); return pimpl->maxTxPacketSize_; } uint32_t ClientSocket::GetMaxReceivePacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxReceivePacketSize:%{public}d", pimpl->maxRxPacketSize_.load()); return pimpl->maxRxPacketSize_; } @@ -569,7 +556,7 @@ bool ClientSocket::IsAllowSocketConnect(int socketType) } struct ServerSocket::impl { - impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt); + impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm); ~impl() { if (fd_ > 0) { @@ -604,7 +591,8 @@ struct ServerSocket::impl { .uuid = bluetooth::Uuid::ConvertFrom128Bits(uuid_.ConvertTo128Bits()), .securityFlag = (int32_t)getSecurityFlags(), .type = (int32_t)type_, - .observer = observer_ + .observer = observer_, + .psm = psm_ }; int ret = proxy->Listen(param, fd_); if (ret != BT_NO_ERROR) { @@ -821,6 +809,7 @@ struct ServerSocket::impl { bool encrypt_; int fd_; int socketStatus_; + int psm_; std::string name_ { "" }; @@ -834,15 +823,21 @@ struct ServerSocket::impl { std::atomic maxRxPacketSize_{ 0 }; }; -ServerSocket::impl::impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt) - : uuid_(uuid), type_(type), encrypt_(encrypt), fd_(-1), socketStatus_(SOCKET_INIT), name_(name) +ServerSocket::impl::impl(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm) + : uuid_(uuid), type_(type), encrypt_(encrypt), fd_(-1), socketStatus_(SOCKET_INIT), psm_(psm), name_(name) { - HILOGD("(4 parameters) starts"); + HILOGD("(5 parameters) starts"); observer_ = new BluetoothServerSocketObserverStub(); } +ServerSocket::ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm) + : pimpl(new ServerSocket::impl(name, uuid, type, encrypt, psm)) +{ + HILOGD("type:%{public}d encrypt:%{public}d psm:%{public}d", type, encrypt, psm); +} + ServerSocket::ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt) - : pimpl(new ServerSocket::impl(name, uuid, type, encrypt)) + : pimpl(new ServerSocket::impl(name, uuid, type, encrypt, -1)) { HILOGD("type:%{public}d encrypt:%{public}d", type, encrypt); } @@ -853,21 +848,18 @@ ServerSocket::~ServerSocket() int ServerSocket::Listen() { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); return pimpl->Listen(); } std::shared_ptr ServerSocket::Accept(int timeout) { HILOGD("enter"); - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, nullptr, "pimpl is nullptr!"); return pimpl->Accept(timeout); } void ServerSocket::Close() { HILOGD("enter"); - CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is nullptr!"); return pimpl->Close(); } @@ -879,35 +871,30 @@ const std::string &ServerSocket::GetStringTag() int ServerSocket::GetL2capPsm() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("psm:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } int ServerSocket::GetRfcommScn() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("scn:%{public}d", pimpl->socketChannel_.load()); return pimpl->socketChannel_; } uint32_t ServerSocket::GetMaxTransmitPacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxTransmitPacketSize:%{public}d", pimpl->maxTxPacketSize_.load()); return pimpl->maxTxPacketSize_; } uint32_t ServerSocket::GetMaxReceivePacketSize() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); HILOGI("MaxReceivePacketSize:%{public}d", pimpl->maxRxPacketSize_.load()); return pimpl->maxRxPacketSize_; } int ServerSocket::GetSocketFd() { - CHECK_AND_RETURN_LOG_RET(pimpl != nullptr, BT_ERR_DEVICE_DISCONNECTED, "pimpl is nullptr!"); return pimpl->fd_; } diff --git a/frameworks/inner/src/bluetooth_socket_outputstream.cpp b/frameworks/inner/src/bluetooth_socket_outputstream.cpp index 840975748d00c69790ddacd693794688a7f3b4c4..04502003dcca6e396b6376ebfa55cff57ae1ac44 100644 --- a/frameworks/inner/src/bluetooth_socket_outputstream.cpp +++ b/frameworks/inner/src/bluetooth_socket_outputstream.cpp @@ -18,6 +18,7 @@ #include #include +#include #include "bluetooth_socket_outputstream.h" #include "bluetooth_log.h" #include "sys/socket.h" @@ -26,7 +27,15 @@ namespace OHOS { namespace Bluetooth { +static constexpr int32_t SOCKET_SEND_TIME_THRESHOLD = 1000; // 1000ms static constexpr int32_t SOCKET_PACKET_HEAD_LENGTH = 1512; +static int64_t GetNowTimestamp(void) +{ + struct timeval tv; + gettimeofday(&tv, nullptr); + int64_t timestamp = tv.tv_sec * 1000 + tv.tv_usec / 1000; + return timestamp; +} static constexpr int32_t AAM_UID = 7878; static constexpr int32_t AAM_BAD_RET = -978974; static constexpr int32_t SOFTBUS_UID = 1024; @@ -52,7 +61,7 @@ int OutputStream::Write(const uint8_t *buf, size_t length) if (sockOptRet != -1 && ioctlRet != -1 && static_cast(bufSize) > bytesInBuffer) { // -1代表无权限获取发送队列大小 // 该方法是跟踪send前socket发送通道是否占满导致发包阻塞 unsigned long availableLength = static_cast(bufSize) - bytesInBuffer; - int32_t sendLength = static_cast (length) + SOCKET_PACKET_HEAD_LENGTH; + int32_t sendLength = static_cast(length) + SOCKET_PACKET_HEAD_LENGTH; if (availableLength < static_cast(sendLength)) { HILOGW("send queue is full, availableLength is %{public}lu, sendlength is %{public}d", availableLength, sendLength); @@ -73,14 +82,19 @@ int OutputStream::Write(const uint8_t *buf, size_t length) } setTimeoutFlag_ = true; } - + int64_t beginTimestamp = GetNowTimestamp(); auto ret = send(socketFd_, buf, length, MSG_NOSIGNAL); + int64_t endTimestamp = GetNowTimestamp(); + if (endTimestamp - beginTimestamp > SOCKET_SEND_TIME_THRESHOLD) { + HILOGE("socket send time %{public}" PRId64, endTimestamp - beginTimestamp); + } HILOGD("ret: %{public}zd", ret); if (ret <= 0) { - setTimeoutFlag_ == false; + setTimeoutFlag_ = false; HILOGE("socket write exception! ret:%{public}zd errno:%{public}d", ret, errno); + return errno; } return ret; } diff --git a/frameworks/inner/src/bluetooth_switch_module.cpp b/frameworks/inner/src/bluetooth_switch_module.cpp index 2f9b30fd9c6eff2b36f4799ebf49c61461ba7833..2ce69d90857351abb1c7c3e39edbb474ef5fc3d4 100644 --- a/frameworks/inner/src/bluetooth_switch_module.cpp +++ b/frameworks/inner/src/bluetooth_switch_module.cpp @@ -48,7 +48,8 @@ void BluetoothSwitchModule::LogBluetoothSwitchEvent(BluetoothSwitchEvent event) } } -int BluetoothSwitchModule::ProcessBluetoothSwitchEvent(BluetoothSwitchEvent event, bool isAsync) +int BluetoothSwitchModule::ProcessBluetoothSwitchEvent( + BluetoothSwitchEvent event, std::string callingName, bool isAsync) { CHECK_AND_RETURN_LOG_RET(switchAction_, BT_ERR_INTERNAL_ERROR, "switchAction is nullptr"); @@ -56,11 +57,11 @@ int BluetoothSwitchModule::ProcessBluetoothSwitchEvent(BluetoothSwitchEvent even LogBluetoothSwitchEvent(event); switch (event) { case BluetoothSwitchEvent::ENABLE_BLUETOOTH: - return ProcessEnableBluetoothEvent(isAsync); + return ProcessEnableBluetoothEvent(callingName, isAsync); case BluetoothSwitchEvent::DISABLE_BLUETOOTH: - return ProcessDisableBluetoothEvent(isAsync); + return ProcessDisableBluetoothEvent(callingName, isAsync); case BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE: - return ProcessEnableBluetoothToRestrictModeEvent(); + return ProcessEnableBluetoothToRestrictModeEvent(callingName); case BluetoothSwitchEvent::BLUETOOTH_ON: return ProcessBluetoothOnEvent(); case BluetoothSwitchEvent::BLUETOOTH_OFF: @@ -107,38 +108,41 @@ int BluetoothSwitchModule::ProcessBluetoothSwitchAction( isBtSwitchProcessing_ = false; ffrtQueue_.cancel(taskTimeoutHandle_); } - // Considering interface compatibility, when a thiry party app invokes the Bluetooth switch interface, - // a dialog box is displayed, indicating that the call is success. - if (ret == BT_ERR_DIALOG_FOR_USER_CONFIRM) { + // Considering interface compatibility, + // 1) when a thiry party app invokes the Bluetooth switch interface, a dialog box is displayed, + // indicating that the call is success. + // 2) when the switch operation of the system application is transferred to another module, + // the interface call is considered successful. + if (ret == BT_ERR_DIALOG_FOR_USER_CONFIRM || ret == BT_ERR_SWITCH_OP_TRANSFERRED) { ret = BT_NO_ERROR; } return ret; } -int BluetoothSwitchModule::ProcessEnableBluetoothEvent(bool isAsync) +int BluetoothSwitchModule::ProcessEnableBluetoothEvent(const std::string &callingName, bool isAsync) { return ProcessBluetoothSwitchAction( - [this, isAsync]() { + [this, callingName, isAsync]() { bool noAutoConnect = noAutoConnect_.load(); if (noAutoConnect) { SetNoAutoConnect(false); } - return switchAction_->EnableBluetooth(noAutoConnect, isAsync); + return switchAction_->EnableBluetooth(noAutoConnect, callingName, isAsync); }, BluetoothSwitchEvent::ENABLE_BLUETOOTH); } -int BluetoothSwitchModule::ProcessDisableBluetoothEvent(bool isAsync) +int BluetoothSwitchModule::ProcessDisableBluetoothEvent(const std::string &callingName, bool isAsync) { return ProcessBluetoothSwitchAction( - [this, isAsync]() { return switchAction_->DisableBluetooth(isAsync); }, + [this, callingName, isAsync]() { return switchAction_->DisableBluetooth(callingName, isAsync); }, BluetoothSwitchEvent::DISABLE_BLUETOOTH); } -int BluetoothSwitchModule::ProcessEnableBluetoothToRestrictModeEvent(void) +int BluetoothSwitchModule::ProcessEnableBluetoothToRestrictModeEvent(const std::string &callingName) { return ProcessBluetoothSwitchAction( - [this]() { return switchAction_->EnableBluetoothToRestrictMode(); }, + [this, callingName]() { return switchAction_->EnableBluetoothToRestrictMode(callingName); }, BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE); } diff --git a/frameworks/inner/src/bluetooth_switch_module.h b/frameworks/inner/src/bluetooth_switch_module.h index 90191dc34330e1a27d8078b1fe61d7af37ba9735..ccd9cb1d0f7573c5684ec846392139d2a5f30d79 100644 --- a/frameworks/inner/src/bluetooth_switch_module.h +++ b/frameworks/inner/src/bluetooth_switch_module.h @@ -30,9 +30,9 @@ public: IBluetoothSwitchAction() = default; virtual ~IBluetoothSwitchAction() = default; - virtual int EnableBluetooth(bool, bool) = 0; - virtual int DisableBluetooth(bool) = 0; - virtual int EnableBluetoothToRestrictMode(void) = 0; + virtual int EnableBluetooth(bool, std::string, bool) = 0; + virtual int DisableBluetooth(std::string, bool) = 0; + virtual int EnableBluetoothToRestrictMode(std::string) = 0; }; enum class BluetoothSwitchEvent : int { @@ -51,13 +51,13 @@ public: : ffrtQueue_("bt_switch"), switchAction_(std::move(switchAction)) {} ~BluetoothSwitchModule() = default; - int ProcessBluetoothSwitchEvent(BluetoothSwitchEvent event, bool isAsync = false); + int ProcessBluetoothSwitchEvent(BluetoothSwitchEvent event, std::string callingName = "", bool isAsync = false); void SetNoAutoConnect(bool noAutoConnect); private: - int ProcessEnableBluetoothEvent(bool isAsync = false); - int ProcessDisableBluetoothEvent(bool isAsync = false); - int ProcessEnableBluetoothToRestrictModeEvent(void); + int ProcessEnableBluetoothEvent(const std::string &callingName, bool isAsync); + int ProcessDisableBluetoothEvent(const std::string &callingName, bool isAsync); + int ProcessEnableBluetoothToRestrictModeEvent(const std::string &callingName); int ProcessBluetoothOnEvent(void); int ProcessBluetoothOffEvent(void); int ProcessBluetoothHalfEvent(void); diff --git a/frameworks/js/napi/include/napi_bluetooth_ble_utils.h b/frameworks/js/napi/include/napi_bluetooth_ble_utils.h index 5a692ad52c15392da97aca32954f76b36363bdad..ced77c7090376845149ce2993ae158697c8f53e1 100644 --- a/frameworks/js/napi/include/napi_bluetooth_ble_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_ble_utils.h @@ -72,6 +72,7 @@ napi_value ScanDutyInit(napi_env env); napi_value MatchModeInit(napi_env env); napi_value PhyTypeInit(napi_env env); napi_value ScanReportModeInit(napi_env env); +napi_value GattDisconnectReasonInit(napi_env env); void SetGattClientDeviceId(const std::string &deviceId); std::string GetGattClientDeviceId(); diff --git a/frameworks/js/napi/include/napi_bluetooth_spp_server.h b/frameworks/js/napi/include/napi_bluetooth_spp_server.h index 5ecbfe191c7de0a9e74694e623551a29c3a05ec9..2b20619df3d681141df96d8cc6f7b9426f6034ae 100644 --- a/frameworks/js/napi/include/napi_bluetooth_spp_server.h +++ b/frameworks/js/napi/include/napi_bluetooth_spp_server.h @@ -42,6 +42,7 @@ struct NapiSppServer { static napi_value SppCloseServerSocket(napi_env env, napi_callback_info info); static napi_value RegisterSocketObserver(napi_env env, napi_callback_info info); static napi_value DeRegisterSocketObserver(napi_env env, napi_callback_info info); + static napi_value getL2capPsm(napi_env env, napi_callback_info info); static std::map> serverMap; static int count; diff --git a/frameworks/js/napi/include/napi_bluetooth_utils.h b/frameworks/js/napi/include/napi_bluetooth_utils.h index 8edfea3029ab112d9b329fca54bd19ecd2a5abb7..7e9b3c21a30e2f1953630d3b47a76c89bbb1c571 100644 --- a/frameworks/js/napi/include/napi_bluetooth_utils.h +++ b/frameworks/js/napi/include/napi_bluetooth_utils.h @@ -87,6 +87,7 @@ struct SppOption { std::string uuid_ = ""; bool secure_ = false; BtSocketType type_; + int32_t psm_ = SPP_SOCKET_PSM_VALUE; }; struct ConnStateChangeParam { @@ -418,7 +419,9 @@ enum MajorMinorClass { enum SppType { /** RFCOMM */ - SPP_RFCOMM = 0 + SPP_RFCOMM = 0, + SPP_L2CAP = 1, + SPP_L2CAP_BLE = 2, }; enum PlayingState { diff --git a/frameworks/js/napi/include/napi_ha_event_utils.h b/frameworks/js/napi/include/napi_ha_event_utils.h index 93266fe58f1325f0383594b242de8d2da8b8813a..70f2832d4097b282d797582fd8562a85e15e8377 100644 --- a/frameworks/js/napi/include/napi_ha_event_utils.h +++ b/frameworks/js/napi/include/napi_ha_event_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (C) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved. + * Copyright (C) Huawei Device Co., Ltd. 2025-2025. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/include/napi_native_object.h b/frameworks/js/napi/include/napi_native_object.h index 010b3189e975e790a5251f7ba511d4941ec3d734..6f1b7ff49821c93e007d4a12cc25c792e4bd237c 100644 --- a/frameworks/js/napi/include/napi_native_object.h +++ b/frameworks/js/napi/include/napi_native_object.h @@ -140,18 +140,18 @@ private: class NapiNativeStateChangeParam : public NapiNativeObject { public: NapiNativeStateChangeParam(std::string deviceAddr, int connectState, - bool isDisconnected = false, int disconnectReason = -1, int cause = 0) - : deviceAddr_(deviceAddr), connectState_(connectState), isDisconnected_(isDisconnected), - disconnectReason_(disconnectReason), stateChangeCause_(cause) {} + int cause = 0, bool isDisconnected = false, int disconnectReason = -1) + : deviceAddr_(deviceAddr), connectState_(connectState), stateChangeCause_(cause), + isDisconnected_(isDisconnected), disconnectReason_(disconnectReason) {} virtual ~NapiNativeStateChangeParam() override = default; napi_value ToNapiValue(napi_env env) const override; private: std::string deviceAddr_ = ""; int connectState_ = -1; + int stateChangeCause_ = -1; bool isDisconnected_ = false; int disconnectReason_ = -1; - int stateChangeCause_ = -1; }; class NapiNativeBleConnectionStateChangeParam : public NapiNativeStateChangeParam { @@ -159,8 +159,8 @@ public: NapiNativeBleConnectionStateChangeParam(std::string deviceAddr, int connectState) : NapiNativeStateChangeParam(deviceAddr, connectState) {} NapiNativeBleConnectionStateChangeParam( - std::string deviceAddr, int connectState, bool isDisconnected, int disconnectReason) - : NapiNativeStateChangeParam(deviceAddr, connectState, isDisconnected, disconnectReason) {} + std::string deviceAddr, int connectState, int cause, bool isDisconnected, int disconnectReason) + : NapiNativeStateChangeParam(deviceAddr, connectState, cause, isDisconnected, disconnectReason) {} ~NapiNativeBleConnectionStateChangeParam() override = default; }; diff --git a/frameworks/js/napi/src/access/napi_bluetooth_access.cpp b/frameworks/js/napi/src/access/napi_bluetooth_access.cpp index 62a022010975ddd004cce3257388186bb69fa544..2ebae8588adb55bb87abd3843c725eaede249d34 100644 --- a/frameworks/js/napi/src/access/napi_bluetooth_access.cpp +++ b/frameworks/js/napi/src/access/napi_bluetooth_access.cpp @@ -276,7 +276,7 @@ napi_value NapiAccess::EnableBluetoothAsync(napi_env env, napi_callback_info inf HILOGI("enter"); auto func = []() { bool isAsync = true; - int32_t ret = BluetoothHost::GetDefaultHost().EnableBle(isAsync); + int32_t ret = BluetoothHost::GetDefaultHost().EnableBle("", isAsync); HILOGI("EnableBluetoothAsync ret: %{public}d", ret); return NapiAsyncWorkRet(ret); }; @@ -291,7 +291,7 @@ napi_value NapiAccess::DisableBluetoothAsync(napi_env env, napi_callback_info in HILOGI("enter"); auto func = []() { bool isAsync = true; - int32_t ret = BluetoothHost::GetDefaultHost().DisableBt(isAsync); + int32_t ret = BluetoothHost::GetDefaultHost().DisableBt("", isAsync); HILOGI("DisableBluetoothAsync ret: %{public}d", ret); return NapiAsyncWorkRet(ret); }; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp index 42f0cf8cd6e2383d1fd3033eb4f6e2c0c9e87576..20802047687e2dc1b7e152cd4c26acd27ad32e0f 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble.cpp @@ -1216,6 +1216,7 @@ napi_value PropertyInit(napi_env env, napi_value exports) SetNamedPropertyByInteger(env, advertisingStateObj, static_cast(AdvertisingState::STOPPED), "STOPPED"); napi_value scanReportTypeObj = ScanReportTypeInit(env); + napi_value gattDisconnectReasonObj = GattDisconnectReasonInit(env); #endif napi_property_descriptor exportFuncs[] = { @@ -1228,6 +1229,7 @@ napi_value PropertyInit(napi_env env, napi_value exports) DECLARE_NAPI_PROPERTY("GattWriteType", gattWriteTypeObj), DECLARE_NAPI_PROPERTY("AdvertisingState", advertisingStateObj), DECLARE_NAPI_PROPERTY("ScanReportType", scanReportTypeObj), + DECLARE_NAPI_PROPERTY("GattDisconnectReason", gattDisconnectReasonObj), #endif }; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp index a4c81c8ae05a85b12d99ac1dbe91f936ad02157b..d5d0ad6080a7121cfd0efbdf2ce30f6cacca849c 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_ble_utils.cpp @@ -511,6 +511,21 @@ napi_value ScanReportModeInit(napi_env env) return reportModeObj; } +napi_value GattDisconnectReasonInit(napi_env env) +{ + napi_value gattDisconnectReasonObj = nullptr; + napi_create_object(env, &gattDisconnectReasonObj); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_TIMEOUT), "CONN_TIMEOUT"); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_TERMINATE_PEER_USER), "CONN_TERMINATE_PEER_USER"); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_TERMINATE_LOCAL_HOST), "CONN_TERMINATE_LOCAL_HOST"); + SetNamedPropertyByInteger(env, gattDisconnectReasonObj, + static_cast(GattDisconnectReason::CONN_UNKNOWN), "CONN_UNKNOWN"); + return gattDisconnectReasonObj; +} + void SetGattClientDeviceId(const std::string &deviceId) { deviceAddr = deviceId; diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp index f89046007d9717b2088cc734fe2acc1c827ddbc6..80bf70ac312a346d5d95f44c79408120ca40a70d 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_client_callback.cpp @@ -62,7 +62,7 @@ void NapiGattClientCallback::OnConnectionStateChangedWithReason(int connectionSt connectionState, disconnectReason, ret); if (connectionState == static_cast(BTConnectState::DISCONNECTED)) { auto nativeObject = std::make_shared( - deviceAddr_, connectionState, true, disconnectReason); + deviceAddr_, connectionState, 0, true, disconnectReason); eventSubscribe_.PublishEvent(STR_BT_GATT_CLIENT_CALLBACK_BLE_CONNECTIION_STATE_CHANGE, nativeObject); return; } diff --git a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp index d84d681cba5e8cd054cff044e3396ee175aac165..8d0a60468a0b086d37f695d6b7ef7fc18f7bcc14 100644 --- a/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp +++ b/frameworks/js/napi/src/ble/napi_bluetooth_gatt_server_callback.cpp @@ -88,7 +88,7 @@ void NapiGattServerCallback::OnConnectionStateUpdateWithReason( } } auto nativeObject = std::make_shared( - device.GetDeviceAddr(), state, true, disconnectReason); + device.GetDeviceAddr(), state, 0, true, disconnectReason); eventSubscribe_.PublishEvent(STR_BT_GATT_SERVER_CALLBACK_CONNECT_STATE_CHANGE, nativeObject); } } diff --git a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp index 315505328f1f7d6c799634f73cffd7806e8b8138..e29dc2162a5d515239e43541827ff814ff8b7ca1 100644 --- a/frameworks/js/napi/src/common/napi_bluetooth_error.cpp +++ b/frameworks/js/napi/src/common/napi_bluetooth_error.cpp @@ -66,6 +66,8 @@ static std::map napiErrMsgMap { { BtErrCode::BT_ERR_GATT_CONNECTION_NOT_AUTHORIZED, "The connection is not authorized." }, { BtErrCode::BT_ERR_BLE_SCAN_NO_RESOURCE, "Fails to start scan as it is out of hardware resources."}, { BtErrCode::BT_ERR_BLE_SCAN_ALREADY_STARTED, "Failed to start scan as Ble scan is already started by the app."}, + { BtErrCode::BT_ERR_DIALOG_FOR_USER_NOT_RESPOND, "The user does not respond."}, + { BtErrCode::BT_ERR_DIALOG_FOR_USER_REFUSE, "User refuse the action."}, }; std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode) diff --git a/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp b/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp index 70d5980c044a1cce279a38efc39d844ac0f12ea9..90f5604a78d12fd85c339e45123ba010c51696af 100644 --- a/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp +++ b/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp @@ -75,9 +75,7 @@ napi_status NapiEventSubscribeModule::Register(napi_env env, napi_callback_info callbackVec.end()); auto napiCallback = std::make_shared(env, callback); - if (napiCallback) { - callbackVec.push_back(napiCallback); - } + callbackVec.push_back(napiCallback); HILOGI("Register one %{public}s callback in %{public}s module, %{public}s, %{public}zu callback left", name.c_str(), moduleName_.c_str(), napiCallback->ToLogString().c_str(), callbackVec.size()); }); diff --git a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp index 20f0aa300b5e87011d7eb185918a61d90298e7e8..c40ed3392e3e0a4ce85093544bfb75bc5c8c4e8e 100644 --- a/frameworks/js/napi/src/common/napi_ha_event_utils.cpp +++ b/frameworks/js/napi/src/common/napi_ha_event_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved. + * Copyright (C) Huawei Device Co., Ltd. 2025-2025. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp b/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp index abd062dadcd5006ab15c45f4baf36d76fbc86b14..15cd9b0f2f101b2970350161a4b624af92540abe 100644 --- a/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp +++ b/frameworks/js/napi/src/socket/napi_bluetooth_spp_client.cpp @@ -56,7 +56,10 @@ static napi_status CheckSppConnectParams( callbackInfo->env_ = env; callbackInfo->sppOption_ = GetSppOptionFromJS(env, argv[PARAM1]); - NAPI_BT_RETURN_IF((callbackInfo->sppOption_ == nullptr), "GetSppOptionFromJS faild.", napi_invalid_arg); + NAPI_BT_RETURN_IF((callbackInfo->sppOption_ == nullptr), "GetSppOptionFromJS failed.", napi_invalid_arg); + NAPI_BT_RETURN_IF(( + (callbackInfo->sppOption_->type_ == TYPE_L2CAP || callbackInfo->sppOption_->type_ == TYPE_L2CAP_LE) && + callbackInfo->sppOption_->psm_ <= 0), "GetSppOptionFromJS failed", napi_invalid_arg); callbackInfo->deviceId_ = deviceId; napi_value promise = nullptr; @@ -89,7 +92,7 @@ std::shared_ptr GetSppOptionFromJS(napi_env env, napi_value object) napi_create_string_utf8(env, "uuid", NAPI_AUTO_LENGTH, &propertyNameValue); napi_get_property(env, object, propertyNameValue, &value); bool isSuccess = ParseString(env, sppOption->uuid_, value); - if (!isSuccess || (!IsValidUuid(sppOption->uuid_))) { + if (sppOption->uuid_ != "" && (!isSuccess || (!IsValidUuid(sppOption->uuid_)))) { HILOGE("Parse UUID faild."); return nullptr; } @@ -107,6 +110,17 @@ std::shared_ptr GetSppOptionFromJS(napi_env env, napi_value object) sppOption->type_ = BtSocketType(type); HILOGI("uuid: %{public}s, secure: %{public}d, type: %{public}d", sppOption->uuid_.c_str(), sppOption->secure_, sppOption->type_); + if (sppOption->type_ == TYPE_RFCOMM && sppOption->uuid_ == "") { + HILOGE("RFCOMM type but uuid is nullptr"); + return nullptr; + } + int psm = -1; + napi_create_string_utf8(env, "psm", NAPI_AUTO_LENGTH, &propertyNameValue); + napi_get_property(env, object, propertyNameValue, &value); + ParseInt32(env, psm, value); + sppOption->psm_ = psm; + HILOGI("uuid: %{public}s, secure: %{public}d, type: %{public}d, psm: %{public}d", + sppOption->uuid_.c_str(), sppOption->secure_, sppOption->type_, sppOption->psm_); return sppOption; } @@ -135,7 +149,7 @@ napi_value NapiSppClient::SppConnect(napi_env env, napi_callback_info info) UUID::FromString(callbackInfo->sppOption_->uuid_), callbackInfo->sppOption_->type_, callbackInfo->sppOption_->secure_); HILOGI("SppConnect client_ constructed"); - callbackInfo->errorCode_ = callbackInfo->client_->Connect(SPP_SOCKET_PSM_VALUE); + callbackInfo->errorCode_ = callbackInfo->client_->Connect(callbackInfo->sppOption_->psm_); if (callbackInfo->errorCode_ == BtStatus::BT_SUCCESS) { HILOGI("SppConnect successfully"); callbackInfo->errorCode_ = CODE_SUCCESS; diff --git a/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp b/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp index ae275f015b12599d5a84a9926ce124120c15997a..60c3ee4344309fc1b4b635ef66b3bcd665974997 100644 --- a/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp +++ b/frameworks/js/napi/src/socket/napi_bluetooth_spp_server.cpp @@ -40,6 +40,7 @@ void DefineSppFunctions(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("sppCloseClientSocket", NapiSppClient::SppCloseClientSocket), DECLARE_NAPI_FUNCTION("sppWrite", NapiSppClient::SppWrite), DECLARE_NAPI_FUNCTION("getDeviceId", NapiSppClient::GetDeviceId), + DECLARE_NAPI_FUNCTION("getL2capPsm", NapiSppServer::getL2capPsm), #ifdef BLUETOOTH_API_SINCE_10 DECLARE_NAPI_FUNCTION("on", NapiSppServer::RegisterSocketObserver), DECLARE_NAPI_FUNCTION("off", NapiSppServer::DeRegisterSocketObserver), @@ -67,6 +68,8 @@ napi_value SppTypeInit(napi_env env) napi_value sppType = nullptr; napi_create_object(env, &sppType); SetNamedPropertyByInteger(env, sppType, SppType::SPP_RFCOMM, "SPP_RFCOMM"); + SetNamedPropertyByInteger(env, sppType, SppType::SPP_L2CAP, "SPP_L2CAP"); + SetNamedPropertyByInteger(env, sppType, SppType::SPP_L2CAP_BLE, "SPP_L2CAP_BLE"); return sppType; } @@ -137,7 +140,7 @@ napi_value NapiSppServer::SppListen(napi_env env, napi_callback_info info) SppListenCallbackInfo* callbackInfo = static_cast(data); callbackInfo->server_ = std::make_shared(callbackInfo->name_, UUID::FromString(callbackInfo->sppOption_->uuid_), callbackInfo->sppOption_->type_, - callbackInfo->sppOption_->secure_); + callbackInfo->sppOption_->secure_, callbackInfo->sppOption_->psm_); int errorCode = callbackInfo->server_->Listen(); HILOGI("SppListen ServerSocket constructor end"); if (callbackInfo->server_ ->GetStringTag() != "") { @@ -352,5 +355,32 @@ napi_value NapiSppServer::SppCloseServerSocket(napi_env env, napi_callback_info return NapiGetBooleanRet(env, isOK); } + +static napi_status CheckSppFdParams(napi_env env, napi_callback_info info, int &id) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = {0}; + + NAPI_BT_CALL_RETURN(napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + NAPI_BT_RETURN_IF(argc != ARGS_SIZE_ONE, "Requires 1 arguments.", napi_invalid_arg); + NAPI_BT_RETURN_IF(!ParseInt32(env, id, argv[PARAM0]), "Wrong argument type. int expected.", napi_invalid_arg); + return napi_ok; +} + +napi_value NapiSppServer::getL2capPsm(napi_env env, napi_callback_info info) +{ + HILOGD("enter"); + int id = -1; + auto status = CheckSppFdParams(env, info, id); + NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM); + auto server = serverMap[id]; + NAPI_BT_ASSERT_RETURN_UNDEF(env, server != nullptr, BT_ERR_INVALID_PARAM); + NAPI_BT_ASSERT_RETURN_UNDEF(env, server->server_ != nullptr, BT_ERR_INVALID_PARAM); + int32_t l2capPsm = server->server_->GetL2capPsm(); + napi_value result = nullptr; + napi_create_int32(env, l2capPsm, &result); + return result; +} + } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_def.h b/interfaces/inner_api/include/bluetooth_def.h index 6e31d2422e5c3f612a0cd2af5b50846ff0f22caa..f3debb737ac7efb0f76f156866836ce73c844029 100644 --- a/interfaces/inner_api/include/bluetooth_def.h +++ b/interfaces/inner_api/include/bluetooth_def.h @@ -1693,6 +1693,7 @@ struct SensingInfo { enum class SATELLITE_CONTROL_MODE { ANTENNA = 0, BLUETOOTH_SWITCH = 1, + SIGNALHUB_MAC_SWITCH = 2, }; struct TrustPairDeviceParam { diff --git a/interfaces/inner_api/include/bluetooth_errorcode.h b/interfaces/inner_api/include/bluetooth_errorcode.h index c40eadd821e97b05376b164a721443af00fc0833..f40d2017c11f25c6e65cfc7019a5d87a70788e7b 100644 --- a/interfaces/inner_api/include/bluetooth_errorcode.h +++ b/interfaces/inner_api/include/bluetooth_errorcode.h @@ -88,6 +88,7 @@ enum BtErrCode { // errorCode for inner BT_ERR_DIALOG_FOR_USER_CONFIRM = -100, + BT_ERR_SWITCH_OP_TRANSFERRED = -101, }; } // namespace Bluetooth } // namespace OHOS diff --git a/interfaces/inner_api/include/bluetooth_gatt_client.h b/interfaces/inner_api/include/bluetooth_gatt_client.h index edff2a0c591dc59b74931cfc07a70c84a6d158eb..9e03b67a5813f634007f5e4f6f6bad23890d66cf 100644 --- a/interfaces/inner_api/include/bluetooth_gatt_client.h +++ b/interfaces/inner_api/include/bluetooth_gatt_client.h @@ -100,7 +100,7 @@ public: /** * @brief The function to OnCharacteristicWriteResult. * - * @param characteristic Characteristic object. + * @param characteristic Characteristic object. The value attribute is the initial value 0. * @param ret ret of GattClientCallback. * @since 6 * diff --git a/interfaces/inner_api/include/bluetooth_host.h b/interfaces/inner_api/include/bluetooth_host.h index 86f829503cb1002918d87aa9343900dfbdc8666e..91ce3ad93234f3b1652e7baf907f9c9767aff023 100644 --- a/interfaces/inner_api/include/bluetooth_host.h +++ b/interfaces/inner_api/include/bluetooth_host.h @@ -341,12 +341,13 @@ public: /** * @brief Disable classic. * + * @param name Indicate the calling application to disable bluetooth. The default value is current application. * @param isAsync Indicate Async function flag. * @return Returns true if the operation is accepted; * returns false if the operation is rejected. * @since 6 */ - int DisableBt(bool isAsync = false); + int DisableBt(std::string name = "", bool isAsync = false); /** * @brief Get classic enable/disable state. @@ -404,12 +405,13 @@ public: /** * @brief Enable ble. * + * @param name Indicate the calling application to enable bluetooth. The default value is current application. * @param isAsync Indicate Async function flag. * @return Returns true if the operation is accepted; * returns false if the operation is rejected. * @since 6 */ - int EnableBle(bool isAsync = false); + int EnableBle(std::string name = "", bool isAsync = false); /** * @brief Enable bluetooth without AutoConnect. @@ -423,11 +425,12 @@ public: /** * @brief Enable bluetooth to restrict mode. * + * @param name Indicate the calling application to enable bluetooth. The default value is current application. * @return Returns BT_NO_ERROR if the operation is accepted; * returns others if the operation is rejected. * @since 12 */ - int EnableBluetoothToRestrictMode(void); + int EnableBluetoothToRestrictMode(std::string name = ""); /** * @brief Get br/edr enable/disable state. @@ -784,12 +787,12 @@ public: /** * @brief Restrict Bluetooth BR/EDR ability, just BLE ability available. * - * @param remoteAddr remote device addr. + * @param name Indicate the calling application to restrict bluetooth. The default value is current application. * @return Returns {@link BT_NO_ERROR} if the operation is successful; * returns an error code defined in {@link BtErrCode} otherwise. * @since 12 */ - int RestrictBluetooth(); + int RestrictBluetooth(std::string name = ""); /** * @brief update virtual device * @@ -880,6 +883,17 @@ public: * @since 20 */ int NotifyDialogResult(uint32_t dialogType, bool dialogResult); + + /** + * @brief set the package name of calling app which is pairing or connecting remote bluetooth device. + * + * @param address The address of remote bluetooth device. + * @param packageName The package name of calling app. + * @return Returns {@link BT_NO_ERROR} if the operation is successful; + * returns an error code defined in {@link BtErrCode} otherwise. + * @since 21 + */ + int32_t SetCallingPackageName(const std::string &address, const std::string &packageName); private: /** * @brief A constructor used to create a BluetoothHost instance. diff --git a/interfaces/inner_api/include/bluetooth_socket.h b/interfaces/inner_api/include/bluetooth_socket.h index 906f11f51f5d45bb591cec7058ce829c6444bd6e..d44bbc33b17fde7b852e63793109ddabab7480ea 100644 --- a/interfaces/inner_api/include/bluetooth_socket.h +++ b/interfaces/inner_api/include/bluetooth_socket.h @@ -287,6 +287,18 @@ public: */ ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt); + /** + * @brief A constructor used to create an ServerSocket instance. + * + * @param name Server name. + * @param uuid Uuid. + * @param type Socket type. + * @param encrypt Remote device auth and encrypt connection. + * @param psm L2CAP socket psm. + * @since 20 + */ + ServerSocket(const std::string &name, UUID uuid, BtSocketType type, bool encrypt, int psm); + /** * @brief Destroy the ServerSocket object. * diff --git a/interfaces/inner_api/include/c_header/ohos_bt_gatt.h b/interfaces/inner_api/include/c_header/ohos_bt_gatt.h index fbf00ebbdb8bca6233586c239167af24ae90a1b1..0e0a17c399ca4bdcf6167d39521b0359724bf42e 100644 --- a/interfaces/inner_api/include/c_header/ohos_bt_gatt.h +++ b/interfaces/inner_api/include/c_header/ohos_bt_gatt.h @@ -402,7 +402,7 @@ typedef struct { /** Handling advertisments sent by advertisers with specific manufactureId */ unsigned short manufactureId; /** Adv_Ind Report */ - bool advIndReport; + bool advIndReport = false; /** Scan filter identifier index */ uint8_t filterIndex; } BleScanNativeFilter; diff --git a/test/BUILD.gn b/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..00c39c84d9769942eb6058fd3ed07e91a9868bcb --- /dev/null +++ b/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (C) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//foundation/communication/bluetooth/bluetooth.gni") +group("unit_test") { + testonly = true + deps = [ + "unittest/napi:unittest", + ] +} \ No newline at end of file diff --git a/test/unittest/napi/BUILD.gn b/test/unittest/napi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4a740abacd7ee821210b8816264f38964ce1647d --- /dev/null +++ b/test/unittest/napi/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (C) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/bluetooth/bluetooth.gni") + +module_output_path = "bluetooth/bluetooth" +FRAMWORK_DIR = "//foundation/communication/bluetooth" + +config("module_private_config") { + cflags = [ + "-Werror", + "-Wno-macro-redefined", + "-Wno-non-c-typedef-for-linkage", + "-Wno-unused-const-variable", + "-Wno-deprecated-builtins", + "-Wno-defaulted-function-deleted", + "-Woverloaded-virtual", + ] + include_dirs = [ + ".", + "$FRAMWORK_DIR/frameworks/inner/include", + "$FRAMWORK_DIR/frameworks/js/napi/include", + "$FRAMWORK_DIR/frameworks/js/napi/src/parser", + "$FRAMWORK_DIR/interfaces/inner_api/include", + "$FRAMWORK_DIR/interfaces/inner_api/include/c_header", + ] + defines = [ + "BTFW_LOG_TAG = \"bluetooth_test\"", + "BTFW_LOG_DOMAIN = 0xD005300", + "private = public", + "protected = public", + ] +} + +ohos_unittest("bluetooth_napi_event_subscribe_module_test") { + module_out_path = module_output_path + + sources = [ + "$FRAMWORK_DIR/frameworks/js/napi/src/common/napi_event_subscribe_module.cpp", + "napi_event_subscribe_module_test.cpp", + ] + + configs = [ + ":module_private_config", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "googletest:gmock_main", + "googletest:gtest_main", + ] +} + +################################################################################ +group("unittest") { + testonly = true + + deps = [] + + if (is_phone_product) { + deps += [ + ":bluetooth_napi_event_subscribe_module_test", + ] + } +} \ No newline at end of file diff --git a/test/unittest/napi/napi/native_api.h b/test/unittest/napi/napi/native_api.h new file mode 100644 index 0000000000000000000000000000000000000000..65bc3d6e96ca87ede5a0f2f19ab2b8f67005244f --- /dev/null +++ b/test/unittest/napi/napi/native_api.h @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_NATIVE_API_H +#define NAPI_NATIVE_API_H + +struct napi_env {}; +using napi_value = void *; +enum napi_status { + napi_ok = 0, + napi_invalid_arg, +}; +struct napi_async_work {}; +struct napi_deferred {}; +using napi_ref = int; +struct uv_work_t { + void *data; +}; +struct napi_callback_info {}; +using napi_handle_scope = void *; +typedef enum { + napi_undefined, + napi_null, +} napi_valuetype; + +napi_status napi_create_reference(napi_env env, napi_value value, uint32_t initial_refcount, napi_ref* result); +napi_status napi_get_reference_value(napi_env env, napi_ref ref, napi_value* result); +napi_status napi_call_function(napi_env env, napi_value recv, napi_value func, size_t argc, + const napi_value* argv, napi_value* result); +napi_status napi_is_exception_pending(napi_env env, bool* result); +napi_status napi_delete_reference(napi_env env, napi_ref ref); +napi_status napi_get_and_clear_last_exception(napi_env env, napi_value* result); +napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, bool* result); +napi_status napi_create_promise(napi_env env, napi_deferred* deferred, napi_value* promise); +napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, napi_value resolution); +napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, napi_value rejection); +napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result); +napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, size_t* argc, napi_value* argv, + napi_value* this_arg, void** data); +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope); + +using napi_threadsafe_function = void *; +#endif // NAPI_NATIVE_API_H \ No newline at end of file diff --git a/test/unittest/napi/napi/native_node_api.h b/test/unittest/napi/napi/native_node_api.h new file mode 100644 index 0000000000000000000000000000000000000000..9cdd1c25827007066c41a6937beabe46ac9fc8d8 --- /dev/null +++ b/test/unittest/napi/napi/native_node_api.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NATIVE_NODE_API_H +#define NATIVE_NODE_API_H + +#endif // NATIVE_NODE_API_H \ No newline at end of file diff --git a/test/unittest/napi/napi_event_subscribe_module_test.cpp b/test/unittest/napi/napi_event_subscribe_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b6bff8476f1abdef3f4892db122af003e5444af --- /dev/null +++ b/test/unittest/napi/napi_event_subscribe_module_test.cpp @@ -0,0 +1,443 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "bluetooth_log.h" +#include "napi_event_subscribe_module.h" + +using namespace testing; +using namespace testing::ext; + +static size_t g_napiGetCbInfoArgc = 0; +void NapiGetCbInfoMockSetArgc(size_t argc) +{ + g_napiGetCbInfoArgc = argc; +} +napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, size_t* argc, napi_value* argv, + napi_value* this_arg, void** data) +{ + *argc = g_napiGetCbInfoArgc; + return napi_ok; +} +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) +{ + return napi_ok; +} + +namespace OHOS { +namespace Bluetooth { +void NapiMockClear(void); + +class NapiEventSubscribeModuleTest : public testing::Test { +public: + NapiEventSubscribeModuleTest() = default; + ~NapiEventSubscribeModuleTest() = default; + + static void SetUpTestSuite(void) {} + static void TearDownTestSuite(void) {} + void SetUp() + { + NapiMockClear(); + } + void TearDown() {} + + napi_env env_; + napi_callback_info info_; +}; + +static std::string g_napiParseStringStr = ""; +static bool g_napiParseStringIsString = false; + +void NapiParseStringMock(std::string str, bool isString) +{ + g_napiParseStringStr = str; + g_napiParseStringIsString = isString; +} + +napi_status NapiParseString(napi_env env, napi_value value, std::string &outStr) +{ + outStr = g_napiParseStringStr; + return g_napiParseStringIsString ? napi_ok : napi_invalid_arg; +} + +static bool g_napiIsFunction = false; + +napi_status NapiIsFunctionMock(bool isFunction) +{ + g_napiIsFunction = isFunction; + return napi_ok; +} + +napi_status NapiIsFunction(napi_env env, napi_value value) +{ + return g_napiIsFunction ? napi_ok : napi_invalid_arg; +} + +NapiCallback::NapiCallback(napi_env env, napi_value callback) {} +NapiCallback::~NapiCallback() {} + +static int g_napiCallFunctionCount = 0; +void NapiCallback::CallFunction(const std::shared_ptr &object) +{ + g_napiCallFunctionCount++; +} +void NapiCallback::CallFunction(int errCode, const std::shared_ptr &object) {} +napi_env NapiCallback::GetNapiEnv(void) +{ + return env_; +} +std::string NapiCallback::ToLogString(void) const +{ + return ""; +} + +static bool g_napiCallbackIsEqual = false; +void NapiCallbackIsEqualMock(bool equal) +{ + g_napiCallbackIsEqual = equal; +} +bool NapiCallback::Equal(napi_env env, napi_value &callback) const +{ + return g_napiCallbackIsEqual; +} + +int DoInJsMainThread(std::function func) +{ + func(); + return 0; +} + +int DoInJsMainThread(napi_env env, std::function func) +{ + func(); + return 0; +} + +void NapiMockClear(void) +{ + g_napiGetCbInfoArgc = 0; + g_napiParseStringStr = ""; + g_napiParseStringIsString = false; + g_napiIsFunction = false; + g_napiCallbackIsEqual = false; + g_napiCallFunctionCount = 0; +} + +static const char * const TEST_CALLBACK_NAME = "testCallback"; + +/** + * @tc.name: NapiEventSubscribeModuleTest_001 + * @tc.desc: Test register and deregister normal + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_001, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_001 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(true); + + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 0); + + HILOGI("NapiEventSubscribeModuleTest_001 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_002 + * @tc.desc: Test register the type callback, and the same callback Repeated + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_002, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_002 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + // Mock the same callback + NapiCallbackIsEqualMock(true); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + HILOGI("NapiEventSubscribeModuleTest_002 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_003 + * @tc.desc: Test register the type callback, and multi callback + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_003, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_003 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 2); + + HILOGI("NapiEventSubscribeModuleTest_003 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_004 + * @tc.desc: Test publish event + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_004, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_004 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + subscribe.PublishEvent(TEST_CALLBACK_NAME, nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 1); + + HILOGI("NapiEventSubscribeModuleTest_004 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_005 + * @tc.desc: Test register failed + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_005, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_005 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + // Invalid params size + NapiGetCbInfoMockSetArgc(1); + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[0] string type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, false); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid type name + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock("errCallbackName", true); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[1] function type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + NapiIsFunctionMock(false); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + HILOGI("NapiEventSubscribeModuleTest_005 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_006 + * @tc.desc: Test register failed + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_006, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_006 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + // Invalid params size + NapiGetCbInfoMockSetArgc(3); + napi_status ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + NapiGetCbInfoMockSetArgc(0); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[0] string type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, false); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid type name + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock("errCallbackName", true); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // Invalid argv[1] function type + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + NapiIsFunctionMock(false); + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_invalid_arg); + + // The callback is not registered + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(true); + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + + HILOGI("NapiEventSubscribeModuleTest_006 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_007 + * @tc.desc: Test publish event failed + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_007, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_007 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + // Invalid eventName + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + subscribe.PublishEvent("errCallbackName", nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 0); + + // Empty callback in map + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(true); + + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 0); + + subscribe.PublishEvent(TEST_CALLBACK_NAME, nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 0); + + HILOGI("NapiEventSubscribeModuleTest_007 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_008 + * @tc.desc: Test Deregister all callback + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_008, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_008 enter"); + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + NapiGetCbInfoMockSetArgc(2); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + NapiIsFunctionMock(true); + NapiCallbackIsEqualMock(false); + + napi_status ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 1); + + ret = subscribe.Register(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 2); + + NapiGetCbInfoMockSetArgc(1); + NapiParseStringMock(TEST_CALLBACK_NAME, true); + + ret = subscribe.Deregister(env_, info_); + EXPECT_EQ(ret, napi_ok); + EXPECT_EQ(subscribe.eventSubscribeMap_.ReadVal(TEST_CALLBACK_NAME).size(), 0); + + HILOGI("NapiEventSubscribeModuleTest_008 end"); +} + +/** + * @tc.name: NapiEventSubscribeModuleTest_009 + * @tc.desc: Test publish a event with multi callback + * @tc.type: FUNC + */ +HWTEST_F(NapiEventSubscribeModuleTest, NapiEventSubscribeModuleTest_009, TestSize.Level0) +{ + HILOGI("NapiEventSubscribeModuleTest_009 enter"); + napi_env env; + napi_value callback = nullptr; + NapiEventSubscribeModule subscribe(TEST_CALLBACK_NAME, "testModule"); + + subscribe.eventSubscribeMap_.ChangeValueByLambda(TEST_CALLBACK_NAME, [env, callback](auto & callbackVec) { + auto napiCallback = std::make_shared(env, callback); + callbackVec.push_back(napiCallback); + napiCallback = std::make_shared(env, callback); + callbackVec.push_back(napiCallback); + }); + + subscribe.PublishEvent(TEST_CALLBACK_NAME, nullptr); + EXPECT_EQ(g_napiCallFunctionCount, 2); + + HILOGI("NapiEventSubscribeModuleTest_009 end"); +} +} // namespace Bluetooth +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/napi/uv.h b/test/unittest/napi/uv.h new file mode 100644 index 0000000000000000000000000000000000000000..48526dc0dd61e4e0247d5865c69f21ca6904c139 --- /dev/null +++ b/test/unittest/napi/uv.h @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef UV_H +#define UV_H + +#endif // UV_H \ No newline at end of file