blob: 66b0f5ad744373fc49fbe6336395d61dfa5e9e9e [file] [log] [blame]
Andreas Huber99fdbb52016-10-10 13:22:58 -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
17#include <inttypes.h>
18#include <math.h>
19#include <stdint.h>
20#include <sys/types.h>
21
22#include <android-base/logging.h>
Andreas Huber99fdbb52016-10-10 13:22:58 -070023#include <utils/Atomic.h>
24#include <utils/Errors.h>
25#include <utils/Singleton.h>
26
27#include "SensorDevice.h"
28#include "SensorService.h"
29
30#include "convert.h"
31
32using android::hardware::sensors::V1_0::ISensors;
33using android::hardware::hidl_vec;
34
35using Event = android::hardware::sensors::V1_0::Event;
36using SensorInfo = android::hardware::sensors::V1_0::SensorInfo;
37using SensorType = android::hardware::sensors::V1_0::SensorType;
38using DynamicSensorInfo = android::hardware::sensors::V1_0::DynamicSensorInfo;
39using SensorInfo = android::hardware::sensors::V1_0::SensorInfo;
40using Result = android::hardware::sensors::V1_0::Result;
41
42using namespace android::hardware::sensors::V1_0::implementation;
43
44namespace android {
45// ---------------------------------------------------------------------------
46
47ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
48
49static status_t StatusFromResult(Result result) {
50 switch (result) {
51 case Result::OK:
52 return OK;
53 case Result::BAD_VALUE:
54 return BAD_VALUE;
55 case Result::PERMISSION_DENIED:
56 return PERMISSION_DENIED;
57 case Result::INVALID_OPERATION:
58 return INVALID_OPERATION;
59 }
60}
61
62SensorDevice::SensorDevice() {
63 mSensors = ISensors::getService("sensors");
64
65 if (mSensors == NULL) {
66 return;
67 }
68
69 mSensors->getSensorsList(
70 [&](const auto &list) {
71 const size_t count = list.size();
72
73 mActivationCount.setCapacity(count);
74 Info model;
75 for (size_t i=0 ; i < count; i++) {
76 sensor_t sensor;
77 convertToSensor(list[i], &sensor);
78 mSensorList.push_back(sensor);
79
80 mActivationCount.add(list[i].sensorHandle, model);
81
82 /* auto result = */mSensors->activate(
83 list[i].sensorHandle, 0 /* enabled */);
84 }
85 });
86}
87
88void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
89 if (connected) {
90 Info model;
91 mActivationCount.add(handle, model);
92 /* auto result = */mSensors->activate(handle, 0 /* enabled */);
93 } else {
94 mActivationCount.removeItem(handle);
95 }
96}
97
98std::string SensorDevice::dump() const {
99 if (mSensors == NULL) return "HAL not initialized\n";
100
101#if 0
102 result.appendFormat("HAL: %s (%s), version %#010x\n",
103 mSensorModule->common.name,
104 mSensorModule->common.author,
105 getHalDeviceVersion());
106#endif
107
108 String8 result;
109 mSensors->getSensorsList([&](const auto &list) {
110 const size_t count = list.size();
111
112 result.appendFormat(
113 "Total %zu h/w sensors, %zu running:\n",
114 count,
115 mActivationCount.size());
116
117 Mutex::Autolock _l(mLock);
118 for (size_t i = 0 ; i < count ; i++) {
119 const Info& info = mActivationCount.valueFor(
120 list[i].sensorHandle);
121
122 if (info.batchParams.isEmpty()) continue;
123 result.appendFormat(
124 "0x%08x) active-count = %zu; ",
125 list[i].sensorHandle,
126 info.batchParams.size());
127
128 result.append("sampling_period(ms) = {");
129 for (size_t j = 0; j < info.batchParams.size(); j++) {
130 const BatchParams& params = info.batchParams.valueAt(j);
131 result.appendFormat(
132 "%.1f%s",
133 params.batchDelay / 1e6f,
134 j < info.batchParams.size() - 1 ? ", " : "");
135 }
136 result.appendFormat(
137 "}, selected = %.1f ms; ",
138 info.bestBatchParams.batchDelay / 1e6f);
139
140 result.append("batching_period(ms) = {");
141 for (size_t j = 0; j < info.batchParams.size(); j++) {
142 BatchParams params = info.batchParams.valueAt(j);
143
144 result.appendFormat(
145 "%.1f%s",
146 params.batchTimeout / 1e6f,
147 j < info.batchParams.size() - 1 ? ", " : "");
148 }
149
150 result.appendFormat(
151 "}, selected = %.1f ms\n",
152 info.bestBatchParams.batchTimeout / 1e6f);
153 }
154 });
155
156 return result.string();
157}
158
159ssize_t SensorDevice::getSensorList(sensor_t const** list) {
160 *list = &mSensorList[0];
161
162 return mSensorList.size();
163}
164
165status_t SensorDevice::initCheck() const {
166 return mSensors != NULL ? NO_ERROR : NO_INIT;
167}
168
169ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
170 if (mSensors == NULL) return NO_INIT;
171
172 ssize_t err;
173
174 mSensors->poll(
175 count,
176 [&](auto result,
177 const auto &events,
178 const auto &dynamicSensorsAdded) {
179 if (result == Result::OK) {
180 convertToSensorEvents(events, dynamicSensorsAdded, buffer);
181 err = (ssize_t)events.size();
182 } else {
183 err = StatusFromResult(result);
184 }
185 });
186
187 return err;
188}
189
190void SensorDevice::autoDisable(void *ident, int handle) {
191 Info& info( mActivationCount.editValueFor(handle) );
192 Mutex::Autolock _l(mLock);
193 info.removeBatchParamsForIdent(ident);
194}
195
196status_t SensorDevice::activate(void* ident, int handle, int enabled) {
197 if (mSensors == NULL) return NO_INIT;
198
199 status_t err(NO_ERROR);
200 bool actuateHardware = false;
201
202 Mutex::Autolock _l(mLock);
203 Info& info( mActivationCount.editValueFor(handle) );
204
205 ALOGD_IF(DEBUG_CONNECTIONS,
206 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
207 ident, handle, enabled, info.batchParams.size());
208
209 if (enabled) {
210 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
211
212 if (isClientDisabledLocked(ident)) {
213 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
214 ident, handle);
215 return INVALID_OPERATION;
216 }
217
218 if (info.batchParams.indexOfKey(ident) >= 0) {
219 if (info.numActiveClients() == 1) {
220 // This is the first connection, we need to activate the underlying h/w sensor.
221 actuateHardware = true;
222 }
223 } else {
224 // Log error. Every activate call should be preceded by a batch() call.
225 ALOGE("\t >>>ERROR: activate called without batch");
226 }
227 } else {
228 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
229
230 // If a connected dynamic sensor is deactivated, remove it from the
231 // dictionary.
232 auto it = mConnectedDynamicSensors.find(handle);
233 if (it != mConnectedDynamicSensors.end()) {
234 delete it->second;
235 mConnectedDynamicSensors.erase(it);
236 }
237
238 if (info.removeBatchParamsForIdent(ident) >= 0) {
239 if (info.numActiveClients() == 0) {
240 // This is the last connection, we need to de-activate the underlying h/w sensor.
241 actuateHardware = true;
242 } else {
243 const int halVersion = getHalDeviceVersion();
244 if (halVersion >= SENSORS_DEVICE_API_VERSION_1_1) {
245 // Call batch for this sensor with the previously calculated best effort
246 // batch_rate and timeout. One of the apps has unregistered for sensor
247 // events, and the best effort batch parameters might have changed.
248 ALOGD_IF(DEBUG_CONNECTIONS,
249 "\t>>> actuating h/w batch %d %d %" PRId64 " %" PRId64, handle,
250 info.bestBatchParams.flags, info.bestBatchParams.batchDelay,
251 info.bestBatchParams.batchTimeout);
252 /* auto result = */mSensors->batch(
253 handle,
254 info.bestBatchParams.flags,
255 info.bestBatchParams.batchDelay,
256 info.bestBatchParams.batchTimeout);
257 }
258 }
259 } else {
260 // sensor wasn't enabled for this ident
261 }
262
263 if (isClientDisabledLocked(ident)) {
264 return NO_ERROR;
265 }
266 }
267
268 if (actuateHardware) {
269 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
270 enabled);
271 err = StatusFromResult(mSensors->activate(handle, enabled));
272 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
273 strerror(-err));
274
275 if (err != NO_ERROR && enabled) {
276 // Failure when enabling the sensor. Clean up on failure.
277 info.removeBatchParamsForIdent(ident);
278 }
279 }
280
281 // On older devices which do not support batch, call setDelay().
282 if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_1 && info.numActiveClients() > 0) {
283 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w setDelay %d %" PRId64, handle,
284 info.bestBatchParams.batchDelay);
285 /* auto result = */mSensors->setDelay(
286 handle, info.bestBatchParams.batchDelay);
287 }
288 return err;
289}
290
291status_t SensorDevice::batch(
292 void* ident,
293 int handle,
294 int flags,
295 int64_t samplingPeriodNs,
296 int64_t maxBatchReportLatencyNs) {
297 if (mSensors == NULL) return NO_INIT;
298
299 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
300 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
301 }
302
303 const int halVersion = getHalDeviceVersion();
304 if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 && maxBatchReportLatencyNs != 0) {
305 // Batch is not supported on older devices return invalid operation.
306 return INVALID_OPERATION;
307 }
308
309 ALOGD_IF(DEBUG_CONNECTIONS,
310 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
311 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
312
313 Mutex::Autolock _l(mLock);
314 Info& info(mActivationCount.editValueFor(handle));
315
316 if (info.batchParams.indexOfKey(ident) < 0) {
317 BatchParams params(flags, samplingPeriodNs, maxBatchReportLatencyNs);
318 info.batchParams.add(ident, params);
319 } else {
320 // A batch has already been called with this ident. Update the batch parameters.
321 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
322 }
323
324 BatchParams prevBestBatchParams = info.bestBatchParams;
325 // Find the minimum of all timeouts and batch_rates for this sensor.
326 info.selectBatchParams();
327
328 ALOGD_IF(DEBUG_CONNECTIONS,
329 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
330 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
331 prevBestBatchParams.batchDelay, info.bestBatchParams.batchDelay,
332 prevBestBatchParams.batchTimeout, info.bestBatchParams.batchTimeout);
333
334 status_t err(NO_ERROR);
335 // If the min period or min timeout has changed since the last batch call, call batch.
336 if (prevBestBatchParams != info.bestBatchParams) {
337 if (halVersion >= SENSORS_DEVICE_API_VERSION_1_1) {
338 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH %d %d %" PRId64 " %" PRId64, handle,
339 info.bestBatchParams.flags, info.bestBatchParams.batchDelay,
340 info.bestBatchParams.batchTimeout);
341 err = StatusFromResult(
342 mSensors->batch(
343 handle,
344 info.bestBatchParams.flags,
345 info.bestBatchParams.batchDelay,
346 info.bestBatchParams.batchTimeout));
347 } else {
348 // For older devices which do not support batch, call setDelay() after activate() is
349 // called. Some older devices may not support calling setDelay before activate(), so
350 // call setDelay in SensorDevice::activate() method.
351 }
352 if (err != NO_ERROR) {
353 ALOGE("sensor batch failed %p %d %d %" PRId64 " %" PRId64 " err=%s",
354 mSensors.get(), handle,
355 info.bestBatchParams.flags, info.bestBatchParams.batchDelay,
356 info.bestBatchParams.batchTimeout, strerror(-err));
357 info.removeBatchParamsForIdent(ident);
358 }
359 }
360 return err;
361}
362
363status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
364 if (mSensors == NULL) return NO_INIT;
365 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
366 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
367 }
368 Mutex::Autolock _l(mLock);
369 if (isClientDisabledLocked(ident)) return INVALID_OPERATION;
370 Info& info( mActivationCount.editValueFor(handle) );
371 // If the underlying sensor is NOT in continuous mode, setDelay() should return an error.
372 // Calling setDelay() in batch mode is an invalid operation.
373 if (info.bestBatchParams.batchTimeout != 0) {
374 return INVALID_OPERATION;
375 }
376 ssize_t index = info.batchParams.indexOfKey(ident);
377 if (index < 0) {
378 return BAD_INDEX;
379 }
380 BatchParams& params = info.batchParams.editValueAt(index);
381 params.batchDelay = samplingPeriodNs;
382 info.selectBatchParams();
383
384 return StatusFromResult(
385 mSensors->setDelay(handle, info.bestBatchParams.batchDelay));
386}
387
388int SensorDevice::getHalDeviceVersion() const {
389 if (mSensors == NULL) return -1;
390 return SENSORS_DEVICE_API_VERSION_1_4;
391}
392
393status_t SensorDevice::flush(void* ident, int handle) {
394 if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_1) {
395 return INVALID_OPERATION;
396 }
397 if (isClientDisabled(ident)) return INVALID_OPERATION;
398 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
399 return StatusFromResult(mSensors->flush(handle));
400}
401
402bool SensorDevice::isClientDisabled(void* ident) {
403 Mutex::Autolock _l(mLock);
404 return isClientDisabledLocked(ident);
405}
406
407bool SensorDevice::isClientDisabledLocked(void* ident) {
408 return mDisabledClients.indexOf(ident) >= 0;
409}
410
411void SensorDevice::enableAllSensors() {
412 Mutex::Autolock _l(mLock);
413 mDisabledClients.clear();
414 ALOGI("cleared mDisabledClients");
415 const int halVersion = getHalDeviceVersion();
416 for (size_t i = 0; i< mActivationCount.size(); ++i) {
417 Info& info = mActivationCount.editValueAt(i);
418 if (info.batchParams.isEmpty()) continue;
419 info.selectBatchParams();
420 const int sensor_handle = mActivationCount.keyAt(i);
421 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
422 sensor_handle);
423 status_t err(NO_ERROR);
424 if (halVersion > SENSORS_DEVICE_API_VERSION_1_0) {
425 err = StatusFromResult(
426 mSensors->batch(
427 sensor_handle,
428 info.bestBatchParams.flags,
429 info.bestBatchParams.batchDelay,
430 info.bestBatchParams.batchTimeout));
431 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
432 }
433
434 if (err == NO_ERROR) {
435 err = StatusFromResult(
436 mSensors->activate(sensor_handle, 1 /* enabled */));
437 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
438 }
439
440 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0) {
441 err = StatusFromResult(
442 mSensors->setDelay(
443 sensor_handle, info.bestBatchParams.batchDelay));
444 ALOGE_IF(err, "Error calling setDelay sensor %d (%s)", sensor_handle, strerror(-err));
445 }
446 }
447}
448
449void SensorDevice::disableAllSensors() {
450 Mutex::Autolock _l(mLock);
451 for (size_t i = 0; i< mActivationCount.size(); ++i) {
452 const Info& info = mActivationCount.valueAt(i);
453 // Check if this sensor has been activated previously and disable it.
454 if (info.batchParams.size() > 0) {
455 const int sensor_handle = mActivationCount.keyAt(i);
456 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
457 sensor_handle);
458 /* auto result = */mSensors->activate(
459 sensor_handle, 0 /* enabled */);
460
461 // Add all the connections that were registered for this sensor to the disabled
462 // clients list.
463 for (size_t j = 0; j < info.batchParams.size(); ++j) {
464 mDisabledClients.add(info.batchParams.keyAt(j));
465 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
466 }
467 }
468 }
469}
470
471status_t SensorDevice::injectSensorData(
472 const sensors_event_t *injected_sensor_event) {
473 ALOGD_IF(DEBUG_CONNECTIONS,
474 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
475 injected_sensor_event->sensor,
476 injected_sensor_event->timestamp, injected_sensor_event->data[0],
477 injected_sensor_event->data[1], injected_sensor_event->data[2],
478 injected_sensor_event->data[3], injected_sensor_event->data[4],
479 injected_sensor_event->data[5]);
480
481 if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_4) {
482 return INVALID_OPERATION;
483 }
484
485 Event ev;
486 convertFromSensorEvent(*injected_sensor_event, &ev);
487
488 return StatusFromResult(mSensors->injectSensorData(ev));
489}
490
491status_t SensorDevice::setMode(uint32_t mode) {
492 if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_4) {
493 return INVALID_OPERATION;
494 }
495
496 return StatusFromResult(
497 mSensors->setOperationMode(
498 static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
499}
500
501// ---------------------------------------------------------------------------
502
503int SensorDevice::Info::numActiveClients() {
504 SensorDevice& device(SensorDevice::getInstance());
505 int num = 0;
506 for (size_t i = 0; i < batchParams.size(); ++i) {
507 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
508 ++num;
509 }
510 }
511 return num;
512}
513
514status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int flags,
515 int64_t samplingPeriodNs,
516 int64_t maxBatchReportLatencyNs) {
517 ssize_t index = batchParams.indexOfKey(ident);
518 if (index < 0) {
519 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64 " timeout=%" PRId64 ") failed (%s)",
520 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
521 return BAD_INDEX;
522 }
523 BatchParams& params = batchParams.editValueAt(index);
524 params.flags = flags;
525 params.batchDelay = samplingPeriodNs;
526 params.batchTimeout = maxBatchReportLatencyNs;
527 return NO_ERROR;
528}
529
530void SensorDevice::Info::selectBatchParams() {
531 BatchParams bestParams(0, -1, -1);
532 SensorDevice& device(SensorDevice::getInstance());
533
534 for (size_t i = 0; i < batchParams.size(); ++i) {
535 if (device.isClientDisabledLocked(batchParams.keyAt(i))) continue;
536 BatchParams params = batchParams.valueAt(i);
537 if (bestParams.batchDelay == -1 || params.batchDelay < bestParams.batchDelay) {
538 bestParams.batchDelay = params.batchDelay;
539 }
540 if (bestParams.batchTimeout == -1 || params.batchTimeout < bestParams.batchTimeout) {
541 bestParams.batchTimeout = params.batchTimeout;
542 }
543 }
544 bestBatchParams = bestParams;
545}
546
547ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
548 ssize_t idx = batchParams.removeItem(ident);
549 if (idx >= 0) {
550 selectBatchParams();
551 }
552 return idx;
553}
554
555void SensorDevice::notifyConnectionDestroyed(void* ident) {
556 Mutex::Autolock _l(mLock);
557 mDisabledClients.remove(ident);
558}
559
560void SensorDevice::convertToSensorEvent(
561 const Event &src, sensors_event_t *dst) {
562 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
563 src, dst);
564
565 if (src.sensorType == SensorType::SENSOR_TYPE_DYNAMIC_SENSOR_META) {
566 const DynamicSensorInfo &dyn = src.u.dynamic;
567
568 dst->dynamic_sensor_meta.connected = dyn.connected;
569 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
570 if (dyn.connected) {
571 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
572 CHECK(it != mConnectedDynamicSensors.end());
573
574 dst->dynamic_sensor_meta.sensor = it->second;
575
576 memcpy(dst->dynamic_sensor_meta.uuid,
577 dyn.uuid.data(),
578 sizeof(dst->dynamic_sensor_meta.uuid));
579 }
580 }
581}
582
583void SensorDevice::convertToSensorEvents(
584 const hidl_vec<Event> &src,
585 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
586 sensors_event_t *dst) {
587 // Allocate a sensor_t structure for each dynamic sensor added and insert
588 // it into the dictionary of connected dynamic sensors keyed by handle.
589 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
590 const SensorInfo &info = dynamicSensorsAdded[i];
591
592 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
593 CHECK(it == mConnectedDynamicSensors.end());
594
595 sensor_t *sensor = new sensor_t;
596 convertToSensor(info, sensor);
597
598 mConnectedDynamicSensors.insert(
599 std::make_pair(sensor->handle, sensor));
600 }
601
602 for (size_t i = 0; i < src.size(); ++i) {
603 convertToSensorEvent(src[i], &dst[i]);
604 }
605}
606
607// ---------------------------------------------------------------------------
608}; // namespace android
609