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