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