1 /*
2 * Copyright 2021 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 <base/functional/bind.h>
18 #include <base/functional/callback_forward.h>
19 #include <base/location.h>
20 #include <bluetooth/log.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <functional>
25 #include <future>
26
27 #include "common/message_loop_thread.h"
28 #include "common/postable_context.h"
29 #include "include/hardware/bluetooth.h"
30 #include "os/log.h"
31
32 using bluetooth::common::MessageLoopThread;
33 using BtMainClosure = std::function<void()>;
34
35 namespace {
36
37 MessageLoopThread main_thread("bt_test_main_thread");
do_post_on_bt_main(BtMainClosure closure)38 void do_post_on_bt_main(BtMainClosure closure) { closure(); }
39
40 } // namespace
41
do_in_main_thread(const base::Location & from_here,base::OnceClosure task)42 bt_status_t do_in_main_thread(const base::Location& from_here,
43 base::OnceClosure task) {
44 bluetooth::log::assert_that(
45 main_thread.DoInThread(from_here, std::move(task)),
46 "Unable to run on main thread");
47 return BT_STATUS_SUCCESS;
48 }
49
do_in_main_thread_delayed(const base::Location & from_here,base::OnceClosure task,std::chrono::microseconds delay)50 bt_status_t do_in_main_thread_delayed(const base::Location& from_here,
51 base::OnceClosure task,
52 std::chrono::microseconds delay) {
53 bluetooth::log::assert_that(
54 !main_thread.DoInThreadDelayed(from_here, std::move(task), delay),
55 "Unable to run on main thread delayed");
56 return BT_STATUS_SUCCESS;
57 }
58
post_on_bt_main(BtMainClosure closure)59 void post_on_bt_main(BtMainClosure closure) {
60 bluetooth::log::assert_that(
61 do_in_main_thread(
62 FROM_HERE, base::BindOnce(do_post_on_bt_main, std::move(closure))) ==
63 BT_STATUS_SUCCESS,
64 "Unable to post on main thread");
65 }
66
main_thread_start_up()67 void main_thread_start_up() {
68 main_thread.StartUp();
69 bluetooth::log::assert_that(main_thread.IsRunning(),
70 "Unable to start message loop on main thread");
71 }
72
main_thread_shut_down()73 void main_thread_shut_down() { main_thread.ShutDown(); }
74
75 // osi_alarm
get_main_thread()76 bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; }
77
get_main()78 bluetooth::common::PostableContext* get_main() {
79 return main_thread.Postable();
80 }
81