SensorService.cpp revision 08f04bf36c3f5d2e91de5525dfce778e56464fc2
1e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard/*
2e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * Copyright (C) 2010 The Android Open Source Project
3e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard *
4e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * Licensed under the Apache License, Version 2.0 (the "License");
5e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * you may not use this file except in compliance with the License.
6e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * You may obtain a copy of the License at
7e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard *
8e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard *      http://www.apache.org/licenses/LICENSE-2.0
9e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard *
10e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * Unless required by applicable law or agreed to in writing, software
11e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * distributed under the License is distributed on an "AS IS" BASIS,
12e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * See the License for the specific language governing permissions and
14e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * limitations under the License.
15e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard */
16e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
17e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <inttypes.h>
18e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <math.h>
19e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <stdint.h>
20e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <sys/types.h>
21956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <sys/socket.h>
22956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
23e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <cutils/properties.h>
24956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
25956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <utils/SortedVector.h>
26956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <utils/KeyedVector.h>
27e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <utils/threads.h>
28e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <utils/Atomic.h>
29e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <utils/Errors.h>
30e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <utils/RefBase.h>
31e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <utils/Singleton.h>
32e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <utils/String16.h>
33e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
34b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard#include <binder/BinderService.h>
35956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <binder/IServiceManager.h>
36956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <binder/PermissionCache.h>
37956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
38956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <gui/ISensorServer.h>
39956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <gui/ISensorEventConnection.h>
40956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong#include <gui/SensorEventQueue.h>
41956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
42e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <hardware/sensors.h>
43e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include <hardware_legacy/power.h>
44e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
45e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "BatteryService.h"
46e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "CorrectedGyroSensor.h"
47e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "GravitySensor.h"
48e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "LinearAccelerationSensor.h"
49e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "OrientationSensor.h"
50b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard#include "RotationVectorSensor.h"
51e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "SensorFusion.h"
52e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard#include "SensorService.h"
53e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
54b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgardnamespace android {
55b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard// ---------------------------------------------------------------------------
56b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
57b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard/*
58e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * Notes:
59e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard *
60e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * - what about a gyro-corrected magnetic-field sensor?
61b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard * - run mag sensor from time to time to force calibration
62e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard *
64e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard */
65e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
66956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongconst char* SensorService::WAKE_LOCK_NAME = "SensorService";
67956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong// Permissions.
68956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongstatic const String16 sDataInjectionPermission("android.permission.HARDWARE_TEST");
69956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongstatic const String16 sDump("android.permission.DUMP");
70956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
71956c553ab0ce72f8074ad0fda2ffd66a0305700cJames DongSensorService::SensorService()
72e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
73e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard      mWakeLockAcquired(false)
74e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard{
75e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard}
76e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
77b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgardvoid SensorService::onFirstRef()
78b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard{
79e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    ALOGD("nuSensorService starting...");
80e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    SensorDevice& dev(SensorDevice::getInstance());
81e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
82e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    if (dev.initCheck() == NO_ERROR) {
83e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        sensor_t const* list;
84e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        ssize_t count = dev.getSensorList(&list);
85e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        if (count > 0) {
86e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            ssize_t orientationIndex = -1;
87e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            bool hasGyro = false;
88e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            uint32_t virtualSensorsNeeds =
89e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    (1<<SENSOR_TYPE_GRAVITY) |
90e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
91e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    (1<<SENSOR_TYPE_ROTATION_VECTOR);
92e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
93e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mLastEventSeen.setCapacity(count);
94e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            for (ssize_t i=0 ; i<count ; i++) {
95e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                registerSensor( new HardwareSensor(list[i]) );
96e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                switch (list[i].type) {
97e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    case SENSOR_TYPE_ORIENTATION:
98e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                        orientationIndex = i;
99e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                        break;
100e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    case SENSOR_TYPE_GYROSCOPE:
101e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
102956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        hasGyro = true;
103956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        break;
104956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    case SENSOR_TYPE_GRAVITY:
105956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    case SENSOR_TYPE_LINEAR_ACCELERATION:
106956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    case SENSOR_TYPE_ROTATION_VECTOR:
107e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                        virtualSensorsNeeds &= ~(1<<list[i].type);
108e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                        break;
109e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
110e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
111e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
112e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // it's safe to instantiate the SensorFusion object here
113e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // (it wants to be instantiated after h/w sensors have been
114e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // registered)
115e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            const SensorFusion& fusion(SensorFusion::getInstance());
116b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
117e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // build the sensor list returned to users
118e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mUserSensorList = mSensorList;
119e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
120e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            if (hasGyro) {
121e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                Sensor aSensor;
122e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
123e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                // Add Android virtual sensors if they're not already
124e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                // available in the HAL
125e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
126e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                aSensor = registerVirtualSensor( new RotationVectorSensor() );
127e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
128e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    mUserSensorList.add(aSensor);
129e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
130e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
131e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                aSensor = registerVirtualSensor( new GravitySensor(list, count) );
132e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
133e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    mUserSensorList.add(aSensor);
134e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
135e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
136e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
137e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
138e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    mUserSensorList.add(aSensor);
139e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
140e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
141e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                aSensor = registerVirtualSensor( new OrientationSensor() );
142e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
143e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    // if we are doing our own rotation-vector, also add
144e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    // the orientation sensor and remove the HAL provided one.
145e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    mUserSensorList.replaceAt(aSensor, orientationIndex);
146e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
147e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
148e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                // virtual debugging sensors are not added to mUserSensorList
149e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
150e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                registerVirtualSensor( new GyroDriftSensor() );
151e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
152e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
153e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // debugging sensor list
154e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mUserSensorListDebug = mSensorList;
155e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
156e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // Check if the device really supports batching by looking at the FIFO event
157e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // counts for each sensor.
158e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            bool batchingSupported = false;
159e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            for (int i = 0; i < mSensorList.size(); ++i) {
160e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                if (mSensorList[i].getFifoMaxEventCount() > 0) {
161e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    batchingSupported = true;
162e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    break;
163e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
164e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
165e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
166e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            if (batchingSupported) {
167e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                // Increase socket buffer size to a max of 100 KB for batching capabilities.
168e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
169e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            } else {
170e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
171e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
172e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
173e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // Compare the socketBufferSize value against the system limits and limit
174e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // it to maxSystemSocketBufferSize if necessary.
175e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
176e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            char line[128];
177e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
178e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                line[sizeof(line) - 1] = '\0';
179e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                size_t maxSystemSocketBufferSize;
180e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                sscanf(line, "%zu", &maxSystemSocketBufferSize);
181e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                if (mSocketBufferSize > maxSystemSocketBufferSize) {
182956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    mSocketBufferSize = maxSystemSocketBufferSize;
183956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                }
184956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
185956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (fp) {
186956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                fclose(fp);
187e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
188e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
189e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mWakeLockAcquired = false;
190e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mLooper = new Looper(false);
191e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
192e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mSensorEventBuffer = new sensors_event_t[minBufferSize];
193e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mSensorEventScratch = new sensors_event_t[minBufferSize];
194e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
195e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mCurrentOperatingMode = NORMAL;
196e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
197b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            mAckReceiver = new SensorEventAckReceiver(this);
198e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
199e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mInitCheck = NO_ERROR;
200e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            run("SensorService", PRIORITY_URGENT_DISPLAY);
201e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
202b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    }
203e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard}
204e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
205e2e838afcf03e603a41a0455846eaf9614537c16Mans RullgardSensor SensorService::registerSensor(SensorInterface* s)
206b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard{
207e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    sensors_event_t event;
208e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    memset(&event, 0, sizeof(event));
209e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
210e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    const Sensor sensor(s->getSensor());
211b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    // add to the sensor list (returned to clients)
212e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    mSensorList.add(sensor);
213b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    // add to our handle->SensorInterface mapping
214e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    mSensorMap.add(sensor.getHandle(), s);
215e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    // create an entry in the mLastEventSeen array
216e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    mLastEventSeen.add(sensor.getHandle(), event);
217e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
218e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    return sensor;
219e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard}
220e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
221e2e838afcf03e603a41a0455846eaf9614537c16Mans RullgardSensor SensorService::registerVirtualSensor(SensorInterface* s)
222e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard{
223e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    Sensor sensor = registerSensor(s);
224e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    mVirtualSensorList.add( s );
225e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    return sensor;
226b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard}
227e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
228e2e838afcf03e603a41a0455846eaf9614537c16Mans RullgardSensorService::~SensorService()
229e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard{
230e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    for (size_t i=0 ; i<mSensorMap.size() ; i++)
231e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        delete mSensorMap.valueAt(i);
232e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard}
233e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
234b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgardstatus_t SensorService::dump(int fd, const Vector<String16>& args)
235e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard{
236e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    String8 result;
237e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    if (!PermissionCache::checkCallingPermission(sDump)) {
238e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        result.appendFormat("Permission Denial: "
239e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                "can't dump SensorService from pid=%d, uid=%d\n",
240e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                IPCThreadState::self()->getCallingPid(),
241e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                IPCThreadState::self()->getCallingUid());
242e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    } else if (args.size() > 0) {
243e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        if (args.size() > 1) {
244e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard           return INVALID_OPERATION;
245e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
246e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        Mutex::Autolock _l(mLock);
247e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        SensorDevice& dev(SensorDevice::getInstance());
248e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        if (args[0] == String16("restrict") && mCurrentOperatingMode == NORMAL) {
249e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mCurrentOperatingMode = RESTRICTED;
250e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            dev.disableAllSensors();
251e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // Clear all pending flush connections for all active sensors. If one of the active
252e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // connections has called flush() and the underlying sensor has been disabled before a
253e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            // flush complete event is returned, we need to remove the connection from this queue.
254e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
255e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
256e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
257e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        } else if (args[0] == String16("enable") && mCurrentOperatingMode == RESTRICTED) {
258e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            mCurrentOperatingMode = NORMAL;
259e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            dev.enableAllSensors();
260e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
261e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        return status_t(NO_ERROR);
262e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    } else {
263e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        Mutex::Autolock _l(mLock);
264e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        result.append("Sensor List:\n");
265e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        for (size_t i=0 ; i<mSensorList.size() ; i++) {
266e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            const Sensor& s(mSensorList[i]);
267e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
268e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            result.appendFormat(
269e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
270e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    s.getName().string(),
271e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    s.getVendor().string(),
272e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    s.getVersion(),
273956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    s.getStringType().string(),
274956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    s.getHandle(),
275956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    s.getRequiredPermission().string(),
276956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    s.getType());
277956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
278e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            const int reportingMode = s.getReportingMode();
279e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
280e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.append(" continuous | ");
281e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
282e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.append(" on-change | ");
283e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
284e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.append(" one-shot | ");
285b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            } else {
286e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.append(" special-trigger | ");
287e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
288e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
289e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            if (s.getMaxDelay() > 0) {
290b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
291b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            } else {
292b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
293b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            }
294e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
295e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            if (s.getMinDelay() > 0) {
296e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
297e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            } else {
298e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.appendFormat("minDelay=%dus |", s.getMinDelay());
299b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            }
300e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
301b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            if (s.getFifoMaxEventCount() > 0) {
302b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                result.appendFormat("FifoMax=%d events | ",
303b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                        s.getFifoMaxEventCount());
304e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            } else {
305e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                result.append("no batching | ");
306e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
307e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
308956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (s.isWakeUpSensor()) {
309956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                result.appendFormat("wakeUp | ");
310956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            } else {
311956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                result.appendFormat("non-wakeUp | ");
312956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
313e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
314e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            switch (s.getType()) {
315e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                case SENSOR_TYPE_ROTATION_VECTOR:
316e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
317e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    result.appendFormat(
318e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
319e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
320e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    break;
321e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
322b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
323e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    result.appendFormat(
324e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
325b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
326b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                            e.timestamp);
327b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                    break;
328e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                case SENSOR_TYPE_GAME_ROTATION_VECTOR:
329e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    result.appendFormat(
330e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                            "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
331e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                            e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
332e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    break;
333e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                case SENSOR_TYPE_SIGNIFICANT_MOTION:
334e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                case SENSOR_TYPE_STEP_DETECTOR:
335e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
336b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                    break;
337b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                case SENSOR_TYPE_STEP_COUNTER:
338e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
339b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                                         e.timestamp);
340e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    break;
341e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                default:
3428a3b3707a6e320ba75f4ecd47fdc001f16c15cb8Martin Storsjo                    // default to 3 values
3438a3b3707a6e320ba75f4ecd47fdc001f16c15cb8Martin Storsjo                    result.appendFormat(
3448a3b3707a6e320ba75f4ecd47fdc001f16c15cb8Martin Storsjo                            "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
3458a3b3707a6e320ba75f4ecd47fdc001f16c15cb8Martin Storsjo                            e.data[0], e.data[1], e.data[2], e.timestamp);
3468a3b3707a6e320ba75f4ecd47fdc001f16c15cb8Martin Storsjo                    break;
3478a3b3707a6e320ba75f4ecd47fdc001f16c15cb8Martin Storsjo            }
348e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            result.append("\n");
349e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
350e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        SensorFusion::getInstance().dump(result);
351956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        SensorDevice::getInstance().dump(result);
352956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
353956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        result.append("Active sensors:\n");
354956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
355956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            int handle = mActiveSensors.keyAt(i);
356e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
357e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    getSensorName(handle).string(),
358e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    handle,
359e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    mActiveSensors.valueAt(i)->getNumConnections());
360e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
361e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
362b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        result.appendFormat("Socket Buffer size = %d events\n",
363e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                            mSocketBufferSize/sizeof(sensors_event_t));
364e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
365b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        result.appendFormat("Mode :");
366e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        switch(mCurrentOperatingMode) {
367e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard           case NORMAL:
368e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard               result.appendFormat(" NORMAL\n");
369956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong               break;
370956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong           case RESTRICTED:
371956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong               result.appendFormat(" RESTRICTED\n");
372b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard               break;
373956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong           case DATA_INJECTION:
374e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard               result.appendFormat(" DATA_INJECTION\n");
375e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
376e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        result.appendFormat("%zd active connections\n", mActiveConnections.size());
377e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
378e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
379e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            sp<SensorEventConnection> connection(mActiveConnections[i].promote());
380b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            if (connection != 0) {
381b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                result.appendFormat("Connection Number: %zu \n", i);
382e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                connection->dump(result);
383b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            }
384e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
385956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    }
386956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    write(fd, result.string(), result.size());
387956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    return NO_ERROR;
388956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
389956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
390956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongvoid SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
391b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        sensors_event_t const* buffer, const int count) {
392956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    for (int i=0 ; i<count ; i++) {
393956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        int handle = buffer[i].sensor;
394956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (buffer[i].type == SENSOR_TYPE_META_DATA) {
395956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            handle = buffer[i].meta_data.sensor;
396956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
397956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (connection->hasSensor(handle)) {
398956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            SensorInterface* sensor = mSensorMap.valueFor(handle);
399956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            // If this buffer has an event from a one_shot sensor and this connection is registered
400956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            // for this particular one_shot sensor, try cleaning up the connection.
401956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (sensor != NULL &&
402956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
403956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                sensor->autoDisable(connection.get(), handle);
404956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                cleanupWithoutDisableLocked(connection, handle);
405956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
406956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
407956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
408956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong   }
409956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
410956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
411956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongbool SensorService::threadLoop()
412956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong{
413956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    ALOGD("nuSensorService thread starting...");
414956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
415956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    // each virtual sensor could generate an event per "real" event, that's why we need
416956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
417956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    // in practice, this is too aggressive, but guaranteed to be enough.
418b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
419956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
420956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
421956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    SensorDevice& device(SensorDevice::getInstance());
422956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    const size_t vcount = mVirtualSensorList.size();
423956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
424956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    const int halVersion = device.getHalDeviceVersion();
425956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    do {
426956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
427956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (count < 0) {
428e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            ALOGE("sensor poll failed (%s)", strerror(-count));
429e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            break;
430e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        }
431956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
432956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        // Reset sensors_event_t.flags to zero for all events in the buffer.
433956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        for (int i = 0; i < count; i++) {
434956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong             mSensorEventBuffer[i].flags = 0;
435956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
436956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
437e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // Make a copy of the connection vector as some connections may be removed during the
438e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // course of this loop (especially when one-shot sensor events are present in the
439e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // sensor_event buffer). Promote all connections to StrongPointers before the lock is
440e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // acquired. If the destructor of the sp gets called when the lock is acquired, it may
441e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
442e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
443e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        SortedVector< sp<SensorEventConnection> > activeConnections;
444e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        populateActiveConnections(&activeConnections);
445e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        Mutex::Autolock _l(mLock);
446e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
447e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
448e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
449e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
450e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        // releasing the wakelock.
451e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        bool bufferHasWakeUpEvent = false;
452e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        for (int i = 0; i < count; i++) {
453956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
454956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                bufferHasWakeUpEvent = true;
455956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                break;
456956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
457956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
458956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
459956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
460956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            setWakeLockAcquiredLocked(true);
461956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
462956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        recordLastValueLocked(mSensorEventBuffer, count);
463956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
464956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        // handle virtual sensors
465956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (count && vcount) {
466956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            sensors_event_t const * const event = mSensorEventBuffer;
467956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
468956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (activeVirtualSensorCount) {
469956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                size_t k = 0;
470956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                SensorFusion& fusion(SensorFusion::getInstance());
471956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                if (fusion.isEnabled()) {
472956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    for (size_t i=0 ; i<size_t(count) ; i++) {
473e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                        fusion.process(event[i]);
474e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                    }
475956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                }
476956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
477956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
478b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                        if (count + k >= minBufferSize) {
479956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                            ALOGE("buffer too small to hold all events: "
480b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                                    "count=%zd, k=%zu, size=%zu",
481b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                                    count, k, minBufferSize);
482956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                            break;
483956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        }
484956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        sensors_event_t out;
485956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
486956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        if (si->process(&out, event[i])) {
487956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                            mSensorEventBuffer[count + k] = out;
488956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                            k++;
489956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        }
490956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    }
491b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                }
492956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                if (k) {
493956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    // record the last synthesized values
494956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    recordLastValueLocked(&mSensorEventBuffer[count], k);
495b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                    count += k;
496956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    // sort the buffer by time-stamps
497956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    sortEventBuffer(mSensorEventBuffer, count);
498956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                }
499b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            }
500956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
501956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
502956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        // handle backward compatibility for RotationVector sensor
503956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
504956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            for (int i = 0; i < count; i++) {
505956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
506956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    // All the 4 components of the quaternion should be available
507b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                    // No heading accuracy. Set it to -1
508956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    mSensorEventBuffer[i].data[4] = -1;
509b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                }
510956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
511956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
512956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
513b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        // Map flush_complete_events in the buffer to SensorEventConnections which called
514956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
515b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        // SensorEventConnection mapped to the corresponding flush_complete_event in
516956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
517956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        for (int i = 0; i < count; ++i) {
518956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            mMapFlushEventsToConnections[i] = NULL;
519956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
520956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
521956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
522b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                if (rec != NULL) {
523956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
524956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                    rec->removeFirstPendingFlushConnection();
525e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard                }
526e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard            }
527956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
528b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
529956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        // Send our events to clients. Check the state of wake lock for each client and release the
530b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        // lock if none of the clients need it.
531956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        bool needsWakeLock = false;
532956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        size_t numConnections = activeConnections.size();
533956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        for (size_t i=0 ; i < numConnections; ++i) {
534956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (activeConnections[i] != 0) {
535956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
536956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                        mMapFlushEventsToConnections);
537956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                needsWakeLock |= activeConnections[i]->needsWakeLock();
538956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                // If the connection has one-shot sensors, it may be cleaned up after first trigger.
539956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                // Early check for one-shot sensors.
540956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                if (activeConnections[i]->hasOneShotSensors()) {
541b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard                    cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
542956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                            count);
543956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                }
544956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
545956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
546956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
547956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (mWakeLockAcquired && !needsWakeLock) {
548956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            setWakeLockAcquiredLocked(false);
549956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
550956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    } while (!Thread::exitPending());
551e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard
552956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    ALOGW("Exiting SensorService::threadLoop => aborting...");
553b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    abort();
554956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    return false;
555b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard}
556b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
557956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongsp<Looper> SensorService::getLooper() const {
558b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    return mLooper;
559956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
560b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
561956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongvoid SensorService::resetAllWakeLockRefCounts() {
562956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    SortedVector< sp<SensorEventConnection> > activeConnections;
563956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    populateActiveConnections(&activeConnections);
564b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    {
565956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        Mutex::Autolock _l(mLock);
566956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        for (size_t i=0 ; i < activeConnections.size(); ++i) {
567956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            if (activeConnections[i] != 0) {
568956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                activeConnections[i]->resetWakeLockRefCount();
569956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
570956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
571956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        setWakeLockAcquiredLocked(false);
572e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    }
573956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
574956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
575956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongvoid SensorService::setWakeLockAcquiredLocked(bool acquire) {
576956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    if (acquire) {
577956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (!mWakeLockAcquired) {
578956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
579956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            mWakeLockAcquired = true;
580b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        }
581956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        mLooper->wake();
582956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    } else {
583956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (mWakeLockAcquired) {
584956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            release_wake_lock(WAKE_LOCK_NAME);
585956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            mWakeLockAcquired = false;
586956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
587956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    }
588b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard}
589956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
590b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgardbool SensorService::isWakeLockAcquired() {
591956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    Mutex::Autolock _l(mLock);
592956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    return mWakeLockAcquired;
593956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
594b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
595956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongbool SensorService::SensorEventAckReceiver::threadLoop() {
596b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    ALOGD("new thread SensorEventAckReceiver");
597956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    sp<Looper> looper = mService->getLooper();
598956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    do {
599956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        bool wakeLockAcquired = mService->isWakeLockAcquired();
600b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        int timeout = -1;
601956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (wakeLockAcquired) timeout = 5000;
602956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        int ret = looper->pollOnce(timeout);
603956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (ret == ALOOPER_POLL_TIMEOUT) {
604956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong           mService->resetAllWakeLockRefCounts();
605956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
606956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    } while(!Thread::exitPending());
607956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    return false;
608e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard}
609956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
610b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgardvoid SensorService::recordLastValueLocked(
611956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        const sensors_event_t* buffer, size_t count) {
612b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    const sensors_event_t* last = NULL;
613956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    for (size_t i = 0; i < count; i++) {
614956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        const sensors_event_t* event = &buffer[i];
615956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (event->type != SENSOR_TYPE_META_DATA) {
616b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            if (last && event->sensor != last->sensor) {
617956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong                mLastEventSeen.editValueFor(last->sensor) = *last;
618956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            }
619956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            last = event;
620956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
621956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    }
622956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    if (last) {
623e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        mLastEventSeen.editValueFor(last->sensor) = *last;
624e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    }
625956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
626b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard
627956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongvoid SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
628956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong{
629956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    struct compar {
630956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        static int cmp(void const* lhs, void const* rhs) {
631b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
632956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
633956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            return l->timestamp - r->timestamp;
634956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        }
635956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    };
636b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
637956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
638956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
639b676a05348e4c516fa8b57e33b10548e6142c3f8Mans RullgardString8 SensorService::getSensorName(int handle) const {
640b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    size_t count = mUserSensorList.size();
641956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    for (size_t i=0 ; i<count ; i++) {
642956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        const Sensor& sensor(mUserSensorList[i]);
643956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        if (sensor.getHandle() == handle) {
644b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard            return sensor.getName();
645b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard        }
646956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    }
647956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    String8 result("unknown");
648956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    return result;
649956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
650956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
651956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongbool SensorService::isVirtualSensor(int handle) const {
652956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    SensorInterface* sensor = mSensorMap.valueFor(handle);
653e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    return sensor->isVirtual();
654b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard}
655956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
656956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dongbool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
657956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    int handle = event.sensor;
658956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    if (event.type == SENSOR_TYPE_META_DATA) {
659e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard        handle = event.meta_data.sensor;
660e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    }
661e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    SensorInterface* sensor = mSensorMap.valueFor(handle);
662e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard    return sensor != NULL && sensor->getSensor().isWakeUpSensor();
663e2e838afcf03e603a41a0455846eaf9614537c16Mans Rullgard}
664956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
665956c553ab0ce72f8074ad0fda2ffd66a0305700cJames DongSensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
666956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong     return mActiveSensors.valueFor(handle);
667956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong}
668956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong
669b676a05348e4c516fa8b57e33b10548e6142c3f8Mans RullgardVector<Sensor> SensorService::getSensorList()
670956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong{
671956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    char value[PROPERTY_VALUE_MAX];
672b676a05348e4c516fa8b57e33b10548e6142c3f8Mans Rullgard    property_get("debug.sensors", value, "0");
673956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
674956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong            mUserSensorListDebug : mUserSensorList;
675956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    Vector<Sensor> accessibleSensorList;
676956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong    for (size_t i = 0; i < initialSensorList.size(); i++) {
677956c553ab0ce72f8074ad0fda2ffd66a0305700cJames Dong        Sensor sensor = initialSensorList[i];
678        if (canAccessSensor(sensor)) {
679            accessibleSensorList.add(sensor);
680        } else {
681            ALOGI("Skipped sensor %s because it requires permission %s",
682                  sensor.getName().string(),
683                  sensor.getRequiredPermission().string());
684        }
685    }
686    return accessibleSensorList;
687}
688
689sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
690        int requestedMode) {
691    // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
692    if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
693        return NULL;
694    }
695    // DATA_INJECTION mode needs to have the required permissions set.
696    if (requestedMode == DATA_INJECTION && !hasDataInjectionPermissions()) {
697        return NULL;
698    }
699
700    Mutex::Autolock _l(mLock);
701    uid_t uid = IPCThreadState::self()->getCallingUid();
702    sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
703            requestedMode == DATA_INJECTION));
704    if (requestedMode == DATA_INJECTION) {
705        if (mActiveConnections.indexOf(result) < 0) {
706            mActiveConnections.add(result);
707        }
708        // Add the associated file descriptor to the Looper for polling whenever there is data to
709        // be injected.
710        result->updateLooperRegistration(mLooper);
711    }
712    return result;
713}
714
715status_t SensorService::enableDataInjection(int requestedMode) {
716    if (!hasDataInjectionPermissions()) {
717        return INVALID_OPERATION;
718    }
719    Mutex::Autolock _l(mLock);
720    ALOGD_IF(DEBUG_CONNECTIONS, "SensorService::enableDataInjection %d", requestedMode);
721    SensorDevice& dev(SensorDevice::getInstance());
722    status_t err(NO_ERROR);
723    if (requestedMode == DATA_INJECTION) {
724        if (mCurrentOperatingMode == NORMAL) {
725           dev.disableAllSensors();
726           err = dev.setMode(requestedMode);
727           if (err == NO_ERROR) {
728               mCurrentOperatingMode = DATA_INJECTION;
729           } else {
730               // Re-enable sensors.
731               dev.enableAllSensors();
732           }
733       } else if (mCurrentOperatingMode == DATA_INJECTION) {
734           // Already in DATA_INJECTION mode. Treat this as a no_op.
735           return NO_ERROR;
736       } else {
737           // Transition to data injection mode supported only from NORMAL mode.
738           return INVALID_OPERATION;
739       }
740    } else if (requestedMode == NORMAL && mCurrentOperatingMode != NORMAL) {
741       err = resetToNormalModeLocked();
742    }
743    return err;
744}
745
746status_t SensorService::resetToNormalMode() {
747    Mutex::Autolock _l(mLock);
748    return resetToNormalModeLocked();
749}
750
751status_t SensorService::resetToNormalModeLocked() {
752    SensorDevice& dev(SensorDevice::getInstance());
753    dev.enableAllSensors();
754    status_t err = dev.setMode(NORMAL);
755    mCurrentOperatingMode = NORMAL;
756    return err;
757}
758
759void SensorService::cleanupConnection(SensorEventConnection* c)
760{
761    Mutex::Autolock _l(mLock);
762    const wp<SensorEventConnection> connection(c);
763    size_t size = mActiveSensors.size();
764    ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
765    for (size_t i=0 ; i<size ; ) {
766        int handle = mActiveSensors.keyAt(i);
767        if (c->hasSensor(handle)) {
768            ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
769            SensorInterface* sensor = mSensorMap.valueFor( handle );
770            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
771            if (sensor) {
772                sensor->activate(c, false);
773            }
774            c->removeSensor(handle);
775        }
776        SensorRecord* rec = mActiveSensors.valueAt(i);
777        ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
778        ALOGD_IF(DEBUG_CONNECTIONS,
779                "removing connection %p for sensor[%zu].handle=0x%08x",
780                c, i, handle);
781
782        if (rec && rec->removeConnection(connection)) {
783            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
784            mActiveSensors.removeItemsAt(i, 1);
785            mActiveVirtualSensors.removeItem(handle);
786            delete rec;
787            size--;
788        } else {
789            i++;
790        }
791    }
792    c->updateLooperRegistration(mLooper);
793    mActiveConnections.remove(connection);
794    BatteryService::cleanup(c->getUid());
795    if (c->needsWakeLock()) {
796        checkWakeLockStateLocked();
797    }
798}
799
800Sensor SensorService::getSensorFromHandle(int handle) const {
801    return mSensorMap.valueFor(handle)->getSensor();
802}
803
804status_t SensorService::enable(const sp<SensorEventConnection>& connection,
805        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
806{
807    if (mInitCheck != NO_ERROR)
808        return mInitCheck;
809
810    SensorInterface* sensor = mSensorMap.valueFor(handle);
811    if (sensor == NULL) {
812        return BAD_VALUE;
813    }
814
815    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
816        return BAD_VALUE;
817    }
818
819    Mutex::Autolock _l(mLock);
820    if (mCurrentOperatingMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
821        return INVALID_OPERATION;
822    }
823
824    SensorRecord* rec = mActiveSensors.valueFor(handle);
825    if (rec == 0) {
826        rec = new SensorRecord(connection);
827        mActiveSensors.add(handle, rec);
828        if (sensor->isVirtual()) {
829            mActiveVirtualSensors.add(handle, sensor);
830        }
831    } else {
832        if (rec->addConnection(connection)) {
833            // this sensor is already activated, but we are adding a connection that uses it.
834            // Immediately send down the last known value of the requested sensor if it's not a
835            // "continuous" sensor.
836            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
837                // NOTE: The wake_up flag of this event may get set to
838                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
839                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
840                if (event.version == sizeof(sensors_event_t)) {
841                    if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
842                        setWakeLockAcquiredLocked(true);
843                    }
844                    connection->sendEvents(&event, 1, NULL);
845                    if (!connection->needsWakeLock() && mWakeLockAcquired) {
846                        checkWakeLockStateLocked();
847                    }
848                }
849            }
850        }
851    }
852
853    if (connection->addSensor(handle)) {
854        BatteryService::enableSensor(connection->getUid(), handle);
855        // the sensor was added (which means it wasn't already there)
856        // so, see if this connection becomes active
857        if (mActiveConnections.indexOf(connection) < 0) {
858            mActiveConnections.add(connection);
859        }
860    } else {
861        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
862            handle, connection.get());
863    }
864
865    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
866    if (samplingPeriodNs < minDelayNs) {
867        samplingPeriodNs = minDelayNs;
868    }
869
870    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
871                                "rate=%" PRId64 " timeout== %" PRId64"",
872             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
873
874    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
875                                 maxBatchReportLatencyNs);
876
877    // Call flush() before calling activate() on the sensor. Wait for a first flush complete
878    // event before sending events on this connection. Ignore one-shot sensors which don't
879    // support flush(). Also if this sensor isn't already active, don't call flush().
880    if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
881            rec->getNumConnections() > 1) {
882        connection->setFirstFlushPending(handle, true);
883        status_t err_flush = sensor->flush(connection.get(), handle);
884        // Flush may return error if the underlying h/w sensor uses an older HAL.
885        if (err_flush == NO_ERROR) {
886            rec->addPendingFlushConnection(connection.get());
887        } else {
888            connection->setFirstFlushPending(handle, false);
889        }
890    }
891
892    if (err == NO_ERROR) {
893        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
894        err = sensor->activate(connection.get(), true);
895    }
896
897    if (err == NO_ERROR) {
898        connection->updateLooperRegistration(mLooper);
899    }
900
901    if (err != NO_ERROR) {
902        // batch/activate has failed, reset our state.
903        cleanupWithoutDisableLocked(connection, handle);
904    }
905    return err;
906}
907
908status_t SensorService::disable(const sp<SensorEventConnection>& connection,
909        int handle)
910{
911    if (mInitCheck != NO_ERROR)
912        return mInitCheck;
913
914    Mutex::Autolock _l(mLock);
915    status_t err = cleanupWithoutDisableLocked(connection, handle);
916    if (err == NO_ERROR) {
917        SensorInterface* sensor = mSensorMap.valueFor(handle);
918        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
919    }
920    return err;
921}
922
923status_t SensorService::cleanupWithoutDisable(
924        const sp<SensorEventConnection>& connection, int handle) {
925    Mutex::Autolock _l(mLock);
926    return cleanupWithoutDisableLocked(connection, handle);
927}
928
929status_t SensorService::cleanupWithoutDisableLocked(
930        const sp<SensorEventConnection>& connection, int handle) {
931    SensorRecord* rec = mActiveSensors.valueFor(handle);
932    if (rec) {
933        // see if this connection becomes inactive
934        if (connection->removeSensor(handle)) {
935            BatteryService::disableSensor(connection->getUid(), handle);
936        }
937        if (connection->hasAnySensor() == false) {
938            connection->updateLooperRegistration(mLooper);
939            mActiveConnections.remove(connection);
940        }
941        // see if this sensor becomes inactive
942        if (rec->removeConnection(connection)) {
943            mActiveSensors.removeItem(handle);
944            mActiveVirtualSensors.removeItem(handle);
945            delete rec;
946        }
947        return NO_ERROR;
948    }
949    return BAD_VALUE;
950}
951
952status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
953        int handle, nsecs_t ns)
954{
955    if (mInitCheck != NO_ERROR)
956        return mInitCheck;
957
958    SensorInterface* sensor = mSensorMap.valueFor(handle);
959    if (!sensor)
960        return BAD_VALUE;
961
962    if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
963        return BAD_VALUE;
964    }
965
966    if (ns < 0)
967        return BAD_VALUE;
968
969    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
970    if (ns < minDelayNs) {
971        ns = minDelayNs;
972    }
973
974    return sensor->setDelay(connection.get(), handle, ns);
975}
976
977status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
978    if (mInitCheck != NO_ERROR) return mInitCheck;
979    SensorDevice& dev(SensorDevice::getInstance());
980    const int halVersion = dev.getHalDeviceVersion();
981    status_t err(NO_ERROR);
982    Mutex::Autolock _l(mLock);
983    // Loop through all sensors for this connection and call flush on each of them.
984    for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
985        const int handle = connection->mSensorInfo.keyAt(i);
986        SensorInterface* sensor = mSensorMap.valueFor(handle);
987        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
988            ALOGE("flush called on a one-shot sensor");
989            err = INVALID_OPERATION;
990            continue;
991        }
992        if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
993            // For older devices just increment pending flush count which will send a trivial
994            // flush complete event.
995            connection->incrementPendingFlushCount(handle);
996        } else {
997            status_t err_flush = sensor->flush(connection.get(), handle);
998            if (err_flush == NO_ERROR) {
999                SensorRecord* rec = mActiveSensors.valueFor(handle);
1000                if (rec != NULL) rec->addPendingFlushConnection(connection);
1001            }
1002            err = (err_flush != NO_ERROR) ? err_flush : err;
1003        }
1004    }
1005    return err;
1006}
1007
1008bool SensorService::canAccessSensor(const Sensor& sensor) {
1009    return (sensor.getRequiredPermission().isEmpty()) ||
1010            PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
1011}
1012
1013bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
1014    if (canAccessSensor(sensor)) {
1015        return true;
1016    } else {
1017        String8 errorMessage;
1018        errorMessage.appendFormat(
1019                "%s a sensor (%s) without holding its required permission: %s",
1020                operation,
1021                sensor.getName().string(),
1022                sensor.getRequiredPermission().string());
1023        return false;
1024    }
1025}
1026
1027bool SensorService::hasDataInjectionPermissions() {
1028    if (!PermissionCache::checkCallingPermission(sDataInjectionPermission)) {
1029        ALOGE("Permission Denial trying to activate data injection without"
1030              " the required permission");
1031        return false;
1032    }
1033    return true;
1034}
1035
1036void SensorService::checkWakeLockState() {
1037    Mutex::Autolock _l(mLock);
1038    checkWakeLockStateLocked();
1039}
1040
1041void SensorService::checkWakeLockStateLocked() {
1042    if (!mWakeLockAcquired) {
1043        return;
1044    }
1045    bool releaseLock = true;
1046    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1047        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1048        if (connection != 0) {
1049            if (connection->needsWakeLock()) {
1050                releaseLock = false;
1051                break;
1052            }
1053        }
1054    }
1055    if (releaseLock) {
1056        setWakeLockAcquiredLocked(false);
1057    }
1058}
1059
1060void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1061    Mutex::Autolock _l(mLock);
1062    connection->writeToSocketFromCache();
1063    if (connection->needsWakeLock()) {
1064        setWakeLockAcquiredLocked(true);
1065    }
1066}
1067
1068void SensorService::populateActiveConnections(
1069        SortedVector< sp<SensorEventConnection> >* activeConnections) {
1070    Mutex::Autolock _l(mLock);
1071    for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1072        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1073        if (connection != 0) {
1074            activeConnections->add(connection);
1075        }
1076    }
1077}
1078
1079bool SensorService::isWhiteListedPackage(const String8& packageName) {
1080    // TODO: Come up with a list of packages.
1081    return (packageName.find(".cts.") != -1);
1082}
1083
1084// ---------------------------------------------------------------------------
1085SensorService::SensorRecord::SensorRecord(
1086        const sp<SensorEventConnection>& connection)
1087{
1088    mConnections.add(connection);
1089}
1090
1091bool SensorService::SensorRecord::addConnection(
1092        const sp<SensorEventConnection>& connection)
1093{
1094    if (mConnections.indexOf(connection) < 0) {
1095        mConnections.add(connection);
1096        return true;
1097    }
1098    return false;
1099}
1100
1101bool SensorService::SensorRecord::removeConnection(
1102        const wp<SensorEventConnection>& connection)
1103{
1104    ssize_t index = mConnections.indexOf(connection);
1105    if (index >= 0) {
1106        mConnections.removeItemsAt(index, 1);
1107    }
1108    // Remove this connections from the queue of flush() calls made on this sensor.
1109    for (Vector< wp<SensorEventConnection> >::iterator it =
1110            mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
1111
1112        if (it->unsafe_get() == connection.unsafe_get()) {
1113            it = mPendingFlushConnections.erase(it);
1114        } else {
1115            ++it;
1116        }
1117    }
1118    return mConnections.size() ? false : true;
1119}
1120
1121void SensorService::SensorRecord::addPendingFlushConnection(
1122        const sp<SensorEventConnection>& connection) {
1123    mPendingFlushConnections.add(connection);
1124}
1125
1126void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1127    if (mPendingFlushConnections.size() > 0) {
1128        mPendingFlushConnections.removeAt(0);
1129    }
1130}
1131
1132SensorService::SensorEventConnection *
1133SensorService::SensorRecord::getFirstPendingFlushConnection() {
1134   if (mPendingFlushConnections.size() > 0) {
1135        return mPendingFlushConnections[0].unsafe_get();
1136    }
1137    return NULL;
1138}
1139
1140void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1141    mPendingFlushConnections.clear();
1142}
1143
1144// ---------------------------------------------------------------------------
1145
1146SensorService::SensorEventConnection::SensorEventConnection(
1147        const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode)
1148    : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
1149      mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName),
1150      mDataInjectionMode(isDataInjectionMode) {
1151    mChannel = new BitTube(mService->mSocketBufferSize);
1152#if DEBUG_CONNECTIONS
1153    mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
1154    mTotalAcksNeeded = mTotalAcksReceived = 0;
1155#endif
1156}
1157
1158SensorService::SensorEventConnection::~SensorEventConnection() {
1159    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
1160    mService->cleanupConnection(this);
1161    if (mEventCache != NULL) {
1162        delete mEventCache;
1163    }
1164}
1165
1166void SensorService::SensorEventConnection::onFirstRef() {
1167    LooperCallback::onFirstRef();
1168}
1169
1170bool SensorService::SensorEventConnection::needsWakeLock() {
1171    Mutex::Autolock _l(mConnectionLock);
1172    return !mDead && mWakeLockRefCount > 0;
1173}
1174
1175void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1176    Mutex::Autolock _l(mConnectionLock);
1177    mWakeLockRefCount = 0;
1178}
1179
1180void SensorService::SensorEventConnection::dump(String8& result) {
1181    Mutex::Autolock _l(mConnectionLock);
1182    result.appendFormat("Operating Mode: %s\n", mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
1183    result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1184            mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
1185    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1186        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
1187        result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
1188                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
1189                            mSensorInfo.keyAt(i),
1190                            flushInfo.mFirstFlushPending ? "First flush pending" :
1191                                                           "active",
1192                            flushInfo.mPendingFlushEventsToSend);
1193    }
1194#if DEBUG_CONNECTIONS
1195    result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1196            " total_acks_needed %d | total_acks_recvd %d\n",
1197            mEventsReceived,
1198            mEventsSent,
1199            mEventsSentFromCache,
1200            mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1201            mTotalAcksNeeded,
1202            mTotalAcksReceived);
1203#endif
1204}
1205
1206bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
1207    Mutex::Autolock _l(mConnectionLock);
1208    if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1209        return false;
1210    }
1211    if (mSensorInfo.indexOfKey(handle) < 0) {
1212        mSensorInfo.add(handle, FlushInfo());
1213        return true;
1214    }
1215    return false;
1216}
1217
1218bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
1219    Mutex::Autolock _l(mConnectionLock);
1220    if (mSensorInfo.removeItem(handle) >= 0) {
1221        return true;
1222    }
1223    return false;
1224}
1225
1226bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
1227    Mutex::Autolock _l(mConnectionLock);
1228    return mSensorInfo.indexOfKey(handle) >= 0;
1229}
1230
1231bool SensorService::SensorEventConnection::hasAnySensor() const {
1232    Mutex::Autolock _l(mConnectionLock);
1233    return mSensorInfo.size() ? true : false;
1234}
1235
1236bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1237    Mutex::Autolock _l(mConnectionLock);
1238    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1239        const int handle = mSensorInfo.keyAt(i);
1240        if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1241            return true;
1242        }
1243    }
1244    return false;
1245}
1246
1247String8 SensorService::SensorEventConnection::getPackageName() const {
1248    return mPackageName;
1249}
1250
1251void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1252                                bool value) {
1253    Mutex::Autolock _l(mConnectionLock);
1254    ssize_t index = mSensorInfo.indexOfKey(handle);
1255    if (index >= 0) {
1256        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1257        flushInfo.mFirstFlushPending = value;
1258    }
1259}
1260
1261void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1262    Mutex::Autolock _l(mConnectionLock);
1263    updateLooperRegistrationLocked(looper);
1264}
1265
1266void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1267        const sp<Looper>& looper) {
1268    bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1269                              mDataInjectionMode;
1270    // If all sensors are unregistered OR Looper has encountered an error, we
1271    // can remove the Fd from the Looper if it has been previously added.
1272    if (!isConnectionActive || mDead) {
1273        if (mHasLooperCallbacks) {
1274            ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1275            looper->removeFd(mChannel->getSendFd());
1276            mHasLooperCallbacks = false;
1277        }
1278        return;
1279    }
1280
1281    int looper_flags = 0;
1282    if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
1283    if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
1284    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1285        const int handle = mSensorInfo.keyAt(i);
1286        if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1287            looper_flags |= ALOOPER_EVENT_INPUT;
1288            break;
1289        }
1290    }
1291    // If flags is still set to zero, we don't need to add this fd to the Looper, if
1292    // the fd has already been added, remove it. This is likely to happen when ALL the
1293    // events stored in the cache have been sent to the corresponding app.
1294    if (looper_flags == 0) {
1295        if (mHasLooperCallbacks) {
1296            ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1297            looper->removeFd(mChannel->getSendFd());
1298            mHasLooperCallbacks = false;
1299        }
1300        return;
1301    }
1302    // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1303    // registered for wake-up sensors OR for sending events in the cache.
1304    int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1305    if (ret == 1) {
1306        ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1307        mHasLooperCallbacks = true;
1308    } else {
1309        ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1310    }
1311}
1312
1313void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1314    Mutex::Autolock _l(mConnectionLock);
1315    ssize_t index = mSensorInfo.indexOfKey(handle);
1316    if (index >= 0) {
1317        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1318        flushInfo.mPendingFlushEventsToSend++;
1319    }
1320}
1321
1322status_t SensorService::SensorEventConnection::sendEvents(
1323        sensors_event_t const* buffer, size_t numEvents,
1324        sensors_event_t* scratch,
1325        SensorEventConnection const * const * mapFlushEventsToConnections) {
1326    // filter out events not for this connection
1327    size_t count = 0;
1328    Mutex::Autolock _l(mConnectionLock);
1329    if (scratch) {
1330        size_t i=0;
1331        while (i<numEvents) {
1332            int32_t sensor_handle = buffer[i].sensor;
1333            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1334                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
1335                        buffer[i].meta_data.sensor);
1336                // Setting sensor_handle to the correct sensor to ensure the sensor events per
1337                // connection are filtered correctly.  buffer[i].sensor is zero for meta_data
1338                // events.
1339                sensor_handle = buffer[i].meta_data.sensor;
1340            }
1341            ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
1342            // Check if this connection has registered for this sensor. If not continue to the
1343            // next sensor_event.
1344            if (index < 0) {
1345                ++i;
1346                continue;
1347            }
1348
1349            FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1350            // Check if there is a pending flush_complete event for this sensor on this connection.
1351            if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1352                    this == mapFlushEventsToConnections[i]) {
1353                flushInfo.mFirstFlushPending = false;
1354                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1355                        buffer[i].meta_data.sensor);
1356                ++i;
1357                continue;
1358            }
1359
1360            // If there is a pending flush complete event for this sensor on this connection,
1361            // ignore the event and proceed to the next.
1362            if (flushInfo.mFirstFlushPending) {
1363                ++i;
1364                continue;
1365            }
1366
1367            do {
1368                // Keep copying events into the scratch buffer as long as they are regular
1369                // sensor_events are from the same sensor_handle OR they are flush_complete_events
1370                // from the same sensor_handle AND the current connection is mapped to the
1371                // corresponding flush_complete_event.
1372                if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1373                    if (this == mapFlushEventsToConnections[i]) {
1374                        scratch[count++] = buffer[i];
1375                    }
1376                    ++i;
1377                } else {
1378                    // Regular sensor event, just copy it to the scratch buffer.
1379                    scratch[count++] = buffer[i++];
1380                }
1381            } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1382                                        buffer[i].type != SENSOR_TYPE_META_DATA) ||
1383                                       (buffer[i].type == SENSOR_TYPE_META_DATA  &&
1384                                        buffer[i].meta_data.sensor == sensor_handle)));
1385        }
1386    } else {
1387        scratch = const_cast<sensors_event_t *>(buffer);
1388        count = numEvents;
1389    }
1390
1391    sendPendingFlushEventsLocked();
1392    // Early return if there are no events for this connection.
1393    if (count == 0) {
1394        return status_t(NO_ERROR);
1395    }
1396
1397#if DEBUG_CONNECTIONS
1398     mEventsReceived += count;
1399#endif
1400    if (mCacheSize != 0) {
1401        // There are some events in the cache which need to be sent first. Copy this buffer to
1402        // the end of cache.
1403        if (mCacheSize + count <= mMaxCacheSize) {
1404            memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1405            mCacheSize += count;
1406        } else {
1407            // Check if any new sensors have registered on this connection which may have increased
1408            // the max cache size that is desired.
1409            if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1410                reAllocateCacheLocked(scratch, count);
1411                return status_t(NO_ERROR);
1412            }
1413            // Some events need to be dropped.
1414            int remaningCacheSize = mMaxCacheSize - mCacheSize;
1415            if (remaningCacheSize != 0) {
1416                memcpy(&mEventCache[mCacheSize], scratch,
1417                                                remaningCacheSize * sizeof(sensors_event_t));
1418            }
1419            int numEventsDropped = count - remaningCacheSize;
1420            countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1421            // Drop the first "numEventsDropped" in the cache.
1422            memmove(mEventCache, &mEventCache[numEventsDropped],
1423                    (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1424
1425            // Copy the remainingEvents in scratch buffer to the end of cache.
1426            memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1427                                            numEventsDropped * sizeof(sensors_event_t));
1428        }
1429        return status_t(NO_ERROR);
1430    }
1431
1432    int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1433    if (index_wake_up_event >= 0) {
1434        scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1435        ++mWakeLockRefCount;
1436#if DEBUG_CONNECTIONS
1437        ++mTotalAcksNeeded;
1438#endif
1439    }
1440
1441    // NOTE: ASensorEvent and sensors_event_t are the same type.
1442    ssize_t size = SensorEventQueue::write(mChannel,
1443                                    reinterpret_cast<ASensorEvent const*>(scratch), count);
1444    if (size < 0) {
1445        // Write error, copy events to local cache.
1446        if (index_wake_up_event >= 0) {
1447            // If there was a wake_up sensor_event, reset the flag.
1448            scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1449            if (mWakeLockRefCount > 0) {
1450                --mWakeLockRefCount;
1451            }
1452#if DEBUG_CONNECTIONS
1453            --mTotalAcksNeeded;
1454#endif
1455        }
1456        if (mEventCache == NULL) {
1457            mMaxCacheSize = computeMaxCacheSizeLocked();
1458            mEventCache = new sensors_event_t[mMaxCacheSize];
1459            mCacheSize = 0;
1460        }
1461        memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1462        mCacheSize += count;
1463
1464        // Add this file descriptor to the looper to get a callback when this fd is available for
1465        // writing.
1466        updateLooperRegistrationLocked(mService->getLooper());
1467        return size;
1468    }
1469
1470#if DEBUG_CONNECTIONS
1471    if (size > 0) {
1472        mEventsSent += count;
1473    }
1474#endif
1475
1476    return size < 0 ? status_t(size) : status_t(NO_ERROR);
1477}
1478
1479void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1480                                                                 int count) {
1481    sensors_event_t *eventCache_new;
1482    const int new_cache_size = computeMaxCacheSizeLocked();
1483    // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1484    eventCache_new = new sensors_event_t[new_cache_size];
1485    memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1486    memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1487
1488    ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1489            new_cache_size);
1490
1491    delete mEventCache;
1492    mEventCache = eventCache_new;
1493    mCacheSize += count;
1494    mMaxCacheSize = new_cache_size;
1495}
1496
1497void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1498    ASensorEvent flushCompleteEvent;
1499    memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
1500    flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
1501    // Loop through all the sensors for this connection and check if there are any pending
1502    // flush complete events to be sent.
1503    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1504        FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1505        while (flushInfo.mPendingFlushEventsToSend > 0) {
1506            const int sensor_handle = mSensorInfo.keyAt(i);
1507            flushCompleteEvent.meta_data.sensor = sensor_handle;
1508            bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1509            if (wakeUpSensor) {
1510               ++mWakeLockRefCount;
1511               flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1512            }
1513            ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1514            if (size < 0) {
1515                if (wakeUpSensor) --mWakeLockRefCount;
1516                return;
1517            }
1518            ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1519                    flushCompleteEvent.meta_data.sensor);
1520            flushInfo.mPendingFlushEventsToSend--;
1521        }
1522    }
1523}
1524
1525void SensorService::SensorEventConnection::writeToSocketFromCache() {
1526    // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1527    // half the size of the socket buffer allocated in BitTube whichever is smaller.
1528    const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1529            int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
1530    Mutex::Autolock _l(mConnectionLock);
1531    // Send pending flush complete events (if any)
1532    sendPendingFlushEventsLocked();
1533    for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
1534        const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
1535        int index_wake_up_event =
1536                  findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1537        if (index_wake_up_event >= 0) {
1538            mEventCache[index_wake_up_event + numEventsSent].flags |=
1539                    WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1540            ++mWakeLockRefCount;
1541#if DEBUG_CONNECTIONS
1542            ++mTotalAcksNeeded;
1543#endif
1544        }
1545
1546        ssize_t size = SensorEventQueue::write(mChannel,
1547                          reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
1548                          numEventsToWrite);
1549        if (size < 0) {
1550            if (index_wake_up_event >= 0) {
1551                // If there was a wake_up sensor_event, reset the flag.
1552                mEventCache[index_wake_up_event + numEventsSent].flags  &=
1553                        ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1554                if (mWakeLockRefCount > 0) {
1555                    --mWakeLockRefCount;
1556                }
1557#if DEBUG_CONNECTIONS
1558                --mTotalAcksNeeded;
1559#endif
1560            }
1561            memmove(mEventCache, &mEventCache[numEventsSent],
1562                                 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1563            ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
1564                    numEventsSent, mCacheSize);
1565            mCacheSize -= numEventsSent;
1566            return;
1567        }
1568        numEventsSent += numEventsToWrite;
1569#if DEBUG_CONNECTIONS
1570        mEventsSentFromCache += numEventsToWrite;
1571#endif
1572    }
1573    ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1574    // All events from the cache have been sent. Reset cache size to zero.
1575    mCacheSize = 0;
1576    // There are no more events in the cache. We don't need to poll for write on the fd.
1577    // Update Looper registration.
1578    updateLooperRegistrationLocked(mService->getLooper());
1579}
1580
1581void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
1582                sensors_event_t const* scratch, const int numEventsDropped) {
1583    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
1584    // Count flushComplete events in the events that are about to the dropped. These will be sent
1585    // separately before the next batch of events.
1586    for (int j = 0; j < numEventsDropped; ++j) {
1587        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1588            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1589            flushInfo.mPendingFlushEventsToSend++;
1590            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1591                     flushInfo.mPendingFlushEventsToSend);
1592        }
1593    }
1594    return;
1595}
1596
1597int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1598                       sensors_event_t const* scratch, const int count) {
1599    for (int i = 0; i < count; ++i) {
1600        if (mService->isWakeUpSensorEvent(scratch[i])) {
1601            return i;
1602        }
1603    }
1604    return -1;
1605}
1606
1607sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
1608{
1609    return mChannel;
1610}
1611
1612status_t SensorService::SensorEventConnection::enableDisable(
1613        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1614        int reservedFlags)
1615{
1616    status_t err;
1617    if (enabled) {
1618        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1619                               reservedFlags);
1620
1621    } else {
1622        err = mService->disable(this, handle);
1623    }
1624    return err;
1625}
1626
1627status_t SensorService::SensorEventConnection::setEventRate(
1628        int handle, nsecs_t samplingPeriodNs)
1629{
1630    return mService->setEventRate(this, handle, samplingPeriodNs);
1631}
1632
1633status_t  SensorService::SensorEventConnection::flush() {
1634    return  mService->flushSensor(this);
1635}
1636
1637int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
1638    if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1639        {
1640            // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1641            // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1642            // can release the wake-lock.
1643            ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1644            Mutex::Autolock _l(mConnectionLock);
1645            mDead = true;
1646            mWakeLockRefCount = 0;
1647            updateLooperRegistrationLocked(mService->getLooper());
1648        }
1649        mService->checkWakeLockState();
1650        if (mDataInjectionMode) {
1651            // If the Looper has encountered some error in data injection mode, reset SensorService
1652            // back to normal mode.
1653            mService->resetToNormalMode();
1654            mDataInjectionMode = false;
1655        }
1656        return 1;
1657    }
1658
1659    if (events & ALOOPER_EVENT_INPUT) {
1660        unsigned char buf[sizeof(sensors_event_t)];
1661        ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
1662        {
1663           Mutex::Autolock _l(mConnectionLock);
1664           if (numBytesRead == sizeof(sensors_event_t)) {
1665               if (!mDataInjectionMode) {
1666                   ALOGE("Data injected in normal mode, dropping event"
1667                         "package=%s uid=%d", mPackageName.string(), mUid);
1668                   // Unregister call backs.
1669                   return 0;
1670               }
1671               SensorDevice& dev(SensorDevice::getInstance());
1672               sensors_event_t sensor_event;
1673               memset(&sensor_event, 0, sizeof(sensor_event));
1674               memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1675               Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1676               sensor_event.type = sensor.getType();
1677               dev.injectSensorData(&sensor_event, 1);
1678#if DEBUG_CONNECTIONS
1679               ++mEventsReceived;
1680#endif
1681           } else if (numBytesRead == sizeof(uint32_t)) {
1682               uint32_t numAcks = 0;
1683               memcpy(&numAcks, buf, numBytesRead);
1684               // Sanity check to ensure  there are no read errors in recv, numAcks is always
1685               // within the range and not zero. If any of the above don't hold reset
1686               // mWakeLockRefCount to zero.
1687               if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1688                   mWakeLockRefCount -= numAcks;
1689               } else {
1690                   mWakeLockRefCount = 0;
1691               }
1692#if DEBUG_CONNECTIONS
1693               mTotalAcksReceived += numAcks;
1694#endif
1695           } else {
1696               // Read error, reset wakelock refcount.
1697               mWakeLockRefCount = 0;
1698           }
1699        }
1700        // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1701        // here as checkWakeLockState() will need it.
1702        if (mWakeLockRefCount == 0) {
1703            mService->checkWakeLockState();
1704        }
1705        // continue getting callbacks.
1706        return 1;
1707    }
1708
1709    if (events & ALOOPER_EVENT_OUTPUT) {
1710        // send sensor data that is stored in mEventCache for this connection.
1711        mService->sendEventsFromCache(this);
1712    }
1713    return 1;
1714}
1715
1716int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1717    int fifoWakeUpSensors = 0;
1718    int fifoNonWakeUpSensors = 0;
1719    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1720        const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1721        if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1722            // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1723            // non wake_up sensors.
1724            if (sensor.isWakeUpSensor()) {
1725                fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1726            } else {
1727                fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1728            }
1729        } else {
1730            // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1731            if (sensor.isWakeUpSensor()) {
1732                fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1733                                          fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1734
1735            } else {
1736                fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1737                                          fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1738
1739            }
1740        }
1741   }
1742   if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1743       // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
1744       // size that is equal to that of the batch mode.
1745       // ALOGW("Write failure in non-batch mode");
1746       return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
1747   }
1748   return fifoWakeUpSensors + fifoNonWakeUpSensors;
1749}
1750
1751// ---------------------------------------------------------------------------
1752}; // namespace android
1753
1754