blob: 8e2109b04c46c7ddd412b0bc72e08d39154ebf71 [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
Svetoslavb412f6e2015-04-29 16:50:41 -070034#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070035#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070036#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070038
39#include <gui/ISensorServer.h>
40#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070041#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070042
43#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070044#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070045
Mathias Agopian787ac1b2012-09-18 18:49:18 -070046#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070047#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080048#include "GravitySensor.h"
49#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070050#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080051#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070052#include "SensorFusion.h"
53#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070054
55namespace android {
56// ---------------------------------------------------------------------------
57
Mathias Agopian33015422011-05-27 18:18:13 -070058/*
59 * Notes:
60 *
61 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070062 * - run mag sensor from time to time to force calibration
63 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
64 *
65 */
66
Aravind Akella8ef3c892015-07-10 11:24:28 -070067const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070068// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070069static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070070
Mathias Agopianfc328812010-07-14 23:41:37 -070071SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070072 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
73 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070074{
75}
76
77void SensorService::onFirstRef()
78{
Steve Blocka5512372011-12-20 16:23:08 +000079 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080080 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070081
Mathias Agopianf001c922010-11-11 17:58:51 -080082 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080083 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070084 ssize_t count = dev.getSensorList(&list);
85 if (count > 0) {
86 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070087 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070088 uint32_t virtualSensorsNeeds =
89 (1<<SENSOR_TYPE_GRAVITY) |
90 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070091 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
92 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
93 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070094
95 mLastEventSeen.setCapacity(count);
96 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070097 bool useThisSensor=true;
98
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070099 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -0700100 case SENSOR_TYPE_ACCELEROMETER:
101 hasAccel = true;
102 break;
103 case SENSOR_TYPE_MAGNETIC_FIELD:
104 hasMag = true;
105 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700106 case SENSOR_TYPE_ORIENTATION:
107 orientationIndex = i;
108 break;
109 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700110 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700111 hasGyro = true;
112 break;
113 case SENSOR_TYPE_GRAVITY:
114 case SENSOR_TYPE_LINEAR_ACCELERATION:
115 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700116 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
117 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
118 if (IGNORE_HARDWARE_FUSION) {
119 useThisSensor = false;
120 } else {
121 virtualSensorsNeeds &= ~(1<<list[i].type);
122 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700123 break;
124 }
Peng Xuf66684a2015-07-23 11:41:53 -0700125 if (useThisSensor) {
126 registerSensor( new HardwareSensor(list[i]) );
127 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700128 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700129
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700130 // it's safe to instantiate the SensorFusion object here
131 // (it wants to be instantiated after h/w sensors have been
132 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700133 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700134
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700135 // build the sensor list returned to users
136 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700137
Aravind Akellaf5047892015-07-20 17:29:33 -0700138 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700139 // Add Android virtual sensors if they're not already
140 // available in the HAL
Peng Xuf66684a2015-07-23 11:41:53 -0700141 Sensor aSensor;
Mathias Agopian03193062013-05-10 19:32:39 -0700142
143 aSensor = registerVirtualSensor( new RotationVectorSensor() );
144 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
145 mUserSensorList.add(aSensor);
146 }
147
Mathias Agopian03193062013-05-10 19:32:39 -0700148 aSensor = registerVirtualSensor( new OrientationSensor() );
149 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
150 // if we are doing our own rotation-vector, also add
151 // the orientation sensor and remove the HAL provided one.
152 mUserSensorList.replaceAt(aSensor, orientationIndex);
153 }
154
Peng Xuf66684a2015-07-23 11:41:53 -0700155 aSensor = registerVirtualSensor(
156 new LinearAccelerationSensor(list, count) );
157 if (virtualSensorsNeeds &
158 (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
159 mUserSensorList.add(aSensor);
160 }
161
Mathias Agopian33264862012-06-28 19:46:54 -0700162 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700163 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700164 registerVirtualSensor( new GyroDriftSensor() );
165 }
166
Peng Xuf66684a2015-07-23 11:41:53 -0700167 if (hasAccel && hasGyro) {
168 Sensor aSensor;
169
170 aSensor = registerVirtualSensor(
171 new GravitySensor(list, count) );
172 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
173 mUserSensorList.add(aSensor);
174 }
175
176 aSensor = registerVirtualSensor(
177 new GameRotationVectorSensor() );
178 if (virtualSensorsNeeds &
179 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) {
180 mUserSensorList.add(aSensor);
181 }
182 }
183
184 if (hasAccel && hasMag) {
185 Sensor aSensor;
186
187 aSensor = registerVirtualSensor(
188 new GeoMagRotationVectorSensor() );
189 if (virtualSensorsNeeds &
190 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) {
191 mUserSensorList.add(aSensor);
192 }
193 }
194
Mathias Agopian33264862012-06-28 19:46:54 -0700195 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700196 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700197
Aravind Akella5466c3d2014-08-22 16:11:10 -0700198 // Check if the device really supports batching by looking at the FIFO event
199 // counts for each sensor.
200 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700201 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700202 if (mSensorList[i].getFifoMaxEventCount() > 0) {
203 batchingSupported = true;
204 break;
205 }
206 }
207
208 if (batchingSupported) {
209 // Increase socket buffer size to a max of 100 KB for batching capabilities.
210 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
211 } else {
212 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
213 }
214
215 // Compare the socketBufferSize value against the system limits and limit
216 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700217 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
218 char line[128];
219 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
220 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700221 size_t maxSystemSocketBufferSize;
222 sscanf(line, "%zu", &maxSystemSocketBufferSize);
223 if (mSocketBufferSize > maxSystemSocketBufferSize) {
224 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700225 }
226 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700227 if (fp) {
228 fclose(fp);
229 }
230
Aravind Akella9a844cf2014-02-11 18:58:52 -0800231 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700232 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700233 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
234 mSensorEventBuffer = new sensors_event_t[minBufferSize];
235 mSensorEventScratch = new sensors_event_t[minBufferSize];
236 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700237 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700238
Aravind Akella18d6d512015-06-18 14:18:28 -0700239 mNextSensorRegIndex = 0;
240 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
241 mLastNSensorRegistrations.push();
242 }
243
244 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700245 mAckReceiver = new SensorEventAckReceiver(this);
246 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700247 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700248 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700249 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700250}
251
Mathias Agopian03193062013-05-10 19:32:39 -0700252Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800253{
254 sensors_event_t event;
255 memset(&event, 0, sizeof(event));
256
257 const Sensor sensor(s->getSensor());
258 // add to the sensor list (returned to clients)
259 mSensorList.add(sensor);
260 // add to our handle->SensorInterface mapping
261 mSensorMap.add(sensor.getHandle(), s);
262 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700263 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700264
265 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800266}
267
Mathias Agopian03193062013-05-10 19:32:39 -0700268Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800269{
Mathias Agopian03193062013-05-10 19:32:39 -0700270 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800271 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700272 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800273}
274
Mathias Agopianfc328812010-07-14 23:41:37 -0700275SensorService::~SensorService()
276{
Mathias Agopianf001c922010-11-11 17:58:51 -0800277 for (size_t i=0 ; i<mSensorMap.size() ; i++)
278 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700279}
280
Aravind Akella4949c502015-02-11 15:54:35 -0800281status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700282{
Mathias Agopianfc328812010-07-14 23:41:37 -0700283 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700284 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700285 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000286 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700287 IPCThreadState::self()->getCallingPid(),
288 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700289 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700290 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800291 return INVALID_OPERATION;
292 }
293 Mutex::Autolock _l(mLock);
294 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700295 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700296 // If already in restricted mode. Ignore.
297 if (mCurrentOperatingMode == RESTRICTED) {
298 return status_t(NO_ERROR);
299 }
300 // If in any mode other than normal, ignore.
301 if (mCurrentOperatingMode != NORMAL) {
302 return INVALID_OPERATION;
303 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700304 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800305 dev.disableAllSensors();
306 // Clear all pending flush connections for all active sensors. If one of the active
307 // connections has called flush() and the underlying sensor has been disabled before a
308 // flush complete event is returned, we need to remove the connection from this queue.
309 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
310 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
311 }
Aravind Akella841a5922015-06-29 12:37:48 -0700312 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700313 return status_t(NO_ERROR);
314 } else if (args.size() == 1 && args[0] == String16("enable")) {
315 // If currently in restricted mode, reset back to NORMAL mode else ignore.
316 if (mCurrentOperatingMode == RESTRICTED) {
317 mCurrentOperatingMode = NORMAL;
318 dev.enableAllSensors();
319 }
Aravind Akella841a5922015-06-29 12:37:48 -0700320 if (mCurrentOperatingMode == DATA_INJECTION) {
321 resetToNormalModeLocked();
322 }
323 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700324 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700325 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
326 if (mCurrentOperatingMode == NORMAL) {
327 dev.disableAllSensors();
328 status_t err = dev.setMode(DATA_INJECTION);
329 if (err == NO_ERROR) {
330 mCurrentOperatingMode = DATA_INJECTION;
331 } else {
332 // Re-enable sensors.
333 dev.enableAllSensors();
334 }
335 mWhiteListedPackage.setTo(String8(args[1]));
336 return NO_ERROR;
337 } else if (mCurrentOperatingMode == DATA_INJECTION) {
338 // Already in DATA_INJECTION mode. Treat this as a no_op.
339 return NO_ERROR;
340 } else {
341 // Transition to data injection mode supported only from NORMAL mode.
342 return INVALID_OPERATION;
343 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700344 } else if (mSensorList.size() == 0) {
345 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700346 } else {
347 // Default dump the sensor list and debugging information.
348 result.append("Sensor List:\n");
349 for (size_t i=0 ; i<mSensorList.size() ; i++) {
350 const Sensor& s(mSensorList[i]);
351 result.appendFormat(
352 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
353 s.getName().string(),
354 s.getVendor().string(),
355 s.getVersion(),
356 s.getStringType().string(),
357 s.getHandle(),
358 s.getRequiredPermission().string(),
359 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700360
Aravind Akella444f2672015-05-07 12:40:52 -0700361 const int reportingMode = s.getReportingMode();
362 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
363 result.append(" continuous | ");
364 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
365 result.append(" on-change | ");
366 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
367 result.append(" one-shot | ");
368 } else {
369 result.append(" special-trigger | ");
370 }
371
372 if (s.getMaxDelay() > 0) {
373 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
374 } else {
375 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
376 }
377
378 if (s.getMinDelay() > 0) {
379 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
380 } else {
381 result.appendFormat("minDelay=%dus |", s.getMinDelay());
382 }
383
384 if (s.getFifoMaxEventCount() > 0) {
385 result.appendFormat("FifoMax=%d events | ",
386 s.getFifoMaxEventCount());
387 } else {
388 result.append("no batching | ");
389 }
390
391 if (s.isWakeUpSensor()) {
392 result.appendFormat("wakeUp | ");
393 } else {
394 result.appendFormat("non-wakeUp | ");
395 }
396
Aravind Akella18d6d512015-06-18 14:18:28 -0700397 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
398 if (bufIndex >= 0) {
399 const CircularBuffer* buf = mLastEventSeen.valueAt(bufIndex);
400 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
401 buf->printBuffer(result);
402 } else {
403 result.append("last=<> \n");
404 }
Aravind Akella444f2672015-05-07 12:40:52 -0700405 }
406 result.append("\n");
407 }
408 SensorFusion::getInstance().dump(result);
409 SensorDevice::getInstance().dump(result);
410
411 result.append("Active sensors:\n");
412 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
413 int handle = mActiveSensors.keyAt(i);
414 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
415 getSensorName(handle).string(),
416 handle,
417 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700418 }
419
Andreas Gamped4036b62015-07-28 13:49:04 -0700420 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700421 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700422 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
423 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700424 result.appendFormat("Mode :");
425 switch(mCurrentOperatingMode) {
426 case NORMAL:
427 result.appendFormat(" NORMAL\n");
428 break;
429 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700430 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700431 break;
432 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700433 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700434 }
Aravind Akella444f2672015-05-07 12:40:52 -0700435 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700436
Aravind Akella444f2672015-05-07 12:40:52 -0700437 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
438 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
439 if (connection != 0) {
440 result.appendFormat("Connection Number: %zu \n", i);
441 connection->dump(result);
442 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700443 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700444
445 result.appendFormat("Previous Registrations:\n");
446 // Log in the reverse chronological order.
447 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
448 SENSOR_REGISTRATIONS_BUF_SIZE;
449 const int startIndex = currentIndex;
450 do {
451 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
452 if (SensorRegistrationInfo::isSentinel(reg_info)) {
453 // Ignore sentinel, proceed to next item.
454 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
455 SENSOR_REGISTRATIONS_BUF_SIZE;
456 continue;
457 }
458 if (reg_info.mActivated) {
459 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
460 "samplingRate=%dus maxReportLatency=%dus\n",
461 reg_info.mHour, reg_info.mMin, reg_info.mSec,
462 reg_info.mPackageName.string(), reg_info.mSensorHandle,
463 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
464 } else {
465 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
466 reg_info.mHour, reg_info.mMin, reg_info.mSec,
467 reg_info.mPackageName.string(), reg_info.mSensorHandle);
468 }
469 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
470 SENSOR_REGISTRATIONS_BUF_SIZE;
471 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700472 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700473 }
474 write(fd, result.string(), result.size());
475 return NO_ERROR;
476}
477
Aravind Akella9a844cf2014-02-11 18:58:52 -0800478void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700479 sensors_event_t const* buffer, const int count) {
480 for (int i=0 ; i<count ; i++) {
481 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700482 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
483 handle = buffer[i].meta_data.sensor;
484 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700485 if (connection->hasSensor(handle)) {
486 SensorInterface* sensor = mSensorMap.valueFor(handle);
487 // If this buffer has an event from a one_shot sensor and this connection is registered
488 // for this particular one_shot sensor, try cleaning up the connection.
489 if (sensor != NULL &&
490 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
491 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800492 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700493 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700494
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700495 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700496 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700497}
498
Mathias Agopianfc328812010-07-14 23:41:37 -0700499bool SensorService::threadLoop()
500{
Steve Blocka5512372011-12-20 16:23:08 +0000501 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700502
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700503 // each virtual sensor could generate an event per "real" event, that's why we need
504 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
505 // in practice, this is too aggressive, but guaranteed to be enough.
506 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
507 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
508
Mathias Agopianf001c922010-11-11 17:58:51 -0800509 SensorDevice& device(SensorDevice::getInstance());
510 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700511
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700512 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700513 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700514 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
515 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000516 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700517 break;
518 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700519
520 // Reset sensors_event_t.flags to zero for all events in the buffer.
521 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700522 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700523 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700524
525 // Make a copy of the connection vector as some connections may be removed during the
526 // course of this loop (especially when one-shot sensor events are present in the
527 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
528 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
529 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
530 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
531 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700532 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800533 Mutex::Autolock _l(mLock);
534 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
535 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
536 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
537 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
538 // releasing the wakelock.
539 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700540 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700541 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800542 bufferHasWakeUpEvent = true;
543 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700544 }
545 }
546
Aravind Akella9a844cf2014-02-11 18:58:52 -0800547 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700548 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800549 }
Aravind Akella8493b792014-09-08 15:45:47 -0700550 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800551
Mathias Agopianf001c922010-11-11 17:58:51 -0800552 // handle virtual sensors
553 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700554 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800555 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800556 if (activeVirtualSensorCount) {
557 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700558 SensorFusion& fusion(SensorFusion::getInstance());
559 if (fusion.isEnabled()) {
560 for (size_t i=0 ; i<size_t(count) ; i++) {
561 fusion.process(event[i]);
562 }
563 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700564 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800565 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700566 if (count + k >= minBufferSize) {
567 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700568 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700569 count, k, minBufferSize);
570 break;
571 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800572 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800573 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700574 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700575 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800576 k++;
577 }
578 }
579 }
580 if (k) {
581 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700582 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800583 count += k;
584 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700585 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700586 }
587 }
588 }
589
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700590 // handle backward compatibility for RotationVector sensor
591 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
592 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700593 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700594 // All the 4 components of the quaternion should be available
595 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700596 mSensorEventBuffer[i].data[4] = -1;
597 }
598 }
599 }
600
601 // Map flush_complete_events in the buffer to SensorEventConnections which called
602 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
603 // SensorEventConnection mapped to the corresponding flush_complete_event in
604 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
605 for (int i = 0; i < count; ++i) {
606 mMapFlushEventsToConnections[i] = NULL;
607 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
608 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
609 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
610 if (rec != NULL) {
611 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
612 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700613 }
614 }
615 }
616
Aravind Akella9a844cf2014-02-11 18:58:52 -0800617 // Send our events to clients. Check the state of wake lock for each client and release the
618 // lock if none of the clients need it.
619 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700620 size_t numConnections = activeConnections.size();
621 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700622 if (activeConnections[i] != 0) {
623 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700624 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700625 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700626 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
627 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700628 if (activeConnections[i]->hasOneShotSensors()) {
629 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
630 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700631 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800632 }
633 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700634
Aravind Akella9a844cf2014-02-11 18:58:52 -0800635 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700636 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800637 }
Aravind Akella8493b792014-09-08 15:45:47 -0700638 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700639
Steve Block3c20fbe2012-01-05 23:22:43 +0000640 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800641 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700642 return false;
643}
644
Aravind Akella56ae4262014-07-10 16:01:10 -0700645sp<Looper> SensorService::getLooper() const {
646 return mLooper;
647}
648
Aravind Akellab4373ac2014-10-29 17:55:20 -0700649void SensorService::resetAllWakeLockRefCounts() {
650 SortedVector< sp<SensorEventConnection> > activeConnections;
651 populateActiveConnections(&activeConnections);
652 {
653 Mutex::Autolock _l(mLock);
654 for (size_t i=0 ; i < activeConnections.size(); ++i) {
655 if (activeConnections[i] != 0) {
656 activeConnections[i]->resetWakeLockRefCount();
657 }
658 }
659 setWakeLockAcquiredLocked(false);
660 }
661}
662
663void SensorService::setWakeLockAcquiredLocked(bool acquire) {
664 if (acquire) {
665 if (!mWakeLockAcquired) {
666 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
667 mWakeLockAcquired = true;
668 }
669 mLooper->wake();
670 } else {
671 if (mWakeLockAcquired) {
672 release_wake_lock(WAKE_LOCK_NAME);
673 mWakeLockAcquired = false;
674 }
675 }
676}
677
Aravind Akellab4373ac2014-10-29 17:55:20 -0700678bool SensorService::isWakeLockAcquired() {
679 Mutex::Autolock _l(mLock);
680 return mWakeLockAcquired;
681}
682
Aravind Akella56ae4262014-07-10 16:01:10 -0700683bool SensorService::SensorEventAckReceiver::threadLoop() {
684 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700685 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700686 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700687 bool wakeLockAcquired = mService->isWakeLockAcquired();
688 int timeout = -1;
689 if (wakeLockAcquired) timeout = 5000;
690 int ret = looper->pollOnce(timeout);
691 if (ret == ALOOPER_POLL_TIMEOUT) {
692 mService->resetAllWakeLockRefCounts();
693 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700694 } while(!Thread::exitPending());
695 return false;
696}
697
Aravind Akella9a844cf2014-02-11 18:58:52 -0800698void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800699 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800700 for (size_t i = 0; i < count; i++) {
Aravind Akella444f2672015-05-07 12:40:52 -0700701 if (buffer[i].type != SENSOR_TYPE_META_DATA) {
702 CircularBuffer* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
703 if (circular_buf == NULL) {
704 circular_buf = new CircularBuffer(buffer[i].type);
Aravind Akella4b847042014-03-03 19:02:46 -0800705 }
Aravind Akella444f2672015-05-07 12:40:52 -0700706 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800707 }
708 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800709}
710
Mathias Agopianf001c922010-11-11 17:58:51 -0800711void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
712{
713 struct compar {
714 static int cmp(void const* lhs, void const* rhs) {
715 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
716 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700717 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800718 }
719 };
720 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
721}
722
Mathias Agopian5d270722010-07-19 15:20:39 -0700723String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700724 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700725 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700726 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700727 if (sensor.getHandle() == handle) {
728 return sensor.getName();
729 }
730 }
731 String8 result("unknown");
732 return result;
733}
734
Aravind Akellab4099e72013-10-15 15:43:10 -0700735bool SensorService::isVirtualSensor(int handle) const {
736 SensorInterface* sensor = mSensorMap.valueFor(handle);
737 return sensor->isVirtual();
738}
739
Aravind Akella9a844cf2014-02-11 18:58:52 -0800740bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700741 int handle = event.sensor;
742 if (event.type == SENSOR_TYPE_META_DATA) {
743 handle = event.meta_data.sensor;
744 }
745 SensorInterface* sensor = mSensorMap.valueFor(handle);
746 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800747}
748
Aravind Akella6c2664a2014-08-13 12:24:50 -0700749SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
750 return mActiveSensors.valueFor(handle);
751}
752
Svetoslavb412f6e2015-04-29 16:50:41 -0700753Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700754{
Mathias Agopian33264862012-06-28 19:46:54 -0700755 char value[PROPERTY_VALUE_MAX];
756 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000757 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
758 mUserSensorListDebug : mUserSensorList;
759 Vector<Sensor> accessibleSensorList;
760 for (size_t i = 0; i < initialSensorList.size(); i++) {
761 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700762 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000763 accessibleSensorList.add(sensor);
764 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700765 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100766 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700767 sensor.getRequiredPermission().string(),
768 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000769 }
Mathias Agopian33264862012-06-28 19:46:54 -0700770 }
Aravind Akella70018042014-04-07 22:52:37 +0000771 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700772}
773
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700774sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700775 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700776 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
777 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
778 return NULL;
779 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700780
781 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700782 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
783 // operating in DI mode.
784 if (requestedMode == DATA_INJECTION) {
785 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
786 if (!isWhiteListedPackage(packageName)) return NULL;
787 }
788
Mathias Agopian5307d172012-09-18 17:02:43 -0700789 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700790 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700791 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700792 if (requestedMode == DATA_INJECTION) {
793 if (mActiveConnections.indexOf(result) < 0) {
794 mActiveConnections.add(result);
795 }
796 // Add the associated file descriptor to the Looper for polling whenever there is data to
797 // be injected.
798 result->updateLooperRegistration(mLooper);
799 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700800 return result;
801}
802
Aravind Akella841a5922015-06-29 12:37:48 -0700803int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700804 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700805 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700806}
807
808status_t SensorService::resetToNormalMode() {
809 Mutex::Autolock _l(mLock);
810 return resetToNormalModeLocked();
811}
812
813status_t SensorService::resetToNormalModeLocked() {
814 SensorDevice& dev(SensorDevice::getInstance());
815 dev.enableAllSensors();
816 status_t err = dev.setMode(NORMAL);
817 mCurrentOperatingMode = NORMAL;
818 return err;
819}
820
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800821void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700822{
823 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800824 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700825 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700826 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700827 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800828 int handle = mActiveSensors.keyAt(i);
829 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700830 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800831 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000832 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800833 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800834 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800835 }
Aravind Akella8a969552014-09-28 17:52:41 -0700836 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800837 }
838 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700839 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000840 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700841 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700842 c, i, handle);
843
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800844 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000845 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700846 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800847 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700848 delete rec;
849 size--;
850 } else {
851 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700852 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700853 }
Aravind Akella8a969552014-09-28 17:52:41 -0700854 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700855 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700856 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800857 if (c->needsWakeLock()) {
858 checkWakeLockStateLocked();
859 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700860}
861
Aravind Akella70018042014-04-07 22:52:37 +0000862Sensor SensorService::getSensorFromHandle(int handle) const {
863 return mSensorMap.valueFor(handle)->getSensor();
864}
865
Mathias Agopianfc328812010-07-14 23:41:37 -0700866status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700867 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
868 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700869{
Mathias Agopian50df2952010-07-19 19:09:10 -0700870 if (mInitCheck != NO_ERROR)
871 return mInitCheck;
872
Mathias Agopianf001c922010-11-11 17:58:51 -0800873 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700874 if (sensor == NULL) {
875 return BAD_VALUE;
876 }
Aravind Akella70018042014-04-07 22:52:37 +0000877
Svetoslavb412f6e2015-04-29 16:50:41 -0700878 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000879 return BAD_VALUE;
880 }
881
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700882 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700883 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
884 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800885 return INVALID_OPERATION;
886 }
887
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700888 SensorRecord* rec = mActiveSensors.valueFor(handle);
889 if (rec == 0) {
890 rec = new SensorRecord(connection);
891 mActiveSensors.add(handle, rec);
892 if (sensor->isVirtual()) {
893 mActiveVirtualSensors.add(handle, sensor);
894 }
895 } else {
896 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800897 // this sensor is already activated, but we are adding a connection that uses it.
898 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700899 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700900 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800901 // NOTE: The wake_up flag of this event may get set to
902 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Aravind Akella444f2672015-05-07 12:40:52 -0700903 CircularBuffer *circular_buf = mLastEventSeen.valueFor(handle);
904 if (circular_buf) {
905 sensors_event_t event;
906 memset(&event, 0, sizeof(event));
907 // It is unlikely that this buffer is empty as the sensor is already active.
908 // One possible corner case may be two applications activating an on-change
909 // sensor at the same time.
910 if(circular_buf->populateLastEvent(&event)) {
911 event.sensor = handle;
912 if (event.version == sizeof(sensors_event_t)) {
913 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
914 setWakeLockAcquiredLocked(true);
915 }
916 connection->sendEvents(&event, 1, NULL);
917 if (!connection->needsWakeLock() && mWakeLockAcquired) {
918 checkWakeLockStateLocked();
919 }
920 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800921 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700922 }
923 }
924 }
925 }
926
927 if (connection->addSensor(handle)) {
928 BatteryService::enableSensor(connection->getUid(), handle);
929 // the sensor was added (which means it wasn't already there)
930 // so, see if this connection becomes active
931 if (mActiveConnections.indexOf(connection) < 0) {
932 mActiveConnections.add(connection);
933 }
934 } else {
935 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
936 handle, connection.get());
937 }
938
Aravind Akella724d91d2013-06-27 12:04:23 -0700939 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
940 if (samplingPeriodNs < minDelayNs) {
941 samplingPeriodNs = minDelayNs;
942 }
943
Aravind Akella6c2664a2014-08-13 12:24:50 -0700944 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
945 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700946 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
947
Aravind Akella4949c502015-02-11 15:54:35 -0800948 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700949 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700950
Aravind Akella5466c3d2014-08-22 16:11:10 -0700951 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
952 // event before sending events on this connection. Ignore one-shot sensors which don't
953 // support flush(). Also if this sensor isn't already active, don't call flush().
954 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
955 rec->getNumConnections() > 1) {
956 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700957 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700958 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700959 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700960 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700961 } else {
962 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700963 }
964 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700965
966 if (err == NO_ERROR) {
967 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
968 err = sensor->activate(connection.get(), true);
969 }
970
Aravind Akella8a969552014-09-28 17:52:41 -0700971 if (err == NO_ERROR) {
972 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700973 SensorRegistrationInfo &reg_info =
974 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
975 reg_info.mSensorHandle = handle;
976 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
977 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
978 reg_info.mActivated = true;
979 reg_info.mPackageName = connection->getPackageName();
980 time_t rawtime = time(NULL);
981 struct tm * timeinfo = localtime(&rawtime);
982 reg_info.mHour = timeinfo->tm_hour;
983 reg_info.mMin = timeinfo->tm_min;
984 reg_info.mSec = timeinfo->tm_sec;
985 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700986 }
987
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700988 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700989 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700990 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700991 }
992 return err;
993}
994
995status_t SensorService::disable(const sp<SensorEventConnection>& connection,
996 int handle)
997{
Mathias Agopian50df2952010-07-19 19:09:10 -0700998 if (mInitCheck != NO_ERROR)
999 return mInitCheck;
1000
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001001 Mutex::Autolock _l(mLock);
1002 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001003 if (err == NO_ERROR) {
1004 SensorInterface* sensor = mSensorMap.valueFor(handle);
1005 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001006
1007 }
1008 if (err == NO_ERROR) {
1009 SensorRegistrationInfo &reg_info =
1010 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1011 reg_info.mActivated = false;
1012 reg_info.mPackageName= connection->getPackageName();
1013 reg_info.mSensorHandle = handle;
1014 time_t rawtime = time(NULL);
1015 struct tm * timeinfo = localtime(&rawtime);
1016 reg_info.mHour = timeinfo->tm_hour;
1017 reg_info.mMin = timeinfo->tm_min;
1018 reg_info.mSec = timeinfo->tm_sec;
1019 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001020 }
1021 return err;
1022}
1023
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001024status_t SensorService::cleanupWithoutDisable(
1025 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001026 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001027 return cleanupWithoutDisableLocked(connection, handle);
1028}
1029
1030status_t SensorService::cleanupWithoutDisableLocked(
1031 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001032 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001033 if (rec) {
1034 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001035 if (connection->removeSensor(handle)) {
1036 BatteryService::disableSensor(connection->getUid(), handle);
1037 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001038 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001039 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001040 mActiveConnections.remove(connection);
1041 }
1042 // see if this sensor becomes inactive
1043 if (rec->removeConnection(connection)) {
1044 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001045 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001046 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001047 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001048 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001049 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001050 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001051}
1052
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001053status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001054 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001055{
Mathias Agopian50df2952010-07-19 19:09:10 -07001056 if (mInitCheck != NO_ERROR)
1057 return mInitCheck;
1058
Mathias Agopianae09d652011-11-01 17:37:49 -07001059 SensorInterface* sensor = mSensorMap.valueFor(handle);
1060 if (!sensor)
1061 return BAD_VALUE;
1062
Svetoslavb412f6e2015-04-29 16:50:41 -07001063 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001064 return BAD_VALUE;
1065 }
1066
Mathias Agopian1cd70002010-07-21 15:59:50 -07001067 if (ns < 0)
1068 return BAD_VALUE;
1069
Mathias Agopian62569ec2011-11-07 21:21:47 -08001070 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1071 if (ns < minDelayNs) {
1072 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001073 }
1074
Mathias Agopianf001c922010-11-11 17:58:51 -08001075 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001076}
1077
Svetoslavb412f6e2015-04-29 16:50:41 -07001078status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1079 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001080 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001081 SensorDevice& dev(SensorDevice::getInstance());
1082 const int halVersion = dev.getHalDeviceVersion();
1083 status_t err(NO_ERROR);
1084 Mutex::Autolock _l(mLock);
1085 // Loop through all sensors for this connection and call flush on each of them.
1086 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1087 const int handle = connection->mSensorInfo.keyAt(i);
1088 SensorInterface* sensor = mSensorMap.valueFor(handle);
1089 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1090 ALOGE("flush called on a one-shot sensor");
1091 err = INVALID_OPERATION;
1092 continue;
1093 }
Aravind Akella8493b792014-09-08 15:45:47 -07001094 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001095 // For older devices just increment pending flush count which will send a trivial
1096 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001097 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001098 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001099 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1100 err = INVALID_OPERATION;
1101 continue;
1102 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001103 status_t err_flush = sensor->flush(connection.get(), handle);
1104 if (err_flush == NO_ERROR) {
1105 SensorRecord* rec = mActiveSensors.valueFor(handle);
1106 if (rec != NULL) rec->addPendingFlushConnection(connection);
1107 }
1108 err = (err_flush != NO_ERROR) ? err_flush : err;
1109 }
Aravind Akella70018042014-04-07 22:52:37 +00001110 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001111 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001112}
Aravind Akella70018042014-04-07 22:52:37 +00001113
Svetoslavb412f6e2015-04-29 16:50:41 -07001114bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1115 const String16& opPackageName) {
1116 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001117
Svetoslavb412f6e2015-04-29 16:50:41 -07001118 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001119 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001120 }
1121
1122 bool hasPermission = false;
1123
1124 // Runtime permissions can't use the cache as they may change.
1125 if (sensor.isRequiredPermissionRuntime()) {
1126 hasPermission = checkPermission(String16(requiredPermission),
1127 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001128 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001129 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1130 }
1131
1132 if (!hasPermission) {
1133 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1134 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001135 return false;
1136 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001137
1138 const int32_t opCode = sensor.getRequiredAppOp();
1139 if (opCode >= 0) {
1140 AppOpsManager appOps;
1141 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1142 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001143 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001144 operation, sensor.getName().string(), opCode);
1145 return false;
1146 }
1147 }
1148
1149 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001150}
1151
Aravind Akella9a844cf2014-02-11 18:58:52 -08001152void SensorService::checkWakeLockState() {
1153 Mutex::Autolock _l(mLock);
1154 checkWakeLockStateLocked();
1155}
1156
1157void SensorService::checkWakeLockStateLocked() {
1158 if (!mWakeLockAcquired) {
1159 return;
1160 }
1161 bool releaseLock = true;
1162 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1163 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1164 if (connection != 0) {
1165 if (connection->needsWakeLock()) {
1166 releaseLock = false;
1167 break;
1168 }
1169 }
1170 }
1171 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001172 setWakeLockAcquiredLocked(false);
1173 }
1174}
1175
1176void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1177 Mutex::Autolock _l(mLock);
1178 connection->writeToSocketFromCache();
1179 if (connection->needsWakeLock()) {
1180 setWakeLockAcquiredLocked(true);
1181 }
1182}
1183
1184void SensorService::populateActiveConnections(
1185 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1186 Mutex::Autolock _l(mLock);
1187 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1188 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1189 if (connection != 0) {
1190 activeConnections->add(connection);
1191 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001192 }
1193}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001194
Aravind Akella4949c502015-02-11 15:54:35 -08001195bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001196 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001197}
1198
Aravind Akella444f2672015-05-07 12:40:52 -07001199int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1200 switch (sensor_event_type) {
1201 case SENSOR_TYPE_ROTATION_VECTOR:
1202 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1203 return 5;
1204
1205 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1206 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1207 return 6;
1208
1209 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1210 return 4;
1211
1212 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1213 case SENSOR_TYPE_STEP_DETECTOR:
1214 case SENSOR_TYPE_STEP_COUNTER:
1215 return 1;
1216
1217 default:
1218 return 3;
1219 }
1220}
1221
Mathias Agopianfc328812010-07-14 23:41:37 -07001222// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001223SensorService::SensorRecord::SensorRecord(
1224 const sp<SensorEventConnection>& connection)
1225{
1226 mConnections.add(connection);
1227}
1228
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001229bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001230 const sp<SensorEventConnection>& connection)
1231{
1232 if (mConnections.indexOf(connection) < 0) {
1233 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001234 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001235 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001236 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001237}
1238
1239bool SensorService::SensorRecord::removeConnection(
1240 const wp<SensorEventConnection>& connection)
1241{
1242 ssize_t index = mConnections.indexOf(connection);
1243 if (index >= 0) {
1244 mConnections.removeItemsAt(index, 1);
1245 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001246 // Remove this connections from the queue of flush() calls made on this sensor.
1247 for (Vector< wp<SensorEventConnection> >::iterator it =
1248 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001249
Aravind Akella6c2664a2014-08-13 12:24:50 -07001250 if (it->unsafe_get() == connection.unsafe_get()) {
1251 it = mPendingFlushConnections.erase(it);
1252 } else {
1253 ++it;
1254 }
1255 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001256 return mConnections.size() ? false : true;
1257}
1258
Aravind Akella6c2664a2014-08-13 12:24:50 -07001259void SensorService::SensorRecord::addPendingFlushConnection(
1260 const sp<SensorEventConnection>& connection) {
1261 mPendingFlushConnections.add(connection);
1262}
1263
1264void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1265 if (mPendingFlushConnections.size() > 0) {
1266 mPendingFlushConnections.removeAt(0);
1267 }
1268}
1269
1270SensorService::SensorEventConnection *
1271SensorService::SensorRecord::getFirstPendingFlushConnection() {
1272 if (mPendingFlushConnections.size() > 0) {
1273 return mPendingFlushConnections[0].unsafe_get();
1274 }
1275 return NULL;
1276}
1277
Aravind Akella4949c502015-02-11 15:54:35 -08001278void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1279 mPendingFlushConnections.clear();
1280}
1281
Aravind Akella18d6d512015-06-18 14:18:28 -07001282
1283// ---------------------------------------------------------------------------
1284SensorService::TrimmedSensorEvent::TrimmedSensorEvent(int sensorType) {
1285 mTimestamp = -1;
1286 const int numData = SensorService::getNumEventsForSensorType(sensorType);
1287 if (sensorType == SENSOR_TYPE_STEP_COUNTER) {
1288 mStepCounter = 0;
1289 } else {
1290 mData = new float[numData];
1291 for (int i = 0; i < numData; ++i) {
1292 mData[i] = -1.0;
1293 }
1294 }
1295 mHour = mMin = mSec = INT32_MIN;
1296}
1297
1298bool SensorService::TrimmedSensorEvent::isSentinel(const TrimmedSensorEvent& event) {
1299 return (event.mHour == INT32_MIN && event.mMin == INT32_MIN && event.mSec == INT32_MIN);
1300}
Aravind Akella444f2672015-05-07 12:40:52 -07001301// --------------------------------------------------------------------------
1302SensorService::CircularBuffer::CircularBuffer(int sensor_event_type) {
1303 mNextInd = 0;
Aravind Akella18d6d512015-06-18 14:18:28 -07001304 mBufSize = CIRCULAR_BUF_SIZE;
1305 if (sensor_event_type == SENSOR_TYPE_STEP_COUNTER ||
1306 sensor_event_type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
1307 sensor_event_type == SENSOR_TYPE_ACCELEROMETER) {
1308 mBufSize = CIRCULAR_BUF_SIZE * 5;
1309 }
1310 mTrimmedSensorEventArr = new TrimmedSensorEvent *[mBufSize];
Aravind Akella444f2672015-05-07 12:40:52 -07001311 mSensorType = sensor_event_type;
Aravind Akella18d6d512015-06-18 14:18:28 -07001312 for (int i = 0; i < mBufSize; ++i) {
1313 mTrimmedSensorEventArr[i] = new TrimmedSensorEvent(mSensorType);
Aravind Akella444f2672015-05-07 12:40:52 -07001314 }
1315}
1316
1317void SensorService::CircularBuffer::addEvent(const sensors_event_t& sensor_event) {
1318 TrimmedSensorEvent *curr_event = mTrimmedSensorEventArr[mNextInd];
1319 curr_event->mTimestamp = sensor_event.timestamp;
1320 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1321 curr_event->mStepCounter = sensor_event.u64.step_counter;
1322 } else {
1323 memcpy(curr_event->mData, sensor_event.data,
1324 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1325 }
1326 time_t rawtime = time(NULL);
1327 struct tm * timeinfo = localtime(&rawtime);
1328 curr_event->mHour = timeinfo->tm_hour;
1329 curr_event->mMin = timeinfo->tm_min;
1330 curr_event->mSec = timeinfo->tm_sec;
Aravind Akella18d6d512015-06-18 14:18:28 -07001331 mNextInd = (mNextInd + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001332}
1333
1334void SensorService::CircularBuffer::printBuffer(String8& result) const {
1335 const int numData = SensorService::getNumEventsForSensorType(mSensorType);
1336 int i = mNextInd, eventNum = 1;
Aravind Akella18d6d512015-06-18 14:18:28 -07001337 result.appendFormat("last %d events = < ", mBufSize);
Aravind Akella444f2672015-05-07 12:40:52 -07001338 do {
Aravind Akella18d6d512015-06-18 14:18:28 -07001339 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[i])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001340 // Sentinel, ignore.
Aravind Akella18d6d512015-06-18 14:18:28 -07001341 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001342 continue;
1343 }
1344 result.appendFormat("%d) ", eventNum++);
1345 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001346 result.appendFormat("%" PRIu64 ",", mTrimmedSensorEventArr[i]->mStepCounter);
Aravind Akella444f2672015-05-07 12:40:52 -07001347 } else {
1348 for (int j = 0; j < numData; ++j) {
1349 result.appendFormat("%5.1f,", mTrimmedSensorEventArr[i]->mData[j]);
1350 }
1351 }
Andreas Gamped4036b62015-07-28 13:49:04 -07001352 result.appendFormat("%" PRId64 " %02d:%02d:%02d ", mTrimmedSensorEventArr[i]->mTimestamp,
Aravind Akella444f2672015-05-07 12:40:52 -07001353 mTrimmedSensorEventArr[i]->mHour, mTrimmedSensorEventArr[i]->mMin,
1354 mTrimmedSensorEventArr[i]->mSec);
Aravind Akella18d6d512015-06-18 14:18:28 -07001355 i = (i + 1) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001356 } while (i != mNextInd);
1357 result.appendFormat(">\n");
1358}
1359
1360bool SensorService::CircularBuffer::populateLastEvent(sensors_event_t *event) {
Aravind Akella18d6d512015-06-18 14:18:28 -07001361 int lastEventInd = (mNextInd - 1 + mBufSize) % mBufSize;
Aravind Akella444f2672015-05-07 12:40:52 -07001362 // Check if the buffer is empty.
Aravind Akella18d6d512015-06-18 14:18:28 -07001363 if (TrimmedSensorEvent::isSentinel(*mTrimmedSensorEventArr[lastEventInd])) {
Aravind Akella444f2672015-05-07 12:40:52 -07001364 return false;
1365 }
1366 event->version = sizeof(sensors_event_t);
1367 event->type = mSensorType;
1368 event->timestamp = mTrimmedSensorEventArr[lastEventInd]->mTimestamp;
1369 if (mSensorType == SENSOR_TYPE_STEP_COUNTER) {
1370 event->u64.step_counter = mTrimmedSensorEventArr[lastEventInd]->mStepCounter;
1371 } else {
1372 memcpy(event->data, mTrimmedSensorEventArr[lastEventInd]->mData,
1373 sizeof(float) * SensorService::getNumEventsForSensorType(mSensorType));
1374 }
1375 return true;
1376}
1377
1378SensorService::CircularBuffer::~CircularBuffer() {
Aravind Akella18d6d512015-06-18 14:18:28 -07001379 for (int i = 0; i < mBufSize; ++i) {
Aravind Akella444f2672015-05-07 12:40:52 -07001380 delete mTrimmedSensorEventArr[i];
1381 }
1382 delete [] mTrimmedSensorEventArr;
1383}
1384
Mathias Agopianfc328812010-07-14 23:41:37 -07001385// ---------------------------------------------------------------------------
1386
1387SensorService::SensorEventConnection::SensorEventConnection(
Svetoslavb412f6e2015-04-29 16:50:41 -07001388 const sp<SensorService>& service, uid_t uid, String8 packageName, bool isDataInjectionMode,
1389 const String16& opPackageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001390 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Svetoslavb412f6e2015-04-29 16:50:41 -07001391 mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(NULL),
1392 mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001393 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001394#if DEBUG_CONNECTIONS
1395 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001396 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001397#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001398}
1399
Aravind Akella56ae4262014-07-10 16:01:10 -07001400SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001401 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001402 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001403 if (mEventCache != NULL) {
1404 delete mEventCache;
1405 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001406}
1407
Aravind Akella56ae4262014-07-10 16:01:10 -07001408void SensorService::SensorEventConnection::onFirstRef() {
1409 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001410}
1411
Aravind Akella9a844cf2014-02-11 18:58:52 -08001412bool SensorService::SensorEventConnection::needsWakeLock() {
1413 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001414 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001415}
1416
Aravind Akellab4373ac2014-10-29 17:55:20 -07001417void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1418 Mutex::Autolock _l(mConnectionLock);
1419 mWakeLockRefCount = 0;
1420}
1421
Aravind Akella4c8b9512013-09-05 17:03:38 -07001422void SensorService::SensorEventConnection::dump(String8& result) {
1423 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8ef3c892015-07-10 11:24:28 -07001424 result.appendFormat("\tOperating Mode: %s\n",mDataInjectionMode ? "DATA_INJECTION" : "NORMAL");
Aravind Akella18d6d512015-06-18 14:18:28 -07001425 result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
1426 "max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
1427 mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001428 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1429 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001430 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001431 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001432 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001433 flushInfo.mFirstFlushPending ? "First flush pending" :
1434 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001435 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001436 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001437#if DEBUG_CONNECTIONS
1438 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1439 " total_acks_needed %d | total_acks_recvd %d\n",
1440 mEventsReceived,
1441 mEventsSent,
1442 mEventsSentFromCache,
1443 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1444 mTotalAcksNeeded,
1445 mTotalAcksReceived);
1446#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001447}
1448
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001449bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001450 Mutex::Autolock _l(mConnectionLock);
Svetoslavb412f6e2015-04-29 16:50:41 -07001451 if (!canAccessSensor(mService->getSensorFromHandle(handle),
1452 "Tried adding", mOpPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001453 return false;
1454 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001455 if (mSensorInfo.indexOfKey(handle) < 0) {
1456 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001457 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001458 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001459 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001460}
1461
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001462bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001463 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001464 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001465 return true;
1466 }
1467 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001468}
1469
1470bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001471 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001472 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001473}
1474
1475bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001476 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001477 return mSensorInfo.size() ? true : false;
1478}
1479
Aravind Akella8493b792014-09-08 15:45:47 -07001480bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1481 Mutex::Autolock _l(mConnectionLock);
1482 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1483 const int handle = mSensorInfo.keyAt(i);
1484 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1485 return true;
1486 }
1487 }
1488 return false;
1489}
1490
Aravind Akella4949c502015-02-11 15:54:35 -08001491String8 SensorService::SensorEventConnection::getPackageName() const {
1492 return mPackageName;
1493}
1494
Aravind Akella4c8b9512013-09-05 17:03:38 -07001495void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1496 bool value) {
1497 Mutex::Autolock _l(mConnectionLock);
1498 ssize_t index = mSensorInfo.indexOfKey(handle);
1499 if (index >= 0) {
1500 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1501 flushInfo.mFirstFlushPending = value;
1502 }
1503}
1504
Aravind Akella8a969552014-09-28 17:52:41 -07001505void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1506 Mutex::Autolock _l(mConnectionLock);
1507 updateLooperRegistrationLocked(looper);
1508}
1509
1510void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1511 const sp<Looper>& looper) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001512 bool isConnectionActive = (mSensorInfo.size() > 0 && !mDataInjectionMode) ||
1513 mDataInjectionMode;
Aravind Akella8a969552014-09-28 17:52:41 -07001514 // If all sensors are unregistered OR Looper has encountered an error, we
1515 // can remove the Fd from the Looper if it has been previously added.
1516 if (!isConnectionActive || mDead) {
1517 if (mHasLooperCallbacks) {
1518 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1519 looper->removeFd(mChannel->getSendFd());
1520 mHasLooperCallbacks = false;
1521 }
1522 return;
1523 }
1524
1525 int looper_flags = 0;
1526 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001527 if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
Aravind Akella8a969552014-09-28 17:52:41 -07001528 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1529 const int handle = mSensorInfo.keyAt(i);
1530 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1531 looper_flags |= ALOOPER_EVENT_INPUT;
1532 break;
1533 }
1534 }
1535 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1536 // the fd has already been added, remove it. This is likely to happen when ALL the
1537 // events stored in the cache have been sent to the corresponding app.
1538 if (looper_flags == 0) {
1539 if (mHasLooperCallbacks) {
1540 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1541 looper->removeFd(mChannel->getSendFd());
1542 mHasLooperCallbacks = false;
1543 }
1544 return;
1545 }
1546 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1547 // registered for wake-up sensors OR for sending events in the cache.
1548 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1549 if (ret == 1) {
1550 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1551 mHasLooperCallbacks = true;
1552 } else {
1553 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1554 }
1555}
1556
1557void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1558 Mutex::Autolock _l(mConnectionLock);
1559 ssize_t index = mSensorInfo.indexOfKey(handle);
1560 if (index >= 0) {
1561 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1562 flushInfo.mPendingFlushEventsToSend++;
1563 }
1564}
1565
Mathias Agopianfc328812010-07-14 23:41:37 -07001566status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001567 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001568 sensors_event_t* scratch,
1569 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001570 // filter out events not for this connection
Svetoslavb412f6e2015-04-29 16:50:41 -07001571 int count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001572 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001573 if (scratch) {
1574 size_t i=0;
1575 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001576 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001577 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1578 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001579 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001580 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1581 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1582 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001583 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001584 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001585 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001586 // Check if this connection has registered for this sensor. If not continue to the
1587 // next sensor_event.
1588 if (index < 0) {
1589 ++i;
1590 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001591 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001592
Aravind Akella56ae4262014-07-10 16:01:10 -07001593 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001594 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001595 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1596 this == mapFlushEventsToConnections[i]) {
1597 flushInfo.mFirstFlushPending = false;
1598 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1599 buffer[i].meta_data.sensor);
1600 ++i;
1601 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001602 }
1603
1604 // If there is a pending flush complete event for this sensor on this connection,
1605 // ignore the event and proceed to the next.
1606 if (flushInfo.mFirstFlushPending) {
1607 ++i;
1608 continue;
1609 }
1610
1611 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001612 // Keep copying events into the scratch buffer as long as they are regular
1613 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1614 // from the same sensor_handle AND the current connection is mapped to the
1615 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001616 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001617 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001618 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001619 }
1620 ++i;
1621 } else {
1622 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001623 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001624 }
Aravind Akella8493b792014-09-08 15:45:47 -07001625 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1626 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001627 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001628 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001629 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001630 } else {
1631 scratch = const_cast<sensors_event_t *>(buffer);
1632 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001633 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001634
Aravind Akella6c2664a2014-08-13 12:24:50 -07001635 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001636 // Early return if there are no events for this connection.
1637 if (count == 0) {
1638 return status_t(NO_ERROR);
1639 }
1640
1641#if DEBUG_CONNECTIONS
1642 mEventsReceived += count;
1643#endif
1644 if (mCacheSize != 0) {
1645 // There are some events in the cache which need to be sent first. Copy this buffer to
1646 // the end of cache.
1647 if (mCacheSize + count <= mMaxCacheSize) {
1648 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1649 mCacheSize += count;
1650 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001651 // Check if any new sensors have registered on this connection which may have increased
1652 // the max cache size that is desired.
1653 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1654 reAllocateCacheLocked(scratch, count);
1655 return status_t(NO_ERROR);
1656 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001657 // Some events need to be dropped.
1658 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1659 if (remaningCacheSize != 0) {
1660 memcpy(&mEventCache[mCacheSize], scratch,
1661 remaningCacheSize * sizeof(sensors_event_t));
1662 }
1663 int numEventsDropped = count - remaningCacheSize;
1664 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1665 // Drop the first "numEventsDropped" in the cache.
1666 memmove(mEventCache, &mEventCache[numEventsDropped],
1667 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1668
1669 // Copy the remainingEvents in scratch buffer to the end of cache.
1670 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1671 numEventsDropped * sizeof(sensors_event_t));
1672 }
1673 return status_t(NO_ERROR);
1674 }
1675
Aravind Akella6c2664a2014-08-13 12:24:50 -07001676 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1677 if (index_wake_up_event >= 0) {
1678 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1679 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001680#if DEBUG_CONNECTIONS
1681 ++mTotalAcksNeeded;
1682#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001683 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001684
1685 // NOTE: ASensorEvent and sensors_event_t are the same type.
1686 ssize_t size = SensorEventQueue::write(mChannel,
1687 reinterpret_cast<ASensorEvent const*>(scratch), count);
1688 if (size < 0) {
1689 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001690 if (index_wake_up_event >= 0) {
1691 // If there was a wake_up sensor_event, reset the flag.
1692 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001693 if (mWakeLockRefCount > 0) {
1694 --mWakeLockRefCount;
1695 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001696#if DEBUG_CONNECTIONS
1697 --mTotalAcksNeeded;
1698#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001699 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001700 if (mEventCache == NULL) {
1701 mMaxCacheSize = computeMaxCacheSizeLocked();
1702 mEventCache = new sensors_event_t[mMaxCacheSize];
1703 mCacheSize = 0;
1704 }
1705 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1706 mCacheSize += count;
1707
1708 // Add this file descriptor to the looper to get a callback when this fd is available for
1709 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001710 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001711 return size;
1712 }
1713
1714#if DEBUG_CONNECTIONS
1715 if (size > 0) {
1716 mEventsSent += count;
1717 }
1718#endif
1719
1720 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1721}
1722
Aravind Akella6c2664a2014-08-13 12:24:50 -07001723void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1724 int count) {
1725 sensors_event_t *eventCache_new;
1726 const int new_cache_size = computeMaxCacheSizeLocked();
1727 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1728 eventCache_new = new sensors_event_t[new_cache_size];
1729 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1730 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1731
1732 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1733 new_cache_size);
1734
1735 delete mEventCache;
1736 mEventCache = eventCache_new;
1737 mCacheSize += count;
1738 mMaxCacheSize = new_cache_size;
1739}
1740
1741void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1742 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001743 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001744 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001745 // Loop through all the sensors for this connection and check if there are any pending
1746 // flush complete events to be sent.
1747 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1748 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1749 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001750 const int sensor_handle = mSensorInfo.keyAt(i);
1751 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001752 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1753 if (wakeUpSensor) {
1754 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001755 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1756 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001757 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1758 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001759 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001760 return;
1761 }
1762 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1763 flushCompleteEvent.meta_data.sensor);
1764 flushInfo.mPendingFlushEventsToSend--;
1765 }
1766 }
1767}
1768
Aravind Akellab4373ac2014-10-29 17:55:20 -07001769void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001770 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1771 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1772 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1773 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001774 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001775 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001776 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001777 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001778 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001779 int index_wake_up_event =
1780 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1781 if (index_wake_up_event >= 0) {
1782 mEventCache[index_wake_up_event + numEventsSent].flags |=
1783 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1784 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001785#if DEBUG_CONNECTIONS
1786 ++mTotalAcksNeeded;
1787#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001788 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001789
Aravind Akella56ae4262014-07-10 16:01:10 -07001790 ssize_t size = SensorEventQueue::write(mChannel,
1791 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001792 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001793 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001794 if (index_wake_up_event >= 0) {
1795 // If there was a wake_up sensor_event, reset the flag.
1796 mEventCache[index_wake_up_event + numEventsSent].flags &=
1797 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001798 if (mWakeLockRefCount > 0) {
1799 --mWakeLockRefCount;
1800 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001801#if DEBUG_CONNECTIONS
1802 --mTotalAcksNeeded;
1803#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001804 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001805 memmove(mEventCache, &mEventCache[numEventsSent],
1806 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1807 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001808 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001809 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001810 return;
1811 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001812 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001813#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001814 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001815#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001816 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001817 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1818 // All events from the cache have been sent. Reset cache size to zero.
1819 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001820 // There are no more events in the cache. We don't need to poll for write on the fd.
1821 // Update Looper registration.
1822 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001823}
1824
Aravind Akellac551eac2013-10-14 17:04:42 -07001825void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001826 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001827 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001828 // Count flushComplete events in the events that are about to the dropped. These will be sent
1829 // separately before the next batch of events.
1830 for (int j = 0; j < numEventsDropped; ++j) {
1831 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1832 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1833 flushInfo.mPendingFlushEventsToSend++;
1834 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1835 flushInfo.mPendingFlushEventsToSend);
1836 }
1837 }
1838 return;
1839}
1840
Aravind Akella6c2664a2014-08-13 12:24:50 -07001841int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1842 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001843 for (int i = 0; i < count; ++i) {
1844 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001845 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001846 }
1847 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001848 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001849}
1850
Mathias Agopianb3989272011-10-20 18:42:02 -07001851sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001852{
1853 return mChannel;
1854}
1855
1856status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001857 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1858 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001859{
1860 status_t err;
1861 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001862 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
Svetoslavb412f6e2015-04-29 16:50:41 -07001863 reservedFlags, mOpPackageName);
Aravind Akella56ae4262014-07-10 16:01:10 -07001864
Mathias Agopianfc328812010-07-14 23:41:37 -07001865 } else {
1866 err = mService->disable(this, handle);
1867 }
1868 return err;
1869}
1870
1871status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001872 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001873{
Svetoslavb412f6e2015-04-29 16:50:41 -07001874 return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
Mathias Agopianfc328812010-07-14 23:41:37 -07001875}
1876
Aravind Akella701166d2013-10-08 14:59:26 -07001877status_t SensorService::SensorEventConnection::flush() {
Svetoslavb412f6e2015-04-29 16:50:41 -07001878 return mService->flushSensor(this, mOpPackageName);
Aravind Akella724d91d2013-06-27 12:04:23 -07001879}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001880
Aravind Akella8a969552014-09-28 17:52:41 -07001881int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001882 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001883 {
1884 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1885 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1886 // can release the wake-lock.
1887 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1888 Mutex::Autolock _l(mConnectionLock);
1889 mDead = true;
1890 mWakeLockRefCount = 0;
1891 updateLooperRegistrationLocked(mService->getLooper());
1892 }
1893 mService->checkWakeLockState();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001894 if (mDataInjectionMode) {
1895 // If the Looper has encountered some error in data injection mode, reset SensorService
1896 // back to normal mode.
1897 mService->resetToNormalMode();
1898 mDataInjectionMode = false;
1899 }
Aravind Akella8a969552014-09-28 17:52:41 -07001900 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001901 }
1902
1903 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001904 unsigned char buf[sizeof(sensors_event_t)];
1905 ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001906 {
1907 Mutex::Autolock _l(mConnectionLock);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001908 if (numBytesRead == sizeof(sensors_event_t)) {
1909 if (!mDataInjectionMode) {
1910 ALOGE("Data injected in normal mode, dropping event"
1911 "package=%s uid=%d", mPackageName.string(), mUid);
1912 // Unregister call backs.
1913 return 0;
1914 }
1915 SensorDevice& dev(SensorDevice::getInstance());
1916 sensors_event_t sensor_event;
1917 memset(&sensor_event, 0, sizeof(sensor_event));
1918 memcpy(&sensor_event, buf, sizeof(sensors_event_t));
1919 Sensor sensor = mService->getSensorFromHandle(sensor_event.sensor);
1920 sensor_event.type = sensor.getType();
Svetoslavb412f6e2015-04-29 16:50:41 -07001921 dev.injectSensorData(&sensor_event);
Aravind Akellae74baf62014-08-21 12:28:35 -07001922#if DEBUG_CONNECTIONS
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001923 ++mEventsReceived;
Aravind Akellae74baf62014-08-21 12:28:35 -07001924#endif
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001925 } else if (numBytesRead == sizeof(uint32_t)) {
1926 uint32_t numAcks = 0;
Aravind Akella08f04bf2015-05-08 15:59:23 -07001927 memcpy(&numAcks, buf, numBytesRead);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -07001928 // Sanity check to ensure there are no read errors in recv, numAcks is always
1929 // within the range and not zero. If any of the above don't hold reset
1930 // mWakeLockRefCount to zero.
1931 if (numAcks > 0 && numAcks < mWakeLockRefCount) {
1932 mWakeLockRefCount -= numAcks;
1933 } else {
1934 mWakeLockRefCount = 0;
1935 }
1936#if DEBUG_CONNECTIONS
1937 mTotalAcksReceived += numAcks;
1938#endif
1939 } else {
1940 // Read error, reset wakelock refcount.
1941 mWakeLockRefCount = 0;
1942 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001943 }
1944 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1945 // here as checkWakeLockState() will need it.
1946 if (mWakeLockRefCount == 0) {
1947 mService->checkWakeLockState();
1948 }
1949 // continue getting callbacks.
1950 return 1;
1951 }
1952
1953 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001954 // send sensor data that is stored in mEventCache for this connection.
1955 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001956 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001957 return 1;
1958}
1959
1960int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
Svetoslavb412f6e2015-04-29 16:50:41 -07001961 size_t fifoWakeUpSensors = 0;
1962 size_t fifoNonWakeUpSensors = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001963 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1964 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1965 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1966 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1967 // non wake_up sensors.
1968 if (sensor.isWakeUpSensor()) {
1969 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1970 } else {
1971 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1972 }
1973 } else {
1974 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1975 if (sensor.isWakeUpSensor()) {
1976 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1977 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1978
1979 } else {
1980 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1981 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1982
1983 }
1984 }
1985 }
1986 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1987 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001988 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001989 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001990 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001991 }
1992 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001993}
1994
Mathias Agopianfc328812010-07-14 23:41:37 -07001995// ---------------------------------------------------------------------------
1996}; // namespace android
1997