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