1/*
2 * Copyright (C) 2010 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#define LOG_TAG "Sensors"
18
19#include <sensor/SensorEventQueue.h>
20
21#include <algorithm>
22#include <sys/socket.h>
23
24#include <utils/RefBase.h>
25#include <utils/Looper.h>
26
27#include <sensor/Sensor.h>
28#include <sensor/BitTube.h>
29#include <sensor/ISensorEventConnection.h>
30
31#include <android/sensor.h>
32
33using std::min;
34
35// ----------------------------------------------------------------------------
36namespace android {
37// ----------------------------------------------------------------------------
38
39SensorEventQueue::SensorEventQueue(const sp<ISensorEventConnection>& connection)
40    : mSensorEventConnection(connection), mRecBuffer(NULL), mAvailable(0), mConsumed(0),
41      mNumAcksToSend(0) {
42    mRecBuffer = new ASensorEvent[MAX_RECEIVE_BUFFER_EVENT_COUNT];
43}
44
45SensorEventQueue::~SensorEventQueue() {
46    delete [] mRecBuffer;
47}
48
49void SensorEventQueue::onFirstRef()
50{
51    mSensorChannel = mSensorEventConnection->getSensorChannel();
52}
53
54int SensorEventQueue::getFd() const
55{
56    return mSensorChannel->getFd();
57}
58
59
60ssize_t SensorEventQueue::write(const sp<BitTube>& tube,
61        ASensorEvent const* events, size_t numEvents) {
62    return BitTube::sendObjects(tube, events, numEvents);
63}
64
65ssize_t SensorEventQueue::read(ASensorEvent* events, size_t numEvents) {
66    if (mAvailable == 0) {
67        ssize_t err = BitTube::recvObjects(mSensorChannel,
68                mRecBuffer, MAX_RECEIVE_BUFFER_EVENT_COUNT);
69        if (err < 0) {
70            return err;
71        }
72        mAvailable = static_cast<size_t>(err);
73        mConsumed = 0;
74    }
75    size_t count = min(numEvents, mAvailable);
76    memcpy(events, mRecBuffer + mConsumed, count * sizeof(ASensorEvent));
77    mAvailable -= count;
78    mConsumed += count;
79    return static_cast<ssize_t>(count);
80}
81
82sp<Looper> SensorEventQueue::getLooper() const
83{
84    Mutex::Autolock _l(mLock);
85    if (mLooper == 0) {
86        mLooper = new Looper(true);
87        mLooper->addFd(getFd(), getFd(), ALOOPER_EVENT_INPUT, NULL, NULL);
88    }
89    return mLooper;
90}
91
92status_t SensorEventQueue::waitForEvent() const
93{
94    const int fd = getFd();
95    sp<Looper> looper(getLooper());
96
97    int events;
98    int32_t result;
99    do {
100        result = looper->pollOnce(-1, NULL, &events, NULL);
101        if (result == ALOOPER_POLL_ERROR) {
102            ALOGE("SensorEventQueue::waitForEvent error (errno=%d)", errno);
103            result = -EPIPE; // unknown error, so we make up one
104            break;
105        }
106        if (events & ALOOPER_EVENT_HANGUP) {
107            // the other-side has died
108            ALOGE("SensorEventQueue::waitForEvent error HANGUP");
109            result = -EPIPE; // unknown error, so we make up one
110            break;
111        }
112    } while (result != fd);
113
114    return  (result == fd) ? status_t(NO_ERROR) : result;
115}
116
117status_t SensorEventQueue::wake() const
118{
119    sp<Looper> looper(getLooper());
120    looper->wake();
121    return NO_ERROR;
122}
123
124status_t SensorEventQueue::enableSensor(Sensor const* sensor) const {
125    return enableSensor(sensor, SENSOR_DELAY_NORMAL);
126}
127
128status_t SensorEventQueue::enableSensor(Sensor const* sensor, int32_t samplingPeriodUs) const {
129    return mSensorEventConnection->enableDisable(sensor->getHandle(), true,
130                                                 us2ns(samplingPeriodUs), 0, 0);
131}
132
133status_t SensorEventQueue::disableSensor(Sensor const* sensor) const {
134    return mSensorEventConnection->enableDisable(sensor->getHandle(), false, 0, 0, 0);
135}
136
137status_t SensorEventQueue::enableSensor(int32_t handle, int32_t samplingPeriodUs,
138                                        int64_t maxBatchReportLatencyUs, int reservedFlags) const {
139    return mSensorEventConnection->enableDisable(handle, true, us2ns(samplingPeriodUs),
140                                                 us2ns(maxBatchReportLatencyUs), reservedFlags);
141}
142
143status_t SensorEventQueue::flush() const {
144    return mSensorEventConnection->flush();
145}
146
147status_t SensorEventQueue::disableSensor(int32_t handle) const {
148    return mSensorEventConnection->enableDisable(handle, false, 0, 0, false);
149}
150
151status_t SensorEventQueue::setEventRate(Sensor const* sensor, nsecs_t ns) const {
152    return mSensorEventConnection->setEventRate(sensor->getHandle(), ns);
153}
154
155status_t SensorEventQueue::injectSensorEvent(const ASensorEvent& event) {
156    do {
157        // Blocking call.
158        ssize_t size = ::send(mSensorChannel->getFd(), &event, sizeof(event), MSG_NOSIGNAL);
159        if (size >= 0) {
160            return NO_ERROR;
161        } else if (size < 0 && errno == EAGAIN) {
162            // If send is returning a "Try again" error, sleep for 100ms and try again. In all
163            // other cases log a failure and exit.
164            usleep(100000);
165        } else {
166            ALOGE("injectSensorEvent failure %s %zd", strerror(errno), size);
167            return INVALID_OPERATION;
168        }
169    } while (true);
170}
171
172void SensorEventQueue::sendAck(const ASensorEvent* events, int count) {
173    for (int i = 0; i < count; ++i) {
174        if (events[i].flags & WAKE_UP_SENSOR_EVENT_NEEDS_ACK) {
175            ++mNumAcksToSend;
176        }
177    }
178    // Send mNumAcksToSend to acknowledge for the wake up sensor events received.
179    if (mNumAcksToSend > 0) {
180        ssize_t size = ::send(mSensorChannel->getFd(), &mNumAcksToSend, sizeof(mNumAcksToSend),
181                MSG_DONTWAIT | MSG_NOSIGNAL);
182        if (size < 0) {
183            ALOGE("sendAck failure %zd %d", size, mNumAcksToSend);
184        } else {
185            mNumAcksToSend = 0;
186        }
187    }
188    return;
189}
190
191// ----------------------------------------------------------------------------
192}; // namespace android
193
194