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
31 // TODO(b/369381361) Enfore -Wmissing-prototypes
32 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
33
34 using bluetooth::common::MessageLoopThread;
35 using BtMainClosure = std::function<void()>;
36
37 namespace {
38
39 MessageLoopThread main_thread("bt_test_main_thread");
do_post_on_bt_main(BtMainClosure closure)40 void do_post_on_bt_main(BtMainClosure closure) { closure(); }
41
42 } // namespace
43
do_in_main_thread(base::OnceClosure task)44 bt_status_t do_in_main_thread(base::OnceClosure task) {
45 bluetooth::log::assert_that(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(base::OnceClosure task,std::chrono::microseconds delay)50 bt_status_t do_in_main_thread_delayed(base::OnceClosure task, std::chrono::microseconds delay) {
51 bluetooth::log::assert_that(!main_thread.DoInThreadDelayed(FROM_HERE, std::move(task), delay),
52 "Unable to run on main thread delayed");
53 return BT_STATUS_SUCCESS;
54 }
55
post_on_bt_main(BtMainClosure closure)56 void post_on_bt_main(BtMainClosure closure) {
57 bluetooth::log::assert_that(do_in_main_thread(base::BindOnce(
58 do_post_on_bt_main, std::move(closure))) == BT_STATUS_SUCCESS,
59 "Unable to post on main thread");
60 }
61
main_thread_start_up()62 void main_thread_start_up() {
63 main_thread.StartUp();
64 bluetooth::log::assert_that(main_thread.IsRunning(),
65 "Unable to start message loop on main thread");
66 }
67
main_thread_shut_down()68 void main_thread_shut_down() { main_thread.ShutDown(); }
69
70 // osi_alarm
get_main_thread()71 bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; }
72
get_main()73 bluetooth::common::PostableContext* get_main() { return main_thread.Postable(); }
74