• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-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 "ohos_bt_gatt.h"
17 
18 #include <unistd.h>
19 #include <cstdint>
20 #include <sstream>
21 #include <vector>
22 #include "__config"
23 #include "bluetooth_ble_advertiser.h"
24 #include "bluetooth_ble_central_manager.h"
25 #include "bluetooth_log.h"
26 #include "bluetooth_remote_device.h"
27 #include "bluetooth_utils.h"
28 #include "cstdint"
29 #include "iosfwd"
30 #include "istream"
31 #include "new"
32 #include "ohos_bt_adapter_utils.h"
33 #include "ohos_bt_def.h"
34 #include "ostream"
35 #include "securec.h"
36 #include "streambuf"
37 #include "string"
38 #include "uuid.h"
39 #include "bluetooth_object_map.h"
40 #include "ohos_bt_gatt_utils.h"
41 #include "bluetooth_timer.h"
42 #include "ffrt.h"
43 #include <functional>
44 #include "ohos_bt_gap.h"
45 
46 
47 #ifdef __cplusplus
48 extern "C" {
49 #endif
50 
51 using namespace std;
52 
53 namespace OHOS {
54 namespace Bluetooth {
55 #define MAX_BLE_ADV_NUM 7
56 
57 class BleCentralManagerCallbackWapper;
58 class BleAdvCallback;
59 
60 static BtGattCallbacks *g_AppCallback;
61 
62 static std::shared_ptr<BleAdvCallback> g_bleAdvCallbacks[MAX_BLE_ADV_NUM];
63 static std::shared_ptr<BleAdvertiser> g_BleAdvertiser = nullptr;
64 static mutex g_advMutex;
65 
66 constexpr int32_t MAX_BLE_SCAN_NUM = 5;
67 static BluetoothObjectMap<std::shared_ptr<BleCentralManager>, (MAX_BLE_SCAN_NUM + 1)> g_bleCentralManagerMap;
68 
69 static uint32_t g_advAddrTimerIds[MAX_BLE_ADV_NUM];
70 static mutex g_advTimerMutex;
71 // ffrt queue
72 static ffrt::queue startAdvQueue("startAdv_Queue");
73 
74 class BleCentralManagerCallbackWapper : public BleCentralManagerCallback {
75 public:
76     /**
77      * @brief Scan result callback.
78      *
79      * @param result Scan result.
80      * @since 6
81      */
OnScanCallback(const BleScanResult & result)82     void OnScanCallback(const BleScanResult &result) override
83     {
84         BtScanResultData scanResult;
85         if (result.IsConnectable()) {
86             scanResult.eventType = OHOS_BLE_EVT_LEGACY_CONNECTABLE;
87         } else {
88             scanResult.eventType = OHOS_BLE_EVT_LEGACY_NON_CONNECTABLE;
89         }
90         scanResult.dataStatus = OHOS_BLE_DATA_COMPLETE;
91         scanResult.addrType = OHOS_BLE_RANDOM_DEVICE_ADDRESS;
92         scanResult.primaryPhy = OHOS_BLE_SCAN_PHY_1M;
93         scanResult.secondaryPhy = OHOS_BLE_SCAN_PHY_1M;
94         scanResult.advSid = 1;
95         scanResult.txPower = 1;
96         scanResult.rssi = result.GetRssi();
97         scanResult.directAddrType = OHOS_BLE_RANDOM_DEVICE_ADDRESS;
98         GetAddrFromString(result.GetPeripheralDevice().GetDeviceAddr(), scanResult.addr.addr);
99         vector<uint8_t> vec = result.GetPayload();
100         scanResult.advData = vec.data();
101         scanResult.advLen = vec.size();
102 
103         std::string strs;
104         std::stringstream strStream;
105         for (int i = 0; i < scanResult.advLen; i++) {
106             char token[3] = {0}; // The length of token is 3.
107             (void)sprintf_s(token, sizeof(token), "%02X", scanResult.advData[i]);
108             strStream << token;
109         }
110         strStream >> strs;
111         string address = result.GetPeripheralDevice().GetDeviceAddr();
112         HILOGD("device: %{public}s, len: %{public}d, scan data: %{public}s",
113             GetEncryptAddr(address).c_str(), scanResult.advLen, strs.c_str());
114         if (appCallback != nullptr && appCallback->scanResultCb != nullptr) {
115             appCallback->scanResultCb(&scanResult);
116         } else {
117             HILOGW("call back is null.");
118         }
119     }
120 
121     /**
122      * @brief Scan result for found or lost callback type.
123      *
124      * @param result Scan result.
125      * @param callbackType callback Type.
126      * @since 12
127      */
OnFoundOrLostCallback(const BleScanResult & result,uint8_t callbackType)128     void OnFoundOrLostCallback(const BleScanResult &result, uint8_t callbackType) override {};
129 
130     /**
131      * @brief Batch scan results event callback.
132      *
133      * @param results Scan results.
134      * @since 6
135      */
OnBleBatchScanResultsEvent(const std::vector<BleScanResult> & results)136     void OnBleBatchScanResultsEvent(const std::vector<BleScanResult> &results) override {}
137 
138     /**
139      * @brief Start or Stop scan event callback.
140      *
141      * @param resultCode Scan result code.
142      * @param isStartScan true->start scan, false->stop scan.
143      * @since 6
144      */
OnStartOrStopScanEvent(int32_t resultCode,bool isStartScan)145     void OnStartOrStopScanEvent(int32_t resultCode, bool isStartScan) override
146     {
147         HILOGD("resultCode: %{public}d, isStartScan: %{public}d", resultCode, isStartScan);
148         if (appCallback != nullptr && appCallback->scanStateChangeCb != nullptr) {
149             appCallback->scanStateChangeCb(resultCode, isStartScan);
150         } else {
151             HILOGE("call back is null.");
152         }
153     }
154 
155     /**
156      * @brief Notify low power device msg callback.
157      *
158      * @param btUuid uuid.
159      * @param msgType notify msgType.
160      * @param value notify msg value.
161      * @since 6
162      */
OnNotifyMsgReportFromLpDevice(const UUID & btUuid,int msgType,const std::vector<uint8_t> & value)163     void OnNotifyMsgReportFromLpDevice(const UUID &btUuid, int msgType, const std::vector<uint8_t> &value) override
164     {
165         if (appCallback != nullptr && appCallback->lpDeviceInfoCb != nullptr) {
166             BtUuid retUuid;
167             string strUuid = btUuid.ToString();
168             retUuid.uuid = (char *)strUuid.c_str();
169             retUuid.uuidLen = strUuid.size();
170             appCallback->lpDeviceInfoCb(&retUuid, msgType, const_cast<uint8_t*>(value.data()), value.size());
171         }
172     }
173 
174 public:
175     BleScanCallbacks *appCallback = nullptr;
176 };
177 
178 class BleAdvCallback : public BleAdvertiseCallback {
179 public:
BleAdvCallback(int advId)180     explicit BleAdvCallback(int advId)
181     {
182         advId_ = advId;
183     }
184 
OnStartResultEvent(int32_t result,int32_t advHandle)185     void OnStartResultEvent(int32_t result, int32_t advHandle) override
186     {
187         HILOGD("advId: %{public}d, advHandle: %{public}d, ret: %{public}d", advId_, advHandle, result);
188         int ret = (result == 0) ? OHOS_BT_STATUS_SUCCESS : OHOS_BT_STATUS_FAIL;
189         advHandle_ = advHandle;
190         if (g_AppCallback != nullptr && g_AppCallback->advEnableCb != nullptr) {
191             g_AppCallback->advEnableCb(advId_, ret);
192         } else {
193             HILOGW("call back is null.");
194         }
195     }
196 
OnEnableResultEvent(int result,int advHandle)197     void OnEnableResultEvent(int result, int advHandle) override
198     {}
199 
OnDisableResultEvent(int result,int advHandle)200     void OnDisableResultEvent(int result, int advHandle) override
201     {}
202 
OnStopResultEvent(int result,int advHandle)203     void OnStopResultEvent(int result, int advHandle) override
204     {
205         HILOGD("advId: %{public}d, advHandle: %{public}d, ret: %{public}d", advId_, advHandle, result);
206         int ret = (result == 0) ? OHOS_BT_STATUS_SUCCESS : OHOS_BT_STATUS_FAIL;
207         advHandle_ = 0xFF; // restore invalid advHandle
208         if (g_AppCallback != nullptr && g_AppCallback->advDisableCb != nullptr) {
209             g_AppCallback->advDisableCb(advId_, ret);
210         } else {
211             HILOGW("call back is null.");
212         }
213         {
214             lock_guard<mutex> lock(g_advTimerMutex);
215             if (g_advAddrTimerIds[advId_] != 0) {
216                 BluetoothTimer::GetInstance()->UnRegister(g_advAddrTimerIds[advId_]);
217                 g_advAddrTimerIds[advId_] = 0;
218             } else {
219                 HILOGD("TimerId no registered, is 0.");
220             }
221         }
222         g_bleAdvCallbacks[advId_] = nullptr;
223     }
224 
OnSetAdvDataEvent(int result)225     void OnSetAdvDataEvent(int result) override
226     {
227         HILOGD("advId: %{public}d, ret: %{public}d", advId_, result);
228         int ret = (result == 0) ? OHOS_BT_STATUS_SUCCESS : OHOS_BT_STATUS_FAIL;
229         if (g_AppCallback != nullptr && g_AppCallback->advDataCb  != nullptr) {
230             g_AppCallback->advDataCb(advId_, ret);
231         }
232     }
233 
OnGetAdvHandleEvent(int result,int advHandle)234     void OnGetAdvHandleEvent(int result, int advHandle) override
235     {}
236 
GetAdvHandle()237     int GetAdvHandle()
238     {
239         return advHandle_;
240     }
241 
242 protected:
243     BleAdvertiserData *advData = nullptr;
244     BleAdvertiserData *advResponseData = nullptr;
245     BleAdvertiserSettings *advSetting = nullptr;
246 
247 private:
248     int advId_;
249     int32_t advHandle_ = 0xFF;
250 };
251 
252 /**
253  * @brief Initializes the Bluetooth protocol stack.
254  *
255  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the Bluetooth protocol stack is initialized;
256  * returns an error code defined in {@link BtStatus} otherwise.
257  * @since 6
258  */
InitBtStack(void)259 int InitBtStack(void)
260 {
261     return OHOS_BT_STATUS_SUCCESS;
262 }
263 
264 /**
265  * @brief Enables the Bluetooth protocol stack.
266  *
267  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the Bluetooth protocol stack is enabled;
268  * returns an error code defined in {@link BtStatus} otherwise.
269  * @since 6
270  */
EnableBtStack(void)271 int EnableBtStack(void)
272 {
273     return OHOS_BT_STATUS_SUCCESS;
274 }
275 
276 /**
277  * @brief Disables the Bluetooth protocol stack.
278  *
279  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the Bluetooth protocol stack is disabled;
280  * returns an error code defined in {@link BtStatus} otherwise.
281  * @since 6
282  */
DisableBtStack(void)283 int DisableBtStack(void)
284 {
285     return OHOS_BT_STATUS_SUCCESS;
286 }
287 
288 /**
289  * @brief Sets the Bluetooth device name.
290  *
291  * @param name Indicates the pointer to the name to set.
292  * @param len Indicates the length of the name to set.
293  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the Bluetooth device name is set;
294  * returns an error code defined in {@link BtStatus} otherwise.
295  * @since 6
296  */
SetDeviceName(const char * name,unsigned int len)297 int SetDeviceName(const char *name, unsigned int len)
298 {
299     return OHOS_BT_STATUS_UNSUPPORTED;
300 }
301 
ConvertDataToVec(uint8_t * data,unsigned int len)302 static vector<uint8_t> ConvertDataToVec(uint8_t *data, unsigned int len)
303 {
304     if (data == nullptr || len == 0) {
305         return {};
306     }
307 
308     return vector<uint8_t>(data, data + len);
309 }
310 
311 /**
312  * @brief Sets advertising data.
313  *
314  * @param advId Indicates the advertisement ID, which is allocated by the upper layer of the advertiser.
315  * @param data Indicates the pointer to the advertising data. For details, see {@link StartAdvRawData}.
316  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if advertising data is set;
317  * returns an error code defined in {@link BtStatus} otherwise.
318  * @since 6
319  */
BleSetAdvData(int advId,const StartAdvRawData data)320 int BleSetAdvData(int advId, const StartAdvRawData data)
321 {
322     if (advId < 0 || advId >= MAX_BLE_ADV_NUM) {
323         HILOGE("Invalid advId (%{public}d)", advId);
324         return OHOS_BT_STATUS_PARM_INVALID;
325     }
326     lock_guard<mutex> lock(g_advMutex);
327     if (g_BleAdvertiser == nullptr || g_bleAdvCallbacks[advId] == nullptr) {
328         HILOGE("Adv is not started, need call 'BleStartAdvEx' first.");
329         return OHOS_BT_STATUS_FAIL;
330     }
331     HILOGD("advId: %{public}d, advLen: %{public}u, scanRspLen: %{public}u", advId, data.advDataLen, data.rspDataLen);
332 
333     auto advData = ConvertDataToVec(data.advData, data.advDataLen);
334     auto rspData = ConvertDataToVec(data.rspData, data.rspDataLen);
335     g_BleAdvertiser->SetAdvertisingData(advData, rspData, g_bleAdvCallbacks[advId]);
336     return OHOS_BT_STATUS_SUCCESS;
337 }
338 
339 /**
340  * @brief Starts advertising.
341  *
342  * @param advId Indicates the advertisement ID, which is allocated by the upper layer of the advertiser.
343  * @param param Indicates the pointer to the advertising parameters. For details, see {@link BleAdvParams}.
344  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if advertising is started;
345  * returns an error code defined in {@link BtStatus} otherwise.
346  * @since 6
347  */
BleStartAdv(int advId,const BleAdvParams * param)348 int BleStartAdv(int advId, const BleAdvParams *param)
349 {
350     return OHOS_BT_STATUS_UNSUPPORTED;
351 }
352 
353 /**
354  * @brief Stops advertising.
355  *
356  * @param advId Indicates the advertisement ID, which is allocated by the upper layer of the advertiser.
357  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if advertising is stopped;
358  * returns an error code defined in {@link BtStatus} otherwise.
359  * @since 6
360  */
BleStopAdv(int advId)361 int BleStopAdv(int advId)
362 {
363     HILOGD("BleStopAdv, advId: %{public}d.", advId);
364     if (advId < 0 || advId >= MAX_BLE_ADV_NUM) {
365         HILOGE("BleStopAdv fail, advId is invalid.");
366         return OHOS_BT_STATUS_FAIL;
367     }
368     lock_guard<mutex> lock(g_advMutex);
369     if (g_BleAdvertiser == nullptr || g_bleAdvCallbacks[advId] == nullptr) {
370         HILOGE("BleStopAdv fail, the current adv is not started.");
371         return OHOS_BT_STATUS_FAIL;
372     }
373     {
374         lock_guard<mutex> lock(g_advTimerMutex);
375         BluetoothTimer::GetInstance()->UnRegister(g_advAddrTimerIds[advId]);
376         g_advAddrTimerIds[advId] = 0;
377     }
378 
379     std::function stopAdvFunc = [advId]() {
380         HILOGI("stop adv in adv_Queue thread, advId = %{public}d", advId);
381         lock_guard<mutex> lock(g_advMutex);
382         int ret = g_BleAdvertiser->StopAdvertising(g_bleAdvCallbacks[advId]);
383         if (ret != BT_NO_ERROR) {
384             HILOGE("fail, advId: %{public}d, ret: %{public}d", advId, ret);
385         }
386     };
387     startAdvQueue.submit(stopAdvFunc);
388 
389     return OHOS_BT_STATUS_SUCCESS;
390 }
391 
392 /**
393  * @brief Updates advertising parameters.
394  *
395  * @param advId Indicates the advertisement ID, which is allocated by the upper layer of the advertiser.
396  * @param param Indicates the pointer to the advertising parameters. For details, see {@link BleAdvParams}.
397  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if advertising parameters are updated;
398  * returns an error code defined in {@link BtStatus} otherwise.
399  * @since 6
400  */
BleUpdateAdv(int advId,const BleAdvParams * param)401 int BleUpdateAdv(int advId, const BleAdvParams *param)
402 {
403     return OHOS_BT_STATUS_UNSUPPORTED;
404 }
405 
406 /**
407  * @brief Sets the secure I/O capability mode.
408  *
409  * @param mode Indicates the capability mode to set. For details, see {@link BleIoCapMode}.
410  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the capability mode is set;
411  * returns an error code defined in {@link BtStatus} otherwise.
412  * @since 6
413  */
BleSetSecurityIoCap(BleIoCapMode mode)414 int BleSetSecurityIoCap(BleIoCapMode mode)
415 {
416     return OHOS_BT_STATUS_UNSUPPORTED;
417 }
418 
419 /**
420  * @brief Sets the authentication mode for secure connection requests.
421  *
422  * @param mode Indicates the authentication mode to set. For details, see {@link BleAuthReqMode}.
423  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the authentication mode is set;
424  * returns an error code defined in {@link BtStatus} otherwise.
425  * @since 6
426  */
BleSetSecurityAuthReq(BleAuthReqMode mode)427 int BleSetSecurityAuthReq(BleAuthReqMode mode)
428 {
429     return OHOS_BT_STATUS_UNSUPPORTED;
430 }
431 
432 /**
433  * @brief Responds to a secure connection request.
434  *
435  * @param bdAddr Indicates the address of the device that sends the request.
436  * @param accept Specifies whether to accept the request. The value <b>true</b> means to accept the request,
437  * and <b>false</b> means to reject the request.
438  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the request is responded to;
439  * returns an error code defined in {@link BtStatus} otherwise.
440  * @since 6
441  */
BleGattSecurityRsp(BdAddr bdAddr,bool accept)442 int BleGattSecurityRsp(BdAddr bdAddr, bool accept)
443 {
444     return OHOS_BT_STATUS_UNSUPPORTED;
445 }
446 
447 /**
448  * @brief Obtains the device MAC address.
449  *
450  * @param mac Indicates the pointer to the device MAC address.
451  * @param len Indicates the length of the device MAC address.
452  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the device MAC address is obtained;
453  * returns an error code defined in {@link BtStatus} otherwise.
454  * @since 6
455  */
ReadBtMacAddr(unsigned char * mac,unsigned int len)456 int ReadBtMacAddr(unsigned char *mac, unsigned int len)
457 {
458     return OHOS_BT_STATUS_UNSUPPORTED;
459 }
460 
461 /**
462  * @brief Sets scan parameters.
463  *
464  * @param clientId Indicates the client ID, which is obtained during client registration.
465  * @param param Indicates the pointer to the scan parameters. For details, see {@link BleScanParams}.
466  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the scan parameters are set;
467  * returns an error code defined in {@link BtStatus} otherwise.
468  * @since 6
469  */
BleSetScanParameters(int clientId,BleScanParams * param)470 int BleSetScanParameters(int clientId, BleScanParams *param)
471 {
472     return OHOS_BT_STATUS_SUCCESS;
473 }
474 
475 /**
476  * @brief Starts a scan.
477  *
478  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the scan is started;
479  * returns an error code defined in {@link BtStatus} otherwise.
480  * @since 6
481  */
BleStartScan(void)482 int BleStartScan(void)
483 {
484     HILOGE("This interface is deprecated. BleStartScanEx is recommended.");
485     return OHOS_BT_STATUS_UNSUPPORTED;
486 }
487 
488 /**
489  * @brief Stops a scan.
490  *
491  * @param scannerId Indicates the scanner id.
492  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the scan is stopped;
493  * returns an error code defined in {@link BtStatus} otherwise.
494  * @since 6
495  */
BleStopScan(int32_t scannerId)496 int BleStopScan(int32_t scannerId)
497 {
498     HILOGD("BleStopScan enter scannerId: %{public}d", scannerId);
499     std::shared_ptr<BleCentralManager> bleCentralManager = g_bleCentralManagerMap.GetObject(scannerId);
500     if (bleCentralManager == nullptr) {
501         HILOGE("BleStopScan fail, scannerId is invalid.");
502         return OHOS_BT_STATUS_FAIL;
503     }
504 
505     bleCentralManager->StopScan();
506     return OHOS_BT_STATUS_SUCCESS;
507 }
508 
509 /**
510  * @brief Registers GATT callbacks.
511  * explain: This function does not support dynamic registration;
512  * @param func Indicates the pointer to the callbacks to register. For details, see {@link BtGattCallbacks}.
513  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the GATT callbacks are registered;
514  * returns an error code defined in {@link BtStatus} otherwise.
515  * @since 6
516  */
BleGattRegisterCallbacks(BtGattCallbacks * func)517 int BleGattRegisterCallbacks(BtGattCallbacks *func)
518 {
519     HILOGI("BleGattRegisterCallbacks enter");
520     if (func == nullptr) {
521         HILOGE("func is null.");
522         return OHOS_BT_STATUS_PARM_INVALID;
523     }
524     g_AppCallback = func;
525     return OHOS_BT_STATUS_SUCCESS;
526 }
527 
528 /**
529  * @brief Register ble scan callbacks.
530  *
531  * @param func Indicates the pointer to the callbacks to register. For details, see {@link BleScanCallbacks}.
532  * @param scannerId Indicates the pointer to the scannerId, identify one scan.
533  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the BLE callbacks are registered;
534  * returns an error code defined in {@link BtStatus} otherwise.
535  * @since 6
536  */
BleRegisterScanCallbacks(BleScanCallbacks * func,int32_t * scannerId)537 int BleRegisterScanCallbacks(BleScanCallbacks *func, int32_t *scannerId)
538 {
539     HILOGI("BleRegisterScanCallbacks enter");
540     if (scannerId == nullptr || func == nullptr) {
541         HILOGE("BleRegisterScanCallbacks scannerId or func is null");
542         return OHOS_BT_STATUS_PARM_INVALID;
543     }
544 
545     std::shared_ptr<BleCentralManagerCallbackWapper> callback = std::make_shared<BleCentralManagerCallbackWapper>();
546     callback->appCallback = func;
547     std::shared_ptr<BleCentralManager> bleCentralManager = std::make_shared<BleCentralManager>(callback);
548     int id = g_bleCentralManagerMap.AddLimitedObject(bleCentralManager);
549     if (id == -1) {
550         HILOGE("BleRegisterScanCallbacks fail.");
551         return OHOS_BT_STATUS_FAIL;
552     }
553     *scannerId = id;
554     HILOGI("BleRegisterScanCallbacks success scannerId: %{public}d", *scannerId);
555     return OHOS_BT_STATUS_SUCCESS;
556 }
557 
558 /**
559  * @brief Deregister ble scan callbacks.
560  *
561  * @param scannerId Indicates the scanner id.
562  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the BLE callbacks are deregistered;
563  * returns an error code defined in {@link BtStatus} otherwise.
564  * @since 6
565  */
BleDeregisterScanCallbacks(int32_t scannerId)566 int BleDeregisterScanCallbacks(int32_t scannerId)
567 {
568     HILOGI("BleDeregisterScanCallbacks enter. scannerId: %{public}d", scannerId);
569     if (g_bleCentralManagerMap.GetObject(scannerId) == nullptr) {
570         HILOGE("BleDeregisterScanCallbacks fail, scannerId is invalid.");
571         return OHOS_BT_STATUS_FAIL;
572     }
573     g_bleCentralManagerMap.RemoveObject(scannerId);
574     return OHOS_BT_STATUS_SUCCESS;
575 }
576 
577 /*
578  * RPA: The two highest bits of the broadcast address are 01, and address type is random.
579  */
IsRpa(const AdvOwnAddrParams * ownAddrParams)580 static bool IsRpa(const AdvOwnAddrParams *ownAddrParams)
581 {
582     if (ownAddrParams != nullptr && ((ownAddrParams->addr[0] & 0xC0) ^ 0x40) == 0 &&
583         ownAddrParams->addrType == BLE_ADDR_RANDOM) {
584             return true;
585         }
586     return false;
587 }
588 
589 /**
590  * @brief Sets own address, own address type, advertising data and parameters, and then starts advertising.
591  *
592  * This function is available for softbus only.
593  *
594  * @param advId Indicates the pointer to the advertisement ID.
595  * @param rawData Indicates the advertising data. For details, see {@link StartAdvRawData}.
596  * @param advParam Indicates the advertising parameters. For details, see {@link BleAdvParams}.
597  * @param ownAddrParams Indicates the own address(little endian) and own address type.
598  * For details, see {@link AdvOwnAddrParams}.
599  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the operation is successful;
600  * returns an error code defined in {@link BtStatus} otherwise.
601  * @since 6
602  */
BleStartAdvWithAddr(int * advId,const StartAdvRawData * rawData,const BleAdvParams * advParam,const AdvOwnAddrParams * ownAddrParams)603 int BleStartAdvWithAddr(int *advId, const StartAdvRawData *rawData, const BleAdvParams *advParam,
604     const AdvOwnAddrParams *ownAddrParams)
605 {
606     HILOGD("BleStartAdvWithAddr enter");
607     if (advId == nullptr || rawData == nullptr || advParam == nullptr || !IsRpa(ownAddrParams)) {
608         HILOGW("params are invalid");
609         return OHOS_BT_STATUS_PARM_INVALID;
610     }
611     if (!IsBleEnabled()) {
612         HILOGE("bluetooth is off.");
613         *advId = -1;
614         return OHOS_BT_STATUS_NOT_READY;
615     }
616     lock_guard<mutex> lock(g_advMutex);
617     int i = AllocateAdvHandle();
618     if (i == MAX_BLE_ADV_NUM) {
619         HILOGW("reach the max num of adv");
620         return OHOS_BT_STATUS_UNHANDLED;
621     }
622     *advId = i;
623 
624     if (!StartAdvAddrTimer(i, ownAddrParams)) {
625         HILOGE("Duplicate addresses after 15 minutes are not allowed to be broadcast");
626         g_bleAdvCallbacks[i] = nullptr;
627         *advId = -1;
628         return OHOS_BT_STATUS_DUPLICATED_ADDR;
629     }
630 
631     BleAdvertiserSettings settings;
632     settings.SetInterval(advParam->minInterval);
633     if (advParam->advType == OHOS_BLE_ADV_SCAN_IND || advParam->advType == OHOS_BLE_ADV_NONCONN_IND) {
634         settings.SetConnectable(false);
635     }
636     std::array<uint8_t, OHOS_BD_ADDR_LEN> addr;
637     std::copy(std::begin(ownAddrParams->addr), std::end(ownAddrParams->addr), std::begin(addr));
638     settings.SetOwnAddr(addr);
639     settings.SetOwnAddrType(ownAddrParams->addrType);
640 
641     auto advData = ConvertDataToVec(rawData->advData, rawData->advDataLen);
642     auto scanResponse = ConvertDataToVec(rawData->rspData, rawData->rspDataLen);
643     if (g_BleAdvertiser == nullptr) {
644         g_BleAdvertiser = BleAdvertiser::CreateInstance();
645     }
646 
647     std::function startAdvFunc = [i, advData, scanResponse, settings]() {
648         HILOGI("start adv in startAdv_Queue thread, handle = %{public}d", i);
649         lock_guard<mutex> lock(g_advMutex);
650         int ret = g_BleAdvertiser->StartAdvertising(settings, advData, scanResponse, 0, g_bleAdvCallbacks[i]);
651         if (ret != BT_NO_ERROR) {
652             HILOGE("fail, ret: %{public}d", ret);
653             //StartAdvertise fail, return default handle -1 to softbus
654             g_bleAdvCallbacks[i] = nullptr;
655             {
656                 lock_guard<mutex> lock(g_advTimerMutex);
657                 BluetoothTimer::GetInstance()->UnRegister(g_advAddrTimerIds[i]);
658                 g_advAddrTimerIds[i] = 0;
659             }
660         }
661     };
662     startAdvQueue.submit(startAdvFunc);
663     HILOGI("ret advId: %{public}d.", *advId);
664     return OHOS_BT_STATUS_SUCCESS;
665 }
666 
667 /**
668  * @brief Sets advertising data and parameters and starts advertising.
669  *
670  * This function is available for system applications only. \n
671  *
672  * @param advId Indicates the pointer to the advertisement ID.
673  * @param rawData Indicates the advertising data. For details, see {@link StartAdvRawData}.
674  * @param advParam Indicates the advertising parameters. For details, see {@link BleAdvParams}.
675  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the operation is successful;
676  * returns an error code defined in {@link BtStatus} otherwise.
677  * @since 6
678  */
BleStartAdvEx(int * advId,const StartAdvRawData rawData,BleAdvParams advParam)679 int BleStartAdvEx(int *advId, const StartAdvRawData rawData, BleAdvParams advParam)
680 {
681     HILOGD("BleStartAdvEx enter");
682     if (!IsBleEnabled()) {
683         HILOGE("bluetooth is off.");
684         *advId = -1;
685         return OHOS_BT_STATUS_NOT_READY;
686     }
687 
688     lock_guard<mutex> lock(g_advMutex);
689     if (g_BleAdvertiser == nullptr) {
690         g_BleAdvertiser = BleAdvertiser::CreateInstance();
691     }
692     int i = 0;
693     for (i = 0; i < MAX_BLE_ADV_NUM; i++) {
694         if (g_bleAdvCallbacks[i] == nullptr) {
695             g_bleAdvCallbacks[i] = std::make_shared<BleAdvCallback>(i);
696             break;
697         }
698     }
699 
700     if (i == MAX_BLE_ADV_NUM) {
701         HILOGW("reach the max num of adv");
702         return OHOS_BT_STATUS_UNHANDLED;
703     }
704     *advId = i;
705     BleAdvertiserSettings settings;
706     settings.SetInterval(advParam.minInterval);
707     if (advParam.advType == OHOS_BLE_ADV_SCAN_IND || advParam.advType == OHOS_BLE_ADV_NONCONN_IND) {
708         settings.SetConnectable(false);
709     }
710     auto advData = ConvertDataToVec(rawData.advData, rawData.advDataLen);
711     auto scanResponse = ConvertDataToVec(rawData.rspData, rawData.rspDataLen);
712 
713     std::function startAdvFunc = [i, advData, scanResponse, settings]() {
714         HILOGI("start adv in startAdv_Queue thread, handle = %{public}d", i);
715         lock_guard<mutex> lock(g_advMutex);
716         int ret = g_BleAdvertiser->StartAdvertising(settings, advData, scanResponse, 0, g_bleAdvCallbacks[i]);
717         if (ret != BT_NO_ERROR) {
718             HILOGE("fail, ret: %{public}d", ret);
719             //StartAdvertise fail, return default handle -1 to softbus
720             g_bleAdvCallbacks[i] = nullptr;
721         }
722     };
723     startAdvQueue.submit(startAdvFunc);
724     HILOGI("ret advId: %{public}d.", *advId);
725     return OHOS_BT_STATUS_SUCCESS;
726 }
727 
728 /**
729  * @brief Enable advertising.
730  *
731  * This function is available for system applications only. \n
732  *
733  * @param advId Indicates the pointer to the advertisement ID.
734  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the operation is successful;
735  * returns an error code defined in {@link BtStatus} otherwise.
736  * @since 11
737  */
BleEnableAdvEx(int advId)738 int BleEnableAdvEx(int advId)
739 {
740     HILOGI("BleEnableAdv, advId: %{public}d.", advId);
741     if (advId < 0 || advId >= MAX_BLE_ADV_NUM) {
742         HILOGE("BleEnableAdv fail, advId is invalid.");
743         return OHOS_BT_STATUS_FAIL;
744     }
745     lock_guard<mutex> lock(g_advMutex);
746     if (g_BleAdvertiser == nullptr || g_bleAdvCallbacks[advId] == nullptr) {
747         HILOGE("BleEnableAdv fail, the current adv is not started.");
748         return OHOS_BT_STATUS_FAIL;
749     }
750 
751     int ret = g_BleAdvertiser->EnableAdvertising(g_bleAdvCallbacks[advId]->GetAdvHandle(), 0,
752         g_bleAdvCallbacks[advId]);
753     if (ret != BT_NO_ERROR) {
754         HILOGE("fail, advId: %{public}d, ret: %{public}d", advId, ret);
755         return OHOS_BT_STATUS_FAIL;
756     }
757     return OHOS_BT_STATUS_SUCCESS;
758 }
759 
760 /**
761  * @brief Disable advertising.
762  *
763  * This function is available for system applications only. \n
764  *
765  * @param advId Indicates the pointer to the advertisement ID.
766  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the operation is successful;
767  * returns an error code defined in {@link BtStatus} otherwise.
768  * @since 11
769  */
BleDisableAdvEx(int advId)770 int BleDisableAdvEx(int advId)
771 {
772     HILOGI("BleDisableAdv, advId: %{public}d.", advId);
773     if (advId < 0 || advId >= MAX_BLE_ADV_NUM) {
774         HILOGE("BleDisableAdv fail, advId is invalid.");
775         return OHOS_BT_STATUS_FAIL;
776     }
777     lock_guard<mutex> lock(g_advMutex);
778     if (g_BleAdvertiser == nullptr || g_bleAdvCallbacks[advId] == nullptr) {
779         HILOGE("BleDisableAdv fail, the current adv is not started.");
780         return OHOS_BT_STATUS_FAIL;
781     }
782 
783     int ret = g_BleAdvertiser->DisableAdvertising(g_bleAdvCallbacks[advId]->GetAdvHandle(), g_bleAdvCallbacks[advId]);
784     if (ret != BT_NO_ERROR) {
785         HILOGE("fail, advId: %{public}d, ret: %{public}d", advId, ret);
786         return OHOS_BT_STATUS_FAIL;
787     }
788     return OHOS_BT_STATUS_SUCCESS;
789 }
790 
SetServiceUuidParameter(BleScanFilter & scanFilter,BleScanNativeFilter * nativeScanFilter)791 static bool SetServiceUuidParameter(BleScanFilter &scanFilter, BleScanNativeFilter *nativeScanFilter)
792 {
793     HILOGD("SetServiceUuidParameter enter");
794     if (nativeScanFilter->serviceUuidLength != 0 && nativeScanFilter->serviceUuid != nullptr) {
795         if (!IsValidUuid(std::string(reinterpret_cast<char *>(nativeScanFilter->serviceUuid)))) {
796             HILOGE("match the UUID faild.");
797             return false;
798         }
799         UUID serviceUuid = UUID::FromString((char *)nativeScanFilter->serviceUuid);
800         scanFilter.SetServiceUuid(serviceUuid);
801         if (nativeScanFilter->serviceUuidMask != nullptr) {
802             if (!IsValidUuid(std::string(reinterpret_cast<char *>(nativeScanFilter->serviceUuidMask)))) {
803                 HILOGE("match the UUID faild.");
804                 return false;
805             }
806             UUID serviceUuidMask = UUID::FromString((char *)nativeScanFilter->serviceUuidMask);
807             scanFilter.SetServiceUuidMask(serviceUuidMask);
808         }
809     }
810     return true;
811 }
812 
813 /**
814  * @brief Sets one scan filter config.
815  *
816  * @param scanFilter Indicates the framework object of scan filter, see {@link BleScanFilter}.
817  * @param nativeScanFilter Indicates the pointer to the scan filter. For details, see {@link BleScanNativeFilter}.
818  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if set onr scan filter config success;
819  * returns an error code defined in {@link BtStatus} otherwise.
820  * @since 6
821  */
SetOneScanFilter(BleScanFilter & scanFilter,BleScanNativeFilter * nativeScanFilter)822 static int SetOneScanFilter(BleScanFilter &scanFilter, BleScanNativeFilter *nativeScanFilter)
823 {
824     HILOGD("SetOneScanFilter enter");
825     if (nativeScanFilter->address != nullptr) {
826         scanFilter.SetDeviceId(nativeScanFilter->address);
827     }
828     if (nativeScanFilter->deviceName != nullptr) {
829         scanFilter.SetName(nativeScanFilter->deviceName);
830     }
831     bool isSuccess = SetServiceUuidParameter(scanFilter, nativeScanFilter);
832     if (!isSuccess) {
833         HILOGE("SetServiceUuidParameter faild.");
834         return OHOS_BT_STATUS_PARM_INVALID;
835     }
836 
837     if (nativeScanFilter->serviceData != nullptr) {
838         std::vector<uint8_t> serviceData;
839         for (unsigned int i = 0; i < nativeScanFilter->serviceDataLength; i++) {
840             serviceData.push_back(nativeScanFilter->serviceData[i]);
841         }
842         scanFilter.SetServiceData(serviceData);
843 
844         if (nativeScanFilter->serviceDataMask != nullptr) {
845             std::vector<uint8_t> serviceDataMask;
846             for (unsigned int i = 0; i < nativeScanFilter->serviceDataLength; i++) {
847                 serviceDataMask.push_back(nativeScanFilter->serviceDataMask[i]);
848             }
849             scanFilter.SetServiceDataMask(serviceDataMask);
850         }
851     }
852 
853     if (nativeScanFilter->manufactureData != nullptr) {
854         std::vector<uint8_t> manufactureData;
855         for (unsigned int i = 0; i < nativeScanFilter->manufactureDataLength; i++) {
856             manufactureData.push_back(nativeScanFilter->manufactureData[i]);
857         }
858         scanFilter.SetManufactureData(manufactureData);
859 
860         if (nativeScanFilter->manufactureDataMask != nullptr) {
861             std::vector<uint8_t> manufactureDataMask;
862             for (unsigned int i = 0; i < nativeScanFilter->manufactureDataLength; i++) {
863                 manufactureDataMask.push_back(nativeScanFilter->manufactureDataMask[i]);
864             }
865             scanFilter.SetManufactureDataMask(manufactureDataMask);
866         }
867 
868         if (nativeScanFilter->manufactureId != 0) {
869             scanFilter.SetManufacturerId(nativeScanFilter->manufactureId);
870         }
871     }
872     scanFilter.SetAdvIndReportFlag(nativeScanFilter->advIndReport);
873     return OHOS_BT_STATUS_SUCCESS;
874 }
875 
876 /**
877  * @brief Sets scan filter configs.
878  *
879  * @param scannerId Indicates the scanner id.
880  * @param filter Indicates the pointer to the scan filter. For details, see {@link BleScanNativeFilter}.
881  * @param filterSize Indicates the number of the scan filter.
882  * @param outScanFilters expected scan filters.
883  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if set scan filter configs success;
884  * returns an error code defined in {@link BtStatus} otherwise.
885  * @since 6
886  */
SetConfigScanFilter(int32_t scannerId,const BleScanNativeFilter * filter,uint32_t filterSize,vector<BleScanFilter> & outScanFilters)887 static int SetConfigScanFilter(int32_t scannerId, const BleScanNativeFilter *filter, uint32_t filterSize,
888     vector<BleScanFilter> &outScanFilters)
889 {
890     HILOGD("SetConfigScanFilter enter");
891     for (uint32_t i = 0; i < filterSize; i++) {
892         BleScanNativeFilter nativeScanFilter = filter[i];
893         BleScanFilter scanFilter;
894         int result = SetOneScanFilter(scanFilter, &nativeScanFilter);
895         if (result != OHOS_BT_STATUS_SUCCESS) {
896             HILOGE("SetOneScanFilter faild, result: %{public}d", result);
897             return OHOS_BT_STATUS_PARM_INVALID;
898         }
899         outScanFilters.push_back(scanFilter);
900     }
901     return OHOS_BT_STATUS_SUCCESS;
902 }
903 
904 /**
905  * @brief Starts a scan with BleScanConfigs.
906  * If don't need ble scan filter, set BleScanNativeFilter to NULL or filterSize to zero.
907  * If one of the ble scan filtering rules is not required, set it to NULL.
908  * For example, set the address to NULL when you don't need it.
909  * Don't support only using manufactureId as filter conditions, need to use it with manufactureData.
910  * The manufactureId need to be set a related number when you need a filtering condition of manufactureData.
911  *
912  * @param scannerId Indicates the scanner id.
913  * @param configs Indicates the pointer to the scan filter. For details, see {@link BleScanConfigs}.
914  * @param filter Indicates the pointer to the scan filter. For details, see {@link BleScanNativeFilter}.
915  * @param filterSize Indicates the number of the scan filter.
916  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if the scan is started;
917  * returns an error code defined in {@link BtStatus} otherwise.
918  * @since 6
919  */
BleStartScanEx(int32_t scannerId,const BleScanConfigs * configs,const BleScanNativeFilter * filter,uint32_t filterSize)920 int BleStartScanEx(int32_t scannerId, const BleScanConfigs *configs, const BleScanNativeFilter *filter,
921     uint32_t filterSize)
922 {
923     if (configs == nullptr) {
924         HILOGE("BleStartScanEx fail, configs is null.");
925         return OHOS_BT_STATUS_FAIL;
926     }
927     HILOGD("BleStartScanEx enter, scannerId: %{public}d, filterSize %{public}u, scanMode: %{public}d",
928         scannerId, filterSize, configs->scanMode);
929     std::shared_ptr<BleCentralManager> bleCentralManager = g_bleCentralManagerMap.GetObject(scannerId);
930     if (bleCentralManager == nullptr) {
931         HILOGE("BleStartScanEx fail, scannerId is invalid.");
932         return OHOS_BT_STATUS_FAIL;
933     }
934 
935     vector<BleScanFilter> scanFilters;
936     if (filter != nullptr && filterSize != 0) {
937         int result = SetConfigScanFilter(scannerId, filter, filterSize, scanFilters);
938         if (result != OHOS_BT_STATUS_SUCCESS) {
939             HILOGE("SetConfigScanFilter faild, result: %{public}d", result);
940             return OHOS_BT_STATUS_PARM_INVALID;
941         }
942     }
943 
944     BleScanSettings settings;
945     settings.SetScanMode(configs->scanMode);
946     bleCentralManager->StartScan(settings, scanFilters);
947     return OHOS_BT_STATUS_SUCCESS;
948 }
949 
950 /**
951  * @brief Get BleCentralManager object.
952  * get one from existing objects, if not exist, create one.
953  * used to operate by BleCentralManager object, but not related to one scan.
954  *
955  * @param bleCentralManager the pointer of BleCentralManager.
956  * @since 6
957 */
GetBleCentralManagerObject(std::shared_ptr<BleCentralManager> & bleCentralManager)958 void GetBleCentralManagerObject(std::shared_ptr<BleCentralManager> &bleCentralManager)
959 {
960     bleCentralManager = g_bleCentralManagerMap.GetObject();
961     if (bleCentralManager == nullptr) {
962         HILOGI("no exist BleCentralManager");
963         std::shared_ptr<BleCentralManagerCallbackWapper> callback = std::make_shared<BleCentralManagerCallbackWapper>();
964         bleCentralManager = std::make_shared<BleCentralManager>(callback);
965     }
966 }
967 
968 /**
969  * @brief set low power device adv param.
970  *
971  * @param duration advertise duration.
972  * @param maxExtAdvEvents maximum number of extended advertising events.
973  * @param window work window.
974  * @param interval work interval.
975  * @param advHandle Indicates the advertise handle.
976  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if set success;
977  * returns an error code defined in {@link BtStatus} otherwise.
978  * @since 6
979 */
SetLpDeviceAdvParam(int duration,int maxExtAdvEvents,int window,int interval,int advHandle)980 int SetLpDeviceAdvParam(int duration, int maxExtAdvEvents, int window, int interval, int advHandle)
981 {
982     HILOGI("SetLpDeviceAdvParam enter. duration: %{public}d, maxExtAdvEvents: %{public}d, window: %{public}d \
983         interval: %{public}d, advHandle: %{public}d", duration, maxExtAdvEvents, window, interval, advHandle);
984     if (duration < LPDEVICE_ADVERTISING_DURATION_MIN || duration > LPDEVICE_ADVERTISING_DURATION_MAX) {
985         HILOGE("duration out of range:, duration: %{public}d", duration);
986         return OHOS_BT_STATUS_PARM_INVALID;
987     }
988 
989     if (maxExtAdvEvents < LPDEVICE_ADVERTISING_EXTADVEVENT_MIN
990         || maxExtAdvEvents > LPDEVICE_ADVERTISING_EXTADVEVENT_MAX) {
991         HILOGE("maxExtAdvEvents out of range:, maxExtAdvEvents: %{public}d", maxExtAdvEvents);
992         return OHOS_BT_STATUS_PARM_INVALID;
993     }
994 
995     if (window < LPDEVICE_ADVERTISING_WINDOW_MIN || window > LPDEVICE_ADVERTISING_WINDOW_MAX) {
996         HILOGE("window out of range:, window: %{public}d", window);
997         return OHOS_BT_STATUS_PARM_INVALID;
998     }
999 
1000     if (interval < LPDEVICE_ADVERTISING_INTERVAL_MIN || interval > LPDEVICE_ADVERTISING_INTERVAL_MAX) {
1001         HILOGE("interval out of range:, interval: %{public}d", interval);
1002         return OHOS_BT_STATUS_PARM_INVALID;
1003     }
1004 
1005     if (interval < window) {
1006         HILOGE("interval must bigger than window, interval: %{public}d, window: %{public}d", interval, window);
1007         return OHOS_BT_STATUS_PARM_INVALID;
1008     }
1009     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1010     GetBleCentralManagerObject(bleCentralManager);
1011     if (bleCentralManager == nullptr) {
1012         HILOGE("get BleCentralManager fail.");
1013         return OHOS_BT_STATUS_FAIL;
1014     }
1015     int ret = bleCentralManager->SetLpDeviceAdvParam(duration, maxExtAdvEvents, window, interval, advHandle);
1016     if (ret != BT_NO_ERROR) {
1017         HILOGE("fail, advHandle: %{public}d,ret: %{public}d", advHandle, ret);
1018         return OHOS_BT_STATUS_FAIL;
1019     }
1020     return OHOS_BT_STATUS_SUCCESS;
1021 }
1022 
1023 /**
1024  * @brief Set scan report channel.
1025  *
1026  * @param scannerId Indicates the scanner id.
1027  * @param enable true:report to low power device; false:not report to low power device.
1028  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if set report channel success;
1029  * returns an error code defined in {@link BtStatus} otherwise.
1030  * @since 6
1031  */
SetScanReportChannelToLpDevice(int32_t scannerId,bool enable)1032 int SetScanReportChannelToLpDevice(int32_t scannerId, bool enable)
1033 {
1034     HILOGD("SetScanReportChannelToLpDevice enter. scannerId: %{public}d, isToAp: %{public}d", scannerId, enable);
1035     std::shared_ptr<BleCentralManager> bleCentralManager = g_bleCentralManagerMap.GetObject(scannerId);
1036     if (bleCentralManager == nullptr) {
1037         HILOGE("SetScanReportChannelToLpDevice fail, ble centra manager is null.");
1038         return OHOS_BT_STATUS_FAIL;
1039     }
1040     int ret = bleCentralManager->SetScanReportChannelToLpDevice(enable);
1041     if (ret != BT_NO_ERROR) {
1042         HILOGE("fail, scannerId: %{public}d, ret: %{public}d", scannerId, ret);
1043         return OHOS_BT_STATUS_FAIL;
1044     }
1045     return OHOS_BT_STATUS_SUCCESS;
1046 }
1047 
1048 /**
1049  * @brief Enable synchronizing data to low power device.
1050  *
1051  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if enable sync success;
1052  * returns an error code defined in {@link BtStatus} otherwise.
1053  * @since 6
1054  */
EnableSyncDataToLpDevice(void)1055 int EnableSyncDataToLpDevice(void)
1056 {
1057     HILOGI("EnableSyncDataToLpDevice enter");
1058     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1059     GetBleCentralManagerObject(bleCentralManager);
1060     if (bleCentralManager == nullptr) {
1061         HILOGE("get BleCentralManager fail.");
1062         return OHOS_BT_STATUS_FAIL;
1063     }
1064     int ret = bleCentralManager->EnableSyncDataToLpDevice();
1065     if (ret != BT_NO_ERROR) {
1066         HILOGE("fail, ret: %{public}d", ret);
1067         return OHOS_BT_STATUS_FAIL;
1068     }
1069     return OHOS_BT_STATUS_SUCCESS;
1070 }
1071 
1072 /**
1073  * @brief Disable synchronizing data to the low power device.
1074  *
1075  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if disable sync success;
1076  * returns an error code defined in {@link BtStatus} otherwise.
1077  * @since 6
1078  */
DisableSyncDataToLpDevice(void)1079 int DisableSyncDataToLpDevice(void)
1080 {
1081     HILOGD("DisableSyncDataToLpDevice enter");
1082     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1083     GetBleCentralManagerObject(bleCentralManager);
1084     if (bleCentralManager == nullptr) {
1085         HILOGE("get BleCentralManager fail.");
1086         return OHOS_BT_STATUS_FAIL;
1087     }
1088     int ret = bleCentralManager->DisableSyncDataToLpDevice();
1089     if (ret != BT_NO_ERROR) {
1090         HILOGE("fail, ret: %{public}d", ret);
1091         return OHOS_BT_STATUS_FAIL;
1092     }
1093     return OHOS_BT_STATUS_SUCCESS;
1094 }
1095 
1096 /**
1097  * @brief Get advertiser handle.
1098  *
1099  * @param advId Indicates the advertisement ID.
1100  * @param advHandle Indicates the pointer to the advertiser handle.
1101  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if get success;
1102  * returns an error code defined in {@link BtStatus} otherwise.
1103  * @since 6
1104  */
GetAdvHandle(int advId,int * advHandle)1105 int GetAdvHandle(int advId, int *advHandle)
1106 {
1107     HILOGI("GetAdvHandle enter. advId: %{public}d", advId);
1108     if (advHandle == nullptr) {
1109         HILOGE("GetAdvHandle fail, advHandle is nullptr.");
1110         return OHOS_BT_STATUS_PARM_INVALID;
1111     }
1112     if (advId < 0 || advId >= MAX_BLE_ADV_NUM) {
1113         HILOGE("GetAdvHandle fail, advId is invalid.advId: %{public}d.", advId);
1114         return OHOS_BT_STATUS_PARM_INVALID;
1115     }
1116     lock_guard<mutex> lock(g_advMutex);
1117     if (g_BleAdvertiser == nullptr || g_bleAdvCallbacks[advId] == nullptr) {
1118         HILOGE("GetAdvHandle fail, the current adv is not started.");
1119         return OHOS_BT_STATUS_FAIL;
1120     }
1121     *advHandle = g_BleAdvertiser->GetAdvHandle(g_bleAdvCallbacks[advId]);
1122     return OHOS_BT_STATUS_SUCCESS;
1123 }
1124 
1125 /**
1126  * @brief Translate ParamData to low power device.
1127  *
1128  * @param data Indicates the pointer to the data.
1129  * @param dataSize Indicates the data size.
1130  * @param type Indicates the data type.
1131  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if set param to low power device success;
1132  * returns an error code defined in {@link BtStatus} otherwise.
1133  * @since 6
1134  */
SendParamsToLpDevice(const uint8_t * data,uint32_t dataSize,int32_t type)1135 int SendParamsToLpDevice(const uint8_t *data, uint32_t dataSize, int32_t type)
1136 {
1137     HILOGI("SendParamsToLpDevice enter. type: %{public}d, dataSize: %{public}d", type, dataSize);
1138     if (data == nullptr || dataSize <= 0) {
1139         HILOGE("SendParamsToLpDevice fail, data is nullptr or dataSize is wrong.");
1140         return OHOS_BT_STATUS_PARM_INVALID;
1141     }
1142     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1143     GetBleCentralManagerObject(bleCentralManager);
1144     if (bleCentralManager == nullptr) {
1145         HILOGE("get BleCentralManager fail.");
1146         return OHOS_BT_STATUS_FAIL;
1147     }
1148     std::vector<uint8_t> dataValue(data, data + dataSize);
1149     int ret = bleCentralManager->SendParamsToLpDevice(std::move(dataValue), type);
1150     if (ret != BT_NO_ERROR) {
1151         HILOGE("fail, ret: %{public}d", ret);
1152         return OHOS_BT_STATUS_FAIL;
1153     }
1154     return OHOS_BT_STATUS_SUCCESS;
1155 }
1156 
1157 /**
1158  * @brief Get whether low power device available.
1159  *
1160  * @return true: available; false: not available.
1161  * @since 6
1162  */
IsLpDeviceAvailable(void)1163 bool IsLpDeviceAvailable(void)
1164 {
1165     HILOGI("IsLpDeviceAvailable enter.");
1166     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1167     GetBleCentralManagerObject(bleCentralManager);
1168     if (bleCentralManager == nullptr) {
1169         HILOGE("get BleCentralManager fail.");
1170         return false;
1171     }
1172 
1173     return bleCentralManager->IsLpDeviceAvailable();
1174 }
1175 
BleScanNativeFilterLog(BleScanNativeFilter & filter)1176 void BleScanNativeFilterLog(BleScanNativeFilter &filter)
1177 {
1178     if (filter.address != nullptr) {
1179         std::string address(filter.address);
1180         HILOGI("address: %{public}s", GetEncryptAddr(filter.address).c_str());
1181     }
1182     if (filter.deviceName != nullptr) {
1183         HILOGI("deviceName: %{public}s", filter.deviceName);
1184     }
1185     if (filter.serviceUuidLength != 0) {
1186         if (filter.serviceUuid != nullptr) {
1187             HILOGI("serviceUuid: %{public}s", reinterpret_cast<char *>(filter.serviceUuid));
1188         }
1189         if (filter.serviceUuidMask != nullptr) {
1190             HILOGI("serviceUuidMask: %{public}s", reinterpret_cast<char *>(filter.serviceUuidMask));
1191         }
1192     }
1193     std::string dataStr;
1194     if (filter.serviceDataLength != 0) {
1195         if (filter.serviceData != nullptr) {
1196             dataStr = "";
1197             ConvertDataToHex(filter.serviceData, filter.serviceDataLength, dataStr);
1198             HILOGI("serviceData: %{public}s", dataStr.c_str());
1199         }
1200         if (filter.serviceDataMask != nullptr) {
1201             dataStr = "";
1202             ConvertDataToHex(filter.serviceDataMask, filter.serviceDataLength, dataStr);
1203             HILOGI("serviceDataMask: %{public}s", dataStr.c_str());
1204         }
1205     }
1206     if (filter.manufactureDataLength != 0) {
1207         if (filter.manufactureData != nullptr) {
1208             dataStr = "";
1209             ConvertDataToHex(filter.manufactureData, filter.manufactureDataLength, dataStr);
1210             HILOGI("manufactureData: %{public}s", dataStr.c_str());
1211         }
1212         if (filter.manufactureDataMask != nullptr) {
1213             dataStr = "";
1214             ConvertDataToHex(filter.manufactureDataMask, filter.manufactureDataLength, dataStr);
1215             HILOGI("manufactureDataMask: %{public}s", dataStr.c_str());
1216         }
1217         HILOGI("manufactureId: %{public}d", filter.manufactureId);
1218     }
1219 }
1220 
ConvertScanFilterParam(const BtLpDeviceParam * param,std::vector<BleScanFilter> & filter)1221 bool ConvertScanFilterParam(const BtLpDeviceParam *param, std::vector<BleScanFilter> &filter)
1222 {
1223     unsigned int maxFilterSize = 10;  // max filter size
1224     if (param->filterSize > maxFilterSize) {
1225         HILOGE("filterSize(%{public}u) is larger than %{public}u", param->filterSize, maxFilterSize);
1226         return false;
1227     }
1228     for (unsigned int i = 0; i < param->filterSize; i++) {
1229         BleScanNativeFilter nativeScanFilter = param->filter[i];
1230         BleScanNativeFilterLog(nativeScanFilter);
1231         BleScanFilter scanFilter;
1232         int result = SetOneScanFilter(scanFilter, &nativeScanFilter);
1233         if (result != OHOS_BT_STATUS_SUCCESS) {
1234             HILOGE("SetOneScanFilter faild, result: %{public}d", result);
1235             return false;
1236         }
1237         filter.push_back(scanFilter);
1238     }
1239     return true;
1240 }
1241 
ConvertAdvSettingParam(const BtLpDeviceParam * param,BleAdvertiserSettings & advSettings)1242 void ConvertAdvSettingParam(const BtLpDeviceParam *param, BleAdvertiserSettings &advSettings)
1243 {
1244     HILOGI("BleAdvParams: minInterval: %{public}d, advType: %{public}d",
1245         param->advParam.minInterval, param->advParam.advType);
1246     advSettings.SetInterval(param->advParam.minInterval);
1247     if (param->advParam.advType == OHOS_BLE_ADV_SCAN_IND ||
1248         param->advParam.advType == OHOS_BLE_ADV_NONCONN_IND) {
1249         advSettings.SetConnectable(false);
1250     }
1251 }
1252 
ConvertAdvDeviceInfo(const BtLpDeviceParam * param,std::vector<BleActiveDeviceInfo> & activeDeviceInfos)1253 bool ConvertAdvDeviceInfo(const BtLpDeviceParam *param, std::vector<BleActiveDeviceInfo> &activeDeviceInfos)
1254 {
1255     if (param->activeDeviceInfo == nullptr || param->activeDeviceSize == 0) {
1256         return true;
1257     }
1258     unsigned int maxActiveDevice = 10;  // max active device
1259     if (param->activeDeviceSize > maxActiveDevice) {
1260         HILOGE("activeDeviceSize(%{public}u) is larger than %{public}u", param->activeDeviceSize, maxActiveDevice);
1261         return false;
1262     }
1263     for (unsigned int i = 0; i < param->activeDeviceSize; i++) {
1264         HILOGI("ActiveDeviceInfo: status: %{public}d, timeOut: %{public}d",
1265             param->activeDeviceInfo[i].status, param->activeDeviceInfo[i].timeOut);
1266         BleActiveDeviceInfo deviceInfo;
1267         std::vector<int8_t> value(param->activeDeviceInfo[i].deviceId,
1268             param->activeDeviceInfo[i].deviceId + OHOS_ACTIVE_DEVICE_ID_LEN);
1269         deviceInfo.deviceId = value;
1270         deviceInfo.status = param->activeDeviceInfo[i].status;
1271         deviceInfo.timeOut = param->activeDeviceInfo[i].timeOut;
1272         activeDeviceInfos.push_back(deviceInfo);
1273     }
1274     return true;
1275 }
1276 
ConvertBtUuid(const BtUuid & inUuid,UUID & outUuid)1277 bool ConvertBtUuid(const BtUuid &inUuid, UUID &outUuid)
1278 {
1279     if (inUuid.uuid == nullptr || inUuid.uuidLen == 0) {
1280         HILOGE("uuid is NULL or len is 0.");
1281         return false;
1282     }
1283     string strUuid(inUuid.uuid);
1284     HILOGD("UUID: %{public}s", strUuid.c_str());
1285     if (!IsValidUuid(strUuid)) {
1286         HILOGE("match the UUID faild.");
1287         return false;
1288     }
1289     outUuid = UUID::FromString(strUuid);
1290     return true;
1291 }
1292 
ConvertLpDeviceParamData(const BtLpDeviceParam * inParam,BleLpDeviceParamSet & outParam)1293 int ConvertLpDeviceParamData(const BtLpDeviceParam *inParam, BleLpDeviceParamSet &outParam)
1294 {
1295     outParam.fieldValidFlagBit = 0;
1296     if (!ConvertBtUuid(inParam->uuid, outParam.uuid)) {
1297         return OHOS_BT_STATUS_PARM_INVALID;
1298     }
1299 
1300     if (inParam->scanConfig != nullptr) {
1301         outParam.scanSettings.SetScanMode(inParam->scanConfig->scanMode);
1302         outParam.fieldValidFlagBit |= BLE_LPDEVICE_SCAN_SETTING_VALID_BIT;
1303     }
1304 
1305     if (inParam->filter != nullptr && inParam->filterSize > 0) {
1306         if (!ConvertScanFilterParam(inParam, outParam.scanFilters)) {
1307             return OHOS_BT_STATUS_PARM_INVALID;
1308         }
1309         outParam.fieldValidFlagBit |= BLE_LPDEVICE_SCAN_FILTER_VALID_BIT;
1310     }
1311 
1312     outParam.fieldValidFlagBit |= BLE_LPDEVICE_ADV_SETTING_VALID_BIT;
1313     ConvertAdvSettingParam(inParam, outParam.advSettings);
1314 
1315     if (inParam->rawData.advData != nullptr && inParam->rawData.advDataLen > 0) {
1316         outParam.advData = ConvertDataToVec(inParam->rawData.advData,
1317             inParam->rawData.advDataLen);
1318         outParam.fieldValidFlagBit |= BLE_LPDEVICE_ADVDATA_VALID_BIT;
1319     }
1320 
1321     if (inParam->rawData.rspData != nullptr && inParam->rawData.rspDataLen > 0) {
1322         outParam.respData = ConvertDataToVec(inParam->rawData.rspData,
1323             inParam->rawData.rspDataLen);
1324         outParam.fieldValidFlagBit |= BLE_LPDEVICE_RESPDATA_VALID_BIT;
1325     }
1326 
1327     if (inParam->activeDeviceInfo != nullptr && inParam->activeDeviceSize > 0) {
1328         if (!ConvertAdvDeviceInfo(inParam, outParam.activeDeviceInfos)) {
1329             return OHOS_BT_STATUS_PARM_INVALID;
1330         }
1331         outParam.fieldValidFlagBit |= BLE_LPDEVICE_ADV_DEVICEINFO_VALID_BIT;
1332     }
1333 
1334     outParam.advHandle = inParam->advHandle;
1335     outParam.duration = inParam->duration;
1336     outParam.deliveryMode = inParam->deliveryMode;
1337     return OHOS_BT_STATUS_SUCCESS;
1338 }
1339 
1340 /**
1341  * @brief Set low power device Param.
1342  *
1343  * @param lpDeviceParam the param set to low power device.
1344  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if set lpDeviceParam success;
1345  * returns an error code defined in {@link BtStatus} otherwise.
1346  * @since 6
1347  */
SetLpDeviceParam(const BtLpDeviceParam * lpDeviceParam)1348 int SetLpDeviceParam(const BtLpDeviceParam *lpDeviceParam)
1349 {
1350     HILOGI("SetLpDeviceParam enter.");
1351     if (lpDeviceParam == nullptr) {
1352         HILOGE("SetLpDeviceParam fail, lpDeviceParam is null.");
1353         return OHOS_BT_STATUS_PARM_INVALID;
1354     }
1355     BleLpDeviceParamSet paramSet;
1356     int ret = ConvertLpDeviceParamData(lpDeviceParam, paramSet);
1357     if (ret != OHOS_BT_STATUS_SUCCESS) {
1358         return ret;
1359     }
1360     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1361     GetBleCentralManagerObject(bleCentralManager);
1362     if (bleCentralManager == nullptr) {
1363         HILOGE("get BleCentralManager fail.");
1364         return OHOS_BT_STATUS_FAIL;
1365     }
1366 
1367     HILOGI("SetLpDeviceParam fieldValidFlagBit: %{public}u", paramSet.fieldValidFlagBit);
1368     ret = bleCentralManager->SetLpDeviceParam(paramSet);
1369     if (ret != BT_NO_ERROR) {
1370         HILOGE("fail, advHandle: %{public}d, ret: %{public}d", paramSet.advHandle, ret);
1371         return OHOS_BT_STATUS_FAIL;
1372     }
1373     return OHOS_BT_STATUS_SUCCESS;
1374 }
1375 
1376 /**
1377  * @brief Remove low power device Param.
1378  *
1379  * @param uuid Uuid.
1380  * @return Returns {@link OHOS_BT_STATUS_SUCCESS} if remove success;
1381  * returns an error code defined in {@link BtStatus} otherwise.
1382  * @since 6
1383  */
RemoveLpDeviceParam(BtUuid uuid)1384 int RemoveLpDeviceParam(BtUuid uuid)
1385 {
1386     HILOGI("RemoveLpDeviceParam enter.");
1387     std::shared_ptr<BleCentralManager> bleCentralManager = nullptr;
1388     GetBleCentralManagerObject(bleCentralManager);
1389     if (bleCentralManager == nullptr) {
1390         HILOGE("get BleCentralManager fail.");
1391         return OHOS_BT_STATUS_FAIL;
1392     }
1393     UUID srvUuid;
1394     if (!ConvertBtUuid(uuid, srvUuid)) {
1395         return OHOS_BT_STATUS_PARM_INVALID;
1396     }
1397     int ret = bleCentralManager->RemoveLpDeviceParam(srvUuid);
1398     if (ret != BT_NO_ERROR) {
1399         HILOGE("fail, ret: %{public}d", ret);
1400         return OHOS_BT_STATUS_FAIL;
1401     }
1402     return OHOS_BT_STATUS_SUCCESS;
1403 }
1404 
ClearGlobalResource(void)1405 void ClearGlobalResource(void)
1406 {
1407     int i = 0;
1408     lock_guard<mutex> lock(g_advMutex);
1409     for (i = 0; i < MAX_BLE_ADV_NUM; i++) {
1410         if (g_bleAdvCallbacks[i] != nullptr) {
1411             g_bleAdvCallbacks[i] = nullptr;
1412         }
1413     }
1414     HILOGD("clear all g_bleAdvCallbacks when ble turn on or bluetooth_serivce unload");
1415 }
1416 
StartAdvAddrTimer(int advHandle,const AdvOwnAddrParams * ownAddrParams)1417 bool StartAdvAddrTimer(int advHandle, const AdvOwnAddrParams *ownAddrParams)
1418 {
1419     RemoveTimeoutAdvAddr();
1420     string addrStr;
1421     ConvertAddr(ownAddrParams->addr, addrStr);
1422     if (!CanStartAdv(addrStr)) {
1423         g_bleAdvCallbacks[advHandle] = nullptr;
1424         return false;
1425     }
1426     // adv must stop after {@link ADV_ADDR_TIME_THRESHOLD}
1427     auto timerCallback = [advHandle]() {
1428         HILOGI("Stop adv : %{public}d.", advHandle);
1429         BleStopAdv(advHandle);
1430     };
1431     uint32_t timerId = 0;
1432     BluetoothTimer::GetInstance()->Register(timerCallback, timerId, ADV_ADDR_TIME_THRESHOLD);
1433     {
1434         lock_guard<mutex> lock(g_advTimerMutex);
1435         g_advAddrTimerIds[advHandle] = timerId;
1436     }
1437     return true;
1438 }
1439 
AllocateAdvHandle(void)1440 int AllocateAdvHandle(void)
1441 {
1442     int i = 0;
1443     for (; i < MAX_BLE_ADV_NUM; i++) {
1444         if (g_bleAdvCallbacks[i] == nullptr) {
1445             g_bleAdvCallbacks[i] = make_shared<BleAdvCallback>(i);
1446             break;
1447         }
1448     }
1449     return i;
1450 }
1451 
1452 }  // namespace Bluetooth
1453 }  // namespace OHOS
1454 #ifdef __cplusplus
1455 }
1456 #endif
1457 /** @} */
1458