1 /*
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 "SensorDevice.h"
18
19 #include "android/hardware/sensors/2.0/types.h"
20 #include "android/hardware/sensors/2.1/types.h"
21 #include "convertV2_1.h"
22
23 #include "AidlSensorHalWrapper.h"
24 #include "HidlSensorHalWrapper.h"
25
26 #include <android-base/logging.h>
27 #include <android/util/ProtoOutputStream.h>
28 #include <cutils/atomic.h>
29 #include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
30 #include <hardware/sensors-base.h>
31 #include <hardware/sensors.h>
32 #include <sensors/convert.h>
33 #include <utils/Errors.h>
34 #include <utils/Singleton.h>
35
36 #include <chrono>
37 #include <cinttypes>
38 #include <cstddef>
39 #include <thread>
40
41 using namespace android::hardware::sensors;
42 using android::util::ProtoOutputStream;
43
44 namespace android {
45 // ---------------------------------------------------------------------------
46
47 ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
48
49 namespace {
50
51 template <typename EnumType>
asBaseType(EnumType value)52 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
53 return static_cast<typename std::underlying_type<EnumType>::type>(value);
54 }
55
56 // Used internally by the framework to wake the Event FMQ. These values must start after
57 // the last value of EventQueueFlagBits
58 enum EventQueueFlagBitsInternal : uint32_t {
59 INTERNAL_WAKE = 1 << 16,
60 };
61
62 enum DevicePrivateBase : int32_t {
63 DEVICE_PRIVATE_BASE = 65536,
64 };
65
66 } // anonymous namespace
67
SensorDevice()68 SensorDevice::SensorDevice() {
69 if (!connectHalService()) {
70 return;
71 }
72
73 initializeSensorList();
74
75 mIsDirectReportSupported = (mHalWrapper->unregisterDirectChannel(-1) != INVALID_OPERATION);
76 }
77
initializeSensorList()78 void SensorDevice::initializeSensorList() {
79 if (mHalWrapper == nullptr) {
80 return;
81 }
82
83 auto list = mHalWrapper->getSensorsList();
84 const size_t count = list.size();
85
86 mActivationCount.setCapacity(count);
87 Info model;
88 for (size_t i = 0; i < count; i++) {
89 sensor_t sensor = list[i];
90
91 if (sensor.type < DEVICE_PRIVATE_BASE) {
92 sensor.resolution = SensorDeviceUtils::resolutionForSensor(sensor);
93
94 // Some sensors don't have a default resolution and will be left at 0.
95 // Don't crash in this case since CTS will verify that devices don't go to
96 // production with a resolution of 0.
97 if (sensor.resolution != 0) {
98 float quantizedRange = sensor.maxRange;
99 SensorDeviceUtils::quantizeValue(&quantizedRange, sensor.resolution,
100 /*factor=*/1);
101 // Only rewrite maxRange if the requantization produced a "significant"
102 // change, which is fairly arbitrarily defined as resolution / 8.
103 // Smaller deltas are permitted, as they may simply be due to floating
104 // point representation error, etc.
105 if (fabsf(sensor.maxRange - quantizedRange) > sensor.resolution / 8) {
106 ALOGW("%s's max range %.12f is not a multiple of the resolution "
107 "%.12f - updated to %.12f",
108 sensor.name, sensor.maxRange, sensor.resolution, quantizedRange);
109 sensor.maxRange = quantizedRange;
110 }
111 } else {
112 // Don't crash here or the device will go into a crashloop.
113 ALOGW("%s should have a non-zero resolution", sensor.name);
114 }
115 }
116
117 // Check and clamp power if it is 0 (or close)
118 constexpr float MIN_POWER_MA = 0.001; // 1 microAmp
119 if (sensor.power < MIN_POWER_MA) {
120 ALOGI("%s's reported power %f invalid, clamped to %f", sensor.name, sensor.power,
121 MIN_POWER_MA);
122 sensor.power = MIN_POWER_MA;
123 }
124 mSensorList.push_back(sensor);
125
126 mActivationCount.add(list[i].handle, model);
127
128 // Only disable all sensors on HAL 1.0 since HAL 2.0
129 // handles this in its initialize method
130 if (!mHalWrapper->supportsMessageQueues()) {
131 mHalWrapper->activate(list[i].handle, 0 /* enabled */);
132 }
133 }
134 }
135
~SensorDevice()136 SensorDevice::~SensorDevice() {}
137
connectHalService()138 bool SensorDevice::connectHalService() {
139 std::unique_ptr<ISensorHalWrapper> aidl_wrapper = std::make_unique<AidlSensorHalWrapper>();
140 if (aidl_wrapper->connect(this)) {
141 mHalWrapper = std::move(aidl_wrapper);
142 return true;
143 }
144
145 std::unique_ptr<ISensorHalWrapper> hidl_wrapper = std::make_unique<HidlSensorHalWrapper>();
146 if (hidl_wrapper->connect(this)) {
147 mHalWrapper = std::move(hidl_wrapper);
148 return true;
149 }
150
151 // TODO: check aidl connection;
152 return false;
153 }
154
prepareForReconnect()155 void SensorDevice::prepareForReconnect() {
156 mHalWrapper->prepareForReconnect();
157 }
158
reconnect()159 void SensorDevice::reconnect() {
160 Mutex::Autolock _l(mLock);
161
162 auto previousActivations = mActivationCount;
163 auto previousSensorList = mSensorList;
164
165 mActivationCount.clear();
166 mSensorList.clear();
167
168 if (mHalWrapper->connect(this)) {
169 initializeSensorList();
170
171 if (sensorHandlesChanged(previousSensorList, mSensorList)) {
172 LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
173 } else {
174 reactivateSensors(previousActivations);
175 }
176 }
177 mHalWrapper->mReconnecting = false;
178 }
179
sensorHandlesChanged(const std::vector<sensor_t> & oldSensorList,const std::vector<sensor_t> & newSensorList)180 bool SensorDevice::sensorHandlesChanged(const std::vector<sensor_t>& oldSensorList,
181 const std::vector<sensor_t>& newSensorList) {
182 bool didChange = false;
183
184 if (oldSensorList.size() != newSensorList.size()) {
185 ALOGI("Sensor list size changed from %zu to %zu", oldSensorList.size(),
186 newSensorList.size());
187 didChange = true;
188 }
189
190 for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
191 bool found = false;
192 const sensor_t& newSensor = newSensorList[i];
193 for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
194 const sensor_t& prevSensor = oldSensorList[j];
195 if (prevSensor.handle == newSensor.handle) {
196 found = true;
197 if (!sensorIsEquivalent(prevSensor, newSensor)) {
198 ALOGI("Sensor %s not equivalent to previous version", newSensor.name);
199 didChange = true;
200 }
201 }
202 }
203
204 if (!found) {
205 // Could not find the new sensor in the old list of sensors, the lists must
206 // have changed.
207 ALOGI("Sensor %s (handle %d) did not exist before", newSensor.name, newSensor.handle);
208 didChange = true;
209 }
210 }
211 return didChange;
212 }
213
sensorIsEquivalent(const sensor_t & prevSensor,const sensor_t & newSensor)214 bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
215 bool equivalent = true;
216 if (prevSensor.handle != newSensor.handle ||
217 (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
218 (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
219 (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
220 (prevSensor.version != newSensor.version) || (prevSensor.type != newSensor.type) ||
221 (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
222 (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
223 (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
224 (prevSensor.minDelay != newSensor.minDelay) ||
225 (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
226 (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
227 (prevSensor.maxDelay != newSensor.maxDelay) || (prevSensor.flags != newSensor.flags)) {
228 equivalent = false;
229 }
230 return equivalent;
231 }
232
reactivateSensors(const DefaultKeyedVector<int,Info> & previousActivations)233 void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
234 for (size_t i = 0; i < mSensorList.size(); i++) {
235 int handle = mSensorList[i].handle;
236 ssize_t activationIndex = previousActivations.indexOfKey(handle);
237 if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
238 continue;
239 }
240
241 const Info& info = previousActivations[activationIndex];
242 for (size_t j = 0; j < info.batchParams.size(); j++) {
243 const BatchParams& batchParams = info.batchParams[j];
244 status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
245 batchParams.mTSample, batchParams.mTBatch);
246
247 if (res == NO_ERROR) {
248 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
249 }
250 }
251 }
252 }
253
handleDynamicSensorConnection(int handle,bool connected)254 void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
255 // not need to check mSensors because this is is only called after successful poll()
256 if (connected) {
257 Info model;
258 mActivationCount.add(handle, model);
259 mHalWrapper->activate(handle, 0 /* enabled */);
260 } else {
261 mActivationCount.removeItem(handle);
262 }
263 }
264
dump() const265 std::string SensorDevice::dump() const {
266 if (mHalWrapper == nullptr) return "HAL not initialized\n";
267
268 String8 result;
269 result.appendFormat("Total %zu h/w sensors, %zu running %zu disabled clients:\n",
270 mSensorList.size(), mActivationCount.size(), mDisabledClients.size());
271
272 Mutex::Autolock _l(mLock);
273 for (const auto& s : mSensorList) {
274 int32_t handle = s.handle;
275 const Info& info = mActivationCount.valueFor(handle);
276 if (info.numActiveClients() == 0) continue;
277
278 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
279
280 result.append("sampling_period(ms) = {");
281 for (size_t j = 0; j < info.batchParams.size(); j++) {
282 const BatchParams& params = info.batchParams[j];
283 result.appendFormat("%.1f%s%s", params.mTSample / 1e6f,
284 isClientDisabledLocked(info.batchParams.keyAt(j)) ? "(disabled)"
285 : "",
286 (j < info.batchParams.size() - 1) ? ", " : "");
287 }
288 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
289
290 result.append("batching_period(ms) = {");
291 for (size_t j = 0; j < info.batchParams.size(); j++) {
292 const BatchParams& params = info.batchParams[j];
293 result.appendFormat("%.1f%s%s", params.mTBatch / 1e6f,
294 isClientDisabledLocked(info.batchParams.keyAt(j)) ? "(disabled)"
295 : "",
296 (j < info.batchParams.size() - 1) ? ", " : "");
297 }
298 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
299 }
300
301 return result.string();
302 }
303
304 /**
305 * Dump debugging information as android.service.SensorDeviceProto protobuf message using
306 * ProtoOutputStream.
307 *
308 * See proto definition and some notes about ProtoOutputStream in
309 * frameworks/base/core/proto/android/service/sensor_service.proto
310 */
dump(ProtoOutputStream * proto) const311 void SensorDevice::dump(ProtoOutputStream* proto) const {
312 using namespace service::SensorDeviceProto;
313 if (mHalWrapper == nullptr) {
314 proto->write(INITIALIZED, false);
315 return;
316 }
317 proto->write(INITIALIZED, true);
318 proto->write(TOTAL_SENSORS, int(mSensorList.size()));
319 proto->write(ACTIVE_SENSORS, int(mActivationCount.size()));
320
321 Mutex::Autolock _l(mLock);
322 for (const auto& s : mSensorList) {
323 int32_t handle = s.handle;
324 const Info& info = mActivationCount.valueFor(handle);
325 if (info.numActiveClients() == 0) continue;
326
327 uint64_t token = proto->start(SENSORS);
328 proto->write(SensorProto::HANDLE, handle);
329 proto->write(SensorProto::ACTIVE_COUNT, int(info.batchParams.size()));
330 for (size_t j = 0; j < info.batchParams.size(); j++) {
331 const BatchParams& params = info.batchParams[j];
332 proto->write(SensorProto::SAMPLING_PERIOD_MS, params.mTSample / 1e6f);
333 proto->write(SensorProto::BATCHING_PERIOD_MS, params.mTBatch / 1e6f);
334 }
335 proto->write(SensorProto::SAMPLING_PERIOD_SELECTED, info.bestBatchParams.mTSample / 1e6f);
336 proto->write(SensorProto::BATCHING_PERIOD_SELECTED, info.bestBatchParams.mTBatch / 1e6f);
337 proto->end(token);
338 }
339 }
340
getSensorList(sensor_t const ** list)341 ssize_t SensorDevice::getSensorList(sensor_t const** list) {
342 *list = &mSensorList[0];
343
344 return mSensorList.size();
345 }
346
initCheck() const347 status_t SensorDevice::initCheck() const {
348 return mHalWrapper != nullptr ? NO_ERROR : NO_INIT;
349 }
350
poll(sensors_event_t * buffer,size_t count)351 ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
352 if (mHalWrapper == nullptr) return NO_INIT;
353
354 ssize_t eventsRead = 0;
355 if (mHalWrapper->supportsMessageQueues()) {
356 eventsRead = mHalWrapper->pollFmq(buffer, count);
357 } else if (mHalWrapper->supportsPolling()) {
358 eventsRead = mHalWrapper->poll(buffer, count);
359 } else {
360 ALOGE("Must support polling or FMQ");
361 eventsRead = -1;
362 }
363
364 if (eventsRead > 0) {
365 for (ssize_t i = 0; i < eventsRead; i++) {
366 float resolution = getResolutionForSensor(buffer[i].sensor);
367 android::SensorDeviceUtils::quantizeSensorEventValues(&buffer[i], resolution);
368
369 if (buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
370 struct dynamic_sensor_meta_event& dyn = buffer[i].dynamic_sensor_meta;
371 if (dyn.connected) {
372 std::unique_lock<std::mutex> lock(mDynamicSensorsMutex);
373 // Give MAX_DYN_SENSOR_WAIT_SEC for onDynamicSensorsConnected to be invoked
374 // since it can be received out of order from this event due to a bug in the
375 // HIDL spec that marks it as oneway.
376 auto it = mConnectedDynamicSensors.find(dyn.handle);
377 if (it == mConnectedDynamicSensors.end()) {
378 mDynamicSensorsCv.wait_for(lock, MAX_DYN_SENSOR_WAIT, [&, dyn] {
379 return mConnectedDynamicSensors.find(dyn.handle) !=
380 mConnectedDynamicSensors.end();
381 });
382 it = mConnectedDynamicSensors.find(dyn.handle);
383 CHECK(it != mConnectedDynamicSensors.end());
384 }
385
386 dyn.sensor = &it->second;
387 }
388 }
389 }
390 }
391
392 return eventsRead;
393 }
394
onDynamicSensorsConnected(const std::vector<sensor_t> & dynamicSensorsAdded)395 void SensorDevice::onDynamicSensorsConnected(const std::vector<sensor_t>& dynamicSensorsAdded) {
396 std::unique_lock<std::mutex> lock(mDynamicSensorsMutex);
397
398 // Allocate a sensor_t structure for each dynamic sensor added and insert
399 // it into the dictionary of connected dynamic sensors keyed by handle.
400 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
401 const sensor_t& sensor = dynamicSensorsAdded[i];
402
403 auto it = mConnectedDynamicSensors.find(sensor.handle);
404 CHECK(it == mConnectedDynamicSensors.end());
405
406 mConnectedDynamicSensors.insert(std::make_pair(sensor.handle, sensor));
407 }
408
409 mDynamicSensorsCv.notify_all();
410 }
411
onDynamicSensorsDisconnected(const std::vector<int32_t> &)412 void SensorDevice::onDynamicSensorsDisconnected(
413 const std::vector<int32_t>& /* dynamicSensorHandlesRemoved */) {
414 // TODO: Currently dynamic sensors do not seem to be removed
415 }
416
writeWakeLockHandled(uint32_t count)417 void SensorDevice::writeWakeLockHandled(uint32_t count) {
418 if (mHalWrapper != nullptr && mHalWrapper->supportsMessageQueues()) {
419 mHalWrapper->writeWakeLockHandled(count);
420 }
421 }
422
autoDisable(void * ident,int handle)423 void SensorDevice::autoDisable(void* ident, int handle) {
424 Mutex::Autolock _l(mLock);
425 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
426 if (activationIndex < 0) {
427 ALOGW("Handle %d cannot be found in activation record", handle);
428 return;
429 }
430 Info& info(mActivationCount.editValueAt(activationIndex));
431 info.removeBatchParamsForIdent(ident);
432 if (info.numActiveClients() == 0) {
433 info.isActive = false;
434 }
435 }
436
activate(void * ident,int handle,int enabled)437 status_t SensorDevice::activate(void* ident, int handle, int enabled) {
438 if (mHalWrapper == nullptr) return NO_INIT;
439
440 Mutex::Autolock _l(mLock);
441 return activateLocked(ident, handle, enabled);
442 }
443
activateLocked(void * ident,int handle,int enabled)444 status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
445 bool activateHardware = false;
446
447 status_t err(NO_ERROR);
448
449 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
450 if (activationIndex < 0) {
451 ALOGW("Handle %d cannot be found in activation record", handle);
452 return BAD_VALUE;
453 }
454 Info& info(mActivationCount.editValueAt(activationIndex));
455
456 ALOGD_IF(DEBUG_CONNECTIONS,
457 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu", ident,
458 handle, enabled, info.batchParams.size());
459
460 if (enabled) {
461 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
462
463 if (isClientDisabledLocked(ident)) {
464 ALOGW("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d", ident,
465 handle);
466 return NO_ERROR;
467 }
468
469 if (info.batchParams.indexOfKey(ident) >= 0) {
470 if (info.numActiveClients() > 0 && !info.isActive) {
471 activateHardware = true;
472 }
473 } else {
474 // Log error. Every activate call should be preceded by a batch() call.
475 ALOGE("\t >>>ERROR: activate called without batch");
476 }
477 } else {
478 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
479
480 // If a connected dynamic sensor is deactivated, remove it from the
481 // dictionary.
482 auto it = mConnectedDynamicSensors.find(handle);
483 if (it != mConnectedDynamicSensors.end()) {
484 mConnectedDynamicSensors.erase(it);
485 }
486
487 if (info.removeBatchParamsForIdent(ident) >= 0) {
488 if (info.numActiveClients() == 0) {
489 // This is the last connection, we need to de-activate the underlying h/w sensor.
490 activateHardware = true;
491 } else {
492 // Call batch for this sensor with the previously calculated best effort
493 // batch_rate and timeout. One of the apps has unregistered for sensor
494 // events, and the best effort batch parameters might have changed.
495 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64,
496 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
497 mHalWrapper->batch(handle, info.bestBatchParams.mTSample,
498 info.bestBatchParams.mTBatch);
499 }
500 } else {
501 // sensor wasn't enabled for this ident
502 }
503
504 if (isClientDisabledLocked(ident)) {
505 return NO_ERROR;
506 }
507 }
508
509 if (activateHardware) {
510 err = doActivateHardwareLocked(handle, enabled);
511
512 if (err != NO_ERROR && enabled) {
513 // Failure when enabling the sensor. Clean up on failure.
514 info.removeBatchParamsForIdent(ident);
515 } else {
516 // Update the isActive flag if there is no error. If there is an error when disabling a
517 // sensor, still set the flag to false since the batch parameters have already been
518 // removed. This ensures that everything remains in-sync.
519 info.isActive = enabled;
520 }
521 }
522
523 return err;
524 }
525
doActivateHardwareLocked(int handle,bool enabled)526 status_t SensorDevice::doActivateHardwareLocked(int handle, bool enabled) {
527 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
528 enabled);
529 status_t err = mHalWrapper->activate(handle, enabled);
530 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
531 strerror(-err));
532 return err;
533 }
534
batch(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)535 status_t SensorDevice::batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
536 int64_t maxBatchReportLatencyNs) {
537 if (mHalWrapper == nullptr) return NO_INIT;
538
539 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
540 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
541 }
542 if (maxBatchReportLatencyNs < 0) {
543 maxBatchReportLatencyNs = 0;
544 }
545
546 ALOGD_IF(DEBUG_CONNECTIONS,
547 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64
548 " timeout=%" PRId64,
549 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
550
551 Mutex::Autolock _l(mLock);
552 return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
553 }
554
batchLocked(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)555 status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
556 int64_t maxBatchReportLatencyNs) {
557 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
558 if (activationIndex < 0) {
559 ALOGW("Handle %d cannot be found in activation record", handle);
560 return BAD_VALUE;
561 }
562 Info& info(mActivationCount.editValueAt(activationIndex));
563
564 if (info.batchParams.indexOfKey(ident) < 0) {
565 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
566 info.batchParams.add(ident, params);
567 } else {
568 // A batch has already been called with this ident. Update the batch parameters.
569 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
570 }
571
572 status_t err = updateBatchParamsLocked(handle, info);
573 if (err != NO_ERROR) {
574 ALOGE("sensor batch failed 0x%08x %" PRId64 " %" PRId64 " err=%s", handle,
575 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch, strerror(-err));
576 info.removeBatchParamsForIdent(ident);
577 }
578
579 return err;
580 }
581
updateBatchParamsLocked(int handle,Info & info)582 status_t SensorDevice::updateBatchParamsLocked(int handle, Info& info) {
583 BatchParams prevBestBatchParams = info.bestBatchParams;
584 // Find the minimum of all timeouts and batch_rates for this sensor.
585 info.selectBatchParams();
586
587 ALOGD_IF(DEBUG_CONNECTIONS,
588 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64 " curr_timeout=%" PRId64
589 " min_timeout=%" PRId64,
590 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
591 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
592
593 status_t err(NO_ERROR);
594 // If the min period or min timeout has changed since the last batch call, call batch.
595 if (prevBestBatchParams != info.bestBatchParams && info.numActiveClients() > 0) {
596 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
597 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
598 err = mHalWrapper->batch(handle, info.bestBatchParams.mTSample,
599 info.bestBatchParams.mTBatch);
600 }
601
602 return err;
603 }
604
setDelay(void * ident,int handle,int64_t samplingPeriodNs)605 status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
606 return batch(ident, handle, 0, samplingPeriodNs, 0);
607 }
608
getHalDeviceVersion() const609 int SensorDevice::getHalDeviceVersion() const {
610 if (mHalWrapper == nullptr) return -1;
611 return SENSORS_DEVICE_API_VERSION_1_4;
612 }
613
flush(void * ident,int handle)614 status_t SensorDevice::flush(void* ident, int handle) {
615 if (mHalWrapper == nullptr) return NO_INIT;
616 if (isClientDisabled(ident)) return INVALID_OPERATION;
617 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
618 return mHalWrapper->flush(handle);
619 }
620
isClientDisabled(void * ident) const621 bool SensorDevice::isClientDisabled(void* ident) const {
622 Mutex::Autolock _l(mLock);
623 return isClientDisabledLocked(ident);
624 }
625
isClientDisabledLocked(void * ident) const626 bool SensorDevice::isClientDisabledLocked(void* ident) const {
627 return mDisabledClients.count(ident) > 0;
628 }
629
getDisabledClientsLocked() const630 std::vector<void*> SensorDevice::getDisabledClientsLocked() const {
631 std::vector<void*> vec;
632 for (const auto& it : mDisabledClients) {
633 vec.push_back(it.first);
634 }
635
636 return vec;
637 }
638
addDisabledReasonForIdentLocked(void * ident,DisabledReason reason)639 void SensorDevice::addDisabledReasonForIdentLocked(void* ident, DisabledReason reason) {
640 mDisabledClients[ident] |= 1 << reason;
641 }
642
removeDisabledReasonForIdentLocked(void * ident,DisabledReason reason)643 void SensorDevice::removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason) {
644 if (isClientDisabledLocked(ident)) {
645 mDisabledClients[ident] &= ~(1 << reason);
646 if (mDisabledClients[ident] == 0) {
647 mDisabledClients.erase(ident);
648 }
649 }
650 }
651
setUidStateForConnection(void * ident,SensorService::UidState state)652 void SensorDevice::setUidStateForConnection(void* ident, SensorService::UidState state) {
653 Mutex::Autolock _l(mLock);
654 if (state == SensorService::UID_STATE_ACTIVE) {
655 removeDisabledReasonForIdentLocked(ident, DisabledReason::DISABLED_REASON_UID_IDLE);
656 } else {
657 addDisabledReasonForIdentLocked(ident, DisabledReason::DISABLED_REASON_UID_IDLE);
658 }
659
660 for (size_t i = 0; i < mActivationCount.size(); ++i) {
661 int handle = mActivationCount.keyAt(i);
662 Info& info = mActivationCount.editValueAt(i);
663
664 if (info.hasBatchParamsForIdent(ident)) {
665 updateBatchParamsLocked(handle, info);
666 bool disable = info.numActiveClients() == 0 && info.isActive;
667 bool enable = info.numActiveClients() > 0 && !info.isActive;
668
669 if ((enable || disable) && doActivateHardwareLocked(handle, enable) == NO_ERROR) {
670 info.isActive = enable;
671 }
672 }
673 }
674 }
675
isSensorActive(int handle) const676 bool SensorDevice::isSensorActive(int handle) const {
677 Mutex::Autolock _l(mLock);
678 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
679 if (activationIndex < 0) {
680 return false;
681 }
682 return mActivationCount.valueAt(activationIndex).isActive;
683 }
684
onMicSensorAccessChanged(void * ident,int handle,nsecs_t samplingPeriodNs)685 void SensorDevice::onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs) {
686 Mutex::Autolock _l(mLock);
687 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
688 if (activationIndex < 0) {
689 ALOGW("Handle %d cannot be found in activation record", handle);
690 return;
691 }
692 Info& info(mActivationCount.editValueAt(activationIndex));
693 if (info.hasBatchParamsForIdent(ident)) {
694 ssize_t index = info.batchParams.indexOfKey(ident);
695 BatchParams& params = info.batchParams.editValueAt(index);
696 params.mTSample = samplingPeriodNs;
697 }
698 }
699
enableAllSensors()700 void SensorDevice::enableAllSensors() {
701 if (mHalWrapper == nullptr) return;
702 Mutex::Autolock _l(mLock);
703
704 for (void* client : getDisabledClientsLocked()) {
705 removeDisabledReasonForIdentLocked(client,
706 DisabledReason::DISABLED_REASON_SERVICE_RESTRICTED);
707 }
708
709 for (size_t i = 0; i < mActivationCount.size(); ++i) {
710 Info& info = mActivationCount.editValueAt(i);
711 if (info.batchParams.isEmpty()) continue;
712 info.selectBatchParams();
713 const int sensor_handle = mActivationCount.keyAt(i);
714 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
715 sensor_handle);
716 status_t err = mHalWrapper->batch(sensor_handle, info.bestBatchParams.mTSample,
717 info.bestBatchParams.mTBatch);
718 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
719
720 if (err == NO_ERROR) {
721 err = mHalWrapper->activate(sensor_handle, 1 /* enabled */);
722 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
723 }
724
725 if (err == NO_ERROR) {
726 info.isActive = true;
727 }
728 }
729 }
730
disableAllSensors()731 void SensorDevice::disableAllSensors() {
732 if (mHalWrapper == nullptr) return;
733 Mutex::Autolock _l(mLock);
734 for (size_t i = 0; i < mActivationCount.size(); ++i) {
735 Info& info = mActivationCount.editValueAt(i);
736 // Check if this sensor has been activated previously and disable it.
737 if (info.batchParams.size() > 0) {
738 const int sensor_handle = mActivationCount.keyAt(i);
739 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
740 sensor_handle);
741 mHalWrapper->activate(sensor_handle, 0 /* enabled */);
742
743 // Add all the connections that were registered for this sensor to the disabled
744 // clients list.
745 for (size_t j = 0; j < info.batchParams.size(); ++j) {
746 addDisabledReasonForIdentLocked(info.batchParams.keyAt(j),
747 DisabledReason::DISABLED_REASON_SERVICE_RESTRICTED);
748 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
749 }
750
751 info.isActive = false;
752 }
753 }
754 }
755
injectSensorData(const sensors_event_t * injected_sensor_event)756 status_t SensorDevice::injectSensorData(const sensors_event_t* injected_sensor_event) {
757 if (mHalWrapper == nullptr) return NO_INIT;
758 ALOGD_IF(DEBUG_CONNECTIONS,
759 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
760 injected_sensor_event->sensor, injected_sensor_event->timestamp,
761 injected_sensor_event->data[0], injected_sensor_event->data[1],
762 injected_sensor_event->data[2], injected_sensor_event->data[3],
763 injected_sensor_event->data[4], injected_sensor_event->data[5]);
764
765 return mHalWrapper->injectSensorData(injected_sensor_event);
766 }
767
setMode(uint32_t mode)768 status_t SensorDevice::setMode(uint32_t mode) {
769 if (mHalWrapper == nullptr) return NO_INIT;
770 return mHalWrapper->setOperationMode(static_cast<SensorService::Mode>(mode));
771 }
772
registerDirectChannel(const sensors_direct_mem_t * memory)773 int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
774 if (mHalWrapper == nullptr) return NO_INIT;
775 Mutex::Autolock _l(mLock);
776
777 int32_t channelHandle;
778 status_t status = mHalWrapper->registerDirectChannel(memory, &channelHandle);
779 if (status != OK) {
780 channelHandle = -1;
781 }
782
783 return channelHandle;
784 }
785
unregisterDirectChannel(int32_t channelHandle)786 void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
787 mHalWrapper->unregisterDirectChannel(channelHandle);
788 }
789
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)790 int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
791 const struct sensors_direct_cfg_t* config) {
792 if (mHalWrapper == nullptr) return NO_INIT;
793 Mutex::Autolock _l(mLock);
794
795 return mHalWrapper->configureDirectChannel(sensorHandle, channelHandle, config);
796 }
797
798 // ---------------------------------------------------------------------------
799
numActiveClients() const800 int SensorDevice::Info::numActiveClients() const {
801 SensorDevice& device(SensorDevice::getInstance());
802 int num = 0;
803 for (size_t i = 0; i < batchParams.size(); ++i) {
804 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
805 ++num;
806 }
807 }
808 return num;
809 }
810
setBatchParamsForIdent(void * ident,int,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)811 status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int, int64_t samplingPeriodNs,
812 int64_t maxBatchReportLatencyNs) {
813 ssize_t index = batchParams.indexOfKey(ident);
814 if (index < 0) {
815 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64 " timeout=%" PRId64
816 ") failed (%s)",
817 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
818 return BAD_INDEX;
819 }
820 BatchParams& params = batchParams.editValueAt(index);
821 params.mTSample = samplingPeriodNs;
822 params.mTBatch = maxBatchReportLatencyNs;
823 return NO_ERROR;
824 }
825
selectBatchParams()826 void SensorDevice::Info::selectBatchParams() {
827 BatchParams bestParams; // default to max Tsample and max Tbatch
828 SensorDevice& device(SensorDevice::getInstance());
829
830 for (size_t i = 0; i < batchParams.size(); ++i) {
831 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
832 continue;
833 }
834 bestParams.merge(batchParams[i]);
835 }
836 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
837 if (bestParams.mTBatch <= bestParams.mTSample) {
838 bestParams.mTBatch = 0;
839 }
840 bestBatchParams = bestParams;
841 }
842
removeBatchParamsForIdent(void * ident)843 ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
844 ssize_t idx = batchParams.removeItem(ident);
845 if (idx >= 0) {
846 selectBatchParams();
847 }
848 return idx;
849 }
850
notifyConnectionDestroyed(void * ident)851 void SensorDevice::notifyConnectionDestroyed(void* ident) {
852 Mutex::Autolock _l(mLock);
853 mDisabledClients.erase(ident);
854 }
855
isDirectReportSupported() const856 bool SensorDevice::isDirectReportSupported() const {
857 return mIsDirectReportSupported;
858 }
859
getResolutionForSensor(int sensorHandle)860 float SensorDevice::getResolutionForSensor(int sensorHandle) {
861 for (size_t i = 0; i < mSensorList.size(); i++) {
862 if (sensorHandle == mSensorList[i].handle) {
863 return mSensorList[i].resolution;
864 }
865 }
866
867 auto it = mConnectedDynamicSensors.find(sensorHandle);
868 if (it != mConnectedDynamicSensors.end()) {
869 return it->second.resolution;
870 }
871
872 return 0;
873 }
874
875 // ---------------------------------------------------------------------------
876 }; // namespace android
877