blob: 4b50f6fd9ec2540e6e6e2d9b6165b970bb70fa46 [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()
Mathias Agopian1cb13462011-06-27 16:05:52 -070069 : mInitCheck(NO_INIT)
Mathias Agopianfc328812010-07-14 23:41:37 -070070{
71}
72
73void SensorService::onFirstRef()
74{
Steve Blocka5512372011-12-20 16:23:08 +000075 ALOGD("nuSensorService starting...");
Mathias Agopian50df2952010-07-19 19:09:10 -070076
Mathias Agopianf001c922010-11-11 17:58:51 -080077 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070078
Mathias Agopianf001c922010-11-11 17:58:51 -080079 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080080 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070081 ssize_t count = dev.getSensorList(&list);
82 if (count > 0) {
83 ssize_t orientationIndex = -1;
84 bool hasGyro = false;
85 uint32_t virtualSensorsNeeds =
86 (1<<SENSOR_TYPE_GRAVITY) |
87 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
88 (1<<SENSOR_TYPE_ROTATION_VECTOR);
89
90 mLastEventSeen.setCapacity(count);
91 for (ssize_t i=0 ; i<count ; i++) {
92 registerSensor( new HardwareSensor(list[i]) );
93 switch (list[i].type) {
94 case SENSOR_TYPE_ORIENTATION:
95 orientationIndex = i;
96 break;
97 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -070098 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070099 hasGyro = true;
100 break;
101 case SENSOR_TYPE_GRAVITY:
102 case SENSOR_TYPE_LINEAR_ACCELERATION:
103 case SENSOR_TYPE_ROTATION_VECTOR:
104 virtualSensorsNeeds &= ~(1<<list[i].type);
105 break;
106 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700107 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700108
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700109 // it's safe to instantiate the SensorFusion object here
110 // (it wants to be instantiated after h/w sensors have been
111 // registered)
112 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700113
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700114 // build the sensor list returned to users
115 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700116
117 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700118 Sensor aSensor;
119
120 // Add Android virtual sensors if they're not already
121 // available in the HAL
122
123 aSensor = registerVirtualSensor( new RotationVectorSensor() );
124 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
125 mUserSensorList.add(aSensor);
126 }
127
128 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
129 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
130 mUserSensorList.add(aSensor);
131 }
132
133 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
134 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
135 mUserSensorList.add(aSensor);
136 }
137
138 aSensor = registerVirtualSensor( new OrientationSensor() );
139 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
140 // if we are doing our own rotation-vector, also add
141 // the orientation sensor and remove the HAL provided one.
142 mUserSensorList.replaceAt(aSensor, orientationIndex);
143 }
144
Mathias Agopian33264862012-06-28 19:46:54 -0700145 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700146 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700147 registerVirtualSensor( new GyroDriftSensor() );
148 }
149
Mathias Agopian33264862012-06-28 19:46:54 -0700150 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700151 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700152
Aravind Akella5466c3d2014-08-22 16:11:10 -0700153 // Check if the device really supports batching by looking at the FIFO event
154 // counts for each sensor.
155 bool batchingSupported = false;
156 for (int i = 0; i < mSensorList.size(); ++i) {
157 if (mSensorList[i].getFifoMaxEventCount() > 0) {
158 batchingSupported = true;
159 break;
160 }
161 }
162
163 if (batchingSupported) {
164 // Increase socket buffer size to a max of 100 KB for batching capabilities.
165 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
166 } else {
167 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
168 }
169
170 // Compare the socketBufferSize value against the system limits and limit
171 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700172 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
173 char line[128];
174 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
175 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700176 size_t maxSystemSocketBufferSize;
177 sscanf(line, "%zu", &maxSystemSocketBufferSize);
178 if (mSocketBufferSize > maxSystemSocketBufferSize) {
179 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700180 }
181 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700182 if (fp) {
183 fclose(fp);
184 }
185
Aravind Akella9a844cf2014-02-11 18:58:52 -0800186 mWakeLockAcquired = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700187 run("SensorService", PRIORITY_URGENT_DISPLAY);
Aravind Akella56ae4262014-07-10 16:01:10 -0700188 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700189
190 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
191 mSensorEventBuffer = new sensors_event_t[minBufferSize];
192 mSensorEventScratch = new sensors_event_t[minBufferSize];
193 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700194 mInitCheck = NO_ERROR;
195 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700196 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700197}
198
Mathias Agopian03193062013-05-10 19:32:39 -0700199Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800200{
201 sensors_event_t event;
202 memset(&event, 0, sizeof(event));
203
204 const Sensor sensor(s->getSensor());
205 // add to the sensor list (returned to clients)
206 mSensorList.add(sensor);
207 // add to our handle->SensorInterface mapping
208 mSensorMap.add(sensor.getHandle(), s);
209 // create an entry in the mLastEventSeen array
210 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700211
212 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800213}
214
Mathias Agopian03193062013-05-10 19:32:39 -0700215Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800216{
Mathias Agopian03193062013-05-10 19:32:39 -0700217 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800218 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700219 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800220}
221
Mathias Agopianfc328812010-07-14 23:41:37 -0700222SensorService::~SensorService()
223{
Mathias Agopianf001c922010-11-11 17:58:51 -0800224 for (size_t i=0 ; i<mSensorMap.size() ; i++)
225 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700226}
227
Mathias Agopian1cb13462011-06-27 16:05:52 -0700228static const String16 sDump("android.permission.DUMP");
229
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700230status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700231{
Mathias Agopianfc328812010-07-14 23:41:37 -0700232 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700233 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700234 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000235 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700236 IPCThreadState::self()->getCallingPid(),
237 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700238 } else {
239 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700240 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700241 for (size_t i=0 ; i<mSensorList.size() ; i++) {
242 const Sensor& s(mSensorList[i]);
243 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700244 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700245 "%-15s| %-10s| %-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700246 s.getName().string(),
247 s.getVendor().string(),
Aravind Akella70018042014-04-07 22:52:37 +0000248 s.getStringType().string(),
249 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700250 s.getRequiredPermission().string(),
251 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700252
Aravind Akella0e025c52014-06-03 19:19:57 -0700253 const int reportingMode = s.getReportingMode();
254 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700255 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700256 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700257 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700258 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700259 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700260 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700261 result.append(" special-trigger | ");
262 }
263
264 if (s.getMaxDelay() > 0) {
265 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
266 } else {
267 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700268 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700269
270 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700271 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700272 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700273 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700274 }
275
Aravind Akella724d91d2013-06-27 12:04:23 -0700276 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000277 result.appendFormat("FifoMax=%d events | ",
278 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700279 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700280 result.append("no batching | ");
281 }
282
283 if (s.isWakeUpSensor()) {
284 result.appendFormat("wakeUp | ");
285 } else {
286 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700287 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700288
289 switch (s.getType()) {
290 case SENSOR_TYPE_ROTATION_VECTOR:
291 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
292 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700293 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
294 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700295 break;
296 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
297 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
298 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700299 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
300 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
301 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700302 break;
303 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
304 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700305 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
306 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700307 break;
308 case SENSOR_TYPE_SIGNIFICANT_MOTION:
309 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700310 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700311 break;
312 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700313 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
314 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700315 break;
316 default:
317 // default to 3 values
318 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700319 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
320 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700321 break;
322 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700323 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700324 }
325 SensorFusion::getInstance().dump(result);
326 SensorDevice::getInstance().dump(result);
327
Mathias Agopianba02cd22013-07-03 16:20:57 -0700328 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700329 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700330 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700331 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700332 getSensorName(handle).string(),
333 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700334 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700335 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700336
Aravind Akella5466c3d2014-08-22 16:11:10 -0700337 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700338 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800339 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700340 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700341
342 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
343 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
344 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700345 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700346 connection->dump(result);
347 }
348 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700349 }
350 write(fd, result.string(), result.size());
351 return NO_ERROR;
352}
353
Aravind Akella9a844cf2014-02-11 18:58:52 -0800354void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700355 sensors_event_t const* buffer, const int count) {
356 for (int i=0 ; i<count ; i++) {
357 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700358 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
359 handle = buffer[i].meta_data.sensor;
360 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700361 if (connection->hasSensor(handle)) {
362 SensorInterface* sensor = mSensorMap.valueFor(handle);
363 // If this buffer has an event from a one_shot sensor and this connection is registered
364 // for this particular one_shot sensor, try cleaning up the connection.
365 if (sensor != NULL &&
366 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
367 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800368 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700369 }
370 }
371 }
372}
373
Mathias Agopianfc328812010-07-14 23:41:37 -0700374bool SensorService::threadLoop()
375{
Steve Blocka5512372011-12-20 16:23:08 +0000376 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700377
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700378 // each virtual sensor could generate an event per "real" event, that's why we need
379 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
380 // in practice, this is too aggressive, but guaranteed to be enough.
381 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
382 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
383
Mathias Agopianf001c922010-11-11 17:58:51 -0800384 SensorDevice& device(SensorDevice::getInstance());
385 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700386
Aravind Akella56ae4262014-07-10 16:01:10 -0700387 SensorEventAckReceiver sender(this);
388 sender.run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700389 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700390 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700391 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
392 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000393 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700394 break;
395 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700396
397 // Reset sensors_event_t.flags to zero for all events in the buffer.
398 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700399 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700400 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700401
402 // Make a copy of the connection vector as some connections may be removed during the
403 // course of this loop (especially when one-shot sensor events are present in the
404 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
405 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
406 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
407 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
408 SortedVector< sp<SensorEventConnection> > activeConnections;
409 {
410 Mutex::Autolock _l(mLock);
411 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
412 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
413 if (connection != 0) {
414 activeConnections.add(connection);
415 }
416 }
417 }
418
Aravind Akella9a844cf2014-02-11 18:58:52 -0800419 Mutex::Autolock _l(mLock);
420 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
421 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
422 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
423 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
424 // releasing the wakelock.
425 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700426 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700427 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800428 bufferHasWakeUpEvent = true;
429 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700430 }
431 }
432
Aravind Akella9a844cf2014-02-11 18:58:52 -0800433 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
434 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
435 mWakeLockAcquired = true;
436 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
437 }
Aravind Akella8493b792014-09-08 15:45:47 -0700438 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800439
Mathias Agopianf001c922010-11-11 17:58:51 -0800440 // handle virtual sensors
441 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700442 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800443 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800444 if (activeVirtualSensorCount) {
445 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700446 SensorFusion& fusion(SensorFusion::getInstance());
447 if (fusion.isEnabled()) {
448 for (size_t i=0 ; i<size_t(count) ; i++) {
449 fusion.process(event[i]);
450 }
451 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700452 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800453 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700454 if (count + k >= minBufferSize) {
455 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700456 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700457 count, k, minBufferSize);
458 break;
459 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800460 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800461 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700462 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700463 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800464 k++;
465 }
466 }
467 }
468 if (k) {
469 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700470 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800471 count += k;
472 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700473 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700474 }
475 }
476 }
477
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700478 // handle backward compatibility for RotationVector sensor
479 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
480 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700481 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700482 // All the 4 components of the quaternion should be available
483 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700484 mSensorEventBuffer[i].data[4] = -1;
485 }
486 }
487 }
488
489 // Map flush_complete_events in the buffer to SensorEventConnections which called
490 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
491 // SensorEventConnection mapped to the corresponding flush_complete_event in
492 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
493 for (int i = 0; i < count; ++i) {
494 mMapFlushEventsToConnections[i] = NULL;
495 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
496 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
497 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
498 if (rec != NULL) {
499 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
500 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700501 }
502 }
503 }
504
Aravind Akella9a844cf2014-02-11 18:58:52 -0800505 // Send our events to clients. Check the state of wake lock for each client and release the
506 // lock if none of the clients need it.
507 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700508 size_t numConnections = activeConnections.size();
509 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700510 if (activeConnections[i] != 0) {
511 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700512 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700513 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700514 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
515 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700516 if (activeConnections[i]->hasOneShotSensors()) {
517 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
518 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700519 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800520 }
521 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700522
Aravind Akella9a844cf2014-02-11 18:58:52 -0800523 if (mWakeLockAcquired && !needsWakeLock) {
524 release_wake_lock(WAKE_LOCK_NAME);
525 mWakeLockAcquired = false;
526 ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
527 }
Aravind Akella8493b792014-09-08 15:45:47 -0700528 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700529
Steve Block3c20fbe2012-01-05 23:22:43 +0000530 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800531 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700532 return false;
533}
534
Aravind Akella56ae4262014-07-10 16:01:10 -0700535sp<Looper> SensorService::getLooper() const {
536 return mLooper;
537}
538
539bool SensorService::SensorEventAckReceiver::threadLoop() {
540 ALOGD("new thread SensorEventAckReceiver");
541 do {
542 sp<Looper> looper = mService->getLooper();
543 looper->pollOnce(-1);
544 } while(!Thread::exitPending());
545 return false;
546}
547
Aravind Akella9a844cf2014-02-11 18:58:52 -0800548void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800549 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800550 const sensors_event_t* last = NULL;
551 for (size_t i = 0; i < count; i++) {
552 const sensors_event_t* event = &buffer[i];
553 if (event->type != SENSOR_TYPE_META_DATA) {
554 if (last && event->sensor != last->sensor) {
555 mLastEventSeen.editValueFor(last->sensor) = *last;
556 }
557 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800558 }
559 }
Aravind Akella4b847042014-03-03 19:02:46 -0800560 if (last) {
561 mLastEventSeen.editValueFor(last->sensor) = *last;
562 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800563}
564
Mathias Agopianf001c922010-11-11 17:58:51 -0800565void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
566{
567 struct compar {
568 static int cmp(void const* lhs, void const* rhs) {
569 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
570 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700571 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800572 }
573 };
574 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
575}
576
Mathias Agopian5d270722010-07-19 15:20:39 -0700577String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700578 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700579 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700580 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700581 if (sensor.getHandle() == handle) {
582 return sensor.getName();
583 }
584 }
585 String8 result("unknown");
586 return result;
587}
588
Aravind Akellab4099e72013-10-15 15:43:10 -0700589bool SensorService::isVirtualSensor(int handle) const {
590 SensorInterface* sensor = mSensorMap.valueFor(handle);
591 return sensor->isVirtual();
592}
593
Aravind Akella9a844cf2014-02-11 18:58:52 -0800594bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700595 int handle = event.sensor;
596 if (event.type == SENSOR_TYPE_META_DATA) {
597 handle = event.meta_data.sensor;
598 }
599 SensorInterface* sensor = mSensorMap.valueFor(handle);
600 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800601}
602
Aravind Akella6c2664a2014-08-13 12:24:50 -0700603
604SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
605 return mActiveSensors.valueFor(handle);
606}
607
Mathias Agopianfc328812010-07-14 23:41:37 -0700608Vector<Sensor> SensorService::getSensorList()
609{
Mathias Agopian33264862012-06-28 19:46:54 -0700610 char value[PROPERTY_VALUE_MAX];
611 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000612 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
613 mUserSensorListDebug : mUserSensorList;
614 Vector<Sensor> accessibleSensorList;
615 for (size_t i = 0; i < initialSensorList.size(); i++) {
616 Sensor sensor = initialSensorList[i];
617 if (canAccessSensor(sensor)) {
618 accessibleSensorList.add(sensor);
619 } else {
620 String8 infoMessage;
621 infoMessage.appendFormat(
622 "Skipped sensor %s because it requires permission %s",
623 sensor.getName().string(),
624 sensor.getRequiredPermission().string());
625 ALOGI(infoMessage.string());
626 }
Mathias Agopian33264862012-06-28 19:46:54 -0700627 }
Aravind Akella70018042014-04-07 22:52:37 +0000628 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700629}
630
631sp<ISensorEventConnection> SensorService::createSensorEventConnection()
632{
Mathias Agopian5307d172012-09-18 17:02:43 -0700633 uid_t uid = IPCThreadState::self()->getCallingUid();
634 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700635 return result;
636}
637
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800638void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700639{
640 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800641 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700642 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700643 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700644 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800645 int handle = mActiveSensors.keyAt(i);
646 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700647 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800648 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000649 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800650 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800651 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800652 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800653 }
654 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700655 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000656 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700657 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700658 c, i, handle);
659
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800660 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000661 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700662 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800663 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700664 delete rec;
665 size--;
666 } else {
667 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700668 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700669 }
Aravind Akella51059602014-09-23 16:42:49 -0700670 mLooper->removeFd(c->getSensorChannel()->getSendFd());
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700671 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700672 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800673 if (c->needsWakeLock()) {
674 checkWakeLockStateLocked();
675 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700676}
677
Aravind Akella70018042014-04-07 22:52:37 +0000678Sensor SensorService::getSensorFromHandle(int handle) const {
679 return mSensorMap.valueFor(handle)->getSensor();
680}
681
Mathias Agopianfc328812010-07-14 23:41:37 -0700682status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700683 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700684{
Mathias Agopian50df2952010-07-19 19:09:10 -0700685 if (mInitCheck != NO_ERROR)
686 return mInitCheck;
687
Mathias Agopianf001c922010-11-11 17:58:51 -0800688 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700689 if (sensor == NULL) {
690 return BAD_VALUE;
691 }
Aravind Akella70018042014-04-07 22:52:37 +0000692
693 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
694 return BAD_VALUE;
695 }
696
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700697 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700698 SensorRecord* rec = mActiveSensors.valueFor(handle);
699 if (rec == 0) {
700 rec = new SensorRecord(connection);
701 mActiveSensors.add(handle, rec);
702 if (sensor->isVirtual()) {
703 mActiveVirtualSensors.add(handle, sensor);
704 }
705 } else {
706 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800707 // this sensor is already activated, but we are adding a connection that uses it.
708 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700709 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700710 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800711 // NOTE: The wake_up flag of this event may get set to
712 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700713 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
714 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800715 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
716 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
717 mWakeLockAcquired = true;
718 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
719 WAKE_LOCK_NAME);
720 }
721 connection->sendEvents(&event, 1, NULL);
722 if (!connection->needsWakeLock() && mWakeLockAcquired) {
723 checkWakeLockStateLocked();
724 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700725 }
726 }
727 }
728 }
729
730 if (connection->addSensor(handle)) {
731 BatteryService::enableSensor(connection->getUid(), handle);
732 // the sensor was added (which means it wasn't already there)
733 // so, see if this connection becomes active
734 if (mActiveConnections.indexOf(connection) < 0) {
735 mActiveConnections.add(connection);
736 }
737 } else {
738 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
739 handle, connection.get());
740 }
741
Aravind Akella724d91d2013-06-27 12:04:23 -0700742 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
743 if (samplingPeriodNs < minDelayNs) {
744 samplingPeriodNs = minDelayNs;
745 }
746
Aravind Akella6c2664a2014-08-13 12:24:50 -0700747 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
748 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700749 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
750
751 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
752 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700753
Aravind Akella5466c3d2014-08-22 16:11:10 -0700754 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
755 // event before sending events on this connection. Ignore one-shot sensors which don't
756 // support flush(). Also if this sensor isn't already active, don't call flush().
757 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
758 rec->getNumConnections() > 1) {
759 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700760 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700761 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700762 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700763 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700764 } else {
765 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700766 }
767 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700768
769 if (err == NO_ERROR) {
770 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
771 err = sensor->activate(connection.get(), true);
772 }
773
Aravind Akella56ae4262014-07-10 16:01:10 -0700774 if (err == NO_ERROR && sensor->getSensor().isWakeUpSensor()) {
775 // Add the file descriptor to the Looper for receiving acknowledgments;
776 int ret = mLooper->addFd(connection->getSensorChannel()->getSendFd(), 0,
777 ALOOPER_EVENT_INPUT, connection.get(), NULL);
778 }
779
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700780 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700781 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700782 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700783 }
784 return err;
785}
786
787status_t SensorService::disable(const sp<SensorEventConnection>& connection,
788 int handle)
789{
Mathias Agopian50df2952010-07-19 19:09:10 -0700790 if (mInitCheck != NO_ERROR)
791 return mInitCheck;
792
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700793 Mutex::Autolock _l(mLock);
794 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700795 if (err == NO_ERROR) {
796 SensorInterface* sensor = mSensorMap.valueFor(handle);
797 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
798 }
799 return err;
800}
801
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700802status_t SensorService::cleanupWithoutDisable(
803 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700804 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700805 return cleanupWithoutDisableLocked(connection, handle);
806}
807
808status_t SensorService::cleanupWithoutDisableLocked(
809 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700810 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700811 if (rec) {
812 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700813 if (connection->removeSensor(handle)) {
814 BatteryService::disableSensor(connection->getUid(), handle);
815 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700816 if (connection->hasAnySensor() == false) {
Aravind Akella51059602014-09-23 16:42:49 -0700817 mLooper->removeFd(connection->getSensorChannel()->getSendFd());
Mathias Agopianfc328812010-07-14 23:41:37 -0700818 mActiveConnections.remove(connection);
819 }
820 // see if this sensor becomes inactive
821 if (rec->removeConnection(connection)) {
822 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800823 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700824 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700825 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700826 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700827 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700828 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700829}
830
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700831status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700832 int handle, nsecs_t ns)
833{
Mathias Agopian50df2952010-07-19 19:09:10 -0700834 if (mInitCheck != NO_ERROR)
835 return mInitCheck;
836
Mathias Agopianae09d652011-11-01 17:37:49 -0700837 SensorInterface* sensor = mSensorMap.valueFor(handle);
838 if (!sensor)
839 return BAD_VALUE;
840
Aravind Akella70018042014-04-07 22:52:37 +0000841 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
842 return BAD_VALUE;
843 }
844
Mathias Agopian1cd70002010-07-21 15:59:50 -0700845 if (ns < 0)
846 return BAD_VALUE;
847
Mathias Agopian62569ec2011-11-07 21:21:47 -0800848 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
849 if (ns < minDelayNs) {
850 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700851 }
852
Mathias Agopianf001c922010-11-11 17:58:51 -0800853 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700854}
855
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700856status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
Aravind Akella70018042014-04-07 22:52:37 +0000857 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700858 SensorDevice& dev(SensorDevice::getInstance());
859 const int halVersion = dev.getHalDeviceVersion();
860 status_t err(NO_ERROR);
861 Mutex::Autolock _l(mLock);
862 // Loop through all sensors for this connection and call flush on each of them.
863 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
864 const int handle = connection->mSensorInfo.keyAt(i);
865 SensorInterface* sensor = mSensorMap.valueFor(handle);
866 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
867 ALOGE("flush called on a one-shot sensor");
868 err = INVALID_OPERATION;
869 continue;
870 }
871 SensorEventConnection::FlushInfo& flushInfo = connection->mSensorInfo.editValueFor(handle);
Aravind Akella8493b792014-09-08 15:45:47 -0700872 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700873 // For older devices just increment pending flush count which will send a trivial
874 // flush complete event.
875 flushInfo.mPendingFlushEventsToSend++;
876 } else {
877 status_t err_flush = sensor->flush(connection.get(), handle);
878 if (err_flush == NO_ERROR) {
879 SensorRecord* rec = mActiveSensors.valueFor(handle);
880 if (rec != NULL) rec->addPendingFlushConnection(connection);
881 }
882 err = (err_flush != NO_ERROR) ? err_flush : err;
883 }
Aravind Akella70018042014-04-07 22:52:37 +0000884 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700885 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -0700886}
Aravind Akella70018042014-04-07 22:52:37 +0000887
Aravind Akella70018042014-04-07 22:52:37 +0000888bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700889 return (sensor.getRequiredPermission().isEmpty()) ||
890 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +0000891}
892
893bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
894 if (canAccessSensor(sensor)) {
895 return true;
896 } else {
897 String8 errorMessage;
898 errorMessage.appendFormat(
899 "%s a sensor (%s) without holding its required permission: %s",
900 operation,
901 sensor.getName().string(),
902 sensor.getRequiredPermission().string());
903 return false;
904 }
905}
906
Aravind Akella9a844cf2014-02-11 18:58:52 -0800907void SensorService::checkWakeLockState() {
908 Mutex::Autolock _l(mLock);
909 checkWakeLockStateLocked();
910}
911
912void SensorService::checkWakeLockStateLocked() {
913 if (!mWakeLockAcquired) {
914 return;
915 }
916 bool releaseLock = true;
917 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
918 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
919 if (connection != 0) {
920 if (connection->needsWakeLock()) {
921 releaseLock = false;
922 break;
923 }
924 }
925 }
926 if (releaseLock) {
927 ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
928 release_wake_lock(WAKE_LOCK_NAME);
929 mWakeLockAcquired = false;
930 }
931}
Aravind Akella6c2664a2014-08-13 12:24:50 -0700932
Mathias Agopianfc328812010-07-14 23:41:37 -0700933// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -0700934SensorService::SensorRecord::SensorRecord(
935 const sp<SensorEventConnection>& connection)
936{
937 mConnections.add(connection);
938}
939
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700940bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700941 const sp<SensorEventConnection>& connection)
942{
943 if (mConnections.indexOf(connection) < 0) {
944 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700945 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700946 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700947 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700948}
949
950bool SensorService::SensorRecord::removeConnection(
951 const wp<SensorEventConnection>& connection)
952{
953 ssize_t index = mConnections.indexOf(connection);
954 if (index >= 0) {
955 mConnections.removeItemsAt(index, 1);
956 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700957 // Remove this connections from the queue of flush() calls made on this sensor.
958 for (Vector< wp<SensorEventConnection> >::iterator it =
959 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
960 if (it->unsafe_get() == connection.unsafe_get()) {
961 it = mPendingFlushConnections.erase(it);
962 } else {
963 ++it;
964 }
965 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700966 return mConnections.size() ? false : true;
967}
968
Aravind Akella6c2664a2014-08-13 12:24:50 -0700969void SensorService::SensorRecord::addPendingFlushConnection(
970 const sp<SensorEventConnection>& connection) {
971 mPendingFlushConnections.add(connection);
972}
973
974void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
975 if (mPendingFlushConnections.size() > 0) {
976 mPendingFlushConnections.removeAt(0);
977 }
978}
979
980SensorService::SensorEventConnection *
981SensorService::SensorRecord::getFirstPendingFlushConnection() {
982 if (mPendingFlushConnections.size() > 0) {
983 return mPendingFlushConnections[0].unsafe_get();
984 }
985 return NULL;
986}
987
Mathias Agopianfc328812010-07-14 23:41:37 -0700988// ---------------------------------------------------------------------------
989
990SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -0700991 const sp<SensorService>& service, uid_t uid)
Aravind Akella56ae4262014-07-10 16:01:10 -0700992 : mService(service), mUid(uid), mWakeLockRefCount(0), mEventCache(NULL), mCacheSize(0),
993 mMaxCacheSize(0) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700994 const SensorDevice& device(SensorDevice::getInstance());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700995 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -0700996#if DEBUG_CONNECTIONS
997 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -0700998 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700999#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001000}
1001
Aravind Akella56ae4262014-07-10 16:01:10 -07001002SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001003 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001004 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001005 if (mEventCache != NULL) {
1006 delete mEventCache;
1007 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001008}
1009
Aravind Akella56ae4262014-07-10 16:01:10 -07001010void SensorService::SensorEventConnection::onFirstRef() {
1011 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001012}
1013
Aravind Akella9a844cf2014-02-11 18:58:52 -08001014bool SensorService::SensorEventConnection::needsWakeLock() {
1015 Mutex::Autolock _l(mConnectionLock);
1016 return mWakeLockRefCount > 0;
1017}
1018
Aravind Akella4c8b9512013-09-05 17:03:38 -07001019void SensorService::SensorEventConnection::dump(String8& result) {
1020 Mutex::Autolock _l(mConnectionLock);
Aravind Akella0ec20662014-09-14 17:29:48 -07001021 result.appendFormat("\t WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1022 mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001023 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1024 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001025 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001026 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001027 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001028 flushInfo.mFirstFlushPending ? "First flush pending" :
1029 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001030 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001031 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001032#if DEBUG_CONNECTIONS
1033 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1034 " total_acks_needed %d | total_acks_recvd %d\n",
1035 mEventsReceived,
1036 mEventsSent,
1037 mEventsSentFromCache,
1038 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1039 mTotalAcksNeeded,
1040 mTotalAcksReceived);
1041#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001042}
1043
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001044bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001045 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +00001046 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1047 return false;
1048 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001049 if (mSensorInfo.indexOfKey(handle) < 0) {
1050 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001051 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001052 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001053 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001054}
1055
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001056bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001057 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001058 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001059 return true;
1060 }
1061 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001062}
1063
1064bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001065 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001066 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001067}
1068
1069bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001070 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001071 return mSensorInfo.size() ? true : false;
1072}
1073
Aravind Akella8493b792014-09-08 15:45:47 -07001074bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1075 Mutex::Autolock _l(mConnectionLock);
1076 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1077 const int handle = mSensorInfo.keyAt(i);
1078 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1079 return true;
1080 }
1081 }
1082 return false;
1083}
1084
Aravind Akella4c8b9512013-09-05 17:03:38 -07001085void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1086 bool value) {
1087 Mutex::Autolock _l(mConnectionLock);
1088 ssize_t index = mSensorInfo.indexOfKey(handle);
1089 if (index >= 0) {
1090 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1091 flushInfo.mFirstFlushPending = value;
1092 }
1093}
1094
Mathias Agopianfc328812010-07-14 23:41:37 -07001095status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001096 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001097 sensors_event_t* scratch,
1098 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001099 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001100 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001101 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001102 if (scratch) {
1103 size_t i=0;
1104 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001105 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001106 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1107 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001108 buffer[i].meta_data.sensor);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001109 // Setting sensor_handle to the correct sensor to ensure the sensor events per connection are
Aravind Akella724d91d2013-06-27 12:04:23 -07001110 // filtered correctly. buffer[i].sensor is zero for meta_data events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001111 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001112 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001113 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001114 // Check if this connection has registered for this sensor. If not continue to the
1115 // next sensor_event.
1116 if (index < 0) {
1117 ++i;
1118 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001119 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001120
Aravind Akella56ae4262014-07-10 16:01:10 -07001121 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001122 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001123 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1124 this == mapFlushEventsToConnections[i]) {
1125 flushInfo.mFirstFlushPending = false;
1126 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1127 buffer[i].meta_data.sensor);
1128 ++i;
1129 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001130 }
1131
1132 // If there is a pending flush complete event for this sensor on this connection,
1133 // ignore the event and proceed to the next.
1134 if (flushInfo.mFirstFlushPending) {
1135 ++i;
1136 continue;
1137 }
1138
1139 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001140 // Keep copying events into the scratch buffer as long as they are regular
1141 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1142 // from the same sensor_handle AND the current connection is mapped to the
1143 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001144 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001145 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001146 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001147 }
1148 ++i;
1149 } else {
1150 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001151 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001152 }
Aravind Akella8493b792014-09-08 15:45:47 -07001153 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1154 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001155 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001156 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001157 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001158 } else {
1159 scratch = const_cast<sensors_event_t *>(buffer);
1160 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001161 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001162
Aravind Akella6c2664a2014-08-13 12:24:50 -07001163 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001164 // Early return if there are no events for this connection.
1165 if (count == 0) {
1166 return status_t(NO_ERROR);
1167 }
1168
1169#if DEBUG_CONNECTIONS
1170 mEventsReceived += count;
1171#endif
1172 if (mCacheSize != 0) {
1173 // There are some events in the cache which need to be sent first. Copy this buffer to
1174 // the end of cache.
1175 if (mCacheSize + count <= mMaxCacheSize) {
1176 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1177 mCacheSize += count;
1178 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001179 // Check if any new sensors have registered on this connection which may have increased
1180 // the max cache size that is desired.
1181 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1182 reAllocateCacheLocked(scratch, count);
1183 return status_t(NO_ERROR);
1184 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001185 // Some events need to be dropped.
1186 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1187 if (remaningCacheSize != 0) {
1188 memcpy(&mEventCache[mCacheSize], scratch,
1189 remaningCacheSize * sizeof(sensors_event_t));
1190 }
1191 int numEventsDropped = count - remaningCacheSize;
1192 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1193 // Drop the first "numEventsDropped" in the cache.
1194 memmove(mEventCache, &mEventCache[numEventsDropped],
1195 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1196
1197 // Copy the remainingEvents in scratch buffer to the end of cache.
1198 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1199 numEventsDropped * sizeof(sensors_event_t));
1200 }
1201 return status_t(NO_ERROR);
1202 }
1203
Aravind Akella6c2664a2014-08-13 12:24:50 -07001204 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1205 if (index_wake_up_event >= 0) {
1206 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1207 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001208#if DEBUG_CONNECTIONS
1209 ++mTotalAcksNeeded;
1210#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001211 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001212
1213 // NOTE: ASensorEvent and sensors_event_t are the same type.
1214 ssize_t size = SensorEventQueue::write(mChannel,
1215 reinterpret_cast<ASensorEvent const*>(scratch), count);
1216 if (size < 0) {
1217 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001218 if (index_wake_up_event >= 0) {
1219 // If there was a wake_up sensor_event, reset the flag.
1220 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001221 if (mWakeLockRefCount > 0) {
1222 --mWakeLockRefCount;
1223 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001224#if DEBUG_CONNECTIONS
1225 --mTotalAcksNeeded;
1226#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001227 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001228 if (mEventCache == NULL) {
1229 mMaxCacheSize = computeMaxCacheSizeLocked();
1230 mEventCache = new sensors_event_t[mMaxCacheSize];
1231 mCacheSize = 0;
1232 }
1233 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1234 mCacheSize += count;
1235
1236 // Add this file descriptor to the looper to get a callback when this fd is available for
1237 // writing.
1238 mService->getLooper()->addFd(mChannel->getSendFd(), 0,
1239 ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_INPUT, this, NULL);
1240 return size;
1241 }
1242
1243#if DEBUG_CONNECTIONS
1244 if (size > 0) {
1245 mEventsSent += count;
1246 }
1247#endif
1248
1249 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1250}
1251
Aravind Akella6c2664a2014-08-13 12:24:50 -07001252void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1253 int count) {
1254 sensors_event_t *eventCache_new;
1255 const int new_cache_size = computeMaxCacheSizeLocked();
1256 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1257 eventCache_new = new sensors_event_t[new_cache_size];
1258 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1259 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1260
1261 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1262 new_cache_size);
1263
1264 delete mEventCache;
1265 mEventCache = eventCache_new;
1266 mCacheSize += count;
1267 mMaxCacheSize = new_cache_size;
1268}
1269
1270void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1271 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001272 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001273 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001274 // Loop through all the sensors for this connection and check if there are any pending
1275 // flush complete events to be sent.
1276 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1277 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1278 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001279 const int sensor_handle = mSensorInfo.keyAt(i);
1280 flushCompleteEvent.meta_data.sensor = sensor_handle;
1281 if (mService->getSensorFromHandle(sensor_handle).isWakeUpSensor()) {
1282 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1283 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001284 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1285 if (size < 0) {
1286 return;
1287 }
1288 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1289 flushCompleteEvent.meta_data.sensor);
1290 flushInfo.mPendingFlushEventsToSend--;
1291 }
1292 }
1293}
1294
Aravind Akella56ae4262014-07-10 16:01:10 -07001295void SensorService::SensorEventConnection::writeToSocketFromCacheLocked() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001296 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1297 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1298 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1299 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
1300 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001301 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001302 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001303 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001304 int index_wake_up_event =
1305 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1306 if (index_wake_up_event >= 0) {
1307 mEventCache[index_wake_up_event + numEventsSent].flags |=
1308 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1309 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001310#if DEBUG_CONNECTIONS
1311 ++mTotalAcksNeeded;
1312#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001313 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001314
Aravind Akella56ae4262014-07-10 16:01:10 -07001315 ssize_t size = SensorEventQueue::write(mChannel,
1316 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001317 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001318 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001319 if (index_wake_up_event >= 0) {
1320 // If there was a wake_up sensor_event, reset the flag.
1321 mEventCache[index_wake_up_event + numEventsSent].flags &=
1322 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001323 if (mWakeLockRefCount > 0) {
1324 --mWakeLockRefCount;
1325 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001326#if DEBUG_CONNECTIONS
1327 --mTotalAcksNeeded;
1328#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001329 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001330 memmove(mEventCache, &mEventCache[numEventsSent],
1331 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1332 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001333 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001334 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001335 return;
1336 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001337 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001338#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001339 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001340#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001341 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001342 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1343 // All events from the cache have been sent. Reset cache size to zero.
1344 mCacheSize = 0;
1345 // Poll only for ALOOPER_EVENT_INPUT(read) on the file descriptor.
1346 mService->getLooper()->addFd(mChannel->getSendFd(), 0, ALOOPER_EVENT_INPUT, this, NULL);
Mathias Agopianfc328812010-07-14 23:41:37 -07001347}
1348
Aravind Akellac551eac2013-10-14 17:04:42 -07001349void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001350 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001351 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001352 // Count flushComplete events in the events that are about to the dropped. These will be sent
1353 // separately before the next batch of events.
1354 for (int j = 0; j < numEventsDropped; ++j) {
1355 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1356 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1357 flushInfo.mPendingFlushEventsToSend++;
1358 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1359 flushInfo.mPendingFlushEventsToSend);
1360 }
1361 }
1362 return;
1363}
1364
Aravind Akella6c2664a2014-08-13 12:24:50 -07001365int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1366 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001367 for (int i = 0; i < count; ++i) {
1368 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001369 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001370 }
1371 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001372 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001373}
1374
Mathias Agopianb3989272011-10-20 18:42:02 -07001375sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001376{
1377 return mChannel;
1378}
1379
1380status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001381 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1382 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001383{
1384 status_t err;
1385 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001386 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1387 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001388
Mathias Agopianfc328812010-07-14 23:41:37 -07001389 } else {
1390 err = mService->disable(this, handle);
1391 }
1392 return err;
1393}
1394
1395status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001396 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001397{
Aravind Akella724d91d2013-06-27 12:04:23 -07001398 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001399}
1400
Aravind Akella701166d2013-10-08 14:59:26 -07001401status_t SensorService::SensorEventConnection::flush() {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001402 return mService->flushSensor(this);
Aravind Akella724d91d2013-06-27 12:04:23 -07001403}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001404
Aravind Akella56ae4262014-07-10 16:01:10 -07001405int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* data) {
1406 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1407 return 0;
1408 }
1409
1410 if (events & ALOOPER_EVENT_INPUT) {
1411 char buf;
1412 ssize_t ret = ::recv(fd, &buf, sizeof(buf), MSG_DONTWAIT);
1413
1414 {
1415 Mutex::Autolock _l(mConnectionLock);
Aravind Akella0ec20662014-09-14 17:29:48 -07001416 if (mWakeLockRefCount > 0) {
1417 --mWakeLockRefCount;
1418 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001419#if DEBUG_CONNECTIONS
1420 ++mTotalAcksReceived;
1421#endif
Aravind Akella56ae4262014-07-10 16:01:10 -07001422 }
1423 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1424 // here as checkWakeLockState() will need it.
1425 if (mWakeLockRefCount == 0) {
1426 mService->checkWakeLockState();
1427 }
1428 // continue getting callbacks.
1429 return 1;
1430 }
1431
1432 if (events & ALOOPER_EVENT_OUTPUT) {
1433 // send sensor data that is stored in mEventCache.
Aravind Akella9a844cf2014-02-11 18:58:52 -08001434 Mutex::Autolock _l(mConnectionLock);
Aravind Akella56ae4262014-07-10 16:01:10 -07001435 writeToSocketFromCacheLocked();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001436 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001437 return 1;
1438}
1439
1440int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1441 int fifoWakeUpSensors = 0;
1442 int fifoNonWakeUpSensors = 0;
1443 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1444 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1445 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1446 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1447 // non wake_up sensors.
1448 if (sensor.isWakeUpSensor()) {
1449 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1450 } else {
1451 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1452 }
1453 } else {
1454 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1455 if (sensor.isWakeUpSensor()) {
1456 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1457 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1458
1459 } else {
1460 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1461 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1462
1463 }
1464 }
1465 }
1466 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1467 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001468 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001469 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001470 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001471 }
1472 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001473}
1474
Mathias Agopianfc328812010-07-14 23:41:37 -07001475// ---------------------------------------------------------------------------
1476}; // namespace android
1477