summaryrefslogtreecommitdiff
path: root/services/sensorservice/AidlSensorHalWrapper.cpp
blob: 91c2d1f3be5aed3ab0ebfeb2d61366b76a0be32d (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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
 * Copyright (C) 2021 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.
 */

#include "AidlSensorHalWrapper.h"
#include "ISensorsWrapper.h"
#include "SensorDeviceUtils.h"
#include "android/hardware/sensors/2.0/types.h"

#include <aidl/android/hardware/sensors/BnSensorsCallback.h>
#include <aidlcommonsupport/NativeHandle.h>
#include <android-base/logging.h>
#include <android/binder_manager.h>
#include <aidl/sensors/convert.h>

using ::aidl::android::hardware::sensors::AdditionalInfo;
using ::aidl::android::hardware::sensors::DynamicSensorInfo;
using ::aidl::android::hardware::sensors::Event;
using ::aidl::android::hardware::sensors::ISensors;
using ::aidl::android::hardware::sensors::SensorInfo;
using ::aidl::android::hardware::sensors::SensorStatus;
using ::aidl::android::hardware::sensors::SensorType;
using ::android::AidlMessageQueue;
using ::android::hardware::EventFlag;
using ::android::hardware::sensors::V2_1::implementation::MAX_RECEIVE_BUFFER_EVENT_COUNT;
using ::android::hardware::sensors::implementation::convertToStatus;
using ::android::hardware::sensors::implementation::convertToSensor;
using ::android::hardware::sensors::implementation::convertToSensorEvent;
using ::android::hardware::sensors::implementation::convertFromSensorEvent;


namespace android {

namespace {

void serviceDied(void *cookie) {
    ALOGW("Sensors HAL died, attempting to reconnect.");
    ((AidlSensorHalWrapper *)cookie)->prepareForReconnect();
}

template <typename EnumType>
constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
    return static_cast<typename std::underlying_type<EnumType>::type>(value);
}

enum EventQueueFlagBitsInternal : uint32_t {
    INTERNAL_WAKE = 1 << 16,
};

} // anonymous namespace

class AidlSensorsCallback : public ::aidl::android::hardware::sensors::BnSensorsCallback {
public:
    AidlSensorsCallback(AidlSensorHalWrapper::SensorDeviceCallback *sensorDeviceCallback)
          : mSensorDeviceCallback(sensorDeviceCallback) {}

    ::ndk::ScopedAStatus onDynamicSensorsConnected(
            const std::vector<SensorInfo> &sensorInfos) override {
        std::vector<sensor_t> sensors;
        for (const SensorInfo &sensorInfo : sensorInfos) {
            sensor_t sensor;
            convertToSensor(sensorInfo, &sensor);
            sensors.push_back(sensor);
        }

        mSensorDeviceCallback->onDynamicSensorsConnected(sensors);
        return ::ndk::ScopedAStatus::ok();
    }

    ::ndk::ScopedAStatus onDynamicSensorsDisconnected(
            const std::vector<int32_t> &sensorHandles) override {
        mSensorDeviceCallback->onDynamicSensorsDisconnected(sensorHandles);
        return ::ndk::ScopedAStatus::ok();
    }

private:
    ISensorHalWrapper::SensorDeviceCallback *mSensorDeviceCallback;
};

AidlSensorHalWrapper::AidlSensorHalWrapper()
      : mEventQueueFlag(nullptr),
        mWakeLockQueueFlag(nullptr),
        mDeathRecipient(AIBinder_DeathRecipient_new(serviceDied)) {}

bool AidlSensorHalWrapper::supportsPolling() {
    return false;
}

bool AidlSensorHalWrapper::supportsMessageQueues() {
    return true;
}

bool AidlSensorHalWrapper::connect(SensorDeviceCallback *callback) {
    mSensorDeviceCallback = callback;
    mSensors = nullptr;

    auto aidlServiceName = std::string() + ISensors::descriptor + "/default";
    if (AServiceManager_isDeclared(aidlServiceName.c_str())) {
        if (mSensors != nullptr) {
            AIBinder_unlinkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
        }

        ndk::SpAIBinder binder(AServiceManager_waitForService(aidlServiceName.c_str()));
        if (binder.get() != nullptr) {
            mSensors = ISensors::fromBinder(binder);
            mEventQueue = std::make_unique<AidlMessageQueue<
                    Event, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
                                                   /*configureEventFlagWord=*/true);

            mWakeLockQueue = std::make_unique<AidlMessageQueue<
                    int32_t, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
                                                     /*configureEventFlagWord=*/true);
            if (mEventQueueFlag != nullptr) {
                EventFlag::deleteEventFlag(&mEventQueueFlag);
            }
            EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
            if (mWakeLockQueueFlag != nullptr) {
                EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
            }
            EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakeLockQueueFlag);

            CHECK(mEventQueue != nullptr && mEventQueueFlag != nullptr &&
                  mWakeLockQueue != nullptr && mWakeLockQueueFlag != nullptr);

            mCallback = ndk::SharedRefBase::make<AidlSensorsCallback>(mSensorDeviceCallback);
            mSensors->initialize(mEventQueue->dupeDesc(), mWakeLockQueue->dupeDesc(), mCallback);

            AIBinder_linkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
        } else {
            ALOGE("Could not connect to declared sensors AIDL HAL");
        }
    }

    return mSensors != nullptr;
}

