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 #include <unistd.h>
21
22 #include "btm.h"
23 #include "btstack.h"
24 #include "log.h"
25 #include "log_util.h"
26
27 #include "adapter_config.h"
28 #include "adapter_device_config.h"
29 #include "adapter_device_info.h"
30 #include "adapter_state_machine.h"
31 #include "base_def.h"
32 #include "base_observer_list.h"
33 #include "bluetooth_common_event_helper.h"
34 #include "class_creator.h"
35 #include "interface_adapter_classic.h"
36 #include "permission_utils.h"
37 #include "power_manager.h"
38 #include "profile_config.h"
39 #include "profile_service_manager.h"
40 #include "sys_state_machine.h"
41
42 namespace OHOS {
43 namespace bluetooth {
44 // data define
45 const int TRANSPORT_MAX = 2;
46 const std::string PERMISSIONS = "ohos.permission.USE_BLUETOOTH";
47
48 // T is BleAdapter or ClassicAdapter
49 template <typename T>
50 struct AdapterInfo {
AdapterInfoOHOS::bluetooth::AdapterInfo51 AdapterInfo(std::shared_ptr<T> instance, std::unique_ptr<AdapterStateMachine> stateMachine)
52 : instance(instance), stateMachine(std::move(stateMachine))
53 {}
~AdapterInfoOHOS::bluetooth::AdapterInfo54 ~AdapterInfo()
55 {}
56
57 BTStateID state = BTStateID::STATE_TURN_OFF;
58 std::shared_ptr<T> instance = nullptr;
59 std::unique_ptr<AdapterStateMachine> stateMachine = nullptr;
60 };
61
62 // static function
GetInstance()63 IAdapterManager *IAdapterManager::GetInstance()
64 {
65 return AdapterManager::GetInstance();
66 }
GetInstance()67 AdapterManager *AdapterManager::GetInstance()
68 {
69 static AdapterManager instance;
70 return &instance;
71 }
72
73 // impl class
74 struct AdapterManager::impl {
75 impl();
76 ~impl();
77
78 std::recursive_mutex syncMutex_ = {};
79 std::promise<void> stopPromise_ = {};
80 std::promise<void> resetPromise_ = {};
81 std::unique_ptr<utility::Dispatcher> dispatcher_ = nullptr;
82 std::unique_ptr<AdapterInfo<ClassicAdapter>> classicAdapter_ = nullptr;
83 std::unique_ptr<AdapterInfo<BleAdapter>> bleAdapter_ = nullptr;
84 SysStateMachine sysStateMachine_ = {};
85 std::string sysState_ = SYS_STATE_STOPPED;
86 BtmCallbacks hciFailureCallbacks = {};
87 BaseObserverList<IAdapterStateObserver> adapterObservers_ = {};
88 BaseObserverList<ISystemStateObserver> systemObservers_ = {};
89
90 class AdaptersContextCallback;
91 std::unique_ptr<AdaptersContextCallback> contextCallback_ = nullptr;
92
93 void OnEnable(const std::string &name, bool ret);
94 void OnDisable(const std::string &name, bool ret);
95 void ProcessMessage(const BTTransport transport, const utility::Message &msg);
96
97 BT_DISALLOW_COPY_AND_ASSIGN(impl);
98 };
99
100 class AdapterManager::impl::AdaptersContextCallback : public utility::IContextCallback {
101 public:
AdaptersContextCallback(AdapterManager::impl & impl)102 explicit AdaptersContextCallback(AdapterManager::impl &impl) : impl_(impl){};
103 ~AdaptersContextCallback() = default;
104
OnEnable(const std::string & name,bool ret)105 void OnEnable(const std::string &name, bool ret)
106 {
107 LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
108 impl_.OnEnable(name, ret);
109 }
OnDisable(const std::string & name,bool ret)110 void OnDisable(const std::string &name, bool ret)
111 {
112 LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
113 impl_.OnDisable(name, ret);
114 }
115
116 private:
117 AdapterManager::impl &impl_;
118 };
119
impl()120 AdapterManager::impl::impl()
121 {
122 dispatcher_ = std::make_unique<utility::Dispatcher>("AdapterManager");
123 dispatcher_->Initialize();
124
125 // context callback create
126 contextCallback_ = std::make_unique<AdaptersContextCallback>(*this);
127 }
128
~impl()129 AdapterManager::impl::~impl()
130 {
131 if (dispatcher_ != nullptr) {
132 dispatcher_->Uninitialize();
133 }
134 }
135
OnEnable(const std::string & name,bool ret)136 void AdapterManager::impl::OnEnable(const std::string &name, bool ret)
137 {
138 LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
139 BTTransport transport = BTTransport::ADAPTER_BREDR;
140
141 if (name.c_str() == ADAPTER_NAME_CLASSIC) {
142 transport = BTTransport::ADAPTER_BREDR;
143 } else if (name.c_str() == ADAPTER_NAME_BLE) {
144 transport = BTTransport::ADAPTER_BLE;
145 } else {
146 LOG_ERROR("%{public}s, name=%{public}s is warning transport\n", __PRETTY_FUNCTION__, name.c_str());
147 }
148
149 utility::Message msg(AdapterStateMachine::MSG_ADAPTER_ENABLE_CMP, ret ? true : false);
150 dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, this, transport, msg));
151 }
152
OnDisable(const std::string & name,bool ret)153 void AdapterManager::impl::OnDisable(const std::string &name, bool ret)
154 {
155 LOG_DEBUG("%{public}s, name=%{public}s, ret=%{public}d\n", __PRETTY_FUNCTION__, name.c_str(), ret);
156 BTTransport transport = BTTransport::ADAPTER_BREDR;
157
158 if (name.c_str() == ADAPTER_NAME_CLASSIC) {
159 transport = BTTransport::ADAPTER_BREDR;
160 } else if (name.c_str() == ADAPTER_NAME_BLE) {
161 transport = BTTransport::ADAPTER_BLE;
162 } else {
163 LOG_ERROR("%{public}s, name=%{public}s is warning transport\n", __PRETTY_FUNCTION__, name.c_str());
164 }
165
166 utility::Message msg(AdapterStateMachine::MSG_ADAPTER_DISABLE_CMP, ret ? true : false);
167 dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, this, transport, msg));
168 }
169
ProcessMessage(const BTTransport transport,const utility::Message & msg)170 void AdapterManager::impl::ProcessMessage(const BTTransport transport, const utility::Message &msg)
171 {
172 std::lock_guard<std::recursive_mutex> lock(syncMutex_);
173
174 if (transport == ADAPTER_BREDR && classicAdapter_ && classicAdapter_->stateMachine) {
175 classicAdapter_->stateMachine->ProcessMessage(msg);
176 return;
177 }
178
179 if (transport == ADAPTER_BLE && bleAdapter_ && bleAdapter_->stateMachine) {
180 bleAdapter_->stateMachine->ProcessMessage(msg);
181 return;
182 }
183 LOG_ERROR("%{public}s transport(%{public}d) failed", __PRETTY_FUNCTION__, transport);
184 }
185
186 // AdapterManager class
AdapterManager()187 AdapterManager::AdapterManager() : pimpl(std::make_unique<AdapterManager::impl>())
188 {
189 // sys state Machine create
190 pimpl->sysStateMachine_.Init(*this);
191 }
192
~AdapterManager()193 AdapterManager::~AdapterManager()
194 {}
195
Start()196 bool AdapterManager::Start()
197 {
198 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
199
200 if (GetSysState() == SYS_STATE_STARTED) {
201 LOG_ERROR("Bluetooth has been started!!");
202 return false;
203 }
204
205 if (!AdapterConfig::GetInstance()->Load()) {
206 LOG_ERROR("Load Config File Failed!!");
207 return false;
208 }
209
210 if (!ProfileConfig::GetInstance()->Load()) {
211 LOG_ERROR("Load Profile Config File Failed!!");
212 return false;
213 }
214
215 if (BTM_Initialize() != BT_SUCCESS) {
216 LOG_ERROR("Bluetooth Stack Initialize Failed!!");
217 return false;
218 }
219
220 if (!OutputSetting()) {
221 LOG_ERROR("Bluetooth output set Failed!!");
222 return false;
223 }
224
225 CreateAdapters();
226
227 ProfileServiceManager::Initialize(*pimpl->dispatcher_);
228
229 IPowerManager::Initialize(*pimpl->dispatcher_);
230
231 RegisterHciResetCallback();
232
233 OnSysStateChange(SYS_STATE_STARTED);
234
235 utility::Message msg(SysStateMachine::MSG_SYS_START_CMP);
236 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
237
238 RestoreTurnOnState();
239
240 return true;
241 }
242
OutputSetting() const243 bool AdapterManager::OutputSetting() const
244 {
245 bool outputValue = false;
246 bool desensitization = false;
247
248 AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_DESENSITIZATION, desensitization);
249 if (AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_BTSNOOP_OUTPUT, outputValue) &&
250 outputValue) {
251 std::string outputPath = "./snoop.log";
252 AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_BTSNOOP_OUTPUT_PATH, outputPath);
253
254 if (BTM_SetSnoopFilePath(outputPath.c_str(), outputPath.length()) != BT_SUCCESS) {
255 LOG_ERROR("Set snoop file path Failed!!");
256 return false;
257 }
258
259 if (BTM_EnableSnoopFileOutput(desensitization) != BT_SUCCESS) {
260 LOG_ERROR("Enable snoop file output Failed!!");
261 return false;
262 }
263 } else {
264 if (BTM_DisableSnoopFileOutput() != BT_SUCCESS) {
265 LOG_ERROR("Disable snoop file output Failed!!");
266 return false;
267 }
268 }
269
270 outputValue = false;
271 if (AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_HCILOG_OUTPUT, outputValue) &&
272 outputValue) {
273 if (BTM_EnableHciLogOutput(desensitization) != BT_SUCCESS) {
274 LOG_ERROR("Enable HciLog output Failed!!");
275 return false;
276 }
277 } else {
278 if (BTM_DisableHciLogOutput() != BT_SUCCESS) {
279 LOG_ERROR("Disable HciLog output Failed!!");
280 return false;
281 }
282 }
283
284 return true;
285 }
286
Stop() const287 void AdapterManager::Stop() const
288 {
289 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
290
291 if (GetSysState() == SYS_STATE_STOPPED) {
292 LOG_DEBUG("AdapterManager is stoped");
293 } else if (GetSysState() == SYS_STATE_STOPPING) {
294 LOG_DEBUG("AdapterManager is stoping...");
295 } else {
296 std::promise<void> stopPromise;
297 std::future<void> stopFuture = stopPromise.get_future();
298
299 {
300 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
301 pimpl->stopPromise_ = std::move(stopPromise);
302 }
303
304 utility::Message msg(SysStateMachine::MSG_SYS_STOP_REQ);
305 pimpl->dispatcher_->PostTask(
306 std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
307 stopFuture.wait();
308 }
309 }
310
AdapterStop() const311 bool AdapterManager::AdapterStop() const
312 {
313 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
314 ProfileServiceManager::Uninitialize();
315 IPowerManager::Uninitialize();
316
317 DeregisterHciResetCallback();
318
319 if (pimpl->classicAdapter_) {
320 pimpl->classicAdapter_->instance->GetContext()->Uninitialize();
321 pimpl->classicAdapter_ = nullptr;
322 }
323 if (pimpl->bleAdapter_) {
324 pimpl->bleAdapter_->instance->GetContext()->Uninitialize();
325 pimpl->bleAdapter_ = nullptr;
326 }
327
328 BTM_Close();
329
330 utility::Message msg(SysStateMachine::MSG_SYS_STOP_CMP);
331 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
332
333 return true;
334 }
335
Enable(const BTTransport transport) const336 bool AdapterManager::Enable(const BTTransport transport) const
337 {
338 LOG_DEBUG("%{public}s start transport is %{public}d", __PRETTY_FUNCTION__, transport);
339 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
340 std::string propertynames[] = {PROPERTY_BREDR_TURNON, PROPERTY_BLE_TURNON};
341
342 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
343 LOG_ERROR("Enable() false, check permission failed");
344 return false;
345 }
346
347 if (GetSysState() != SYS_STATE_STARTED) {
348 LOG_ERROR("AdapterManager system is stoped");
349 return false;
350 }
351
352 if ((transport == ADAPTER_BREDR && pimpl->classicAdapter_ == nullptr) ||
353 (transport == ADAPTER_BLE && pimpl->bleAdapter_ == nullptr)) {
354 LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
355 return false;
356 }
357
358 if (GetState(transport) == BTStateID::STATE_TURN_OFF) {
359 utility::Message msg(AdapterStateMachine::MSG_USER_ENABLE_REQ);
360 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
361
362 AdapterDeviceConfig::GetInstance()->SetValue(SECTION_HOST, propertynames[transport], (int)true);
363 AdapterDeviceConfig::GetInstance()->Save();
364
365 return true;
366 } else if (GetState(transport) == BTStateID::STATE_TURN_ON) {
367 LOG_INFO("%{public}s is turn on", __PRETTY_FUNCTION__);
368 return false;
369 } else {
370 LOG_INFO("%{public}s is turning state %{public}d", __PRETTY_FUNCTION__, GetState(transport));
371 return false;
372 }
373 }
374
Disable(const BTTransport transport) const375 bool AdapterManager::Disable(const BTTransport transport) const
376 {
377 LOG_DEBUG("%{public}s start transport is %{public}d", __PRETTY_FUNCTION__, transport);
378 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
379 std::string propertynames[] = {PROPERTY_BREDR_TURNON, PROPERTY_BLE_TURNON};
380
381 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
382 LOG_ERROR("Disable() false, check permission failed");
383 return false;
384 }
385
386 if ((transport == ADAPTER_BREDR && pimpl->classicAdapter_ == nullptr) ||
387 (transport == ADAPTER_BLE && pimpl->bleAdapter_ == nullptr)) {
388 LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
389 return false;
390 }
391
392 if (GetState(transport) == BTStateID::STATE_TURN_ON) {
393 utility::Message msg(AdapterStateMachine::MSG_USER_DISABLE_REQ);
394 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
395
396 AdapterDeviceConfig::GetInstance()->SetValue(SECTION_HOST, propertynames[transport], (int)false);
397 AdapterDeviceConfig::GetInstance()->Save();
398
399 return true;
400 } else if (GetState(transport) == BTStateID::STATE_TURN_OFF) {
401 LOG_INFO("%{public}s is turn off", __PRETTY_FUNCTION__);
402 return false;
403 } else {
404 LOG_INFO("%{public}s is turning state %{public}d", __PRETTY_FUNCTION__, GetState(transport));
405 return false;
406 }
407 }
408
FactoryReset() const409 bool AdapterManager::FactoryReset() const
410 {
411 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
412
413 if (GetSysState() == SYS_STATE_STARTED) {
414 std::promise<void> resetPromise;
415 std::future<void> resetFuture = resetPromise.get_future();
416
417 {
418 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
419 pimpl->resetPromise_ = std::move(resetPromise);
420 }
421
422 utility::Message msg(SysStateMachine::MSG_SYS_FACTORY_RESET_REQ);
423 pimpl->dispatcher_->PostTask(
424 std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
425 resetFuture.wait();
426 return true;
427 } else {
428 LOG_INFO("System state is not started");
429 return false;
430 }
431 }
432
HciFailedReset(void * context)433 void AdapterManager::HciFailedReset(void *context)
434 {
435 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
436 (static_cast<AdapterManager *>(context))->Reset();
437 }
438
RegisterHciResetCallback()439 void AdapterManager::RegisterHciResetCallback()
440 {
441 pimpl->hciFailureCallbacks.hciFailure = HciFailedReset;
442 BTM_RegisterCallbacks(&(pimpl->hciFailureCallbacks), this);
443 }
444
DeregisterHciResetCallback() const445 void AdapterManager::DeregisterHciResetCallback() const
446 {
447 if (pimpl->hciFailureCallbacks.hciFailure != nullptr) {
448 BTM_DeregisterCallbacks(&(pimpl->hciFailureCallbacks));
449 pimpl->hciFailureCallbacks.hciFailure = nullptr;
450 }
451 }
452
Reset() const453 void AdapterManager::Reset() const
454 {
455 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
456
457 utility::Message msg(SysStateMachine::MSG_SYS_RESET_REQ);
458 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
459 }
460
ClearAllStorage() const461 bool AdapterManager::ClearAllStorage() const
462 {
463 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
464
465 if (!AdapterConfig::GetInstance()->Reload()) {
466 return false;
467 }
468 if (!ProfileConfig::GetInstance()->Reload()) {
469 return false;
470 }
471 if (!AdapterDeviceConfig::GetInstance()->Reload()) {
472 return false;
473 }
474 if (!AdapterDeviceInfo::GetInstance()->Reload()) {
475 return false;
476 }
477
478 utility::Message msg(SysStateMachine::MSG_SYS_CLEAR_ALL_STORAGE_CMP);
479 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
480 return true;
481 }
482
GetState(const BTTransport transport) const483 BTStateID AdapterManager::GetState(const BTTransport transport) const
484 {
485 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
486
487 BTStateID state = BTStateID::STATE_TURN_OFF;
488 if (transport == ADAPTER_BREDR && pimpl->classicAdapter_) {
489 state = pimpl->classicAdapter_->state;
490 }
491 if (transport == ADAPTER_BLE && pimpl->bleAdapter_) {
492 state = pimpl->bleAdapter_->state;
493 }
494 return state;
495 }
496
RegisterStateObserver(IAdapterStateObserver & observer) const497 bool AdapterManager::RegisterStateObserver(IAdapterStateObserver &observer) const
498 {
499 return pimpl->adapterObservers_.Register(observer);
500 }
501
DeregisterStateObserver(IAdapterStateObserver & observer) const502 bool AdapterManager::DeregisterStateObserver(IAdapterStateObserver &observer) const
503 {
504 return pimpl->adapterObservers_.Deregister(observer);
505 }
506
RegisterSystemStateObserver(ISystemStateObserver & observer) const507 bool AdapterManager::RegisterSystemStateObserver(ISystemStateObserver &observer) const
508 {
509 return pimpl->systemObservers_.Register(observer);
510 }
511
DeregisterSystemStateObserver(ISystemStateObserver & observer) const512 bool AdapterManager::DeregisterSystemStateObserver(ISystemStateObserver &observer) const
513 {
514 return pimpl->systemObservers_.Deregister(observer);
515 }
516
GetAdapterConnectState() const517 BTConnectState AdapterManager::GetAdapterConnectState() const
518 {
519 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
520 return ProfileServiceManager::GetInstance()->GetProfileServicesConnectState();
521 }
522
GetClassicAdapterInterface(void) const523 std::shared_ptr<IAdapterClassic> AdapterManager::GetClassicAdapterInterface(void) const
524 {
525 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
526 return pimpl->classicAdapter_ != nullptr ? pimpl->classicAdapter_->instance : nullptr;
527 }
528
GetBleAdapterInterface(void) const529 std::shared_ptr<IAdapterBle> AdapterManager::GetBleAdapterInterface(void) const
530 {
531 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
532 return pimpl->bleAdapter_ != nullptr ? pimpl->bleAdapter_->instance : nullptr;
533 }
534
OnSysStateChange(const std::string & state) const535 void AdapterManager::OnSysStateChange(const std::string &state) const
536 {
537 LOG_DEBUG("%{public}s state is %{public}s", __PRETTY_FUNCTION__, state.c_str());
538
539 std::string oldSysState;
540 std::string newSysState = state;
541
542 { // lock start,update systerm state
543 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
544 oldSysState = pimpl->sysState_;
545 pimpl->sysState_ = state;
546 } // lock end
547
548 // notify systerm state update
549 BTSystemState notifySysState = (newSysState == SYS_STATE_STARTED) ? BTSystemState::ON : BTSystemState::OFF;
550 if ((newSysState != oldSysState) && ((newSysState == SYS_STATE_STARTED) || (oldSysState == SYS_STATE_STARTED))) {
551 HILOGE("oldSysState is %{public}s, newSysState is %{public}s", oldSysState.c_str(), newSysState.c_str());
552 pimpl->systemObservers_.ForEach(
553 [notifySysState](ISystemStateObserver &observer) { observer.OnSystemStateChange(notifySysState); });
554 }
555 }
556
GetSysState() const557 std::string AdapterManager::GetSysState() const
558 {
559 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
560 return pimpl->sysState_;
561 }
562
OnSysStateExit(const std::string & state) const563 void AdapterManager::OnSysStateExit(const std::string &state) const
564 {
565 LOG_DEBUG("%{public}s state is %{public}s", __PRETTY_FUNCTION__, state.c_str());
566
567 if (state == SYS_STATE_FRESETTING) {
568 pimpl->resetPromise_.set_value();
569 } else if (state == SYS_STATE_STOPPING) {
570 pimpl->stopPromise_.set_value();
571 } else {
572 // Nothing to do.
573 }
574 }
PublishBluetoothStateChangeEvent(const BTTransport transport,const BTStateID state) const575 void AdapterManager::PublishBluetoothStateChangeEvent(const BTTransport transport, const BTStateID state) const
576 {
577 if (transport == ADAPTER_BREDR && (state == BTStateID::STATE_TURN_ON || state == BTStateID::STATE_TURN_OFF)) {
578 std::vector<std::string> permissions;
579 permissions.emplace_back(PERMISSIONS);
580 BluetoothHelper::BluetoothCommonEventHelper::PublishBluetoothStateChangeEvent(state, permissions);
581 }
582 }
583
OnAdapterStateChange(const BTTransport transport,const BTStateID state) const584 void AdapterManager::OnAdapterStateChange(const BTTransport transport, const BTStateID state) const
585 {
586 LOG_DEBUG("%{public}s transport is %{public}d state is %{public}d", __PRETTY_FUNCTION__, transport, state);
587 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
588
589 if ((transport == ADAPTER_BREDR && pimpl->classicAdapter_ == nullptr) ||
590 (transport == ADAPTER_BLE && pimpl->bleAdapter_ == nullptr)) {
591 return;
592 }
593 if ((transport == ADAPTER_BLE) && (state == STATE_TURN_ON)) {
594 HILOGI("enable ADAPTER_BREDR");
595 Enable(ADAPTER_BREDR);
596 }
597 if ((transport == ADAPTER_BREDR) && (state == STATE_TURN_OFF)) {
598 HILOGI("disable ADAPTER_BLE");
599 Disable(ADAPTER_BLE);
600 }
601 // notify observers state update
602 auto &adapterState = transport == ADAPTER_BREDR ? pimpl->classicAdapter_->state : pimpl->bleAdapter_->state;
603 if (adapterState != state) {
604 adapterState = state;
605 if (GetSysState() != SYS_STATE_RESETTING) {
606 PublishBluetoothStateChangeEvent(transport, state);
607 pimpl->adapterObservers_.ForEach(
608 [transport, state](IAdapterStateObserver &observer) { observer.OnStateChange(transport, state); });
609 }
610 }
611
612 // notify sys state machine
613 int classicState = pimpl->classicAdapter_ ? pimpl->classicAdapter_->state : BTStateID::STATE_TURN_OFF;
614 int bleState = pimpl->bleAdapter_ ? pimpl->bleAdapter_->state : BTStateID::STATE_TURN_OFF;
615
616 utility::Message msg(SysStateMachine::MSG_SYS_ADAPTER_STATE_CHANGE_REQ);
617 msg.arg1_ = ((unsigned int)classicState << CLASSIC_ENABLE_STATE_BIT) + bleState;
618 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
619 }
620
OnProfileServicesEnableComplete(const BTTransport transport,const bool ret) const621 void AdapterManager::OnProfileServicesEnableComplete(const BTTransport transport, const bool ret) const
622 {
623 LOG_DEBUG("%{public}s transport is %{public}d, ret is %{public}d", __PRETTY_FUNCTION__, transport, ret);
624
625 utility::Message msg(AdapterStateMachine::MSG_PROFILE_ENABLE_CMP, ret ? true : false);
626 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
627 }
628
OnProfileServicesDisableComplete(const BTTransport transport,const bool ret) const629 void AdapterManager::OnProfileServicesDisableComplete(const BTTransport transport, const bool ret) const
630 {
631 LOG_DEBUG("%{public}s transport is %{public}d, ret is %{public}d", __PRETTY_FUNCTION__, transport, ret);
632
633 utility::Message msg(AdapterStateMachine::MSG_PROFILE_DISABLE_CMP, ret ? true : false);
634 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
635 }
636
OnPairDevicesRemoved(const BTTransport transport,const std::vector<RawAddress> & devices) const637 void AdapterManager::OnPairDevicesRemoved(const BTTransport transport, const std::vector<RawAddress> &devices) const
638 {
639 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::RemoveDeviceProfileConfig, this, transport, devices));
640 }
641
RemoveDeviceProfileConfig(const BTTransport transport,const std::vector<RawAddress> & devices) const642 void AdapterManager::RemoveDeviceProfileConfig(
643 const BTTransport transport, const std::vector<RawAddress> &devices) const
644 {
645 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
646
647 std::vector<RawAddress> otherDevices {};
648 std::shared_ptr<IAdapter> otherAdapter =
649 (transport == BTTransport::ADAPTER_BREDR) ?
650 static_cast<std::shared_ptr<IAdapter>>(GetBleAdapterInterface()) :
651 static_cast<std::shared_ptr<IAdapter>>(GetClassicAdapterInterface());
652 if (otherAdapter) {
653 otherDevices = otherAdapter->GetPairedDevices();
654 }
655
656 for (auto &device : devices) {
657 if (std::find(otherDevices.begin(), otherDevices.end(), device) == otherDevices.end()) {
658 ProfileConfig::GetInstance()->RemoveAddr(device.GetAddress());
659 }
660 }
661 }
662
663 namespace {
664 template <typename T>
CreateAdapter(const std::string & adapterSection,const std::string & adapterName,utility::Dispatcher & dispatcher,utility::IContextCallback & callback)665 std::unique_ptr<AdapterInfo<T>> CreateAdapter(const std::string &adapterSection, const std::string &adapterName,
666 utility::Dispatcher &dispatcher, utility::IContextCallback &callback)
667 {
668 bool value = false;
669 std::unique_ptr<AdapterInfo<T>> adapterInfo = nullptr;
670 if (AdapterConfig::GetInstance()->GetValue(adapterSection, PROPERTY_IS_VALID, value) && value) {
671 std::shared_ptr<T> adapter(ClassCreator<T>::NewInstance(adapterName));
672 auto stateMachine = std::make_unique<AdapterStateMachine>(dispatcher);
673 if (adapter && stateMachine) {
674 adapter->GetContext()->Initialize();
675 adapter->GetContext()->RegisterCallback(callback);
676 stateMachine->Init(*adapter);
677 adapterInfo = std::make_unique<AdapterInfo<T>>(adapter, std::move(stateMachine));
678 } else {
679 LOG_ERROR("Create %{public}s failed", adapterName.c_str());
680 }
681 }
682 return adapterInfo;
683 }
684 } // namespace {}
685
CreateAdapters() const686 void AdapterManager::CreateAdapters() const
687 {
688 pimpl->classicAdapter_ = CreateAdapter<ClassicAdapter>(
689 SECTION_CLASSIC_ADAPTER, ADAPTER_NAME_CLASSIC, *pimpl->dispatcher_, *(pimpl->contextCallback_));
690 pimpl->bleAdapter_ = CreateAdapter<BleAdapter>(
691 SECTION_BLE_ADAPTER, ADAPTER_NAME_BLE, *pimpl->dispatcher_, *(pimpl->contextCallback_));
692 }
693
GetMaxNumConnectedAudioDevices() const694 int AdapterManager::GetMaxNumConnectedAudioDevices() const
695 {
696 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
697 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
698
699 int value = 0;
700 IAdapterConfig *config = AdapterConfig::GetInstance();
701
702 if (!config->GetValue(SECTION_A2DP_SRC_SERVICE, PROPERTY_MAX_CONNECTED_DEVICES, value)) {
703 HILOGE("%{public}s %{public}s not found", SECTION_A2DP_SRC_SERVICE.c_str(),
704 PROPERTY_MAX_CONNECTED_DEVICES.c_str());
705 }
706 return value;
707 }
708
SetPhonebookPermission(const std::string & address,BTPermissionType permission) const709 bool AdapterManager::SetPhonebookPermission(const std::string &address, BTPermissionType permission) const
710 {
711 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
712 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
713
714 IProfileConfig *config = ProfileConfig::GetInstance();
715 bool tmp = false;
716 switch (permission) {
717 case BTPermissionType::ACCESS_UNKNOWN:
718 return config->RemoveProperty(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_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_PHONEBOOK_PERMISSION, tmp);
728 }
729
GetPhonebookPermission(const std::string & address) const730 BTPermissionType AdapterManager::GetPhonebookPermission(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_PHONEBOOK_PERMISSION, value)) {
739 HILOGE("%{public}s %{public}s not found", GetEncryptAddr(address).c_str(),
740 PROPERTY_PHONEBOOK_PERMISSION.c_str());
741 return BTPermissionType::ACCESS_UNKNOWN;
742 }
743
744 if (value) {
745 return BTPermissionType::ACCESS_ALLOWED;
746 } else {
747 return BTPermissionType::ACCESS_FORBIDDEN;
748 }
749 }
750
SetMessagePermission(const std::string & address,BTPermissionType permission) const751 bool AdapterManager::SetMessagePermission(const std::string &address, BTPermissionType permission) const
752 {
753 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
754 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
755
756 IProfileConfig *config = ProfileConfig::GetInstance();
757 bool tmp = false;
758
759 switch (permission) {
760 case BTPermissionType::ACCESS_UNKNOWN:
761 return config->RemoveProperty(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION);
762 case BTPermissionType::ACCESS_ALLOWED:
763 tmp = true;
764 break;
765 case BTPermissionType::ACCESS_FORBIDDEN:
766 break;
767 default:
768 return false;
769 }
770 return config->SetValue(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION, tmp);
771 }
772
GetMessagePermission(const std::string & address) const773 BTPermissionType AdapterManager::GetMessagePermission(const std::string &address) const
774 {
775 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
776 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
777
778 IProfileConfig *config = ProfileConfig::GetInstance();
779 bool value = false;
780
781 if (!config->GetValue(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION, value)) {
782 HILOGE("%{public}s %{public}s not found", GetEncryptAddr(address).c_str(),
783 PROPERTY_MESSAGE_PERMISSION.c_str());
784 return BTPermissionType::ACCESS_UNKNOWN;
785 }
786
787 if (value) {
788 return BTPermissionType::ACCESS_ALLOWED;
789 } else {
790 return BTPermissionType::ACCESS_FORBIDDEN;
791 }
792 }
793
GetPowerMode(const std::string & address) const794 int AdapterManager::GetPowerMode(const std::string &address) const
795 {
796 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
797 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
798
799 RawAddress addr = RawAddress(address);
800 return static_cast<int>(IPowerManager::GetInstance().GetPowerMode(addr));
801 }
802
RestoreTurnOnState()803 void AdapterManager::RestoreTurnOnState()
804 {
805 std::thread([this] {
806 static const std::array<std::pair<std::string, BTTransport>, TRANSPORT_MAX> adapterConfigTbl = {
807 std::make_pair(PROPERTY_BLE_TURNON, BTTransport::ADAPTER_BLE),
808 std::make_pair(PROPERTY_BREDR_TURNON, BTTransport::ADAPTER_BREDR),
809 };
810
811 auto classicAdapter = GetClassicAdapterInterface();
812 if (!classicAdapter) {
813 LOG_ERROR("classicAdapter is nullptr");
814 return;
815 }
816
817 while (true) {
818 sleep(1);
819
820 int processed = 0;
821 const unsigned char btStateFlag = 0;
822 int turnOn = 0;
823
824 AdapterDeviceConfig::GetInstance()->GetValue(SECTION_HOST, adapterConfigTbl[btStateFlag].first, turnOn);
825 LOG_INFO("restore turnon, %{public}s, %{public}d", adapterConfigTbl[btStateFlag].first.c_str(), turnOn);
826 for (int i = 0; i < TRANSPORT_MAX; i++) {
827 if (!turnOn) {
828 processed++;
829 continue;
830 }
831 if (GetState(adapterConfigTbl[i].second) != BTStateID::STATE_TURN_ON) {
832 Enable(adapterConfigTbl[i].second);
833 continue;
834 }
835
836 processed++;
837 if (adapterConfigTbl[i].second == BTTransport::ADAPTER_BREDR) {
838 classicAdapter->SetBtScanMode(SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0);
839 classicAdapter->SetBondableMode(BONDABLE_MODE_ON);
840 }
841 }
842
843 if (processed == TRANSPORT_MAX) {
844 LOG_INFO("restore turnon thread END");
845 return;
846 }
847 }
848 }).detach();
849 }
850 } // namespace bluetooth
851 } // namespace OHOS
852