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 int maxSize = 0;
248 AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_OUTPUTMAXSIZE, maxSize);
249 AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_DESENSITIZATION, desensitization);
250 if (AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_BTSNOOP_OUTPUT, outputValue) &&
251 outputValue) {
252 std::string outputPath = "./snoop.log";
253 AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_BTSNOOP_OUTPUT_PATH, outputPath);
254
255 if (BTM_SetSnoopOutputMaxsize(maxSize)) {
256 LOG_ERROR("Set snoop file output maxsize Failed!!");
257 return false;
258 }
259
260 if (BTM_SetSnoopFilePath(outputPath.c_str(), outputPath.length()) != BT_SUCCESS) {
261 LOG_ERROR("Set snoop file path Failed!!");
262 return false;
263 }
264
265 if (BTM_EnableSnoopFileOutput(desensitization) != BT_SUCCESS) {
266 LOG_ERROR("Enable snoop file output Failed!!");
267 return false;
268 }
269 } else {
270 if (BTM_DisableSnoopFileOutput() != BT_SUCCESS) {
271 LOG_ERROR("Disable snoop file output Failed!!");
272 return false;
273 }
274 }
275
276 outputValue = false;
277 if (AdapterConfig::GetInstance()->GetValue(SECTION_OUTPUT_SETTING, PROPERTY_HCILOG_OUTPUT, outputValue) &&
278 outputValue) {
279 if (BTM_SetSnoopOutputMaxsize(maxSize)) {
280 LOG_ERROR("Set snoop file output maxsize Failed!!");
281 return false;
282 }
283
284 if (BTM_EnableHciLogOutput(desensitization) != BT_SUCCESS) {
285 LOG_ERROR("Enable HciLog output Failed!!");
286 return false;
287 }
288 } else {
289 if (BTM_DisableHciLogOutput() != BT_SUCCESS) {
290 LOG_ERROR("Disable HciLog output Failed!!");
291 return false;
292 }
293 }
294
295 return true;
296 }
297
Stop() const298 void AdapterManager::Stop() const
299 {
300 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
301
302 if (GetSysState() == SYS_STATE_STOPPED) {
303 LOG_DEBUG("AdapterManager is stoped");
304 } else if (GetSysState() == SYS_STATE_STOPPING) {
305 LOG_DEBUG("AdapterManager is stoping...");
306 } else {
307 std::promise<void> stopPromise;
308 std::future<void> stopFuture = stopPromise.get_future();
309
310 {
311 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
312 pimpl->stopPromise_ = std::move(stopPromise);
313 }
314
315 utility::Message msg(SysStateMachine::MSG_SYS_STOP_REQ);
316 pimpl->dispatcher_->PostTask(
317 std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
318 stopFuture.wait();
319 }
320 }
321
AdapterStop() const322 bool AdapterManager::AdapterStop() const
323 {
324 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
325 ProfileServiceManager::Uninitialize();
326 IPowerManager::Uninitialize();
327
328 DeregisterHciResetCallback();
329
330 if (pimpl->classicAdapter_) {
331 pimpl->classicAdapter_->instance->GetContext()->Uninitialize();
332 pimpl->classicAdapter_ = nullptr;
333 }
334 if (pimpl->bleAdapter_) {
335 pimpl->bleAdapter_->instance->GetContext()->Uninitialize();
336 pimpl->bleAdapter_ = nullptr;
337 }
338
339 BTM_Close();
340
341 utility::Message msg(SysStateMachine::MSG_SYS_STOP_CMP);
342 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
343
344 return true;
345 }
346
Enable(const BTTransport transport) const347 bool AdapterManager::Enable(const BTTransport transport) const
348 {
349 LOG_DEBUG("%{public}s start transport is %{public}d", __PRETTY_FUNCTION__, transport);
350 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
351 std::string propertynames[] = {PROPERTY_BREDR_TURNON, PROPERTY_BLE_TURNON};
352
353 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
354 LOG_ERROR("Enable() false, check permission failed");
355 return false;
356 }
357
358 if (GetSysState() != SYS_STATE_STARTED) {
359 LOG_ERROR("AdapterManager system is stoped");
360 return false;
361 }
362
363 if ((transport == ADAPTER_BREDR && pimpl->classicAdapter_ == nullptr) ||
364 (transport == ADAPTER_BLE && pimpl->bleAdapter_ == nullptr)) {
365 LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
366 return false;
367 }
368
369 if (GetState(transport) == BTStateID::STATE_TURN_OFF) {
370 utility::Message msg(AdapterStateMachine::MSG_USER_ENABLE_REQ);
371 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
372
373 AdapterDeviceConfig::GetInstance()->SetValue(SECTION_HOST, propertynames[transport], (int)true);
374 AdapterDeviceConfig::GetInstance()->Save();
375
376 return true;
377 } else if (GetState(transport) == BTStateID::STATE_TURN_ON) {
378 LOG_INFO("%{public}s is turn on", __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
Disable(const BTTransport transport) const386 bool AdapterManager::Disable(const BTTransport transport) const
387 {
388 LOG_DEBUG("%{public}s start transport is %{public}d", __PRETTY_FUNCTION__, transport);
389 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
390 std::string propertynames[] = {PROPERTY_BREDR_TURNON, PROPERTY_BLE_TURNON};
391
392 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
393 LOG_ERROR("Disable() false, check permission failed");
394 return false;
395 }
396
397 if ((transport == ADAPTER_BREDR && pimpl->classicAdapter_ == nullptr) ||
398 (transport == ADAPTER_BLE && pimpl->bleAdapter_ == nullptr)) {
399 LOG_INFO("%{public}s BTTransport not register", __PRETTY_FUNCTION__);
400 return false;
401 }
402
403 if (GetState(transport) == BTStateID::STATE_TURN_ON) {
404 utility::Message msg(AdapterStateMachine::MSG_USER_DISABLE_REQ);
405 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
406
407 AdapterDeviceConfig::GetInstance()->SetValue(SECTION_HOST, propertynames[transport], (int)false);
408 AdapterDeviceConfig::GetInstance()->Save();
409
410 return true;
411 } else if (GetState(transport) == BTStateID::STATE_TURN_OFF) {
412 LOG_INFO("%{public}s is turn off", __PRETTY_FUNCTION__);
413 return false;
414 } else {
415 LOG_INFO("%{public}s is turning state %{public}d", __PRETTY_FUNCTION__, GetState(transport));
416 return false;
417 }
418 }
419
FactoryReset() const420 bool AdapterManager::FactoryReset() const
421 {
422 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
423
424 if (GetSysState() == SYS_STATE_STARTED) {
425 std::promise<void> resetPromise;
426 std::future<void> resetFuture = resetPromise.get_future();
427
428 {
429 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
430 pimpl->resetPromise_ = std::move(resetPromise);
431 }
432
433 utility::Message msg(SysStateMachine::MSG_SYS_FACTORY_RESET_REQ);
434 pimpl->dispatcher_->PostTask(
435 std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
436 resetFuture.wait();
437 return true;
438 } else {
439 LOG_INFO("System state is not started");
440 return false;
441 }
442 }
443
HciFailedReset(void * context)444 void AdapterManager::HciFailedReset(void *context)
445 {
446 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
447 (static_cast<AdapterManager *>(context))->Reset();
448 }
449
RegisterHciResetCallback()450 void AdapterManager::RegisterHciResetCallback()
451 {
452 pimpl->hciFailureCallbacks.hciFailure = HciFailedReset;
453 BTM_RegisterCallbacks(&(pimpl->hciFailureCallbacks), this);
454 }
455
DeregisterHciResetCallback() const456 void AdapterManager::DeregisterHciResetCallback() const
457 {
458 if (pimpl->hciFailureCallbacks.hciFailure != nullptr) {
459 BTM_DeregisterCallbacks(&(pimpl->hciFailureCallbacks));
460 pimpl->hciFailureCallbacks.hciFailure = nullptr;
461 }
462 }
463
Reset() const464 void AdapterManager::Reset() const
465 {
466 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
467
468 utility::Message msg(SysStateMachine::MSG_SYS_RESET_REQ);
469 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
470 }
471
ClearAllStorage() const472 bool AdapterManager::ClearAllStorage() const
473 {
474 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
475
476 if (!AdapterConfig::GetInstance()->Reload()) {
477 return false;
478 }
479 if (!ProfileConfig::GetInstance()->Reload()) {
480 return false;
481 }
482 if (!AdapterDeviceConfig::GetInstance()->Reload()) {
483 return false;
484 }
485 if (!AdapterDeviceInfo::GetInstance()->Reload()) {
486 return false;
487 }
488
489 utility::Message msg(SysStateMachine::MSG_SYS_CLEAR_ALL_STORAGE_CMP);
490 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
491 return true;
492 }
493
GetState(const BTTransport transport) const494 BTStateID AdapterManager::GetState(const BTTransport transport) const
495 {
496 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
497
498 BTStateID state = BTStateID::STATE_TURN_OFF;
499 if (transport == ADAPTER_BREDR && pimpl->classicAdapter_) {
500 state = pimpl->classicAdapter_->state;
501 }
502 if (transport == ADAPTER_BLE && pimpl->bleAdapter_) {
503 state = pimpl->bleAdapter_->state;
504 }
505 return state;
506 }
507
RegisterStateObserver(IAdapterStateObserver & observer) const508 bool AdapterManager::RegisterStateObserver(IAdapterStateObserver &observer) const
509 {
510 return pimpl->adapterObservers_.Register(observer);
511 }
512
DeregisterStateObserver(IAdapterStateObserver & observer) const513 bool AdapterManager::DeregisterStateObserver(IAdapterStateObserver &observer) const
514 {
515 return pimpl->adapterObservers_.Deregister(observer);
516 }
517
RegisterSystemStateObserver(ISystemStateObserver & observer) const518 bool AdapterManager::RegisterSystemStateObserver(ISystemStateObserver &observer) const
519 {
520 return pimpl->systemObservers_.Register(observer);
521 }
522
DeregisterSystemStateObserver(ISystemStateObserver & observer) const523 bool AdapterManager::DeregisterSystemStateObserver(ISystemStateObserver &observer) const
524 {
525 return pimpl->systemObservers_.Deregister(observer);
526 }
527
GetAdapterConnectState() const528 BTConnectState AdapterManager::GetAdapterConnectState() const
529 {
530 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
531 return ProfileServiceManager::GetInstance()->GetProfileServicesConnectState();
532 }
533
GetClassicAdapterInterface(void) const534 std::shared_ptr<IAdapterClassic> AdapterManager::GetClassicAdapterInterface(void) const
535 {
536 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
537 return pimpl->classicAdapter_ != nullptr ? pimpl->classicAdapter_->instance : nullptr;
538 }
539
GetBleAdapterInterface(void) const540 std::shared_ptr<IAdapterBle> AdapterManager::GetBleAdapterInterface(void) const
541 {
542 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
543 return pimpl->bleAdapter_ != nullptr ? pimpl->bleAdapter_->instance : nullptr;
544 }
545
OnSysStateChange(const std::string & state) const546 void AdapterManager::OnSysStateChange(const std::string &state) const
547 {
548 LOG_DEBUG("%{public}s state is %{public}s", __PRETTY_FUNCTION__, state.c_str());
549
550 std::string oldSysState;
551 std::string newSysState = state;
552
553 { // lock start,update systerm state
554 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
555 oldSysState = pimpl->sysState_;
556 pimpl->sysState_ = state;
557 } // lock end
558
559 // notify systerm state update
560 BTSystemState notifySysState = (newSysState == SYS_STATE_STARTED) ? BTSystemState::ON : BTSystemState::OFF;
561 if ((newSysState != oldSysState) && ((newSysState == SYS_STATE_STARTED) || (oldSysState == SYS_STATE_STARTED))) {
562 HILOGE("oldSysState is %{public}s, newSysState is %{public}s", oldSysState.c_str(), newSysState.c_str());
563 pimpl->systemObservers_.ForEach(
564 [notifySysState](ISystemStateObserver &observer) { observer.OnSystemStateChange(notifySysState); });
565 }
566 }
567
GetSysState() const568 std::string AdapterManager::GetSysState() const
569 {
570 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
571 return pimpl->sysState_;
572 }
573
OnSysStateExit(const std::string & state) const574 void AdapterManager::OnSysStateExit(const std::string &state) const
575 {
576 LOG_DEBUG("%{public}s state is %{public}s", __PRETTY_FUNCTION__, state.c_str());
577
578 if (state == SYS_STATE_FRESETTING) {
579 pimpl->resetPromise_.set_value();
580 } else if (state == SYS_STATE_STOPPING) {
581 pimpl->stopPromise_.set_value();
582 } else {
583 // Nothing to do.
584 }
585 }
PublishBluetoothStateChangeEvent(const BTTransport transport,const BTStateID state) const586 void AdapterManager::PublishBluetoothStateChangeEvent(const BTTransport transport, const BTStateID state) const
587 {
588 if (transport == ADAPTER_BREDR && (state == BTStateID::STATE_TURN_ON || state == BTStateID::STATE_TURN_OFF)) {
589 std::vector<std::string> permissions;
590 permissions.emplace_back(PERMISSIONS);
591 BluetoothHelper::BluetoothCommonEventHelper::PublishBluetoothStateChangeEvent(state, permissions);
592 }
593 }
594
OnAdapterStateChange(const BTTransport transport,const BTStateID state) const595 void AdapterManager::OnAdapterStateChange(const BTTransport transport, const BTStateID state) const
596 {
597 LOG_DEBUG("%{public}s transport is %{public}d state is %{public}d", __PRETTY_FUNCTION__, transport, state);
598 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
599
600 if ((transport == ADAPTER_BREDR && pimpl->classicAdapter_ == nullptr) ||
601 (transport == ADAPTER_BLE && pimpl->bleAdapter_ == nullptr)) {
602 return;
603 }
604 if ((transport == ADAPTER_BLE) && (state == STATE_TURN_ON)) {
605 HILOGI("enable ADAPTER_BREDR");
606 Enable(ADAPTER_BREDR);
607 }
608 if ((transport == ADAPTER_BREDR) && (state == STATE_TURN_OFF)) {
609 HILOGI("disable ADAPTER_BLE");
610 Disable(ADAPTER_BLE);
611 }
612 // notify observers state update
613 auto &adapterState = transport == ADAPTER_BREDR ? pimpl->classicAdapter_->state : pimpl->bleAdapter_->state;
614 if (adapterState != state) {
615 adapterState = state;
616 if (GetSysState() != SYS_STATE_RESETTING) {
617 PublishBluetoothStateChangeEvent(transport, state);
618 pimpl->adapterObservers_.ForEach(
619 [transport, state](IAdapterStateObserver &observer) { observer.OnStateChange(transport, state); });
620 }
621 }
622
623 // notify sys state machine
624 int classicState = pimpl->classicAdapter_ ? pimpl->classicAdapter_->state : BTStateID::STATE_TURN_OFF;
625 int bleState = pimpl->bleAdapter_ ? pimpl->bleAdapter_->state : BTStateID::STATE_TURN_OFF;
626
627 utility::Message msg(SysStateMachine::MSG_SYS_ADAPTER_STATE_CHANGE_REQ);
628 msg.arg1_ = ((unsigned int)classicState << CLASSIC_ENABLE_STATE_BIT) + bleState;
629 pimpl->dispatcher_->PostTask(std::bind(&utility::StateMachine::ProcessMessage, &(pimpl->sysStateMachine_), msg));
630 }
631
OnProfileServicesEnableComplete(const BTTransport transport,const bool ret) const632 void AdapterManager::OnProfileServicesEnableComplete(const BTTransport transport, const bool ret) const
633 {
634 LOG_DEBUG("%{public}s transport is %{public}d, ret is %{public}d", __PRETTY_FUNCTION__, transport, ret);
635
636 utility::Message msg(AdapterStateMachine::MSG_PROFILE_ENABLE_CMP, ret ? true : false);
637 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
638 }
639
OnProfileServicesDisableComplete(const BTTransport transport,const bool ret) const640 void AdapterManager::OnProfileServicesDisableComplete(const BTTransport transport, const bool ret) const
641 {
642 LOG_DEBUG("%{public}s transport is %{public}d, ret is %{public}d", __PRETTY_FUNCTION__, transport, ret);
643
644 utility::Message msg(AdapterStateMachine::MSG_PROFILE_DISABLE_CMP, ret ? true : false);
645 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::impl::ProcessMessage, pimpl.get(), transport, msg));
646 }
647
OnPairDevicesRemoved(const BTTransport transport,const std::vector<RawAddress> & devices) const648 void AdapterManager::OnPairDevicesRemoved(const BTTransport transport, const std::vector<RawAddress> &devices) const
649 {
650 pimpl->dispatcher_->PostTask(std::bind(&AdapterManager::RemoveDeviceProfileConfig, this, transport, devices));
651 }
652
RemoveDeviceProfileConfig(const BTTransport transport,const std::vector<RawAddress> & devices) const653 void AdapterManager::RemoveDeviceProfileConfig(
654 const BTTransport transport, const std::vector<RawAddress> &devices) const
655 {
656 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
657
658 std::vector<RawAddress> otherDevices {};
659 std::shared_ptr<IAdapter> otherAdapter =
660 (transport == BTTransport::ADAPTER_BREDR) ?
661 static_cast<std::shared_ptr<IAdapter>>(GetBleAdapterInterface()) :
662 static_cast<std::shared_ptr<IAdapter>>(GetClassicAdapterInterface());
663 if (otherAdapter) {
664 otherDevices = otherAdapter->GetPairedDevices();
665 }
666
667 for (auto &device : devices) {
668 if (std::find(otherDevices.begin(), otherDevices.end(), device) == otherDevices.end()) {
669 ProfileConfig::GetInstance()->RemoveAddr(device.GetAddress());
670 }
671 }
672 }
673
674 namespace {
675 template <typename T>
CreateAdapter(const std::string & adapterSection,const std::string & adapterName,utility::Dispatcher & dispatcher,utility::IContextCallback & callback)676 std::unique_ptr<AdapterInfo<T>> CreateAdapter(const std::string &adapterSection, const std::string &adapterName,
677 utility::Dispatcher &dispatcher, utility::IContextCallback &callback)
678 {
679 bool value = false;
680 std::unique_ptr<AdapterInfo<T>> adapterInfo = nullptr;
681 if (AdapterConfig::GetInstance()->GetValue(adapterSection, PROPERTY_IS_VALID, value) && value) {
682 std::shared_ptr<T> adapter(ClassCreator<T>::NewInstance(adapterName));
683 auto stateMachine = std::make_unique<AdapterStateMachine>(dispatcher);
684 if (adapter && stateMachine) {
685 adapter->GetContext()->Initialize();
686 adapter->GetContext()->RegisterCallback(callback);
687 stateMachine->Init(*adapter);
688 adapterInfo = std::make_unique<AdapterInfo<T>>(adapter, std::move(stateMachine));
689 } else {
690 LOG_ERROR("Create %{public}s failed", adapterName.c_str());
691 }
692 }
693 return adapterInfo;
694 }
695 } // namespace {}
696
CreateAdapters() const697 void AdapterManager::CreateAdapters() const
698 {
699 pimpl->classicAdapter_ = CreateAdapter<ClassicAdapter>(
700 SECTION_CLASSIC_ADAPTER, ADAPTER_NAME_CLASSIC, *pimpl->dispatcher_, *(pimpl->contextCallback_));
701 pimpl->bleAdapter_ = CreateAdapter<BleAdapter>(
702 SECTION_BLE_ADAPTER, ADAPTER_NAME_BLE, *pimpl->dispatcher_, *(pimpl->contextCallback_));
703 }
704
GetMaxNumConnectedAudioDevices() const705 int AdapterManager::GetMaxNumConnectedAudioDevices() const
706 {
707 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
708 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
709
710 int value = 0;
711 IAdapterConfig *config = AdapterConfig::GetInstance();
712
713 if (!config->GetValue(SECTION_A2DP_SRC_SERVICE, PROPERTY_MAX_CONNECTED_DEVICES, value)) {
714 HILOGE("%{public}s %{public}s not found", SECTION_A2DP_SRC_SERVICE.c_str(),
715 PROPERTY_MAX_CONNECTED_DEVICES.c_str());
716 }
717 return value;
718 }
719
SetPhonebookPermission(const std::string & address,BTPermissionType permission) const720 bool AdapterManager::SetPhonebookPermission(const std::string &address, BTPermissionType permission) const
721 {
722 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
723 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
724
725 IProfileConfig *config = ProfileConfig::GetInstance();
726 bool tmp = false;
727 switch (permission) {
728 case BTPermissionType::ACCESS_UNKNOWN:
729 return config->RemoveProperty(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_PERMISSION);
730 case BTPermissionType::ACCESS_ALLOWED:
731 tmp = true;
732 break;
733 case BTPermissionType::ACCESS_FORBIDDEN:
734 break;
735 default:
736 return false;
737 }
738 return config->SetValue(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_PERMISSION, tmp);
739 }
740
GetPhonebookPermission(const std::string & address) const741 BTPermissionType AdapterManager::GetPhonebookPermission(const std::string &address) const
742 {
743 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
744 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
745
746 IProfileConfig *config = ProfileConfig::GetInstance();
747 bool value = false;
748
749 if (!config->GetValue(address, SECTION_PERMISSION, PROPERTY_PHONEBOOK_PERMISSION, value)) {
750 HILOGE("%{public}s %{public}s not found", GetEncryptAddr(address).c_str(),
751 PROPERTY_PHONEBOOK_PERMISSION.c_str());
752 return BTPermissionType::ACCESS_UNKNOWN;
753 }
754
755 if (value) {
756 return BTPermissionType::ACCESS_ALLOWED;
757 } else {
758 return BTPermissionType::ACCESS_FORBIDDEN;
759 }
760 }
761
SetMessagePermission(const std::string & address,BTPermissionType permission) const762 bool AdapterManager::SetMessagePermission(const std::string &address, BTPermissionType permission) const
763 {
764 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
765 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
766
767 IProfileConfig *config = ProfileConfig::GetInstance();
768 bool tmp = false;
769
770 switch (permission) {
771 case BTPermissionType::ACCESS_UNKNOWN:
772 return config->RemoveProperty(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION);
773 case BTPermissionType::ACCESS_ALLOWED:
774 tmp = true;
775 break;
776 case BTPermissionType::ACCESS_FORBIDDEN:
777 break;
778 default:
779 return false;
780 }
781 return config->SetValue(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION, tmp);
782 }
783
GetMessagePermission(const std::string & address) const784 BTPermissionType AdapterManager::GetMessagePermission(const std::string &address) const
785 {
786 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
787 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
788
789 IProfileConfig *config = ProfileConfig::GetInstance();
790 bool value = false;
791
792 if (!config->GetValue(address, SECTION_PERMISSION, PROPERTY_MESSAGE_PERMISSION, value)) {
793 HILOGE("%{public}s %{public}s not found", GetEncryptAddr(address).c_str(),
794 PROPERTY_MESSAGE_PERMISSION.c_str());
795 return BTPermissionType::ACCESS_UNKNOWN;
796 }
797
798 if (value) {
799 return BTPermissionType::ACCESS_ALLOWED;
800 } else {
801 return BTPermissionType::ACCESS_FORBIDDEN;
802 }
803 }
804
GetPowerMode(const std::string & address) const805 int AdapterManager::GetPowerMode(const std::string &address) const
806 {
807 LOG_DEBUG("%{public}s start", __PRETTY_FUNCTION__);
808 std::lock_guard<std::recursive_mutex> lock(pimpl->syncMutex_);
809
810 RawAddress addr = RawAddress(address);
811 return static_cast<int>(IPowerManager::GetInstance().GetPowerMode(addr));
812 }
813
RestoreTurnOnState()814 void AdapterManager::RestoreTurnOnState()
815 {
816 std::thread([this] {
817 static const std::array<std::pair<std::string, BTTransport>, TRANSPORT_MAX> adapterConfigTbl = {
818 std::make_pair(PROPERTY_BLE_TURNON, BTTransport::ADAPTER_BLE),
819 std::make_pair(PROPERTY_BREDR_TURNON, BTTransport::ADAPTER_BREDR),
820 };
821
822 auto classicAdapter = GetClassicAdapterInterface();
823 if (!classicAdapter) {
824 LOG_ERROR("classicAdapter is nullptr");
825 return;
826 }
827
828 while (true) {
829 sleep(1);
830
831 int processed = 0;
832 const unsigned char btStateFlag = 0;
833 int turnOn = 0;
834
835 AdapterDeviceConfig::GetInstance()->GetValue(SECTION_HOST, adapterConfigTbl[btStateFlag].first, turnOn);
836 LOG_INFO("restore turnon, %{public}s, %{public}d", adapterConfigTbl[btStateFlag].first.c_str(), turnOn);
837 for (int i = 0; i < TRANSPORT_MAX; i++) {
838 if (!turnOn) {
839 processed++;
840 continue;
841 }
842 if (GetState(adapterConfigTbl[i].second) != BTStateID::STATE_TURN_ON) {
843 Enable(adapterConfigTbl[i].second);
844 continue;
845 }
846
847 processed++;
848 if (adapterConfigTbl[i].second == BTTransport::ADAPTER_BREDR) {
849 classicAdapter->SetBtScanMode(SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 0);
850 classicAdapter->SetBondableMode(BONDABLE_MODE_ON);
851 }
852 }
853
854 if (processed == TRANSPORT_MAX) {
855 LOG_INFO("restore turnon thread END");
856 return;
857 }
858 }
859 }).detach();
860 }
861 } // namespace bluetooth
862 } // namespace OHOS
863