void AidlSensorHalWrapper::prepareForReconnect() {
    mReconnecting = true;
    if (mEventQueueFlag != nullptr) {
        mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
    }
}

ssize_t AidlSensorHalWrapper::poll(sensors_event_t * /* buffer */, size_t /* count */) {
    return 0;
}

ssize_t AidlSensorHalWrapper::pollFmq(sensors_event_t *buffer, size_t maxNumEventsToRead) {
    ssize_t eventsRead = 0;
    size_t availableEvents = mEventQueue->availableToRead();

    if (availableEvents == 0) {
        uint32_t eventFlagState = 0;

        // Wait for events to become available. This is necessary so that the Event FMQ's read() is
        // able to be called with the correct number of events to read. If the specified number of
        // events is not available, then read() would return no events, possibly introducing
        // additional latency in delivering events to applications.
        if (mEventQueueFlag != nullptr) {
            mEventQueueFlag->wait(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_READ_AND_PROCESS) |
                                          asBaseType(INTERNAL_WAKE),
                                  &eventFlagState);
        }
        availableEvents = mEventQueue->availableToRead();

        if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
            ALOGD("Event FMQ internal wake, returning from poll with no events");
            return DEAD_OBJECT;
        } else if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mInHalBypassMode &&
                   availableEvents == 0) {
            ALOGD("Event FMQ internal wake due to HAL Bypass Mode, returning from poll with no "
                  "events");
            return OK;
        }
    }

    size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
    if (eventsToRead > 0) {
        if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
            // Notify the Sensors HAL that sensor events have been read. This is required to support
            // the use of writeBlocking by the Sensors HAL.
            if (mEventQueueFlag != nullptr) {
                mEventQueueFlag->wake(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_EVENTS_READ));
            }

            for (size_t i = 0; i < eventsToRead; i++) {
                convertToSensorEvent(mEventBuffer[i], &buffer[i]);
            }
            eventsRead = eventsToRead;
        } else {
            ALOGW("Failed to read %zu events, currently %zu events available", eventsToRead,
                  availableEvents);
        }
    }

    return eventsRead;
}

std::vector<sensor_t> AidlSensorHalWrapper::getSensorsList() {
    std::vector<sensor_t> sensorsFound;

    if (mSensors != nullptr) {
        std::vector<SensorInfo> list;
        mSensors->getSensorsList(&list);
        for (size_t i = 0; i < list.size(); i++) {
            sensor_t sensor;
            convertToSensor(list[i], &sensor);
            sensorsFound.push_back(sensor);
        }
    }

    return sensorsFound;
}

