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