1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_HDI_BLUETOOTH_HCI_WATCHER_H
17 #define OHOS_HDI_BLUETOOTH_HCI_WATCHER_H
18 
19 #include <atomic>
20 #include <ctime>
21 #include <functional>
22 #include <map>
23 #include <mutex>
24 #include <sys/time.h>
25 #include <thread>
26 
27 namespace OHOS {
28 namespace HDI {
29 namespace Bluetooth {
30 namespace Hci {
31 class HciWatcher {
32 public:
33     using HciDataCallback = std::function<void(int fd)>;
34     using TimeoutCallback = std::function<void()>;
35 
36     HciWatcher();
37     ~HciWatcher();
38 
39     bool AddFdToWatcher(int fd, HciDataCallback callback);
40     bool RemoveFdToWatcher(int fd);
41     bool SetTimeout(std::chrono::milliseconds timeout, TimeoutCallback callback);
42     bool Start();
43     bool Stop();
44 
45 private:
46     void WatcherThread();
47     void ThreadWakeup();
48 
49 private:
50     std::atomic_bool running_ = {false};
51     std::map<int, HciDataCallback> fds_;
52     std::mutex fdsMutex_;
53     int wakeupPipe_[2] = {0};
54     timeval timeoutTimer_ = {};
55     TimeoutCallback timeoutCallback_;
56     std::mutex timeoutMutex_;
57     std::thread thread_;
58 };
59 }  // namespace Hci
60 }  // namespace Bluetooth
61 }  // namespace HDI
62 }  // namespace OHOS
63 #endif /* OHOS_HDI_BLUETOOTH_HCI_WATCHER_H */