• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "bluetooth_host.h"
17 #include <memory>
18 #include <mutex>
19 #include <unistd.h>
20 #include "bluetooth_ble_peripheral_observer_stub.h"
21 #include "bluetooth_host_load_callback.h"
22 #include "bluetooth_host_observer_stub.h"
23 #include "bluetooth_host_proxy.h"
24 #include "bluetooth_load_system_ability.h"
25 #include "bluetooth_log.h"
26 #include "bluetooth_utils.h"
27 #include "bluetooth_observer_list.h"
28 #include "bluetooth_remote_device_observer_stub.h"
29 #include "iservice_registry.h"
30 #include "system_ability_definition.h"
31 #include "bluetooth_errorcode.h"
32 
33 namespace OHOS {
34 namespace Bluetooth {
35 namespace {
36 constexpr int32_t LOAD_SA_TIMEOUT_MS = 5000;
37 }
38 
39 struct BluetoothHost::impl {
40     impl();
41     ~impl();
42 
43     bool LoadBluetoothHostService();
44     void LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject);
45     void LoadSystemAbilityFail();
46     bool InitBluetoothHostProxy(void);
47 
48     // host observer
49     class BluetoothHostObserverImp;
50     sptr<BluetoothHostObserverImp> observerImp_ = nullptr;
51     sptr<BluetoothHostObserverImp> bleObserverImp_ = nullptr;
52 
53     // remote device observer
54     class BluetoothRemoteDeviceObserverImp;
55     sptr<BluetoothRemoteDeviceObserverImp> remoteObserverImp_ = nullptr;
56 
57     // remote device observer
58     class BluetoothBlePeripheralCallbackImp;
59     sptr<BluetoothBlePeripheralCallbackImp> bleRemoteObserverImp_ = nullptr;
60 
61     // user regist observers
62     BluetoothObserverList<BluetoothHostObserver> observers_;
63 
64     // user regist remote observers
65     BluetoothObserverList<BluetoothRemoteDeviceObserver> remoteObservers_;
66 
67     sptr<IBluetoothHost> proxy_ = nullptr;
68 
69     bool InitBluetoothHostObserver(void);
70 
71     void SyncRandomAddrToService(void);
72 
73     std::mutex proxyMutex_;
74     std::string stagingRealAddr_;
75     std::string stagingRandomAddr_;
76 private:
77     class BluetoothHostDeathRecipient;
78     sptr<BluetoothHostDeathRecipient> deathRecipient_ = nullptr;
79     std::condition_variable proxyConVar_;
80 };
81 
82 class BluetoothHost::impl::BluetoothHostObserverImp : public BluetoothHostObserverStub {
83 public:
BluetoothHostObserverImp(BluetoothHost::impl & host)84     explicit BluetoothHostObserverImp(BluetoothHost::impl &host) : host_(host){};
~BluetoothHostObserverImp()85     ~BluetoothHostObserverImp() override{};
86 
Register(std::shared_ptr<BluetoothHostObserver> & observer)87     void Register(std::shared_ptr<BluetoothHostObserver> &observer)
88     {
89         host_.observers_.Register(observer);
90     }
91 
Deregister(std::shared_ptr<BluetoothHostObserver> & observer)92     void Deregister(std::shared_ptr<BluetoothHostObserver> &observer)
93     {
94         host_.observers_.Deregister(observer);
95     }
96 
OnStateChanged(int32_t transport,int32_t status)97     void OnStateChanged(int32_t transport, int32_t status) override
98     {
99         HILOGD("bluetooth state, transport: %{public}s, status: %{public}s",
100             GetBtTransportName(transport).c_str(), GetBtStateName(status).c_str());
101         if (status == BTStateID::STATE_TURN_ON) {
102             host_.SyncRandomAddrToService();
103         }
104         host_.observers_.ForEach([transport, status](std::shared_ptr<BluetoothHostObserver> observer) {
105             observer->OnStateChanged(transport, status);
106         });
107     }
108 
OnDiscoveryStateChanged(int32_t status)109     void OnDiscoveryStateChanged(int32_t status) override
110     {
111         HILOGI("enter, status: %{public}d", status);
112         host_.observers_.ForEach(
113             [status](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnDiscoveryStateChanged(status); });
114     }
115 
OnDiscoveryResult(const BluetoothRawAddress & device)116     void OnDiscoveryResult(const BluetoothRawAddress &device) override
117     {
118         HILOGD("enter, device: %{public}s", GetEncryptAddr((device).GetAddress()).c_str());
119         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
120         host_.observers_.ForEach([remoteDevice](std::shared_ptr<BluetoothHostObserver> observer) {
121             observer->OnDiscoveryResult(remoteDevice);
122         });
123     }
124 
OnPairRequested(const int32_t transport,const BluetoothRawAddress & device)125     void OnPairRequested(const int32_t transport, const BluetoothRawAddress &device) override
126     {
127         HILOGI("enter, transport: %{public}d, device: %{public}s",
128             transport, GetEncryptAddr((device).GetAddress()).c_str());
129         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
130         host_.observers_.ForEach([remoteDevice](std::shared_ptr<BluetoothHostObserver> observer) {
131             observer->OnPairRequested(remoteDevice);
132         });
133     }
134 
OnPairConfirmed(const int32_t transport,const BluetoothRawAddress & device,int reqType,int number)135     void OnPairConfirmed(const int32_t transport, const BluetoothRawAddress &device, int reqType, int number) override
136     {
137         HILOGI("enter, transport: %{public}d, device: %{public}s, reqType: %{public}d, number: %{public}d",
138             transport, GetEncryptAddr((device).GetAddress()).c_str(), reqType, number);
139         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
140         host_.observers_.ForEach([remoteDevice, reqType, number](std::shared_ptr<BluetoothHostObserver> observer) {
141             observer->OnPairConfirmed(remoteDevice, reqType, number);
142         });
143     }
144 
OnScanModeChanged(int mode)145     void OnScanModeChanged(int mode) override
146     {
147         HILOGI("enter, mode: %{public}d", mode);
148         host_.observers_.ForEach(
149             [mode](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnScanModeChanged(mode); });
150     }
151 
OnDeviceNameChanged(const std::string & deviceName)152     void OnDeviceNameChanged(const std::string &deviceName) override
153     {
154         HILOGI("enter, deviceName: %{public}s", deviceName.c_str());
155         host_.observers_.ForEach([deviceName](std::shared_ptr<BluetoothHostObserver> observer) {
156             observer->OnDeviceNameChanged(deviceName);
157         });
158     }
159 
OnDeviceAddrChanged(const std::string & address)160     void OnDeviceAddrChanged(const std::string &address) override
161     {
162         HILOGI("enter");
163         host_.observers_.ForEach(
164             [address](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnDeviceAddrChanged(address); });
165     }
166 
167 private:
168     BluetoothHost::impl &host_;
169     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothHostObserverImp);
170 };
171 
172 class BluetoothHost::impl::BluetoothRemoteDeviceObserverImp : public BluetoothRemoteDeviceObserverstub {
173 public:
BluetoothRemoteDeviceObserverImp(BluetoothHost::impl & host)174     explicit BluetoothRemoteDeviceObserverImp(BluetoothHost::impl &host) : host_(host){};
175     ~BluetoothRemoteDeviceObserverImp() override = default;
176 
OnAclStateChanged(const BluetoothRawAddress & device,int32_t state,uint32_t reason)177     void OnAclStateChanged(const BluetoothRawAddress &device, int32_t state, uint32_t reason) override
178     {
179         HILOGD("enter, device: %{public}s, state: %{public}d, reason: %{public}u",
180             GetEncryptAddr((device).GetAddress()).c_str(), state, reason);
181         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
182         host_.remoteObservers_.ForEach(
183             [remoteDevice, state, reason](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
184                 observer->OnAclStateChanged(remoteDevice, state, reason);
185             });
186     }
187 
OnPairStatusChanged(const int32_t transport,const BluetoothRawAddress & device,int32_t status)188     void OnPairStatusChanged(const int32_t transport, const BluetoothRawAddress &device, int32_t status) override
189     {
190         HILOGI("enter, transport: %{public}d, device: %{public}s, status: %{public}d",
191             transport, GetEncryptAddr((device).GetAddress()).c_str(), status);
192         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
193         host_.remoteObservers_.ForEach(
194             [remoteDevice, status](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
195                 observer->OnPairStatusChanged(remoteDevice, status);
196             });
197     }
198 
OnRemoteUuidChanged(const BluetoothRawAddress & device,const std::vector<bluetooth::Uuid> uuids)199     void OnRemoteUuidChanged(const BluetoothRawAddress &device, const std::vector<bluetooth::Uuid> uuids) override
200     {
201         HILOGI("enter, device: %{public}s", GetEncryptAddr((device).GetAddress()).c_str());
202         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
203         host_.remoteObservers_.ForEach(
204             [remoteDevice, uuids](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
205                 std::vector<ParcelUuid> parcelUuids;
206                 for (auto &uuid : uuids) {
207                     ParcelUuid parcelUuid = UUID::ConvertFrom128Bits(uuid.ConvertTo128Bits());
208                     parcelUuids.push_back(parcelUuid);
209                 }
210                 observer->OnRemoteUuidChanged(remoteDevice, parcelUuids);
211             });
212     }
213 
OnRemoteNameChanged(const BluetoothRawAddress & device,const std::string deviceName)214     void OnRemoteNameChanged(const BluetoothRawAddress &device, const std::string deviceName) override
215     {
216         HILOGI("enter, device: %{public}s, deviceName: %{public}s",
217             GetEncryptAddr((device).GetAddress()).c_str(), deviceName.c_str());
218         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
219         host_.remoteObservers_.ForEach(
220             [remoteDevice, deviceName](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
221                 observer->OnRemoteNameChanged(remoteDevice, deviceName);
222             });
223     }
224 
OnRemoteAliasChanged(const BluetoothRawAddress & device,const std::string alias)225     void OnRemoteAliasChanged(const BluetoothRawAddress &device, const std::string alias) override
226     {
227         HILOGI("enter, device: %{public}s, alias: %{public}s",
228             GetEncryptAddr((device).GetAddress()).c_str(), alias.c_str());
229         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
230         host_.remoteObservers_.ForEach(
231             [remoteDevice, alias](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
232                 observer->OnRemoteAliasChanged(remoteDevice, alias);
233             });
234     }
235 
OnRemoteCodChanged(const BluetoothRawAddress & device,int32_t cod)236     void OnRemoteCodChanged(const BluetoothRawAddress &device, int32_t cod) override
237     {
238         HILOGI("enter, device: %{public}s, cod: %{public}d", GetEncryptAddr((device).GetAddress()).c_str(), cod);
239         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
240         BluetoothDeviceClass deviceClass(cod);
241         host_.remoteObservers_.ForEach(
242             [remoteDevice, deviceClass](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
243                 observer->OnRemoteCodChanged(remoteDevice, deviceClass);
244             });
245     }
246 
OnRemoteBatteryLevelChanged(const BluetoothRawAddress & device,int32_t batteryLevel)247     void OnRemoteBatteryLevelChanged(const BluetoothRawAddress &device, int32_t batteryLevel) override
248     {
249         HILOGI("enter, device: %{public}s, batteryLevel: %{public}d",
250             GetEncryptAddr((device).GetAddress()).c_str(), batteryLevel);
251         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
252         host_.remoteObservers_.ForEach(
253             [remoteDevice, batteryLevel](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
254                 observer->OnRemoteBatteryLevelChanged(remoteDevice, batteryLevel);
255             });
256     }
257 
258 private:
259     BluetoothHost::impl &host_;
260     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothRemoteDeviceObserverImp);
261 };
262 
263 class BluetoothHost::impl::BluetoothBlePeripheralCallbackImp : public BluetoothBlePeripheralObserverStub {
264 public:
BluetoothBlePeripheralCallbackImp(BluetoothHost::impl & host)265     explicit BluetoothBlePeripheralCallbackImp(BluetoothHost::impl &host) : host_(host){};
266     ~BluetoothBlePeripheralCallbackImp() override = default;
267 
OnAclStateChanged(const BluetoothRawAddress & device,int state,unsigned int reason)268     void OnAclStateChanged(const BluetoothRawAddress &device, int state, unsigned int reason) override
269     {
270         HILOGD("enter, device: %{public}s, state: %{public}d, reason: %{public}u",
271             GetEncryptAddr((device).GetAddress()).c_str(), state, reason);
272         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BLE);
273         host_.remoteObservers_.ForEach(
274             [remoteDevice, state, reason](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
275                 observer->OnAclStateChanged(remoteDevice, state, reason);
276             });
277     }
278 
OnPairStatusChanged(const int32_t transport,const BluetoothRawAddress & device,int status)279     void OnPairStatusChanged(const int32_t transport, const BluetoothRawAddress &device, int status) override
280     {
281         HILOGI("enter, transport: %{public}d, device: %{public}s, status: %{public}d",
282             transport, GetEncryptAddr((device).GetAddress()).c_str(), status);
283         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
284         host_.remoteObservers_.ForEach(
285             [remoteDevice, status](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
286                 observer->OnPairStatusChanged(remoteDevice, status);
287             });
288     }
289 
OnReadRemoteRssiEvent(const BluetoothRawAddress & device,int rssi,int status)290     void OnReadRemoteRssiEvent(const BluetoothRawAddress &device, int rssi, int status) override
291     {
292         HILOGI("enter, device: %{public}s, rssi: %{public}d, status: %{public}d",
293             GetEncryptAddr((device).GetAddress()).c_str(), rssi, status);
294         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BLE);
295         host_.remoteObservers_.ForEach(
296             [remoteDevice, rssi, status](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
297                 observer->OnReadRemoteRssiEvent(remoteDevice, rssi, status);
298             });
299     }
300 
301 private:
302     BluetoothHost::impl &host_;
303     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothBlePeripheralCallbackImp);
304 };
305 
306 class BluetoothHost::impl::BluetoothHostDeathRecipient final : public IRemoteObject::DeathRecipient {
307 public:
BluetoothHostDeathRecipient(BluetoothHost::impl & impl)308     explicit BluetoothHostDeathRecipient(BluetoothHost::impl &impl) : impl_(impl)
309     {};
310     ~BluetoothHostDeathRecipient() final = default;
311     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothHostDeathRecipient);
312 
OnRemoteDied(const wptr<IRemoteObject> & remote)313     void OnRemoteDied(const wptr<IRemoteObject> &remote) final
314     {
315         HILOGI("bluetooth_servi died and then re-registered");
316         std::lock_guard<std::mutex> lock(impl_.proxyMutex_);
317         impl_.proxy_ = nullptr;
318 
319         // Notify the upper layer that bluetooth is disabled.
320         if (impl_.observerImp_ != nullptr && impl_.bleObserverImp_ != nullptr) {
321             HILOGI("bluetooth_servi died and send state off to app");
322             impl_.observerImp_->OnStateChanged(BTTransport::ADAPTER_BLE, BTStateID::STATE_TURN_OFF);
323             impl_.bleObserverImp_->OnStateChanged(BTTransport::ADAPTER_BREDR, BTStateID::STATE_TURN_OFF);
324         }
325     }
326 
327 private:
ResetHostProxy()328     bool ResetHostProxy()
329     {
330         HILOGI("proxy is null, try to get proxy.");
331         return true;
332     }
333     BluetoothHost::impl &impl_;
334 };
335 
impl()336 BluetoothHost::impl::impl()
337 {
338     BluetootLoadSystemAbility::GetInstance().RegisterNotifyMsg(PROFILE_ID_HOST);
339     if (!BluetootLoadSystemAbility::GetInstance().HasSubscribedBluetoothSystemAbility()) {
340         BluetootLoadSystemAbility::GetInstance().SubScribeBluetoothSystemAbility();
341         return;
342     }
343     InitBluetoothHostProxy();
344 }
345 
~impl()346 BluetoothHost::impl::~impl()
347 {
348     HILOGI("starts");
349     if (proxy_ == nullptr) {
350         HILOGE("proxy_ is null");
351         return;
352     }
353     proxy_->DeregisterObserver(observerImp_);
354     proxy_->DeregisterBleAdapterObserver(bleObserverImp_);
355     proxy_->DeregisterRemoteDeviceObserver(remoteObserverImp_);
356     proxy_->DeregisterBlePeripheralCallback(bleRemoteObserverImp_);
357     proxy_->AsObject()->RemoveDeathRecipient(deathRecipient_);
358 }
359 
InitBluetoothHostProxy(void)360 bool BluetoothHost::impl::InitBluetoothHostProxy(void)
361 {
362     std::lock_guard<std::mutex> lock(proxyMutex_);
363     if (proxy_) {
364         return true;
365     }
366     HILOGE("enter");
367     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
368     if (samgrProxy == nullptr) {
369         HILOGE("samgrProxy is nullptr.");
370         return false;
371     }
372     auto object = samgrProxy->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
373     if (object == nullptr) {
374         HILOGE("object is nullptr.");
375         return false;
376     }
377     proxy_ = iface_cast<IBluetoothHost>(object);
378     if (!InitBluetoothHostObserver()) {
379         return false;
380     }
381     return true;
382 }
383 
InitBluetoothHostObserver(void)384 bool BluetoothHost::impl::InitBluetoothHostObserver(void)
385 {
386     HILOGI("enter");
387     deathRecipient_ = new BluetoothHostDeathRecipient(*this);
388     if (deathRecipient_ == nullptr) {
389         HILOGE("deathRecipient_ is null");
390         return false;
391     }
392     observerImp_ = new (std::nothrow) BluetoothHostObserverImp(*this);
393     if (observerImp_ == nullptr) {
394         HILOGE("observerImp_ is null");
395         return false;
396     }
397     remoteObserverImp_ = new (std::nothrow) BluetoothRemoteDeviceObserverImp(*this);
398     if (remoteObserverImp_ == nullptr) {
399         HILOGE("remoteObserverImp_ is null");
400         return false;
401     }
402     bleRemoteObserverImp_ = new (std::nothrow) BluetoothBlePeripheralCallbackImp(*this);
403     if (bleRemoteObserverImp_ == nullptr) {
404         HILOGE("bleRemoteObserverImp_ is null");
405         return false;
406     }
407     bleObserverImp_ = new (std::nothrow) BluetoothHostObserverImp(*this);
408     if (bleObserverImp_ == nullptr) {
409         HILOGE("bleObserverImp_ is null");
410         return false;
411     }
412     if (proxy_ == nullptr) {
413         HILOGE("proxy_ is null");
414         return false;
415     }
416     proxy_->AsObject()->AddDeathRecipient(deathRecipient_);
417     proxy_->RegisterObserver(observerImp_);
418     proxy_->RegisterBleAdapterObserver(bleObserverImp_);
419     proxy_->RegisterRemoteDeviceObserver(remoteObserverImp_);
420     proxy_->RegisterBlePeripheralCallback(bleRemoteObserverImp_);
421     return true;
422 }
423 
LoadBluetoothHostService()424 bool BluetoothHost::impl::LoadBluetoothHostService()
425 {
426     std::unique_lock<std::mutex> lock(proxyMutex_);
427     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
428     if (samgrProxy == nullptr) {
429         HILOGE("samgrProxy is nullptr.");
430         return false;
431     }
432     auto object = samgrProxy->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
433     if (object != nullptr) {
434         proxy_ = iface_cast<IBluetoothHost>(object);
435         if (!InitBluetoothHostObserver()) {
436             HILOGE("InitBluetoothHostObserver fail");
437             return false;
438         }
439         return true;
440     }
441 
442     sptr<BluetoothHostLoadCallBack> loadCallback = new BluetoothHostLoadCallBack();
443     if (loadCallback == nullptr) {
444         HILOGE("loadCallback is nullptr.");
445         return false;
446     }
447     int32_t ret = samgrProxy->LoadSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, loadCallback);
448     if (ret != ERR_OK) {
449         HILOGE("Failed to load bluetooth systemAbility");
450         return false;
451     }
452 
453     auto waitStatus = proxyConVar_.wait_for(
454         lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), [this]() { return proxy_ != nullptr; });
455     if (!waitStatus) {
456         HILOGE("load bluetooth systemAbility timeout");
457         return false;
458     }
459     return true;
460 }
461 
LoadSystemAbilitySuccess(const sptr<IRemoteObject> & remoteObject)462 void BluetoothHost::impl::LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)
463 {
464     HILOGI("LoadSystemAbilitySuccess FinishStart SA");
465     std::lock_guard<std::mutex> lock(proxyMutex_);
466     if (remoteObject != nullptr) {
467         proxy_ = iface_cast<IBluetoothHost>(remoteObject);
468     } else {
469         HILOGE("LoadSystemAbilitySuccess remoteObject is NULL.");
470     }
471     proxyConVar_.notify_one();
472 }
473 
LoadSystemAbilityFail()474 void BluetoothHost::impl::LoadSystemAbilityFail()
475 {
476     HILOGI("LoadSystemAbilityFail FinishStart SA");
477     std::lock_guard<std::mutex> lock(proxyMutex_);
478     proxy_ = nullptr;
479     proxyConVar_.notify_one();
480 }
481 
SyncRandomAddrToService(void)482 void BluetoothHost::impl::SyncRandomAddrToService(void)
483 {
484     HILOGI("SyncRandomAddrToService.");
485     if (!IsValidBluetoothAddr(stagingRealAddr_)) {
486         HILOGE("stagingRealAddr_ is invalid.");
487         return;
488     }
489     if (!IsValidBluetoothAddr(stagingRandomAddr_)) {
490         HILOGE("stagingRandomAddr_ is invalid.");
491         return;
492     }
493     if (proxy_ == nullptr) {
494         HILOGE("proxy_ is nullptr.");
495         return;
496     }
497     proxy_->SyncRandomAddress(stagingRealAddr_, stagingRandomAddr_);
498     stagingRealAddr_ = "";
499     stagingRandomAddr_ = "";
500 }
501 
BluetoothHost()502 BluetoothHost::BluetoothHost()
503 {
504     pimpl = std::make_unique<impl>();
505     if (!pimpl) {
506         HILOGE("fails: no pimpl");
507     }
508 }
509 
~BluetoothHost()510 BluetoothHost::~BluetoothHost() {}
511 
GetDefaultHost()512 BluetoothHost &BluetoothHost::GetDefaultHost()
513 {
514     // C++11 static local variable initialization is thread-safe.
515     static BluetoothHost hostAdapter;
516     return hostAdapter;
517 }
518 
RegisterObserver(BluetoothHostObserver & observer)519 void BluetoothHost::RegisterObserver(BluetoothHostObserver &observer)
520 {
521     if (!pimpl) {
522         HILOGE("fails: no pimpl");
523         return;
524     }
525 
526     std::shared_ptr<BluetoothHostObserver> pointer(&observer, [](BluetoothHostObserver *) {});
527     pimpl->observers_.Register(pointer);
528 }
529 
DeregisterObserver(BluetoothHostObserver & observer)530 void BluetoothHost::DeregisterObserver(BluetoothHostObserver &observer)
531 {
532     if (!pimpl) {
533         HILOGE("fails: no pimpl");
534         return;
535     }
536 
537     std::shared_ptr<BluetoothHostObserver> pointer(&observer, [](BluetoothHostObserver *) {});
538     pimpl->observers_.Deregister(pointer);
539 }
540 
Init()541 void BluetoothHost::Init()
542 {
543     if (!pimpl) {
544         HILOGE("fails: no pimpl");
545         return;
546     }
547     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
548     if (samgrProxy == nullptr) {
549         HILOGE("samgrProxy is nullptr.");
550         return;
551     }
552     auto object = samgrProxy->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
553     if (object == nullptr) {
554         HILOGE("object is nullptr.");
555         return;
556     }
557     std::lock_guard<std::mutex> lock(pimpl->proxyMutex_);
558     pimpl->proxy_ = iface_cast<IBluetoothHost>(object);
559     pimpl->InitBluetoothHostObserver();
560 }
561 
EnableBt()562 int BluetoothHost::EnableBt()
563 {
564     HILOGI("enter");
565     if (!pimpl || !pimpl->proxy_) {
566         HILOGE("pimpl or bluetooth host is nullptr");
567         return BT_ERR_INTERNAL_ERROR;
568     }
569 
570     return pimpl->proxy_->EnableBt();
571 }
572 
DisableBt()573 int BluetoothHost::DisableBt()
574 {
575     HILOGI("enter");
576     if (!pimpl || !pimpl->proxy_) {
577         HILOGE("pimpl or bluetooth host is nullptr");
578         return BT_ERR_INTERNAL_ERROR;
579     }
580 
581     return pimpl->proxy_->DisableBt();
582 }
583 
GetBtState() const584 int BluetoothHost::GetBtState() const
585 {
586     HILOGI("enter");
587     if (!IS_BT_ENABLED()) {
588         HILOGE("bluetooth is off.");
589         return BTStateID::STATE_TURN_OFF;
590     }
591 
592     if (!pimpl || !pimpl->proxy_) {
593         HILOGE("pimpl or bluetooth host is nullptr");
594         return BTStateID::STATE_TURN_OFF;
595     }
596 
597     int state = BTStateID::STATE_TURN_OFF;
598     pimpl->proxy_->GetBtState(state);
599     HILOGI("state: %{public}d", state);
600     return state;
601 }
602 
GetBtState(int & state) const603 int BluetoothHost::GetBtState(int &state) const
604 {
605     HILOGI("enter");
606     state = BTStateID::STATE_TURN_OFF;
607     if (!IS_BT_ENABLED()) {
608         HILOGE("bluetooth is off.");
609         return BT_NO_ERROR;
610     }
611 
612     if (!pimpl || !pimpl->proxy_) {
613         HILOGE("pimpl or bluetooth host is nullptr");
614         return BT_ERR_INVALID_STATE;
615     }
616 
617     int ret = pimpl->proxy_->GetBtState(state);
618     HILOGI("state: %{public}d", state);
619     return ret;
620 }
621 
BluetoothFactoryReset()622 bool BluetoothHost::BluetoothFactoryReset()
623 {
624     HILOGI("enter");
625     if (!IS_BT_ENABLED()) {
626         HILOGE("bluetooth is off.");
627         return false;
628     }
629 
630     if (!pimpl || !pimpl->proxy_) {
631         HILOGE("pimpl or bluetooth host is nullptr");
632         return false;
633     }
634 
635     return pimpl->proxy_->BluetoothFactoryReset();
636 }
637 
IsValidBluetoothAddr(const std::string & addr)638 bool BluetoothHost::IsValidBluetoothAddr(const std::string &addr)
639 {
640     if (addr.empty() || addr.length() != ADDRESS_LENGTH) {
641         return false;
642     }
643     for (int i = 0; i < ADDRESS_LENGTH; i++) {
644         char c = addr[i];
645         switch (i % ADDRESS_SEPARATOR_UNIT) {
646             case 0:
647             case 1:
648                 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
649                     break;
650                 }
651                 return false;
652             case ADDRESS_COLON_INDEX:
653             default:
654                 if (c == ':') {
655                     break;
656                 }
657                 return false;
658         }
659     }
660     return true;
661 }
662 
GetRemoteDevice(const std::string & addr,int transport) const663 BluetoothRemoteDevice BluetoothHost::GetRemoteDevice(const std::string &addr, int transport) const
664 {
665     BluetoothRemoteDevice remoteDevice(addr, transport);
666     return remoteDevice;
667 }
668 
EnableBle()669 int BluetoothHost::EnableBle()
670 {
671     HILOGI("enter");
672     if (!pimpl || !pimpl->LoadBluetoothHostService()) {
673         HILOGE("pimpl or bluetooth host is nullptr");
674         return BT_ERR_INTERNAL_ERROR;
675     }
676     return pimpl->proxy_->EnableBle();
677 }
678 
DisableBle()679 int BluetoothHost::DisableBle()
680 {
681     HILOGI("enter");
682     if (!pimpl || !pimpl->proxy_) {
683         HILOGE("pimpl or bluetooth host is nullptr");
684         return BT_ERR_INTERNAL_ERROR;
685     }
686     return pimpl->proxy_->DisableBle();
687 }
688 
IsBrEnabled() const689 bool BluetoothHost::IsBrEnabled() const
690 {
691     if (!pimpl || !pimpl->proxy_) {
692         HILOGE("pimpl or bluetooth host is nullptr");
693         return false;
694     }
695 
696     return pimpl->proxy_->IsBrEnabled();
697 }
698 
IsBleEnabled() const699 bool BluetoothHost::IsBleEnabled() const
700 {
701     if (!pimpl || !pimpl->proxy_) {
702         HILOGE("pimpl or bluetooth host is nullptr");
703         return false;
704     }
705 
706     return pimpl->proxy_->IsBleEnabled();
707 }
708 
GetLocalAddress() const709 std::string BluetoothHost::GetLocalAddress() const
710 {
711     HILOGI("enter");
712     if (!pimpl || !pimpl->proxy_) {
713         HILOGE("pimpl or bluetooth host is nullptr");
714         return std::string();
715     }
716 
717     return pimpl->proxy_->GetLocalAddress();
718 }
719 
GetProfileList() const720 std::vector<uint32_t> BluetoothHost::GetProfileList() const
721 {
722     HILOGI("enter");
723     std::vector<uint32_t> profileList;
724     if (!pimpl || !pimpl->proxy_) {
725         HILOGE("pimpl or bluetooth host is nullptr");
726         return profileList;
727     }
728 
729     profileList = pimpl->proxy_->GetProfileList();
730     return profileList;
731 }
732 
GetMaxNumConnectedAudioDevices() const733 int BluetoothHost::GetMaxNumConnectedAudioDevices() const
734 {
735     HILOGI("enter");
736     if (!pimpl || !pimpl->proxy_) {
737         HILOGE("pimpl or bluetooth host is nullptr");
738         return INVALID_VALUE;
739     }
740 
741     return pimpl->proxy_->GetMaxNumConnectedAudioDevices();
742 }
743 
GetBtConnectionState() const744 int BluetoothHost::GetBtConnectionState() const
745 {
746     HILOGI("enter");
747     int state = static_cast<int>(BTConnectState::DISCONNECTED);
748     if (!IS_BT_ENABLED()) {
749         HILOGE("bluetooth is off.");
750         return state;
751     }
752 
753     if (!pimpl || !pimpl->proxy_) {
754         HILOGE("pimpl or bluetooth host is nullptr");
755         return state;
756     }
757 
758     pimpl->proxy_->GetBtConnectionState(state);
759     HILOGI("state: %{public}d", state);
760     return state;
761 }
762 
GetBtConnectionState(int & state) const763 int BluetoothHost::GetBtConnectionState(int &state) const
764 {
765     HILOGI("enter");
766     state = static_cast<int>(BTConnectState::DISCONNECTED);
767     if (!IS_BT_ENABLED()) {
768         HILOGE("bluetooth is off.");
769         return BT_ERR_INVALID_STATE;
770     }
771 
772     if (!pimpl || !pimpl->proxy_) {
773         HILOGE("pimpl or bluetooth host is nullptr");
774         return BT_ERR_UNAVAILABLE_PROXY;
775     }
776 
777     int ret = pimpl->proxy_->GetBtConnectionState(state);
778     HILOGI("state: %{public}d", state);
779     return ret;
780 }
781 
GetBtProfileConnState(uint32_t profileId,int & state) const782 int BluetoothHost::GetBtProfileConnState(uint32_t profileId, int &state) const
783 {
784     HILOGI("enter, profileId: %{public}d", profileId);
785     state = static_cast<int>(BTConnectState::DISCONNECTED);
786     if (!IS_BT_ENABLED()) {
787         HILOGE("bluetooth is off.");
788         return BT_ERR_INVALID_STATE;
789     }
790 
791     if (!pimpl || !pimpl->proxy_) {
792         HILOGE("pimpl or bluetooth host is nullptr");
793         return BT_ERR_UNAVAILABLE_PROXY;
794     }
795 
796     return pimpl->proxy_->GetBtProfileConnState(profileId, state);
797 }
798 
GetLocalSupportedUuids(std::vector<ParcelUuid> & uuids)799 void BluetoothHost::GetLocalSupportedUuids(std::vector<ParcelUuid> &uuids)
800 {
801     HILOGI("enter");
802     if (!pimpl || !pimpl->proxy_) {
803         HILOGE("pimpl or bluetooth host is nullptr");
804         return;
805     }
806 
807     std::vector<std::string> stringUuids;
808     pimpl->proxy_->GetLocalSupportedUuids(stringUuids);
809     for (auto uuid : stringUuids) {
810         uuids.push_back(UUID::FromString(uuid));
811     }
812 }
813 
Start()814 bool BluetoothHost::Start()
815 {
816     // / This function only used for passthrough, so this is empty.
817     return true;
818 }
819 
Stop()820 void BluetoothHost::Stop()
821 {
822     // / This function only used for passthrough, so this is empty.
823 }
824 
GetLocalDeviceClass() const825 BluetoothDeviceClass BluetoothHost::GetLocalDeviceClass() const
826 {
827     HILOGI("enter");
828     if (!pimpl || !pimpl->proxy_) {
829         HILOGE("pimpl or bluetooth host is nullptr");
830         return BluetoothDeviceClass(0);
831     }
832 
833     int LocalDeviceClass = pimpl->proxy_->GetLocalDeviceClass();
834     return BluetoothDeviceClass(LocalDeviceClass);
835 }
836 
SetLocalDeviceClass(const BluetoothDeviceClass & deviceClass)837 bool BluetoothHost::SetLocalDeviceClass(const BluetoothDeviceClass &deviceClass)
838 {
839     HILOGI("enter");
840     if (!pimpl || !pimpl->proxy_) {
841         HILOGE("pimpl or bluetooth host is nullptr");
842         return false;
843     }
844 
845     int cod = deviceClass.GetClassOfDevice();
846     return pimpl->proxy_->SetLocalDeviceClass(cod);
847 }
848 
GetLocalName() const849 std::string BluetoothHost::GetLocalName() const
850 {
851     HILOGI("enter");
852     if (!pimpl || !pimpl->proxy_) {
853         HILOGE("pimpl or bluetooth host is nullptr");
854         return std::string();
855     }
856 
857     std::string name = INVALID_NAME;
858     pimpl->proxy_->GetLocalName(name);
859     return name;
860 }
861 
GetLocalName(std::string & name) const862 int BluetoothHost::GetLocalName(std::string &name) const
863 {
864     HILOGI("enter");
865     if (!pimpl || !pimpl->proxy_) {
866         HILOGE("pimpl or bluetooth host is nullptr");
867         return BT_ERR_UNAVAILABLE_PROXY;
868     }
869 
870     return pimpl->proxy_->GetLocalName(name);
871 }
872 
SetLocalName(const std::string & name)873 int BluetoothHost::SetLocalName(const std::string &name)
874 {
875     HILOGI("enter");
876     if (!IS_BT_ENABLED()) {
877         HILOGE("bluetooth is off.");
878         return BT_ERR_INVALID_STATE;
879     }
880     if (!pimpl || !pimpl->proxy_) {
881         HILOGE("pimpl or bluetooth host is nullptr");
882         return BT_ERR_UNAVAILABLE_PROXY;
883     }
884 
885     return pimpl->proxy_->SetLocalName(name);
886 }
887 
GetBtScanMode(int32_t & scanMode) const888 int BluetoothHost::GetBtScanMode(int32_t &scanMode) const
889 {
890     HILOGI("enter");
891     if (!IS_BT_ENABLED()) {
892         HILOGE("bluetooth is off.");
893         return BT_ERR_INVALID_STATE;
894     }
895 
896     if (!pimpl || !pimpl->proxy_) {
897         HILOGE("pimpl or bluetooth host is nullptr");
898         return BT_ERR_UNAVAILABLE_PROXY;
899     }
900 
901     return pimpl->proxy_->GetBtScanMode(scanMode);
902 }
903 
SetBtScanMode(int mode,int duration)904 int BluetoothHost::SetBtScanMode(int mode, int duration)
905 {
906     HILOGI("enter, mode: %{public}d, duration: %{public}d", mode, duration);
907     if (!IS_BT_ENABLED()) {
908         HILOGE("bluetooth is off.");
909         return BT_ERR_INVALID_STATE;
910     }
911 
912     if (!pimpl || !pimpl->proxy_) {
913         HILOGE("pimpl or bluetooth host is nullptr");
914         return BT_ERR_UNAVAILABLE_PROXY;
915     }
916 
917     return pimpl->proxy_->SetBtScanMode(mode, duration);
918 }
919 
GetBondableMode(int transport) const920 int BluetoothHost::GetBondableMode(int transport) const
921 {
922     HILOGI("enter, transport: %{public}d", transport);
923     if (!pimpl || !pimpl->proxy_) {
924         HILOGE("pimpl or bluetooth host is nullptr");
925         return INVALID_VALUE;
926     }
927 
928     return pimpl->proxy_->GetBondableMode(transport);
929 }
930 
SetBondableMode(int transport,int mode)931 bool BluetoothHost::SetBondableMode(int transport, int mode)
932 {
933     HILOGI("enter, transport: %{public}d, mode: %{public}d", transport, mode);
934     if (!pimpl || !pimpl->proxy_) {
935         HILOGE("pimpl or bluetooth host is nullptr");
936         return false;
937     }
938 
939     return pimpl->proxy_->SetBondableMode(transport, mode);
940 }
941 
StartBtDiscovery()942 int BluetoothHost::StartBtDiscovery()
943 {
944     HILOGI("enter");
945     if (!IS_BT_ENABLED()) {
946         HILOGE("bluetooth is off.");
947         return BT_ERR_INVALID_STATE;
948     }
949 
950     if (!pimpl || !pimpl->proxy_) {
951         HILOGE("pimpl or bluetooth host is nullptr");
952         return BT_ERR_UNAVAILABLE_PROXY;
953     }
954 
955     return pimpl->proxy_->StartBtDiscovery();
956 }
957 
CancelBtDiscovery()958 int BluetoothHost::CancelBtDiscovery()
959 {
960     HILOGI("enter");
961     if (!IS_BT_ENABLED()) {
962         HILOGE("bluetooth is off.");
963         return BT_ERR_INVALID_STATE;
964     }
965 
966     if (!pimpl || !pimpl->proxy_) {
967         HILOGE("pimpl or bluetooth host is nullptr");
968         return BT_ERR_UNAVAILABLE_PROXY;
969     }
970 
971     return pimpl->proxy_->CancelBtDiscovery();
972 }
973 
IsBtDiscovering(int transport) const974 bool BluetoothHost::IsBtDiscovering(int transport) const
975 {
976     HILOGI("enter, transport: %{public}d", transport);
977     if (!IS_BT_ENABLED()) {
978         HILOGE("bluetooth is off.");
979         return false;
980     }
981 
982     if (!pimpl || !pimpl->proxy_) {
983         HILOGE("pimpl or bluetooth host is nullptr");
984         return false;
985     }
986 
987     return pimpl->proxy_->IsBtDiscovering(transport);
988 }
989 
GetBtDiscoveryEndMillis() const990 long BluetoothHost::GetBtDiscoveryEndMillis() const
991 {
992     HILOGI("enter");
993     if (!IS_BT_ENABLED()) {
994         HILOGE("bluetooth is off.");
995         return 0;
996     }
997 
998     if (!pimpl || !pimpl->proxy_) {
999         HILOGE("pimpl or bluetooth host is nullptr");
1000         return 0;
1001     }
1002 
1003     return pimpl->proxy_->GetBtDiscoveryEndMillis();
1004 }
1005 
GetPairedDevices(int transport,std::vector<BluetoothRemoteDevice> & pairedDevices) const1006 int32_t BluetoothHost::GetPairedDevices(int transport, std::vector<BluetoothRemoteDevice> &pairedDevices) const
1007 {
1008     HILOGI("enter, transport: %{public}d", transport);
1009     if (!IS_BT_ENABLED()) {
1010         HILOGE("bluetooth is off.");
1011         return BT_ERR_INVALID_STATE;
1012     }
1013     if (!pimpl || !pimpl->proxy_) {
1014         HILOGE("pimpl or bluetooth host is nullptr");
1015         return BT_ERR_UNAVAILABLE_PROXY;
1016     }
1017 
1018     std::vector<BluetoothRawAddress> pairedAddr;
1019     int32_t ret = pimpl->proxy_->GetPairedDevices(transport, pairedAddr);
1020 
1021     for (auto it = pairedAddr.begin(); it != pairedAddr.end(); it++) {
1022         BluetoothRemoteDevice device((*it).GetAddress(), transport);
1023         pairedDevices.emplace_back(device);
1024     }
1025     return ret;
1026 }
1027 
RemovePair(const BluetoothRemoteDevice & device)1028 int32_t BluetoothHost::RemovePair(const BluetoothRemoteDevice &device)
1029 {
1030     HILOGI("enter, device: %{public}s", GET_ENCRYPT_ADDR(device));
1031     if (!device.IsValidBluetoothRemoteDevice()) {
1032         HILOGE("Invalid remote device.");
1033         return BT_ERR_INTERNAL_ERROR;
1034     }
1035 
1036     if (!pimpl || !pimpl->proxy_) {
1037         HILOGE("pimpl or bluetooth host is nullptr");
1038         return BT_ERR_UNAVAILABLE_PROXY;
1039     }
1040 
1041     sptr<BluetoothRawAddress> rawAddrSptr = new BluetoothRawAddress(device.GetDeviceAddr());
1042     return pimpl->proxy_->RemovePair(device.GetTransportType(), rawAddrSptr);
1043 }
1044 
RemoveAllPairs()1045 bool BluetoothHost::RemoveAllPairs()
1046 {
1047     HILOGI("enter");
1048     if (!pimpl || !pimpl->proxy_) {
1049         HILOGE("pimpl or bluetooth host is nullptr");
1050         return false;
1051     }
1052 
1053     return pimpl->proxy_->RemoveAllPairs();
1054 }
1055 
RegisterRemoteDeviceObserver(std::shared_ptr<BluetoothRemoteDeviceObserver> observer)1056 void BluetoothHost::RegisterRemoteDeviceObserver(std::shared_ptr<BluetoothRemoteDeviceObserver> observer)
1057 {
1058     if (!pimpl) {
1059         HILOGE("fails: no pimpl");
1060         return;
1061     }
1062     pimpl->remoteObservers_.Register(observer);
1063 }
1064 
DeregisterRemoteDeviceObserver(BluetoothRemoteDeviceObserver & observer)1065 void BluetoothHost::DeregisterRemoteDeviceObserver(BluetoothRemoteDeviceObserver &observer)
1066 {
1067     if (!pimpl) {
1068         HILOGE("fails: no pimpl");
1069         return;
1070     }
1071     std::shared_ptr<BluetoothRemoteDeviceObserver> pointer(&observer, [](BluetoothRemoteDeviceObserver *) {});
1072     pimpl->remoteObservers_.Deregister(pointer);
1073 }
1074 
GetBleMaxAdvertisingDataLength() const1075 int BluetoothHost::GetBleMaxAdvertisingDataLength() const
1076 {
1077     if (!pimpl || !pimpl->proxy_) {
1078         HILOGE("pimpl or bluetooth host is nullptr");
1079         return INVALID_VALUE;
1080     }
1081 
1082     return pimpl->proxy_->GetBleMaxAdvertisingDataLength();
1083 }
1084 
LoadSystemAbilitySuccess(const sptr<IRemoteObject> & remoteObject)1085 void BluetoothHost::LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)
1086 {
1087     if (!pimpl) {
1088         HILOGE("fails: no pimpl");
1089         return;
1090     }
1091     pimpl->LoadSystemAbilitySuccess(remoteObject);
1092 }
1093 
LoadSystemAbilityFail()1094 void BluetoothHost::LoadSystemAbilityFail()
1095 {
1096     if (!pimpl) {
1097         HILOGE("fails: no pimpl");
1098         return;
1099     }
1100     pimpl->LoadSystemAbilityFail();
1101 }
1102 
GetLocalProfileUuids(std::vector<std::string> & uuids)1103 int32_t BluetoothHost::GetLocalProfileUuids(std::vector<std::string> &uuids)
1104 {
1105     if (!IS_BT_ENABLED()) {
1106         HILOGE("bluetooth is off.");
1107         return BT_ERR_INTERNAL_ERROR;
1108     }
1109     if (!pimpl || !pimpl->proxy_) {
1110         HILOGE("pimpl or bluetooth host is nullptr");
1111         return BT_ERR_UNAVAILABLE_PROXY;
1112     }
1113     return pimpl->proxy_->GetLocalProfileUuids(uuids);
1114 }
1115 
SetFastScan(bool isEnable)1116 int BluetoothHost::SetFastScan(bool isEnable)
1117 {
1118     HILOGI("enter, isEnable: %{public}d", isEnable);
1119     if (!IS_BT_ENABLED()) {
1120         HILOGE("bluetooth is off.");
1121         return BT_ERR_INVALID_STATE;
1122     }
1123 
1124     if (!pimpl || !pimpl->proxy_) {
1125         HILOGE("pimpl or bluetooth host is nullptr");
1126         return BT_ERR_UNAVAILABLE_PROXY;
1127     }
1128     return pimpl->proxy_->SetFastScan(isEnable);
1129 }
1130 
GetRandomAddress(const std::string & realAddr,std::string & randomAddr) const1131 int BluetoothHost::GetRandomAddress(const std::string &realAddr, std::string &randomAddr) const
1132 {
1133     HILOGI("enter.");
1134     randomAddr = realAddr;
1135     return BT_NO_ERROR;
1136 }
1137 } // namespace Bluetooth
1138 } // namespace OHOS
1139