• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "bluetooth_hid_host.h"
17 
18 #include "bluetooth_errorcode.h"
19 #include "bluetooth_log.h"
20 #include "bluetooth_utils.h"
21 #include "napi_async_work.h"
22 #include "napi_bluetooth_hid_host_observer.h"
23 #include "napi_bluetooth_error.h"
24 #include "napi_bluetooth_utils.h"
25 #include "napi_bluetooth_profile.h"
26 #include "napi_bluetooth_hid_host.h"
27 
28 namespace OHOS {
29 namespace Bluetooth {
30 using namespace std;
31 NapiBluetoothHidHostObserver NapiBluetoothHidHost::observer_;
32 thread_local napi_ref NapiBluetoothHidHost::consRef_ = nullptr;
33 
DefineHidHostJSClass(napi_env env,napi_value exports)34 void NapiBluetoothHidHost::DefineHidHostJSClass(napi_env env, napi_value exports)
35 {
36     napi_value constructor;
37     napi_property_descriptor properties[] = {
38         DECLARE_NAPI_FUNCTION("on", On),
39         DECLARE_NAPI_FUNCTION("off", Off),
40 #ifdef BLUETOOTH_API_SINCE_10
41         DECLARE_NAPI_FUNCTION("getConnectedDevices", GetConnectionDevices),
42         DECLARE_NAPI_FUNCTION("getConnectionState", GetDeviceState),
43 #else
44         DECLARE_NAPI_FUNCTION("getConnectionDevices", GetConnectionDevices),
45         DECLARE_NAPI_FUNCTION("getDeviceState", GetDeviceState),
46 #endif
47         DECLARE_NAPI_FUNCTION("connect", Connect),
48         DECLARE_NAPI_FUNCTION("disconnect", Disconnect),
49         DECLARE_NAPI_FUNCTION("setConnectionStrategy", SetConnectionStrategy),
50         DECLARE_NAPI_FUNCTION("getConnectionStrategy", GetConnectionStrategy),
51     };
52 
53     napi_define_class(env, "NapiBluetoothHidHost", NAPI_AUTO_LENGTH, HidHostConstructor, nullptr,
54         sizeof(properties) / sizeof(properties[0]), properties, &constructor);
55 #ifdef BLUETOOTH_API_SINCE_10
56     DefineCreateProfile(env, exports);
57     napi_create_reference(env, constructor, 1, &consRef_);
58 #else
59     napi_value napiProfile;
60     napi_new_instance(env, constructor, 0, nullptr, &napiProfile);
61     NapiProfile::SetProfile(env, ProfileId::PROFILE_HID_HOST, napiProfile);
62     HidHost *profile = HidHost::GetProfile();
63     profile->RegisterObserver(&observer_);
64 #endif
65     HILOGI("finished");
66 }
67 
DefineCreateProfile(napi_env env,napi_value exports)68 napi_value NapiBluetoothHidHost::DefineCreateProfile(napi_env env, napi_value exports)
69 {
70     napi_property_descriptor properties[] = {
71         DECLARE_NAPI_FUNCTION("createHidHostProfile", CreateHidHostProfile),
72     };
73     napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties);
74     return exports;
75 }
76 
CreateHidHostProfile(napi_env env,napi_callback_info info)77 napi_value NapiBluetoothHidHost::CreateHidHostProfile(napi_env env, napi_callback_info info)
78 {
79     HILOGI("enter");
80     napi_value napiProfile;
81     napi_value constructor = nullptr;
82     napi_get_reference_value(env, consRef_, &constructor);
83     napi_new_instance(env, constructor, 0, nullptr, &napiProfile);
84     NapiProfile::SetProfile(env, ProfileId::PROFILE_HID_HOST, napiProfile);
85 
86     HidHost *profile = HidHost::GetProfile();
87     profile->RegisterObserver(&observer_);
88 
89     return napiProfile;
90 }
91 
92 
HidHostConstructor(napi_env env,napi_callback_info info)93 napi_value NapiBluetoothHidHost::HidHostConstructor(napi_env env, napi_callback_info info)
94 {
95     napi_value thisVar = nullptr;
96     napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
97     return thisVar;
98 }
99 
On(napi_env env,napi_callback_info info)100 napi_value NapiBluetoothHidHost::On(napi_env env, napi_callback_info info)
101 {
102     HILOGI("enter");
103     size_t expectedArgsCount = ARGS_SIZE_TWO;
104     size_t argc = expectedArgsCount;
105     napi_value argv[ARGS_SIZE_TWO] = {0};
106     napi_value thisVar = nullptr;
107 
108     napi_value ret = nullptr;
109     napi_get_undefined(env, &ret);
110 
111     napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
112     if (argc != expectedArgsCount) {
113         HILOGE("Requires 2 argument.");
114         return ret;
115     }
116     string type;
117     if (!ParseString(env, type, argv[PARAM0])) {
118         HILOGE("string expected.");
119         return ret;
120     }
121     std::shared_ptr<BluetoothCallbackInfo> callbackInfo = std::make_shared<BluetoothCallbackInfo>();
122     callbackInfo->env_ = env;
123 
124     napi_valuetype valueType = napi_undefined;
125     napi_typeof(env, argv[PARAM1], &valueType);
126     if (valueType != napi_function) {
127         HILOGE("Wrong argument type. Function expected.");
128         return ret;
129     }
130     napi_create_reference(env, argv[PARAM1], 1, &callbackInfo->callback_);
131     observer_.callbackInfos_[type] = callbackInfo;
132     HILOGI("%{public}s is registered", type.c_str());
133     return ret;
134 }
135 
Off(napi_env env,napi_callback_info info)136 napi_value NapiBluetoothHidHost::Off(napi_env env, napi_callback_info info)
137 {
138     HILOGI("enter");
139     size_t expectedArgsCount = ARGS_SIZE_ONE;
140     size_t argc = expectedArgsCount;
141     napi_value argv[ARGS_SIZE_ONE] = {0};
142     napi_value thisVar = nullptr;
143 
144     napi_value ret = nullptr;
145     napi_get_undefined(env, &ret);
146 
147     napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr);
148     if (argc != expectedArgsCount) {
149         HILOGE("Requires 1 argument.");
150         return ret;
151     }
152     string type;
153     if (!ParseString(env, type, argv[PARAM0])) {
154         HILOGE("string expected.");
155         return ret;
156     }
157 
158     if (observer_.callbackInfos_[type] != nullptr) {
159     std::shared_ptr<BluetoothCallbackInfo> callbackInfo = observer_.callbackInfos_[type];
160     napi_delete_reference(env, callbackInfo->callback_);
161     }
162     observer_.callbackInfos_[type] = nullptr;
163     HILOGI("%{public}s is unregistered", type.c_str());
164     return ret;
165 }
166 
GetConnectionDevices(napi_env env,napi_callback_info info)167 napi_value NapiBluetoothHidHost::GetConnectionDevices(napi_env env, napi_callback_info info)
168 {
169     HILOGI("enter");
170 
171     napi_value ret = nullptr;
172     if (napi_create_array(env, &ret) != napi_ok) {
173         HILOGE("napi_create_array failed.");
174     }
175     napi_status checkRet = CheckEmptyParam(env, info);
176     NAPI_BT_ASSERT_RETURN(env, checkRet == napi_ok, BT_ERR_INVALID_PARAM, ret);
177 
178     HidHost *profile = HidHost::GetProfile();
179     vector<int> states = { static_cast<int>(BTConnectState::CONNECTED) };
180     vector<BluetoothRemoteDevice> devices;
181     int errorCode = profile->GetDevicesByStates(states, devices);
182     HILOGI("errorCode:%{public}s, devices size:%{public}zu", GetErrorCode(errorCode).c_str(), devices.size());
183     NAPI_BT_ASSERT_RETURN(env, errorCode == BT_NO_ERROR, errorCode, ret);
184 
185     vector<string> deviceVector;
186     for (auto &device: devices) {
187         deviceVector.push_back(device.GetDeviceAddr());
188     }
189     ConvertStringVectorToJS(env, ret, deviceVector);
190     return ret;
191 }
192 
GetDeviceState(napi_env env,napi_callback_info info)193 napi_value NapiBluetoothHidHost::GetDeviceState(napi_env env, napi_callback_info info)
194 {
195     HILOGI("enter");
196     napi_value result = nullptr;
197     int32_t profileState = ProfileConnectionState::STATE_DISCONNECTED;
198     if (napi_create_int32(env, profileState, &result) != napi_ok) {
199         HILOGE("napi_create_int32 failed.");
200     }
201 
202     std::string remoteAddr {};
203     bool checkRet = CheckDeivceIdParam(env, info, remoteAddr);
204     NAPI_BT_ASSERT_RETURN(env, checkRet, BT_ERR_INVALID_PARAM, result);
205 
206     HidHost *profile = HidHost::GetProfile();
207     BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR);
208     int32_t state = static_cast<int32_t>(BTConnectState::DISCONNECTED);
209     int32_t errorCode = profile->GetDeviceState(device, state);
210     HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str());
211     NAPI_BT_ASSERT_RETURN(env, errorCode == BT_NO_ERROR, errorCode, result);
212 
213     profileState = GetProfileConnectionState(state);
214     if (napi_create_int32(env, profileState, &result) != napi_ok) {
215         HILOGE("napi_create_int32 failed.");
216     }
217     HILOGI("profileState: %{public}d", profileState);
218     return result;
219 }
220 
Connect(napi_env env,napi_callback_info info)221 napi_value NapiBluetoothHidHost::Connect(napi_env env, napi_callback_info info)
222 {
223     HILOGI("enter");
224     std::string remoteAddr {};
225     bool checkRet = CheckDeivceIdParam(env, info, remoteAddr);
226     NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM);
227 
228     HidHost *profile = HidHost::GetProfile();
229     BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR);
230     int32_t errorCode = profile->Connect(device);
231     HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str());
232     NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_NO_ERROR, errorCode);
233     return NapiGetBooleanTrue(env);
234 }
235 
Disconnect(napi_env env,napi_callback_info info)236 napi_value NapiBluetoothHidHost::Disconnect(napi_env env, napi_callback_info info)
237 {
238     HILOGI("Disconnect called");
239     std::string remoteAddr {};
240     bool checkRet = CheckDeivceIdParam(env, info, remoteAddr);
241     NAPI_BT_ASSERT_RETURN_FALSE(env, checkRet, BT_ERR_INVALID_PARAM);
242 
243     HidHost *profile = HidHost::GetProfile();
244     BluetoothRemoteDevice device(remoteAddr, BT_TRANSPORT_BREDR);
245     int32_t errorCode = profile->Disconnect(device);
246     HILOGI("errorCode:%{public}s", GetErrorCode(errorCode).c_str());
247     NAPI_BT_ASSERT_RETURN_FALSE(env, errorCode == BT_NO_ERROR, errorCode);
248     return NapiGetBooleanTrue(env);
249 }
250 
SetConnectionStrategy(napi_env env,napi_callback_info info)251 napi_value NapiBluetoothHidHost::SetConnectionStrategy(napi_env env, napi_callback_info info)
252 {
253     HILOGI("start");
254     std::string remoteAddr {};
255     int32_t strategy = 0;
256     auto status = CheckSetConnectStrategyParam(env, info, remoteAddr, strategy);
257     NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM);
258 
259     auto func = [remoteAddr, strategy]() {
260         BluetoothRemoteDevice remoteDevice(remoteAddr, BT_TRANSPORT_BREDR);
261         HidHost *profile = HidHost::GetProfile();
262         int32_t err = profile->SetConnectStrategy(remoteDevice, strategy);
263         HILOGI("err: %{public}d", err);
264         return NapiAsyncWorkRet(err);
265     };
266     auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK);
267     NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR);
268     asyncWork->Run();
269     return asyncWork->GetRet();
270 }
271 
GetConnectionStrategy(napi_env env,napi_callback_info info)272 napi_value NapiBluetoothHidHost::GetConnectionStrategy(napi_env env, napi_callback_info info)
273 {
274     HILOGI("start");
275     std::string remoteAddr {};
276     auto status = CheckDeviceAddressParam(env, info, remoteAddr);
277     NAPI_BT_ASSERT_RETURN_UNDEF(env, status == napi_ok, BT_ERR_INVALID_PARAM);
278 
279     auto func = [remoteAddr]() {
280         int strategy = 0;
281         BluetoothRemoteDevice remoteDevice(remoteAddr, BT_TRANSPORT_BREDR);
282         HidHost *profile = HidHost::GetProfile();
283         int32_t err = profile->GetConnectStrategy(remoteDevice, strategy);
284         HILOGI("err: %{public}d, deviceName: %{public}d", err, strategy);
285         auto object = std::make_shared<NapiNativeInt>(strategy);
286         return NapiAsyncWorkRet(err, object);
287     };
288     auto asyncWork = NapiAsyncWorkFactory::CreateAsyncWork(env, info, func, ASYNC_WORK_NO_NEED_CALLBACK);
289     NAPI_BT_ASSERT_RETURN_UNDEF(env, asyncWork, BT_ERR_INTERNAL_ERROR);
290     asyncWork->Run();
291     return asyncWork->GetRet();
292 }
293 }  // namespace Bluetooth
294 }  // namespace OHOS