1 /*
2  * Copyright (C) 2021-2022 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 "ohos_bt_gap.h"
17 
18 #include <string.h>
19 #include "__config"
20 #include "bluetooth_def.h"
21 #include "bluetooth_host.h"
22 #include "bluetooth_log.h"
23 #include "bluetooth_remote_device.h"
24 #include "bluetooth_utils.h"
25 #include "iosfwd"
26 #include "ohos_bt_adapter_utils.h"
27 #include "ohos_bt_def.h"
28 #include "string"
29 
30 #ifdef __cplusplus
31 extern "C" {
32 #endif
33 
34 using namespace std;
35 
36 namespace OHOS {
37 namespace Bluetooth {
38 static BluetoothHost *g_BluetoothHost;
39 static BtGapCallBacks *g_GapCallback;
40 
41 class BluetoothHostObserverWapper : public BluetoothHostObserver {
42 public:
43     /**
44      * @brief Adapter state change function.
45      *
46      * @param transport Transport type when state change.
47      *        BTTransport::ADAPTER_BREDR : classic;
48      *        BTTransport::ADAPTER_BLE : ble.
49      * @param state Change to the new state.
50      *        BTStateID::STATE_TURNING_ON;
51      *        BTStateID::STATE_TURN_ON;
52      *        BTStateID::STATE_TURNING_OFF;
53      *        BTStateID::STATE_TURN_OFF.
54      * @since 6
55      */
56     void OnStateChanged(const int transport, const int status) override
57     {
58         int cvtTransport = OHOS_BT_TRANSPORT_LE;
59         if (transport == BTTransport::ADAPTER_BREDR) {
60             cvtTransport = OHOS_BT_TRANSPORT_BR_EDR;
61         }
62         HILOGI("transport: %{public}d, status: %{public}d", cvtTransport, status);
63         if (g_GapCallback != nullptr && g_GapCallback->stateChangeCallback != nullptr) {
64             g_GapCallback->stateChangeCallback(cvtTransport, status);
65         } else {
66             HILOGW("callback func is null!");
67         }
68     }
69 
70     /**
71      * @brief Discovery state changed observer.
72      *
73      * @param status Device discovery status.
74      * @since 6
75      */
76     void OnDiscoveryStateChanged(int status) override
77     {
78         return;
79     }
80 
81     /**
82      * @brief Discovery result observer.
83      *
84      * @param device Remote device.
85      * @param rssi Rssi of device.
86      * @param deviceName Name of device.
87      * @param deviceClass Class of device.
88      * @since 6
89      */
90     void OnDiscoveryResult(
91         const BluetoothRemoteDevice &device, int rssi, const std::string deviceName, int deviceClass) override
92     {
93         return;
94     }
95 
96     /**
97      * @brief Pair request observer.
98      *
99      * @param device Remote device.
100      * @since 6
101      */
102     void OnPairRequested(const BluetoothRemoteDevice &device) override
103     {
104         return;
105     }
106 
107     /**
108      * @brief Pair confirmed observer.
109      *
110      * @param device Remote device.
111      * @param reqType Pair type.
112      * @param number Paired passkey.
113      * @since 6
114      */
115     void OnPairConfirmed(const BluetoothRemoteDevice &device, int reqType, int number) override
116     {
117         return;
118     }
119 
120     /**
121      * @brief Scan mode changed observer.
122      *
123      * @param mode Device scan mode.
124      * @since 6
125      */
126     void OnScanModeChanged(int mode) override
127     {
128         HILOGI("mode: %{public}d", mode);
129         if (g_GapCallback != nullptr && g_GapCallback->scanModeChangedCallback != nullptr) {
130             g_GapCallback->scanModeChangedCallback(mode);
131         } else {
132             HILOGW("mode: %{public}d, but callback is null!", mode);
133         }
134     };
135 
136     /**
137      * @brief Device name changed observer.
138      *
139      * @param deviceName Device name.
140      * @since 6
141      */
142     void OnDeviceNameChanged(const std::string &deviceName) override
143     {
144         return;
145     }
146 
147     /**
148      * @brief Device address changed observer.
149      *
150      * @param address Device address.
151      * @since 6
152      */
153     void OnDeviceAddrChanged(const std::string &address) override
154     {
155         return;
156     }
157 };
158 
159 class BluetoothRemoteDeviceObserverWapper : public BluetoothRemoteDeviceObserver {
160 public:
161     /**
162      * @brief Acl state changed observer.
163      *
164      * @param device Remote device.
165      * @param state Remote device acl state.
166      * @param reason Remote device reason.
167      * @since 6
168      */
169     void OnAclStateChanged(const BluetoothRemoteDevice &device, int state, unsigned int reason) override
170     {
171         if (g_GapCallback == nullptr || g_GapCallback->aclStateChangedCallbak == nullptr) {
172             HILOGW("callback func is null!");
173             return;
174         }
175         std::string stateStr;
176         GetAclStateName(device.GetTransportType(), state, stateStr);
177         HILOGD("device: %{public}s, state: %{public}s, reason: %{public}u",
178             GetEncryptAddr(device.GetDeviceAddr()).c_str(), stateStr.c_str(), reason);
179         BdAddr remoteAddr;
180         GetAddrFromString(device.GetDeviceAddr(), remoteAddr.addr);
181         g_GapCallback->aclStateChangedCallbak(&remoteAddr, ConvertAclState(device.GetTransportType(), state), reason);
182     }
183 
184     /**
185      * @brief Pair status changed observer.
186      *
187      * @param device Remote device.
188      * @param status Remote device pair status.
189      * @param cause Pair fail cause.
190      * @since 12
191      */
192     void OnPairStatusChanged(const BluetoothRemoteDevice &device, int status, int cause) override
193     {
194         return;
195     }
196 
197     /**
198      * @brief Remote uuid changed observer.
199      *
200      * @param device Remote device.
201      * @param uuids Remote device uuids.
202      * @since 6
203      */
204     void OnRemoteUuidChanged(const BluetoothRemoteDevice &device, const std::vector<ParcelUuid> &uuids) override
205     {
206         return;
207     }
208 
209     /**
210      * @brief Remote name changed observer.
211      *
212      * @param device Remote device.
213      * @param deviceName Remote device name.
214      * @since 6
215      */
216     void OnRemoteNameChanged(const BluetoothRemoteDevice &device, const std::string &deviceName) override
217     {
218         return;
219     }
220 
221     /**
222      * @brief Remote alias changed observer.
223      *
224      * @param device Remote device.
225      * @param alias Remote device alias.
226      * @since 6
227      */
228     void OnRemoteAliasChanged(const BluetoothRemoteDevice &device, const std::string &alias) override
229     {
230         return;
231     }
232 
233     /**
234      * @brief Remote cod changed observer.
235      *
236      * @param device Remote device.
237      * @param cod Remote device cod.
238      * @since 6
239      */
240     void OnRemoteCodChanged(const BluetoothRemoteDevice &device, const BluetoothDeviceClass &cod) override
241     {
242         return;
243     }
244 
245     /**
246      * @brief Remote battery level changed observer.
247      *
248      * @param device Remote device.
249      * @param cod Remote device battery Level.
250      * @since 6
251      */
252     void OnRemoteBatteryLevelChanged(const BluetoothRemoteDevice &device, int batteryLevel) override
253     {
254         return;
255     }
256 
257     /**
258      * @brief Remote rssi event observer.
259      *
260      * @param device Remote device.
261      * @param rssi Remote device rssi.
262      * @param status Read status.
263      * @since 6
264      */
265     void OnReadRemoteRssiEvent(const BluetoothRemoteDevice &device, int rssi, int status) override
266     {
267         return;
268     }
269 };
270 
271 static std::shared_ptr<BluetoothHostObserverWapper> g_hostObserver = nullptr;
272 static std::shared_ptr<BluetoothRemoteDeviceObserverWapper> g_remoteDeviceObserver = nullptr;
273 
EnableBle(void)274 bool EnableBle(void)
275 {
276     HILOGI("enter");
277     if (g_BluetoothHost == nullptr) {
278         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
279     }
280 
281     if (g_BluetoothHost->IsBleEnabled()) {
282         HILOGI("ble enabled already");
283         return true;
284     }
285     bool  isEnabled = false;
286     int32_t ret = g_BluetoothHost->EnableBle();
287     HILOGI("result: %{public}d", ret);
288     if (ret == BT_NO_ERROR) {
289         isEnabled = true;
290     }
291     return isEnabled;
292 }
293 
DisableBle(void)294 bool DisableBle(void)
295 {
296     HILOGI("enter");
297     if (g_BluetoothHost == nullptr) {
298         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
299     }
300 
301     if (!g_BluetoothHost->IsBleEnabled()) {
302         HILOGI("ble disabled already");
303         return true;
304     }
305     bool  isEnabled = false;
306     int ret = g_BluetoothHost->DisableBle();
307     HILOGI("result: %{public}d", ret);
308     if (ret == BT_NO_ERROR) {
309         isEnabled = true;
310     }
311     return isEnabled;
312 }
313 
EnableBt(void)314 bool EnableBt(void)
315 {
316     HILOGI("enter");
317     if (g_BluetoothHost == nullptr) {
318         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
319     }
320 
321     int state;
322     g_BluetoothHost->GetBtState(state);
323     if (state == BTStateID::STATE_TURNING_ON ||
324         state == BTStateID::STATE_TURN_ON) {
325         HILOGI("br state is %{public}d", state);
326         return true;
327     }
328     bool  isEnabled = false;
329     int ret = g_BluetoothHost->EnableBt();
330     HILOGI("result: %{public}d", ret);
331     if (ret == BT_NO_ERROR) {
332         isEnabled = true;
333     }
334     return isEnabled;
335 }
336 
DisableBt(void)337 bool DisableBt(void)
338 {
339     HILOGI("enter");
340     if (g_BluetoothHost == nullptr) {
341         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
342     }
343 
344     int state;
345     g_BluetoothHost->GetBtState(state);
346     if (state == BTStateID::STATE_TURNING_OFF ||
347         state == BTStateID::STATE_TURN_OFF) {
348         HILOGI("br state is %{public}d", state);
349         return true;
350     }
351     bool  isDisabled = false;
352     int ret = g_BluetoothHost->DisableBt();
353     HILOGI("result: %{public}d", ret);
354     if (ret == BT_NO_ERROR) {
355         isDisabled = true;
356     }
357     return isDisabled;
358 }
359 
GetBtState()360 int GetBtState()
361 {
362     HILOGI("enter");
363     if (g_BluetoothHost == nullptr) {
364         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
365     }
366 
367     int state;
368     g_BluetoothHost->GetBtState(state);
369     HILOGI("br state: %{public}d", state);
370     return state;
371 }
372 
IsBleEnabled()373 bool IsBleEnabled()
374 {
375     if (g_BluetoothHost == nullptr) {
376         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
377     }
378 
379     bool ret = g_BluetoothHost->IsBleEnabled();
380     HILOGD("ble enable: %{public}d", ret);
381     return ret;
382 }
383 
GetLocalAddr(unsigned char *mac, unsigned int len)384 bool GetLocalAddr(unsigned char *mac, unsigned int len)
385 {
386     HILOGD("enter");
387     if (mac == nullptr || len < OHOS_BD_ADDR_LEN) {
388         HILOGE("invalid param, len:%{public}d", len);
389         return false;
390     }
391     if (g_BluetoothHost == nullptr) {
392         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
393     }
394 
395     std::string localAddress = INVALID_MAC_ADDRESS;
396     int32_t err = g_BluetoothHost->GetLocalAddress(localAddress);
397     if (err != BT_NO_ERROR) {
398         HILOGE("error %{public}d", err);
399         return false;
400     }
401     GetAddrFromString(localAddress, mac);
402     HILOGI("device: %{public}s", GetEncryptAddr(localAddress).c_str());
403     return true;
404 }
405 
SetLocalName(unsigned char *localName, unsigned char length)406 bool SetLocalName(unsigned char *localName, unsigned char length)
407 {
408     HILOGI("enter");
409     if (localName == nullptr) {
410         HILOGE("localName is null");
411         return false;
412     }
413 
414     if (g_BluetoothHost == nullptr) {
415         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
416     }
417 
418     string newName(reinterpret_cast<const char *>(localName));
419     bool isSuccess = false;
420     int ret = g_BluetoothHost->SetLocalName(newName);
421     if (ret == BT_NO_ERROR) {
422         isSuccess = true;
423     }
424     HILOGI("result %{public}d: LocalName : %{public}s", ret, g_BluetoothHost->GetLocalName().c_str());
425     return isSuccess;
426 }
427 
SetBtScanMode(int mode, int duration)428 bool SetBtScanMode(int mode, int duration)
429 {
430     HILOGI("mode: %{public}d, duration: %{public}d", mode, duration);
431     if (g_BluetoothHost == nullptr) {
432         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
433     }
434     bool isSuccess = false;
435     int ret = g_BluetoothHost->SetBtScanMode(mode, duration);
436     if (ret == BT_NO_ERROR) {
437         isSuccess = true;
438     }
439     g_BluetoothHost->SetBondableMode(BT_TRANSPORT_BREDR, BONDABLE_MODE_ON);
440     return isSuccess;
441 }
442 
PairRequestReply(const BdAddr *bdAddr, int transport, bool accept)443 bool PairRequestReply(const BdAddr *bdAddr, int transport, bool accept)
444 {
445     string strAddress;
446     ConvertAddr(bdAddr->addr, strAddress);
447     HILOGI("device: %{public}s", GetEncryptAddr(strAddress).c_str());
448     BluetoothRemoteDevice remoteDevice;
449     if (transport == OHOS_BT_TRANSPORT_BR_EDR) {
450         remoteDevice = g_BluetoothHost->GetRemoteDevice(strAddress, BT_TRANSPORT_BREDR);
451     } else if (transport == OHOS_BT_TRANSPORT_LE) {
452         remoteDevice = g_BluetoothHost->GetRemoteDevice(strAddress, BT_TRANSPORT_BLE);
453     } else {
454         HILOGE("transport: %{public}d is invalid", transport);
455         return false;
456     }
457     bool ret = remoteDevice.PairRequestReply(accept);
458     HILOGI("transport: %{public}d, accept: %{public}d, ret: %{public}d", transport, accept, ret);
459     return ret;
460 }
461 
SetDevicePairingConfirmation(const BdAddr *bdAddr, int transport, bool accept)462 bool SetDevicePairingConfirmation(const BdAddr *bdAddr, int transport, bool accept)
463 {
464     string strAddress;
465     ConvertAddr(bdAddr->addr, strAddress);
466     HILOGI("device: %{public}s, accept: %{public}d", GetEncryptAddr(strAddress).c_str(), accept);
467     BluetoothRemoteDevice remoteDevice;
468     if (transport == OHOS_BT_TRANSPORT_BR_EDR) {
469         remoteDevice = g_BluetoothHost->GetRemoteDevice(strAddress, BT_TRANSPORT_BREDR);
470     } else if (transport == OHOS_BT_TRANSPORT_LE) {
471         remoteDevice = g_BluetoothHost->GetRemoteDevice(strAddress, BT_TRANSPORT_BLE);
472     } else {
473         HILOGE("transport: %{public}d is invalid", transport);
474         return false;
475     }
476     bool isSuccess = false;
477     int ret = remoteDevice.SetDevicePairingConfirmation(accept);
478     HILOGI("ret: %{public}d", ret);
479     if (ret == BT_NO_ERROR) {
480         isSuccess = true;
481     }
482     return isSuccess;
483 }
484 
485 /**
486  * explain: This function does not support dynamic registration;
487  */
GapRegisterCallbacks(BtGapCallBacks *func)488 int GapRegisterCallbacks(BtGapCallBacks *func)
489 {
490     HILOGI("enter");
491     if (func == nullptr) {
492         HILOGE("func is null.");
493         return OHOS_BT_STATUS_PARM_INVALID;
494     }
495     if (g_BluetoothHost == nullptr) {
496         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
497     }
498     g_GapCallback = func;
499     g_hostObserver = std::make_shared<BluetoothHostObserverWapper>();
500     g_remoteDeviceObserver = std::make_shared<BluetoothRemoteDeviceObserverWapper>();
501     g_BluetoothHost->RegisterObserver(g_hostObserver);
502     g_BluetoothHost->RegisterRemoteDeviceObserver(g_remoteDeviceObserver);
503     return OHOS_BT_STATUS_SUCCESS;
504 }
505 
SetFastScan(bool isEnable)506 bool SetFastScan(bool isEnable)
507 {
508     HILOGI("isEnable: %{public}d", isEnable);
509     if (g_BluetoothHost == nullptr) {
510         g_BluetoothHost = &BluetoothHost::GetDefaultHost();
511     }
512     bool isSuccess = false;
513     int ret = g_BluetoothHost->SetFastScan(isEnable);
514     if (ret == BT_NO_ERROR) {
515         isSuccess = true;
516     }
517 
518     return isSuccess;
519 }
520 }  // namespace Bluetooth
521 }  // namespace OHOS
522 #ifdef __cplusplus
523 }
524 #endif
525