blob: 6c3144b80322bc875645d810a7ca3faaba288458 [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);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700189 mInitCheck = NO_ERROR;
190 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700191 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700192}
193
Mathias Agopian03193062013-05-10 19:32:39 -0700194Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800195{
196 sensors_event_t event;
197 memset(&event, 0, sizeof(event));
198
199 const Sensor sensor(s->getSensor());
200 // add to the sensor list (returned to clients)
201 mSensorList.add(sensor);
202 // add to our handle->SensorInterface mapping
203 mSensorMap.add(sensor.getHandle(), s);
204 // create an entry in the mLastEventSeen array
205 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700206
207 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800208}
209
Mathias Agopian03193062013-05-10 19:32:39 -0700210Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800211{
Mathias Agopian03193062013-05-10 19:32:39 -0700212 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800213 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700214 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800215}
216
Mathias Agopianfc328812010-07-14 23:41:37 -0700217SensorService::~SensorService()
218{
Mathias Agopianf001c922010-11-11 17:58:51 -0800219 for (size_t i=0 ; i<mSensorMap.size() ; i++)
220 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700221}
222
Mathias Agopian1cb13462011-06-27 16:05:52 -0700223static const String16 sDump("android.permission.DUMP");
224
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700225status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700226{
Mathias Agopianfc328812010-07-14 23:41:37 -0700227 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700228 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700229 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000230 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700231 IPCThreadState::self()->getCallingPid(),
232 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700233 } else {
234 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700235 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700236 for (size_t i=0 ; i<mSensorList.size() ; i++) {
237 const Sensor& s(mSensorList[i]);
238 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700239 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700240 "%-15s| %-10s| %-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700241 s.getName().string(),
242 s.getVendor().string(),
Aravind Akella70018042014-04-07 22:52:37 +0000243 s.getStringType().string(),
244 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700245 s.getRequiredPermission().string(),
246 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700247
Aravind Akella0e025c52014-06-03 19:19:57 -0700248 const int reportingMode = s.getReportingMode();
249 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700250 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700251 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700252 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700253 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700254 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700255 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700256 result.append(" special-trigger | ");
257 }
258
259 if (s.getMaxDelay() > 0) {
260 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
261 } else {
262 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700263 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700264
265 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700266 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700267 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700268 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700269 }
270
Aravind Akella724d91d2013-06-27 12:04:23 -0700271 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000272 result.appendFormat("FifoMax=%d events | ",
273 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700274 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700275 result.append("no batching | ");
276 }
277
278 if (s.isWakeUpSensor()) {
279 result.appendFormat("wakeUp | ");
280 } else {
281 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700282 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700283
284 switch (s.getType()) {
285 case SENSOR_TYPE_ROTATION_VECTOR:
286 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
287 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700288 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
289 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700290 break;
291 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
292 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
293 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700294 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
295 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
296 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700297 break;
298 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
299 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700300 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
301 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700302 break;
303 case SENSOR_TYPE_SIGNIFICANT_MOTION:
304 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700305 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700306 break;
307 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700308 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
309 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700310 break;
311 default:
312 // default to 3 values
313 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700314 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
315 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700316 break;
317 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700318 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700319 }
320 SensorFusion::getInstance().dump(result);
321 SensorDevice::getInstance().dump(result);
322
Mathias Agopianba02cd22013-07-03 16:20:57 -0700323 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700324 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700325 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700326 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700327 getSensorName(handle).string(),
328 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700329 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700330 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700331
Aravind Akella5466c3d2014-08-22 16:11:10 -0700332 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700333 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800334 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700335 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700336
337 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
338 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
339 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700340 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700341 connection->dump(result);
342 }
343 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700344 }
345 write(fd, result.string(), result.size());
346 return NO_ERROR;
347}
348
Aravind Akella9a844cf2014-02-11 18:58:52 -0800349void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700350 sensors_event_t const* buffer, const int count) {
351 for (int i=0 ; i<count ; i++) {
352 int handle = buffer[i].sensor;
Aravind Akella0e025c52014-06-03 19:19:57 -0700353 if (connection->hasSensor(handle)) {
354 SensorInterface* sensor = mSensorMap.valueFor(handle);
355 // If this buffer has an event from a one_shot sensor and this connection is registered
356 // for this particular one_shot sensor, try cleaning up the connection.
357 if (sensor != NULL &&
358 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
359 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800360 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700361 }
362 }
363 }
364}
365
Mathias Agopianfc328812010-07-14 23:41:37 -0700366bool SensorService::threadLoop()
367{
Steve Blocka5512372011-12-20 16:23:08 +0000368 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700369
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700370 // each virtual sensor could generate an event per "real" event, that's why we need
371 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
372 // in practice, this is too aggressive, but guaranteed to be enough.
373 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
374 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
375
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700376 sensors_event_t buffer[minBufferSize];
377 sensors_event_t scratch[minBufferSize];
Mathias Agopianf001c922010-11-11 17:58:51 -0800378 SensorDevice& device(SensorDevice::getInstance());
379 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700380
Aravind Akella56ae4262014-07-10 16:01:10 -0700381 SensorEventAckReceiver sender(this);
382 sender.run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopianf001c922010-11-11 17:58:51 -0800383 ssize_t count;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700384 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700385 do {
Mathias Agopianf001c922010-11-11 17:58:51 -0800386 count = device.poll(buffer, numEventMax);
Mathias Agopianfc328812010-07-14 23:41:37 -0700387 if (count<0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000388 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700389 break;
390 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700391
392 // Reset sensors_event_t.flags to zero for all events in the buffer.
393 for (int i = 0; i < count; i++) {
394 buffer[i].flags = 0;
395 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800396 Mutex::Autolock _l(mLock);
397 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
398 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
399 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
400 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
401 // releasing the wakelock.
402 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700403 for (int i = 0; i < count; i++) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800404 if (isWakeUpSensorEvent(buffer[i])) {
405 bufferHasWakeUpEvent = true;
406 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700407 }
408 }
409
Aravind Akella9a844cf2014-02-11 18:58:52 -0800410 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
411 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
412 mWakeLockAcquired = true;
413 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
414 }
415 recordLastValueLocked(buffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800416
Mathias Agopianf001c922010-11-11 17:58:51 -0800417 // handle virtual sensors
418 if (count && vcount) {
Mathias Agopian984826c2011-05-17 22:54:42 -0700419 sensors_event_t const * const event = buffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800420 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800421 if (activeVirtualSensorCount) {
422 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700423 SensorFusion& fusion(SensorFusion::getInstance());
424 if (fusion.isEnabled()) {
425 for (size_t i=0 ; i<size_t(count) ; i++) {
426 fusion.process(event[i]);
427 }
428 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700429 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800430 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700431 if (count + k >= minBufferSize) {
432 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700433 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700434 count, k, minBufferSize);
435 break;
436 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800437 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800438 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700439 if (si->process(&out, event[i])) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800440 buffer[count + k] = out;
441 k++;
442 }
443 }
444 }
445 if (k) {
446 // record the last synthesized values
Aravind Akella9a844cf2014-02-11 18:58:52 -0800447 recordLastValueLocked(&buffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800448 count += k;
449 // sort the buffer by time-stamps
450 sortEventBuffer(buffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700451 }
452 }
453 }
454
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700455 // handle backward compatibility for RotationVector sensor
456 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
457 for (int i = 0; i < count; i++) {
Mathias Agopian7438fd12013-07-08 12:50:39 -0700458 if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700459 // All the 4 components of the quaternion should be available
460 // No heading accuracy. Set it to -1
461 buffer[i].data[4] = -1;
462 }
463 }
464 }
465
Aravind Akella9a844cf2014-02-11 18:58:52 -0800466 // Send our events to clients. Check the state of wake lock for each client and release the
467 // lock if none of the clients need it.
468 bool needsWakeLock = false;
469 for (size_t i=0 ; i < mActiveConnections.size(); i++) {
470 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Mathias Agopianf001c922010-11-11 17:58:51 -0800471 if (connection != 0) {
472 connection->sendEvents(buffer, count, scratch);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800473 needsWakeLock |= connection->needsWakeLock();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700474 // Some sensors need to be auto disabled after the trigger
Aravind Akella9a844cf2014-02-11 18:58:52 -0800475 cleanupAutoDisabledSensorLocked(connection, buffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800476 }
477 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700478
Aravind Akella9a844cf2014-02-11 18:58:52 -0800479 if (mWakeLockAcquired && !needsWakeLock) {
480 release_wake_lock(WAKE_LOCK_NAME);
481 mWakeLockAcquired = false;
482 ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
483 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700484 } while (count >= 0 || Thread::exitPending());
485
Steve Block3c20fbe2012-01-05 23:22:43 +0000486 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800487 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700488 return false;
489}
490
Aravind Akella56ae4262014-07-10 16:01:10 -0700491sp<Looper> SensorService::getLooper() const {
492 return mLooper;
493}
494
495bool SensorService::SensorEventAckReceiver::threadLoop() {
496 ALOGD("new thread SensorEventAckReceiver");
497 do {
498 sp<Looper> looper = mService->getLooper();
499 looper->pollOnce(-1);
500 } while(!Thread::exitPending());
501 return false;
502}
503
Aravind Akella9a844cf2014-02-11 18:58:52 -0800504void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800505 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800506 const sensors_event_t* last = NULL;
507 for (size_t i = 0; i < count; i++) {
508 const sensors_event_t* event = &buffer[i];
509 if (event->type != SENSOR_TYPE_META_DATA) {
510 if (last && event->sensor != last->sensor) {
511 mLastEventSeen.editValueFor(last->sensor) = *last;
512 }
513 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800514 }
515 }
Aravind Akella4b847042014-03-03 19:02:46 -0800516 if (last) {
517 mLastEventSeen.editValueFor(last->sensor) = *last;
518 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800519}
520
Mathias Agopianf001c922010-11-11 17:58:51 -0800521void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
522{
523 struct compar {
524 static int cmp(void const* lhs, void const* rhs) {
525 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
526 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700527 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800528 }
529 };
530 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
531}
532
Mathias Agopian5d270722010-07-19 15:20:39 -0700533String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700534 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700535 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700536 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700537 if (sensor.getHandle() == handle) {
538 return sensor.getName();
539 }
540 }
541 String8 result("unknown");
542 return result;
543}
544
Aravind Akellab4099e72013-10-15 15:43:10 -0700545bool SensorService::isVirtualSensor(int handle) const {
546 SensorInterface* sensor = mSensorMap.valueFor(handle);
547 return sensor->isVirtual();
548}
549
Aravind Akella9a844cf2014-02-11 18:58:52 -0800550bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700551 int handle = event.sensor;
552 if (event.type == SENSOR_TYPE_META_DATA) {
553 handle = event.meta_data.sensor;
554 }
555 SensorInterface* sensor = mSensorMap.valueFor(handle);
556 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800557}
558
Aravind Akella6c2664a2014-08-13 12:24:50 -0700559
560SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
561 return mActiveSensors.valueFor(handle);
562}
563
Mathias Agopianfc328812010-07-14 23:41:37 -0700564Vector<Sensor> SensorService::getSensorList()
565{
Mathias Agopian33264862012-06-28 19:46:54 -0700566 char value[PROPERTY_VALUE_MAX];
567 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000568 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
569 mUserSensorListDebug : mUserSensorList;
570 Vector<Sensor> accessibleSensorList;
571 for (size_t i = 0; i < initialSensorList.size(); i++) {
572 Sensor sensor = initialSensorList[i];
573 if (canAccessSensor(sensor)) {
574 accessibleSensorList.add(sensor);
575 } else {
576 String8 infoMessage;
577 infoMessage.appendFormat(
578 "Skipped sensor %s because it requires permission %s",
579 sensor.getName().string(),
580 sensor.getRequiredPermission().string());
581 ALOGI(infoMessage.string());
582 }
Mathias Agopian33264862012-06-28 19:46:54 -0700583 }
Aravind Akella70018042014-04-07 22:52:37 +0000584 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700585}
586
587sp<ISensorEventConnection> SensorService::createSensorEventConnection()
588{
Mathias Agopian5307d172012-09-18 17:02:43 -0700589 uid_t uid = IPCThreadState::self()->getCallingUid();
590 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700591 return result;
592}
593
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800594void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700595{
596 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800597 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700598 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700599 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700600 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800601 int handle = mActiveSensors.keyAt(i);
602 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700603 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800604 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000605 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800606 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800607 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800608 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800609 }
610 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700611 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000612 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700613 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700614 c, i, handle);
615
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800616 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000617 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700618 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800619 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700620 delete rec;
621 size--;
622 } else {
623 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700624 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700625 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700626 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700627 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800628 if (c->needsWakeLock()) {
629 checkWakeLockStateLocked();
630 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700631}
632
Aravind Akella70018042014-04-07 22:52:37 +0000633Sensor SensorService::getSensorFromHandle(int handle) const {
634 return mSensorMap.valueFor(handle)->getSensor();
635}
636
Mathias Agopianfc328812010-07-14 23:41:37 -0700637status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700638 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700639{
Mathias Agopian50df2952010-07-19 19:09:10 -0700640 if (mInitCheck != NO_ERROR)
641 return mInitCheck;
642
Mathias Agopianf001c922010-11-11 17:58:51 -0800643 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700644 if (sensor == NULL) {
645 return BAD_VALUE;
646 }
Aravind Akella70018042014-04-07 22:52:37 +0000647
648 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
649 return BAD_VALUE;
650 }
651
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700652 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700653 SensorRecord* rec = mActiveSensors.valueFor(handle);
654 if (rec == 0) {
655 rec = new SensorRecord(connection);
656 mActiveSensors.add(handle, rec);
657 if (sensor->isVirtual()) {
658 mActiveVirtualSensors.add(handle, sensor);
659 }
660 } else {
661 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800662 // this sensor is already activated, but we are adding a connection that uses it.
663 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700664 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700665 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800666 // NOTE: The wake_up flag of this event may get set to
667 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700668 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
669 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800670 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
671 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
672 mWakeLockAcquired = true;
673 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
674 WAKE_LOCK_NAME);
675 }
676 connection->sendEvents(&event, 1, NULL);
677 if (!connection->needsWakeLock() && mWakeLockAcquired) {
678 checkWakeLockStateLocked();
679 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700680 }
681 }
682 }
683 }
684
685 if (connection->addSensor(handle)) {
686 BatteryService::enableSensor(connection->getUid(), handle);
687 // the sensor was added (which means it wasn't already there)
688 // so, see if this connection becomes active
689 if (mActiveConnections.indexOf(connection) < 0) {
690 mActiveConnections.add(connection);
691 }
692 } else {
693 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
694 handle, connection.get());
695 }
696
Aravind Akella724d91d2013-06-27 12:04:23 -0700697 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
698 if (samplingPeriodNs < minDelayNs) {
699 samplingPeriodNs = minDelayNs;
700 }
701
Aravind Akella6c2664a2014-08-13 12:24:50 -0700702 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
703 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700704 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
705
706 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
707 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700708
Aravind Akella5466c3d2014-08-22 16:11:10 -0700709 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
710 // event before sending events on this connection. Ignore one-shot sensors which don't
711 // support flush(). Also if this sensor isn't already active, don't call flush().
712 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
713 rec->getNumConnections() > 1) {
714 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700715 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700716 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700717 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700718 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700719 } else {
720 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700721 }
722 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700723
724 if (err == NO_ERROR) {
725 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
726 err = sensor->activate(connection.get(), true);
727 }
728
Aravind Akella56ae4262014-07-10 16:01:10 -0700729 if (err == NO_ERROR && sensor->getSensor().isWakeUpSensor()) {
730 // Add the file descriptor to the Looper for receiving acknowledgments;
731 int ret = mLooper->addFd(connection->getSensorChannel()->getSendFd(), 0,
732 ALOOPER_EVENT_INPUT, connection.get(), NULL);
733 }
734
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700735 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700736 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700737 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700738 }
739 return err;
740}
741
742status_t SensorService::disable(const sp<SensorEventConnection>& connection,
743 int handle)
744{
Mathias Agopian50df2952010-07-19 19:09:10 -0700745 if (mInitCheck != NO_ERROR)
746 return mInitCheck;
747
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700748 Mutex::Autolock _l(mLock);
749 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700750 if (err == NO_ERROR) {
751 SensorInterface* sensor = mSensorMap.valueFor(handle);
752 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
753 }
754 return err;
755}
756
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700757status_t SensorService::cleanupWithoutDisable(
758 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700759 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700760 return cleanupWithoutDisableLocked(connection, handle);
761}
762
763status_t SensorService::cleanupWithoutDisableLocked(
764 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700765 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700766 if (rec) {
767 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700768 if (connection->removeSensor(handle)) {
769 BatteryService::disableSensor(connection->getUid(), handle);
770 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700771 if (connection->hasAnySensor() == false) {
772 mActiveConnections.remove(connection);
773 }
774 // see if this sensor becomes inactive
775 if (rec->removeConnection(connection)) {
776 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800777 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700778 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700779 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700780 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700781 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700782 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700783}
784
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700785status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700786 int handle, nsecs_t ns)
787{
Mathias Agopian50df2952010-07-19 19:09:10 -0700788 if (mInitCheck != NO_ERROR)
789 return mInitCheck;
790
Mathias Agopianae09d652011-11-01 17:37:49 -0700791 SensorInterface* sensor = mSensorMap.valueFor(handle);
792 if (!sensor)
793 return BAD_VALUE;
794
Aravind Akella70018042014-04-07 22:52:37 +0000795 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
796 return BAD_VALUE;
797 }
798
Mathias Agopian1cd70002010-07-21 15:59:50 -0700799 if (ns < 0)
800 return BAD_VALUE;
801
Mathias Agopian62569ec2011-11-07 21:21:47 -0800802 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
803 if (ns < minDelayNs) {
804 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700805 }
806
Mathias Agopianf001c922010-11-11 17:58:51 -0800807 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700808}
809
Aravind Akella724d91d2013-06-27 12:04:23 -0700810status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
811 int handle) {
Aravind Akella70018042014-04-07 22:52:37 +0000812 if (mInitCheck != NO_ERROR) return mInitCheck;
813 SensorInterface* sensor = mSensorMap.valueFor(handle);
814 if (sensor == NULL) {
815 return BAD_VALUE;
816 }
817
818 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried flushing")) {
819 return BAD_VALUE;
820 }
821
Aravind Akella0e025c52014-06-03 19:19:57 -0700822 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
823 ALOGE("flush called on a one-shot sensor");
Aravind Akella70018042014-04-07 22:52:37 +0000824 return INVALID_OPERATION;
825 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700826
827 status_t ret = sensor->flush(connection.get(), handle);
828 if (ret == NO_ERROR) {
829 SensorRecord* rec = mActiveSensors.valueFor(handle);
830 if (rec != NULL) rec->addPendingFlushConnection(connection);
831 }
832 return ret;
Aravind Akella724d91d2013-06-27 12:04:23 -0700833}
Aravind Akella70018042014-04-07 22:52:37 +0000834
Aravind Akella70018042014-04-07 22:52:37 +0000835bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700836 return (sensor.getRequiredPermission().isEmpty()) ||
837 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +0000838}
839
840bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
841 if (canAccessSensor(sensor)) {
842 return true;
843 } else {
844 String8 errorMessage;
845 errorMessage.appendFormat(
846 "%s a sensor (%s) without holding its required permission: %s",
847 operation,
848 sensor.getName().string(),
849 sensor.getRequiredPermission().string());
850 return false;
851 }
852}
853
Aravind Akella9a844cf2014-02-11 18:58:52 -0800854void SensorService::checkWakeLockState() {
855 Mutex::Autolock _l(mLock);
856 checkWakeLockStateLocked();
857}
858
859void SensorService::checkWakeLockStateLocked() {
860 if (!mWakeLockAcquired) {
861 return;
862 }
863 bool releaseLock = true;
864 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
865 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
866 if (connection != 0) {
867 if (connection->needsWakeLock()) {
868 releaseLock = false;
869 break;
870 }
871 }
872 }
873 if (releaseLock) {
874 ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
875 release_wake_lock(WAKE_LOCK_NAME);
876 mWakeLockAcquired = false;
877 }
878}
Aravind Akella6c2664a2014-08-13 12:24:50 -0700879
Mathias Agopianfc328812010-07-14 23:41:37 -0700880// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -0700881SensorService::SensorRecord::SensorRecord(
882 const sp<SensorEventConnection>& connection)
883{
884 mConnections.add(connection);
885}
886
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700887bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700888 const sp<SensorEventConnection>& connection)
889{
890 if (mConnections.indexOf(connection) < 0) {
891 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700892 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700893 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700894 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700895}
896
897bool SensorService::SensorRecord::removeConnection(
898 const wp<SensorEventConnection>& connection)
899{
900 ssize_t index = mConnections.indexOf(connection);
901 if (index >= 0) {
902 mConnections.removeItemsAt(index, 1);
903 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700904 // Remove this connections from the queue of flush() calls made on this sensor.
905 for (Vector< wp<SensorEventConnection> >::iterator it =
906 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
907 if (it->unsafe_get() == connection.unsafe_get()) {
908 it = mPendingFlushConnections.erase(it);
909 } else {
910 ++it;
911 }
912 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700913 return mConnections.size() ? false : true;
914}
915
Aravind Akella6c2664a2014-08-13 12:24:50 -0700916void SensorService::SensorRecord::addPendingFlushConnection(
917 const sp<SensorEventConnection>& connection) {
918 mPendingFlushConnections.add(connection);
919}
920
921void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
922 if (mPendingFlushConnections.size() > 0) {
923 mPendingFlushConnections.removeAt(0);
924 }
925}
926
927SensorService::SensorEventConnection *
928SensorService::SensorRecord::getFirstPendingFlushConnection() {
929 if (mPendingFlushConnections.size() > 0) {
930 return mPendingFlushConnections[0].unsafe_get();
931 }
932 return NULL;
933}
934
Mathias Agopianfc328812010-07-14 23:41:37 -0700935// ---------------------------------------------------------------------------
936
937SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -0700938 const sp<SensorService>& service, uid_t uid)
Aravind Akella56ae4262014-07-10 16:01:10 -0700939 : mService(service), mUid(uid), mWakeLockRefCount(0), mEventCache(NULL), mCacheSize(0),
940 mMaxCacheSize(0) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700941 const SensorDevice& device(SensorDevice::getInstance());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700942 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -0700943#if DEBUG_CONNECTIONS
944 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -0700945 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700946#endif
Mathias Agopianfc328812010-07-14 23:41:37 -0700947}
948
Aravind Akella56ae4262014-07-10 16:01:10 -0700949SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +0000950 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akella56ae4262014-07-10 16:01:10 -0700951 if (mEventCache != NULL) {
952 delete mEventCache;
953 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700954 mService->cleanupConnection(this);
955}
956
Aravind Akella56ae4262014-07-10 16:01:10 -0700957void SensorService::SensorEventConnection::onFirstRef() {
958 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -0700959}
960
Aravind Akella9a844cf2014-02-11 18:58:52 -0800961bool SensorService::SensorEventConnection::needsWakeLock() {
962 Mutex::Autolock _l(mConnectionLock);
963 return mWakeLockRefCount > 0;
964}
965
Aravind Akella4c8b9512013-09-05 17:03:38 -0700966void SensorService::SensorEventConnection::dump(String8& result) {
967 Mutex::Autolock _l(mConnectionLock);
Aravind Akella56ae4262014-07-10 16:01:10 -0700968 result.appendFormat("\t %d WakeLockRefCount \n", mWakeLockRefCount);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700969 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
970 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700971 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d | uid %d|"
Aravind Akella56ae4262014-07-10 16:01:10 -0700972 "cache size: %d max cache size %d\n",
Aravind Akella4c8b9512013-09-05 17:03:38 -0700973 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700974 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -0700975 flushInfo.mFirstFlushPending ? "First flush pending" :
976 "active",
Patrick Tjineefced12014-02-05 15:06:03 -0800977 flushInfo.mPendingFlushEventsToSend,
Aravind Akella56ae4262014-07-10 16:01:10 -0700978 mUid,
979 mCacheSize,
980 mMaxCacheSize);
981#if DEBUG_CONNECTIONS
Aravind Akellae74baf62014-08-21 12:28:35 -0700982 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
983 " total_acks_needed %d | total_acks_recvd %d\n",
Aravind Akella56ae4262014-07-10 16:01:10 -0700984 mEventsReceived,
985 mEventsSent,
986 mEventsSentFromCache,
Aravind Akellae74baf62014-08-21 12:28:35 -0700987 mEventsReceived - (mEventsSentFromCache +
988 mEventsSent + mCacheSize),
989 mTotalAcksNeeded,
990 mTotalAcksReceived);
Aravind Akella56ae4262014-07-10 16:01:10 -0700991#endif
992
Aravind Akella4c8b9512013-09-05 17:03:38 -0700993 }
994}
995
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700996bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800997 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +0000998 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
999 return false;
1000 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001001 if (mSensorInfo.indexOfKey(handle) < 0) {
1002 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001003 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001004 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001005 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001006}
1007
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001008bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001009 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001010 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001011 return true;
1012 }
1013 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001014}
1015
1016bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001017 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001018 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001019}
1020
1021bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001022 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001023 return mSensorInfo.size() ? true : false;
1024}
1025
Aravind Akella4c8b9512013-09-05 17:03:38 -07001026void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1027 bool value) {
1028 Mutex::Autolock _l(mConnectionLock);
1029 ssize_t index = mSensorInfo.indexOfKey(handle);
1030 if (index >= 0) {
1031 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1032 flushInfo.mFirstFlushPending = value;
1033 }
1034}
1035
Mathias Agopianfc328812010-07-14 23:41:37 -07001036status_t SensorService::SensorEventConnection::sendEvents(
Mathias Agopiancf510012010-07-22 16:18:10 -07001037 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella56ae4262014-07-10 16:01:10 -07001038 sensors_event_t* scratch) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001039 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001040 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001041 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001042 if (scratch) {
1043 size_t i=0;
1044 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001045 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001046 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1047 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
1048 buffer[i].meta_data.sensor);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001049 // Setting sensor_handle to the correct sensor to ensure the sensor events per connection are
Aravind Akella724d91d2013-06-27 12:04:23 -07001050 // filtered correctly. buffer[i].sensor is zero for meta_data events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001051 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001052 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001053 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001054 // Check if this connection has registered for this sensor. If not continue to the
1055 // next sensor_event.
1056 if (index < 0) {
1057 ++i;
1058 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001059 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001060
Aravind Akella56ae4262014-07-10 16:01:10 -07001061 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001062 // Check if there is a pending flush_complete event for this sensor on this connection.
1063 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true) {
1064 SensorService::SensorRecord *rec = mService->getSensorRecord(sensor_handle);
1065 if (rec && rec->getFirstPendingFlushConnection() == this) {
1066 rec->removeFirstPendingFlushConnection();
Aravind Akella56ae4262014-07-10 16:01:10 -07001067 flushInfo.mFirstFlushPending = false;
1068 ++i;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001069 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1070 buffer[i].meta_data.sensor);
Aravind Akella56ae4262014-07-10 16:01:10 -07001071 continue;
1072 }
1073 }
1074
1075 // If there is a pending flush complete event for this sensor on this connection,
1076 // ignore the event and proceed to the next.
1077 if (flushInfo.mFirstFlushPending) {
1078 ++i;
1079 continue;
1080 }
1081
1082 do {
1083 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001084 // Check if this connection has called flush() on this sensor. Only if
1085 // a flush() has been explicitly called, send a flush_complete_event.
1086 SensorService::SensorRecord *rec = mService->getSensorRecord(sensor_handle);
1087 if (rec && rec->getFirstPendingFlushConnection() == this) {
1088 rec->removeFirstPendingFlushConnection();
Aravind Akella56ae4262014-07-10 16:01:10 -07001089 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001090 }
1091 ++i;
1092 } else {
1093 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001094 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001095 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001096 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001097 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001098 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001099 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001100 } else {
1101 scratch = const_cast<sensors_event_t *>(buffer);
1102 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001103 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001104
Aravind Akella6c2664a2014-08-13 12:24:50 -07001105 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001106 // Early return if there are no events for this connection.
1107 if (count == 0) {
1108 return status_t(NO_ERROR);
1109 }
1110
1111#if DEBUG_CONNECTIONS
1112 mEventsReceived += count;
1113#endif
1114 if (mCacheSize != 0) {
1115 // There are some events in the cache which need to be sent first. Copy this buffer to
1116 // the end of cache.
1117 if (mCacheSize + count <= mMaxCacheSize) {
1118 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1119 mCacheSize += count;
1120 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001121 // Check if any new sensors have registered on this connection which may have increased
1122 // the max cache size that is desired.
1123 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1124 reAllocateCacheLocked(scratch, count);
1125 return status_t(NO_ERROR);
1126 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001127 // Some events need to be dropped.
1128 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1129 if (remaningCacheSize != 0) {
1130 memcpy(&mEventCache[mCacheSize], scratch,
1131 remaningCacheSize * sizeof(sensors_event_t));
1132 }
1133 int numEventsDropped = count - remaningCacheSize;
1134 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1135 // Drop the first "numEventsDropped" in the cache.
1136 memmove(mEventCache, &mEventCache[numEventsDropped],
1137 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1138
1139 // Copy the remainingEvents in scratch buffer to the end of cache.
1140 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1141 numEventsDropped * sizeof(sensors_event_t));
1142 }
1143 return status_t(NO_ERROR);
1144 }
1145
Aravind Akella6c2664a2014-08-13 12:24:50 -07001146 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1147 if (index_wake_up_event >= 0) {
1148 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1149 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001150#if DEBUG_CONNECTIONS
1151 ++mTotalAcksNeeded;
1152#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001153 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001154
1155 // NOTE: ASensorEvent and sensors_event_t are the same type.
1156 ssize_t size = SensorEventQueue::write(mChannel,
1157 reinterpret_cast<ASensorEvent const*>(scratch), count);
1158 if (size < 0) {
1159 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001160 if (index_wake_up_event >= 0) {
1161 // If there was a wake_up sensor_event, reset the flag.
1162 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1163 --mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001164#if DEBUG_CONNECTIONS
1165 --mTotalAcksNeeded;
1166#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001167 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001168 if (mEventCache == NULL) {
1169 mMaxCacheSize = computeMaxCacheSizeLocked();
1170 mEventCache = new sensors_event_t[mMaxCacheSize];
1171 mCacheSize = 0;
1172 }
1173 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1174 mCacheSize += count;
1175
1176 // Add this file descriptor to the looper to get a callback when this fd is available for
1177 // writing.
1178 mService->getLooper()->addFd(mChannel->getSendFd(), 0,
1179 ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_INPUT, this, NULL);
1180 return size;
1181 }
1182
1183#if DEBUG_CONNECTIONS
1184 if (size > 0) {
1185 mEventsSent += count;
1186 }
1187#endif
1188
1189 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1190}
1191
Aravind Akella6c2664a2014-08-13 12:24:50 -07001192void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1193 int count) {
1194 sensors_event_t *eventCache_new;
1195 const int new_cache_size = computeMaxCacheSizeLocked();
1196 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1197 eventCache_new = new sensors_event_t[new_cache_size];
1198 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1199 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1200
1201 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1202 new_cache_size);
1203
1204 delete mEventCache;
1205 mEventCache = eventCache_new;
1206 mCacheSize += count;
1207 mMaxCacheSize = new_cache_size;
1208}
1209
1210void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1211 ASensorEvent flushCompleteEvent;
1212 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
1213 flushCompleteEvent.sensor = 0;
1214 // Loop through all the sensors for this connection and check if there are any pending
1215 // flush complete events to be sent.
1216 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1217 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1218 while (flushInfo.mPendingFlushEventsToSend > 0) {
1219 flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
1220 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1221 if (size < 0) {
1222 return;
1223 }
1224 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1225 flushCompleteEvent.meta_data.sensor);
1226 flushInfo.mPendingFlushEventsToSend--;
1227 }
1228 }
1229}
1230
Aravind Akella56ae4262014-07-10 16:01:10 -07001231void SensorService::SensorEventConnection::writeToSocketFromCacheLocked() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001232 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1233 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1234 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1235 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
1236 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001237 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001238 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001239 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001240 int index_wake_up_event =
1241 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1242 if (index_wake_up_event >= 0) {
1243 mEventCache[index_wake_up_event + numEventsSent].flags |=
1244 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1245 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001246#if DEBUG_CONNECTIONS
1247 ++mTotalAcksNeeded;
1248#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001249 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001250
Aravind Akella56ae4262014-07-10 16:01:10 -07001251 ssize_t size = SensorEventQueue::write(mChannel,
1252 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001253 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001254 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001255 if (index_wake_up_event >= 0) {
1256 // If there was a wake_up sensor_event, reset the flag.
1257 mEventCache[index_wake_up_event + numEventsSent].flags &=
1258 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1259 --mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001260#if DEBUG_CONNECTIONS
1261 --mTotalAcksNeeded;
1262#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001263 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001264 memmove(mEventCache, &mEventCache[numEventsSent],
1265 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1266 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001267 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001268 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001269 return;
1270 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001271 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001272#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001273 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001274#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001275 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001276 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1277 // All events from the cache have been sent. Reset cache size to zero.
1278 mCacheSize = 0;
1279 // Poll only for ALOOPER_EVENT_INPUT(read) on the file descriptor.
1280 mService->getLooper()->addFd(mChannel->getSendFd(), 0, ALOOPER_EVENT_INPUT, this, NULL);
Mathias Agopianfc328812010-07-14 23:41:37 -07001281}
1282
Aravind Akellac551eac2013-10-14 17:04:42 -07001283void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella4c8b9512013-09-05 17:03:38 -07001284 sensors_event_t* scratch, const int numEventsDropped) {
1285 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001286 // Count flushComplete events in the events that are about to the dropped. These will be sent
1287 // separately before the next batch of events.
1288 for (int j = 0; j < numEventsDropped; ++j) {
1289 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1290 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1291 flushInfo.mPendingFlushEventsToSend++;
1292 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1293 flushInfo.mPendingFlushEventsToSend);
1294 }
1295 }
1296 return;
1297}
1298
Aravind Akella6c2664a2014-08-13 12:24:50 -07001299int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1300 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001301 for (int i = 0; i < count; ++i) {
1302 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001303 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001304 }
1305 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001306 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001307}
1308
Mathias Agopianb3989272011-10-20 18:42:02 -07001309sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001310{
1311 return mChannel;
1312}
1313
1314status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001315 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1316 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001317{
1318 status_t err;
1319 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001320 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1321 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001322
Mathias Agopianfc328812010-07-14 23:41:37 -07001323 } else {
1324 err = mService->disable(this, handle);
1325 }
1326 return err;
1327}
1328
1329status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001330 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001331{
Aravind Akella724d91d2013-06-27 12:04:23 -07001332 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001333}
1334
Aravind Akella701166d2013-10-08 14:59:26 -07001335status_t SensorService::SensorEventConnection::flush() {
Aravind Akellac551eac2013-10-14 17:04:42 -07001336 SensorDevice& dev(SensorDevice::getInstance());
1337 const int halVersion = dev.getHalDeviceVersion();
Aravind Akella701166d2013-10-08 14:59:26 -07001338 Mutex::Autolock _l(mConnectionLock);
1339 status_t err(NO_ERROR);
Aravind Akellac551eac2013-10-14 17:04:42 -07001340 // Loop through all sensors for this connection and call flush on each of them.
Aravind Akella701166d2013-10-08 14:59:26 -07001341 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1342 const int handle = mSensorInfo.keyAt(i);
Aravind Akella56ae4262014-07-10 16:01:10 -07001343 FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
Aravind Akellab4099e72013-10-15 15:43:10 -07001344 if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
Aravind Akellac551eac2013-10-14 17:04:42 -07001345 // For older devices just increment pending flush count which will send a trivial
1346 // flush complete event.
Aravind Akellac551eac2013-10-14 17:04:42 -07001347 flushInfo.mPendingFlushEventsToSend++;
1348 } else {
1349 status_t err_flush = mService->flushSensor(this, handle);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001350 if (err_flush != NO_ERROR) {
Aravind Akellac551eac2013-10-14 17:04:42 -07001351 ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
1352 }
1353 err = (err_flush != NO_ERROR) ? err_flush : err;
Aravind Akella701166d2013-10-08 14:59:26 -07001354 }
Aravind Akella701166d2013-10-08 14:59:26 -07001355 }
1356 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001357}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001358
Aravind Akella56ae4262014-07-10 16:01:10 -07001359int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* data) {
1360 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1361 return 0;
1362 }
1363
1364 if (events & ALOOPER_EVENT_INPUT) {
1365 char buf;
1366 ssize_t ret = ::recv(fd, &buf, sizeof(buf), MSG_DONTWAIT);
1367
1368 {
1369 Mutex::Autolock _l(mConnectionLock);
1370 --mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001371#if DEBUG_CONNECTIONS
1372 ++mTotalAcksReceived;
1373#endif
Aravind Akella56ae4262014-07-10 16:01:10 -07001374 }
1375 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1376 // here as checkWakeLockState() will need it.
1377 if (mWakeLockRefCount == 0) {
1378 mService->checkWakeLockState();
1379 }
1380 // continue getting callbacks.
1381 return 1;
1382 }
1383
1384 if (events & ALOOPER_EVENT_OUTPUT) {
1385 // send sensor data that is stored in mEventCache.
Aravind Akella9a844cf2014-02-11 18:58:52 -08001386 Mutex::Autolock _l(mConnectionLock);
Aravind Akella56ae4262014-07-10 16:01:10 -07001387 writeToSocketFromCacheLocked();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001388 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001389 return 1;
1390}
1391
1392int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1393 int fifoWakeUpSensors = 0;
1394 int fifoNonWakeUpSensors = 0;
1395 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1396 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1397 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1398 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1399 // non wake_up sensors.
1400 if (sensor.isWakeUpSensor()) {
1401 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1402 } else {
1403 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1404 }
1405 } else {
1406 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1407 if (sensor.isWakeUpSensor()) {
1408 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1409 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1410
1411 } else {
1412 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1413 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1414
1415 }
1416 }
1417 }
1418 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1419 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001420 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001421 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001422 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001423 }
1424 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001425}
1426
Mathias Agopianfc328812010-07-14 23:41:37 -07001427// ---------------------------------------------------------------------------
1428}; // namespace android
1429