summaryrefslogtreecommitdiff
path: root/services/sensorservice/aidl/SensorManager.cpp
blob: 9b0334443bb0d0b4bd6e2e64ca191c89f9d94fe5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// LOG_TAG defined via build flag.
#ifndef LOG_TAG
#define LOG_TAG "AidlSensorManager"
#endif

#include "DirectReportChannel.h"
#include "EventQueue.h"
#include "SensorManagerAidl.h"
#include "utils.h"

#include <aidl/android/hardware/sensors/ISensors.h>
#include <android-base/logging.h>
#include <android/binder_ibinder.h>
#include <sched.h>

namespace android {
namespace frameworks {
namespace sensorservice {
namespace implementation {

using ::aidl::android::frameworks::sensorservice::IDirectReportChannel;
using ::aidl::android::frameworks::sensorservice::IEventQueue;
using ::aidl::android::frameworks::sensorservice::IEventQueueCallback;
using ::aidl::android::frameworks::sensorservice::ISensorManager;
using ::aidl::android::hardware::common::Ashmem;
using ::aidl::android::hardware::sensors::ISensors;
using ::aidl::android::hardware::sensors::SensorInfo;
using ::aidl::android::hardware::sensors::SensorType;
using ::android::frameworks::sensorservice::implementation::SensorManagerAidl;

static const char* POLL_THREAD_NAME = "aidl_ssvc_poll";

SensorManagerAidl::SensorManagerAidl(JavaVM* vm)
      : mLooper(new Looper(false)), mStopThread(true), mJavaVm(vm) {}
SensorManagerAidl::~SensorManagerAidl() {
    // Stops pollAll inside the thread.
    std::lock_guard<std::mutex> lock(mThreadMutex);

    mStopThread = true;
    if (mLooper != nullptr) {
        mLooper->wake();
    }
    if (mPollThread.joinable()) {
        mPollThread.join();
    }
}

ndk::ScopedAStatus createDirectChannel(::android::SensorManager& manager, size_t size, int type,
                                       const native_handle_t* handle,
                                       std::shared_ptr<IDirectReportChannel>* chan) {
    int channelId = manager.createDirectChannel(size, type, handle);
    if (channelId < 0) {
        return convertResult(channelId);
    }
    if (channelId == 0) {
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_UNKNOWN_ERROR);
    }
    *chan = ndk::SharedRefBase::make<DirectReportChannel>(manager, channelId);
    return ndk::ScopedAStatus::ok();
}

ndk::ScopedAStatus SensorManagerAidl::createAshmemDirectChannel(
        const Ashmem& in_mem, int64_t in_size,
        std::shared_ptr<IDirectReportChannel>* _aidl_return) {
    if (in_size > in_mem.size || in_size < ISensors::DIRECT_REPORT_SENSOR_EVENT_TOTAL_LENGTH) {
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_BAD_VALUE);
    }
    native_handle_t* handle = native_handle_create(1, 0);
    handle->data[0] = dup(in_mem.fd.get());

    auto status = createDirectChannel(getInternalManager(), in_size, SENSOR_DIRECT_MEM_TYPE_ASHMEM,
                                      handle, _aidl_return);
    int result = native_handle_close(handle);
    CHECK(result == 0) << "Failed to close the native_handle_t: " << result;
    result = native_handle_delete(handle);
    CHECK(result == 0) << "Failed to delete the native_handle_t: " << result;

    return status;
}

ndk::ScopedAStatus SensorManagerAidl::createGrallocDirectChannel(
        const ndk::ScopedFileDescriptor& in_mem, int64_t in_size,
        std::shared_ptr<IDirectReportChannel>* _aidl_return) {
    native_handle_t* handle = native_handle_create(1, 0);
    handle->data[0] = dup(in_mem.get());

    auto status = createDirectChannel(getInternalManager(), in_size, SENSOR_DIRECT_MEM_TYPE_GRALLOC,
                                      handle, _aidl_return);
    int result = native_handle_close(handle);
    CHECK(result == 0) << "Failed to close the native_handle_t: " << result;
    result = native_handle_delete(handle);
    CHECK(result == 0) << "Failed to delete the native_handle_t: " << result;

    return status;
}

ndk::ScopedAStatus SensorManagerAidl::createEventQueue(
        const std::shared_ptr<IEventQueueCallback>& in_callback,
        std::shared_ptr<IEventQueue>* _aidl_return) {
    if (in_callback == nullptr) {
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_BAD_VALUE);
    }

    sp<::android::Looper> looper = getLooper();
    if (looper == nullptr) {
        LOG(ERROR) << "::android::SensorManagerAidl::createEventQueue cannot initialize looper";
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_UNKNOWN_ERROR);
    }

    String8 package(String8::format("aidl_client_pid_%d", AIBinder_getCallingPid()));
    sp<::android::SensorEventQueue> internalQueue = getInternalManager().createEventQueue(package);
    if (internalQueue == nullptr) {
        LOG(ERROR) << "::android::SensorManagerAidl::createEventQueue returns nullptr.";
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_UNKNOWN_ERROR);
    }

    *_aidl_return = ndk::SharedRefBase::make<EventQueue>(in_callback, looper, internalQueue);

    return ndk::ScopedAStatus::ok();
}