status_t AidlSensorHalWrapper::setOperationMode(SensorService::Mode mode) {
    if (mSensors == nullptr) return NO_INIT;
    if (mode == SensorService::Mode::HAL_BYPASS_REPLAY_DATA_INJECTION) {
        if (!mInHalBypassMode) {
            mInHalBypassMode = true;
            mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
        }
        return OK;
    } else {
        if (mInHalBypassMode) {
            mInHalBypassMode = false;
        }
    }
    return convertToStatus(mSensors->setOperationMode(static_cast<ISensors::OperationMode>(mode)));
}

status_t AidlSensorHalWrapper::activate(int32_t sensorHandle, bool enabled) {
    if (mSensors == nullptr) return NO_INIT;
    return convertToStatus(mSensors->activate(sensorHandle, enabled));
}

status_t AidlSensorHalWrapper::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
                                     int64_t maxReportLatencyNs) {
    if (mSensors == nullptr) return NO_INIT;
    return convertToStatus(mSensors->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs));
}

status_t AidlSensorHalWrapper::flush(int32_t sensorHandle) {
    if (mSensors == nullptr) return NO_INIT;
    return convertToStatus(mSensors->flush(sensorHandle));
}

status_t AidlSensorHalWrapper::injectSensorData(const sensors_event_t *event) {
    if (mSensors == nullptr) return NO_INIT;

    Event ev;
    convertFromSensorEvent(*event, &ev);
    return convertToStatus(mSensors->injectSensorData(ev));
}

status_t AidlSensorHalWrapper::registerDirectChannel(const sensors_direct_mem_t *memory,
                                                     int32_t *channelHandle) {
    if (mSensors == nullptr) return NO_INIT;

    ISensors::SharedMemInfo::SharedMemType type;
    switch (memory->type) {
        case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
            type = ISensors::SharedMemInfo::SharedMemType::ASHMEM;
            break;
        case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
            type = ISensors::SharedMemInfo::SharedMemType::GRALLOC;
            break;
        default:
            return BAD_VALUE;
    }

    if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
        return BAD_VALUE;
    }
    ISensors::SharedMemInfo::SharedMemFormat format =
            ISensors::SharedMemInfo::SharedMemFormat::SENSORS_EVENT;

    ISensors::SharedMemInfo mem = {
            .type = type,
            .format = format,
            .size = static_cast<int32_t>(memory->size),
            .memoryHandle = dupToAidl(memory->handle),
    };

    return convertToStatus(mSensors->registerDirectChannel(mem, channelHandle));
}

status_t AidlSensorHalWrapper::unregisterDirectChannel(int32_t channelHandle) {
    if (mSensors == nullptr) return NO_INIT;
    return convertToStatus(mSensors->unregisterDirectChannel(channelHandle));
}

status_t AidlSensorHalWrapper::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
                                                      const struct sensors_direct_cfg_t *config) {
    if (mSensors == nullptr) return NO_INIT;

    ISensors::RateLevel rate;
    switch (config->rate_level) {
        case SENSOR_DIRECT_RATE_STOP:
            rate = ISensors::RateLevel::STOP;
            break;
        case SENSOR_DIRECT_RATE_NORMAL:
            rate = ISensors::RateLevel::NORMAL;
            break;
        case SENSOR_DIRECT_RATE_FAST:
            rate = ISensors::RateLevel::FAST;
            break;
        case SENSOR_DIRECT_RATE_VERY_FAST:
            rate = ISensors::RateLevel::VERY_FAST;
            break;
        default:
            return BAD_VALUE;
    }

    int32_t token;
    status_t status = convertToStatus(
        mSensors->configDirectReport(sensorHandle, channelHandle, rate, &token));
    if (status == OK && rate != ISensors::RateLevel::STOP) {
        status = static_cast<status_t>(token);
    }
    return status;
}

void AidlSensorHalWrapper::writeWakeLockHandled(uint32_t count) {
    int signedCount = (int)count;
    if (mWakeLockQueue->write(&signedCount)) {
        mWakeLockQueueFlag->wake(asBaseType(ISensors::WAKE_LOCK_QUEUE_FLAG_BITS_DATA_WRITTEN));
    } else {
        ALOGW("Failed to write wake lock handled");
    }
}

} // namespace android