• 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 "adapter_manager.h"
17 
18 #include <array>
19 #include <functional>
20 
21 #include "btm.h"
22 #include "btstack.h"
23 #include "log.h"
24 
25 #include "adapter_config.h"
26 #include "adapter_device_config.h"
27 #include "adapter_device_info.h"
28 #include "adapter_state_machine.h"
29 #include "base_def.h"
30 #include "base_observer_list.h"
31 #include "class_creator.h"
32 #include "permission_utils.h"
33 #include "power_manager.h"
34 #include "profile_config.h"
35 #include "profile_service_manager.h"
36 #include "sys_state_machine.h"
37 
38 namespace OHOS {
39 namespace bluetooth {
40 // data define
41 const int TRANSPORT_MAX = 2;
42 
43 struct AdapterInfo {
AdapterInfoOHOS::bluetooth::AdapterInfo44     AdapterInfo(std::unique_ptr<IAdapter> instance, std::unique_ptr<AdapterStateMachine> stateMachine)
45         : instance_(std::move(instance)), stateMachine_(std::move(stateMachine))
46     {}
~AdapterInfoOHOS::bluetooth::AdapterInfo47     ~AdapterInfo()
48     {}
49 
50     BTStateID state_ = BTStateID::STATE_TURN_OFF;
51     std::unique_ptr<IAdapter> instance_ = nullptr;
52     std::unique_ptr<AdapterStateMachine> stateMachine_ = nullptr;
53 };
54 
55 // static function
GetInstance()56 IAdapterManager *IAdapterManager::GetInstance()
57 {
58     return AdapterManager::GetInstance();
59 }
GetInstance()60 AdapterManager *AdapterManager::GetInstance()
61 {
62     static AdapterManager instance;
63     return &instance;
64 }
65 
66 // impl class
67 struct AdapterManager::impl {
68     impl();
69     ~impl();
70 
71     std::recursive_mutex syncMutex_ = {};
72     std::promise<void> stopPromise_ = {};
73     std::promise<void> resetPromise_ = {};
74     std::unique_ptr<utility::Dispatcher> dispatcher_ = nullptr;
75     std::array<std::unique_ptr<AdapterInfo>, TRANSPORT_MAX> adapters_ = {};
76     SysStateMachine sysStateMachine_ = {};
77     std::string sysState_ = SYS_STATE_STOPPED;
78     BtmCallbacks hciFailureCallbacks = {};
79     BaseObserverList<IAdapterStateObserver> adapterObservers_ = {};
80     BaseObserverList<ISystemStateObserver> systemObservers_ = {};
81 
82     class AdaptersContextCallback;
83     std::unique_ptr<AdaptersContextCallback> contextCallback_ = nullptr;
84 
85     void OnEnable(const std::string &name, bool ret);
86     void OnDisable(const std::string &name, bool ret);
87     void ProcessMessage(const BTTransport transport, const utility::Message &msg);
88 
89     BT_DISALLOW_COPY_AND_ASSIGN(impl);
90 };
91 
92 class AdapterManager::impl::AdaptersContextCallback : public utility::IContextCallback {
93 public:
AdaptersContextCallback(AdapterManager::impl & impl)94     explicit AdaptersContextCallback(AdapterManager::impl &impl) : impl_(impl){};
95     ~AdaptersContextCallback() = default;
96 
OnEnable(const std::string & name,bool ret)97     void OnEnable(const std::string &name, bool ret)
98     {
99         LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
100         impl_.OnEnable(name, ret);
101     }
OnDisable(const std::string & name,bool ret)102     void OnDisable(const std::string &name, bool ret)
103     {
104         LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
105         impl_.OnDisable(name, ret);
106     }
107 
108 private:
109     AdapterManager::impl &impl_;
110 };
111 
impl()112 AdapterManager::impl::impl()
113 {
114     dispatcher_ = std::make_unique<utility::Dispatcher>("AdapterManager");
115     dispatcher_->Initialize();
116 
117     // context callback create
118     contextCallback_ = std::make_unique<AdaptersContextCallback>(*this);
119 }
120 
~impl()121 AdapterManager::impl::~impl()
122 {
123     if (dispatcher_ != nullptr) {
124         dispatcher_->Uninitialize();
125     }
126 }
127 
OnEnable(const std::string & name,bool ret)128 void AdapterManager::impl::OnEnable(const std::string &name, bool ret)
129 {
130     LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
131     BTTransport transport = BTTransport::ADAPTER_BREDR;
132 
133     if (name.c_str() == ADAPTER_NAME_CLASSIC) {
134         transport = BTTransport::ADAPTER_BREDR;
135     } else if (name.c_str() == ADAPTER_NAME_BLE) {
136         transport = BTTransport::ADAPTER_BLE;
137     } else {
138         LOG_ERROR("%{public}s, name=%{public}s is warning transport\n", __PRETTY_FUNCTION__, name.c_str());
139     }
140 
141     utility::Message msg(AdapterStateMachine::MSG_ADAPTER_ENABLE_CMP, ret ? true : false);
142     dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, this, transport, msg));
143 }
144 
OnDisable(const std::string & name,bool ret)145 void AdapterManager::impl::OnDisable(const std::string &name, bool ret)
146 {
147     LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
148     BTTransport transport = BTTransport::ADAPTER_BREDR;
149 
150     if (name.c_str() == ADAPTER_NAME_CLASSIC) {
151         transport = BTTransport::ADAPTER_BREDR;
152     } else if (name.c_str() == ADAPTER_NAME_BLE) {
153         transport = BTTransport::ADAPTER_BLE;
154     } else {
155         LOG_ERROR("%{public}s, name=%{public}s is warning transport\n", __PRETTY_FUNCTION__, name.c_str());
156     }
157 
158     utility::Message msg(AdapterStateMachine::MSG_ADAPTER_DISABLE_CMP, ret ? true : false);
159     dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, this, transport, msg));
160 }
161 
ProcessMessage(const BTTransport transport,const utility::Message & msg)162 void AdapterManager::impl::ProcessMessage(const BTTransport transport, const utility::Message &msg)
163 {
164     std::lock_guard<std::recursive_mutex> lock(syncMutex_);
165 
166     if (adapters_[transport] == nullptr) {
167         LOG_DEBUG("%{public}s adapter is nullptr", __PRETTY_FUNCTION__);
168         return;
169     }
170 
171     if (adapters_[transport]->stateMachine_ == nullptr) {
172         LOG_DEBUG("%{public}s stateMachine_ is nullptr", __PRETTY_FUNCTION__);
173         return;
174     }
175 
176     adapters_[transport]->stateMachine_->ProcessMessage(msg);
177 }
178 
179 // AdapterManager class
AdapterManager()180 AdapterManager::AdapterManager() : pimpl(std::make_unique<AdapterManager::impl>())
181 {
182     // sys state Machine create
183     pimpl->sysStateMachine_.Init(*this);
184 }
185 
~AdapterManager()186 AdapterManager::~AdapterManager()
187 {}
188 
Start()189 bool AdapterManager::Start()
190 {
191     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
192 
193     if (GetSysState() == SYS_STATE_STARTED) {
194         LOG_ERROR("Bluetooth has been started!!");
195         return false;
196     }
197 
198     if (!AdapterConfig::GetInstance()->Load()) {
199         LOG_ERROR("Load Config File Failed!!");
200         return false;
201     }
202 
203     if (!ProfileConfig::GetInstance()->Load()) {
204         LOG_ERROR("Load Profile Config File Failed!!");
205         return false;
206     }
207 
208     if (BTM_Initialize() != BT_NO_ERROR) {
209         LOG_ERROR("Bluetooth Stack Initialize Failed!!");
210         return false;
211     }
212 
213     if (!OutputSetting()) {
214         LOG_ERROR("Bluetooth output set Failed!!");
215         return false;
216     }
217 
218     CreateAdapters();
219 
220     ProfileServiceManager::Initialize(*pimpl->dispatcher_);
221 
222     IPowerManager::Initialize(*pimpl->dispatcher_);
223 
224     RegisterHciResetCallback();
225 
226     OnSysStateChange(SYS_STATE_STARTED);
227 
228     utility::Message msg(SysStateMachine::MSG_SYS_START_CMP);
229     pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
230 
231     return true;
232 }
233 
OutputSetting() const234 bool AdapterManager::OutputSetting() const
235 {
236     bool outputValue = false;
237     bool desensitization = false;
238 
239     AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_DESENSITIZATION, desensitization);
240     if (AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_BTSNOOP_OUTPUT, outputValue) &&
241         outputValue) {
242         std::string outputPath = "./snoop.log";
243         AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_BTSNOOP_OUTPUT_PATH, outputPath);
244 
245         if (BTM_SetSnoopFilePath(outputPath.c_str(), outputPath.length()) != BT_NO_ERROR) {
246             LOG_ERROR("Set snoop file path Failed!!");
247             return false;
248         }
249 
250         if (BTM_EnableSnoopFileOutput(desensitization) != BT_NO_ERROR) {
251             LOG_ERROR("Enable snoop file output Failed!!");
252             return false;
253         }
254     } else {
255         if (BTM_DisableSnoopFileOutput() != BT_NO_ERROR) {
256             LOG_ERROR("Disable snoop file output Failed!!");
257             return false;
258         }
259     }
260 
261     outputValue = false;
262     if (AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_HCILOG_OUTPUT, outputValue) &&
263         outputValue) {
264         if (BTM_EnableHciLogOutput(desensitization) != BT_NO_ERROR) {
265             LOG_ERROR("Enable HciLog output Failed!!");
266             return false;
267         }
268     } else {
269         if (BTM_DisableHciLogOutput() != BT_NO_ERROR) {
270             LOG_ERROR("Disable HciLog output Failed!!");
271             return false;
272         }
273     }
274 
275     return true;
276 }
277 
Stop() const278 void AdapterManager::Stop() const
279 {
280     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
281 
282     if (GetSysState() == SYS_STATE_STOPPED) {
283         LOG_DEBUG("AdapterManager is stoped");
284     } else if (GetSysState() == SYS_STATE_STOPPING) {
285         LOG_DEBUG("AdapterManager is stoping...");
286     } else {
287         std::promise<void> stopPromise;
288         std::future<void> stopFuture = stopPromise.get_future();
289 
290         {
291             std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
292             pimpl->stopPromise_ = std::move(stopPromise);
293         }
294 
295         utility::Message msg(SysStateMachine::MSG_SYS_STOP_REQ);
296         pimpl->dispatcher_->PostTask(
297             std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
298         stopFuture.wait();
299     }
300 }
301 
AdapterStop() const302 bool AdapterManager::AdapterStop() const
303 {
304     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
305     ProfileServiceManager::Uninitialize();
306     IPowerManager::Uninitialize();
307 
308     DeregisterHciResetCallback();
309 
310     for (int i = 0; i < TRANSPORT_MAX; i++) {
311         if (pimpl->adapters_[i]) {
312             pimpl->adapters_[i]->instance_->GetContext()->Uninitialize();
313             pimpl->adapters_[i] = nullptr;
314         }
315     }
316 
317     BTM_Close();
318 
319     utility::Message msg(SysStateMachine::MSG_SYS_STOP_CMP);
320     pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
321 
322     return true;
323 }
324 
Enable(const BTTransport transport) const325 bool AdapterManager::Enable(const BTTransport transport) const
326 {
327     LOG_DEBUG("%{public}s start transport is %{public}d", __PRETTY_FUNCTION__, transport);
328     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
329 
330     if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
331         LOG_ERROR("Enable() false, check permission failed");
332         return false;
333     }
334 
335     if (GetSysState() != SYS_STATE_STARTED) {
336         LOG_ERROR("AdapterManager system is stoped");
337         return false;
338     }
339 
340     if (pimpl->adapters_[transport] == nullptr) {
341         LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
342         return false;
343     }
344 
345     if (GetState(transport) == BTStateID::STATE_TURN_OFF) {
346         utility::Message msg(AdapterStateMachine::MSG_USER_ENABLE_REQ);
347         pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
348         return true;
349     } else if (GetState(transport) == BTStateID::STATE_TURN_ON) {
350         LOG_INFO("%{public}s is turn on", __PRETTY_FUNCTION__);
351         return false;
352     } else {
353         LOG_INFO("%{public}s is turning state %{public}d", __PRETTY_FUNCTION__, GetState(transport));
354         return false;
355     }
356 }
357 
Disable(const BTTransport transport) const358 bool AdapterManager::Disable(const BTTransport transport) const
359 {
360     LOG_DEBUG("%{public}s start transport is %{public}d", __PRETTY_FUNCTION__, transport);
361     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
362 
363     if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
364         LOG_ERROR("Disable() false, check permission failed");
365         return false;
366     }
367 
368     if (pimpl->adapters_[transport] == nullptr) {
369         LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
370         return false;
371     }
372 
373     if (GetState(transport) == BTStateID::STATE_TURN_ON) {
374         utility::Message msg(AdapterStateMachine::MSG_USER_DISABLE_REQ);
375         pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
376         return true;
377     } else if (GetState(transport) == BTStateID::STATE_TURN_OFF) {
378         LOG_INFO("%{public}s is turn off", __PRETTY_FUNCTION__);
379         return false;
380     } else {
381         LOG_INFO("%{public}s is turning state %{public}d", __PRETTY_FUNCTION__, GetState(transport));
382         return false;
383     }
384 }
385 
FactoryReset() const386 bool AdapterManager::FactoryReset() const
387 {
388     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
389 
390     if (GetSysState() == SYS_STATE_STARTED) {
391         std::promise<void> resetPromise;
392         std::future<void> resetFuture = resetPromise.get_future();
393 
394         {
395             std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
396             pimpl->resetPromise_ = std::move(resetPromise);
397         }
398 
399         utility::Message msg(SysStateMachine::MSG_SYS_FACTORY_RESET_REQ);
400         pimpl->dispatcher_->PostTask(
401             std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
402         resetFuture.wait();
403         return true;
404     } else {
405         LOG_INFO("System state is not started");
406         return false;
407     }
408 }
409 
HciFailedReset(void * context)410 void AdapterManager::HciFailedReset(void *context)
411 {
412     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
413     (static_cast<AdapterManager *>(context))->Reset();
414 }
415 
RegisterHciResetCallback()416 void AdapterManager::RegisterHciResetCallback()
417 {
418     pimpl->hciFailureCallbacks.hciFailure = HciFailedReset;
419     BTM_RegisterCallbacks(&(pimpl->hciFailureCallbacks), this);
420 }
421 
DeregisterHciResetCallback() const422 void AdapterManager::DeregisterHciResetCallback() const
423 {
424     if (pimpl->hciFailureCallbacks.hciFailure != nullptr) {
425         BTM_DeregisterCallbacks(&(pimpl->hciFailureCallbacks));
426         pimpl->hciFailureCallbacks.hciFailure = nullptr;
427     }
428 }
429 
Reset() const430 void AdapterManager::Reset() const
431 {
432     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
433 
434     utility::Message msg(SysStateMachine::MSG_SYS_RESET_REQ);
435     pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
436 }
437 
ClearAllStorage() const438 bool AdapterManager::ClearAllStorage() const
439 {
440     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
441 
442     if (!AdapterConfig::GetInstance()->Reload()) {
443         return false;
444     }
445     if (!ProfileConfig::GetInstance()->Reload()) {
446         return false;
447     }
448     if (!AdapterDeviceConfig::GetInstance()->Reload()) {
449         return false;
450     }
451     if (!AdapterDeviceInfo::GetInstance()->Reload()) {
452         return false;
453     }
454 
455     utility::Message msg(SysStateMachine::MSG_SYS_CLEAR_ALL_STORAGE_CMP);
456     pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
457     return true;
458 }
459 
GetState(const BTTransport transport) const460 BTStateID AdapterManager::GetState(const BTTransport transport) const
461 {
462     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
463 
464     if (pimpl->adapters_[transport] == nullptr) {
465         LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
466         return BTStateID::STATE_TURN_OFF;
467     }
468 
469     return pimpl->adapters_[transport]->state_;
470 }
471 
RegisterStateObserver(IAdapterStateObserver & observer) const472 bool AdapterManager::RegisterStateObserver(IAdapterStateObserver &observer) const
473 {
474     return pimpl->adapterObservers_.Register(observer);
475 }
476 
DeregisterStateObserver(IAdapterStateObserver & observer) const477 bool AdapterManager::DeregisterStateObserver(IAdapterStateObserver &observer) const
478 {
479     return pimpl->adapterObservers_.Deregister(observer);
480 }
481 
RegisterSystemStateObserver(ISystemStateObserver & observer) const482 bool AdapterManager::RegisterSystemStateObserver(ISystemStateObserver &observer) const
483 {
484     return pimpl->systemObservers_.Register(observer);
485 }
486 
DeregisterSystemStateObserver(ISystemStateObserver & observer) const487 bool AdapterManager::DeregisterSystemStateObserver(ISystemStateObserver &observer) const
488 {
489     return pimpl->systemObservers_.Deregister(observer);
490 }
491 
GetAdapterConnectState() const492 BTConnectState AdapterManager::GetAdapterConnectState() const
493 {
494     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
495     return ProfileServiceManager::GetInstance()->GetProfileServicesConnectState();
496 }
497 
GetAdapter(const BTTransport transport) const498 IAdapter *AdapterManager::GetAdapter(const BTTransport transport) const
499 {
500     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
501 
502     if (pimpl->adapters_[transport] != nullptr) {
503         return pimpl->adapters_[transport]->instance_.get();
504     } else {
505         return nullptr;
506     }
507 }
508 
OnSysStateChange(const std::string & state) const509 void AdapterManager::OnSysStateChange(const std::string &state) const
510 {
511     LOG_DEBUG("%{public}s state is %{public}s", __PRETTY_FUNCTION__, state.c_str());
512 
513     std::string oldSysState;
514     std::string newSysState = state;
515 
516     {  // lock start,update systerm state
517         std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
518         oldSysState = pimpl->sysState_;
519         pimpl->sysState_ = state;
520     }  // lock end
521 
522     // notify systerm state update
523     BTSystemState notifySysState = (newSysState == SYS_STATE_STARTED) ? BTSystemState::ON : BTSystemState::OFF;
524     if ((newSysState != oldSysState) && ((newSysState == SYS_STATE_STARTED) || (oldSysState == SYS_STATE_STARTED))) {
525         LOG_DEBUG(
526             "%{public}s oldSysState is %{public}s, newSysState is %{public}s", __PRETTY_FUNCTION__, oldSysState.c_str(), newSysState.c_str());
527         pimpl->systemObservers_.ForEach(
528             [notifySysState](ISystemStateObserver &observer) { observer.OnSystemStateChange(notifySysState); });
529     }
530 }
531 
GetSysState() const532 std::string AdapterManager::GetSysState() const
533 {
534     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
535     return pimpl->sysState_;
536 }
537 
OnSysStateExit(const std::string & state) const538 void AdapterManager::OnSysStateExit(const std::string &state) const
539 {
540     LOG_DEBUG("%{public}s state is %{public}s", __PRETTY_FUNCTION__, state.c_str());
541 
542     if (state == SYS_STATE_FRESETTING) {
543         pimpl->resetPromise_.set_value();
544     } else if (state == SYS_STATE_STOPPING) {
545         pimpl->stopPromise_.set_value();
546     } else {
547         // Nothing to do.
548     }
549 }
550 
OnAdapterStateChange(const BTTransport transport,const BTStateID state) const551 void AdapterManager::OnAdapterStateChange(const BTTransport transport, const BTStateID state) const
552 {
553     LOG_DEBUG("%{public}s transport is %{public}d state is %{public}d", __PRETTY_FUNCTION__, transport, state);
554     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
555 
556     if (pimpl->adapters_[transport] == nullptr) {
557         return;
558     }
559 
560     // notify observers state update
561     if (pimpl->adapters_[transport]->state_ != state) {
562         pimpl->adapters_[transport]->state_ = state;
563         if (GetSysState() != SYS_STATE_RESETTING) {
564             pimpl->adapterObservers_.ForEach(
565                 [transport, state](IAdapterStateObserver &observer) { observer.OnStateChange(transport, state); });
566         }
567     }
568 
569     // notify sys state machine
570     int classicState = pimpl->adapters_[BTTransport::ADAPTER_BREDR]
571                            ? pimpl->adapters_[BTTransport::ADAPTER_BREDR]->state_
572                            : BTStateID::STATE_TURN_OFF;
573     int bleState = pimpl->adapters_[BTTransport::ADAPTER_BLE] ? pimpl->adapters_[BTTransport::ADAPTER_BLE]->state_
574                                                               : BTStateID::STATE_TURN_OFF;
575 
576     utility::Message msg(SysStateMachine::MSG_SYS_ADAPTER_STATE_CHANGE_REQ);
577     msg.arg1_ = ((unsigned int)classicState << CLASSIC_ENABLE_STATE_BIT) + bleState;
578     pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
579 }
580 
OnProfileServicesEnableComplete(const BTTransport transport,const bool ret) const581 void AdapterManager::OnProfileServicesEnableComplete(const BTTransport transport, const bool ret) const
582 {
583     LOG_DEBUG("%{public}s transport is %{public}d, ret is %{public}d", __PRETTY_FUNCTION__, transport, ret);
584 
585     utility::Message msg(AdapterStateMachine::MSG_PROFILE_ENABLE_CMP, ret ? true : false);
586     pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
587 }
588 
OnProfileServicesDisableComplete(const BTTransport transport,const bool ret) const589 void AdapterManager::OnProfileServicesDisableComplete(const BTTransport transport, const bool ret) const
590 {
591     LOG_DEBUG("%{public}s transport is %{public}d, ret is %{public}d", __PRETTY_FUNCTION__, transport, ret);
592 
593     utility::Message msg(AdapterStateMachine::MSG_PROFILE_DISABLE_CMP, ret ? true : false);
594     pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
595 }
596 
OnPairDevicesRemoved(const BTTransport transport,const std::vector<RawAddress> & devices) const597 void AdapterManager::OnPairDevicesRemoved(const BTTransport transport, const std::vector<RawAddress> &devices) const
598 {
599     pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::RemoveDeviceProfileConfig, this, transport, devices));
600 }
601 
RemoveDeviceProfileConfig(const BTTransport transport,const std::vector<RawAddress> & devices) const602 void AdapterManager::RemoveDeviceProfileConfig(
603     const BTTransport transport, const std::vector<RawAddress> &devices) const
604 {
605     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
606 
607     BTTransport otherTransport =
608         (transport == BTTransport::ADAPTER_BREDR) ? BTTransport::ADAPTER_BLE : BTTransport::ADAPTER_BREDR;
609 
610     std::vector<RawAddress> otherDevices;
611     otherDevices.clear();
612 
613     if (pimpl->adapters_[otherTransport] != nullptr) {
614         otherDevices = GetAdapter(otherTransport)->GetPairedDevices();
615     }
616 
617     for (auto &device : devices) {
618         if (std::find(otherDevices.begin(), otherDevices.end(), device) == otherDevices.end()) {
619             ProfileConfig::GetInstance()->RemoveAddr(device.GetAddress());
620         }
621     }
622 }
623 
CreateAdapters() const624 void AdapterManager::CreateAdapters() const
625 {
626     static const std::array<std::pair<std::string, std::string>, TRANSPORT_MAX> adapterConfigTbl = {
627         std::make_pair(SECTION_CLASSIC_ADAPTER, ADAPTER_NAME_CLASSIC),
628         std::make_pair(SECTION_BLE_ADAPTER, ADAPTER_NAME_BLE),
629     };
630 
631     for (int i = 0; i < TRANSPORT_MAX; i++) {
632         bool value = false;
633         if (AdapterConfig::GetInstance()->GetValue(adapterConfigTbl[i].first, PROPERTY_IS_VALID, value) && value) {
634             std::unique_ptr<IAdapter> adapter(ClassCreator<IAdapter>::NewInstance(adapterConfigTbl[i].second));
635             std::unique_ptr<AdapterStateMachine> stateMachine(
636                 std::make_unique<AdapterStateMachine>(*pimpl->dispatcher_));
637 
638             if (adapter == nullptr || stateMachine == nullptr) {
639                 adapter = nullptr;
640                 stateMachine = nullptr;
641                 LOG_ERROR("Create %{public}s Failed!!", adapterConfigTbl[i].second.c_str());
642             } else {
643                 adapter->GetContext()->Initialize();
644                 adapter->GetContext()->RegisterCallback(*(pimpl->contextCallback_));
645                 stateMachine->Init(*adapter);
646                 pimpl->adapters_[i].reset(
647                     std::make_unique<AdapterInfo>(std::move(adapter), std::move(stateMachine)).release());
648             }
649         }
650     }
651 }
652 
GetMaxNumConnectedAudioDevices() const653 int AdapterManager::GetMaxNumConnectedAudioDevices() const
654 {
655     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
656     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
657 
658     int value = 0;
659     IAdapterConfig *config = AdapterConfig::GetInstance();
660 
661     if (!config->GetValue(SECTION_A2DP_SRC_SERVICE, PROPERTY_MAX_CONNECTED_DEVICES, value)) {
662         LOG_ERROR("%{public}s %{public}s not found", SECTION_A2DP_SRC_SERVICE.c_str(), PROPERTY_MAX_CONNECTED_DEVICES.c_str());
663     }
664     return value;
665 }
666 
SetPhonebookPermission(const std::string & address,BTPermissionType permission) const667 bool AdapterManager::SetPhonebookPermission(const std::string &address, BTPermissionType permission) const
668 {
669     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
670     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
671 
672     IProfileConfig *config = ProfileConfig::GetInstance();
673     bool tmp = false;
674     switch (permission) {
675         case BTPermissionType::ACCESS_UNKNOWN:
676             return config->RemoveProperty(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_PERMISSION);
677         case BTPermissionType::ACCESS_ALLOWED:
678             tmp = true;
679             break;
680         case BTPermissionType::ACCESS_FORBIDDEN:
681             break;
682         default:
683             return false;
684     }
685     return config->SetValue(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_PERMISSION, tmp);
686 }
687 
GetPhonebookPermission(const std::string & address) const688 BTPermissionType AdapterManager::GetPhonebookPermission(const std::string &address) const
689 {
690     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
691     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
692 
693     IProfileConfig *config = ProfileConfig::GetInstance();
694     bool value = false;
695 
696     if (!config->GetValue(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_PERMISSION, value)) {
697         LOG_DEBUG("%{public}s %{public}s not found", address.c_str(), PROPERTY_PHONEBOOK_PERMISSION.c_str());
698         return BTPermissionType::ACCESS_UNKNOWN;
699     }
700 
701     if (value) {
702         return BTPermissionType::ACCESS_ALLOWED;
703     } else {
704         return BTPermissionType::ACCESS_FORBIDDEN;
705     }
706 }
707 
SetMessagePermission(const std::string & address,BTPermissionType permission) const708 bool AdapterManager::SetMessagePermission(const std::string &address, BTPermissionType permission) const
709 {
710     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
711     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
712 
713     IProfileConfig *config = ProfileConfig::GetInstance();
714     bool tmp = false;
715 
716     switch (permission) {
717         case BTPermissionType::ACCESS_UNKNOWN:
718             return config->RemoveProperty(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION);
719         case BTPermissionType::ACCESS_ALLOWED:
720             tmp = true;
721             break;
722         case BTPermissionType::ACCESS_FORBIDDEN:
723             break;
724         default:
725             return false;
726     }
727     return config->SetValue(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION, tmp);
728 }
729 
GetMessagePermission(const std::string & address) const730 BTPermissionType AdapterManager::GetMessagePermission(const std::string &address) const
731 {
732     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
733     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
734 
735     IProfileConfig *config = ProfileConfig::GetInstance();
736     bool value = false;
737 
738     if (!config->GetValue(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION, value)) {
739         LOG_DEBUG("%{public}s %{public}s not found", address.c_str(), PROPERTY_MESSAGE_PERMISSION.c_str());
740         return BTPermissionType::ACCESS_UNKNOWN;
741     }
742 
743     if (value) {
744         return BTPermissionType::ACCESS_ALLOWED;
745     } else {
746         return BTPermissionType::ACCESS_FORBIDDEN;
747     }
748 }
749 
GetPowerMode(const std::string & address) const750 int AdapterManager::GetPowerMode(const std::string &address) const
751 {
752     LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
753     std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
754 
755     RawAddress addr = RawAddress(address);
756     return static_cast<int>(IPowerManager::GetInstance().GetPowerMode(addr));
757 }
758 }  // namespace bluetooth
759 }  // namespace OHOS