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
27namespace OHOS {
28namespace HDI {
29namespace Bluetooth {
30namespace Hci {
31class HciWatcher {
32public:
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
45private:
46    void WatcherThread();
47    void ThreadWakeup();
48
49private:
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 */