blob: 8fe79d0136f1bd594227ecef4aef160f2cbe95d3 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070017#include <inttypes.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080018#include <math.h>
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -070019#include <stdint.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <sys/types.h>
Aravind Akella56ae4262014-07-10 16:01:10 -070021#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070022
Mathias Agopian33015422011-05-27 18:18:13 -070023#include <cutils/properties.h>
24
Mathias Agopianfc328812010-07-14 23:41:37 -070025#include <utils/SortedVector.h>
26#include <utils/KeyedVector.h>
27#include <utils/threads.h>
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/RefBase.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070031#include <utils/Singleton.h>
Mathias Agopianc4a930d2010-07-22 22:19:43 -070032#include <utils/String16.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070033
34#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070035#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070037
38#include <gui/ISensorServer.h>
39#include <gui/ISensorEventConnection.h>
Mathias Agopian907103b2012-04-02 18:38:02 -070040#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070041
42#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070043#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070044
Mathias Agopian787ac1b2012-09-18 18:49:18 -070045#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070046#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080047#include "GravitySensor.h"
48#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070049#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080050#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070051#include "SensorFusion.h"
52#include "SensorService.h"
Mathias Agopianfc328812010-07-14 23:41:37 -070053
54namespace android {
55// ---------------------------------------------------------------------------
56
Mathias Agopian33015422011-05-27 18:18:13 -070057/*
58 * Notes:
59 *
60 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070061 * - run mag sensor from time to time to force calibration
62 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
63 *
64 */
65
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070066const char* SensorService::WAKE_LOCK_NAME = "SensorService";
67
Mathias Agopianfc328812010-07-14 23:41:37 -070068SensorService::SensorService()
Mathias Agopian1cb13462011-06-27 16:05:52 -070069 : mInitCheck(NO_INIT)
Mathias Agopianfc328812010-07-14 23:41:37 -070070{
71}
72
73void SensorService::onFirstRef()
74{
Steve Blocka5512372011-12-20 16:23:08 +000075 ALOGD("nuSensorService starting...");
Mathias Agopian50df2952010-07-19 19:09:10 -070076
Mathias Agopianf001c922010-11-11 17:58:51 -080077 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070078
Mathias Agopianf001c922010-11-11 17:58:51 -080079 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080080 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070081 ssize_t count = dev.getSensorList(&list);
82 if (count > 0) {
83 ssize_t orientationIndex = -1;
84 bool hasGyro = false;
85 uint32_t virtualSensorsNeeds =
86 (1<<SENSOR_TYPE_GRAVITY) |
87 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
88 (1<<SENSOR_TYPE_ROTATION_VECTOR);
89
90 mLastEventSeen.setCapacity(count);
91 for (ssize_t i=0 ; i<count ; i++) {
92 registerSensor( new HardwareSensor(list[i]) );
93 switch (list[i].type) {
94 case SENSOR_TYPE_ORIENTATION:
95 orientationIndex = i;
96 break;
97 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -070098 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070099 hasGyro = true;
100 break;
101 case SENSOR_TYPE_GRAVITY:
102 case SENSOR_TYPE_LINEAR_ACCELERATION:
103 case SENSOR_TYPE_ROTATION_VECTOR:
104 virtualSensorsNeeds &= ~(1<<list[i].type);
105 break;
106 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700107 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700108
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700109 // it's safe to instantiate the SensorFusion object here
110 // (it wants to be instantiated after h/w sensors have been
111 // registered)
112 const SensorFusion& fusion(SensorFusion::getInstance());
Mathias Agopian984826c2011-05-17 22:54:42 -0700113
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700114 // build the sensor list returned to users
115 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700116
117 if (hasGyro) {
Mathias Agopian03193062013-05-10 19:32:39 -0700118 Sensor aSensor;
119
120 // Add Android virtual sensors if they're not already
121 // available in the HAL
122
123 aSensor = registerVirtualSensor( new RotationVectorSensor() );
124 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
125 mUserSensorList.add(aSensor);
126 }
127
128 aSensor = registerVirtualSensor( new GravitySensor(list, count) );
129 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
130 mUserSensorList.add(aSensor);
131 }
132
133 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
134 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
135 mUserSensorList.add(aSensor);
136 }
137
138 aSensor = registerVirtualSensor( new OrientationSensor() );
139 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
140 // if we are doing our own rotation-vector, also add
141 // the orientation sensor and remove the HAL provided one.
142 mUserSensorList.replaceAt(aSensor, orientationIndex);
143 }
144
Mathias Agopian33264862012-06-28 19:46:54 -0700145 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700146 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700147 registerVirtualSensor( new GyroDriftSensor() );
148 }
149
Mathias Agopian33264862012-06-28 19:46:54 -0700150 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700151 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700152
Aravind Akella4c8b9512013-09-05 17:03:38 -0700153 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
154 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
155 char line[128];
156 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
157 line[sizeof(line) - 1] = '\0';
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700158 sscanf(line, "%zu", &mSocketBufferSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700159 if (mSocketBufferSize > MAX_SOCKET_BUFFER_SIZE_BATCHED) {
160 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
161 }
162 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700163 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);
Aravind Akella56ae4262014-07-10 16:01:10 -0700169 mLooper = new Looper(false);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700170 mInitCheck = NO_ERROR;
171 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700172 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700173}
174
Mathias Agopian03193062013-05-10 19:32:39 -0700175Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800176{
177 sensors_event_t event;
178 memset(&event, 0, sizeof(event));
179
180 const Sensor sensor(s->getSensor());
181 // add to the sensor list (returned to clients)
182 mSensorList.add(sensor);
183 // add to our handle->SensorInterface mapping
184 mSensorMap.add(sensor.getHandle(), s);
185 // create an entry in the mLastEventSeen array
186 mLastEventSeen.add(sensor.getHandle(), event);
Mathias Agopian03193062013-05-10 19:32:39 -0700187
188 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800189}
190
Mathias Agopian03193062013-05-10 19:32:39 -0700191Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800192{
Mathias Agopian03193062013-05-10 19:32:39 -0700193 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800194 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700195 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800196}
197
Mathias Agopianfc328812010-07-14 23:41:37 -0700198SensorService::~SensorService()
199{
Mathias Agopianf001c922010-11-11 17:58:51 -0800200 for (size_t i=0 ; i<mSensorMap.size() ; i++)
201 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700202}
203
Mathias Agopian1cb13462011-06-27 16:05:52 -0700204static const String16 sDump("android.permission.DUMP");
205
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700206status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
Mathias Agopianfc328812010-07-14 23:41:37 -0700207{
Mathias Agopianfc328812010-07-14 23:41:37 -0700208 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700209 if (!PermissionCache::checkCallingPermission(sDump)) {
Mathias Agopianba02cd22013-07-03 16:20:57 -0700210 result.appendFormat("Permission Denial: "
Aravind Akella70018042014-04-07 22:52:37 +0000211 "can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700212 IPCThreadState::self()->getCallingPid(),
213 IPCThreadState::self()->getCallingUid());
Mathias Agopianfc328812010-07-14 23:41:37 -0700214 } else {
215 Mutex::Autolock _l(mLock);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700216 result.append("Sensor List:\n");
Mathias Agopian3560fb22010-07-22 21:24:39 -0700217 for (size_t i=0 ; i<mSensorList.size() ; i++) {
218 const Sensor& s(mSensorList[i]);
219 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
Mathias Agopianba02cd22013-07-03 16:20:57 -0700220 result.appendFormat(
Aravind Akella70018042014-04-07 22:52:37 +0000221 "%-48s| %-32s| %-48s| 0x%08x | \"%s\"\n\t",
Mathias Agopian3560fb22010-07-22 21:24:39 -0700222 s.getName().string(),
223 s.getVendor().string(),
Aravind Akella70018042014-04-07 22:52:37 +0000224 s.getStringType().string(),
225 s.getHandle(),
226 s.getRequiredPermission().string());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700227
Aravind Akella0e025c52014-06-03 19:19:57 -0700228 const int reportingMode = s.getReportingMode();
229 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
230 result.append("continuous |");
231 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
232 result.append("on-change | ");
233 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
234 result.append("one-shot | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700235 } else {
Aravind Akella0e025c52014-06-03 19:19:57 -0700236 result.append("special-trigger | ");
Mathias Agopianba02cd22013-07-03 16:20:57 -0700237 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700238
239 if (s.getMinDelay() > 0) {
240 result.appendFormat("maxRate=%7.2fHz | ", 1e6f / s.getMinDelay());
241 } else {
242 result.appendFormat("minDelay=%5dus |", s.getMinDelay());
243 }
244
Aravind Akella724d91d2013-06-27 12:04:23 -0700245 if (s.getFifoMaxEventCount() > 0) {
Aravind Akella70018042014-04-07 22:52:37 +0000246 result.appendFormat("FifoMax=%d events | ",
247 s.getFifoMaxEventCount());
Aravind Akella724d91d2013-06-27 12:04:23 -0700248 } else {
249 result.append("no batching support | ");
250 }
Mathias Agopianba02cd22013-07-03 16:20:57 -0700251
252 switch (s.getType()) {
253 case SENSOR_TYPE_ROTATION_VECTOR:
254 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
255 result.appendFormat(
256 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
257 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]);
258 break;
259 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
260 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
261 result.appendFormat(
262 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
263 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]);
264 break;
265 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
266 result.appendFormat(
267 "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n",
268 e.data[0], e.data[1], e.data[2], e.data[3]);
269 break;
270 case SENSOR_TYPE_SIGNIFICANT_MOTION:
271 case SENSOR_TYPE_STEP_DETECTOR:
272 result.appendFormat( "last=<%f>\n", e.data[0]);
273 break;
274 case SENSOR_TYPE_STEP_COUNTER:
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700275 result.appendFormat( "last=<%" PRIu64 ">\n", e.u64.step_counter);
Mathias Agopianba02cd22013-07-03 16:20:57 -0700276 break;
277 default:
278 // default to 3 values
279 result.appendFormat(
280 "last=<%5.1f,%5.1f,%5.1f>\n",
281 e.data[0], e.data[1], e.data[2]);
282 break;
283 }
284 }
285 SensorFusion::getInstance().dump(result);
286 SensorDevice::getInstance().dump(result);
287
Mathias Agopianba02cd22013-07-03 16:20:57 -0700288 result.append("Active sensors:\n");
Mathias Agopianfc328812010-07-14 23:41:37 -0700289 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
Mathias Agopian5d270722010-07-19 15:20:39 -0700290 int handle = mActiveSensors.keyAt(i);
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700291 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
Mathias Agopian5d270722010-07-19 15:20:39 -0700292 getSensorName(handle).string(),
293 handle,
Mathias Agopianfc328812010-07-14 23:41:37 -0700294 mActiveSensors.valueAt(i)->getNumConnections());
Mathias Agopianfc328812010-07-14 23:41:37 -0700295 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700296
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700297 result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800298 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700299 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella4c8b9512013-09-05 17:03:38 -0700300
301 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
302 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
303 if (connection != 0) {
Mark Salyzyn92dc3fc2014-03-12 13:12:44 -0700304 result.appendFormat("Connection Number: %zu \n", i);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700305 connection->dump(result);
306 }
307 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700308 }
309 write(fd, result.string(), result.size());
310 return NO_ERROR;
311}
312
Aravind Akella9a844cf2014-02-11 18:58:52 -0800313void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700314 sensors_event_t const* buffer, const int count) {
315 for (int i=0 ; i<count ; i++) {
316 int handle = buffer[i].sensor;
Aravind Akella0e025c52014-06-03 19:19:57 -0700317 if (connection->hasSensor(handle)) {
318 SensorInterface* sensor = mSensorMap.valueFor(handle);
319 // If this buffer has an event from a one_shot sensor and this connection is registered
320 // for this particular one_shot sensor, try cleaning up the connection.
321 if (sensor != NULL &&
322 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
323 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800324 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700325 }
326 }
327 }
328}
329
Mathias Agopianfc328812010-07-14 23:41:37 -0700330bool SensorService::threadLoop()
331{
Steve Blocka5512372011-12-20 16:23:08 +0000332 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700333
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700334 // each virtual sensor could generate an event per "real" event, that's why we need
335 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
336 // in practice, this is too aggressive, but guaranteed to be enough.
337 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
338 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
339
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700340 sensors_event_t buffer[minBufferSize];
341 sensors_event_t scratch[minBufferSize];
Mathias Agopianf001c922010-11-11 17:58:51 -0800342 SensorDevice& device(SensorDevice::getInstance());
343 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700344
Aravind Akella56ae4262014-07-10 16:01:10 -0700345 SensorEventAckReceiver sender(this);
346 sender.run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Mathias Agopianf001c922010-11-11 17:58:51 -0800347 ssize_t count;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700348 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700349 do {
Mathias Agopianf001c922010-11-11 17:58:51 -0800350 count = device.poll(buffer, numEventMax);
Mathias Agopianfc328812010-07-14 23:41:37 -0700351 if (count<0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000352 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700353 break;
354 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700355
356 // Reset sensors_event_t.flags to zero for all events in the buffer.
357 for (int i = 0; i < count; i++) {
358 buffer[i].flags = 0;
359 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800360 Mutex::Autolock _l(mLock);
361 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
362 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
363 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
364 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
365 // releasing the wakelock.
366 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700367 for (int i = 0; i < count; i++) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800368 if (isWakeUpSensorEvent(buffer[i])) {
369 bufferHasWakeUpEvent = true;
370 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700371 }
372 }
373
Aravind Akella9a844cf2014-02-11 18:58:52 -0800374 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
375 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
376 mWakeLockAcquired = true;
377 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
378 }
379 recordLastValueLocked(buffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800380
Mathias Agopianf001c922010-11-11 17:58:51 -0800381 // handle virtual sensors
382 if (count && vcount) {
Mathias Agopian984826c2011-05-17 22:54:42 -0700383 sensors_event_t const * const event = buffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800384 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800385 if (activeVirtualSensorCount) {
386 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700387 SensorFusion& fusion(SensorFusion::getInstance());
388 if (fusion.isEnabled()) {
389 for (size_t i=0 ; i<size_t(count) ; i++) {
390 fusion.process(event[i]);
391 }
392 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700393 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800394 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700395 if (count + k >= minBufferSize) {
396 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700397 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700398 count, k, minBufferSize);
399 break;
400 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800401 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800402 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700403 if (si->process(&out, event[i])) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800404 buffer[count + k] = out;
405 k++;
406 }
407 }
408 }
409 if (k) {
410 // record the last synthesized values
Aravind Akella9a844cf2014-02-11 18:58:52 -0800411 recordLastValueLocked(&buffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800412 count += k;
413 // sort the buffer by time-stamps
414 sortEventBuffer(buffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700415 }
416 }
417 }
418
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700419 // handle backward compatibility for RotationVector sensor
420 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
421 for (int i = 0; i < count; i++) {
Mathias Agopian7438fd12013-07-08 12:50:39 -0700422 if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700423 // All the 4 components of the quaternion should be available
424 // No heading accuracy. Set it to -1
425 buffer[i].data[4] = -1;
426 }
427 }
428 }
429
Aravind Akella9a844cf2014-02-11 18:58:52 -0800430 // Send our events to clients. Check the state of wake lock for each client and release the
431 // lock if none of the clients need it.
432 bool needsWakeLock = false;
433 for (size_t i=0 ; i < mActiveConnections.size(); i++) {
434 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
Mathias Agopianf001c922010-11-11 17:58:51 -0800435 if (connection != 0) {
436 connection->sendEvents(buffer, count, scratch);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800437 needsWakeLock |= connection->needsWakeLock();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700438 // Some sensors need to be auto disabled after the trigger
Aravind Akella9a844cf2014-02-11 18:58:52 -0800439 cleanupAutoDisabledSensorLocked(connection, buffer, count);
Mathias Agopianf001c922010-11-11 17:58:51 -0800440 }
441 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700442
Aravind Akella9a844cf2014-02-11 18:58:52 -0800443 if (mWakeLockAcquired && !needsWakeLock) {
444 release_wake_lock(WAKE_LOCK_NAME);
445 mWakeLockAcquired = false;
446 ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
447 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700448 } while (count >= 0 || Thread::exitPending());
449
Steve Block3c20fbe2012-01-05 23:22:43 +0000450 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800451 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700452 return false;
453}
454
Aravind Akella56ae4262014-07-10 16:01:10 -0700455sp<Looper> SensorService::getLooper() const {
456 return mLooper;
457}
458
459bool SensorService::SensorEventAckReceiver::threadLoop() {
460 ALOGD("new thread SensorEventAckReceiver");
461 do {
462 sp<Looper> looper = mService->getLooper();
463 looper->pollOnce(-1);
464 } while(!Thread::exitPending());
465 return false;
466}
467
Aravind Akella9a844cf2014-02-11 18:58:52 -0800468void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800469 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800470 const sensors_event_t* last = NULL;
471 for (size_t i = 0; i < count; i++) {
472 const sensors_event_t* event = &buffer[i];
473 if (event->type != SENSOR_TYPE_META_DATA) {
474 if (last && event->sensor != last->sensor) {
475 mLastEventSeen.editValueFor(last->sensor) = *last;
476 }
477 last = event;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800478 }
479 }
Aravind Akella4b847042014-03-03 19:02:46 -0800480 if (last) {
481 mLastEventSeen.editValueFor(last->sensor) = *last;
482 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800483}
484
Mathias Agopianf001c922010-11-11 17:58:51 -0800485void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
486{
487 struct compar {
488 static int cmp(void const* lhs, void const* rhs) {
489 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
490 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700491 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800492 }
493 };
494 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
495}
496
Mathias Agopian5d270722010-07-19 15:20:39 -0700497String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700498 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700499 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700500 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700501 if (sensor.getHandle() == handle) {
502 return sensor.getName();
503 }
504 }
505 String8 result("unknown");
506 return result;
507}
508
Aravind Akellab4099e72013-10-15 15:43:10 -0700509bool SensorService::isVirtualSensor(int handle) const {
510 SensorInterface* sensor = mSensorMap.valueFor(handle);
511 return sensor->isVirtual();
512}
513
Aravind Akella9a844cf2014-02-11 18:58:52 -0800514bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700515 int handle = event.sensor;
516 if (event.type == SENSOR_TYPE_META_DATA) {
517 handle = event.meta_data.sensor;
518 }
519 SensorInterface* sensor = mSensorMap.valueFor(handle);
520 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800521}
522
Mathias Agopianfc328812010-07-14 23:41:37 -0700523Vector<Sensor> SensorService::getSensorList()
524{
Mathias Agopian33264862012-06-28 19:46:54 -0700525 char value[PROPERTY_VALUE_MAX];
526 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000527 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
528 mUserSensorListDebug : mUserSensorList;
529 Vector<Sensor> accessibleSensorList;
530 for (size_t i = 0; i < initialSensorList.size(); i++) {
531 Sensor sensor = initialSensorList[i];
532 if (canAccessSensor(sensor)) {
533 accessibleSensorList.add(sensor);
534 } else {
535 String8 infoMessage;
536 infoMessage.appendFormat(
537 "Skipped sensor %s because it requires permission %s",
538 sensor.getName().string(),
539 sensor.getRequiredPermission().string());
540 ALOGI(infoMessage.string());
541 }
Mathias Agopian33264862012-06-28 19:46:54 -0700542 }
Aravind Akella70018042014-04-07 22:52:37 +0000543 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700544}
545
546sp<ISensorEventConnection> SensorService::createSensorEventConnection()
547{
Mathias Agopian5307d172012-09-18 17:02:43 -0700548 uid_t uid = IPCThreadState::self()->getCallingUid();
549 sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
Mathias Agopianfc328812010-07-14 23:41:37 -0700550 return result;
551}
552
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800553void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700554{
555 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800556 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700557 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700558 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700559 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800560 int handle = mActiveSensors.keyAt(i);
561 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700562 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800563 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000564 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800565 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800566 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800567 }
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800568 }
569 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700570 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000571 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700572 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700573 c, i, handle);
574
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800575 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000576 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700577 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800578 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700579 delete rec;
580 size--;
581 } else {
582 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700583 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700584 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700585 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700586 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800587 if (c->needsWakeLock()) {
588 checkWakeLockStateLocked();
589 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700590}
591
Aravind Akella70018042014-04-07 22:52:37 +0000592Sensor SensorService::getSensorFromHandle(int handle) const {
593 return mSensorMap.valueFor(handle)->getSensor();
594}
595
Mathias Agopianfc328812010-07-14 23:41:37 -0700596status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Aravind Akella724d91d2013-06-27 12:04:23 -0700597 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -0700598{
Mathias Agopian50df2952010-07-19 19:09:10 -0700599 if (mInitCheck != NO_ERROR)
600 return mInitCheck;
601
Mathias Agopianf001c922010-11-11 17:58:51 -0800602 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700603 if (sensor == NULL) {
604 return BAD_VALUE;
605 }
Aravind Akella70018042014-04-07 22:52:37 +0000606
607 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried enabling")) {
608 return BAD_VALUE;
609 }
610
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700611 Mutex::Autolock _l(mLock);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700612 SensorRecord* rec = mActiveSensors.valueFor(handle);
613 if (rec == 0) {
614 rec = new SensorRecord(connection);
615 mActiveSensors.add(handle, rec);
616 if (sensor->isVirtual()) {
617 mActiveVirtualSensors.add(handle, sensor);
618 }
619 } else {
620 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800621 // this sensor is already activated, but we are adding a connection that uses it.
622 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700623 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700624 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800625 // NOTE: The wake_up flag of this event may get set to
626 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700627 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
628 if (event.version == sizeof(sensors_event_t)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800629 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
630 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
631 mWakeLockAcquired = true;
632 ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
633 WAKE_LOCK_NAME);
634 }
635 connection->sendEvents(&event, 1, NULL);
636 if (!connection->needsWakeLock() && mWakeLockAcquired) {
637 checkWakeLockStateLocked();
638 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700639 }
640 }
641 }
642 }
643
644 if (connection->addSensor(handle)) {
645 BatteryService::enableSensor(connection->getUid(), handle);
646 // the sensor was added (which means it wasn't already there)
647 // so, see if this connection becomes active
648 if (mActiveConnections.indexOf(connection) < 0) {
649 mActiveConnections.add(connection);
650 }
651 } else {
652 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
653 handle, connection.get());
654 }
655
Aravind Akella724d91d2013-06-27 12:04:23 -0700656 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
657 if (samplingPeriodNs < minDelayNs) {
658 samplingPeriodNs = minDelayNs;
659 }
660
Mark Salyzyndb458612014-06-10 14:50:02 -0700661 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%" PRId64 " timeout== %" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700662 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
663
664 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
665 maxBatchReportLatencyNs);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700666 if (err == NO_ERROR) {
667 connection->setFirstFlushPending(handle, true);
668 status_t err_flush = sensor->flush(connection.get(), handle);
669 // Flush may return error if the sensor is not activated or the underlying h/w sensor does
670 // not support flush.
671 if (err_flush != NO_ERROR) {
672 connection->setFirstFlushPending(handle, false);
673 }
674 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700675
676 if (err == NO_ERROR) {
677 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
678 err = sensor->activate(connection.get(), true);
679 }
680
Aravind Akella56ae4262014-07-10 16:01:10 -0700681 if (err == NO_ERROR && sensor->getSensor().isWakeUpSensor()) {
682 // Add the file descriptor to the Looper for receiving acknowledgments;
683 int ret = mLooper->addFd(connection->getSensorChannel()->getSendFd(), 0,
684 ALOOPER_EVENT_INPUT, connection.get(), NULL);
685 }
686
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700687 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700688 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700689 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700690 }
691 return err;
692}
693
694status_t SensorService::disable(const sp<SensorEventConnection>& connection,
695 int handle)
696{
Mathias Agopian50df2952010-07-19 19:09:10 -0700697 if (mInitCheck != NO_ERROR)
698 return mInitCheck;
699
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700700 Mutex::Autolock _l(mLock);
701 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700702 if (err == NO_ERROR) {
703 SensorInterface* sensor = mSensorMap.valueFor(handle);
704 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
705 }
706 return err;
707}
708
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700709status_t SensorService::cleanupWithoutDisable(
710 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700711 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700712 return cleanupWithoutDisableLocked(connection, handle);
713}
714
715status_t SensorService::cleanupWithoutDisableLocked(
716 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700717 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700718 if (rec) {
719 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700720 if (connection->removeSensor(handle)) {
721 BatteryService::disableSensor(connection->getUid(), handle);
722 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700723 if (connection->hasAnySensor() == false) {
724 mActiveConnections.remove(connection);
725 }
726 // see if this sensor becomes inactive
727 if (rec->removeConnection(connection)) {
728 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800729 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700730 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -0700731 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700732 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700733 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700734 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -0700735}
736
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700737status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Mathias Agopianfc328812010-07-14 23:41:37 -0700738 int handle, nsecs_t ns)
739{
Mathias Agopian50df2952010-07-19 19:09:10 -0700740 if (mInitCheck != NO_ERROR)
741 return mInitCheck;
742
Mathias Agopianae09d652011-11-01 17:37:49 -0700743 SensorInterface* sensor = mSensorMap.valueFor(handle);
744 if (!sensor)
745 return BAD_VALUE;
746
Aravind Akella70018042014-04-07 22:52:37 +0000747 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried configuring")) {
748 return BAD_VALUE;
749 }
750
Mathias Agopian1cd70002010-07-21 15:59:50 -0700751 if (ns < 0)
752 return BAD_VALUE;
753
Mathias Agopian62569ec2011-11-07 21:21:47 -0800754 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
755 if (ns < minDelayNs) {
756 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -0700757 }
758
Mathias Agopianf001c922010-11-11 17:58:51 -0800759 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -0700760}
761
Aravind Akella724d91d2013-06-27 12:04:23 -0700762status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
763 int handle) {
Aravind Akella70018042014-04-07 22:52:37 +0000764 if (mInitCheck != NO_ERROR) return mInitCheck;
765 SensorInterface* sensor = mSensorMap.valueFor(handle);
766 if (sensor == NULL) {
767 return BAD_VALUE;
768 }
769
770 if (!verifyCanAccessSensor(sensor->getSensor(), "Tried flushing")) {
771 return BAD_VALUE;
772 }
773
Aravind Akella0e025c52014-06-03 19:19:57 -0700774 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
775 ALOGE("flush called on a one-shot sensor");
Aravind Akella70018042014-04-07 22:52:37 +0000776 return INVALID_OPERATION;
777 }
778 return sensor->flush(connection.get(), handle);
Aravind Akella724d91d2013-06-27 12:04:23 -0700779}
Aravind Akella70018042014-04-07 22:52:37 +0000780
781
782bool SensorService::canAccessSensor(const Sensor& sensor) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700783 return (sensor.getRequiredPermission().isEmpty()) ||
784 PermissionCache::checkCallingPermission(String16(sensor.getRequiredPermission()));
Aravind Akella70018042014-04-07 22:52:37 +0000785}
786
787bool SensorService::verifyCanAccessSensor(const Sensor& sensor, const char* operation) {
788 if (canAccessSensor(sensor)) {
789 return true;
790 } else {
791 String8 errorMessage;
792 errorMessage.appendFormat(
793 "%s a sensor (%s) without holding its required permission: %s",
794 operation,
795 sensor.getName().string(),
796 sensor.getRequiredPermission().string());
797 return false;
798 }
799}
800
Aravind Akella9a844cf2014-02-11 18:58:52 -0800801void SensorService::checkWakeLockState() {
802 Mutex::Autolock _l(mLock);
803 checkWakeLockStateLocked();
804}
805
806void SensorService::checkWakeLockStateLocked() {
807 if (!mWakeLockAcquired) {
808 return;
809 }
810 bool releaseLock = true;
811 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
812 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
813 if (connection != 0) {
814 if (connection->needsWakeLock()) {
815 releaseLock = false;
816 break;
817 }
818 }
819 }
820 if (releaseLock) {
821 ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
822 release_wake_lock(WAKE_LOCK_NAME);
823 mWakeLockAcquired = false;
824 }
825}
Mathias Agopianfc328812010-07-14 23:41:37 -0700826// ---------------------------------------------------------------------------
Mathias Agopianfc328812010-07-14 23:41:37 -0700827SensorService::SensorRecord::SensorRecord(
828 const sp<SensorEventConnection>& connection)
829{
830 mConnections.add(connection);
831}
832
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700833bool SensorService::SensorRecord::addConnection(
Mathias Agopianfc328812010-07-14 23:41:37 -0700834 const sp<SensorEventConnection>& connection)
835{
836 if (mConnections.indexOf(connection) < 0) {
837 mConnections.add(connection);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700838 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700839 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700840 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700841}
842
843bool SensorService::SensorRecord::removeConnection(
844 const wp<SensorEventConnection>& connection)
845{
846 ssize_t index = mConnections.indexOf(connection);
847 if (index >= 0) {
848 mConnections.removeItemsAt(index, 1);
849 }
850 return mConnections.size() ? false : true;
851}
852
853// ---------------------------------------------------------------------------
854
855SensorService::SensorEventConnection::SensorEventConnection(
Mathias Agopian5307d172012-09-18 17:02:43 -0700856 const sp<SensorService>& service, uid_t uid)
Aravind Akella56ae4262014-07-10 16:01:10 -0700857 : mService(service), mUid(uid), mWakeLockRefCount(0), mEventCache(NULL), mCacheSize(0),
858 mMaxCacheSize(0) {
Aravind Akella4c8b9512013-09-05 17:03:38 -0700859 const SensorDevice& device(SensorDevice::getInstance());
860 if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
Aravind Akella56ae4262014-07-10 16:01:10 -0700861 // Increase socket buffer size to a max of 100 KB for batching capabilities.
862 mChannel = new BitTube(mService->mSocketBufferSize);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700863 } else {
864 mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED);
865 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700866#if DEBUG_CONNECTIONS
867 mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
868#endif
Mathias Agopianfc328812010-07-14 23:41:37 -0700869}
870
Aravind Akella56ae4262014-07-10 16:01:10 -0700871SensorService::SensorEventConnection::~SensorEventConnection() {
Steve Blocka5512372011-12-20 16:23:08 +0000872 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
Aravind Akella56ae4262014-07-10 16:01:10 -0700873 if (mEventCache != NULL) {
874 delete mEventCache;
875 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700876 mService->cleanupConnection(this);
877}
878
Aravind Akella56ae4262014-07-10 16:01:10 -0700879void SensorService::SensorEventConnection::onFirstRef() {
880 LooperCallback::onFirstRef();
Mathias Agopianfc328812010-07-14 23:41:37 -0700881}
882
Aravind Akella9a844cf2014-02-11 18:58:52 -0800883bool SensorService::SensorEventConnection::needsWakeLock() {
884 Mutex::Autolock _l(mConnectionLock);
885 return mWakeLockRefCount > 0;
886}
887
Aravind Akella4c8b9512013-09-05 17:03:38 -0700888void SensorService::SensorEventConnection::dump(String8& result) {
889 Mutex::Autolock _l(mConnectionLock);
Aravind Akella56ae4262014-07-10 16:01:10 -0700890 result.appendFormat("\t %d WakeLockRefCount \n", mWakeLockRefCount);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700891 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
892 const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
Aravind Akella56ae4262014-07-10 16:01:10 -0700893 result.appendFormat("\t %s | status: %s | pending flush events %d | flush calls %d| uid %d|"
894 "cache size: %d max cache size %d\n",
Aravind Akella4c8b9512013-09-05 17:03:38 -0700895 mService->getSensorName(mSensorInfo.keyAt(i)).string(),
896 flushInfo.mFirstFlushPending ? "First flush pending" :
897 "active",
Patrick Tjineefced12014-02-05 15:06:03 -0800898 flushInfo.mPendingFlushEventsToSend,
Aravind Akella56ae4262014-07-10 16:01:10 -0700899 flushInfo.mNumFlushCalls,
900 mUid,
901 mCacheSize,
902 mMaxCacheSize);
903#if DEBUG_CONNECTIONS
904 result.appendFormat("\t events recvd: %d | sent %d | cache %d | dropped %d\n",
905 mEventsReceived,
906 mEventsSent,
907 mEventsSentFromCache,
908 mEventsReceived - (mEventsSentFromCache +
909 mEventsSent + mCacheSize));
910#endif
911
Aravind Akella4c8b9512013-09-05 17:03:38 -0700912 }
913}
914
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700915bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800916 Mutex::Autolock _l(mConnectionLock);
Aravind Akella70018042014-04-07 22:52:37 +0000917 if (!verifyCanAccessSensor(mService->getSensorFromHandle(handle), "Tried adding")) {
918 return false;
919 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700920 if (mSensorInfo.indexOfKey(handle) < 0) {
921 mSensorInfo.add(handle, FlushInfo());
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700922 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700923 }
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700924 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700925}
926
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700927bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800928 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700929 if (mSensorInfo.removeItem(handle) >= 0) {
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700930 return true;
931 }
932 return false;
Mathias Agopianfc328812010-07-14 23:41:37 -0700933}
934
935bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800936 Mutex::Autolock _l(mConnectionLock);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700937 return mSensorInfo.indexOfKey(handle) >= 0;
Mathias Agopianfc328812010-07-14 23:41:37 -0700938}
939
940bool SensorService::SensorEventConnection::hasAnySensor() const {
Mathias Agopian71d7a5c2010-11-14 20:55:25 -0800941 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700942 return mSensorInfo.size() ? true : false;
943}
944
Aravind Akella4c8b9512013-09-05 17:03:38 -0700945void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
946 bool value) {
947 Mutex::Autolock _l(mConnectionLock);
948 ssize_t index = mSensorInfo.indexOfKey(handle);
949 if (index >= 0) {
950 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
951 flushInfo.mFirstFlushPending = value;
952 }
953}
954
Mathias Agopianfc328812010-07-14 23:41:37 -0700955status_t SensorService::SensorEventConnection::sendEvents(
Mathias Agopiancf510012010-07-22 16:18:10 -0700956 sensors_event_t const* buffer, size_t numEvents,
Aravind Akella56ae4262014-07-10 16:01:10 -0700957 sensors_event_t* scratch) {
Mathias Agopiancf510012010-07-22 16:18:10 -0700958 // filter out events not for this connection
Mathias Agopian3560fb22010-07-22 21:24:39 -0700959 size_t count = 0;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800960 Mutex::Autolock _l(mConnectionLock);
Mathias Agopian3560fb22010-07-22 21:24:39 -0700961 if (scratch) {
962 size_t i=0;
963 while (i<numEvents) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700964 int32_t curr = buffer[i].sensor;
965 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
966 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
967 buffer[i].meta_data.sensor);
968 // Setting curr to the correct sensor to ensure the sensor events per connection are
969 // filtered correctly. buffer[i].sensor is zero for meta_data events.
970 curr = buffer[i].meta_data.sensor;
971 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700972 ssize_t index = mSensorInfo.indexOfKey(curr);
Aravind Akella56ae4262014-07-10 16:01:10 -0700973 // Check if this connection has registered for this sensor. If not continue to the
974 // next sensor_event.
975 if (index < 0) {
976 ++i;
977 continue;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700978 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700979
980 // Check if there is a pending flush_complete event for this sensor on this connection.
981 FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
982 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
983 if (flushInfo.mFirstFlushPending == true) {
984 // This is the first flush before activate is called. Events can now be sent for
985 // this sensor on this connection.
986 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
987 buffer[i].meta_data.sensor);
988 flushInfo.mFirstFlushPending = false;
989 ++i;
990 continue;
991 }
992 }
993
994 // If there is a pending flush complete event for this sensor on this connection,
995 // ignore the event and proceed to the next.
996 if (flushInfo.mFirstFlushPending) {
997 ++i;
998 continue;
999 }
1000
1001 do {
1002 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
1003 // Send flush complete event only if flush() has been explicitly called by
1004 // this app else ignore.
1005 if (flushInfo.mNumFlushCalls > 0) {
1006 scratch[count++] = buffer[i];
1007 flushInfo.mNumFlushCalls--;
1008 }
1009 ++i;
1010 } else {
1011 // Regular sensor event, just copy it to the scratch buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001012 scratch[count++] = buffer[i++];
Aravind Akella56ae4262014-07-10 16:01:10 -07001013 }
1014 } while ((i<numEvents) && ((buffer[i].sensor == curr) ||
1015 (buffer[i].type == SENSOR_TYPE_META_DATA &&
1016 buffer[i].meta_data.sensor == curr)));
Mathias Agopiancf510012010-07-22 16:18:10 -07001017 }
Mathias Agopian3560fb22010-07-22 21:24:39 -07001018 } else {
1019 scratch = const_cast<sensors_event_t *>(buffer);
1020 count = numEvents;
Mathias Agopiancf510012010-07-22 16:18:10 -07001021 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001022
Aravind Akella56ae4262014-07-10 16:01:10 -07001023 // Early return if there are no events for this connection.
1024 if (count == 0) {
1025 return status_t(NO_ERROR);
1026 }
1027
1028#if DEBUG_CONNECTIONS
1029 mEventsReceived += count;
1030#endif
1031 if (mCacheSize != 0) {
1032 // There are some events in the cache which need to be sent first. Copy this buffer to
1033 // the end of cache.
1034 if (mCacheSize + count <= mMaxCacheSize) {
1035 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1036 mCacheSize += count;
1037 } else {
1038 // Some events need to be dropped.
1039 int remaningCacheSize = mMaxCacheSize - mCacheSize;
1040 if (remaningCacheSize != 0) {
1041 memcpy(&mEventCache[mCacheSize], scratch,
1042 remaningCacheSize * sizeof(sensors_event_t));
1043 }
1044 int numEventsDropped = count - remaningCacheSize;
1045 countFlushCompleteEventsLocked(mEventCache, numEventsDropped);
1046 // Drop the first "numEventsDropped" in the cache.
1047 memmove(mEventCache, &mEventCache[numEventsDropped],
1048 (mCacheSize - numEventsDropped) * sizeof(sensors_event_t));
1049
1050 // Copy the remainingEvents in scratch buffer to the end of cache.
1051 memcpy(&mEventCache[mCacheSize - numEventsDropped], scratch + remaningCacheSize,
1052 numEventsDropped * sizeof(sensors_event_t));
1053 }
1054 return status_t(NO_ERROR);
1055 }
1056
1057 int numWakeUpSensorEvents = countWakeUpSensorEventsLocked(scratch, count);
1058 mWakeLockRefCount += numWakeUpSensorEvents;
1059
1060 // NOTE: ASensorEvent and sensors_event_t are the same type.
1061 ssize_t size = SensorEventQueue::write(mChannel,
1062 reinterpret_cast<ASensorEvent const*>(scratch), count);
1063 if (size < 0) {
1064 // Write error, copy events to local cache.
1065 mWakeLockRefCount -= numWakeUpSensorEvents;
1066 if (mEventCache == NULL) {
1067 mMaxCacheSize = computeMaxCacheSizeLocked();
1068 mEventCache = new sensors_event_t[mMaxCacheSize];
1069 mCacheSize = 0;
1070 }
1071 memcpy(&mEventCache[mCacheSize], scratch, count * sizeof(sensors_event_t));
1072 mCacheSize += count;
1073
1074 // Add this file descriptor to the looper to get a callback when this fd is available for
1075 // writing.
1076 mService->getLooper()->addFd(mChannel->getSendFd(), 0,
1077 ALOOPER_EVENT_OUTPUT | ALOOPER_EVENT_INPUT, this, NULL);
1078 return size;
1079 }
1080
1081#if DEBUG_CONNECTIONS
1082 if (size > 0) {
1083 mEventsSent += count;
1084 }
1085#endif
1086
1087 return size < 0 ? status_t(size) : status_t(NO_ERROR);
1088}
1089
1090void SensorService::SensorEventConnection::writeToSocketFromCacheLocked() {
1091 // At a time write at most half the size of the receiver buffer in SensorEventQueue.
1092 const int maxWriteSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2;
1093 // Send pending flush events (if any) before sending events from the buffer.
Aravind Akella4c8b9512013-09-05 17:03:38 -07001094 {
1095 ASensorEvent flushCompleteEvent;
1096 flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
1097 flushCompleteEvent.sensor = 0;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001098 // Loop through all the sensors for this connection and check if there are any pending
1099 // flush complete events to be sent.
1100 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1101 FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
1102 while (flushInfo.mPendingFlushEventsToSend > 0) {
1103 flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
1104 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
1105 if (size < 0) {
Aravind Akella56ae4262014-07-10 16:01:10 -07001106 return;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001107 }
1108 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
Aravind Akella56ae4262014-07-10 16:01:10 -07001109 flushCompleteEvent.meta_data.sensor);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001110 flushInfo.mPendingFlushEventsToSend--;
1111 }
1112 }
1113 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001114 // Write "count" events at a time.
1115 for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
1116 const int count = (mCacheSize - numEventsSent) < maxWriteSize ?
1117 mCacheSize - numEventsSent : maxWriteSize;
1118 int numWakeUpSensorEvents =
1119 countWakeUpSensorEventsLocked(mEventCache + numEventsSent, count);
1120 mWakeLockRefCount += numWakeUpSensorEvents;
Aravind Akella4c8b9512013-09-05 17:03:38 -07001121
Aravind Akella56ae4262014-07-10 16:01:10 -07001122 ssize_t size = SensorEventQueue::write(mChannel,
1123 reinterpret_cast<ASensorEvent const*>(mEventCache + numEventsSent),
1124 count);
1125 if (size < 0) {
1126 memmove(mEventCache, &mEventCache[numEventsSent],
1127 (mCacheSize - numEventsSent) * sizeof(sensors_event_t));
1128 ALOGD_IF(DEBUG_CONNECTIONS, "wrote %d events from cache size==%d ",
1129 numEventsSent, mCacheSize);
1130 mCacheSize -= numEventsSent;
1131 mWakeLockRefCount -= numWakeUpSensorEvents;
1132 return;
1133 }
1134 numEventsSent += count;
1135#if DEBUG_CONNECTIONS
1136 mEventsSentFromCache += count;
1137#endif
Aravind Akellab4099e72013-10-15 15:43:10 -07001138 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001139 ALOGD_IF(DEBUG_CONNECTIONS, "wrote all events from cache size=%d ", mCacheSize);
1140 // All events from the cache have been sent. Reset cache size to zero.
1141 mCacheSize = 0;
1142 // Poll only for ALOOPER_EVENT_INPUT(read) on the file descriptor.
1143 mService->getLooper()->addFd(mChannel->getSendFd(), 0, ALOOPER_EVENT_INPUT, this, NULL);
Mathias Agopianfc328812010-07-14 23:41:37 -07001144}
1145
Aravind Akellac551eac2013-10-14 17:04:42 -07001146void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
Aravind Akella4c8b9512013-09-05 17:03:38 -07001147 sensors_event_t* scratch, const int numEventsDropped) {
1148 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001149 // Count flushComplete events in the events that are about to the dropped. These will be sent
1150 // separately before the next batch of events.
1151 for (int j = 0; j < numEventsDropped; ++j) {
1152 if (scratch[j].type == SENSOR_TYPE_META_DATA) {
1153 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
1154 flushInfo.mPendingFlushEventsToSend++;
1155 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
1156 flushInfo.mPendingFlushEventsToSend);
1157 }
1158 }
1159 return;
1160}
1161
Aravind Akella9a844cf2014-02-11 18:58:52 -08001162int SensorService::SensorEventConnection::countWakeUpSensorEventsLocked(
1163 sensors_event_t* scratch, const int count) {
1164 for (int i = 0; i < count; ++i) {
1165 if (mService->isWakeUpSensorEvent(scratch[i])) {
1166 scratch[i].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001167 return 1;
1168 }
1169 }
1170 return 0;
1171}
1172
Mathias Agopianb3989272011-10-20 18:42:02 -07001173sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
Mathias Agopianfc328812010-07-14 23:41:37 -07001174{
1175 return mChannel;
1176}
1177
1178status_t SensorService::SensorEventConnection::enableDisable(
Aravind Akella724d91d2013-06-27 12:04:23 -07001179 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
1180 int reservedFlags)
Mathias Agopianfc328812010-07-14 23:41:37 -07001181{
1182 status_t err;
1183 if (enabled) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001184 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
1185 reservedFlags);
Aravind Akella56ae4262014-07-10 16:01:10 -07001186
Mathias Agopianfc328812010-07-14 23:41:37 -07001187 } else {
1188 err = mService->disable(this, handle);
1189 }
1190 return err;
1191}
1192
1193status_t SensorService::SensorEventConnection::setEventRate(
Aravind Akella724d91d2013-06-27 12:04:23 -07001194 int handle, nsecs_t samplingPeriodNs)
Mathias Agopianfc328812010-07-14 23:41:37 -07001195{
Aravind Akella724d91d2013-06-27 12:04:23 -07001196 return mService->setEventRate(this, handle, samplingPeriodNs);
Mathias Agopianfc328812010-07-14 23:41:37 -07001197}
1198
Aravind Akella701166d2013-10-08 14:59:26 -07001199status_t SensorService::SensorEventConnection::flush() {
Aravind Akellac551eac2013-10-14 17:04:42 -07001200 SensorDevice& dev(SensorDevice::getInstance());
1201 const int halVersion = dev.getHalDeviceVersion();
Aravind Akella701166d2013-10-08 14:59:26 -07001202 Mutex::Autolock _l(mConnectionLock);
1203 status_t err(NO_ERROR);
Aravind Akellac551eac2013-10-14 17:04:42 -07001204 // Loop through all sensors for this connection and call flush on each of them.
Aravind Akella701166d2013-10-08 14:59:26 -07001205 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1206 const int handle = mSensorInfo.keyAt(i);
Aravind Akella56ae4262014-07-10 16:01:10 -07001207 FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
Aravind Akellab4099e72013-10-15 15:43:10 -07001208 if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
Aravind Akellac551eac2013-10-14 17:04:42 -07001209 // For older devices just increment pending flush count which will send a trivial
1210 // flush complete event.
Aravind Akellac551eac2013-10-14 17:04:42 -07001211 flushInfo.mPendingFlushEventsToSend++;
1212 } else {
1213 status_t err_flush = mService->flushSensor(this, handle);
Aravind Akella56ae4262014-07-10 16:01:10 -07001214 if (err_flush == NO_ERROR) {
1215 flushInfo.mNumFlushCalls++;
1216 } else {
Aravind Akellac551eac2013-10-14 17:04:42 -07001217 ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
1218 }
1219 err = (err_flush != NO_ERROR) ? err_flush : err;
Aravind Akella701166d2013-10-08 14:59:26 -07001220 }
Aravind Akella701166d2013-10-08 14:59:26 -07001221 }
1222 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001223}
Aravind Akella4c8b9512013-09-05 17:03:38 -07001224
Aravind Akella56ae4262014-07-10 16:01:10 -07001225int SensorService::SensorEventConnection::handleEvent(int fd, int events, void* data) {
1226 if (events & ALOOPER_EVENT_HANGUP || events & ALOOPER_EVENT_ERROR) {
1227 return 0;
1228 }
1229
1230 if (events & ALOOPER_EVENT_INPUT) {
1231 char buf;
1232 ssize_t ret = ::recv(fd, &buf, sizeof(buf), MSG_DONTWAIT);
1233
1234 {
1235 Mutex::Autolock _l(mConnectionLock);
1236 --mWakeLockRefCount;
1237 }
1238 // Check if wakelock can be released by sensorservice. mConnectionLock needs to be released
1239 // here as checkWakeLockState() will need it.
1240 if (mWakeLockRefCount == 0) {
1241 mService->checkWakeLockState();
1242 }
1243 // continue getting callbacks.
1244 return 1;
1245 }
1246
1247 if (events & ALOOPER_EVENT_OUTPUT) {
1248 // send sensor data that is stored in mEventCache.
Aravind Akella9a844cf2014-02-11 18:58:52 -08001249 Mutex::Autolock _l(mConnectionLock);
Aravind Akella56ae4262014-07-10 16:01:10 -07001250 writeToSocketFromCacheLocked();
Aravind Akella9a844cf2014-02-11 18:58:52 -08001251 }
Aravind Akella56ae4262014-07-10 16:01:10 -07001252 return 1;
1253}
1254
1255int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
1256 int fifoWakeUpSensors = 0;
1257 int fifoNonWakeUpSensors = 0;
1258 for (size_t i = 0; i < mSensorInfo.size(); ++i) {
1259 const Sensor& sensor = mService->getSensorFromHandle(mSensorInfo.keyAt(i));
1260 if (sensor.getFifoReservedEventCount() == sensor.getFifoMaxEventCount()) {
1261 // Each sensor has a reserved fifo. Sum up the fifo sizes for all wake up sensors and
1262 // non wake_up sensors.
1263 if (sensor.isWakeUpSensor()) {
1264 fifoWakeUpSensors += sensor.getFifoReservedEventCount();
1265 } else {
1266 fifoNonWakeUpSensors += sensor.getFifoReservedEventCount();
1267 }
1268 } else {
1269 // Shared fifo. Compute the max of the fifo sizes for wake_up and non_wake up sensors.
1270 if (sensor.isWakeUpSensor()) {
1271 fifoWakeUpSensors = fifoWakeUpSensors > sensor.getFifoMaxEventCount() ?
1272 fifoWakeUpSensors : sensor.getFifoMaxEventCount();
1273
1274 } else {
1275 fifoNonWakeUpSensors = fifoNonWakeUpSensors > sensor.getFifoMaxEventCount() ?
1276 fifoNonWakeUpSensors : sensor.getFifoMaxEventCount();
1277
1278 }
1279 }
1280 }
1281 if (fifoWakeUpSensors + fifoNonWakeUpSensors == 0) {
1282 // It is extremely unlikely that there is a write failure in non batch mode. Return a cache
1283 // size of 100.
1284 ALOGI("Write failure in non-batch mode");
1285 return 100;
1286 }
1287 return fifoWakeUpSensors + fifoNonWakeUpSensors;
Aravind Akella9a844cf2014-02-11 18:58:52 -08001288}
1289
Mathias Agopianfc328812010-07-14 23:41:37 -07001290// ---------------------------------------------------------------------------
1291}; // namespace android
1292