blob: 2336d881afedddfc903a941424ec633c756c6bde [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
34#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070035#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070037
38#include <gui/ISensorServer.h>
39#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070040#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070041
42#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070043#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070044
Mathias Agopian787ac1b2012-09-18 18:49:18 -070045#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080047#include "GravitySensor.h"
48#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080050#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070051#include "SensorFusion.h"
52#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070053
54namespace android {
55// ---------------------------------------------------------------------------
56
Mathias Agopian33015422011-05-27 18:18:13 -070057/*
58 * Notes:
59 *
60 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070061 * - run mag sensor from time to time to force calibration
62 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63 *
64 */
65
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070066const char* SensorService::WAKE_LOCK_NAME = "SensorService";
67
Mathias Agopianfc328812010-07-14 23:41:37 -070068SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070069 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
70 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070071{
72}
73
74void SensorService::onFirstRef()
75{
Steve Blocka5512372011-12-20 16:23:08 +000076 ALOGD("nuSensorService starting...");
Mathias Agopian50df2952010-07-19 19:09:10 -070077
Mathias Agopianf001c922010-11-11 17:58:51 -080078 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070079
Mathias Agopianf001c922010-11-11 17:58:51 -080080 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080081 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070082 ssize_t count = dev.getSensorList(&list);
83 if (count > 0) {
84 ssize_t orientationIndex = -1;
85 bool hasGyro = false;
86 uint32_t virtualSensorsNeeds =
87 (1<<SENSOR_TYPE_GRAVITY) |
88 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
89 (1<<SENSOR_TYPE_ROTATION_VECTOR);
90
91 mLastEventSeen.setCapacity(count);
92 for (ssize_t i=0 ; i<count ; i++) {
93 registerSensor( new HardwareSensor(list[i]) );
94 switch (list[i].type) {
95 case SENSOR_TYPE_ORIENTATION:
96 orientationIndex = i;
97 break;
98 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -070099 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700100 hasGyro = true;
101 break;
102 case SENSOR_TYPE_GRAVITY:
103 case SENSOR_TYPE_LINEAR_ACCELERATION:
104 case SENSOR_TYPE_ROTATION_VECTOR:
105 virtualSensorsNeeds &= ~(1<<list[i].type);
106 break;
107 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700108 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700109
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700110 // it's safe to instantiate the SensorFusion object here
111 // (it wants to be instantiated after h/w sensors have been
112 // registered)
113 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700114
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700115 // build the sensor list returned to users
116 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700117
118 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700119 Sensor aSensor;
120
121 // Add Android virtual sensors if they're not already
122 // available in the HAL
123
124 aSensor = registerVirtualSensor( new RotationVectorSensor() );
125 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
126 mUserSensorList.add(aSensor);
127 }
128
129 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
130 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
131 mUserSensorList.add(aSensor);
132 }
133
134 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
135 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
136 mUserSensorList.add(aSensor);
137 }
138
139 aSensor = registerVirtualSensor( new OrientationSensor() );
140 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
141 // if we are doing our own rotation-vector, also add
142 // the orientation sensor and remove the HAL provided one.
143 mUserSensorList.replaceAt(aSensor, orientationIndex);
144 }
145
Mathias Agopian33264862012-06-28 19:46:54 -0700146 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700147 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700148 registerVirtualSensor( new GyroDriftSensor() );
149 }
150
Mathias Agopian33264862012-06-28 19:46:54 -0700151 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700152 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700153
Aravind Akella5466c3d2014-08-22 16:11:10 -0700154 // Check if the device really supports batching by looking at the FIFO event
155 // counts for each sensor.
156 bool batchingSupported = false;
157 for (int i = 0; i < mSensorList.size(); ++i) {
158 if (mSensorList[i].getFifoMaxEventCount() > 0) {
159 batchingSupported = true;
160 break;
161 }
162 }
163
164 if (batchingSupported) {
165 // Increase socket buffer size to a max of 100 KB for batching capabilities.
166 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
167 } else {
168 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
169 }
170
171 // Compare the socketBufferSize value against the system limits and limit
172 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700173 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
174 char line[128];
175 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
176 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700177 size_t maxSystemSocketBufferSize;
178 sscanf(line, "%zu", &maxSystemSocketBufferSize);
179 if (mSocketBufferSize > maxSystemSocketBufferSize) {
180 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700181 }
182 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700183 if (fp) {
184 fclose(fp);
185 }
186
Aravind Akella9a844cf2014-02-11 18:58:52 -0800187 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700188 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700189 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
190 mSensorEventBuffer = new sensors_event_t[minBufferSize];
191 mSensorEventScratch = new sensors_event_t[minBufferSize];
192 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akella4949c502015-02-11 15:54:35 -0800193 mMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700194
Aravind Akellab4373ac2014-10-29 17:55:20 -0700195 mAckReceiver = new SensorEventAckReceiver(this);
196 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700197 mInitCheck = NO_ERROR;
Aravind Akella7830ef32014-10-07 14:13:12 -0700198 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700199 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700200 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700201}
202
Mathias Agopian03193062013-05-10 19:32:39 -0700203Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800204{
205 sensors_event_t event;
206 memset(&event, 0, sizeof(event));
207
208 const Sensor sensor(s->getSensor());
209 // add to the sensor list (returned to clients)
210 mSensorList.add(sensor);
211 // add to our handle->SensorInterface mapping
212 mSensorMap.add(sensor.getHandle(), s);
213 // create an entry in the mLastEventSeen array
214 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700215
216 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800217}
218
Mathias Agopian03193062013-05-10 19:32:39 -0700219Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800220{
Mathias Agopian03193062013-05-10 19:32:39 -0700221 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800222 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700223 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800224}
225
Mathias Agopianfc328812010-07-14 23:41:37 -0700226SensorService::~SensorService()
227{
Mathias Agopianf001c922010-11-11 17:58:51 -0800228 for (size_t i=0 ; i<mSensorMap.size() ; i++)
229 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700230}
231
Mathias Agopian1cb13462011-06-27 16:05:52 -0700232static const String16 sDump("android.permission.DUMP");
233
Aravind Akella4949c502015-02-11 15:54:35 -0800234status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700235{
Mathias Agopianfc328812010-07-14 23:41:37 -0700236 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700237 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700238 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000239 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700240 IPCThreadState::self()->getCallingPid(),
241 IPCThreadState::self()->getCallingUid());
Aravind Akella4949c502015-02-11 15:54:35 -0800242 } else if (args.size() > 0) {
243 if (args.size() > 1) {
244 return INVALID_OPERATION;
245 }
246 Mutex::Autolock _l(mLock);
247 SensorDevice& dev(SensorDevice::getInstance());
248 if (args[0] == String16("restrict") && mMode == NORMAL) {
249 mMode = RESTRICTED;
250 dev.disableAllSensors();
251 // Clear all pending flush connections for all active sensors. If one of the active
252 // connections has called flush() and the underlying sensor has been disabled before a
253 // flush complete event is returned, we need to remove the connection from this queue.
254 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
255 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
256 }
257 } else if (args[0] == String16("enable") && mMode == RESTRICTED) {
258 mMode = NORMAL;
259 dev.enableAllSensors();
260 }
261 return status_t(NO_ERROR);
Mathias Agopianfc328812010-07-14 23:41:37 -0700262 } else {
263 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700264 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700265 for (size_t i=0 ; i<mSensorList.size() ; i++) {
266 const Sensor& s(mSensorList[i]);
267 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700268 result.appendFormat(
Aravind Akella0b6acb22014-10-18 16:37:13 -0700269 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700270 s.getName().string(),
271 s.getVendor().string(),
Aravind Akella0b6acb22014-10-18 16:37:13 -0700272 s.getVersion(),
Aravind Akella70018042014-04-07 22:52:37 +0000273 s.getStringType().string(),
274 s.getHandle(),
Aravind Akella6c2664a2014-08-13 12:24:50 -0700275 s.getRequiredPermission().string(),
276 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700277
Aravind Akella0e025c52014-06-03 19:19:57 -0700278 const int reportingMode = s.getReportingMode();
279 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700280 result.append(" continuous | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700281 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700282 result.append(" on-change | ");
Aravind Akella0e025c52014-06-03 19:19:57 -0700283 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700284 result.append(" one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700285 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700286 result.append(" special-trigger | ");
287 }
288
289 if (s.getMaxDelay() > 0) {
290 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
291 } else {
292 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700293 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700294
295 if (s.getMinDelay() > 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700296 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700297 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700298 result.appendFormat("minDelay=%dus |", s.getMinDelay());
Aravind Akella0e025c52014-06-03 19:19:57 -0700299 }
300
Aravind Akella724d91d2013-06-27 12:04:23 -0700301 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000302 result.appendFormat("FifoMax=%d events | ",
303 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700304 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700305 result.append("no batching | ");
306 }
307
308 if (s.isWakeUpSensor()) {
309 result.appendFormat("wakeUp | ");
310 } else {
311 result.appendFormat("non-wakeUp | ");
Aravind Akella724d91d2013-06-27 12:04:23 -0700312 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700313
314 switch (s.getType()) {
315 case SENSOR_TYPE_ROTATION_VECTOR:
316 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
317 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700318 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
319 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700320 break;
321 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
322 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
323 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700324 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
325 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5],
326 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700327 break;
328 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
329 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700330 "last=<%5.1f,%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
331 e.data[0], e.data[1], e.data[2], e.data[3], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700332 break;
333 case SENSOR_TYPE_SIGNIFICANT_MOTION:
334 case SENSOR_TYPE_STEP_DETECTOR:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700335 result.appendFormat( "last=<%f %" PRId64 ">\n", e.data[0], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700336 break;
337 case SENSOR_TYPE_STEP_COUNTER:
Aravind Akella6c2664a2014-08-13 12:24:50 -0700338 result.appendFormat( "last=<%" PRIu64 ", %" PRId64 ">\n", e.u64.step_counter,
339 e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700340 break;
341 default:
342 // default to 3 values
343 result.appendFormat(
Aravind Akella6c2664a2014-08-13 12:24:50 -0700344 "last=<%5.1f,%5.1f,%5.1f, %" PRId64 ">\n",
345 e.data[0], e.data[1], e.data[2], e.timestamp);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700346 break;
347 }
Aravind Akella6c2664a2014-08-13 12:24:50 -0700348 result.append("\n");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700349 }
350 SensorFusion::getInstance().dump(result);
351 SensorDevice::getInstance().dump(result);
352
Mathias Agopianba02cd22013-07-03 16:20:57 -0700353 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700354 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700355 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700356 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700357 getSensorName(handle).string(),
358 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700359 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700360 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700361
Aravind Akella5466c3d2014-08-22 16:11:10 -0700362 result.appendFormat("Socket Buffer size = %d events\n",
Aravind Akella6c2664a2014-08-13 12:24:50 -0700363 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella9a844cf2014-02-11 18:58:52 -0800364 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Aravind Akella4949c502015-02-11 15:54:35 -0800365 result.appendFormat("Mode :");
366 switch(mMode) {
367 case NORMAL:
368 result.appendFormat(" NORMAL\n");
369 break;
370 case RESTRICTED:
371 result.appendFormat(" RESTRICTED\n");
372 break;
373 case DATA_INJECTION:
374 result.appendFormat(" DATA_INJECTION\n");
375 }
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700376 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700377
378 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
379 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
380 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700381 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700382 connection->dump(result);
383 }
384 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700385 }
386 write(fd, result.string(), result.size());
387 return NO_ERROR;
388}
389
Aravind Akella9a844cf2014-02-11 18:58:52 -0800390void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700391 sensors_event_t const* buffer, const int count) {
392 for (int i=0 ; i<count ; i++) {
393 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700394 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
395 handle = buffer[i].meta_data.sensor;
396 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700397 if (connection->hasSensor(handle)) {
398 SensorInterface* sensor = mSensorMap.valueFor(handle);
399 // If this buffer has an event from a one_shot sensor and this connection is registered
400 // for this particular one_shot sensor, try cleaning up the connection.
401 if (sensor != NULL &&
402 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
403 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800404 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700405 }
406 }
407 }
408}
409
Mathias Agopianfc328812010-07-14 23:41:37 -0700410bool SensorService::threadLoop()
411{
Steve Blocka5512372011-12-20 16:23:08 +0000412 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700413
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700414 // each virtual sensor could generate an event per "real" event, that's why we need
415 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
416 // in practice, this is too aggressive, but guaranteed to be enough.
417 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
418 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
419
Mathias Agopianf001c922010-11-11 17:58:51 -0800420 SensorDevice& device(SensorDevice::getInstance());
421 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700422
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700423 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700424 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700425 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
426 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000427 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700428 break;
429 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700430
431 // Reset sensors_event_t.flags to zero for all events in the buffer.
432 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700433 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700434 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700435
436 // Make a copy of the connection vector as some connections may be removed during the
437 // course of this loop (especially when one-shot sensor events are present in the
438 // sensor_event buffer). Promote all connections to StrongPointers before the lock is
439 // acquired. If the destructor of the sp gets called when the lock is acquired, it may
440 // result in a deadlock as ~SensorEventConnection() needs to acquire mLock again for
441 // cleanup. So copy all the strongPointers to a vector before the lock is acquired.
442 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700443 populateActiveConnections(&activeConnections);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800444 Mutex::Autolock _l(mLock);
445 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
446 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
447 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
448 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
449 // releasing the wakelock.
450 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700451 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700452 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800453 bufferHasWakeUpEvent = true;
454 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700455 }
456 }
457
Aravind Akella9a844cf2014-02-11 18:58:52 -0800458 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700459 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800460 }
Aravind Akella8493b792014-09-08 15:45:47 -0700461 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800462
Mathias Agopianf001c922010-11-11 17:58:51 -0800463 // handle virtual sensors
464 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700465 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800466 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800467 if (activeVirtualSensorCount) {
468 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700469 SensorFusion& fusion(SensorFusion::getInstance());
470 if (fusion.isEnabled()) {
471 for (size_t i=0 ; i<size_t(count) ; i++) {
472 fusion.process(event[i]);
473 }
474 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700475 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800476 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700477 if (count + k >= minBufferSize) {
478 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700479 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700480 count, k, minBufferSize);
481 break;
482 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800483 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800484 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700485 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700486 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800487 k++;
488 }
489 }
490 }
491 if (k) {
492 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700493 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800494 count += k;
495 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700496 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700497 }
498 }
499 }
500
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700501 // handle backward compatibility for RotationVector sensor
502 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
503 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700504 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700505 // All the 4 components of the quaternion should be available
506 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700507 mSensorEventBuffer[i].data[4] = -1;
508 }
509 }
510 }
511
512 // Map flush_complete_events in the buffer to SensorEventConnections which called
513 // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the
514 // SensorEventConnection mapped to the corresponding flush_complete_event in
515 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
516 for (int i = 0; i < count; ++i) {
517 mMapFlushEventsToConnections[i] = NULL;
518 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
519 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
520 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
521 if (rec != NULL) {
522 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
523 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700524 }
525 }
526 }
527
Aravind Akella9a844cf2014-02-11 18:58:52 -0800528 // Send our events to clients. Check the state of wake lock for each client and release the
529 // lock if none of the clients need it.
530 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700531 size_t numConnections = activeConnections.size();
532 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700533 if (activeConnections[i] != 0) {
534 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700535 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700536 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700537 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
538 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700539 if (activeConnections[i]->hasOneShotSensors()) {
540 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
541 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700542 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800543 }
544 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700545
Aravind Akella9a844cf2014-02-11 18:58:52 -0800546 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700547 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800548 }
Aravind Akella8493b792014-09-08 15:45:47 -0700549 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700550
Steve Block3c20fbe2012-01-05 23:22:43 +0000551 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800552 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700553 return false;
554}
555
Aravind Akella56ae4262014-07-10 16:01:10 -0700556sp<Looper> SensorService::getLooper() const {
557 return mLooper;
558}
559
Aravind Akellab4373ac2014-10-29 17:55:20 -0700560void SensorService::resetAllWakeLockRefCounts() {
561 SortedVector< sp<SensorEventConnection> > activeConnections;
562 populateActiveConnections(&activeConnections);
563 {
564 Mutex::Autolock _l(mLock);
565 for (size_t i=0 ; i < activeConnections.size(); ++i) {
566 if (activeConnections[i] != 0) {
567 activeConnections[i]->resetWakeLockRefCount();
568 }
569 }
570 setWakeLockAcquiredLocked(false);
571 }
572}
573
574void SensorService::setWakeLockAcquiredLocked(bool acquire) {
575 if (acquire) {
576 if (!mWakeLockAcquired) {
577 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
578 mWakeLockAcquired = true;
579 }
580 mLooper->wake();
581 } else {
582 if (mWakeLockAcquired) {
583 release_wake_lock(WAKE_LOCK_NAME);
584 mWakeLockAcquired = false;
585 }
586 }
587}
588
Aravind Akellab4373ac2014-10-29 17:55:20 -0700589bool SensorService::isWakeLockAcquired() {
590 Mutex::Autolock _l(mLock);
591 return mWakeLockAcquired;
592}
593
Aravind Akella56ae4262014-07-10 16:01:10 -0700594bool SensorService::SensorEventAckReceiver::threadLoop() {
595 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700596 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700597 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700598 bool wakeLockAcquired = mService->isWakeLockAcquired();
599 int timeout = -1;
600 if (wakeLockAcquired) timeout = 5000;
601 int ret = looper->pollOnce(timeout);
602 if (ret == ALOOPER_POLL_TIMEOUT) {
603 mService->resetAllWakeLockRefCounts();
604 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700605 } while(!Thread::exitPending());
606 return false;
607}
608
Aravind Akella9a844cf2014-02-11 18:58:52 -0800609void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800610 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800611 const sensors_event_t* last = NULL;
612 for (size_t i = 0; i < count; i++) {
613 const sensors_event_t* event = &buffer[i];
614 if (event->type != SENSOR_TYPE_META_DATA) {
615 if (last && event->sensor != last->sensor) {
616 mLastEventSeen.editValueFor(last->sensor) = *last;
617 }
618 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800619 }
620 }
Aravind Akella4b847042014-03-03 19:02:46 -0800621 if (last) {
622 mLastEventSeen.editValueFor(last->sensor) = *last;
623 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800624}
625
Mathias Agopianf001c922010-11-11 17:58:51 -0800626void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
627{
628 struct compar {
629 static int cmp(void const* lhs, void const* rhs) {
630 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
631 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700632 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800633 }
634 };
635 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
636}
637
Mathias Agopian5d270722010-07-19 15:20:39 -0700638String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700639 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700640 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700641 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700642 if (sensor.getHandle() == handle) {
643 return sensor.getName();
644 }
645 }
646 String8 result("unknown");
647 return result;
648}
649
Aravind Akellab4099e72013-10-15 15:43:10 -0700650bool SensorService::isVirtualSensor(int handle) const {
651 SensorInterface* sensor = mSensorMap.valueFor(handle);
652 return sensor->isVirtual();
653}
654
Aravind Akella9a844cf2014-02-11 18:58:52 -0800655bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700656 int handle = event.sensor;
657 if (event.type == SENSOR_TYPE_META_DATA) {
658 handle = event.meta_data.sensor;
659 }
660 SensorInterface* sensor = mSensorMap.valueFor(handle);
661 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800662}
663
Aravind Akella6c2664a2014-08-13 12:24:50 -0700664SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
665 return mActiveSensors.valueFor(handle);
666}
667
Mathias Agopianfc328812010-07-14 23:41:37 -0700668Vector<Sensor> SensorService::getSensorList()
669{
Mathias Agopian33264862012-06-28 19:46:54 -0700670 char value[PROPERTY_VALUE_MAX];
671 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000672 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
673 mUserSensorListDebug : mUserSensorList;
674 Vector<Sensor> accessibleSensorList;
675 for (size_t i = 0; i < initialSensorList.size(); i++) {
676 Sensor sensor = initialSensorList[i];
677 if (canAccessSensor(sensor)) {
678 accessibleSensorList.add(sensor);
679 } else {
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100680 ALOGI("Skipped sensor %s because it requires permission %s",
681 sensor.getName().string(),
682 sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +0000683 }
Mathias Agopian33264862012-06-28 19:46:54 -0700684 }
Aravind Akella70018042014-04-07 22:52:37 +0000685 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700686}
687
Aravind Akella4949c502015-02-11 15:54:35 -0800688sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700689{
Mathias Agopian5307d172012-09-18 17:02:43 -0700690 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akella4949c502015-02-11 15:54:35 -0800691 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName));
Mathias Agopianfc328812010-07-14 23:41:37 -0700692 return result;
693}
694
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800695void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700696{
697 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800698 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700699 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700700 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700701 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800702 int handle = mActiveSensors.keyAt(i);
703 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700704 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800705 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000706 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800707 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800708 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800709 }
Aravind Akella8a969552014-09-28 17:52:41 -0700710 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800711 }
712 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700713 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000714 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700715 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700716 c, i, handle);
717
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800718 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000719 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700720 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800721 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700722 delete rec;
723 size--;
724 } else {
725 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700726 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700727 }
Aravind Akella8a969552014-09-28 17:52:41 -0700728 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700729 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700730 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800731 if (c->needsWakeLock()) {
732 checkWakeLockStateLocked();
733 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700734}
735
Aravind Akella70018042014-04-07 22:52:37 +0000736Sensor SensorService::getSensorFromHandle(int handle) const {
737 return mSensorMap.valueFor(handle)->getSensor();
738}
739
Mathias Agopianfc328812010-07-14 23:41:37 -0700740status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella4949c502015-02-11 15:54:35 -0800741 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700742{
Mathias Agopian50df2952010-07-19 19:09:10 -0700743 if (mInitCheck != NO_ERROR)
744 return mInitCheck;
745
Mathias Agopianf001c922010-11-11 17:58:51 -0800746 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700747 if (sensor == NULL) {
748 return BAD_VALUE;
749 }
Aravind Akella70018042014-04-07 22:52:37 +0000750
751 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
752 return BAD_VALUE;
753 }
754
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700755 Mutex::Autolock _l(mLock);
Aravind Akella4949c502015-02-11 15:54:35 -0800756 if (mMode == RESTRICTED && !isWhiteListedPackage(connection->getPackageName())) {
757 return INVALID_OPERATION;
758 }
759
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700760 SensorRecord* rec = mActiveSensors.valueFor(handle);
761 if (rec == 0) {
762 rec = new SensorRecord(connection);
763 mActiveSensors.add(handle, rec);
764 if (sensor->isVirtual()) {
765 mActiveVirtualSensors.add(handle, sensor);
766 }
767 } else {
768 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800769 // this sensor is already activated, but we are adding a connection that uses it.
770 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700771 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700772 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800773 // NOTE: The wake_up flag of this event may get set to
774 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700775 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
776 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800777 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700778 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800779 }
780 connection->sendEvents(&event, 1, NULL);
781 if (!connection->needsWakeLock() && mWakeLockAcquired) {
782 checkWakeLockStateLocked();
783 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700784 }
785 }
786 }
787 }
788
789 if (connection->addSensor(handle)) {
790 BatteryService::enableSensor(connection->getUid(), handle);
791 // the sensor was added (which means it wasn't already there)
792 // so, see if this connection becomes active
793 if (mActiveConnections.indexOf(connection) < 0) {
794 mActiveConnections.add(connection);
795 }
796 } else {
797 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
798 handle, connection.get());
799 }
800
Aravind Akella724d91d2013-06-27 12:04:23 -0700801 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
802 if (samplingPeriodNs < minDelayNs) {
803 samplingPeriodNs = minDelayNs;
804 }
805
Aravind Akella6c2664a2014-08-13 12:24:50 -0700806 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
807 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700808 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
809
Aravind Akella4949c502015-02-11 15:54:35 -0800810 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700811 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700812
Aravind Akella5466c3d2014-08-22 16:11:10 -0700813 // Call flush() before calling activate() on the sensor. Wait for a first flush complete
814 // event before sending events on this connection. Ignore one-shot sensors which don't
815 // support flush(). Also if this sensor isn't already active, don't call flush().
816 if (err == NO_ERROR && sensor->getSensor().getReportingMode() != AREPORTING_MODE_ONE_SHOT &&
817 rec->getNumConnections() > 1) {
818 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700819 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700820 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700821 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700822 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700823 } else {
824 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700825 }
826 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700827
828 if (err == NO_ERROR) {
829 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
830 err = sensor->activate(connection.get(), true);
831 }
832
Aravind Akella8a969552014-09-28 17:52:41 -0700833 if (err == NO_ERROR) {
834 connection->updateLooperRegistration(mLooper);
Aravind Akella56ae4262014-07-10 16:01:10 -0700835 }
836
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700837 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700838 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700839 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700840 }
841 return err;
842}
843
844status_t SensorService::disable(const sp<SensorEventConnection>& connection,
845 int handle)
846{
Mathias Agopian50df2952010-07-19 19:09:10 -0700847 if (mInitCheck != NO_ERROR)
848 return mInitCheck;
849
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700850 Mutex::Autolock _l(mLock);
851 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700852 if (err == NO_ERROR) {
853 SensorInterface* sensor = mSensorMap.valueFor(handle);
854 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
855 }
856 return err;
857}
858
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700859status_t SensorService::cleanupWithoutDisable(
860 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700861 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700862 return cleanupWithoutDisableLocked(connection, handle);
863}
864
865status_t SensorService::cleanupWithoutDisableLocked(
866 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700867 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700868 if (rec) {
869 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700870 if (connection->removeSensor(handle)) {
871 BatteryService::disableSensor(connection->getUid(), handle);
872 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700873 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -0700874 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -0700875 mActiveConnections.remove(connection);
876 }
877 // see if this sensor becomes inactive
878 if (rec->removeConnection(connection)) {
879 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800880 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700881 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700882 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700883 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700884 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700885 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700886}
887
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700888status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700889 int handle, nsecs_t ns)
890{
Mathias Agopian50df2952010-07-19 19:09:10 -0700891 if (mInitCheck != NO_ERROR)
892 return mInitCheck;
893
Mathias Agopianae09d652011-11-01 17:37:49 -0700894 SensorInterface* sensor = mSensorMap.valueFor(handle);
895 if (!sensor)
896 return BAD_VALUE;
897
Aravind Akella70018042014-04-07 22:52:37 +0000898 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
899 return BAD_VALUE;
900 }
901
Mathias Agopian1cd70002010-07-21 15:59:50 -0700902 if (ns < 0)
903 return BAD_VALUE;
904
Mathias Agopian62569ec2011-11-07 21:21:47 -0800905 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
906 if (ns < minDelayNs) {
907 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700908 }
909
Mathias Agopianf001c922010-11-11 17:58:51 -0800910 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700911}
912
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700913status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection) {
Aravind Akella70018042014-04-07 22:52:37 +0000914 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700915 SensorDevice& dev(SensorDevice::getInstance());
916 const int halVersion = dev.getHalDeviceVersion();
917 status_t err(NO_ERROR);
918 Mutex::Autolock _l(mLock);
919 // Loop through all sensors for this connection and call flush on each of them.
920 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
921 const int handle = connection->mSensorInfo.keyAt(i);
922 SensorInterface* sensor = mSensorMap.valueFor(handle);
923 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
924 ALOGE("flush called on a one-shot sensor");
925 err = INVALID_OPERATION;
926 continue;
927 }
Aravind Akella8493b792014-09-08 15:45:47 -0700928 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700929 // For older devices just increment pending flush count which will send a trivial
930 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -0700931 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700932 } else {
933 status_t err_flush = sensor->flush(connection.get(), handle);
934 if (err_flush == NO_ERROR) {
935 SensorRecord* rec = mActiveSensors.valueFor(handle);
936 if (rec != NULL) rec->addPendingFlushConnection(connection);
937 }
938 err = (err_flush != NO_ERROR) ? err_flush : err;
939 }
Aravind Akella70018042014-04-07 22:52:37 +0000940 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -0700941 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -0700942}
Aravind Akella70018042014-04-07 22:52:37 +0000943
Aravind Akella70018042014-04-07 22:52:37 +0000944bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700945 return (sensor.getRequiredPermission().isEmpty()) ||
946 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +0000947}
948
949bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
950 if (canAccessSensor(sensor)) {
951 return true;
952 } else {
953 String8 errorMessage;
954 errorMessage.appendFormat(
955 "%s a sensor (%s) without holding its required permission: %s",
956 operation,
957 sensor.getName().string(),
958 sensor.getRequiredPermission().string());
959 return false;
960 }
961}
962
Aravind Akella9a844cf2014-02-11 18:58:52 -0800963void SensorService::checkWakeLockState() {
964 Mutex::Autolock _l(mLock);
965 checkWakeLockStateLocked();
966}
967
968void SensorService::checkWakeLockStateLocked() {
969 if (!mWakeLockAcquired) {
970 return;
971 }
972 bool releaseLock = true;
973 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
974 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
975 if (connection != 0) {
976 if (connection->needsWakeLock()) {
977 releaseLock = false;
978 break;
979 }
980 }
981 }
982 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700983 setWakeLockAcquiredLocked(false);
984 }
985}
986
987void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
988 Mutex::Autolock _l(mLock);
989 connection->writeToSocketFromCache();
990 if (connection->needsWakeLock()) {
991 setWakeLockAcquiredLocked(true);
992 }
993}
994
995void SensorService::populateActiveConnections(
996 SortedVector< sp<SensorEventConnection> >* activeConnections) {
997 Mutex::Autolock _l(mLock);
998 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
999 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1000 if (connection != 0) {
1001 activeConnections->add(connection);
1002 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001003 }
1004}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001005
Aravind Akella4949c502015-02-11 15:54:35 -08001006bool SensorService::isWhiteListedPackage(const String8& packageName) {
1007 // TODO: Come up with a list of packages.
1008 return (packageName.find(".cts.") != -1);
1009}
1010
Mathias Agopianfc328812010-07-14 23:41:37 -07001011// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -07001012SensorService::SensorRecord::SensorRecord(
1013 const sp<SensorEventConnection>& connection)
1014{
1015 mConnections.add(connection);
1016}
1017
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001018bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -07001019 const sp<SensorEventConnection>& connection)
1020{
1021 if (mConnections.indexOf(connection) < 0) {
1022 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001023 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001024 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001025 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001026}
1027
1028bool SensorService::SensorRecord::removeConnection(
1029 const wp<SensorEventConnection>& connection)
1030{
1031 ssize_t index = mConnections.indexOf(connection);
1032 if (index >= 0) {
1033 mConnections.removeItemsAt(index, 1);
1034 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001035 // Remove this connections from the queue of flush() calls made on this sensor.
1036 for (Vector< wp<SensorEventConnection> >::iterator it =
1037 mPendingFlushConnections.begin(); it != mPendingFlushConnections.end();) {
Aravind Akella8a969552014-09-28 17:52:41 -07001038
Aravind Akella6c2664a2014-08-13 12:24:50 -07001039 if (it->unsafe_get() == connection.unsafe_get()) {
1040 it = mPendingFlushConnections.erase(it);
1041 } else {
1042 ++it;
1043 }
1044 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001045 return mConnections.size() ? false : true;
1046}
1047
Aravind Akella6c2664a2014-08-13 12:24:50 -07001048void SensorService::SensorRecord::addPendingFlushConnection(
1049 const sp<SensorEventConnection>& connection) {
1050 mPendingFlushConnections.add(connection);
1051}
1052
1053void SensorService::SensorRecord::removeFirstPendingFlushConnection() {
1054 if (mPendingFlushConnections.size() > 0) {
1055 mPendingFlushConnections.removeAt(0);
1056 }
1057}
1058
1059SensorService::SensorEventConnection *
1060SensorService::SensorRecord::getFirstPendingFlushConnection() {
1061 if (mPendingFlushConnections.size() > 0) {
1062 return mPendingFlushConnections[0].unsafe_get();
1063 }
1064 return NULL;
1065}
1066
Aravind Akella4949c502015-02-11 15:54:35 -08001067void SensorService::SensorRecord::clearAllPendingFlushConnections() {
1068 mPendingFlushConnections.clear();
1069}
1070
Mathias Agopianfc328812010-07-14 23:41:37 -07001071// ---------------------------------------------------------------------------
1072
1073SensorService::SensorEventConnection::SensorEventConnection(
Aravind Akella4949c502015-02-11 15:54:35 -08001074 const sp<SensorService>& service, uid_t uid, String8 packageName)
Aravind Akella8a969552014-09-28 17:52:41 -07001075 : mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
Aravind Akella4949c502015-02-11 15:54:35 -08001076 mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001077 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001078#if DEBUG_CONNECTIONS
1079 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
Aravind Akellae74baf62014-08-21 12:28:35 -07001080 mTotalAcksNeeded = mTotalAcksReceived = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -07001081#endif
Mathias Agopianfc328812010-07-14 23:41:37 -07001082}
1083
Aravind Akella56ae4262014-07-10 16:01:10 -07001084SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +00001085 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akellae148bc22014-09-24 22:12:58 -07001086 mService->cleanupConnection(this);
Aravind Akella56ae4262014-07-10 16:01:10 -07001087 if (mEventCache != NULL) {
1088 delete mEventCache;
1089 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001090}
1091
Aravind Akella56ae4262014-07-10 16:01:10 -07001092void SensorService::SensorEventConnection::onFirstRef() {
1093 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -07001094}
1095
Aravind Akella9a844cf2014-02-11 18:58:52 -08001096bool SensorService::SensorEventConnection::needsWakeLock() {
1097 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001098 return !mDead && mWakeLockRefCount > 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001099}
1100
Aravind Akellab4373ac2014-10-29 17:55:20 -07001101void SensorService::SensorEventConnection::resetWakeLockRefCount() {
1102 Mutex::Autolock _l(mConnectionLock);
1103 mWakeLockRefCount = 0;
1104}
1105
Aravind Akella4c8b9512013-09-05 17:03:38 -07001106void SensorService::SensorEventConnection::dump(String8& result) {
1107 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4949c502015-02-11 15:54:35 -08001108 result.appendFormat("\t%s | WakeLockRefCount %d | uid %d | cache size %d | max cache size %d\n",
1109 mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize, mMaxCacheSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001110 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1111 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella0ec20662014-09-14 17:29:48 -07001112 result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
Aravind Akella4c8b9512013-09-05 17:03:38 -07001113 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001114 mSensorInfo.keyAt(i),
Aravind Akella4c8b9512013-09-05 17:03:38 -07001115 flushInfo.mFirstFlushPending ? "First flush pending" :
1116 "active",
Aravind Akella0ec20662014-09-14 17:29:48 -07001117 flushInfo.mPendingFlushEventsToSend);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001118 }
Aravind Akella0ec20662014-09-14 17:29:48 -07001119#if DEBUG_CONNECTIONS
1120 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d |"
1121 " total_acks_needed %d | total_acks_recvd %d\n",
1122 mEventsReceived,
1123 mEventsSent,
1124 mEventsSentFromCache,
1125 mEventsReceived - (mEventsSentFromCache + mEventsSent + mCacheSize),
1126 mTotalAcksNeeded,
1127 mTotalAcksReceived);
1128#endif
Aravind Akella4c8b9512013-09-05 17:03:38 -07001129}
1130
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001131bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001132 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +00001133 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
1134 return false;
1135 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001136 if (mSensorInfo.indexOfKey(handle) < 0) {
1137 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001138 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -07001139 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001140 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001141}
1142
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001143bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001144 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001145 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001146 return true;
1147 }
1148 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -07001149}
1150
1151bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001152 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001153 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -07001154}
1155
1156bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -08001157 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001158 return mSensorInfo.size() ? true : false;
1159}
1160
Aravind Akella8493b792014-09-08 15:45:47 -07001161bool SensorService::SensorEventConnection::hasOneShotSensors() const {
1162 Mutex::Autolock _l(mConnectionLock);
1163 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1164 const int handle = mSensorInfo.keyAt(i);
1165 if (mService->getSensorFromHandle(handle).getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1166 return true;
1167 }
1168 }
1169 return false;
1170}
1171
Aravind Akella4949c502015-02-11 15:54:35 -08001172String8 SensorService::SensorEventConnection::getPackageName() const {
1173 return mPackageName;
1174}
1175
Aravind Akella4c8b9512013-09-05 17:03:38 -07001176void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
1177 bool value) {
1178 Mutex::Autolock _l(mConnectionLock);
1179 ssize_t index = mSensorInfo.indexOfKey(handle);
1180 if (index >= 0) {
1181 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1182 flushInfo.mFirstFlushPending = value;
1183 }
1184}
1185
Aravind Akella8a969552014-09-28 17:52:41 -07001186void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
1187 Mutex::Autolock _l(mConnectionLock);
1188 updateLooperRegistrationLocked(looper);
1189}
1190
1191void SensorService::SensorEventConnection::updateLooperRegistrationLocked(
1192 const sp<Looper>& looper) {
1193 bool isConnectionActive = mSensorInfo.size() > 0;
1194 // If all sensors are unregistered OR Looper has encountered an error, we
1195 // can remove the Fd from the Looper if it has been previously added.
1196 if (!isConnectionActive || mDead) {
1197 if (mHasLooperCallbacks) {
1198 ALOGD_IF(DEBUG_CONNECTIONS, "%p removeFd fd=%d", this, mChannel->getSendFd());
1199 looper->removeFd(mChannel->getSendFd());
1200 mHasLooperCallbacks = false;
1201 }
1202 return;
1203 }
1204
1205 int looper_flags = 0;
1206 if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
1207 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1208 const int handle = mSensorInfo.keyAt(i);
1209 if (mService->getSensorFromHandle(handle).isWakeUpSensor()) {
1210 looper_flags |= ALOOPER_EVENT_INPUT;
1211 break;
1212 }
1213 }
1214 // If flags is still set to zero, we don't need to add this fd to the Looper, if
1215 // the fd has already been added, remove it. This is likely to happen when ALL the
1216 // events stored in the cache have been sent to the corresponding app.
1217 if (looper_flags == 0) {
1218 if (mHasLooperCallbacks) {
1219 ALOGD_IF(DEBUG_CONNECTIONS, "removeFd fd=%d", mChannel->getSendFd());
1220 looper->removeFd(mChannel->getSendFd());
1221 mHasLooperCallbacks = false;
1222 }
1223 return;
1224 }
1225 // Add the file descriptor to the Looper for receiving acknowledegments if the app has
1226 // registered for wake-up sensors OR for sending events in the cache.
1227 int ret = looper->addFd(mChannel->getSendFd(), 0, looper_flags, this, NULL);
1228 if (ret == 1) {
1229 ALOGD_IF(DEBUG_CONNECTIONS, "%p addFd fd=%d", this, mChannel->getSendFd());
1230 mHasLooperCallbacks = true;
1231 } else {
1232 ALOGE("Looper::addFd failed ret=%d fd=%d", ret, mChannel->getSendFd());
1233 }
1234}
1235
1236void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
1237 Mutex::Autolock _l(mConnectionLock);
1238 ssize_t index = mSensorInfo.indexOfKey(handle);
1239 if (index >= 0) {
1240 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
1241 flushInfo.mPendingFlushEventsToSend++;
1242 }
1243}
1244
Mathias Agopianfc328812010-07-14 23:41:37 -07001245status_t SensorService::SensorEventConnection::sendEvents(
Aravind Akella0ec20662014-09-14 17:29:48 -07001246 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella8493b792014-09-08 15:45:47 -07001247 sensors_event_t* scratch,
1248 SensorEventConnection const * const * mapFlushEventsToConnections) {
Mathias Agopiancf510012010-07-22 16:18:10 -07001249 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -07001250 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001251 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -07001252 if (scratch) {
1253 size_t i=0;
1254 while (i<numEvents) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001255 int32_t sensor_handle = buffer[i].sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001256 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1257 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001258 buffer[i].meta_data.sensor);
Aravind Akella8a969552014-09-28 17:52:41 -07001259 // Setting sensor_handle to the correct sensor to ensure the sensor events per
1260 // connection are filtered correctly. buffer[i].sensor is zero for meta_data
1261 // events.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001262 sensor_handle = buffer[i].meta_data.sensor;
Aravind Akella724d91d2013-06-27 12:04:23 -07001263 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001264 ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001265 // Check if this connection has registered for this sensor. If not continue to the
1266 // next sensor_event.
1267 if (index < 0) {
1268 ++i;
1269 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001270 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001271
Aravind Akella56ae4262014-07-10 16:01:10 -07001272 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001273 // Check if there is a pending flush_complete event for this sensor on this connection.
Aravind Akella8493b792014-09-08 15:45:47 -07001274 if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
1275 this == mapFlushEventsToConnections[i]) {
1276 flushInfo.mFirstFlushPending = false;
1277 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
1278 buffer[i].meta_data.sensor);
1279 ++i;
1280 continue;
Aravind Akella56ae4262014-07-10 16:01:10 -07001281 }
1282
1283 // If there is a pending flush complete event for this sensor on this connection,
1284 // ignore the event and proceed to the next.
1285 if (flushInfo.mFirstFlushPending) {
1286 ++i;
1287 continue;
1288 }
1289
1290 do {
Aravind Akella8493b792014-09-08 15:45:47 -07001291 // Keep copying events into the scratch buffer as long as they are regular
1292 // sensor_events are from the same sensor_handle OR they are flush_complete_events
1293 // from the same sensor_handle AND the current connection is mapped to the
1294 // corresponding flush_complete_event.
Aravind Akella56ae4262014-07-10 16:01:10 -07001295 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
Aravind Akella8493b792014-09-08 15:45:47 -07001296 if (this == mapFlushEventsToConnections[i]) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001297 scratch[count++] = buffer[i];
Aravind Akella56ae4262014-07-10 16:01:10 -07001298 }
1299 ++i;
1300 } else {
1301 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001302 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001303 }
Aravind Akella8493b792014-09-08 15:45:47 -07001304 } while ((i<numEvents) && ((buffer[i].sensor == sensor_handle &&
1305 buffer[i].type != SENSOR_TYPE_META_DATA) ||
Aravind Akella56ae4262014-07-10 16:01:10 -07001306 (buffer[i].type == SENSOR_TYPE_META_DATA &&
Aravind Akella6c2664a2014-08-13 12:24:50 -07001307 buffer[i].meta_data.sensor == sensor_handle)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001308 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001309 } else {
1310 scratch = const_cast<sensors_event_t *>(buffer);
1311 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001312 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001313
Aravind Akella6c2664a2014-08-13 12:24:50 -07001314 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001315 // Early return if there are no events for this connection.
1316 if (count == 0) {
1317 return status_t(NO_ERROR);
1318 }
1319
1320#if DEBUG_CONNECTIONS
1321 mEventsReceived += count;
1322#endif
1323 if (mCacheSize != 0) {
1324 // There are some events in the cache which need to be sent first. Copy this buffer to
1325 // the end of cache.
1326 if (mCacheSize + count <= mMaxCacheSize) {
1327 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1328 mCacheSize += count;
1329 } else {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001330 // Check if any new sensors have registered on this connection which may have increased
1331 // the max cache size that is desired.
1332 if (mCacheSize + count < computeMaxCacheSizeLocked()) {
1333 reAllocateCacheLocked(scratch, count);
1334 return status_t(NO_ERROR);
1335 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001336 // Some events need to be dropped.
1337 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1338 if (remaningCacheSize != 0) {
1339 memcpy(&mEventCache[mCacheSize], scratch,
1340 remaningCacheSize * sizeof(sensors_event_t));
1341 }
1342 int numEventsDropped = count - remaningCacheSize;
1343 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1344 // Drop the first "numEventsDropped" in the cache.
1345 memmove(mEventCache, &mEventCache[numEventsDropped],
1346 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1347
1348 // Copy the remainingEvents in scratch buffer to the end of cache.
1349 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1350 numEventsDropped * sizeof(sensors_event_t));
1351 }
1352 return status_t(NO_ERROR);
1353 }
1354
Aravind Akella6c2664a2014-08-13 12:24:50 -07001355 int index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
1356 if (index_wake_up_event >= 0) {
1357 scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1358 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001359#if DEBUG_CONNECTIONS
1360 ++mTotalAcksNeeded;
1361#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001362 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001363
1364 // NOTE: ASensorEvent and sensors_event_t are the same type.
1365 ssize_t size = SensorEventQueue::write(mChannel,
1366 reinterpret_cast<ASensorEvent const*>(scratch), count);
1367 if (size < 0) {
1368 // Write error, copy events to local cache.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001369 if (index_wake_up_event >= 0) {
1370 // If there was a wake_up sensor_event, reset the flag.
1371 scratch[index_wake_up_event].flags &= ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001372 if (mWakeLockRefCount > 0) {
1373 --mWakeLockRefCount;
1374 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001375#if DEBUG_CONNECTIONS
1376 --mTotalAcksNeeded;
1377#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001378 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001379 if (mEventCache == NULL) {
1380 mMaxCacheSize = computeMaxCacheSizeLocked();
1381 mEventCache = new sensors_event_t[mMaxCacheSize];
1382 mCacheSize = 0;
1383 }
1384 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1385 mCacheSize += count;
1386
1387 // Add this file descriptor to the looper to get a callback when this fd is available for
1388 // writing.
Aravind Akella8a969552014-09-28 17:52:41 -07001389 updateLooperRegistrationLocked(mService->getLooper());
Aravind Akella56ae4262014-07-10 16:01:10 -07001390 return size;
1391 }
1392
1393#if DEBUG_CONNECTIONS
1394 if (size > 0) {
1395 mEventsSent += count;
1396 }
1397#endif
1398
1399 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1400}
1401
Aravind Akella6c2664a2014-08-13 12:24:50 -07001402void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
1403 int count) {
1404 sensors_event_t *eventCache_new;
1405 const int new_cache_size = computeMaxCacheSizeLocked();
1406 // Allocate new cache, copy over events from the old cache & scratch, free up memory.
1407 eventCache_new = new sensors_event_t[new_cache_size];
1408 memcpy(eventCache_new, mEventCache, mCacheSize * sizeof(sensors_event_t));
1409 memcpy(&eventCache_new[mCacheSize], scratch, count * sizeof(sensors_event_t));
1410
1411 ALOGD_IF(DEBUG_CONNECTIONS, "reAllocateCacheLocked maxCacheSize=%d %d", mMaxCacheSize,
1412 new_cache_size);
1413
1414 delete mEventCache;
1415 mEventCache = eventCache_new;
1416 mCacheSize += count;
1417 mMaxCacheSize = new_cache_size;
1418}
1419
1420void SensorService::SensorEventConnection::sendPendingFlushEventsLocked() {
1421 ASensorEvent flushCompleteEvent;
Aravind Akella0ec20662014-09-14 17:29:48 -07001422 memset(&flushCompleteEvent, 0, sizeof(flushCompleteEvent));
Aravind Akella6c2664a2014-08-13 12:24:50 -07001423 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001424 // Loop through all the sensors for this connection and check if there are any pending
1425 // flush complete events to be sent.
1426 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1427 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1428 while (flushInfo.mPendingFlushEventsToSend > 0) {
Aravind Akella0ec20662014-09-14 17:29:48 -07001429 const int sensor_handle = mSensorInfo.keyAt(i);
1430 flushCompleteEvent.meta_data.sensor = sensor_handle;
Aravind Akellab4373ac2014-10-29 17:55:20 -07001431 bool wakeUpSensor = mService->getSensorFromHandle(sensor_handle).isWakeUpSensor();
1432 if (wakeUpSensor) {
1433 ++mWakeLockRefCount;
Aravind Akella0ec20662014-09-14 17:29:48 -07001434 flushCompleteEvent.flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1435 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001436 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1437 if (size < 0) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001438 if (wakeUpSensor) --mWakeLockRefCount;
Aravind Akella6c2664a2014-08-13 12:24:50 -07001439 return;
1440 }
1441 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
1442 flushCompleteEvent.meta_data.sensor);
1443 flushInfo.mPendingFlushEventsToSend--;
1444 }
1445 }
1446}
1447
Aravind Akellab4373ac2014-10-29 17:55:20 -07001448void SensorService::SensorEventConnection::writeToSocketFromCache() {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001449 // At a time write at most half the size of the receiver buffer in SensorEventQueue OR
1450 // half the size of the socket buffer allocated in BitTube whichever is smaller.
1451 const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
1452 int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
Aravind Akellab4373ac2014-10-29 17:55:20 -07001453 Mutex::Autolock _l(mConnectionLock);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001454 // Send pending flush complete events (if any)
Aravind Akella6c2664a2014-08-13 12:24:50 -07001455 sendPendingFlushEventsLocked();
Aravind Akella56ae4262014-07-10 16:01:10 -07001456 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
Aravind Akella5466c3d2014-08-22 16:11:10 -07001457 const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001458 int index_wake_up_event =
1459 findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
1460 if (index_wake_up_event >= 0) {
1461 mEventCache[index_wake_up_event + numEventsSent].flags |=
1462 WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1463 ++mWakeLockRefCount;
Aravind Akellae74baf62014-08-21 12:28:35 -07001464#if DEBUG_CONNECTIONS
1465 ++mTotalAcksNeeded;
1466#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001467 }
Aravind Akella4c8b9512013-09-05 17:03:38 -07001468
Aravind Akella56ae4262014-07-10 16:01:10 -07001469 ssize_t size = SensorEventQueue::write(mChannel,
1470 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
Aravind Akella6c2664a2014-08-13 12:24:50 -07001471 numEventsToWrite);
Aravind Akella56ae4262014-07-10 16:01:10 -07001472 if (size < 0) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001473 if (index_wake_up_event >= 0) {
1474 // If there was a wake_up sensor_event, reset the flag.
1475 mEventCache[index_wake_up_event + numEventsSent].flags &=
1476 ~WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella0ec20662014-09-14 17:29:48 -07001477 if (mWakeLockRefCount > 0) {
1478 --mWakeLockRefCount;
1479 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001480#if DEBUG_CONNECTIONS
1481 --mTotalAcksNeeded;
1482#endif
Aravind Akella6c2664a2014-08-13 12:24:50 -07001483 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001484 memmove(mEventCache, &mEventCache[numEventsSent],
1485 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1486 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
Aravind Akella6c2664a2014-08-13 12:24:50 -07001487 numEventsSent, mCacheSize);
Aravind Akella56ae4262014-07-10 16:01:10 -07001488 mCacheSize -= numEventsSent;
Aravind Akella56ae4262014-07-10 16:01:10 -07001489 return;
1490 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001491 numEventsSent += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001492#if DEBUG_CONNECTIONS
Aravind Akella6c2664a2014-08-13 12:24:50 -07001493 mEventsSentFromCache += numEventsToWrite;
Aravind Akella56ae4262014-07-10 16:01:10 -07001494#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001495 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001496 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1497 // All events from the cache have been sent. Reset cache size to zero.
1498 mCacheSize = 0;
Aravind Akella8a969552014-09-28 17:52:41 -07001499 // There are no more events in the cache. We don't need to poll for write on the fd.
1500 // Update Looper registration.
1501 updateLooperRegistrationLocked(mService->getLooper());
Mathias Agopianfc328812010-07-14 23:41:37 -07001502}
1503
Aravind Akellac551eac2013-10-14 17:04:42 -07001504void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella0ec20662014-09-14 17:29:48 -07001505 sensors_event_t const* scratch, const int numEventsDropped) {
Aravind Akella4c8b9512013-09-05 17:03:38 -07001506 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001507 // Count flushComplete events in the events that are about to the dropped. These will be sent
1508 // separately before the next batch of events.
1509 for (int j = 0; j < numEventsDropped; ++j) {
1510 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1511 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1512 flushInfo.mPendingFlushEventsToSend++;
1513 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1514 flushInfo.mPendingFlushEventsToSend);
1515 }
1516 }
1517 return;
1518}
1519
Aravind Akella6c2664a2014-08-13 12:24:50 -07001520int SensorService::SensorEventConnection::findWakeUpSensorEventLocked(
1521 sensors_event_t const* scratch, const int count) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001522 for (int i = 0; i < count; ++i) {
1523 if (mService->isWakeUpSensorEvent(scratch[i])) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001524 return i;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001525 }
1526 }
Aravind Akella6c2664a2014-08-13 12:24:50 -07001527 return -1;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001528}
1529
Mathias Agopianb3989272011-10-20 18:42:02 -07001530sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001531{
1532 return mChannel;
1533}
1534
1535status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001536 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1537 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001538{
1539 status_t err;
1540 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001541 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1542 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001543
Mathias Agopianfc328812010-07-14 23:41:37 -07001544 } else {
1545 err = mService->disable(this, handle);
1546 }
1547 return err;
1548}
1549
1550status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001551 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001552{
Aravind Akella724d91d2013-06-27 12:04:23 -07001553 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001554}
1555
Aravind Akella701166d2013-10-08 14:59:26 -07001556status_t SensorService::SensorEventConnection::flush() {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001557 return mService->flushSensor(this);
Aravind Akella724d91d2013-06-27 12:04:23 -07001558}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001559
Aravind Akella8a969552014-09-28 17:52:41 -07001560int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* /*data*/) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001561 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
Aravind Akella8a969552014-09-28 17:52:41 -07001562 {
1563 // If the Looper encounters some error, set the flag mDead, reset mWakeLockRefCount,
1564 // and remove the fd from Looper. Call checkWakeLockState to know if SensorService
1565 // can release the wake-lock.
1566 ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
1567 Mutex::Autolock _l(mConnectionLock);
1568 mDead = true;
1569 mWakeLockRefCount = 0;
1570 updateLooperRegistrationLocked(mService->getLooper());
1571 }
1572 mService->checkWakeLockState();
1573 return 1;
Aravind Akella56ae4262014-07-10 16:01:10 -07001574 }
1575
1576 if (events & ALOOPER_EVENT_INPUT) {
Aravind Akella8a969552014-09-28 17:52:41 -07001577 uint32_t numAcks = 0;
1578 ssize_t ret = ::recv(fd, &numAcks, sizeof(numAcks), MSG_DONTWAIT);
Aravind Akella56ae4262014-07-10 16:01:10 -07001579 {
1580 Mutex::Autolock _l(mConnectionLock);
Aravind Akella8a969552014-09-28 17:52:41 -07001581 // Sanity check to ensure there are no read errors in recv, numAcks is always
1582 // within the range and not zero. If any of the above don't hold reset mWakeLockRefCount
1583 // to zero.
1584 if (ret != sizeof(numAcks) || numAcks > mWakeLockRefCount || numAcks == 0) {
1585 ALOGE("Looper read error ret=%d numAcks=%d", ret, numAcks);
1586 mWakeLockRefCount = 0;
1587 } else {
1588 mWakeLockRefCount -= numAcks;
Aravind Akella0ec20662014-09-14 17:29:48 -07001589 }
Aravind Akellae74baf62014-08-21 12:28:35 -07001590#if DEBUG_CONNECTIONS
Aravind Akella8a969552014-09-28 17:52:41 -07001591 mTotalAcksReceived += numAcks;
Aravind Akellae74baf62014-08-21 12:28:35 -07001592#endif
Aravind Akella56ae4262014-07-10 16:01:10 -07001593 }
1594 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1595 // here as checkWakeLockState() will need it.
1596 if (mWakeLockRefCount == 0) {
1597 mService->checkWakeLockState();
1598 }
1599 // continue getting callbacks.
1600 return 1;
1601 }
1602
1603 if (events & ALOOPER_EVENT_OUTPUT) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001604 // send sensor data that is stored in mEventCache for this connection.
1605 mService->sendEventsFromCache(this);
Aravind Akella9a844cf2014-02-11 18:58:52 -08001606 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001607 return 1;
1608}
1609
1610int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1611 int fifoWakeUpSensors = 0;
1612 int fifoNonWakeUpSensors = 0;
1613 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1614 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1615 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1616 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1617 // non wake_up sensors.
1618 if (sensor.isWakeUpSensor()) {
1619 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1620 } else {
1621 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1622 }
1623 } else {
1624 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1625 if (sensor.isWakeUpSensor()) {
1626 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1627 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1628
1629 } else {
1630 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1631 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1632
1633 }
1634 }
1635 }
1636 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1637 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
Aravind Akella6c2664a2014-08-13 12:24:50 -07001638 // size that is equal to that of the batch mode.
Aravind Akellae74baf62014-08-21 12:28:35 -07001639 // ALOGW("Write failure in non-batch mode");
Aravind Akella6c2664a2014-08-13 12:24:50 -07001640 return MAX_SOCKET_BUFFER_SIZE_BATCHED/sizeof(sensors_event_t);
Aravind Akella56ae4262014-07-10 16:01:10 -07001641 }
1642 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001643}
1644
Mathias Agopianfc328812010-07-14 23:41:37 -07001645// ---------------------------------------------------------------------------
1646}; // namespace android
1647