• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 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 #pragma once
18 
19 #include <map>
20 #include <mutex>
21 #include <thread>
22 
23 namespace android::hardware::bluetooth::async {
24 
25 using ReadCallback = std::function<void(int)>;
26 using TimeoutCallback = std::function<void(void)>;
27 
28 class AsyncFdWatcher {
29  public:
30   AsyncFdWatcher() = default;
31   ~AsyncFdWatcher();
32 
33   int WatchFdForNonBlockingReads(int file_descriptor,
34                                  const ReadCallback& on_read_fd_ready_callback);
35   int ConfigureTimeout(const std::chrono::milliseconds timeout,
36                        const TimeoutCallback& on_timeout_callback);
37   void StopWatchingFileDescriptors();
38 
39  private:
40   AsyncFdWatcher(const AsyncFdWatcher&) = delete;
41   AsyncFdWatcher& operator=(const AsyncFdWatcher&) = delete;
42 
43   int tryStartThread();
44   int stopThread();
45   int notifyThread();
46   void ThreadRoutine();
47 
48   std::atomic_bool running_{false};
49   std::thread thread_;
50   std::mutex internal_mutex_;
51   std::mutex timeout_mutex_;
52 
53   std::map<int, ReadCallback> watched_fds_;
54   int notification_listen_fd_;
55   int notification_write_fd_;
56   TimeoutCallback timeout_cb_;
57   std::chrono::milliseconds timeout_ms_;
58 };
59 
60 }  // namespace android::hardware::bluetooth::async
61