blob: 30ec458342eea33c218993ebd8d06b9c0e67c393 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
34#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070035#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070037
38#include <gui/ISensorServer.h>
39#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070040#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070041
42#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070043#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070044
Mathias Agopian787ac1b2012-09-18 18:49:18 -070045#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080047#include "GravitySensor.h"
48#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080050#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070051#include "SensorFusion.h"
52#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070053
54namespace android {
55// ---------------------------------------------------------------------------
56
Mathias Agopian33015422011-05-27 18:18:13 -070057/*
58 * Notes:
59 *
60 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070061 * - run mag sensor from time to time to force calibration
62 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63 *
64 */
65
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070066const char* SensorService::WAKE_LOCK_NAME = "SensorService";
67
Mathias Agopianfc328812010-07-14 23:41:37 -070068SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070069 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
70 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070071{
72}
73
74void SensorService::onFirstRef()
75{
Steve Blocka5512372011-12-20 16:23:08 +000076 ALOGD("nuSensorService starting...");
Mathias Agopian50df2952010-07-19 19:09:10 -070077
Mathias Agopianf001c922010-11-11 17:58:51 -080078 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070079
Mathias Agopianf001c922010-11-11 17:58:51 -080080 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080081 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070082 ssize_t count = dev.getSensorList(&list);
83 if (count > 0) {
84 ssize_t orientationIndex = -1;
Aravind Akellae6406e32015-07-20 17:29:33 -070085 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070086 uint32_t virtualSensorsNeeds =
87 (1<<SENSOR_TYPE_GRAVITY) |
88 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
89 (1<<SENSOR_TYPE_ROTATION_VECTOR);
90
91 mLastEventSeen.setCapacity(count);
92 for (ssize_t i=0 ; i<count ; i++) {
93 registerSensor( new HardwareSensor(list[i]) );
94 switch (list[i].type) {
Aravind Akellae6406e32015-07-20 17:29:33 -070095 case SENSOR_TYPE_ACCELEROMETER:
96 hasAccel = true;
97 break;
98 case SENSOR_TYPE_MAGNETIC_FIELD:
99 hasMag = true;
100 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700101 case SENSOR_TYPE_ORIENTATION:
102 orientationIndex = i;
103 break;
104 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700105 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700106 hasGyro = true;
107 break;
108 case SENSOR_TYPE_GRAVITY:
109 case SENSOR_TYPE_LINEAR_ACCELERATION:
110 case SENSOR_TYPE_ROTATION_VECTOR:
111 virtualSensorsNeeds &= ~(1<<list[i].type);
112 break;
113 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700114 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700115
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700116 // it's safe to instantiate the SensorFusion object here
117 // (it wants to be instantiated after h/w sensors have been
118 // registered)
119 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700120
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700121 // build the sensor list returned to users
122 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700123
Aravind Akellae6406e32015-07-20 17:29:33 -0700124 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700125 Sensor aSensor;
126
127 // Add Android virtual sensors if they're not already
128 // available in the HAL
129
130 aSensor = registerVirtualSensor( new RotationVectorSensor() );
131 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
132 mUserSensorList.add(aSensor);
133 }
134
135 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
136 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
137 mUserSensorList.add(aSensor);
138 }
139
140 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
141 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
142 mUserSensorList.add(aSensor);
143 }
144
145 aSensor = registerVirtualSensor( new OrientationSensor() );
146 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
147 // if we are doing our own rotation-vector, also add
148 // the orientation sensor and remove the HAL provided one.
149 mUserSensorList.replaceAt(aSensor, orientationIndex);
150 }
151
Mathias Agopian33264862012-06-28 19:46:54 -0700152 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700153 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700154 registerVirtualSensor( new GyroDriftSensor() );
155 }
156
Mathias Agopian33264862012-06-28 19:46:54 -0700157 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700158 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700159
Aravind Akella5466c3d2014-08-22 16:11:10 -0700160 // Check if the device really supports batching by looking at the FIFO event
161 // counts for each sensor.
162 bool batchingSupported = false;
163 for (int i = 0; i < mSensorList.size(); ++i) {
164 if (mSensorList[i].getFifoMaxEventCount() > 0) {
165 batchingSupported = true;
166 break;
167 }
168 }
169
170 if (batchingSupported) {
171 // Increase socket buffer size to a max of 100 KB for batching capabilities.
172 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
173 } else {
174 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
175 }
176
177 // Compare the socketBufferSize value against the system limits and limit
178 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700179 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
180 char line[128];
181 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
182 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700183 size_t maxSystemSocketBufferSize;
184 sscanf(line, "%zu", &maxSystemSocketBufferSize);
185 if (mSocketBufferSize > maxSystemSocketBufferSize) {
186 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700187 }
188 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700189 if (fp) {
190 fclose(fp);
191 }
192
Aravind Akella9a844cf2014-02-11 18:58:52 -0800193 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700194 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700195 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
196 mSensorEventBuffer = new sensors_event_t[minBufferSize];
197 mSensorEventScratch = new sensors_event_t[minBufferSize];
198 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akella7830ef32014-10-07 14:13:12 -0700199
Aravind Akellab4373ac2014-10-29 17:55:20 -0700200 mAckReceiver = new SensorEventAckReceiver(this);
201 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700202 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700203 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700204 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700205 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700206}
207
Mathias Agopian03193062013-05-10 19:32:39 -0700208Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800209{
210 sensors_event_t event;
211 memset(&event, 0, sizeof(event));
212
213 const Sensor sensor(s->getSensor());
214 // add to the sensor list (returned to clients)
215 mSensorList.add(sensor);
216 // add to our handle->SensorInterface mapping
217 mSensorMap.add(sensor.getHandle(), s);
218 // create an entry in the mLastEventSeen array
219 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700220
221 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800222}
223
Mathias Agopian03193062013-05-10 19:32:39 -0700224Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800225{
Mathias Agopian03193062013-05-10 19:32:39 -0700226 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800227 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700228 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800229}
230
Mathias Agopianfc328812010-07-14 23:41:37 -0700231SensorService::~SensorService()
232{
Mathias Agopianf001c922010-11-11 17:58:51 -0800233 for (size_t i=0 ; i<mSensorMap.size() ; i++)
234 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700235}
236
Mathias Agopian1cb13462011-06-27 16:05:52 -0700237static const String16 sDump("android.permission.DUMP");
238
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700239status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700240{
Mathias Agopianfc328812010-07-14 23:41:37 -0700241 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700242 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700243 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000244 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700245 IPCThreadState::self()->getCallingPid(),
246 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700247 } else {
248 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700249 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700250 for (size_t i=0 ; i<mSensorList.size() ; i++) {
251 const Sensor& s(mSensorList[i]);
252 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700253 result.appendFormat(
Aravind Akella0b6acb22014-10-18 16:37:13 -0700254 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700255 s.getName().string(),
256 s.getVendor().string(),
Aravind Akella0b6acb22014-10-18 16:37:13 -0700257 s.getVersion(),
Aravind Akella70018042014-04-07 22:52:37 +0000258 s.getStringType().string(),
259 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700260 s.getRequiredPermission().string(),
261 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700262
Aravind Akella0e025c52014-06-03 19:19:57 -0700263 const int reportingMode = s.getReportingMode();
264 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700265 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700266 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700267 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700268 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700269 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700270 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700271 result.append(" special-trigger | ");
272 }
273
274 if (s.getMaxDelay() > 0) {
275 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
276 } else {
277 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700278 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700279
280 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700281 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700282 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700283 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700284 }
285
Aravind Akella724d91d2013-06-27 12:04:23 -0700286 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000287 result.appendFormat("FifoMax=%d events | ",
288 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700289 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700290 result.append("no batching | ");
291 }
292
293 if (s.isWakeUpSensor()) {
294 result.appendFormat("wakeUp | ");
295 } else {
296 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700297 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700298
299 switch (s.getType()) {
300 case SENSOR_TYPE_ROTATION_VECTOR:
301 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
302 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700303 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
304 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700305 break;
306 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
307 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
308 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700309 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
310 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
311 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700312 break;
313 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
314 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700315 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
316 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700317 break;
318 case SENSOR_TYPE_SIGNIFICANT_MOTION:
319 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700320 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700321 break;
322 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700323 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
324 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700325 break;
326 default:
327 // default to 3 values
328 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700329 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
330 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700331 break;
332 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700333 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700334 }
335 SensorFusion::getInstance().dump(result);
336 SensorDevice::getInstance().dump(result);
337
Mathias Agopianba02cd22013-07-03 16:20:57 -0700338 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700339 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700340 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700341 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700342 getSensorName(handle).string(),
343 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700344 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700345 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700346
Aravind Akella5466c3d2014-08-22 16:11:10 -0700347 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700348 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800349 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700350 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700351
352 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
353 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
354 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700355 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700356 connection->dump(result);
357 }
358 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700359 }
360 write(fd, result.string(), result.size());
361 return NO_ERROR;
362}
363
Aravind Akella9a844cf2014-02-11 18:58:52 -0800364void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700365 sensors_event_t const* buffer, const int count) {
366 for (int i=0 ; i<count ; i++) {
367 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700368 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
369 handle = buffer[i].meta_data.sensor;
370 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700371 if (connection->hasSensor(handle)) {
372 SensorInterface* sensor = mSensorMap.valueFor(handle);
373 // If this buffer has an event from a one_shot sensor and this connection is registered
374 // for this particular one_shot sensor, try cleaning up the connection.
375 if (sensor != NULL &&
376 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
377 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800378 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700379 }
380 }
381 }
382}
383
Mathias Agopianfc328812010-07-14 23:41:37 -0700384bool SensorService::threadLoop()
385{
Steve Blocka5512372011-12-20 16:23:08 +0000386 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700387
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700388 // each virtual sensor could generate an event per "real" event, that's why we need
389 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
390 // in practice, this is too aggressive, but guaranteed to be enough.
391 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
392 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
393
Mathias Agopianf001c922010-11-11 17:58:51 -0800394 SensorDevice& device(SensorDevice::getInstance());
395 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700396
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700397 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700398 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700399 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
400 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000401 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700402 break;
403 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700404
405 // Reset sensors_event_t.flags to zero for all events in the buffer.
406 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700407 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700408 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700409
410 // Make a copy of the connection vector as some connections may be removed during the
411 // course of this loop (especially when one-shot sensor events are present in the
412 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
413 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
414 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
415 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
416 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700417 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800418 Mutex::Autolock _l(mLock);
419 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
420 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
421 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
422 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
423 // releasing the wakelock.
424 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700425 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700426 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800427 bufferHasWakeUpEvent = true;
428 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700429 }
430 }
431
Aravind Akella9a844cf2014-02-11 18:58:52 -0800432 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700433 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800434 }
Aravind Akella8493b792014-09-08 15:45:47 -0700435 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800436
Mathias Agopianf001c922010-11-11 17:58:51 -0800437 // handle virtual sensors
438 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700439 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800440 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800441 if (activeVirtualSensorCount) {
442 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700443 SensorFusion& fusion(SensorFusion::getInstance());
444 if (fusion.isEnabled()) {
445 for (size_t i=0 ; i<size_t(count) ; i++) {
446 fusion.process(event[i]);
447 }
448 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700449 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800450 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700451 if (count + k >= minBufferSize) {
452 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700453 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700454 count, k, minBufferSize);
455 break;
456 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800457 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800458 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700459 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700460 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800461 k++;
462 }
463 }
464 }
465 if (k) {
466 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700467 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800468 count += k;
469 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700470 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700471 }
472 }
473 }
474
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700475 // handle backward compatibility for RotationVector sensor
476 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
477 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700478 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700479 // All the 4 components of the quaternion should be available
480 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700481 mSensorEventBuffer[i].data[4] = -1;
482 }
483 }
484 }
485
486 // Map flush_complete_events in the buffer to SensorEventConnections which called
487 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
488 // SensorEventConnection mapped to the corresponding flush_complete_event in
489 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
490 for (int i = 0; i < count; ++i) {
491 mMapFlushEventsToConnections[i] = NULL;
492 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
493 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
494 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
495 if (rec != NULL) {
496 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
497 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700498 }
499 }
500 }
501
Aravind Akella9a844cf2014-02-11 18:58:52 -0800502 // Send our events to clients. Check the state of wake lock for each client and release the
503 // lock if none of the clients need it.
504 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700505 size_t numConnections = activeConnections.size();
506 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700507 if (activeConnections[i] != 0) {
508 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700509 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700510 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700511 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
512 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700513 if (activeConnections[i]->hasOneShotSensors()) {
514 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
515 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700516 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800517 }
518 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700519
Aravind Akella9a844cf2014-02-11 18:58:52 -0800520 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700521 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800522 }
Aravind Akella8493b792014-09-08 15:45:47 -0700523 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700524
Steve Block3c20fbe2012-01-05 23:22:43 +0000525 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800526 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700527 return false;
528}
529
Aravind Akella56ae4262014-07-10 16:01:10 -0700530sp<Looper> SensorService::getLooper() const {
531 return mLooper;
532}
533
Aravind Akellab4373ac2014-10-29 17:55:20 -0700534void SensorService::resetAllWakeLockRefCounts() {
535 SortedVector< sp<SensorEventConnection> > activeConnections;
536 populateActiveConnections(&activeConnections);
537 {
538 Mutex::Autolock _l(mLock);
539 for (size_t i=0 ; i < activeConnections.size(); ++i) {
540 if (activeConnections[i] != 0) {
541 activeConnections[i]->resetWakeLockRefCount();
542 }
543 }
544 setWakeLockAcquiredLocked(false);
545 }
546}
547
548void SensorService::setWakeLockAcquiredLocked(bool acquire) {
549 if (acquire) {
550 if (!mWakeLockAcquired) {
551 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
552 mWakeLockAcquired = true;
553 }
554 mLooper->wake();
555 } else {
556 if (mWakeLockAcquired) {
557 release_wake_lock(WAKE_LOCK_NAME);
558 mWakeLockAcquired = false;
559 }
560 }
561}
562
563
564bool SensorService::isWakeLockAcquired() {
565 Mutex::Autolock _l(mLock);
566 return mWakeLockAcquired;
567}
568
Aravind Akella56ae4262014-07-10 16:01:10 -0700569bool SensorService::SensorEventAckReceiver::threadLoop() {
570 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700571 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700572 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700573 bool wakeLockAcquired = mService->isWakeLockAcquired();
574 int timeout = -1;
575 if (wakeLockAcquired) timeout = 5000;
576 int ret = looper->pollOnce(timeout);
577 if (ret == ALOOPER_POLL_TIMEOUT) {
578 mService->resetAllWakeLockRefCounts();
579 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700580 } while(!Thread::exitPending());
581 return false;
582}
583
Aravind Akella9a844cf2014-02-11 18:58:52 -0800584void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800585 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800586 const sensors_event_t* last = NULL;
587 for (size_t i = 0; i < count; i++) {
588 const sensors_event_t* event = &buffer[i];
589 if (event->type != SENSOR_TYPE_META_DATA) {
590 if (last && event->sensor != last->sensor) {
591 mLastEventSeen.editValueFor(last->sensor) = *last;
592 }
593 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800594 }
595 }
Aravind Akella4b847042014-03-03 19:02:46 -0800596 if (last) {
597 mLastEventSeen.editValueFor(last->sensor) = *last;
598 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800599}
600
Mathias Agopianf001c922010-11-11 17:58:51 -0800601void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
602{
603 struct compar {
604 static int cmp(void const* lhs, void const* rhs) {
605 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
606 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700607 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800608 }
609 };
610 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
611}
612
Mathias Agopian5d270722010-07-19 15:20:39 -0700613String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700614 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700615 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700616 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700617 if (sensor.getHandle() == handle) {
618 return sensor.getName();
619 }
620 }
621 String8 result("unknown");
622 return result;
623}
624
Aravind Akellab4099e72013-10-15 15:43:10 -0700625bool SensorService::isVirtualSensor(int handle) const {
626 SensorInterface* sensor = mSensorMap.valueFor(handle);
627 return sensor->isVirtual();
628}
629
Aravind Akella9a844cf2014-02-11 18:58:52 -0800630bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700631 int handle = event.sensor;
632 if (event.type == SENSOR_TYPE_META_DATA) {
633 handle = event.meta_data.sensor;
634 }
635 SensorInterface* sensor = mSensorMap.valueFor(handle);
636 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800637}
638
Aravind Akella6c2664a2014-08-13 12:24:50 -0700639
640SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
641 return mActiveSensors.valueFor(handle);
642}
643
Mathias Agopianfc328812010-07-14 23:41:37 -0700644Vector<Sensor> SensorService::getSensorList()
645{
Mathias Agopian33264862012-06-28 19:46:54 -0700646 char value[PROPERTY_VALUE_MAX];
647 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000648 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
649 mUserSensorListDebug : mUserSensorList;
650 Vector<Sensor> accessibleSensorList;
651 for (size_t i = 0; i < initialSensorList.size(); i++) {
652 Sensor sensor = initialSensorList[i];
653 if (canAccessSensor(sensor)) {
654 accessibleSensorList.add(sensor);
655 } else {
656 String8 infoMessage;
657 infoMessage.appendFormat(
658 "Skipped sensor %s because it requires permission %s",
659 sensor.getName().string(),
660 sensor.getRequiredPermission().string());
661 ALOGI(infoMessage.string());
662 }
Mathias Agopian33264862012-06-28 19:46:54 -0700663 }
Aravind Akella70018042014-04-07 22:52:37 +0000664 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700665}
666
667sp<ISensorEventConnection> SensorService::createSensorEventConnection()
668{
Mathias Agopian5307d172012-09-18 17:02:43 -0700669 uid_t uid = IPCThreadState::self()->getCallingUid();
670 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700671 return result;
672}
673
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800674void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700675{
676 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800677 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700678 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700679 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700680 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800681 int handle = mActiveSensors.keyAt(i);
682 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700683 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800684 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000685 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800686 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800687 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800688 }
Aravind Akella8a969552014-09-28 17:52:41 -0700689 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800690 }
691 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700692 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000693 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700694 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700695 c, i, handle);
696
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800697 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000698 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700699 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800700 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700701 delete rec;
702 size--;
703 } else {
704 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700705 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700706 }
Aravind Akella8a969552014-09-28 17:52:41 -0700707 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700708 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700709 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800710 if (c->needsWakeLock()) {
711 checkWakeLockStateLocked();
712 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700713}
714
Aravind Akella70018042014-04-07 22:52:37 +0000715Sensor SensorService::getSensorFromHandle(int handle) const {
716 return mSensorMap.valueFor(handle)->getSensor();
717}
718
Mathias Agopianfc328812010-07-14 23:41:37 -0700719status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700720 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700721{
Mathias Agopian50df2952010-07-19 19:09:10 -0700722 if (mInitCheck != NO_ERROR)
723 return mInitCheck;
724
Mathias Agopianf001c922010-11-11 17:58:51 -0800725 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700726 if (sensor == NULL) {
727 return BAD_VALUE;
728 }
Aravind Akella70018042014-04-07 22:52:37 +0000729
730 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
731 return BAD_VALUE;
732 }
733
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700734 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700735 SensorRecord* rec = mActiveSensors.valueFor(handle);
736 if (rec == 0) {
737 rec = new SensorRecord(connection);
738 mActiveSensors.add(handle, rec);
739 if (sensor->isVirtual()) {
740 mActiveVirtualSensors.add(handle, sensor);
741 }
742 } else {
743 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800744 // this sensor is already activated, but we are adding a connection that uses it.
745 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700746 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700747 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800748 // NOTE: The wake_up flag of this event may get set to
749 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700750 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
751 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800752 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700753 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800754 }
755 connection->sendEvents(&event, 1, NULL);
756 if (!connection->needsWakeLock() && mWakeLockAcquired) {
757 checkWakeLockStateLocked();
758 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700759 }
760 }
761 }
762 }
763
764 if (connection->addSensor(handle)) {
765 BatteryService::enableSensor(connection->getUid(), handle);
766 // the sensor was added (which means it wasn't already there)
767 // so, see if this connection becomes active
768 if (mActiveConnections.indexOf(connection) < 0) {
769 mActiveConnections.add(connection);
770 }
771 } else {
772 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
773 handle, connection.get());
774 }
775
Aravind Akella724d91d2013-06-27 12:04:23 -0700776 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
777 if (samplingPeriodNs < minDelayNs) {
778 samplingPeriodNs = minDelayNs;
779 }
780
Aravind Akella6c2664a2014-08-13 12:24:50 -0700781 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
782 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700783 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
784
785 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
786 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700787
Aravind Akella5466c3d2014-08-22 16:11:10 -0700788 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
789 // event before sending events on this connection. Ignore one-shot sensors which don't
790 // support flush(). Also if this sensor isn't already active, don't call flush().
791 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
792 rec->getNumConnections() > 1) {
793 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700794 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700795 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700796 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700797 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700798 } else {
799 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700800 }
801 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700802
803 if (err == NO_ERROR) {
804 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
805 err = sensor->activate(connection.get(), true);
806 }
807
Aravind Akella8a969552014-09-28 17:52:41 -0700808 if (err == NO_ERROR) {
809 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700810 }
811
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700812 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700813 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700814 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700815 }
816 return err;
817}
818
819status_t SensorService::disable(const sp<SensorEventConnection>& connection,
820 int handle)
821{
Mathias Agopian50df2952010-07-19 19:09:10 -0700822 if (mInitCheck != NO_ERROR)
823 return mInitCheck;
824
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700825 Mutex::Autolock _l(mLock);
826 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700827 if (err == NO_ERROR) {
828 SensorInterface* sensor = mSensorMap.valueFor(handle);
829 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
830 }
831 return err;
832}
833
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700834status_t SensorService::cleanupWithoutDisable(
835 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700836 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700837 return cleanupWithoutDisableLocked(connection, handle);
838}
839
840status_t SensorService::cleanupWithoutDisableLocked(
841 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700842 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700843 if (rec) {
844 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700845 if (connection->removeSensor(handle)) {
846 BatteryService::disableSensor(connection->getUid(), handle);
847 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700848 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700849 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700850 mActiveConnections.remove(connection);
851 }
852 // see if this sensor becomes inactive
853 if (rec->removeConnection(connection)) {
854 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800855 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700856 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700857 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700858 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700859 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700860 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700861}
862
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700863status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700864 int handle, nsecs_t ns)
865{
Mathias Agopian50df2952010-07-19 19:09:10 -0700866 if (mInitCheck != NO_ERROR)
867 return mInitCheck;
868
Mathias Agopianae09d652011-11-01 17:37:49 -0700869 SensorInterface* sensor = mSensorMap.valueFor(handle);
870 if (!sensor)
871 return BAD_VALUE;
872
Aravind Akella70018042014-04-07 22:52:37 +0000873 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
874 return BAD_VALUE;
875 }
876
Mathias Agopian1cd70002010-07-21 15:59:50 -0700877 if (ns < 0)
878 return BAD_VALUE;
879
Mathias Agopian62569ec2011-11-07 21:21:47 -0800880 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
881 if (ns < minDelayNs) {
882 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700883 }
884
Mathias Agopianf001c922010-11-11 17:58:51 -0800885 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700886}
887
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700888status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
Aravind Akella70018042014-04-07 22:52:37 +0000889 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700890 SensorDevice& dev(SensorDevice::getInstance());
891 const int halVersion = dev.getHalDeviceVersion();
892 status_t err(NO_ERROR);
893 Mutex::Autolock _l(mLock);
894 // Loop through all sensors for this connection and call flush on each of them.
895 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
896 const int handle = connection->mSensorInfo.keyAt(i);
897 SensorInterface* sensor = mSensorMap.valueFor(handle);
898 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
899 ALOGE("flush called on a one-shot sensor");
900 err = INVALID_OPERATION;
901 continue;
902 }
Aravind Akella8493b792014-09-08 15:45:47 -0700903 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700904 // For older devices just increment pending flush count which will send a trivial
905 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700906 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700907 } else {
908 status_t err_flush = sensor->flush(connection.get(), handle);
909 if (err_flush == NO_ERROR) {
910 SensorRecord* rec = mActiveSensors.valueFor(handle);
911 if (rec != NULL) rec->addPendingFlushConnection(connection);
912 }
913 err = (err_flush != NO_ERROR) ? err_flush : err;
914 }
Aravind Akella70018042014-04-07 22:52:37 +0000915 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700916 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -0700917}
Aravind Akella70018042014-04-07 22:52:37 +0000918
Aravind Akella70018042014-04-07 22:52:37 +0000919bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700920 return (sensor.getRequiredPermission().isEmpty()) ||
921 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +0000922}
923
924bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
925 if (canAccessSensor(sensor)) {
926 return true;
927 } else {
928 String8 errorMessage;
929 errorMessage.appendFormat(
930 "%s a sensor (%s) without holding its required permission: %s",
931 operation,
932 sensor.getName().string(),
933 sensor.getRequiredPermission().string());
934 return false;
935 }
936}
937
Aravind Akella9a844cf2014-02-11 18:58:52 -0800938void SensorService::checkWakeLockState() {
939 Mutex::Autolock _l(mLock);
940 checkWakeLockStateLocked();
941}
942
943void SensorService::checkWakeLockStateLocked() {
944 if (!mWakeLockAcquired) {
945 return;
946 }
947 bool releaseLock = true;
948 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
949 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
950 if (connection != 0) {
951 if (connection->needsWakeLock()) {
952 releaseLock = false;
953 break;
954 }
955 }
956 }
957 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700958 setWakeLockAcquiredLocked(false);
959 }
960}
961
962void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
963 Mutex::Autolock _l(mLock);
964 connection->writeToSocketFromCache();
965 if (connection->needsWakeLock()) {
966 setWakeLockAcquiredLocked(true);
967 }
968}
969
970void SensorService::populateActiveConnections(
971 SortedVector< sp<SensorEventConnection> >* activeConnections) {
972 Mutex::Autolock _l(mLock);
973 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
974 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
975 if (connection != 0) {
976 activeConnections->add(connection);
977 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800978 }
979}
Aravind Akella6c2664a2014-08-13 12:24:50 -0700980
Mathias Agopianfc328812010-07-14 23:41:37 -0700981// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -0700982SensorService::SensorRecord::SensorRecord(
983 const sp<SensorEventConnection>& connection)
984{
985 mConnections.add(connection);
986}
987
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700988bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700989 const sp<SensorEventConnection>& connection)
990{
991 if (mConnections.indexOf(connection) < 0) {
992 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700993 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700994 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700995 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700996}
997
998bool SensorService::SensorRecord::removeConnection(
999 const wp<SensorEventConnection>& connection)
1000{
1001 ssize_t index = mConnections.indexOf(connection);
1002 if (index >= 0) {
1003 mConnections.removeItemsAt(index, 1);
1004 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001005 // Remove this connections from the queue of flush() calls made on this sensor.
1006 for (Vector< wp<SensorEventConnection> >::iterator it =
1007 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001008
Aravind Akella6c2664a2014-08-13 12:24:50 -07001009 if (it->unsafe_get() == connection.unsafe_get()) {
1010 it = mPendingFlushConnections.erase(it);
1011 } else {
1012 ++it;
1013 }
1014 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001015 return mConnections.size() ? false : true;
1016}
1017
Aravind Akella6c2664a2014-08-13 12:24:50 -07001018void SensorService::SensorRecord::addPendingFlushConnection(
1019 const sp<SensorEventConnection>& connection) {
1020 mPendingFlushConnections.add(connection);
1021}
1022
1023void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1024 if (mPendingFlushConnections.size() > 0) {
1025 mPendingFlushConnections.removeAt(0);
1026 }
1027}
1028
1029SensorService::SensorEventConnection *
1030SensorService::SensorRecord::getFirstPendingFlushConnection() {
1031 if (mPendingFlushConnections.size() > 0) {
1032 return mPendingFlushConnections[0].unsafe_get();
1033 }
1034 return NULL;
1035}
1036
Mathias Agopianfc328812010-07-14 23:41:37 -07001037// ---------------------------------------------------------------------------
1038
1039SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -07001040 const sp<SensorService>& service, uid_t uid)
Aravind Akella8a969552014-09-28 17:52:41 -07001041 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
1042 mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001043 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001044#if DEBUG_CONNECTIONS
1045 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001046 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001047#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001048}
1049
Aravind Akella56ae4262014-07-10 16:01:10 -07001050SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001051 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001052 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001053 if (mEventCache != NULL) {
1054 delete mEventCache;
1055 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001056}
1057
Aravind Akella56ae4262014-07-10 16:01:10 -07001058void SensorService::SensorEventConnection::onFirstRef() {
1059 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001060}
1061
Aravind Akella9a844cf2014-02-11 18:58:52 -08001062bool SensorService::SensorEventConnection::needsWakeLock() {
1063 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001064 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001065}
1066
Aravind Akellab4373ac2014-10-29 17:55:20 -07001067void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1068 Mutex::Autolock _l(mConnectionLock);
1069 mWakeLockRefCount = 0;
1070}
1071
Aravind Akella4c8b9512013-09-05 17:03:38 -07001072void SensorService::SensorEventConnection::dump(String8& result) {
1073 Mutex::Autolock _l(mConnectionLock);
Aravind Akella0ec20662014-09-14 17:29:48 -07001074 result.appendFormat("\t WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1075 mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001076 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1077 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001078 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001079 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001080 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001081 flushInfo.mFirstFlushPending ? "First flush pending" :
1082 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001083 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001084 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001085#if DEBUG_CONNECTIONS
1086 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1087 " total_acks_needed %d | total_acks_recvd %d\n",
1088 mEventsReceived,
1089 mEventsSent,
1090 mEventsSentFromCache,
1091 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1092 mTotalAcksNeeded,
1093 mTotalAcksReceived);
1094#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001095}
1096
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001097bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001098 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +00001099 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1100 return false;
1101 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001102 if (mSensorInfo.indexOfKey(handle) < 0) {
1103 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001104 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001105 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001106 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001107}
1108
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001109bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001110 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001111 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001112 return true;
1113 }
1114 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001115}
1116
1117bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001118 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001119 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001120}
1121
1122bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001123 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001124 return mSensorInfo.size() ? true : false;
1125}
1126
Aravind Akella8493b792014-09-08 15:45:47 -07001127bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1128 Mutex::Autolock _l(mConnectionLock);
1129 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1130 const int handle = mSensorInfo.keyAt(i);
1131 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1132 return true;
1133 }
1134 }
1135 return false;
1136}
1137
Aravind Akella4c8b9512013-09-05 17:03:38 -07001138void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1139 bool value) {
1140 Mutex::Autolock _l(mConnectionLock);
1141 ssize_t index = mSensorInfo.indexOfKey(handle);
1142 if (index >= 0) {
1143 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1144 flushInfo.mFirstFlushPending = value;
1145 }
1146}
1147
Aravind Akella8a969552014-09-28 17:52:41 -07001148void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1149 Mutex::Autolock _l(mConnectionLock);
1150 updateLooperRegistrationLocked(looper);
1151}
1152
1153void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1154 const sp<Looper>& looper) {
1155 bool isConnectionActive = mSensorInfo.size() > 0;
1156 // If all sensors are unregistered OR Looper has encountered an error, we
1157 // can remove the Fd from the Looper if it has been previously added.
1158 if (!isConnectionActive || mDead) {
1159 if (mHasLooperCallbacks) {
1160 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1161 looper->removeFd(mChannel->getSendFd());
1162 mHasLooperCallbacks = false;
1163 }
1164 return;
1165 }
1166
1167 int looper_flags = 0;
1168 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
1169 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1170 const int handle = mSensorInfo.keyAt(i);
1171 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1172 looper_flags |= ALOOPER_EVENT_INPUT;
1173 break;
1174 }
1175 }
1176 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1177 // the fd has already been added, remove it. This is likely to happen when ALL the
1178 // events stored in the cache have been sent to the corresponding app.
1179 if (looper_flags == 0) {
1180 if (mHasLooperCallbacks) {
1181 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1182 looper->removeFd(mChannel->getSendFd());
1183 mHasLooperCallbacks = false;
1184 }
1185 return;
1186 }
1187 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1188 // registered for wake-up sensors OR for sending events in the cache.
1189 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1190 if (ret == 1) {
1191 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1192 mHasLooperCallbacks = true;
1193 } else {
1194 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1195 }
1196}
1197
1198void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1199 Mutex::Autolock _l(mConnectionLock);
1200 ssize_t index = mSensorInfo.indexOfKey(handle);
1201 if (index >= 0) {
1202 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1203 flushInfo.mPendingFlushEventsToSend++;
1204 }
1205}
1206
Mathias Agopianfc328812010-07-14 23:41:37 -07001207status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001208 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001209 sensors_event_t* scratch,
1210 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001211 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001212 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001213 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001214 if (scratch) {
1215 size_t i=0;
1216 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001217 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001218 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1219 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001220 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001221 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1222 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1223 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001224 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001225 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001226 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001227 // Check if this connection has registered for this sensor. If not continue to the
1228 // next sensor_event.
1229 if (index < 0) {
1230 ++i;
1231 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001232 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001233
Aravind Akella56ae4262014-07-10 16:01:10 -07001234 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001235 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001236 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1237 this == mapFlushEventsToConnections[i]) {
1238 flushInfo.mFirstFlushPending = false;
1239 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1240 buffer[i].meta_data.sensor);
1241 ++i;
1242 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001243 }
1244
1245 // If there is a pending flush complete event for this sensor on this connection,
1246 // ignore the event and proceed to the next.
1247 if (flushInfo.mFirstFlushPending) {
1248 ++i;
1249 continue;
1250 }
1251
1252 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001253 // Keep copying events into the scratch buffer as long as they are regular
1254 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1255 // from the same sensor_handle AND the current connection is mapped to the
1256 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001257 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001258 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001259 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001260 }
1261 ++i;
1262 } else {
1263 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001264 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001265 }
Aravind Akella8493b792014-09-08 15:45:47 -07001266 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1267 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001268 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001269 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001270 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001271 } else {
1272 scratch = const_cast<sensors_event_t *>(buffer);
1273 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001274 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001275
Aravind Akella6c2664a2014-08-13 12:24:50 -07001276 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001277 // Early return if there are no events for this connection.
1278 if (count == 0) {
1279 return status_t(NO_ERROR);
1280 }
1281
1282#if DEBUG_CONNECTIONS
1283 mEventsReceived += count;
1284#endif
1285 if (mCacheSize != 0) {
1286 // There are some events in the cache which need to be sent first. Copy this buffer to
1287 // the end of cache.
1288 if (mCacheSize + count <= mMaxCacheSize) {
1289 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1290 mCacheSize += count;
1291 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001292 // Check if any new sensors have registered on this connection which may have increased
1293 // the max cache size that is desired.
1294 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1295 reAllocateCacheLocked(scratch, count);
1296 return status_t(NO_ERROR);
1297 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001298 // Some events need to be dropped.
1299 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1300 if (remaningCacheSize != 0) {
1301 memcpy(&mEventCache[mCacheSize], scratch,
1302 remaningCacheSize * sizeof(sensors_event_t));
1303 }
1304 int numEventsDropped = count - remaningCacheSize;
1305 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1306 // Drop the first "numEventsDropped" in the cache.
1307 memmove(mEventCache, &mEventCache[numEventsDropped],
1308 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1309
1310 // Copy the remainingEvents in scratch buffer to the end of cache.
1311 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1312 numEventsDropped * sizeof(sensors_event_t));
1313 }
1314 return status_t(NO_ERROR);
1315 }
1316
Aravind Akella6c2664a2014-08-13 12:24:50 -07001317 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1318 if (index_wake_up_event >= 0) {
1319 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1320 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001321#if DEBUG_CONNECTIONS
1322 ++mTotalAcksNeeded;
1323#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001324 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001325
1326 // NOTE: ASensorEvent and sensors_event_t are the same type.
1327 ssize_t size = SensorEventQueue::write(mChannel,
1328 reinterpret_cast<ASensorEvent const*>(scratch), count);
1329 if (size < 0) {
1330 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001331 if (index_wake_up_event >= 0) {
1332 // If there was a wake_up sensor_event, reset the flag.
1333 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001334 if (mWakeLockRefCount > 0) {
1335 --mWakeLockRefCount;
1336 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001337#if DEBUG_CONNECTIONS
1338 --mTotalAcksNeeded;
1339#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001340 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001341 if (mEventCache == NULL) {
1342 mMaxCacheSize = computeMaxCacheSizeLocked();
1343 mEventCache = new sensors_event_t[mMaxCacheSize];
1344 mCacheSize = 0;
1345 }
1346 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1347 mCacheSize += count;
1348
1349 // Add this file descriptor to the looper to get a callback when this fd is available for
1350 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001351 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001352 return size;
1353 }
1354
1355#if DEBUG_CONNECTIONS
1356 if (size > 0) {
1357 mEventsSent += count;
1358 }
1359#endif
1360
1361 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1362}
1363
Aravind Akella6c2664a2014-08-13 12:24:50 -07001364void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1365 int count) {
1366 sensors_event_t *eventCache_new;
1367 const int new_cache_size = computeMaxCacheSizeLocked();
1368 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1369 eventCache_new = new sensors_event_t[new_cache_size];
1370 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1371 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1372
1373 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1374 new_cache_size);
1375
1376 delete mEventCache;
1377 mEventCache = eventCache_new;
1378 mCacheSize += count;
1379 mMaxCacheSize = new_cache_size;
1380}
1381
1382void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1383 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001384 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001385 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001386 // Loop through all the sensors for this connection and check if there are any pending
1387 // flush complete events to be sent.
1388 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1389 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1390 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001391 const int sensor_handle = mSensorInfo.keyAt(i);
1392 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001393 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1394 if (wakeUpSensor) {
1395 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001396 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1397 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001398 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1399 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001400 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001401 return;
1402 }
1403 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1404 flushCompleteEvent.meta_data.sensor);
1405 flushInfo.mPendingFlushEventsToSend--;
1406 }
1407 }
1408}
1409
Aravind Akellab4373ac2014-10-29 17:55:20 -07001410void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001411 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1412 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1413 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1414 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001415 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001416 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001417 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001418 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001419 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001420 int index_wake_up_event =
1421 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1422 if (index_wake_up_event >= 0) {
1423 mEventCache[index_wake_up_event + numEventsSent].flags |=
1424 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1425 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001426#if DEBUG_CONNECTIONS
1427 ++mTotalAcksNeeded;
1428#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001429 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001430
Aravind Akella56ae4262014-07-10 16:01:10 -07001431 ssize_t size = SensorEventQueue::write(mChannel,
1432 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001433 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001434 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001435 if (index_wake_up_event >= 0) {
1436 // If there was a wake_up sensor_event, reset the flag.
1437 mEventCache[index_wake_up_event + numEventsSent].flags &=
1438 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001439 if (mWakeLockRefCount > 0) {
1440 --mWakeLockRefCount;
1441 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001442#if DEBUG_CONNECTIONS
1443 --mTotalAcksNeeded;
1444#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001445 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001446 memmove(mEventCache, &mEventCache[numEventsSent],
1447 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1448 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001449 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001450 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001451 return;
1452 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001453 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001454#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001455 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001456#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001457 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001458 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1459 // All events from the cache have been sent. Reset cache size to zero.
1460 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001461 // There are no more events in the cache. We don't need to poll for write on the fd.
1462 // Update Looper registration.
1463 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001464}
1465
Aravind Akellac551eac2013-10-14 17:04:42 -07001466void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001467 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001468 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001469 // Count flushComplete events in the events that are about to the dropped. These will be sent
1470 // separately before the next batch of events.
1471 for (int j = 0; j < numEventsDropped; ++j) {
1472 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1473 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1474 flushInfo.mPendingFlushEventsToSend++;
1475 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1476 flushInfo.mPendingFlushEventsToSend);
1477 }
1478 }
1479 return;
1480}
1481
Aravind Akella6c2664a2014-08-13 12:24:50 -07001482int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1483 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001484 for (int i = 0; i < count; ++i) {
1485 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001486 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001487 }
1488 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001489 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001490}
1491
Mathias Agopianb3989272011-10-20 18:42:02 -07001492sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001493{
1494 return mChannel;
1495}
1496
1497status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001498 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1499 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001500{
1501 status_t err;
1502 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001503 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1504 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001505
Mathias Agopianfc328812010-07-14 23:41:37 -07001506 } else {
1507 err = mService->disable(this, handle);
1508 }
1509 return err;
1510}
1511
1512status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001513 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001514{
Aravind Akella724d91d2013-06-27 12:04:23 -07001515 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001516}
1517
Aravind Akella701166d2013-10-08 14:59:26 -07001518status_t SensorService::SensorEventConnection::flush() {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001519 return mService->flushSensor(this);
Aravind Akella724d91d2013-06-27 12:04:23 -07001520}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001521
Aravind Akella8a969552014-09-28 17:52:41 -07001522int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001523 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001524 {
1525 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1526 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1527 // can release the wake-lock.
1528 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1529 Mutex::Autolock _l(mConnectionLock);
1530 mDead = true;
1531 mWakeLockRefCount = 0;
1532 updateLooperRegistrationLocked(mService->getLooper());
1533 }
1534 mService->checkWakeLockState();
1535 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001536 }
1537
1538 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akella8a969552014-09-28 17:52:41 -07001539 uint32_t numAcks = 0;
1540 ssize_t ret = ::recv(fd, &numAcks, sizeof(numAcks), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001541 {
1542 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001543 // Sanity check to ensure there are no read errors in recv, numAcks is always
1544 // within the range and not zero. If any of the above don't hold reset mWakeLockRefCount
1545 // to zero.
1546 if (ret != sizeof(numAcks) || numAcks > mWakeLockRefCount || numAcks == 0) {
1547 ALOGE("Looper read error ret=%d numAcks=%d", ret, numAcks);
1548 mWakeLockRefCount = 0;
1549 } else {
1550 mWakeLockRefCount -= numAcks;
Aravind Akella0ec20662014-09-14 17:29:48 -07001551 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001552#if DEBUG_CONNECTIONS
Aravind Akella8a969552014-09-28 17:52:41 -07001553 mTotalAcksReceived += numAcks;
Aravind Akellae74baf62014-08-21 12:28:35 -07001554#endif
Aravind Akella56ae4262014-07-10 16:01:10 -07001555 }
1556 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1557 // here as checkWakeLockState() will need it.
1558 if (mWakeLockRefCount == 0) {
1559 mService->checkWakeLockState();
1560 }
1561 // continue getting callbacks.
1562 return 1;
1563 }
1564
1565 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001566 // send sensor data that is stored in mEventCache for this connection.
1567 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001568 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001569 return 1;
1570}
1571
1572int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1573 int fifoWakeUpSensors = 0;
1574 int fifoNonWakeUpSensors = 0;
1575 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1576 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1577 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1578 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1579 // non wake_up sensors.
1580 if (sensor.isWakeUpSensor()) {
1581 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1582 } else {
1583 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1584 }
1585 } else {
1586 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1587 if (sensor.isWakeUpSensor()) {
1588 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1589 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1590
1591 } else {
1592 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1593 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1594
1595 }
1596 }
1597 }
1598 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1599 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001600 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001601 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001602 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001603 }
1604 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001605}
1606
Mathias Agopianfc328812010-07-14 23:41:37 -07001607// ---------------------------------------------------------------------------
1608}; // namespace android
1609