1 /*
2  * Copyright (C) 2022 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 #include "service.hpp"
17 
18 #include <android-base/logging.h>
19 #include <android/binder_manager.h>
20 #include <android/binder_process.h>
21 #include <utils/Log.h>
22 
23 namespace aidl {
24 namespace android {
25 namespace hardware {
26 namespace threadnetwork {
27 
Service(void)28 Service::Service(void) : mBinderFd(-1) {
29     binder_status_t status = ABinderProcess_setupPolling(&mBinderFd);
30     CHECK_EQ(status, ::STATUS_OK);
31     CHECK_GE(mBinderFd, 0);
32 }
33 
Update(otSysMainloopContext & context)34 void Service::Update(otSysMainloopContext& context) {
35     FD_SET(mBinderFd, &context.mReadFdSet);
36     context.mMaxFd = std::max(context.mMaxFd, mBinderFd);
37 }
38 
Process(const otSysMainloopContext & context)39 void Service::Process(const otSysMainloopContext& context) {
40     if (FD_ISSET(mBinderFd, &context.mReadFdSet)) {
41         ABinderProcess_handlePolledCommands();
42     }
43 }
44 
startLoop(void)45 void Service::startLoop(void) {
46     const struct timeval kPollTimeout = {1, 0};
47     otSysMainloopContext context;
48     int rval;
49 
50     ot::Posix::Mainloop::Manager::Get().Add(*this);
51 
52     while (true) {
53         context.mMaxFd = -1;
54         context.mTimeout = kPollTimeout;
55 
56         FD_ZERO(&context.mReadFdSet);
57         FD_ZERO(&context.mWriteFdSet);
58         FD_ZERO(&context.mErrorFdSet);
59 
60         ot::Posix::Mainloop::Manager::Get().Update(context);
61 
62         rval = select(context.mMaxFd + 1, &context.mReadFdSet, &context.mWriteFdSet,
63                       &context.mErrorFdSet, &context.mTimeout);
64 
65         if (rval >= 0) {
66             ot::Posix::Mainloop::Manager::Get().Process(context);
67         } else if (errno != EINTR) {
68             ALOGE("select() failed: %s", strerror(errno));
69             break;
70         }
71     }
72 }
73 }  // namespace threadnetwork
74 }  // namespace hardware
75 }  // namespace android
76 }  // namespace aidl
77