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