1 /*
2  * Copyright (C) 2021 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 #include "MultiPoll.h"
18 
19 namespace android::hardware::sensors::V2_1::subhal::implementation {
20 
MultiPoll(uint64_t periodMs)21 MultiPoll::MultiPoll(uint64_t periodMs) : mSamplingPeriodMs(periodMs) {}
22 
addDescriptor(int fd)23 void MultiPoll::addDescriptor(int fd) {
24     pollfd pfd{.fd = fd, .events = POLLIN, .revents = 0};
25     std::unique_lock<std::mutex> lck(mDescriptorsMutex);
26     mDescriptors.push_back(pfd);
27 }
28 
poll(OnPollIn in)29 int MultiPoll::poll(OnPollIn in) {
30     std::vector<pollfd> fds;
31     {
32         // make a copy so you don't need to lock for prolonged periods of time
33         std::unique_lock<std::mutex> lck(mDescriptorsMutex);
34         fds.assign(mDescriptors.begin(), mDescriptors.end());
35     }
36 
37     int err = ::poll(&fds[0], fds.size(), mSamplingPeriodMs);
38     if (err < 0) return err;
39 
40     for (const auto& fd : fds) {
41         if (fd.revents & POLLIN) {
42             in(fd.fd);
43         }
44     }
45 
46     return 0;
47 }
48 
49 }  // namespace android::hardware::sensors::V2_1::subhal::implementation
50