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