blob: aff4e9a508602d109b0470a035842747bad051fd [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>
21
Mathias Agopian33015422011-05-27 18:18:13 -070022#include <cutils/properties.h>
23
Mathias Agopianfc328812010-07-14 23:41:37 -070024#include <utils/SortedVector.h>
25#include <utils/KeyedVector.h>
26#include <utils/threads.h>
27#include <utils/Atomic.h>
28#include <utils/Errors.h>
29#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070030#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070031#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070032
33#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070034#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070035#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070036
37#include <gui/ISensorServer.h>
38#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070039#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070040
41#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070042#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070043
Mathias Agopian787ac1b2012-09-18 18:49:18 -070044#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070045#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080046#include "GravitySensor.h"
47#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070048#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080049#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070050#include "SensorFusion.h"
51#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070052
53namespace android {
54// ---------------------------------------------------------------------------
55
Mathias Agopian33015422011-05-27 18:18:13 -070056/*
57 * Notes:
58 *
59 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070060 * - run mag sensor from time to time to force calibration
61 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
62 *
63 */
64
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070065const char* SensorService::WAKE_LOCK_NAME = "SensorService";
66
Mathias Agopianfc328812010-07-14 23:41:37 -070067SensorService::SensorService()
Mathias Agopian1cb13462011-06-27 16:05:52 -070068 : mInitCheck(NO_INIT)
Mathias Agopianfc328812010-07-14 23:41:37 -070069{
70}
71
72void SensorService::onFirstRef()
73{
Steve Blocka5512372011-12-20 16:23:08 +000074 ALOGD("nuSensorService starting...");
Mathias Agopian50df2952010-07-19 19:09:10 -070075
Mathias Agopianf001c922010-11-11 17:58:51 -080076 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070077
Mathias Agopianf001c922010-11-11 17:58:51 -080078 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080079 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070080 ssize_t count = dev.getSensorList(&list);
81 if (count > 0) {
82 ssize_t orientationIndex = -1;
83 bool hasGyro = false;
84 uint32_t virtualSensorsNeeds =
85 (1<<SENSOR_TYPE_GRAVITY) |
86 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
87 (1<<SENSOR_TYPE_ROTATION_VECTOR);
88
89 mLastEventSeen.setCapacity(count);
90 for (ssize_t i=0 ; i<count ; i++) {
91 registerSensor( new HardwareSensor(list[i]) );
92 switch (list[i].type) {
93 case SENSOR_TYPE_ORIENTATION:
94 orientationIndex = i;
95 break;
96 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -070097 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070098 hasGyro = true;
99 break;
100 case SENSOR_TYPE_GRAVITY:
101 case SENSOR_TYPE_LINEAR_ACCELERATION:
102 case SENSOR_TYPE_ROTATION_VECTOR:
103 virtualSensorsNeeds &= ~(1<<list[i].type);
104 break;
105 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700106 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700107
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700108 // it's safe to instantiate the SensorFusion object here
109 // (it wants to be instantiated after h/w sensors have been
110 // registered)
111 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700112
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700113 // build the sensor list returned to users
114 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700115
116 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700117 Sensor aSensor;
118
119 // Add Android virtual sensors if they're not already
120 // available in the HAL
121
122 aSensor = registerVirtualSensor( new RotationVectorSensor() );
123 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
124 mUserSensorList.add(aSensor);
125 }
126
127 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
128 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
129 mUserSensorList.add(aSensor);
130 }
131
132 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
133 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
134 mUserSensorList.add(aSensor);
135 }
136
137 aSensor = registerVirtualSensor( new OrientationSensor() );
138 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
139 // if we are doing our own rotation-vector, also add
140 // the orientation sensor and remove the HAL provided one.
141 mUserSensorList.replaceAt(aSensor, orientationIndex);
142 }
143
Mathias Agopian33264862012-06-28 19:46:54 -0700144 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700145 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700146 registerVirtualSensor( new GyroDriftSensor() );
147 }
148
Mathias Agopian33264862012-06-28 19:46:54 -0700149 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700150 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700151
Aravind Akella4c8b9512013-09-05 17:03:38 -0700152 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
153 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
154 char line[128];
155 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
156 line[sizeof(line) - 1] = '\0';
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700157 sscanf(line, "%zu", &mSocketBufferSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700158 if (mSocketBufferSize > MAX_SOCKET_BUFFER_SIZE_BATCHED) {
159 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
160 }
161 }
162 ALOGD("Max socket buffer size %u", mSocketBufferSize);
163 if (fp) {
164 fclose(fp);
165 }
166
Aravind Akella9a844cf2014-02-11 18:58:52 -0800167 mWakeLockAcquired = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700168 run("SensorService", PRIORITY_URGENT_DISPLAY);
169 mInitCheck = NO_ERROR;
170 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700171 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700172}
173
Mathias Agopian03193062013-05-10 19:32:39 -0700174Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800175{
176 sensors_event_t event;
177 memset(&event, 0, sizeof(event));
178
179 const Sensor sensor(s->getSensor());
180 // add to the sensor list (returned to clients)
181 mSensorList.add(sensor);
182 // add to our handle->SensorInterface mapping
183 mSensorMap.add(sensor.getHandle(), s);
184 // create an entry in the mLastEventSeen array
185 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700186
187 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800188}
189
Mathias Agopian03193062013-05-10 19:32:39 -0700190Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800191{
Mathias Agopian03193062013-05-10 19:32:39 -0700192 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800193 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700194 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800195}
196
Mathias Agopianfc328812010-07-14 23:41:37 -0700197SensorService::~SensorService()
198{
Mathias Agopianf001c922010-11-11 17:58:51 -0800199 for (size_t i=0 ; i<mSensorMap.size() ; i++)
200 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700201}
202
Mathias Agopian1cb13462011-06-27 16:05:52 -0700203static const String16 sDump("android.permission.DUMP");
204
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700205status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700206{
Mathias Agopianfc328812010-07-14 23:41:37 -0700207 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700208 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700209 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000210 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700211 IPCThreadState::self()->getCallingPid(),
212 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700213 } else {
214 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700215 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700216 for (size_t i=0 ; i<mSensorList.size() ; i++) {
217 const Sensor& s(mSensorList[i]);
218 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700219 result.appendFormat(
Aravind Akella70018042014-04-07 22:52:37 +0000220 "%-48s| %-32s| %-48s| 0x%08x | \"%s\"\n\t",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700221 s.getName().string(),
222 s.getVendor().string(),
Aravind Akella70018042014-04-07 22:52:37 +0000223 s.getStringType().string(),
224 s.getHandle(),
225 s.getRequiredPermission().string());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700226
Mathias Agopianba02cd22013-07-03 16:20:57 -0700227 if (s.getMinDelay() > 0) {
228 result.appendFormat(
Aravind Akella70018042014-04-07 22:52:37 +0000229 "maxRate=%7.2fHz | ", 1e6f / s.getMinDelay());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700230 } else {
231 result.append(s.getMinDelay() == 0
232 ? "on-demand | "
233 : "one-shot | ");
234 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700235 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000236 result.appendFormat("FifoMax=%d events | ",
237 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700238 } else {
239 result.append("no batching support | ");
240 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700241
242 switch (s.getType()) {
243 case SENSOR_TYPE_ROTATION_VECTOR:
244 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
245 result.appendFormat(
246 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
247 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]);
248 break;
249 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
250 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
251 result.appendFormat(
252 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
253 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]);
254 break;
255 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
256 result.appendFormat(
257 "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n",
258 e.data[0], e.data[1], e.data[2], e.data[3]);
259 break;
260 case SENSOR_TYPE_SIGNIFICANT_MOTION:
261 case SENSOR_TYPE_STEP_DETECTOR:
262 result.appendFormat( "last=<%f>\n", e.data[0]);
263 break;
264 case SENSOR_TYPE_STEP_COUNTER:
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700265 result.appendFormat( "last=<%" PRIu64 ">\n", e.u64.step_counter);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700266 break;
267 default:
268 // default to 3 values
269 result.appendFormat(
270 "last=<%5.1f,%5.1f,%5.1f>\n",
271 e.data[0], e.data[1], e.data[2]);
272 break;
273 }
274 }
275 SensorFusion::getInstance().dump(result);
276 SensorDevice::getInstance().dump(result);
277
Mathias Agopianba02cd22013-07-03 16:20:57 -0700278 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700279 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700280 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700281 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700282 getSensorName(handle).string(),
283 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700284 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700285 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700286
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700287 result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800288 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700289 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700290
291 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
292 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
293 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700294 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700295 connection->dump(result);
296 }
297 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700298 }
299 write(fd, result.string(), result.size());
300 return NO_ERROR;
301}
302
Aravind Akella9a844cf2014-02-11 18:58:52 -0800303void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700304 sensors_event_t const* buffer, const int count) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700305 SensorInterface* sensor;
306 status_t err = NO_ERROR;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700307 for (int i=0 ; i<count ; i++) {
308 int handle = buffer[i].sensor;
Mathias Agopian7438fd12013-07-08 12:50:39 -0700309 int type = buffer[i].type;
310 if (type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700311 if (connection->hasSensor(handle)) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700312 sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700313 if (sensor != NULL) {
314 sensor->autoDisable(connection.get(), handle);
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700315 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800316 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700317 }
318 }
319 }
320}
321
Mathias Agopianfc328812010-07-14 23:41:37 -0700322bool SensorService::threadLoop()
323{
Steve Blocka5512372011-12-20 16:23:08 +0000324 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700325
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700326 // each virtual sensor could generate an event per "real" event, that's why we need
327 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
328 // in practice, this is too aggressive, but guaranteed to be enough.
329 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
330 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
331
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700332 sensors_event_t buffer[minBufferSize];
333 sensors_event_t scratch[minBufferSize];
Mathias Agopianf001c922010-11-11 17:58:51 -0800334 SensorDevice& device(SensorDevice::getInstance());
335 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700336
Mathias Agopianf001c922010-11-11 17:58:51 -0800337 ssize_t count;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700338 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700339 do {
Mathias Agopianf001c922010-11-11 17:58:51 -0800340 count = device.poll(buffer, numEventMax);
Mathias Agopianfc328812010-07-14 23:41:37 -0700341 if (count<0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000342 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700343 break;
344 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800345 Mutex::Autolock _l(mLock);
346 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
347 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
348 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
349 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
350 // releasing the wakelock.
351 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700352 for (int i = 0; i < count; i++) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800353 if (isWakeUpSensorEvent(buffer[i])) {
354 bufferHasWakeUpEvent = true;
355 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700356 }
357 }
358
Aravind Akella9a844cf2014-02-11 18:58:52 -0800359 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
360 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
361 mWakeLockAcquired = true;
362 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
363 }
364 recordLastValueLocked(buffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800365
Mathias Agopianf001c922010-11-11 17:58:51 -0800366 // handle virtual sensors
367 if (count && vcount) {
Mathias Agopian984826c2011-05-17 22:54:42 -0700368 sensors_event_t const * const event = buffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800369 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800370 if (activeVirtualSensorCount) {
371 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700372 SensorFusion& fusion(SensorFusion::getInstance());
373 if (fusion.isEnabled()) {
374 for (size_t i=0 ; i<size_t(count) ; i++) {
375 fusion.process(event[i]);
376 }
377 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700378 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800379 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700380 if (count + k >= minBufferSize) {
381 ALOGE("buffer too small to hold all events: "
382 "count=%u, k=%u, size=%u",
383 count, k, minBufferSize);
384 break;
385 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800386 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800387 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700388 if (si->process(&out, event[i])) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800389 buffer[count + k] = out;
390 k++;
391 }
392 }
393 }
394 if (k) {
395 // record the last synthesized values
Aravind Akella9a844cf2014-02-11 18:58:52 -0800396 recordLastValueLocked(&buffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800397 count += k;
398 // sort the buffer by time-stamps
399 sortEventBuffer(buffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700400 }
401 }
402 }
403
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700404 // handle backward compatibility for RotationVector sensor
405 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
406 for (int i = 0; i < count; i++) {
Mathias Agopian7438fd12013-07-08 12:50:39 -0700407 if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700408 // All the 4 components of the quaternion should be available
409 // No heading accuracy. Set it to -1
410 buffer[i].data[4] = -1;
411 }
412 }
413 }
414
Aravind Akella9a844cf2014-02-11 18:58:52 -0800415 // Send our events to clients. Check the state of wake lock for each client and release the
416 // lock if none of the clients need it.
417 bool needsWakeLock = false;
418 for (size_t i=0 ; i < mActiveConnections.size(); i++) {
419 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Mathias Agopianf001c922010-11-11 17:58:51 -0800420 if (connection != 0) {
421 connection->sendEvents(buffer, count, scratch);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800422 needsWakeLock |= connection->needsWakeLock();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700423 // Some sensors need to be auto disabled after the trigger
Aravind Akella9a844cf2014-02-11 18:58:52 -0800424 cleanupAutoDisabledSensorLocked(connection, buffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800425 }
426 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700427
Aravind Akella9a844cf2014-02-11 18:58:52 -0800428 if (mWakeLockAcquired && !needsWakeLock) {
429 release_wake_lock(WAKE_LOCK_NAME);
430 mWakeLockAcquired = false;
431 ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
432 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700433 } while (count >= 0 || Thread::exitPending());
434
Steve Block3c20fbe2012-01-05 23:22:43 +0000435 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800436 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700437 return false;
438}
439
Aravind Akella9a844cf2014-02-11 18:58:52 -0800440void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800441 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800442 const sensors_event_t* last = NULL;
443 for (size_t i = 0; i < count; i++) {
444 const sensors_event_t* event = &buffer[i];
445 if (event->type != SENSOR_TYPE_META_DATA) {
446 if (last && event->sensor != last->sensor) {
447 mLastEventSeen.editValueFor(last->sensor) = *last;
448 }
449 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800450 }
451 }
Aravind Akella4b847042014-03-03 19:02:46 -0800452 if (last) {
453 mLastEventSeen.editValueFor(last->sensor) = *last;
454 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800455}
456
Mathias Agopianf001c922010-11-11 17:58:51 -0800457void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
458{
459 struct compar {
460 static int cmp(void const* lhs, void const* rhs) {
461 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
462 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700463 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800464 }
465 };
466 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
467}
468
Mathias Agopian5d270722010-07-19 15:20:39 -0700469String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700470 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700471 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700472 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700473 if (sensor.getHandle() == handle) {
474 return sensor.getName();
475 }
476 }
477 String8 result("unknown");
478 return result;
479}
480
Aravind Akellab4099e72013-10-15 15:43:10 -0700481bool SensorService::isVirtualSensor(int handle) const {
482 SensorInterface* sensor = mSensorMap.valueFor(handle);
483 return sensor->isVirtual();
484}
485
Aravind Akella9a844cf2014-02-11 18:58:52 -0800486bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
487 SensorInterface* sensor = mSensorMap.valueFor(event.sensor);
488 return sensor->getSensor().isWakeUpSensor();
489}
490
Mathias Agopianfc328812010-07-14 23:41:37 -0700491Vector<Sensor> SensorService::getSensorList()
492{
Mathias Agopian33264862012-06-28 19:46:54 -0700493 char value[PROPERTY_VALUE_MAX];
494 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000495 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
496 mUserSensorListDebug : mUserSensorList;
497 Vector<Sensor> accessibleSensorList;
498 for (size_t i = 0; i < initialSensorList.size(); i++) {
499 Sensor sensor = initialSensorList[i];
500 if (canAccessSensor(sensor)) {
501 accessibleSensorList.add(sensor);
502 } else {
503 String8 infoMessage;
504 infoMessage.appendFormat(
505 "Skipped sensor %s because it requires permission %s",
506 sensor.getName().string(),
507 sensor.getRequiredPermission().string());
508 ALOGI(infoMessage.string());
509 }
Mathias Agopian33264862012-06-28 19:46:54 -0700510 }
Aravind Akella70018042014-04-07 22:52:37 +0000511 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700512}
513
514sp<ISensorEventConnection> SensorService::createSensorEventConnection()
515{
Mathias Agopian5307d172012-09-18 17:02:43 -0700516 uid_t uid = IPCThreadState::self()->getCallingUid();
517 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700518 return result;
519}
520
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800521void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700522{
523 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800524 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700525 size_t size = mActiveSensors.size();
Steve Blocka5512372011-12-20 16:23:08 +0000526 ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700527 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800528 int handle = mActiveSensors.keyAt(i);
529 if (c->hasSensor(handle)) {
Steve Blocka5512372011-12-20 16:23:08 +0000530 ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800531 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000532 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800533 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800534 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800535 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800536 }
537 SensorRecord* rec = mActiveSensors.valueAt(i);
Steve Blockf5a12302012-01-06 19:20:56 +0000538 ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000539 ALOGD_IF(DEBUG_CONNECTIONS,
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700540 "removing connection %p for sensor[%d].handle=0x%08x",
541 c, i, handle);
542
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800543 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000544 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700545 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800546 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700547 delete rec;
548 size--;
549 } else {
550 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700551 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700552 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700553 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700554 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800555 if (c->needsWakeLock()) {
556 checkWakeLockStateLocked();
557 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700558}
559
Aravind Akella70018042014-04-07 22:52:37 +0000560Sensor SensorService::getSensorFromHandle(int handle) const {
561 return mSensorMap.valueFor(handle)->getSensor();
562}
563
Mathias Agopianfc328812010-07-14 23:41:37 -0700564status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700565 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700566{
Mathias Agopian50df2952010-07-19 19:09:10 -0700567 if (mInitCheck != NO_ERROR)
568 return mInitCheck;
569
Mathias Agopianf001c922010-11-11 17:58:51 -0800570 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700571 if (sensor == NULL) {
572 return BAD_VALUE;
573 }
Aravind Akella70018042014-04-07 22:52:37 +0000574
575 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
576 return BAD_VALUE;
577 }
578
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700579 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700580 SensorRecord* rec = mActiveSensors.valueFor(handle);
581 if (rec == 0) {
582 rec = new SensorRecord(connection);
583 mActiveSensors.add(handle, rec);
584 if (sensor->isVirtual()) {
585 mActiveVirtualSensors.add(handle, sensor);
586 }
587 } else {
588 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800589 // this sensor is already activated, but we are adding a connection that uses it.
590 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700591 // "continuous" sensor.
592 if (sensor->getSensor().getMinDelay() == 0) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800593 // NOTE: The wake_up flag of this event may get set to
594 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700595 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
596 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800597 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
598 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
599 mWakeLockAcquired = true;
600 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
601 WAKE_LOCK_NAME);
602 }
603 connection->sendEvents(&event, 1, NULL);
604 if (!connection->needsWakeLock() && mWakeLockAcquired) {
605 checkWakeLockStateLocked();
606 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700607 }
608 }
609 }
610 }
611
612 if (connection->addSensor(handle)) {
613 BatteryService::enableSensor(connection->getUid(), handle);
614 // the sensor was added (which means it wasn't already there)
615 // so, see if this connection becomes active
616 if (mActiveConnections.indexOf(connection) < 0) {
617 mActiveConnections.add(connection);
618 }
619 } else {
620 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
621 handle, connection.get());
622 }
623
Aravind Akella724d91d2013-06-27 12:04:23 -0700624 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
625 if (samplingPeriodNs < minDelayNs) {
626 samplingPeriodNs = minDelayNs;
627 }
628
629 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld",
630 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
631
632 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
633 maxBatchReportLatencyNs);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700634 if (err == NO_ERROR) {
635 connection->setFirstFlushPending(handle, true);
636 status_t err_flush = sensor->flush(connection.get(), handle);
637 // Flush may return error if the sensor is not activated or the underlying h/w sensor does
638 // not support flush.
639 if (err_flush != NO_ERROR) {
640 connection->setFirstFlushPending(handle, false);
641 }
642 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700643
644 if (err == NO_ERROR) {
645 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
646 err = sensor->activate(connection.get(), true);
647 }
648
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700649 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700650 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700651 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700652 }
653 return err;
654}
655
656status_t SensorService::disable(const sp<SensorEventConnection>& connection,
657 int handle)
658{
Mathias Agopian50df2952010-07-19 19:09:10 -0700659 if (mInitCheck != NO_ERROR)
660 return mInitCheck;
661
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700662 Mutex::Autolock _l(mLock);
663 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700664 if (err == NO_ERROR) {
665 SensorInterface* sensor = mSensorMap.valueFor(handle);
666 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
667 }
668 return err;
669}
670
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700671status_t SensorService::cleanupWithoutDisable(
672 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700673 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700674 return cleanupWithoutDisableLocked(connection, handle);
675}
676
677status_t SensorService::cleanupWithoutDisableLocked(
678 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700679 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700680 if (rec) {
681 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700682 if (connection->removeSensor(handle)) {
683 BatteryService::disableSensor(connection->getUid(), handle);
684 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700685 if (connection->hasAnySensor() == false) {
686 mActiveConnections.remove(connection);
687 }
688 // see if this sensor becomes inactive
689 if (rec->removeConnection(connection)) {
690 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800691 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700692 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700693 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700694 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700695 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700696 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700697}
698
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700699status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700700 int handle, nsecs_t ns)
701{
Mathias Agopian50df2952010-07-19 19:09:10 -0700702 if (mInitCheck != NO_ERROR)
703 return mInitCheck;
704
Mathias Agopianae09d652011-11-01 17:37:49 -0700705 SensorInterface* sensor = mSensorMap.valueFor(handle);
706 if (!sensor)
707 return BAD_VALUE;
708
Aravind Akella70018042014-04-07 22:52:37 +0000709 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
710 return BAD_VALUE;
711 }
712
Mathias Agopian1cd70002010-07-21 15:59:50 -0700713 if (ns < 0)
714 return BAD_VALUE;
715
Mathias Agopian62569ec2011-11-07 21:21:47 -0800716 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
717 if (ns < minDelayNs) {
718 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700719 }
720
Mathias Agopianf001c922010-11-11 17:58:51 -0800721 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700722}
723
Aravind Akella724d91d2013-06-27 12:04:23 -0700724status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
725 int handle) {
Aravind Akella70018042014-04-07 22:52:37 +0000726 if (mInitCheck != NO_ERROR) return mInitCheck;
727 SensorInterface* sensor = mSensorMap.valueFor(handle);
728 if (sensor == NULL) {
729 return BAD_VALUE;
730 }
731
732 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried flushing")) {
733 return BAD_VALUE;
734 }
735
736 if (sensor->getSensor().getType() == SENSOR_TYPE_SIGNIFICANT_MOTION) {
737 ALOGE("flush called on Significant Motion sensor");
738 return INVALID_OPERATION;
739 }
740 return sensor->flush(connection.get(), handle);
Aravind Akella724d91d2013-06-27 12:04:23 -0700741}
Aravind Akella70018042014-04-07 22:52:37 +0000742
743
744bool SensorService::canAccessSensor(const Sensor& sensor) {
745 String16 permissionString(sensor.getRequiredPermission());
746 return permissionString.size() == 0 ||
747 PermissionCache::checkCallingPermission(permissionString);
748}
749
750bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
751 if (canAccessSensor(sensor)) {
752 return true;
753 } else {
754 String8 errorMessage;
755 errorMessage.appendFormat(
756 "%s a sensor (%s) without holding its required permission: %s",
757 operation,
758 sensor.getName().string(),
759 sensor.getRequiredPermission().string());
760 return false;
761 }
762}
763
Aravind Akella9a844cf2014-02-11 18:58:52 -0800764void SensorService::checkWakeLockState() {
765 Mutex::Autolock _l(mLock);
766 checkWakeLockStateLocked();
767}
768
769void SensorService::checkWakeLockStateLocked() {
770 if (!mWakeLockAcquired) {
771 return;
772 }
773 bool releaseLock = true;
774 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
775 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
776 if (connection != 0) {
777 if (connection->needsWakeLock()) {
778 releaseLock = false;
779 break;
780 }
781 }
782 }
783 if (releaseLock) {
784 ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
785 release_wake_lock(WAKE_LOCK_NAME);
786 mWakeLockAcquired = false;
787 }
788}
Mathias Agopianfc328812010-07-14 23:41:37 -0700789// ---------------------------------------------------------------------------
790
791SensorService::SensorRecord::SensorRecord(
792 const sp<SensorEventConnection>& connection)
793{
794 mConnections.add(connection);
795}
796
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700797bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700798 const sp<SensorEventConnection>& connection)
799{
800 if (mConnections.indexOf(connection) < 0) {
801 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700802 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700803 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700804 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700805}
806
807bool SensorService::SensorRecord::removeConnection(
808 const wp<SensorEventConnection>& connection)
809{
810 ssize_t index = mConnections.indexOf(connection);
811 if (index >= 0) {
812 mConnections.removeItemsAt(index, 1);
813 }
814 return mConnections.size() ? false : true;
815}
816
817// ---------------------------------------------------------------------------
818
819SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -0700820 const sp<SensorService>& service, uid_t uid)
Aravind Akella9a844cf2014-02-11 18:58:52 -0800821 : mService(service), mUid(uid), mWakeLockRefCount(0)
Mathias Agopianfc328812010-07-14 23:41:37 -0700822{
Aravind Akella4c8b9512013-09-05 17:03:38 -0700823 const SensorDevice& device(SensorDevice::getInstance());
824 if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
825 // Increase socket buffer size to 1MB for batching capabilities.
826 mChannel = new BitTube(service->mSocketBufferSize);
827 } else {
828 mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED);
829 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700830}
831
832SensorService::SensorEventConnection::~SensorEventConnection()
833{
Steve Blocka5512372011-12-20 16:23:08 +0000834 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700835 mService->cleanupConnection(this);
836}
837
838void SensorService::SensorEventConnection::onFirstRef()
839{
840}
841
Aravind Akella9a844cf2014-02-11 18:58:52 -0800842bool SensorService::SensorEventConnection::needsWakeLock() {
843 Mutex::Autolock _l(mConnectionLock);
844 return mWakeLockRefCount > 0;
845}
846
Aravind Akella4c8b9512013-09-05 17:03:38 -0700847void SensorService::SensorEventConnection::dump(String8& result) {
848 Mutex::Autolock _l(mConnectionLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800849 result.appendFormat("%d WakeLockRefCount\n", mWakeLockRefCount);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700850 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
851 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Patrick Tjineefced12014-02-05 15:06:03 -0800852 result.appendFormat("\t %s | status: %s | pending flush events %d | uid %d\n",
Aravind Akella4c8b9512013-09-05 17:03:38 -0700853 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
854 flushInfo.mFirstFlushPending ? "First flush pending" :
855 "active",
Patrick Tjineefced12014-02-05 15:06:03 -0800856 flushInfo.mPendingFlushEventsToSend,
857 mUid);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700858 }
859}
860
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700861bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800862 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +0000863 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
864 return false;
865 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700866 if (mSensorInfo.indexOfKey(handle) < 0) {
867 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700868 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700869 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700870 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700871}
872
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700873bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800874 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700875 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700876 return true;
877 }
878 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700879}
880
881bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800882 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700883 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -0700884}
885
886bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800887 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700888 return mSensorInfo.size() ? true : false;
889}
890
Aravind Akella4c8b9512013-09-05 17:03:38 -0700891void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
892 bool value) {
893 Mutex::Autolock _l(mConnectionLock);
894 ssize_t index = mSensorInfo.indexOfKey(handle);
895 if (index >= 0) {
896 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
897 flushInfo.mFirstFlushPending = value;
898 }
899}
900
Mathias Agopianfc328812010-07-14 23:41:37 -0700901status_t SensorService::SensorEventConnection::sendEvents(
Mathias Agopiancf510012010-07-22 16:18:10 -0700902 sensors_event_t const* buffer, size_t numEvents,
903 sensors_event_t* scratch)
Mathias Agopianfc328812010-07-14 23:41:37 -0700904{
Mathias Agopiancf510012010-07-22 16:18:10 -0700905 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -0700906 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800907 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -0700908 if (scratch) {
909 size_t i=0;
910 while (i<numEvents) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700911 int32_t curr = buffer[i].sensor;
912 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
913 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
914 buffer[i].meta_data.sensor);
915 // Setting curr to the correct sensor to ensure the sensor events per connection are
916 // filtered correctly. buffer[i].sensor is zero for meta_data events.
917 curr = buffer[i].meta_data.sensor;
918 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700919 ssize_t index = mSensorInfo.indexOfKey(curr);
920 if (index >= 0 && mSensorInfo[index].mFirstFlushPending == true &&
921 buffer[i].type == SENSOR_TYPE_META_DATA) {
922 // This is the first flush before activate is called. Events can now be sent for
923 // this sensor on this connection.
924 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
925 buffer[i].meta_data.sensor);
926 mSensorInfo.editValueAt(index).mFirstFlushPending = false;
927 }
928 if (index >= 0 && mSensorInfo[index].mFirstFlushPending == false) {
Mathias Agopian3560fb22010-07-22 21:24:39 -0700929 do {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700930 scratch[count++] = buffer[i++];
Aravind Akella724d91d2013-06-27 12:04:23 -0700931 } while ((i<numEvents) && ((buffer[i].sensor == curr) ||
932 (buffer[i].type == SENSOR_TYPE_META_DATA &&
933 buffer[i].meta_data.sensor == curr)));
Mathias Agopian3560fb22010-07-22 21:24:39 -0700934 } else {
935 i++;
936 }
Mathias Agopiancf510012010-07-22 16:18:10 -0700937 }
Mathias Agopian3560fb22010-07-22 21:24:39 -0700938 } else {
939 scratch = const_cast<sensors_event_t *>(buffer);
940 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -0700941 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700942
Aravind Akella4c8b9512013-09-05 17:03:38 -0700943 // Send pending flush events (if any) before sending events from the cache.
944 {
945 ASensorEvent flushCompleteEvent;
946 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
947 flushCompleteEvent.sensor = 0;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700948 // Loop through all the sensors for this connection and check if there are any pending
949 // flush complete events to be sent.
950 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
951 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
952 while (flushInfo.mPendingFlushEventsToSend > 0) {
953 flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
954 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
955 if (size < 0) {
956 // ALOGW("dropping %d events on the floor", count);
Aravind Akellac551eac2013-10-14 17:04:42 -0700957 countFlushCompleteEventsLocked(scratch, count);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700958 return size;
959 }
960 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
961 flushCompleteEvent.meta_data.sensor);
962 flushInfo.mPendingFlushEventsToSend--;
963 }
964 }
965 }
966
Aravind Akellab4099e72013-10-15 15:43:10 -0700967 // Early return if there are no events for this connection.
968 if (count == 0) {
969 return status_t(NO_ERROR);
970 }
971
Aravind Akella9a844cf2014-02-11 18:58:52 -0800972 int numWakeUpSensorEvents = countWakeUpSensorEventsLocked(scratch, count);
Mathias Agopian907103b2012-04-02 18:38:02 -0700973 // NOTE: ASensorEvent and sensors_event_t are the same type
974 ssize_t size = SensorEventQueue::write(mChannel,
975 reinterpret_cast<ASensorEvent const*>(scratch), count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700976 if (size == -EAGAIN) {
977 // the destination doesn't accept events anymore, it's probably
978 // full. For now, we just drop the events on the floor.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700979 // ALOGW("dropping %d events on the floor", count);
Aravind Akellac551eac2013-10-14 17:04:42 -0700980 countFlushCompleteEventsLocked(scratch, count);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800981 mWakeLockRefCount -= numWakeUpSensorEvents;
Mathias Agopianfc328812010-07-14 23:41:37 -0700982 return size;
983 }
Jeff Brown1e0b1e82010-09-13 23:17:30 -0700984 return size < 0 ? status_t(size) : status_t(NO_ERROR);
Mathias Agopianfc328812010-07-14 23:41:37 -0700985}
986
Aravind Akellac551eac2013-10-14 17:04:42 -0700987void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella4c8b9512013-09-05 17:03:38 -0700988 sensors_event_t* scratch, const int numEventsDropped) {
989 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700990 // Count flushComplete events in the events that are about to the dropped. These will be sent
991 // separately before the next batch of events.
992 for (int j = 0; j < numEventsDropped; ++j) {
993 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
994 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
995 flushInfo.mPendingFlushEventsToSend++;
996 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
997 flushInfo.mPendingFlushEventsToSend);
998 }
999 }
1000 return;
1001}
1002
Aravind Akella9a844cf2014-02-11 18:58:52 -08001003int SensorService::SensorEventConnection::countWakeUpSensorEventsLocked(
1004 sensors_event_t* scratch, const int count) {
1005 for (int i = 0; i < count; ++i) {
1006 if (mService->isWakeUpSensorEvent(scratch[i])) {
1007 scratch[i].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1008 ++mWakeLockRefCount;
1009 return 1;
1010 }
1011 }
1012 return 0;
1013}
1014
Mathias Agopianb3989272011-10-20 18:42:02 -07001015sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001016{
1017 return mChannel;
1018}
1019
1020status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001021 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1022 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001023{
1024 status_t err;
1025 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001026 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1027 reservedFlags);
Mathias Agopianfc328812010-07-14 23:41:37 -07001028 } else {
1029 err = mService->disable(this, handle);
1030 }
1031 return err;
1032}
1033
1034status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001035 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001036{
Aravind Akella724d91d2013-06-27 12:04:23 -07001037 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001038}
1039
Aravind Akella701166d2013-10-08 14:59:26 -07001040status_t SensorService::SensorEventConnection::flush() {
Aravind Akellac551eac2013-10-14 17:04:42 -07001041 SensorDevice& dev(SensorDevice::getInstance());
1042 const int halVersion = dev.getHalDeviceVersion();
Aravind Akella701166d2013-10-08 14:59:26 -07001043 Mutex::Autolock _l(mConnectionLock);
1044 status_t err(NO_ERROR);
Aravind Akellac551eac2013-10-14 17:04:42 -07001045 // Loop through all sensors for this connection and call flush on each of them.
Aravind Akella701166d2013-10-08 14:59:26 -07001046 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1047 const int handle = mSensorInfo.keyAt(i);
Aravind Akellab4099e72013-10-15 15:43:10 -07001048 if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
Aravind Akellac551eac2013-10-14 17:04:42 -07001049 // For older devices just increment pending flush count which will send a trivial
1050 // flush complete event.
1051 FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
1052 flushInfo.mPendingFlushEventsToSend++;
1053 } else {
1054 status_t err_flush = mService->flushSensor(this, handle);
1055 if (err_flush != NO_ERROR) {
1056 ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
1057 }
1058 err = (err_flush != NO_ERROR) ? err_flush : err;
Aravind Akella701166d2013-10-08 14:59:26 -07001059 }
Aravind Akella701166d2013-10-08 14:59:26 -07001060 }
1061 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001062}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001063
Aravind Akella9a844cf2014-02-11 18:58:52 -08001064void SensorService::SensorEventConnection::decreaseWakeLockRefCount() {
1065 {
1066 Mutex::Autolock _l(mConnectionLock);
1067 --mWakeLockRefCount;
1068 }
1069 // Release the lock before calling checkWakeLockState which also needs the same connectionLock.
1070 if (mWakeLockRefCount == 0) {
1071 mService->checkWakeLockState();
1072 }
1073}
1074
Mathias Agopianfc328812010-07-14 23:41:37 -07001075// ---------------------------------------------------------------------------
1076}; // namespace android
1077