SensorInfo convertSensor(Sensor src) {
    SensorInfo dst;
    dst.sensorHandle = src.getHandle();
    dst.name = src.getName();
    dst.vendor = src.getVendor();
    dst.version = src.getVersion();
    dst.type = static_cast<SensorType>(src.getType());
    dst.typeAsString = src.getStringType();
    // maxRange uses maxValue because ::android::Sensor wraps the
    // internal sensor_t in this way.
    dst.maxRange = src.getMaxValue();
    dst.resolution = src.getResolution();
    dst.power = src.getPowerUsage();
    dst.minDelayUs = src.getMinDelay();
    dst.fifoReservedEventCount = src.getFifoReservedEventCount();
    dst.fifoMaxEventCount = src.getFifoMaxEventCount();
    dst.requiredPermission = src.getRequiredPermission();
    dst.maxDelayUs = src.getMaxDelay();
    dst.flags = src.getFlags();
    return dst;
}

ndk::ScopedAStatus SensorManagerAidl::getDefaultSensor(SensorType in_type,
                                                       SensorInfo* _aidl_return) {
    ::android::Sensor const* sensor =
            getInternalManager().getDefaultSensor(static_cast<int>(in_type));
    if (!sensor) {
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_NOT_EXIST);
    }
    *_aidl_return = convertSensor(*sensor);
    return ndk::ScopedAStatus::ok();
}

ndk::ScopedAStatus SensorManagerAidl::getSensorList(std::vector<SensorInfo>* _aidl_return) {
    Sensor const* const* list;
    _aidl_return->clear();
    ssize_t count = getInternalManager().getSensorList(&list);
    if (count < 0 || list == nullptr) {
        LOG(ERROR) << "SensorMAanger::getSensorList failed with count: " << count;
        return ndk::ScopedAStatus::fromServiceSpecificError(ISensorManager::RESULT_UNKNOWN_ERROR);
    }
    _aidl_return->reserve(static_cast<size_t>(count));
    for (ssize_t i = 0; i < count; ++i) {
        _aidl_return->push_back(convertSensor(*list[i]));
    }

    return ndk::ScopedAStatus::ok();
}

::android::SensorManager& SensorManagerAidl::getInternalManager() {
    std::lock_guard<std::mutex> lock(mInternalManagerMutex);
    if (mInternalManager == nullptr) {
        mInternalManager = &::android::SensorManager::getInstanceForPackage(
                String16(ISensorManager::descriptor));
    }
    return *mInternalManager;
}

/* One global looper for all event queues created from this SensorManager. */
sp<Looper> SensorManagerAidl::getLooper() {
    std::lock_guard<std::mutex> lock(mThreadMutex);

    if (!mPollThread.joinable()) {
        // if thread not initialized, start thread
        mStopThread = false;
        std::thread pollThread{[&stopThread = mStopThread, looper = mLooper, javaVm = mJavaVm] {
            struct sched_param p = {};
            p.sched_priority = 10;
            if (sched_setscheduler(0 /* current thread*/, SCHED_FIFO, &p) != 0) {
                LOG(ERROR) << "Could not use SCHED_FIFO for looper thread: " << strerror(errno);
            }

            // set looper
            Looper::setForThread(looper);

            // Attach the thread to JavaVM so that pollAll do not crash if the thread
            // eventually calls into Java.
            JavaVMAttachArgs args{.version = JNI_VERSION_1_2,
                                  .name = POLL_THREAD_NAME,
                                  .group = nullptr};
            JNIEnv* env;
            if (javaVm->AttachCurrentThread(&env, &args) != JNI_OK) {
                LOG(FATAL) << "Cannot attach SensorManager looper thread to Java VM.";
            }

            LOG(INFO) << POLL_THREAD_NAME << " started.";
            for (;;) {
                int pollResult = looper->pollAll(-1 /* timeout */);
                if (pollResult == Looper::POLL_WAKE) {
                    if (stopThread == true) {
                        LOG(INFO) << POLL_THREAD_NAME << ": requested to stop";
                        break;
                    } else {
                        LOG(INFO) << POLL_THREAD_NAME << ": spurious wake up, back to work";
                    }
                } else {
                    LOG(ERROR) << POLL_THREAD_NAME << ": Looper::pollAll returns unexpected "
                               << pollResult;
                    break;
                }
            }

            if (javaVm->DetachCurrentThread() != JNI_OK) {
                LOG(ERROR) << "Cannot detach SensorManager looper thread from Java VM.";
            }

            LOG(INFO) << POLL_THREAD_NAME << " is terminated.";
        }};
        mPollThread = std::move(pollThread);
    }
    return mLooper;
}

} // namespace implementation
} // namespace sensorservice
} // namespace frameworks
} // namespace android