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