blob: d6e112fd68dbed233c66a51e013c32c55d718351 [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 {
25namespace V1_0 {
26namespace implementation {
27
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);
Andre Eisenbach89ba5282016-10-13 15:45:02 -070040 void StopWatchingFileDescriptor();
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_;
Myles Watson7d42dca2017-01-24 16:51:39 -080054 std::mutex timeout_mutex_;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070055
56 int read_fd_;
57 int notification_listen_fd_;
58 int notification_write_fd_;
59 ReadCallback cb_;
Myles Watson7d42dca2017-01-24 16:51:39 -080060 TimeoutCallback timeout_cb_;
61 std::chrono::milliseconds timeout_ms_;
Andre Eisenbach89ba5282016-10-13 15:45:02 -070062};
63
64
65} // namespace implementation
66} // namespace V1_0
67} // namespace bluetooth
68} // namespace hardware
69} // namespace android