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