blob: 9d28792403dc84fb729f3d2dc84530fc2d39e4df [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 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700162 if (fp) {
163 fclose(fp);
164 }
165
Aravind Akella9a844cf2014-02-11 18:58:52 -0800166 mWakeLockAcquired = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700167 run("SensorService", PRIORITY_URGENT_DISPLAY);
168 mInitCheck = NO_ERROR;
169 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700170 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700171}
172
Mathias Agopian03193062013-05-10 19:32:39 -0700173Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800174{
175 sensors_event_t event;
176 memset(&event, 0, sizeof(event));
177
178 const Sensor sensor(s->getSensor());
179 // add to the sensor list (returned to clients)
180 mSensorList.add(sensor);
181 // add to our handle->SensorInterface mapping
182 mSensorMap.add(sensor.getHandle(), s);
183 // create an entry in the mLastEventSeen array
184 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700185
186 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800187}
188
Mathias Agopian03193062013-05-10 19:32:39 -0700189Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800190{
Mathias Agopian03193062013-05-10 19:32:39 -0700191 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800192 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700193 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800194}
195
Mathias Agopianfc328812010-07-14 23:41:37 -0700196SensorService::~SensorService()
197{
Mathias Agopianf001c922010-11-11 17:58:51 -0800198 for (size_t i=0 ; i<mSensorMap.size() ; i++)
199 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700200}
201
Mathias Agopian1cb13462011-06-27 16:05:52 -0700202static const String16 sDump("android.permission.DUMP");
203
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700204status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700205{
Mathias Agopianfc328812010-07-14 23:41:37 -0700206 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700207 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700208 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000209 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700210 IPCThreadState::self()->getCallingPid(),
211 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700212 } else {
213 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700214 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700215 for (size_t i=0 ; i<mSensorList.size() ; i++) {
216 const Sensor& s(mSensorList[i]);
217 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700218 result.appendFormat(
Aravind Akella70018042014-04-07 22:52:37 +0000219 "%-48s| %-32s| %-48s| 0x%08x | \"%s\"\n\t",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700220 s.getName().string(),
221 s.getVendor().string(),
Aravind Akella70018042014-04-07 22:52:37 +0000222 s.getStringType().string(),
223 s.getHandle(),
224 s.getRequiredPermission().string());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700225
Aravind Akella0e025c52014-06-03 19:19:57 -0700226 const int reportingMode = s.getReportingMode();
227 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
228 result.append("continuous |");
229 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
230 result.append("on-change | ");
231 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
232 result.append("one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700233 } else {
Aravind Akella0e025c52014-06-03 19:19:57 -0700234 result.append("special-trigger | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700235 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700236
237 if (s.getMinDelay() > 0) {
238 result.appendFormat("maxRate=%7.2fHz | ", 1e6f / s.getMinDelay());
239 } else {
240 result.appendFormat("minDelay=%5dus |", s.getMinDelay());
241 }
242
Aravind Akella724d91d2013-06-27 12:04:23 -0700243 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000244 result.appendFormat("FifoMax=%d events | ",
245 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700246 } else {
247 result.append("no batching support | ");
248 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700249
250 switch (s.getType()) {
251 case SENSOR_TYPE_ROTATION_VECTOR:
252 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
253 result.appendFormat(
254 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
255 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]);
256 break;
257 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
258 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
259 result.appendFormat(
260 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
261 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]);
262 break;
263 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
264 result.appendFormat(
265 "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n",
266 e.data[0], e.data[1], e.data[2], e.data[3]);
267 break;
268 case SENSOR_TYPE_SIGNIFICANT_MOTION:
269 case SENSOR_TYPE_STEP_DETECTOR:
270 result.appendFormat( "last=<%f>\n", e.data[0]);
271 break;
272 case SENSOR_TYPE_STEP_COUNTER:
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700273 result.appendFormat( "last=<%" PRIu64 ">\n", e.u64.step_counter);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700274 break;
275 default:
276 // default to 3 values
277 result.appendFormat(
278 "last=<%5.1f,%5.1f,%5.1f>\n",
279 e.data[0], e.data[1], e.data[2]);
280 break;
281 }
282 }
283 SensorFusion::getInstance().dump(result);
284 SensorDevice::getInstance().dump(result);
285
Mathias Agopianba02cd22013-07-03 16:20:57 -0700286 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700287 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700288 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700289 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700290 getSensorName(handle).string(),
291 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700292 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700293 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700294
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700295 result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800296 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700297 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700298
299 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
300 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
301 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700302 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700303 connection->dump(result);
304 }
305 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700306 }
307 write(fd, result.string(), result.size());
308 return NO_ERROR;
309}
310
Aravind Akella9a844cf2014-02-11 18:58:52 -0800311void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700312 sensors_event_t const* buffer, const int count) {
313 for (int i=0 ; i<count ; i++) {
314 int handle = buffer[i].sensor;
Aravind Akella0e025c52014-06-03 19:19:57 -0700315 if (connection->hasSensor(handle)) {
316 SensorInterface* sensor = mSensorMap.valueFor(handle);
317 // If this buffer has an event from a one_shot sensor and this connection is registered
318 // for this particular one_shot sensor, try cleaning up the connection.
319 if (sensor != NULL &&
320 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
321 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800322 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700323 }
324 }
325 }
326}
327
Mathias Agopianfc328812010-07-14 23:41:37 -0700328bool SensorService::threadLoop()
329{
Steve Blocka5512372011-12-20 16:23:08 +0000330 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700331
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700332 // each virtual sensor could generate an event per "real" event, that's why we need
333 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
334 // in practice, this is too aggressive, but guaranteed to be enough.
335 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
336 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
337
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700338 sensors_event_t buffer[minBufferSize];
339 sensors_event_t scratch[minBufferSize];
Mathias Agopianf001c922010-11-11 17:58:51 -0800340 SensorDevice& device(SensorDevice::getInstance());
341 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700342
Mathias Agopianf001c922010-11-11 17:58:51 -0800343 ssize_t count;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700344 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700345 do {
Mathias Agopianf001c922010-11-11 17:58:51 -0800346 count = device.poll(buffer, numEventMax);
Mathias Agopianfc328812010-07-14 23:41:37 -0700347 if (count<0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000348 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700349 break;
350 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800351 Mutex::Autolock _l(mLock);
352 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
353 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
354 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
355 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
356 // releasing the wakelock.
357 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700358 for (int i = 0; i < count; i++) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800359 if (isWakeUpSensorEvent(buffer[i])) {
360 bufferHasWakeUpEvent = true;
361 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700362 }
363 }
364
Aravind Akella9a844cf2014-02-11 18:58:52 -0800365 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
366 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
367 mWakeLockAcquired = true;
368 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
369 }
370 recordLastValueLocked(buffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800371
Mathias Agopianf001c922010-11-11 17:58:51 -0800372 // handle virtual sensors
373 if (count && vcount) {
Mathias Agopian984826c2011-05-17 22:54:42 -0700374 sensors_event_t const * const event = buffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800375 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800376 if (activeVirtualSensorCount) {
377 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700378 SensorFusion& fusion(SensorFusion::getInstance());
379 if (fusion.isEnabled()) {
380 for (size_t i=0 ; i<size_t(count) ; i++) {
381 fusion.process(event[i]);
382 }
383 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700384 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800385 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700386 if (count + k >= minBufferSize) {
387 ALOGE("buffer too small to hold all events: "
388 "count=%u, k=%u, size=%u",
389 count, k, minBufferSize);
390 break;
391 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800392 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800393 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700394 if (si->process(&out, event[i])) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800395 buffer[count + k] = out;
396 k++;
397 }
398 }
399 }
400 if (k) {
401 // record the last synthesized values
Aravind Akella9a844cf2014-02-11 18:58:52 -0800402 recordLastValueLocked(&buffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800403 count += k;
404 // sort the buffer by time-stamps
405 sortEventBuffer(buffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700406 }
407 }
408 }
409
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700410 // handle backward compatibility for RotationVector sensor
411 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
412 for (int i = 0; i < count; i++) {
Mathias Agopian7438fd12013-07-08 12:50:39 -0700413 if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700414 // All the 4 components of the quaternion should be available
415 // No heading accuracy. Set it to -1
416 buffer[i].data[4] = -1;
417 }
418 }
419 }
420
Aravind Akella9a844cf2014-02-11 18:58:52 -0800421 // Send our events to clients. Check the state of wake lock for each client and release the
422 // lock if none of the clients need it.
423 bool needsWakeLock = false;
424 for (size_t i=0 ; i < mActiveConnections.size(); i++) {
425 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Mathias Agopianf001c922010-11-11 17:58:51 -0800426 if (connection != 0) {
427 connection->sendEvents(buffer, count, scratch);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800428 needsWakeLock |= connection->needsWakeLock();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700429 // Some sensors need to be auto disabled after the trigger
Aravind Akella9a844cf2014-02-11 18:58:52 -0800430 cleanupAutoDisabledSensorLocked(connection, buffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800431 }
432 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700433
Aravind Akella9a844cf2014-02-11 18:58:52 -0800434 if (mWakeLockAcquired && !needsWakeLock) {
435 release_wake_lock(WAKE_LOCK_NAME);
436 mWakeLockAcquired = false;
437 ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
438 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700439 } while (count >= 0 || Thread::exitPending());
440
Steve Block3c20fbe2012-01-05 23:22:43 +0000441 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800442 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700443 return false;
444}
445
Aravind Akella9a844cf2014-02-11 18:58:52 -0800446void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800447 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800448 const sensors_event_t* last = NULL;
449 for (size_t i = 0; i < count; i++) {
450 const sensors_event_t* event = &buffer[i];
451 if (event->type != SENSOR_TYPE_META_DATA) {
452 if (last && event->sensor != last->sensor) {
453 mLastEventSeen.editValueFor(last->sensor) = *last;
454 }
455 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800456 }
457 }
Aravind Akella4b847042014-03-03 19:02:46 -0800458 if (last) {
459 mLastEventSeen.editValueFor(last->sensor) = *last;
460 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800461}
462
Mathias Agopianf001c922010-11-11 17:58:51 -0800463void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
464{
465 struct compar {
466 static int cmp(void const* lhs, void const* rhs) {
467 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
468 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700469 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800470 }
471 };
472 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
473}
474
Mathias Agopian5d270722010-07-19 15:20:39 -0700475String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700476 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700477 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700478 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700479 if (sensor.getHandle() == handle) {
480 return sensor.getName();
481 }
482 }
483 String8 result("unknown");
484 return result;
485}
486
Aravind Akellab4099e72013-10-15 15:43:10 -0700487bool SensorService::isVirtualSensor(int handle) const {
488 SensorInterface* sensor = mSensorMap.valueFor(handle);
489 return sensor->isVirtual();
490}
491
Aravind Akella9a844cf2014-02-11 18:58:52 -0800492bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
493 SensorInterface* sensor = mSensorMap.valueFor(event.sensor);
494 return sensor->getSensor().isWakeUpSensor();
495}
496
Mathias Agopianfc328812010-07-14 23:41:37 -0700497Vector<Sensor> SensorService::getSensorList()
498{
Mathias Agopian33264862012-06-28 19:46:54 -0700499 char value[PROPERTY_VALUE_MAX];
500 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000501 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
502 mUserSensorListDebug : mUserSensorList;
503 Vector<Sensor> accessibleSensorList;
504 for (size_t i = 0; i < initialSensorList.size(); i++) {
505 Sensor sensor = initialSensorList[i];
506 if (canAccessSensor(sensor)) {
507 accessibleSensorList.add(sensor);
508 } else {
509 String8 infoMessage;
510 infoMessage.appendFormat(
511 "Skipped sensor %s because it requires permission %s",
512 sensor.getName().string(),
513 sensor.getRequiredPermission().string());
514 ALOGI(infoMessage.string());
515 }
Mathias Agopian33264862012-06-28 19:46:54 -0700516 }
Aravind Akella70018042014-04-07 22:52:37 +0000517 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700518}
519
520sp<ISensorEventConnection> SensorService::createSensorEventConnection()
521{
Mathias Agopian5307d172012-09-18 17:02:43 -0700522 uid_t uid = IPCThreadState::self()->getCallingUid();
523 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700524 return result;
525}
526
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800527void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700528{
529 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800530 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700531 size_t size = mActiveSensors.size();
Steve Blocka5512372011-12-20 16:23:08 +0000532 ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700533 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800534 int handle = mActiveSensors.keyAt(i);
535 if (c->hasSensor(handle)) {
Steve Blocka5512372011-12-20 16:23:08 +0000536 ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800537 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000538 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800539 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800540 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800541 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800542 }
543 SensorRecord* rec = mActiveSensors.valueAt(i);
Steve Blockf5a12302012-01-06 19:20:56 +0000544 ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000545 ALOGD_IF(DEBUG_CONNECTIONS,
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700546 "removing connection %p for sensor[%d].handle=0x%08x",
547 c, i, handle);
548
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800549 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000550 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700551 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800552 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700553 delete rec;
554 size--;
555 } else {
556 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700557 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700558 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700559 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700560 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800561 if (c->needsWakeLock()) {
562 checkWakeLockStateLocked();
563 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700564}
565
Aravind Akella70018042014-04-07 22:52:37 +0000566Sensor SensorService::getSensorFromHandle(int handle) const {
567 return mSensorMap.valueFor(handle)->getSensor();
568}
569
Mathias Agopianfc328812010-07-14 23:41:37 -0700570status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700571 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700572{
Mathias Agopian50df2952010-07-19 19:09:10 -0700573 if (mInitCheck != NO_ERROR)
574 return mInitCheck;
575
Mathias Agopianf001c922010-11-11 17:58:51 -0800576 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700577 if (sensor == NULL) {
578 return BAD_VALUE;
579 }
Aravind Akella70018042014-04-07 22:52:37 +0000580
581 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
582 return BAD_VALUE;
583 }
584
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700585 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700586 SensorRecord* rec = mActiveSensors.valueFor(handle);
587 if (rec == 0) {
588 rec = new SensorRecord(connection);
589 mActiveSensors.add(handle, rec);
590 if (sensor->isVirtual()) {
591 mActiveVirtualSensors.add(handle, sensor);
592 }
593 } else {
594 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800595 // this sensor is already activated, but we are adding a connection that uses it.
596 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700597 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700598 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800599 // NOTE: The wake_up flag of this event may get set to
600 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700601 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
602 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800603 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
604 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
605 mWakeLockAcquired = true;
606 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
607 WAKE_LOCK_NAME);
608 }
609 connection->sendEvents(&event, 1, NULL);
610 if (!connection->needsWakeLock() && mWakeLockAcquired) {
611 checkWakeLockStateLocked();
612 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700613 }
614 }
615 }
616 }
617
618 if (connection->addSensor(handle)) {
619 BatteryService::enableSensor(connection->getUid(), handle);
620 // the sensor was added (which means it wasn't already there)
621 // so, see if this connection becomes active
622 if (mActiveConnections.indexOf(connection) < 0) {
623 mActiveConnections.add(connection);
624 }
625 } else {
626 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
627 handle, connection.get());
628 }
629
Aravind Akella724d91d2013-06-27 12:04:23 -0700630 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
631 if (samplingPeriodNs < minDelayNs) {
632 samplingPeriodNs = minDelayNs;
633 }
634
635 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld",
636 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
637
638 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
639 maxBatchReportLatencyNs);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700640 if (err == NO_ERROR) {
641 connection->setFirstFlushPending(handle, true);
642 status_t err_flush = sensor->flush(connection.get(), handle);
643 // Flush may return error if the sensor is not activated or the underlying h/w sensor does
644 // not support flush.
645 if (err_flush != NO_ERROR) {
646 connection->setFirstFlushPending(handle, false);
647 }
648 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700649
650 if (err == NO_ERROR) {
651 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
652 err = sensor->activate(connection.get(), true);
653 }
654
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700655 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700656 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700657 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700658 }
659 return err;
660}
661
662status_t SensorService::disable(const sp<SensorEventConnection>& connection,
663 int handle)
664{
Mathias Agopian50df2952010-07-19 19:09:10 -0700665 if (mInitCheck != NO_ERROR)
666 return mInitCheck;
667
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700668 Mutex::Autolock _l(mLock);
669 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700670 if (err == NO_ERROR) {
671 SensorInterface* sensor = mSensorMap.valueFor(handle);
672 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
673 }
674 return err;
675}
676
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700677status_t SensorService::cleanupWithoutDisable(
678 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700679 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700680 return cleanupWithoutDisableLocked(connection, handle);
681}
682
683status_t SensorService::cleanupWithoutDisableLocked(
684 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700685 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700686 if (rec) {
687 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700688 if (connection->removeSensor(handle)) {
689 BatteryService::disableSensor(connection->getUid(), handle);
690 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700691 if (connection->hasAnySensor() == false) {
692 mActiveConnections.remove(connection);
693 }
694 // see if this sensor becomes inactive
695 if (rec->removeConnection(connection)) {
696 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800697 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700698 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700699 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700700 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700701 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700702 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700703}
704
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700705status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700706 int handle, nsecs_t ns)
707{
Mathias Agopian50df2952010-07-19 19:09:10 -0700708 if (mInitCheck != NO_ERROR)
709 return mInitCheck;
710
Mathias Agopianae09d652011-11-01 17:37:49 -0700711 SensorInterface* sensor = mSensorMap.valueFor(handle);
712 if (!sensor)
713 return BAD_VALUE;
714
Aravind Akella70018042014-04-07 22:52:37 +0000715 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
716 return BAD_VALUE;
717 }
718
Mathias Agopian1cd70002010-07-21 15:59:50 -0700719 if (ns < 0)
720 return BAD_VALUE;
721
Mathias Agopian62569ec2011-11-07 21:21:47 -0800722 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
723 if (ns < minDelayNs) {
724 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700725 }
726
Mathias Agopianf001c922010-11-11 17:58:51 -0800727 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700728}
729
Aravind Akella724d91d2013-06-27 12:04:23 -0700730status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
731 int handle) {
Aravind Akella70018042014-04-07 22:52:37 +0000732 if (mInitCheck != NO_ERROR) return mInitCheck;
733 SensorInterface* sensor = mSensorMap.valueFor(handle);
734 if (sensor == NULL) {
735 return BAD_VALUE;
736 }
737
738 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried flushing")) {
739 return BAD_VALUE;
740 }
741
Aravind Akella0e025c52014-06-03 19:19:57 -0700742 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
743 ALOGE("flush called on a one-shot sensor");
Aravind Akella70018042014-04-07 22:52:37 +0000744 return INVALID_OPERATION;
745 }
746 return sensor->flush(connection.get(), handle);
Aravind Akella724d91d2013-06-27 12:04:23 -0700747}
Aravind Akella70018042014-04-07 22:52:37 +0000748
749
750bool SensorService::canAccessSensor(const Sensor& sensor) {
751 String16 permissionString(sensor.getRequiredPermission());
752 return permissionString.size() == 0 ||
753 PermissionCache::checkCallingPermission(permissionString);
754}
755
756bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
757 if (canAccessSensor(sensor)) {
758 return true;
759 } else {
760 String8 errorMessage;
761 errorMessage.appendFormat(
762 "%s a sensor (%s) without holding its required permission: %s",
763 operation,
764 sensor.getName().string(),
765 sensor.getRequiredPermission().string());
766 return false;
767 }
768}
769
Aravind Akella9a844cf2014-02-11 18:58:52 -0800770void SensorService::checkWakeLockState() {
771 Mutex::Autolock _l(mLock);
772 checkWakeLockStateLocked();
773}
774
775void SensorService::checkWakeLockStateLocked() {
776 if (!mWakeLockAcquired) {
777 return;
778 }
779 bool releaseLock = true;
780 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
781 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
782 if (connection != 0) {
783 if (connection->needsWakeLock()) {
784 releaseLock = false;
785 break;
786 }
787 }
788 }
789 if (releaseLock) {
790 ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
791 release_wake_lock(WAKE_LOCK_NAME);
792 mWakeLockAcquired = false;
793 }
794}
Mathias Agopianfc328812010-07-14 23:41:37 -0700795// ---------------------------------------------------------------------------
796
797SensorService::SensorRecord::SensorRecord(
798 const sp<SensorEventConnection>& connection)
799{
800 mConnections.add(connection);
801}
802
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700803bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700804 const sp<SensorEventConnection>& connection)
805{
806 if (mConnections.indexOf(connection) < 0) {
807 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700808 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700809 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700810 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700811}
812
813bool SensorService::SensorRecord::removeConnection(
814 const wp<SensorEventConnection>& connection)
815{
816 ssize_t index = mConnections.indexOf(connection);
817 if (index >= 0) {
818 mConnections.removeItemsAt(index, 1);
819 }
820 return mConnections.size() ? false : true;
821}
822
823// ---------------------------------------------------------------------------
824
825SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -0700826 const sp<SensorService>& service, uid_t uid)
Aravind Akella9a844cf2014-02-11 18:58:52 -0800827 : mService(service), mUid(uid), mWakeLockRefCount(0)
Mathias Agopianfc328812010-07-14 23:41:37 -0700828{
Aravind Akella4c8b9512013-09-05 17:03:38 -0700829 const SensorDevice& device(SensorDevice::getInstance());
830 if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
831 // Increase socket buffer size to 1MB for batching capabilities.
832 mChannel = new BitTube(service->mSocketBufferSize);
833 } else {
834 mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED);
835 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700836}
837
838SensorService::SensorEventConnection::~SensorEventConnection()
839{
Steve Blocka5512372011-12-20 16:23:08 +0000840 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Mathias Agopianfc328812010-07-14 23:41:37 -0700841 mService->cleanupConnection(this);
842}
843
844void SensorService::SensorEventConnection::onFirstRef()
845{
846}
847
Aravind Akella9a844cf2014-02-11 18:58:52 -0800848bool SensorService::SensorEventConnection::needsWakeLock() {
849 Mutex::Autolock _l(mConnectionLock);
850 return mWakeLockRefCount > 0;
851}
852
Aravind Akella4c8b9512013-09-05 17:03:38 -0700853void SensorService::SensorEventConnection::dump(String8& result) {
854 Mutex::Autolock _l(mConnectionLock);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800855 result.appendFormat("%d WakeLockRefCount\n", mWakeLockRefCount);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700856 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
857 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Patrick Tjineefced12014-02-05 15:06:03 -0800858 result.appendFormat("\t %s | status: %s | pending flush events %d | uid %d\n",
Aravind Akella4c8b9512013-09-05 17:03:38 -0700859 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
860 flushInfo.mFirstFlushPending ? "First flush pending" :
861 "active",
Patrick Tjineefced12014-02-05 15:06:03 -0800862 flushInfo.mPendingFlushEventsToSend,
863 mUid);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700864 }
865}
866
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700867bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800868 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +0000869 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
870 return false;
871 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700872 if (mSensorInfo.indexOfKey(handle) < 0) {
873 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700874 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700875 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700876 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700877}
878
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700879bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800880 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700881 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700882 return true;
883 }
884 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700885}
886
887bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800888 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700889 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -0700890}
891
892bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800893 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700894 return mSensorInfo.size() ? true : false;
895}
896
Aravind Akella4c8b9512013-09-05 17:03:38 -0700897void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
898 bool value) {
899 Mutex::Autolock _l(mConnectionLock);
900 ssize_t index = mSensorInfo.indexOfKey(handle);
901 if (index >= 0) {
902 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
903 flushInfo.mFirstFlushPending = value;
904 }
905}
906
Mathias Agopianfc328812010-07-14 23:41:37 -0700907status_t SensorService::SensorEventConnection::sendEvents(
Mathias Agopiancf510012010-07-22 16:18:10 -0700908 sensors_event_t const* buffer, size_t numEvents,
909 sensors_event_t* scratch)
Mathias Agopianfc328812010-07-14 23:41:37 -0700910{
Mathias Agopiancf510012010-07-22 16:18:10 -0700911 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -0700912 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800913 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -0700914 if (scratch) {
915 size_t i=0;
916 while (i<numEvents) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700917 int32_t curr = buffer[i].sensor;
918 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
919 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
920 buffer[i].meta_data.sensor);
921 // Setting curr to the correct sensor to ensure the sensor events per connection are
922 // filtered correctly. buffer[i].sensor is zero for meta_data events.
923 curr = buffer[i].meta_data.sensor;
924 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700925 ssize_t index = mSensorInfo.indexOfKey(curr);
926 if (index >= 0 && mSensorInfo[index].mFirstFlushPending == true &&
927 buffer[i].type == SENSOR_TYPE_META_DATA) {
928 // This is the first flush before activate is called. Events can now be sent for
929 // this sensor on this connection.
930 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
931 buffer[i].meta_data.sensor);
932 mSensorInfo.editValueAt(index).mFirstFlushPending = false;
933 }
934 if (index >= 0 && mSensorInfo[index].mFirstFlushPending == false) {
Mathias Agopian3560fb22010-07-22 21:24:39 -0700935 do {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700936 scratch[count++] = buffer[i++];
Aravind Akella724d91d2013-06-27 12:04:23 -0700937 } while ((i<numEvents) && ((buffer[i].sensor == curr) ||
938 (buffer[i].type == SENSOR_TYPE_META_DATA &&
939 buffer[i].meta_data.sensor == curr)));
Mathias Agopian3560fb22010-07-22 21:24:39 -0700940 } else {
941 i++;
942 }
Mathias Agopiancf510012010-07-22 16:18:10 -0700943 }
Mathias Agopian3560fb22010-07-22 21:24:39 -0700944 } else {
945 scratch = const_cast<sensors_event_t *>(buffer);
946 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -0700947 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700948
Aravind Akella4c8b9512013-09-05 17:03:38 -0700949 // Send pending flush events (if any) before sending events from the cache.
950 {
951 ASensorEvent flushCompleteEvent;
952 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
953 flushCompleteEvent.sensor = 0;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700954 // Loop through all the sensors for this connection and check if there are any pending
955 // flush complete events to be sent.
956 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
957 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
958 while (flushInfo.mPendingFlushEventsToSend > 0) {
959 flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
960 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
961 if (size < 0) {
962 // ALOGW("dropping %d events on the floor", count);
Aravind Akellac551eac2013-10-14 17:04:42 -0700963 countFlushCompleteEventsLocked(scratch, count);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700964 return size;
965 }
966 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
967 flushCompleteEvent.meta_data.sensor);
968 flushInfo.mPendingFlushEventsToSend--;
969 }
970 }
971 }
972
Aravind Akellab4099e72013-10-15 15:43:10 -0700973 // Early return if there are no events for this connection.
974 if (count == 0) {
975 return status_t(NO_ERROR);
976 }
977
Aravind Akella9a844cf2014-02-11 18:58:52 -0800978 int numWakeUpSensorEvents = countWakeUpSensorEventsLocked(scratch, count);
Mathias Agopian907103b2012-04-02 18:38:02 -0700979 // NOTE: ASensorEvent and sensors_event_t are the same type
980 ssize_t size = SensorEventQueue::write(mChannel,
981 reinterpret_cast<ASensorEvent const*>(scratch), count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700982 if (size == -EAGAIN) {
983 // the destination doesn't accept events anymore, it's probably
984 // full. For now, we just drop the events on the floor.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700985 // ALOGW("dropping %d events on the floor", count);
Aravind Akellac551eac2013-10-14 17:04:42 -0700986 countFlushCompleteEventsLocked(scratch, count);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800987 mWakeLockRefCount -= numWakeUpSensorEvents;
Mathias Agopianfc328812010-07-14 23:41:37 -0700988 return size;
989 }
Jeff Brown1e0b1e82010-09-13 23:17:30 -0700990 return size < 0 ? status_t(size) : status_t(NO_ERROR);
Mathias Agopianfc328812010-07-14 23:41:37 -0700991}
992
Aravind Akellac551eac2013-10-14 17:04:42 -0700993void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella4c8b9512013-09-05 17:03:38 -0700994 sensors_event_t* scratch, const int numEventsDropped) {
995 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700996 // Count flushComplete events in the events that are about to the dropped. These will be sent
997 // separately before the next batch of events.
998 for (int j = 0; j < numEventsDropped; ++j) {
999 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1000 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1001 flushInfo.mPendingFlushEventsToSend++;
1002 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1003 flushInfo.mPendingFlushEventsToSend);
1004 }
1005 }
1006 return;
1007}
1008
Aravind Akella9a844cf2014-02-11 18:58:52 -08001009int SensorService::SensorEventConnection::countWakeUpSensorEventsLocked(
1010 sensors_event_t* scratch, const int count) {
1011 for (int i = 0; i < count; ++i) {
1012 if (mService->isWakeUpSensorEvent(scratch[i])) {
1013 scratch[i].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
1014 ++mWakeLockRefCount;
1015 return 1;
1016 }
1017 }
1018 return 0;
1019}
1020
Mathias Agopianb3989272011-10-20 18:42:02 -07001021sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001022{
1023 return mChannel;
1024}
1025
1026status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001027 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1028 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001029{
1030 status_t err;
1031 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001032 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1033 reservedFlags);
Mathias Agopianfc328812010-07-14 23:41:37 -07001034 } else {
1035 err = mService->disable(this, handle);
1036 }
1037 return err;
1038}
1039
1040status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001041 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001042{
Aravind Akella724d91d2013-06-27 12:04:23 -07001043 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001044}
1045
Aravind Akella701166d2013-10-08 14:59:26 -07001046status_t SensorService::SensorEventConnection::flush() {
Aravind Akellac551eac2013-10-14 17:04:42 -07001047 SensorDevice& dev(SensorDevice::getInstance());
1048 const int halVersion = dev.getHalDeviceVersion();
Aravind Akella701166d2013-10-08 14:59:26 -07001049 Mutex::Autolock _l(mConnectionLock);
1050 status_t err(NO_ERROR);
Aravind Akellac551eac2013-10-14 17:04:42 -07001051 // Loop through all sensors for this connection and call flush on each of them.
Aravind Akella701166d2013-10-08 14:59:26 -07001052 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1053 const int handle = mSensorInfo.keyAt(i);
Aravind Akellab4099e72013-10-15 15:43:10 -07001054 if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
Aravind Akellac551eac2013-10-14 17:04:42 -07001055 // For older devices just increment pending flush count which will send a trivial
1056 // flush complete event.
1057 FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
1058 flushInfo.mPendingFlushEventsToSend++;
1059 } else {
1060 status_t err_flush = mService->flushSensor(this, handle);
1061 if (err_flush != NO_ERROR) {
1062 ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
1063 }
1064 err = (err_flush != NO_ERROR) ? err_flush : err;
Aravind Akella701166d2013-10-08 14:59:26 -07001065 }
Aravind Akella701166d2013-10-08 14:59:26 -07001066 }
1067 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001068}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001069
Aravind Akella9a844cf2014-02-11 18:58:52 -08001070void SensorService::SensorEventConnection::decreaseWakeLockRefCount() {
1071 {
1072 Mutex::Autolock _l(mConnectionLock);
1073 --mWakeLockRefCount;
1074 }
1075 // Release the lock before calling checkWakeLockState which also needs the same connectionLock.
1076 if (mWakeLockRefCount == 0) {
1077 mService->checkWakeLockState();
1078 }
1079}
1080
Mathias Agopianfc328812010-07-14 23:41:37 -07001081// ---------------------------------------------------------------------------
1082}; // namespace android
1083