blob: 3f7ff544ed35f7abfebbaef096e82b974d54e61f [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
19#include <mutex>
20#include <thread>
21
22namespace android {
23namespace hardware {
24namespace bluetooth {
Myles Watsonbe6176d2017-02-21 13:27:01 -080025namespace async {
Andre Eisenbach89ba5282016-10-13 15:45:02 -070026
27using ReadCallback = std::function<void(int)>;
Myles Watson7d42dca2017-01-24 16:51:39 -080028using TimeoutCallback = std::function<void(void)>;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070029
30class AsyncFdWatcher {
31 public:
32 AsyncFdWatcher() = default;
33 ~AsyncFdWatcher();
34
35 int WatchFdForNonBlockingReads(int file_descriptor,
36 const ReadCallback& on_read_fd_ready_callback);
Myles Watson7d42dca2017-01-24 16:51:39 -080037 int ConfigureTimeout(const std::chrono::milliseconds timeout,
38 const TimeoutCallback& on_timeout_callback);
Andre Eisenbach89ba5282016-10-13 15:45:02 -070039 void StopWatchingFileDescriptor();
40
41 private:
42 AsyncFdWatcher(const AsyncFdWatcher&) = delete;
43 AsyncFdWatcher& operator=(const AsyncFdWatcher&) = delete;
44
45 int tryStartThread();
46 int stopThread();
47 int notifyThread();
48 void ThreadRoutine();
49
50 std::atomic_bool running_{false};
51 std::thread thread_;
52 std::mutex internal_mutex_;
Myles Watson7d42dca2017-01-24 16:51:39 -080053 std::mutex timeout_mutex_;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070054
55 int read_fd_;
56 int notification_listen_fd_;
57 int notification_write_fd_;
58 ReadCallback cb_;
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