blob: a857366fb128aa18282f63d9d67397585e95f201 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
34#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070035#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070037
38#include <gui/ISensorServer.h>
39#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070040#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070041
42#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070043#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070044
Mathias Agopian787ac1b2012-09-18 18:49:18 -070045#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080047#include "GravitySensor.h"
48#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080050#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070051#include "SensorFusion.h"
52#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070053
54namespace android {
55// ---------------------------------------------------------------------------
56
Mathias Agopian33015422011-05-27 18:18:13 -070057/*
58 * Notes:
59 *
60 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070061 * - run mag sensor from time to time to force calibration
62 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63 *
64 */
65
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070066const char* SensorService::WAKE_LOCK_NAME = "SensorService";
67
Mathias Agopianfc328812010-07-14 23:41:37 -070068SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070069 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
70 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070071{
72}
73
74void SensorService::onFirstRef()
75{
Steve Blocka5512372011-12-20 16:23:08 +000076 ALOGD("nuSensorService starting...");
Mathias Agopian50df2952010-07-19 19:09:10 -070077
Mathias Agopianf001c922010-11-11 17:58:51 -080078 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070079
Mathias Agopianf001c922010-11-11 17:58:51 -080080 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080081 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070082 ssize_t count = dev.getSensorList(&list);
83 if (count > 0) {
84 ssize_t orientationIndex = -1;
85 bool hasGyro = false;
86 uint32_t virtualSensorsNeeds =
87 (1<<SENSOR_TYPE_GRAVITY) |
88 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
89 (1<<SENSOR_TYPE_ROTATION_VECTOR);
90
91 mLastEventSeen.setCapacity(count);
92 for (ssize_t i=0 ; i<count ; i++) {
93 registerSensor( new HardwareSensor(list[i]) );
94 switch (list[i].type) {
95 case SENSOR_TYPE_ORIENTATION:
96 orientationIndex = i;
97 break;
98 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -070099 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700100 hasGyro = true;
101 break;
102 case SENSOR_TYPE_GRAVITY:
103 case SENSOR_TYPE_LINEAR_ACCELERATION:
104 case SENSOR_TYPE_ROTATION_VECTOR:
105 virtualSensorsNeeds &= ~(1<<list[i].type);
106 break;
107 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700108 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700109
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700110 // it's safe to instantiate the SensorFusion object here
111 // (it wants to be instantiated after h/w sensors have been
112 // registered)
113 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700114
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700115 // build the sensor list returned to users
116 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700117
118 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700119 Sensor aSensor;
120
121 // Add Android virtual sensors if they're not already
122 // available in the HAL
123
124 aSensor = registerVirtualSensor( new RotationVectorSensor() );
125 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
126 mUserSensorList.add(aSensor);
127 }
128
129 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
130 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
131 mUserSensorList.add(aSensor);
132 }
133
134 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
135 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
136 mUserSensorList.add(aSensor);
137 }
138
139 aSensor = registerVirtualSensor( new OrientationSensor() );
140 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
141 // if we are doing our own rotation-vector, also add
142 // the orientation sensor and remove the HAL provided one.
143 mUserSensorList.replaceAt(aSensor, orientationIndex);
144 }
145
Mathias Agopian33264862012-06-28 19:46:54 -0700146 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700147 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700148 registerVirtualSensor( new GyroDriftSensor() );
149 }
150
Mathias Agopian33264862012-06-28 19:46:54 -0700151 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700152 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700153
Aravind Akella5466c3d2014-08-22 16:11:10 -0700154 // Check if the device really supports batching by looking at the FIFO event
155 // counts for each sensor.
156 bool batchingSupported = false;
157 for (int i = 0; i < mSensorList.size(); ++i) {
158 if (mSensorList[i].getFifoMaxEventCount() > 0) {
159 batchingSupported = true;
160 break;
161 }
162 }
163
164 if (batchingSupported) {
165 // Increase socket buffer size to a max of 100 KB for batching capabilities.
166 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
167 } else {
168 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
169 }
170
171 // Compare the socketBufferSize value against the system limits and limit
172 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700173 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
174 char line[128];
175 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
176 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700177 size_t maxSystemSocketBufferSize;
178 sscanf(line, "%zu", &maxSystemSocketBufferSize);
179 if (mSocketBufferSize > maxSystemSocketBufferSize) {
180 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700181 }
182 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700183 if (fp) {
184 fclose(fp);
185 }
186
Aravind Akella9a844cf2014-02-11 18:58:52 -0800187 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700188 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700189 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
190 mSensorEventBuffer = new sensors_event_t[minBufferSize];
191 mSensorEventScratch = new sensors_event_t[minBufferSize];
192 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akella7830ef32014-10-07 14:13:12 -0700193
Aravind Akellab4373ac2014-10-29 17:55:20 -0700194 mAckReceiver = new SensorEventAckReceiver(this);
195 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700196 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700197 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700198 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700199 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700200}
201
Mathias Agopian03193062013-05-10 19:32:39 -0700202Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800203{
204 sensors_event_t event;
205 memset(&event, 0, sizeof(event));
206
207 const Sensor sensor(s->getSensor());
208 // add to the sensor list (returned to clients)
209 mSensorList.add(sensor);
210 // add to our handle->SensorInterface mapping
211 mSensorMap.add(sensor.getHandle(), s);
212 // create an entry in the mLastEventSeen array
213 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700214
215 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800216}
217
Mathias Agopian03193062013-05-10 19:32:39 -0700218Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800219{
Mathias Agopian03193062013-05-10 19:32:39 -0700220 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800221 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700222 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800223}
224
Mathias Agopianfc328812010-07-14 23:41:37 -0700225SensorService::~SensorService()
226{
Mathias Agopianf001c922010-11-11 17:58:51 -0800227 for (size_t i=0 ; i<mSensorMap.size() ; i++)
228 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700229}
230
Mathias Agopian1cb13462011-06-27 16:05:52 -0700231static const String16 sDump("android.permission.DUMP");
232
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700233status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700234{
Mathias Agopianfc328812010-07-14 23:41:37 -0700235 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700236 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700237 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000238 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700239 IPCThreadState::self()->getCallingPid(),
240 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700241 } else {
242 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700243 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700244 for (size_t i=0 ; i<mSensorList.size() ; i++) {
245 const Sensor& s(mSensorList[i]);
246 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700247 result.appendFormat(
Aravind Akella0b6acb22014-10-18 16:37:13 -0700248 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700249 s.getName().string(),
250 s.getVendor().string(),
Aravind Akella0b6acb22014-10-18 16:37:13 -0700251 s.getVersion(),
Aravind Akella70018042014-04-07 22:52:37 +0000252 s.getStringType().string(),
253 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700254 s.getRequiredPermission().string(),
255 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700256
Aravind Akella0e025c52014-06-03 19:19:57 -0700257 const int reportingMode = s.getReportingMode();
258 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700259 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700260 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700261 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700262 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700263 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700264 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700265 result.append(" special-trigger | ");
266 }
267
268 if (s.getMaxDelay() > 0) {
269 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
270 } else {
271 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700272 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700273
274 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700275 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700276 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700277 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700278 }
279
Aravind Akella724d91d2013-06-27 12:04:23 -0700280 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000281 result.appendFormat("FifoMax=%d events | ",
282 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700283 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700284 result.append("no batching | ");
285 }
286
287 if (s.isWakeUpSensor()) {
288 result.appendFormat("wakeUp | ");
289 } else {
290 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700291 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700292
293 switch (s.getType()) {
294 case SENSOR_TYPE_ROTATION_VECTOR:
295 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
296 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700297 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
298 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700299 break;
300 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
301 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
302 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700303 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
304 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
305 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700306 break;
307 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
308 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700309 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
310 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700311 break;
312 case SENSOR_TYPE_SIGNIFICANT_MOTION:
313 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700314 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700315 break;
316 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700317 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
318 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700319 break;
320 default:
321 // default to 3 values
322 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700323 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
324 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700325 break;
326 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700327 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700328 }
329 SensorFusion::getInstance().dump(result);
330 SensorDevice::getInstance().dump(result);
331
Mathias Agopianba02cd22013-07-03 16:20:57 -0700332 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700333 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700334 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700335 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700336 getSensorName(handle).string(),
337 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700338 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700339 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700340
Aravind Akella5466c3d2014-08-22 16:11:10 -0700341 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700342 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800343 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700344 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700345
346 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
347 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
348 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700349 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700350 connection->dump(result);
351 }
352 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700353 }
354 write(fd, result.string(), result.size());
355 return NO_ERROR;
356}
357
Aravind Akella9a844cf2014-02-11 18:58:52 -0800358void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700359 sensors_event_t const* buffer, const int count) {
360 for (int i=0 ; i<count ; i++) {
361 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700362 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
363 handle = buffer[i].meta_data.sensor;
364 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700365 if (connection->hasSensor(handle)) {
366 SensorInterface* sensor = mSensorMap.valueFor(handle);
367 // If this buffer has an event from a one_shot sensor and this connection is registered
368 // for this particular one_shot sensor, try cleaning up the connection.
369 if (sensor != NULL &&
370 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
371 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800372 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700373 }
374 }
375 }
376}
377
Mathias Agopianfc328812010-07-14 23:41:37 -0700378bool SensorService::threadLoop()
379{
Steve Blocka5512372011-12-20 16:23:08 +0000380 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700381
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700382 // each virtual sensor could generate an event per "real" event, that's why we need
383 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
384 // in practice, this is too aggressive, but guaranteed to be enough.
385 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
386 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
387
Mathias Agopianf001c922010-11-11 17:58:51 -0800388 SensorDevice& device(SensorDevice::getInstance());
389 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700390
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700391 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700392 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700393 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
394 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000395 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700396 break;
397 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700398
399 // Reset sensors_event_t.flags to zero for all events in the buffer.
400 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700401 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700402 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700403
404 // Make a copy of the connection vector as some connections may be removed during the
405 // course of this loop (especially when one-shot sensor events are present in the
406 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
407 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
408 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
409 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
410 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700411 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800412 Mutex::Autolock _l(mLock);
413 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
414 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
415 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
416 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
417 // releasing the wakelock.
418 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700419 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700420 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800421 bufferHasWakeUpEvent = true;
422 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700423 }
424 }
425
Aravind Akella9a844cf2014-02-11 18:58:52 -0800426 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700427 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800428 }
Aravind Akella8493b792014-09-08 15:45:47 -0700429 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800430
Mathias Agopianf001c922010-11-11 17:58:51 -0800431 // handle virtual sensors
432 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700433 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800434 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800435 if (activeVirtualSensorCount) {
436 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700437 SensorFusion& fusion(SensorFusion::getInstance());
438 if (fusion.isEnabled()) {
439 for (size_t i=0 ; i<size_t(count) ; i++) {
440 fusion.process(event[i]);
441 }
442 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700443 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800444 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700445 if (count + k >= minBufferSize) {
446 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700447 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700448 count, k, minBufferSize);
449 break;
450 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800451 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800452 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700453 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700454 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800455 k++;
456 }
457 }
458 }
459 if (k) {
460 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700461 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800462 count += k;
463 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700464 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700465 }
466 }
467 }
468
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700469 // handle backward compatibility for RotationVector sensor
470 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
471 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700472 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700473 // All the 4 components of the quaternion should be available
474 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700475 mSensorEventBuffer[i].data[4] = -1;
476 }
477 }
478 }
479
480 // Map flush_complete_events in the buffer to SensorEventConnections which called
481 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
482 // SensorEventConnection mapped to the corresponding flush_complete_event in
483 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
484 for (int i = 0; i < count; ++i) {
485 mMapFlushEventsToConnections[i] = NULL;
486 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
487 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
488 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
489 if (rec != NULL) {
490 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
491 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700492 }
493 }
494 }
495
Aravind Akella9a844cf2014-02-11 18:58:52 -0800496 // Send our events to clients. Check the state of wake lock for each client and release the
497 // lock if none of the clients need it.
498 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700499 size_t numConnections = activeConnections.size();
500 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700501 if (activeConnections[i] != 0) {
502 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700503 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700504 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700505 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
506 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700507 if (activeConnections[i]->hasOneShotSensors()) {
508 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
509 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700510 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800511 }
512 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700513
Aravind Akella9a844cf2014-02-11 18:58:52 -0800514 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700515 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800516 }
Aravind Akella8493b792014-09-08 15:45:47 -0700517 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700518
Steve Block3c20fbe2012-01-05 23:22:43 +0000519 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800520 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700521 return false;
522}
523
Aravind Akella56ae4262014-07-10 16:01:10 -0700524sp<Looper> SensorService::getLooper() const {
525 return mLooper;
526}
527
Aravind Akellab4373ac2014-10-29 17:55:20 -0700528void SensorService::resetAllWakeLockRefCounts() {
529 SortedVector< sp<SensorEventConnection> > activeConnections;
530 populateActiveConnections(&activeConnections);
531 {
532 Mutex::Autolock _l(mLock);
533 for (size_t i=0 ; i < activeConnections.size(); ++i) {
534 if (activeConnections[i] != 0) {
535 activeConnections[i]->resetWakeLockRefCount();
536 }
537 }
538 setWakeLockAcquiredLocked(false);
539 }
540}
541
542void SensorService::setWakeLockAcquiredLocked(bool acquire) {
543 if (acquire) {
544 if (!mWakeLockAcquired) {
545 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
546 mWakeLockAcquired = true;
547 }
548 mLooper->wake();
549 } else {
550 if (mWakeLockAcquired) {
551 release_wake_lock(WAKE_LOCK_NAME);
552 mWakeLockAcquired = false;
553 }
554 }
555}
556
557
558bool SensorService::isWakeLockAcquired() {
559 Mutex::Autolock _l(mLock);
560 return mWakeLockAcquired;
561}
562
Aravind Akella56ae4262014-07-10 16:01:10 -0700563bool SensorService::SensorEventAckReceiver::threadLoop() {
564 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700565 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700566 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700567 bool wakeLockAcquired = mService->isWakeLockAcquired();
568 int timeout = -1;
569 if (wakeLockAcquired) timeout = 5000;
570 int ret = looper->pollOnce(timeout);
571 if (ret == ALOOPER_POLL_TIMEOUT) {
572 mService->resetAllWakeLockRefCounts();
573 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700574 } while(!Thread::exitPending());
575 return false;
576}
577
Aravind Akella9a844cf2014-02-11 18:58:52 -0800578void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800579 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800580 const sensors_event_t* last = NULL;
581 for (size_t i = 0; i < count; i++) {
582 const sensors_event_t* event = &buffer[i];
583 if (event->type != SENSOR_TYPE_META_DATA) {
584 if (last && event->sensor != last->sensor) {
585 mLastEventSeen.editValueFor(last->sensor) = *last;
586 }
587 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800588 }
589 }
Aravind Akella4b847042014-03-03 19:02:46 -0800590 if (last) {
591 mLastEventSeen.editValueFor(last->sensor) = *last;
592 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800593}
594
Mathias Agopianf001c922010-11-11 17:58:51 -0800595void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
596{
597 struct compar {
598 static int cmp(void const* lhs, void const* rhs) {
599 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
600 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700601 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800602 }
603 };
604 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
605}
606
Mathias Agopian5d270722010-07-19 15:20:39 -0700607String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700608 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700609 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700610 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700611 if (sensor.getHandle() == handle) {
612 return sensor.getName();
613 }
614 }
615 String8 result("unknown");
616 return result;
617}
618
Aravind Akellab4099e72013-10-15 15:43:10 -0700619bool SensorService::isVirtualSensor(int handle) const {
620 SensorInterface* sensor = mSensorMap.valueFor(handle);
621 return sensor->isVirtual();
622}
623
Aravind Akella9a844cf2014-02-11 18:58:52 -0800624bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700625 int handle = event.sensor;
626 if (event.type == SENSOR_TYPE_META_DATA) {
627 handle = event.meta_data.sensor;
628 }
629 SensorInterface* sensor = mSensorMap.valueFor(handle);
630 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800631}
632
Aravind Akella6c2664a2014-08-13 12:24:50 -0700633
634SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
635 return mActiveSensors.valueFor(handle);
636}
637
Mathias Agopianfc328812010-07-14 23:41:37 -0700638Vector<Sensor> SensorService::getSensorList()
639{
Mathias Agopian33264862012-06-28 19:46:54 -0700640 char value[PROPERTY_VALUE_MAX];
641 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000642 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
643 mUserSensorListDebug : mUserSensorList;
644 Vector<Sensor> accessibleSensorList;
645 for (size_t i = 0; i < initialSensorList.size(); i++) {
646 Sensor sensor = initialSensorList[i];
647 if (canAccessSensor(sensor)) {
648 accessibleSensorList.add(sensor);
649 } else {
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100650 ALOGI("Skipped sensor %s because it requires permission %s",
651 sensor.getName().string(),
652 sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +0000653 }
Mathias Agopian33264862012-06-28 19:46:54 -0700654 }
Aravind Akella70018042014-04-07 22:52:37 +0000655 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700656}
657
658sp<ISensorEventConnection> SensorService::createSensorEventConnection()
659{
Mathias Agopian5307d172012-09-18 17:02:43 -0700660 uid_t uid = IPCThreadState::self()->getCallingUid();
661 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700662 return result;
663}
664
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800665void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700666{
667 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800668 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700669 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700670 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700671 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800672 int handle = mActiveSensors.keyAt(i);
673 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700674 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800675 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000676 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800677 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800678 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800679 }
Aravind Akella8a969552014-09-28 17:52:41 -0700680 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800681 }
682 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700683 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000684 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700685 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700686 c, i, handle);
687
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800688 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000689 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700690 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800691 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700692 delete rec;
693 size--;
694 } else {
695 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700696 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700697 }
Aravind Akella8a969552014-09-28 17:52:41 -0700698 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700699 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700700 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800701 if (c->needsWakeLock()) {
702 checkWakeLockStateLocked();
703 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700704}
705
Aravind Akella70018042014-04-07 22:52:37 +0000706Sensor SensorService::getSensorFromHandle(int handle) const {
707 return mSensorMap.valueFor(handle)->getSensor();
708}
709
Mathias Agopianfc328812010-07-14 23:41:37 -0700710status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700711 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700712{
Mathias Agopian50df2952010-07-19 19:09:10 -0700713 if (mInitCheck != NO_ERROR)
714 return mInitCheck;
715
Mathias Agopianf001c922010-11-11 17:58:51 -0800716 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700717 if (sensor == NULL) {
718 return BAD_VALUE;
719 }
Aravind Akella70018042014-04-07 22:52:37 +0000720
721 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
722 return BAD_VALUE;
723 }
724
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700725 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700726 SensorRecord* rec = mActiveSensors.valueFor(handle);
727 if (rec == 0) {
728 rec = new SensorRecord(connection);
729 mActiveSensors.add(handle, rec);
730 if (sensor->isVirtual()) {
731 mActiveVirtualSensors.add(handle, sensor);
732 }
733 } else {
734 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800735 // this sensor is already activated, but we are adding a connection that uses it.
736 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700737 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700738 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800739 // NOTE: The wake_up flag of this event may get set to
740 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700741 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
742 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800743 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700744 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800745 }
746 connection->sendEvents(&event, 1, NULL);
747 if (!connection->needsWakeLock() && mWakeLockAcquired) {
748 checkWakeLockStateLocked();
749 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700750 }
751 }
752 }
753 }
754
755 if (connection->addSensor(handle)) {
756 BatteryService::enableSensor(connection->getUid(), handle);
757 // the sensor was added (which means it wasn't already there)
758 // so, see if this connection becomes active
759 if (mActiveConnections.indexOf(connection) < 0) {
760 mActiveConnections.add(connection);
761 }
762 } else {
763 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
764 handle, connection.get());
765 }
766
Aravind Akella724d91d2013-06-27 12:04:23 -0700767 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
768 if (samplingPeriodNs < minDelayNs) {
769 samplingPeriodNs = minDelayNs;
770 }
771
Aravind Akella6c2664a2014-08-13 12:24:50 -0700772 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
773 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700774 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
775
776 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
777 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700778
Aravind Akella5466c3d2014-08-22 16:11:10 -0700779 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
780 // event before sending events on this connection. Ignore one-shot sensors which don't
781 // support flush(). Also if this sensor isn't already active, don't call flush().
782 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
783 rec->getNumConnections() > 1) {
784 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700785 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700786 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700787 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700788 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700789 } else {
790 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700791 }
792 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700793
794 if (err == NO_ERROR) {
795 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
796 err = sensor->activate(connection.get(), true);
797 }
798
Aravind Akella8a969552014-09-28 17:52:41 -0700799 if (err == NO_ERROR) {
800 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700801 }
802
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700803 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700804 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700805 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700806 }
807 return err;
808}
809
810status_t SensorService::disable(const sp<SensorEventConnection>& connection,
811 int handle)
812{
Mathias Agopian50df2952010-07-19 19:09:10 -0700813 if (mInitCheck != NO_ERROR)
814 return mInitCheck;
815
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700816 Mutex::Autolock _l(mLock);
817 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700818 if (err == NO_ERROR) {
819 SensorInterface* sensor = mSensorMap.valueFor(handle);
820 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
821 }
822 return err;
823}
824
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700825status_t SensorService::cleanupWithoutDisable(
826 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700827 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700828 return cleanupWithoutDisableLocked(connection, handle);
829}
830
831status_t SensorService::cleanupWithoutDisableLocked(
832 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700833 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700834 if (rec) {
835 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700836 if (connection->removeSensor(handle)) {
837 BatteryService::disableSensor(connection->getUid(), handle);
838 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700839 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700840 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700841 mActiveConnections.remove(connection);
842 }
843 // see if this sensor becomes inactive
844 if (rec->removeConnection(connection)) {
845 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800846 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700847 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700848 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700849 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700850 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700851 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700852}
853
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700854status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700855 int handle, nsecs_t ns)
856{
Mathias Agopian50df2952010-07-19 19:09:10 -0700857 if (mInitCheck != NO_ERROR)
858 return mInitCheck;
859
Mathias Agopianae09d652011-11-01 17:37:49 -0700860 SensorInterface* sensor = mSensorMap.valueFor(handle);
861 if (!sensor)
862 return BAD_VALUE;
863
Aravind Akella70018042014-04-07 22:52:37 +0000864 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
865 return BAD_VALUE;
866 }
867
Mathias Agopian1cd70002010-07-21 15:59:50 -0700868 if (ns < 0)
869 return BAD_VALUE;
870
Mathias Agopian62569ec2011-11-07 21:21:47 -0800871 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
872 if (ns < minDelayNs) {
873 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700874 }
875
Mathias Agopianf001c922010-11-11 17:58:51 -0800876 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700877}
878
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700879status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
Aravind Akella70018042014-04-07 22:52:37 +0000880 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700881 SensorDevice& dev(SensorDevice::getInstance());
882 const int halVersion = dev.getHalDeviceVersion();
883 status_t err(NO_ERROR);
884 Mutex::Autolock _l(mLock);
885 // Loop through all sensors for this connection and call flush on each of them.
886 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
887 const int handle = connection->mSensorInfo.keyAt(i);
888 SensorInterface* sensor = mSensorMap.valueFor(handle);
889 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
890 ALOGE("flush called on a one-shot sensor");
891 err = INVALID_OPERATION;
892 continue;
893 }
Aravind Akella8493b792014-09-08 15:45:47 -0700894 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700895 // For older devices just increment pending flush count which will send a trivial
896 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700897 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700898 } else {
899 status_t err_flush = sensor->flush(connection.get(), handle);
900 if (err_flush == NO_ERROR) {
901 SensorRecord* rec = mActiveSensors.valueFor(handle);
902 if (rec != NULL) rec->addPendingFlushConnection(connection);
903 }
904 err = (err_flush != NO_ERROR) ? err_flush : err;
905 }
Aravind Akella70018042014-04-07 22:52:37 +0000906 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700907 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -0700908}
Aravind Akella70018042014-04-07 22:52:37 +0000909
Aravind Akella70018042014-04-07 22:52:37 +0000910bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700911 return (sensor.getRequiredPermission().isEmpty()) ||
912 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +0000913}
914
915bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
916 if (canAccessSensor(sensor)) {
917 return true;
918 } else {
919 String8 errorMessage;
920 errorMessage.appendFormat(
921 "%s a sensor (%s) without holding its required permission: %s",
922 operation,
923 sensor.getName().string(),
924 sensor.getRequiredPermission().string());
925 return false;
926 }
927}
928
Aravind Akella9a844cf2014-02-11 18:58:52 -0800929void SensorService::checkWakeLockState() {
930 Mutex::Autolock _l(mLock);
931 checkWakeLockStateLocked();
932}
933
934void SensorService::checkWakeLockStateLocked() {
935 if (!mWakeLockAcquired) {
936 return;
937 }
938 bool releaseLock = true;
939 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
940 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
941 if (connection != 0) {
942 if (connection->needsWakeLock()) {
943 releaseLock = false;
944 break;
945 }
946 }
947 }
948 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700949 setWakeLockAcquiredLocked(false);
950 }
951}
952
953void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
954 Mutex::Autolock _l(mLock);
955 connection->writeToSocketFromCache();
956 if (connection->needsWakeLock()) {
957 setWakeLockAcquiredLocked(true);
958 }
959}
960
961void SensorService::populateActiveConnections(
962 SortedVector< sp<SensorEventConnection> >* activeConnections) {
963 Mutex::Autolock _l(mLock);
964 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
965 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
966 if (connection != 0) {
967 activeConnections->add(connection);
968 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800969 }
970}
Aravind Akella6c2664a2014-08-13 12:24:50 -0700971
Mathias Agopianfc328812010-07-14 23:41:37 -0700972// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -0700973SensorService::SensorRecord::SensorRecord(
974 const sp<SensorEventConnection>& connection)
975{
976 mConnections.add(connection);
977}
978
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700979bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700980 const sp<SensorEventConnection>& connection)
981{
982 if (mConnections.indexOf(connection) < 0) {
983 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700984 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700985 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700986 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700987}
988
989bool SensorService::SensorRecord::removeConnection(
990 const wp<SensorEventConnection>& connection)
991{
992 ssize_t index = mConnections.indexOf(connection);
993 if (index >= 0) {
994 mConnections.removeItemsAt(index, 1);
995 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700996 // Remove this connections from the queue of flush() calls made on this sensor.
997 for (Vector< wp<SensorEventConnection> >::iterator it =
998 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -0700999
Aravind Akella6c2664a2014-08-13 12:24:50 -07001000 if (it->unsafe_get() == connection.unsafe_get()) {
1001 it = mPendingFlushConnections.erase(it);
1002 } else {
1003 ++it;
1004 }
1005 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001006 return mConnections.size() ? false : true;
1007}
1008
Aravind Akella6c2664a2014-08-13 12:24:50 -07001009void SensorService::SensorRecord::addPendingFlushConnection(
1010 const sp<SensorEventConnection>& connection) {
1011 mPendingFlushConnections.add(connection);
1012}
1013
1014void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1015 if (mPendingFlushConnections.size() > 0) {
1016 mPendingFlushConnections.removeAt(0);
1017 }
1018}
1019
1020SensorService::SensorEventConnection *
1021SensorService::SensorRecord::getFirstPendingFlushConnection() {
1022 if (mPendingFlushConnections.size() > 0) {
1023 return mPendingFlushConnections[0].unsafe_get();
1024 }
1025 return NULL;
1026}
1027
Mathias Agopianfc328812010-07-14 23:41:37 -07001028// ---------------------------------------------------------------------------
1029
1030SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -07001031 const sp<SensorService>& service, uid_t uid)
Aravind Akella8a969552014-09-28 17:52:41 -07001032 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
1033 mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001034 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001035#if DEBUG_CONNECTIONS
1036 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001037 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001038#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001039}
1040
Aravind Akella56ae4262014-07-10 16:01:10 -07001041SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001042 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001043 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001044 if (mEventCache != NULL) {
1045 delete mEventCache;
1046 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001047}
1048
Aravind Akella56ae4262014-07-10 16:01:10 -07001049void SensorService::SensorEventConnection::onFirstRef() {
1050 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001051}
1052
Aravind Akella9a844cf2014-02-11 18:58:52 -08001053bool SensorService::SensorEventConnection::needsWakeLock() {
1054 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001055 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001056}
1057
Aravind Akellab4373ac2014-10-29 17:55:20 -07001058void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1059 Mutex::Autolock _l(mConnectionLock);
1060 mWakeLockRefCount = 0;
1061}
1062
Aravind Akella4c8b9512013-09-05 17:03:38 -07001063void SensorService::SensorEventConnection::dump(String8& result) {
1064 Mutex::Autolock _l(mConnectionLock);
Aravind Akella0ec20662014-09-14 17:29:48 -07001065 result.appendFormat("\t WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1066 mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001067 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1068 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001069 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001070 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001071 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001072 flushInfo.mFirstFlushPending ? "First flush pending" :
1073 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001074 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001075 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001076#if DEBUG_CONNECTIONS
1077 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1078 " total_acks_needed %d | total_acks_recvd %d\n",
1079 mEventsReceived,
1080 mEventsSent,
1081 mEventsSentFromCache,
1082 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1083 mTotalAcksNeeded,
1084 mTotalAcksReceived);
1085#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001086}
1087
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001088bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001089 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +00001090 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1091 return false;
1092 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001093 if (mSensorInfo.indexOfKey(handle) < 0) {
1094 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001095 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001096 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001097 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001098}
1099
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001100bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001101 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001102 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001103 return true;
1104 }
1105 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001106}
1107
1108bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001109 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001110 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001111}
1112
1113bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001114 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001115 return mSensorInfo.size() ? true : false;
1116}
1117
Aravind Akella8493b792014-09-08 15:45:47 -07001118bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1119 Mutex::Autolock _l(mConnectionLock);
1120 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1121 const int handle = mSensorInfo.keyAt(i);
1122 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1123 return true;
1124 }
1125 }
1126 return false;
1127}
1128
Aravind Akella4c8b9512013-09-05 17:03:38 -07001129void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1130 bool value) {
1131 Mutex::Autolock _l(mConnectionLock);
1132 ssize_t index = mSensorInfo.indexOfKey(handle);
1133 if (index >= 0) {
1134 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1135 flushInfo.mFirstFlushPending = value;
1136 }
1137}
1138
Aravind Akella8a969552014-09-28 17:52:41 -07001139void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1140 Mutex::Autolock _l(mConnectionLock);
1141 updateLooperRegistrationLocked(looper);
1142}
1143
1144void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1145 const sp<Looper>& looper) {
1146 bool isConnectionActive = mSensorInfo.size() > 0;
1147 // If all sensors are unregistered OR Looper has encountered an error, we
1148 // can remove the Fd from the Looper if it has been previously added.
1149 if (!isConnectionActive || mDead) {
1150 if (mHasLooperCallbacks) {
1151 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1152 looper->removeFd(mChannel->getSendFd());
1153 mHasLooperCallbacks = false;
1154 }
1155 return;
1156 }
1157
1158 int looper_flags = 0;
1159 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
1160 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1161 const int handle = mSensorInfo.keyAt(i);
1162 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1163 looper_flags |= ALOOPER_EVENT_INPUT;
1164 break;
1165 }
1166 }
1167 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1168 // the fd has already been added, remove it. This is likely to happen when ALL the
1169 // events stored in the cache have been sent to the corresponding app.
1170 if (looper_flags == 0) {
1171 if (mHasLooperCallbacks) {
1172 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1173 looper->removeFd(mChannel->getSendFd());
1174 mHasLooperCallbacks = false;
1175 }
1176 return;
1177 }
1178 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1179 // registered for wake-up sensors OR for sending events in the cache.
1180 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1181 if (ret == 1) {
1182 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1183 mHasLooperCallbacks = true;
1184 } else {
1185 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1186 }
1187}
1188
1189void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1190 Mutex::Autolock _l(mConnectionLock);
1191 ssize_t index = mSensorInfo.indexOfKey(handle);
1192 if (index >= 0) {
1193 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1194 flushInfo.mPendingFlushEventsToSend++;
1195 }
1196}
1197
Mathias Agopianfc328812010-07-14 23:41:37 -07001198status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001199 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001200 sensors_event_t* scratch,
1201 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001202 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001203 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001204 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001205 if (scratch) {
1206 size_t i=0;
1207 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001208 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001209 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1210 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001211 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001212 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1213 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1214 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001215 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001216 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001217 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001218 // Check if this connection has registered for this sensor. If not continue to the
1219 // next sensor_event.
1220 if (index < 0) {
1221 ++i;
1222 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001223 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001224
Aravind Akella56ae4262014-07-10 16:01:10 -07001225 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001226 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001227 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1228 this == mapFlushEventsToConnections[i]) {
1229 flushInfo.mFirstFlushPending = false;
1230 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1231 buffer[i].meta_data.sensor);
1232 ++i;
1233 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001234 }
1235
1236 // If there is a pending flush complete event for this sensor on this connection,
1237 // ignore the event and proceed to the next.
1238 if (flushInfo.mFirstFlushPending) {
1239 ++i;
1240 continue;
1241 }
1242
1243 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001244 // Keep copying events into the scratch buffer as long as they are regular
1245 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1246 // from the same sensor_handle AND the current connection is mapped to the
1247 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001248 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001249 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001250 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001251 }
1252 ++i;
1253 } else {
1254 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001255 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001256 }
Aravind Akella8493b792014-09-08 15:45:47 -07001257 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1258 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001259 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001260 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001261 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001262 } else {
1263 scratch = const_cast<sensors_event_t *>(buffer);
1264 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001265 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001266
Aravind Akella6c2664a2014-08-13 12:24:50 -07001267 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001268 // Early return if there are no events for this connection.
1269 if (count == 0) {
1270 return status_t(NO_ERROR);
1271 }
1272
1273#if DEBUG_CONNECTIONS
1274 mEventsReceived += count;
1275#endif
1276 if (mCacheSize != 0) {
1277 // There are some events in the cache which need to be sent first. Copy this buffer to
1278 // the end of cache.
1279 if (mCacheSize + count <= mMaxCacheSize) {
1280 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1281 mCacheSize += count;
1282 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001283 // Check if any new sensors have registered on this connection which may have increased
1284 // the max cache size that is desired.
1285 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1286 reAllocateCacheLocked(scratch, count);
1287 return status_t(NO_ERROR);
1288 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001289 // Some events need to be dropped.
1290 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1291 if (remaningCacheSize != 0) {
1292 memcpy(&mEventCache[mCacheSize], scratch,
1293 remaningCacheSize * sizeof(sensors_event_t));
1294 }
1295 int numEventsDropped = count - remaningCacheSize;
1296 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1297 // Drop the first "numEventsDropped" in the cache.
1298 memmove(mEventCache, &mEventCache[numEventsDropped],
1299 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1300
1301 // Copy the remainingEvents in scratch buffer to the end of cache.
1302 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1303 numEventsDropped * sizeof(sensors_event_t));
1304 }
1305 return status_t(NO_ERROR);
1306 }
1307
Aravind Akella6c2664a2014-08-13 12:24:50 -07001308 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1309 if (index_wake_up_event >= 0) {
1310 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1311 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001312#if DEBUG_CONNECTIONS
1313 ++mTotalAcksNeeded;
1314#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001315 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001316
1317 // NOTE: ASensorEvent and sensors_event_t are the same type.
1318 ssize_t size = SensorEventQueue::write(mChannel,
1319 reinterpret_cast<ASensorEvent const*>(scratch), count);
1320 if (size < 0) {
1321 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001322 if (index_wake_up_event >= 0) {
1323 // If there was a wake_up sensor_event, reset the flag.
1324 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001325 if (mWakeLockRefCount > 0) {
1326 --mWakeLockRefCount;
1327 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001328#if DEBUG_CONNECTIONS
1329 --mTotalAcksNeeded;
1330#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001331 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001332 if (mEventCache == NULL) {
1333 mMaxCacheSize = computeMaxCacheSizeLocked();
1334 mEventCache = new sensors_event_t[mMaxCacheSize];
1335 mCacheSize = 0;
1336 }
1337 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1338 mCacheSize += count;
1339
1340 // Add this file descriptor to the looper to get a callback when this fd is available for
1341 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001342 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001343 return size;
1344 }
1345
1346#if DEBUG_CONNECTIONS
1347 if (size > 0) {
1348 mEventsSent += count;
1349 }
1350#endif
1351
1352 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1353}
1354
Aravind Akella6c2664a2014-08-13 12:24:50 -07001355void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1356 int count) {
1357 sensors_event_t *eventCache_new;
1358 const int new_cache_size = computeMaxCacheSizeLocked();
1359 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1360 eventCache_new = new sensors_event_t[new_cache_size];
1361 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1362 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1363
1364 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1365 new_cache_size);
1366
1367 delete mEventCache;
1368 mEventCache = eventCache_new;
1369 mCacheSize += count;
1370 mMaxCacheSize = new_cache_size;
1371}
1372
1373void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1374 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001375 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001376 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001377 // Loop through all the sensors for this connection and check if there are any pending
1378 // flush complete events to be sent.
1379 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1380 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1381 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001382 const int sensor_handle = mSensorInfo.keyAt(i);
1383 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001384 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1385 if (wakeUpSensor) {
1386 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001387 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1388 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001389 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1390 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001391 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001392 return;
1393 }
1394 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1395 flushCompleteEvent.meta_data.sensor);
1396 flushInfo.mPendingFlushEventsToSend--;
1397 }
1398 }
1399}
1400
Aravind Akellab4373ac2014-10-29 17:55:20 -07001401void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001402 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1403 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1404 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1405 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001406 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001407 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001408 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001409 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001410 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001411 int index_wake_up_event =
1412 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1413 if (index_wake_up_event >= 0) {
1414 mEventCache[index_wake_up_event + numEventsSent].flags |=
1415 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1416 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001417#if DEBUG_CONNECTIONS
1418 ++mTotalAcksNeeded;
1419#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001420 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001421
Aravind Akella56ae4262014-07-10 16:01:10 -07001422 ssize_t size = SensorEventQueue::write(mChannel,
1423 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001424 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001425 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001426 if (index_wake_up_event >= 0) {
1427 // If there was a wake_up sensor_event, reset the flag.
1428 mEventCache[index_wake_up_event + numEventsSent].flags &=
1429 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001430 if (mWakeLockRefCount > 0) {
1431 --mWakeLockRefCount;
1432 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001433#if DEBUG_CONNECTIONS
1434 --mTotalAcksNeeded;
1435#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001436 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001437 memmove(mEventCache, &mEventCache[numEventsSent],
1438 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1439 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001440 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001441 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001442 return;
1443 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001444 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001445#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001446 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001447#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001448 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001449 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1450 // All events from the cache have been sent. Reset cache size to zero.
1451 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001452 // There are no more events in the cache. We don't need to poll for write on the fd.
1453 // Update Looper registration.
1454 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001455}
1456
Aravind Akellac551eac2013-10-14 17:04:42 -07001457void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001458 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001459 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001460 // Count flushComplete events in the events that are about to the dropped. These will be sent
1461 // separately before the next batch of events.
1462 for (int j = 0; j < numEventsDropped; ++j) {
1463 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1464 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1465 flushInfo.mPendingFlushEventsToSend++;
1466 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1467 flushInfo.mPendingFlushEventsToSend);
1468 }
1469 }
1470 return;
1471}
1472
Aravind Akella6c2664a2014-08-13 12:24:50 -07001473int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1474 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001475 for (int i = 0; i < count; ++i) {
1476 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001477 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001478 }
1479 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001480 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001481}
1482
Mathias Agopianb3989272011-10-20 18:42:02 -07001483sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001484{
1485 return mChannel;
1486}
1487
1488status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001489 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1490 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001491{
1492 status_t err;
1493 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001494 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1495 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001496
Mathias Agopianfc328812010-07-14 23:41:37 -07001497 } else {
1498 err = mService->disable(this, handle);
1499 }
1500 return err;
1501}
1502
1503status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001504 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001505{
Aravind Akella724d91d2013-06-27 12:04:23 -07001506 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001507}
1508
Aravind Akella701166d2013-10-08 14:59:26 -07001509status_t SensorService::SensorEventConnection::flush() {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001510 return mService->flushSensor(this);
Aravind Akella724d91d2013-06-27 12:04:23 -07001511}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001512
Aravind Akella8a969552014-09-28 17:52:41 -07001513int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001514 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001515 {
1516 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1517 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1518 // can release the wake-lock.
1519 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1520 Mutex::Autolock _l(mConnectionLock);
1521 mDead = true;
1522 mWakeLockRefCount = 0;
1523 updateLooperRegistrationLocked(mService->getLooper());
1524 }
1525 mService->checkWakeLockState();
1526 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001527 }
1528
1529 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akella8a969552014-09-28 17:52:41 -07001530 uint32_t numAcks = 0;
1531 ssize_t ret = ::recv(fd, &numAcks, sizeof(numAcks), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001532 {
1533 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001534 // Sanity check to ensure there are no read errors in recv, numAcks is always
1535 // within the range and not zero. If any of the above don't hold reset mWakeLockRefCount
1536 // to zero.
1537 if (ret != sizeof(numAcks) || numAcks > mWakeLockRefCount || numAcks == 0) {
1538 ALOGE("Looper read error ret=%d numAcks=%d", ret, numAcks);
1539 mWakeLockRefCount = 0;
1540 } else {
1541 mWakeLockRefCount -= numAcks;
Aravind Akella0ec20662014-09-14 17:29:48 -07001542 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001543#if DEBUG_CONNECTIONS
Aravind Akella8a969552014-09-28 17:52:41 -07001544 mTotalAcksReceived += numAcks;
Aravind Akellae74baf62014-08-21 12:28:35 -07001545#endif
Aravind Akella56ae4262014-07-10 16:01:10 -07001546 }
1547 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1548 // here as checkWakeLockState() will need it.
1549 if (mWakeLockRefCount == 0) {
1550 mService->checkWakeLockState();
1551 }
1552 // continue getting callbacks.
1553 return 1;
1554 }
1555
1556 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001557 // send sensor data that is stored in mEventCache for this connection.
1558 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001559 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001560 return 1;
1561}
1562
1563int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1564 int fifoWakeUpSensors = 0;
1565 int fifoNonWakeUpSensors = 0;
1566 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1567 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1568 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1569 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1570 // non wake_up sensors.
1571 if (sensor.isWakeUpSensor()) {
1572 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1573 } else {
1574 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1575 }
1576 } else {
1577 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1578 if (sensor.isWakeUpSensor()) {
1579 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1580 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1581
1582 } else {
1583 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1584 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1585
1586 }
1587 }
1588 }
1589 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1590 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001591 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001592 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001593 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001594 }
1595 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001596}
1597
Mathias Agopianfc328812010-07-14 23:41:37 -07001598// ---------------------------------------------------------------------------
1599}; // namespace android
1600