blob: 358cbc3d2d2dcad6f3313bbd247e6c5ed9b195c3 [file] [log] [blame]
Andre Eisenbach89ba5282016-10-13 15:45:02 -07001//
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
Myles Watsonf3a3cb72017-03-02 09:26:53 -080019#include <map>
Andre Eisenbach89ba5282016-10-13 15:45:02 -070020#include <mutex>
21#include <thread>
22
23namespace android {
24namespace hardware {
25namespace bluetooth {
Myles Watsonbe6176d2017-02-21 13:27:01 -080026namespace async {
Andre Eisenbach89ba5282016-10-13 15:45:02 -070027
28using ReadCallback = std::function<void(int)>;
Myles Watson7d42dca2017-01-24 16:51:39 -080029using TimeoutCallback = std::function<void(void)>;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070030
31class AsyncFdWatcher {
32 public:
33 AsyncFdWatcher() = default;
34 ~AsyncFdWatcher();
35
36 int WatchFdForNonBlockingReads(int file_descriptor,
37 const ReadCallback& on_read_fd_ready_callback);
Myles Watson7d42dca2017-01-24 16:51:39 -080038 int ConfigureTimeout(const std::chrono::milliseconds timeout,
39 const TimeoutCallback& on_timeout_callback);
Myles Watsonf3a3cb72017-03-02 09:26:53 -080040 void StopWatchingFileDescriptors();
Andre Eisenbach89ba5282016-10-13 15:45:02 -070041
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_;
Myles Watson7d42dca2017-01-24 16:51:39 -080054 std::mutex timeout_mutex_;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070055
Myles Watsonf3a3cb72017-03-02 09:26:53 -080056 std::map<int, ReadCallback> watched_fds_;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070057 int notification_listen_fd_;
58 int notification_write_fd_;
Myles Watson7d42dca2017-01-24 16:51:39 -080059 TimeoutCallback timeout_cb_;
60 std::chrono::milliseconds timeout_ms_;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070061};
62
63
Myles Watsonbe6176d2017-02-21 13:27:01 -080064} // namespace async
Andre Eisenbach89ba5282016-10-13 15:45:02 -070065} // namespace bluetooth
66} // namespace hardware
67} // namespace android