1 /*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "stack_manager.h"
18
19 #include <chrono>
20 #include <future>
21 #include <queue>
22
23 #include "common/bind.h"
24 #include "hal/hci_hal.h"
25 #include "module.h"
26 #include "os/handler.h"
27 #include "os/log.h"
28 #include "os/thread.h"
29
30 using ::bluetooth::os::Handler;
31 using ::bluetooth::os::Thread;
32
33 namespace bluetooth {
34
StartUp(ModuleList * modules,Thread * stack_thread)35 void StackManager::StartUp(ModuleList* modules, Thread* stack_thread) {
36 management_thread_ = new Thread("management_thread", Thread::Priority::NORMAL);
37 handler_ = new Handler(management_thread_);
38
39 std::promise<void> promise;
40 auto future = promise.get_future();
41 handler_->Post(common::BindOnce(&StackManager::handle_start_up, common::Unretained(this), modules, stack_thread,
42 std::move(promise)));
43
44 auto init_status = future.wait_for(std::chrono::seconds(3));
45 ASSERT_LOG(init_status == std::future_status::ready, "Can't start stack");
46
47 LOG_INFO("init complete");
48 }
49
handle_start_up(ModuleList * modules,Thread * stack_thread,std::promise<void> promise)50 void StackManager::handle_start_up(ModuleList* modules, Thread* stack_thread, std::promise<void> promise) {
51 registry_.Start(modules, stack_thread);
52 promise.set_value();
53 }
54
ShutDown()55 void StackManager::ShutDown() {
56 std::promise<void> promise;
57 auto future = promise.get_future();
58 handler_->Post(common::BindOnce(&StackManager::handle_shut_down, common::Unretained(this), std::move(promise)));
59
60 auto stop_status = future.wait_for(std::chrono::seconds(5));
61 ASSERT_LOG(stop_status == std::future_status::ready, "Can't stop stack");
62
63 handler_->Clear();
64 handler_->WaitUntilStopped(std::chrono::milliseconds(2000));
65 delete handler_;
66 delete management_thread_;
67 }
68
handle_shut_down(std::promise<void> promise)69 void StackManager::handle_shut_down(std::promise<void> promise) {
70 registry_.StopAll();
71 promise.set_value();
72 }
73
74 } // namespace bluetooth
75