2 * Copyright (C) 2013 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <hardware/sensors.h>
20 #include <cutils/log.h>
22 #include "SensorEventQueue.h"
24 SensorEventQueue::SensorEventQueue(int capacity
) {
29 mData
= new sensors_event_t
[mCapacity
];
30 pthread_cond_init(&mSpaceAvailableCondition
, NULL
);
33 SensorEventQueue::~SensorEventQueue() {
36 pthread_cond_destroy(&mSpaceAvailableCondition
);
39 int SensorEventQueue::getWritableRegion(int requestedLength
, sensors_event_t
** out
) {
40 if (mSize
== mCapacity
|| requestedLength
<= 0) {
44 // Start writing after the last readable record.
45 int firstWritable
= (mStart
+ mSize
) % mCapacity
;
47 int lastWritable
= firstWritable
+ requestedLength
- 1;
49 // Don't go past the end of the data array.
50 if (lastWritable
> mCapacity
- 1) {
51 lastWritable
= mCapacity
- 1;
53 // Don't go into the readable region.
54 if (firstWritable
< mStart
&& lastWritable
>= mStart
) {
55 lastWritable
= mStart
- 1;
57 *out
= &mData
[firstWritable
];
58 return lastWritable
- firstWritable
+ 1;
61 void SensorEventQueue::markAsWritten(int count
) {
65 int SensorEventQueue::getSize() {
69 sensors_event_t
* SensorEventQueue::peek() {
70 if (mSize
== 0) return NULL
;
71 return &mData
[mStart
];
74 void SensorEventQueue::dequeue() {
75 if (mSize
== 0) return;
76 if (mSize
== mCapacity
) {
77 pthread_cond_broadcast(&mSpaceAvailableCondition
);
80 mStart
= (mStart
+ 1) % mCapacity
;
83 // returns true if it waited, or false if it was a no-op.
84 bool SensorEventQueue::waitForSpace(pthread_mutex_t
* mutex
) {
86 while (mSize
== mCapacity
) {
88 pthread_cond_wait(&mSpaceAvailableCondition
, mutex
);