SensorEventQueue.cpp revision 92863c14b7d36f74ec715b45ca6adc8bf95dc87c
1/*
2 * Copyright (C) 2013 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 <hardware/sensors.h>
18#include <algorithm>
19#include <pthread.h>
20#include <linux/input.h>
21#include <cutils/log.h>
22
23#include "SensorEventQueue.h"
24
25SensorEventQueue::SensorEventQueue(int capacity) {
26    mCapacity = capacity;
27
28    mStart = 0;
29    mSize = 0;
30    mData = new sensors_event_t[mCapacity];
31    pthread_cond_init(&mSpaceAvailableCondition, NULL);
32}
33
34SensorEventQueue::~SensorEventQueue() {
35    delete[] mData;
36    mData = NULL;
37    pthread_cond_destroy(&mSpaceAvailableCondition);
38}
39
40int SensorEventQueue::getWritableRegion(int requestedLength, sensors_event_t** out) {
41    if (mSize == mCapacity || requestedLength <= 0) {
42        *out = NULL;
43        return 0;
44    }
45    // Start writing after the last readable record.
46    int firstWritable = (mStart + mSize) % mCapacity;
47
48    int lastWritable = firstWritable + requestedLength - 1;
49
50    // Don't go past the end of the data array.
51    if (lastWritable > mCapacity - 1) {
52        lastWritable = mCapacity - 1;
53    }
54    // Don't go into the readable region.
55    if (firstWritable < mStart && lastWritable >= mStart) {
56        lastWritable = mStart - 1;
57    }
58    *out = &mData[firstWritable];
59    return lastWritable - firstWritable + 1;
60}
61
62void SensorEventQueue::markAsWritten(int count) {
63    mSize += count;
64}
65
66int SensorEventQueue::getSize() {
67    return mSize;
68}
69
70sensors_event_t* SensorEventQueue::peek() {
71    if (mSize == 0) return NULL;
72    return &mData[mStart];
73}
74
75void SensorEventQueue::dequeue() {
76    if (mSize == 0) return;
77    if (mSize == mCapacity) {
78        pthread_cond_broadcast(&mSpaceAvailableCondition);
79    }
80    mSize--;
81    mStart = (mStart + 1) % mCapacity;
82}
83
84void SensorEventQueue::waitForSpace(pthread_mutex_t* mutex) {
85    while (mSize == mCapacity) {
86        pthread_cond_wait(&mSpaceAvailableCondition, mutex);
87    }
88}
89