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/ISensorsCallback.h"
21 #include "android/hardware/sensors/2.1/types.h"
22 #include "convertV2_1.h"
23
24 #include <android-base/logging.h>
25 #include <android/util/ProtoOutputStream.h>
26 #include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
27 #include <sensors/convert.h>
28 #include <cutils/atomic.h>
29 #include <utils/Errors.h>
30 #include <utils/Singleton.h>
31
32 #include <cstddef>
33 #include <chrono>
34 #include <cinttypes>
35 #include <thread>
36
37 using namespace android::hardware::sensors;
38 using namespace android::hardware::sensors::V1_0;
39 using namespace android::hardware::sensors::V1_0::implementation;
40 using android::hardware::sensors::V2_0::EventQueueFlagBits;
41 using android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
42 using android::hardware::sensors::V2_1::ISensorsCallback;
43 using android::hardware::sensors::V2_1::implementation::convertToOldSensorInfo;
44 using android::hardware::sensors::V2_1::implementation::convertToNewSensorInfos;
45 using android::hardware::sensors::V2_1::implementation::convertToNewEvents;
46 using android::hardware::sensors::V2_1::implementation::ISensorsWrapperV1_0;
47 using android::hardware::sensors::V2_1::implementation::ISensorsWrapperV2_0;
48 using android::hardware::sensors::V2_1::implementation::ISensorsWrapperV2_1;
49 using android::hardware::hidl_vec;
50 using android::hardware::Return;
51 using android::SensorDeviceUtils::HidlServiceRegistrationWaiter;
52 using android::util::ProtoOutputStream;
53
54 namespace android {
55 // ---------------------------------------------------------------------------
56
57 ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
58
59 namespace {
60
statusFromResult(Result result)61 status_t statusFromResult(Result result) {
62 switch (result) {
63 case Result::OK:
64 return OK;
65 case Result::BAD_VALUE:
66 return BAD_VALUE;
67 case Result::PERMISSION_DENIED:
68 return PERMISSION_DENIED;
69 case Result::INVALID_OPERATION:
70 return INVALID_OPERATION;
71 case Result::NO_MEMORY:
72 return NO_MEMORY;
73 }
74 }
75
76 template<typename EnumType>
asBaseType(EnumType value)77 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
78 return static_cast<typename std::underlying_type<EnumType>::type>(value);
79 }
80
81 // Used internally by the framework to wake the Event FMQ. These values must start after
82 // the last value of EventQueueFlagBits
83 enum EventQueueFlagBitsInternal : uint32_t {
84 INTERNAL_WAKE = 1 << 16,
85 };
86
87 } // anonymous namespace
88
serviceDied(uint64_t,const wp<::android::hidl::base::V1_0::IBase> &)89 void SensorsHalDeathReceivier::serviceDied(
90 uint64_t /* cookie */,
91 const wp<::android::hidl::base::V1_0::IBase>& /* service */) {
92 ALOGW("Sensors HAL died, attempting to reconnect.");
93 SensorDevice::getInstance().prepareForReconnect();
94 }
95
96 struct SensorsCallback : public ISensorsCallback {
97 using Result = ::android::hardware::sensors::V1_0::Result;
98 using SensorInfo = ::android::hardware::sensors::V2_1::SensorInfo;
99
onDynamicSensorsConnected_2_1android::SensorsCallback100 Return<void> onDynamicSensorsConnected_2_1(
101 const hidl_vec<SensorInfo> &dynamicSensorsAdded) override {
102 return SensorDevice::getInstance().onDynamicSensorsConnected(dynamicSensorsAdded);
103 }
104
onDynamicSensorsConnectedandroid::SensorsCallback105 Return<void> onDynamicSensorsConnected(
106 const hidl_vec<V1_0::SensorInfo> &dynamicSensorsAdded) override {
107 return SensorDevice::getInstance().onDynamicSensorsConnected(
108 convertToNewSensorInfos(dynamicSensorsAdded));
109 }
110
onDynamicSensorsDisconnectedandroid::SensorsCallback111 Return<void> onDynamicSensorsDisconnected(
112 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) override {
113 return SensorDevice::getInstance().onDynamicSensorsDisconnected(
114 dynamicSensorHandlesRemoved);
115 }
116 };
117
SensorDevice()118 SensorDevice::SensorDevice()
119 : mHidlTransportErrors(20),
120 mRestartWaiter(new HidlServiceRegistrationWaiter()),
121 mEventQueueFlag(nullptr),
122 mWakeLockQueueFlag(nullptr),
123 mReconnecting(false) {
124 if (!connectHidlService()) {
125 return;
126 }
127
128 initializeSensorList();
129
130 mIsDirectReportSupported =
131 (checkReturnAndGetStatus(mSensors->unregisterDirectChannel(-1)) != INVALID_OPERATION);
132 }
133
initializeSensorList()134 void SensorDevice::initializeSensorList() {
135 checkReturn(mSensors->getSensorsList(
136 [&](const auto &list) {
137 const size_t count = list.size();
138
139 mActivationCount.setCapacity(count);
140 Info model;
141 for (size_t i=0 ; i < count; i++) {
142 sensor_t sensor;
143 convertToSensor(convertToOldSensorInfo(list[i]), &sensor);
144
145 if (sensor.type < static_cast<int>(SensorType::DEVICE_PRIVATE_BASE)) {
146 sensor.resolution = SensorDeviceUtils::resolutionForSensor(sensor);
147
148 // Some sensors don't have a default resolution and will be left at 0.
149 // Don't crash in this case since CTS will verify that devices don't go to
150 // production with a resolution of 0.
151 if (sensor.resolution != 0) {
152 float quantizedRange = sensor.maxRange;
153 SensorDeviceUtils::quantizeValue(
154 &quantizedRange, sensor.resolution, /*factor=*/ 1);
155 // Only rewrite maxRange if the requantization produced a "significant"
156 // change, which is fairly arbitrarily defined as resolution / 8.
157 // Smaller deltas are permitted, as they may simply be due to floating
158 // point representation error, etc.
159 if (fabsf(sensor.maxRange - quantizedRange) > sensor.resolution / 8) {
160 ALOGW("%s's max range %.12f is not a multiple of the resolution "
161 "%.12f - updated to %.12f", sensor.name, sensor.maxRange,
162 sensor.resolution, quantizedRange);
163 sensor.maxRange = quantizedRange;
164 }
165 } else {
166 // Don't crash here or the device will go into a crashloop.
167 ALOGW("%s should have a non-zero resolution", sensor.name);
168 }
169 }
170
171 // Sanity check and clamp power if it is 0 (or close)
172 constexpr float MIN_POWER_MA = 0.001; // 1 microAmp
173 if (sensor.power < MIN_POWER_MA) {
174 ALOGI("%s's reported power %f invalid, clamped to %f",
175 sensor.name, sensor.power, MIN_POWER_MA);
176 sensor.power = MIN_POWER_MA;
177 }
178 mSensorList.push_back(sensor);
179
180 mActivationCount.add(list[i].sensorHandle, model);
181
182 // Only disable all sensors on HAL 1.0 since HAL 2.0
183 // handles this in its initialize method
184 if (!mSensors->supportsMessageQueues()) {
185 checkReturn(mSensors->activate(list[i].sensorHandle,
186 0 /* enabled */));
187 }
188 }
189 }));
190 }
191
~SensorDevice()192 SensorDevice::~SensorDevice() {
193 if (mEventQueueFlag != nullptr) {
194 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
195 mEventQueueFlag = nullptr;
196 }
197
198 if (mWakeLockQueueFlag != nullptr) {
199 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
200 mWakeLockQueueFlag = nullptr;
201 }
202 }
203
connectHidlService()204 bool SensorDevice::connectHidlService() {
205 HalConnectionStatus status = connectHidlServiceV2_1();
206 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
207 status = connectHidlServiceV2_0();
208 }
209
210 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
211 status = connectHidlServiceV1_0();
212 }
213 return (status == HalConnectionStatus::CONNECTED);
214 }
215
connectHidlServiceV1_0()216 SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
217 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
218 size_t retry = 10;
219 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
220
221 while (retry-- > 0) {
222 sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
223 if (sensors == nullptr) {
224 // no sensor hidl service found
225 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
226 break;
227 }
228
229 mSensors = new ISensorsWrapperV1_0(sensors);
230 mRestartWaiter->reset();
231 // Poke ISensor service. If it has lingering connection from previous generation of
232 // system server, it will kill itself. There is no intention to handle the poll result,
233 // which will be done since the size is 0.
234 if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
235 // ok to continue
236 connectionStatus = HalConnectionStatus::CONNECTED;
237 break;
238 }
239
240 // hidl service is restarting, pointer is invalid.
241 mSensors = nullptr;
242 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
243 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
244 mRestartWaiter->wait();
245 }
246
247 return connectionStatus;
248 }
249
connectHidlServiceV2_0()250 SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
251 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
252 sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
253
254 if (sensors == nullptr) {
255 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
256 } else {
257 mSensors = new ISensorsWrapperV2_0(sensors);
258 connectionStatus = initializeHidlServiceV2_X();
259 }
260
261 return connectionStatus;
262 }
263
connectHidlServiceV2_1()264 SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_1() {
265 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
266 sp<V2_1::ISensors> sensors = V2_1::ISensors::getService();
267
268 if (sensors == nullptr) {
269 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
270 } else {
271 mSensors = new ISensorsWrapperV2_1(sensors);
272 connectionStatus = initializeHidlServiceV2_X();
273 }
274
275 return connectionStatus;
276 }
277
initializeHidlServiceV2_X()278 SensorDevice::HalConnectionStatus SensorDevice::initializeHidlServiceV2_X() {
279 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
280
281 mWakeLockQueue = std::make_unique<WakeLockQueue>(
282 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
283 true /* configureEventFlagWord */);
284
285 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
286 hardware::EventFlag::createEventFlag(mSensors->getEventQueue()->getEventFlagWord(), &mEventQueueFlag);
287
288 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
289 hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(),
290 &mWakeLockQueueFlag);
291
292 CHECK(mSensors != nullptr && mWakeLockQueue != nullptr &&
293 mEventQueueFlag != nullptr && mWakeLockQueueFlag != nullptr);
294
295 status_t status = checkReturnAndGetStatus(mSensors->initialize(
296 *mWakeLockQueue->getDesc(),
297 new SensorsCallback()));
298
299 if (status != NO_ERROR) {
300 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
301 ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
302 } else {
303 connectionStatus = HalConnectionStatus::CONNECTED;
304 mSensorsHalDeathReceiver = new SensorsHalDeathReceivier();
305 mSensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
306 }
307
308 return connectionStatus;
309 }
310
prepareForReconnect()311 void SensorDevice::prepareForReconnect() {
312 mReconnecting = true;
313
314 // Wake up the polling thread so it returns and allows the SensorService to initiate
315 // a reconnect.
316 mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
317 }
318
reconnect()319 void SensorDevice::reconnect() {
320 Mutex::Autolock _l(mLock);
321 mSensors = nullptr;
322
323 auto previousActivations = mActivationCount;
324 auto previousSensorList = mSensorList;
325
326 mActivationCount.clear();
327 mSensorList.clear();
328
329 if (connectHidlServiceV2_0() == HalConnectionStatus::CONNECTED) {
330 initializeSensorList();
331
332 if (sensorHandlesChanged(previousSensorList, mSensorList)) {
333 LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
334 } else {
335 reactivateSensors(previousActivations);
336 }
337 }
338 mReconnecting = false;
339 }
340
sensorHandlesChanged(const Vector<sensor_t> & oldSensorList,const Vector<sensor_t> & newSensorList)341 bool SensorDevice::sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
342 const Vector<sensor_t>& newSensorList) {
343 bool didChange = false;
344
345 if (oldSensorList.size() != newSensorList.size()) {
346 ALOGI("Sensor list size changed from %zu to %zu", oldSensorList.size(),
347 newSensorList.size());
348 didChange = true;
349 }
350
351 for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
352 bool found = false;
353 const sensor_t& newSensor = newSensorList[i];
354 for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
355 const sensor_t& prevSensor = oldSensorList[j];
356 if (prevSensor.handle == newSensor.handle) {
357 found = true;
358 if (!sensorIsEquivalent(prevSensor, newSensor)) {
359 ALOGI("Sensor %s not equivalent to previous version", newSensor.name);
360 didChange = true;
361 }
362 }
363 }
364
365 if (!found) {
366 // Could not find the new sensor in the old list of sensors, the lists must
367 // have changed.
368 ALOGI("Sensor %s (handle %d) did not exist before", newSensor.name, newSensor.handle);
369 didChange = true;
370 }
371 }
372 return didChange;
373 }
374
sensorIsEquivalent(const sensor_t & prevSensor,const sensor_t & newSensor)375 bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
376 bool equivalent = true;
377 if (prevSensor.handle != newSensor.handle ||
378 (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
379 (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
380 (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
381 (prevSensor.version != newSensor.version) ||
382 (prevSensor.type != newSensor.type) ||
383 (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
384 (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
385 (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
386 (prevSensor.minDelay != newSensor.minDelay) ||
387 (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
388 (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
389 (prevSensor.maxDelay != newSensor.maxDelay) ||
390 (prevSensor.flags != newSensor.flags)) {
391 equivalent = false;
392 }
393 return equivalent;
394 }
395
reactivateSensors(const DefaultKeyedVector<int,Info> & previousActivations)396 void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
397 for (size_t i = 0; i < mSensorList.size(); i++) {
398 int handle = mSensorList[i].handle;
399 ssize_t activationIndex = previousActivations.indexOfKey(handle);
400 if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
401 continue;
402 }
403
404 const Info& info = previousActivations[activationIndex];
405 for (size_t j = 0; j < info.batchParams.size(); j++) {
406 const BatchParams& batchParams = info.batchParams[j];
407 status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
408 batchParams.mTSample, batchParams.mTBatch);
409
410 if (res == NO_ERROR) {
411 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
412 }
413 }
414 }
415 }
416
handleDynamicSensorConnection(int handle,bool connected)417 void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
418 // not need to check mSensors because this is is only called after successful poll()
419 if (connected) {
420 Info model;
421 mActivationCount.add(handle, model);
422 checkReturn(mSensors->activate(handle, 0 /* enabled */));
423 } else {
424 mActivationCount.removeItem(handle);
425 }
426 }
427
dump() const428 std::string SensorDevice::dump() const {
429 if (mSensors == nullptr) return "HAL not initialized\n";
430
431 String8 result;
432 result.appendFormat("Total %zu h/w sensors, %zu running %zu disabled clients:\n",
433 mSensorList.size(), mActivationCount.size(), mDisabledClients.size());
434
435 Mutex::Autolock _l(mLock);
436 for (const auto & s : mSensorList) {
437 int32_t handle = s.handle;
438 const Info& info = mActivationCount.valueFor(handle);
439 if (info.numActiveClients() == 0) continue;
440
441 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
442
443 result.append("sampling_period(ms) = {");
444 for (size_t j = 0; j < info.batchParams.size(); j++) {
445 const BatchParams& params = info.batchParams[j];
446 result.appendFormat("%.1f%s%s", params.mTSample / 1e6f,
447 isClientDisabledLocked(info.batchParams.keyAt(j)) ? "(disabled)" : "",
448 (j < info.batchParams.size() - 1) ? ", " : "");
449 }
450 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
451
452 result.append("batching_period(ms) = {");
453 for (size_t j = 0; j < info.batchParams.size(); j++) {
454 const BatchParams& params = info.batchParams[j];
455 result.appendFormat("%.1f%s%s", params.mTBatch / 1e6f,
456 isClientDisabledLocked(info.batchParams.keyAt(j)) ? "(disabled)" : "",
457 (j < info.batchParams.size() - 1) ? ", " : "");
458 }
459 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
460 }
461
462 return result.string();
463 }
464
465 /**
466 * Dump debugging information as android.service.SensorDeviceProto protobuf message using
467 * ProtoOutputStream.
468 *
469 * See proto definition and some notes about ProtoOutputStream in
470 * frameworks/base/core/proto/android/service/sensor_service.proto
471 */
dump(ProtoOutputStream * proto) const472 void SensorDevice::dump(ProtoOutputStream* proto) const {
473 using namespace service::SensorDeviceProto;
474 if (mSensors == nullptr) {
475 proto->write(INITIALIZED , false);
476 return;
477 }
478 proto->write(INITIALIZED , true);
479 proto->write(TOTAL_SENSORS , int(mSensorList.size()));
480 proto->write(ACTIVE_SENSORS , int(mActivationCount.size()));
481
482 Mutex::Autolock _l(mLock);
483 for (const auto & s : mSensorList) {
484 int32_t handle = s.handle;
485 const Info& info = mActivationCount.valueFor(handle);
486 if (info.numActiveClients() == 0) continue;
487
488 uint64_t token = proto->start(SENSORS);
489 proto->write(SensorProto::HANDLE , handle);
490 proto->write(SensorProto::ACTIVE_COUNT , int(info.batchParams.size()));
491 for (size_t j = 0; j < info.batchParams.size(); j++) {
492 const BatchParams& params = info.batchParams[j];
493 proto->write(SensorProto::SAMPLING_PERIOD_MS , params.mTSample / 1e6f);
494 proto->write(SensorProto::BATCHING_PERIOD_MS , params.mTBatch / 1e6f);
495 }
496 proto->write(SensorProto::SAMPLING_PERIOD_SELECTED , info.bestBatchParams.mTSample / 1e6f);
497 proto->write(SensorProto::BATCHING_PERIOD_SELECTED , info.bestBatchParams.mTBatch / 1e6f);
498 proto->end(token);
499 }
500 }
501
getSensorList(sensor_t const ** list)502 ssize_t SensorDevice::getSensorList(sensor_t const** list) {
503 *list = &mSensorList[0];
504
505 return mSensorList.size();
506 }
507
initCheck() const508 status_t SensorDevice::initCheck() const {
509 return mSensors != nullptr ? NO_ERROR : NO_INIT;
510 }
511
poll(sensors_event_t * buffer,size_t count)512 ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
513 if (mSensors == nullptr) return NO_INIT;
514
515 ssize_t eventsRead = 0;
516 if (mSensors->supportsMessageQueues()) {
517 eventsRead = pollFmq(buffer, count);
518 } else if (mSensors->supportsPolling()) {
519 eventsRead = pollHal(buffer, count);
520 } else {
521 ALOGE("Must support polling or FMQ");
522 eventsRead = -1;
523 }
524 return eventsRead;
525 }
526
pollHal(sensors_event_t * buffer,size_t count)527 ssize_t SensorDevice::pollHal(sensors_event_t* buffer, size_t count) {
528 ssize_t err;
529 int numHidlTransportErrors = 0;
530 bool hidlTransportError = false;
531
532 do {
533 auto ret = mSensors->poll(
534 count,
535 [&](auto result,
536 const auto &events,
537 const auto &dynamicSensorsAdded) {
538 if (result == Result::OK) {
539 convertToSensorEventsAndQuantize(convertToNewEvents(events),
540 convertToNewSensorInfos(dynamicSensorsAdded), buffer);
541 err = (ssize_t)events.size();
542 } else {
543 err = statusFromResult(result);
544 }
545 });
546
547 if (ret.isOk()) {
548 hidlTransportError = false;
549 } else {
550 hidlTransportError = true;
551 numHidlTransportErrors++;
552 if (numHidlTransportErrors > 50) {
553 // Log error and bail
554 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
555 handleHidlDeath(ret.description());
556 } else {
557 std::this_thread::sleep_for(std::chrono::milliseconds(10));
558 }
559 }
560 } while (hidlTransportError);
561
562 if(numHidlTransportErrors > 0) {
563 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
564 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
565 mHidlTransportErrors.add(errLog);
566 mTotalHidlTransportErrors++;
567 }
568
569 return err;
570 }
571
pollFmq(sensors_event_t * buffer,size_t maxNumEventsToRead)572 ssize_t SensorDevice::pollFmq(sensors_event_t* buffer, size_t maxNumEventsToRead) {
573 ssize_t eventsRead = 0;
574 size_t availableEvents = mSensors->getEventQueue()->availableToRead();
575
576 if (availableEvents == 0) {
577 uint32_t eventFlagState = 0;
578
579 // Wait for events to become available. This is necessary so that the Event FMQ's read() is
580 // able to be called with the correct number of events to read. If the specified number of
581 // events is not available, then read() would return no events, possibly introducing
582 // additional latency in delivering events to applications.
583 mEventQueueFlag->wait(asBaseType(EventQueueFlagBits::READ_AND_PROCESS) |
584 asBaseType(INTERNAL_WAKE), &eventFlagState);
585 availableEvents = mSensors->getEventQueue()->availableToRead();
586
587 if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
588 ALOGD("Event FMQ internal wake, returning from poll with no events");
589 return DEAD_OBJECT;
590 }
591 }
592
593 size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
594 if (eventsToRead > 0) {
595 if (mSensors->getEventQueue()->read(mEventBuffer.data(), eventsToRead)) {
596 // Notify the Sensors HAL that sensor events have been read. This is required to support
597 // the use of writeBlocking by the Sensors HAL.
598 mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
599
600 for (size_t i = 0; i < eventsToRead; i++) {
601 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
602 android::SensorDeviceUtils::quantizeSensorEventValues(&buffer[i],
603 getResolutionForSensor(buffer[i].sensor));
604 }
605 eventsRead = eventsToRead;
606 } else {
607 ALOGW("Failed to read %zu events, currently %zu events available",
608 eventsToRead, availableEvents);
609 }
610 }
611
612 return eventsRead;
613 }
614
onDynamicSensorsConnected(const hidl_vec<SensorInfo> & dynamicSensorsAdded)615 Return<void> SensorDevice::onDynamicSensorsConnected(
616 const hidl_vec<SensorInfo> &dynamicSensorsAdded) {
617 // Allocate a sensor_t structure for each dynamic sensor added and insert
618 // it into the dictionary of connected dynamic sensors keyed by handle.
619 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
620 const SensorInfo &info = dynamicSensorsAdded[i];
621
622 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
623 CHECK(it == mConnectedDynamicSensors.end());
624
625 sensor_t *sensor = new sensor_t();
626 convertToSensor(convertToOldSensorInfo(info), sensor);
627
628 mConnectedDynamicSensors.insert(
629 std::make_pair(sensor->handle, sensor));
630 }
631
632 return Return<void>();
633 }
634
onDynamicSensorsDisconnected(const hidl_vec<int32_t> & dynamicSensorHandlesRemoved)635 Return<void> SensorDevice::onDynamicSensorsDisconnected(
636 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) {
637 (void) dynamicSensorHandlesRemoved;
638 // TODO: Currently dynamic sensors do not seem to be removed
639 return Return<void>();
640 }
641
writeWakeLockHandled(uint32_t count)642 void SensorDevice::writeWakeLockHandled(uint32_t count) {
643 if (mSensors != nullptr && mSensors->supportsMessageQueues()) {
644 if (mWakeLockQueue->write(&count)) {
645 mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
646 } else {
647 ALOGW("Failed to write wake lock handled");
648 }
649 }
650 }
651
autoDisable(void * ident,int handle)652 void SensorDevice::autoDisable(void *ident, int handle) {
653 Mutex::Autolock _l(mLock);
654 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
655 if (activationIndex < 0) {
656 ALOGW("Handle %d cannot be found in activation record", handle);
657 return;
658 }
659 Info& info(mActivationCount.editValueAt(activationIndex));
660 info.removeBatchParamsForIdent(ident);
661 if (info.numActiveClients() == 0) {
662 info.isActive = false;
663 }
664 }
665
activate(void * ident,int handle,int enabled)666 status_t SensorDevice::activate(void* ident, int handle, int enabled) {
667 if (mSensors == nullptr) return NO_INIT;
668
669 Mutex::Autolock _l(mLock);
670 return activateLocked(ident, handle, enabled);
671 }
672
activateLocked(void * ident,int handle,int enabled)673 status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
674 bool activateHardware = false;
675
676 status_t err(NO_ERROR);
677
678 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
679 if (activationIndex < 0) {
680 ALOGW("Handle %d cannot be found in activation record", handle);
681 return BAD_VALUE;
682 }
683 Info& info(mActivationCount.editValueAt(activationIndex));
684
685 ALOGD_IF(DEBUG_CONNECTIONS,
686 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
687 ident, handle, enabled, info.batchParams.size());
688
689 if (enabled) {
690 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
691
692 if (isClientDisabledLocked(ident)) {
693 ALOGW("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
694 ident, handle);
695 return NO_ERROR;
696 }
697
698 if (info.batchParams.indexOfKey(ident) >= 0) {
699 if (info.numActiveClients() > 0 && !info.isActive) {
700 activateHardware = true;
701 }
702 } else {
703 // Log error. Every activate call should be preceded by a batch() call.
704 ALOGE("\t >>>ERROR: activate called without batch");
705 }
706 } else {
707 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
708
709 // If a connected dynamic sensor is deactivated, remove it from the
710 // dictionary.
711 auto it = mConnectedDynamicSensors.find(handle);
712 if (it != mConnectedDynamicSensors.end()) {
713 delete it->second;
714 mConnectedDynamicSensors.erase(it);
715 }
716
717 if (info.removeBatchParamsForIdent(ident) >= 0) {
718 if (info.numActiveClients() == 0) {
719 // This is the last connection, we need to de-activate the underlying h/w sensor.
720 activateHardware = true;
721 } else {
722 // Call batch for this sensor with the previously calculated best effort
723 // batch_rate and timeout. One of the apps has unregistered for sensor
724 // events, and the best effort batch parameters might have changed.
725 ALOGD_IF(DEBUG_CONNECTIONS,
726 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
727 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
728 checkReturn(mSensors->batch(
729 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
730 }
731 } else {
732 // sensor wasn't enabled for this ident
733 }
734
735 if (isClientDisabledLocked(ident)) {
736 return NO_ERROR;
737 }
738 }
739
740 if (activateHardware) {
741 err = doActivateHardwareLocked(handle, enabled);
742
743 if (err != NO_ERROR && enabled) {
744 // Failure when enabling the sensor. Clean up on failure.
745 info.removeBatchParamsForIdent(ident);
746 } else {
747 // Update the isActive flag if there is no error. If there is an error when disabling a
748 // sensor, still set the flag to false since the batch parameters have already been
749 // removed. This ensures that everything remains in-sync.
750 info.isActive = enabled;
751 }
752 }
753
754 return err;
755 }
756
doActivateHardwareLocked(int handle,bool enabled)757 status_t SensorDevice::doActivateHardwareLocked(int handle, bool enabled) {
758 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
759 enabled);
760 status_t err = checkReturnAndGetStatus(mSensors->activate(handle, enabled));
761 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
762 strerror(-err));
763 return err;
764 }
765
batch(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)766 status_t SensorDevice::batch(
767 void* ident,
768 int handle,
769 int flags,
770 int64_t samplingPeriodNs,
771 int64_t maxBatchReportLatencyNs) {
772 if (mSensors == nullptr) return NO_INIT;
773
774 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
775 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
776 }
777 if (maxBatchReportLatencyNs < 0) {
778 maxBatchReportLatencyNs = 0;
779 }
780
781 ALOGD_IF(DEBUG_CONNECTIONS,
782 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
783 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
784
785 Mutex::Autolock _l(mLock);
786 return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
787 }
788
batchLocked(void * ident,int handle,int flags,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)789 status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
790 int64_t maxBatchReportLatencyNs) {
791 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
792 if (activationIndex < 0) {
793 ALOGW("Handle %d cannot be found in activation record", handle);
794 return BAD_VALUE;
795 }
796 Info& info(mActivationCount.editValueAt(activationIndex));
797
798 if (info.batchParams.indexOfKey(ident) < 0) {
799 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
800 info.batchParams.add(ident, params);
801 } else {
802 // A batch has already been called with this ident. Update the batch parameters.
803 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
804 }
805
806 status_t err = updateBatchParamsLocked(handle, info);
807 if (err != NO_ERROR) {
808 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
809 mSensors.get(), handle, info.bestBatchParams.mTSample,
810 info.bestBatchParams.mTBatch, strerror(-err));
811 info.removeBatchParamsForIdent(ident);
812 }
813
814 return err;
815 }
816
updateBatchParamsLocked(int handle,Info & info)817 status_t SensorDevice::updateBatchParamsLocked(int handle, Info &info) {
818 BatchParams prevBestBatchParams = info.bestBatchParams;
819 // Find the minimum of all timeouts and batch_rates for this sensor.
820 info.selectBatchParams();
821
822 ALOGD_IF(DEBUG_CONNECTIONS,
823 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
824 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
825 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
826 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
827
828 status_t err(NO_ERROR);
829 // If the min period or min timeout has changed since the last batch call, call batch.
830 if (prevBestBatchParams != info.bestBatchParams && info.numActiveClients() > 0) {
831 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
832 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
833 err = checkReturnAndGetStatus(mSensors->batch(
834 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
835 }
836
837 return err;
838 }
839
setDelay(void * ident,int handle,int64_t samplingPeriodNs)840 status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
841 return batch(ident, handle, 0, samplingPeriodNs, 0);
842 }
843
getHalDeviceVersion() const844 int SensorDevice::getHalDeviceVersion() const {
845 if (mSensors == nullptr) return -1;
846 return SENSORS_DEVICE_API_VERSION_1_4;
847 }
848
flush(void * ident,int handle)849 status_t SensorDevice::flush(void* ident, int handle) {
850 if (mSensors == nullptr) return NO_INIT;
851 if (isClientDisabled(ident)) return INVALID_OPERATION;
852 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
853 return checkReturnAndGetStatus(mSensors->flush(handle));
854 }
855
isClientDisabled(void * ident) const856 bool SensorDevice::isClientDisabled(void* ident) const {
857 Mutex::Autolock _l(mLock);
858 return isClientDisabledLocked(ident);
859 }
860
isClientDisabledLocked(void * ident) const861 bool SensorDevice::isClientDisabledLocked(void* ident) const {
862 return mDisabledClients.count(ident) > 0;
863 }
864
getDisabledClientsLocked() const865 std::vector<void *> SensorDevice::getDisabledClientsLocked() const {
866 std::vector<void *> vec;
867 for (const auto& it : mDisabledClients) {
868 vec.push_back(it.first);
869 }
870
871 return vec;
872 }
873
addDisabledReasonForIdentLocked(void * ident,DisabledReason reason)874 void SensorDevice::addDisabledReasonForIdentLocked(void* ident, DisabledReason reason) {
875 mDisabledClients[ident] |= 1 << reason;
876 }
877
removeDisabledReasonForIdentLocked(void * ident,DisabledReason reason)878 void SensorDevice::removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason) {
879 if (isClientDisabledLocked(ident)) {
880 mDisabledClients[ident] &= ~(1 << reason);
881 if (mDisabledClients[ident] == 0) {
882 mDisabledClients.erase(ident);
883 }
884 }
885 }
886
setUidStateForConnection(void * ident,SensorService::UidState state)887 void SensorDevice::setUidStateForConnection(void* ident, SensorService::UidState state) {
888 Mutex::Autolock _l(mLock);
889 if (state == SensorService::UID_STATE_ACTIVE) {
890 removeDisabledReasonForIdentLocked(ident, DisabledReason::DISABLED_REASON_UID_IDLE);
891 } else {
892 addDisabledReasonForIdentLocked(ident, DisabledReason::DISABLED_REASON_UID_IDLE);
893 }
894
895 for (size_t i = 0; i< mActivationCount.size(); ++i) {
896 int handle = mActivationCount.keyAt(i);
897 Info& info = mActivationCount.editValueAt(i);
898
899 if (info.hasBatchParamsForIdent(ident)) {
900 updateBatchParamsLocked(handle, info);
901 bool disable = info.numActiveClients() == 0 && info.isActive;
902 bool enable = info.numActiveClients() > 0 && !info.isActive;
903
904 if ((enable || disable) &&
905 doActivateHardwareLocked(handle, enable) == NO_ERROR) {
906 info.isActive = enable;
907 }
908 }
909 }
910 }
911
isSensorActive(int handle) const912 bool SensorDevice::isSensorActive(int handle) const {
913 Mutex::Autolock _l(mLock);
914 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
915 if (activationIndex < 0) {
916 return false;
917 }
918 return mActivationCount.valueAt(activationIndex).isActive;
919 }
920
onMicSensorAccessChanged(void * ident,int handle,nsecs_t samplingPeriodNs)921 void SensorDevice::onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs) {
922 Mutex::Autolock _l(mLock);
923 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
924 if (activationIndex < 0) {
925 ALOGW("Handle %d cannot be found in activation record", handle);
926 return;
927 }
928 Info& info(mActivationCount.editValueAt(activationIndex));
929 if (info.hasBatchParamsForIdent(ident)) {
930 ssize_t index = info.batchParams.indexOfKey(ident);
931 BatchParams& params = info.batchParams.editValueAt(index);
932 params.mTSample = samplingPeriodNs;
933 }
934 }
935
enableAllSensors()936 void SensorDevice::enableAllSensors() {
937 if (mSensors == nullptr) return;
938 Mutex::Autolock _l(mLock);
939
940 for (void *client : getDisabledClientsLocked()) {
941 removeDisabledReasonForIdentLocked(
942 client, DisabledReason::DISABLED_REASON_SERVICE_RESTRICTED);
943 }
944
945 for (size_t i = 0; i< mActivationCount.size(); ++i) {
946 Info& info = mActivationCount.editValueAt(i);
947 if (info.batchParams.isEmpty()) continue;
948 info.selectBatchParams();
949 const int sensor_handle = mActivationCount.keyAt(i);
950 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
951 sensor_handle);
952 status_t err = checkReturnAndGetStatus(mSensors->batch(
953 sensor_handle,
954 info.bestBatchParams.mTSample,
955 info.bestBatchParams.mTBatch));
956 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
957
958 if (err == NO_ERROR) {
959 err = checkReturnAndGetStatus(mSensors->activate(sensor_handle, 1 /* enabled */));
960 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
961 }
962
963 if (err == NO_ERROR) {
964 info.isActive = true;
965 }
966 }
967 }
968
disableAllSensors()969 void SensorDevice::disableAllSensors() {
970 if (mSensors == nullptr) return;
971 Mutex::Autolock _l(mLock);
972 for (size_t i = 0; i< mActivationCount.size(); ++i) {
973 Info& info = mActivationCount.editValueAt(i);
974 // Check if this sensor has been activated previously and disable it.
975 if (info.batchParams.size() > 0) {
976 const int sensor_handle = mActivationCount.keyAt(i);
977 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
978 sensor_handle);
979 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
980
981 // Add all the connections that were registered for this sensor to the disabled
982 // clients list.
983 for (size_t j = 0; j < info.batchParams.size(); ++j) {
984 addDisabledReasonForIdentLocked(
985 info.batchParams.keyAt(j), DisabledReason::DISABLED_REASON_SERVICE_RESTRICTED);
986 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
987 }
988
989 info.isActive = false;
990 }
991 }
992 }
993
injectSensorData(const sensors_event_t * injected_sensor_event)994 status_t SensorDevice::injectSensorData(
995 const sensors_event_t *injected_sensor_event) {
996 if (mSensors == nullptr) return NO_INIT;
997 ALOGD_IF(DEBUG_CONNECTIONS,
998 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
999 injected_sensor_event->sensor,
1000 injected_sensor_event->timestamp, injected_sensor_event->data[0],
1001 injected_sensor_event->data[1], injected_sensor_event->data[2],
1002 injected_sensor_event->data[3], injected_sensor_event->data[4],
1003 injected_sensor_event->data[5]);
1004
1005 Event ev;
1006 V2_1::implementation::convertFromSensorEvent(*injected_sensor_event, &ev);
1007
1008 return checkReturnAndGetStatus(mSensors->injectSensorData(ev));
1009 }
1010
setMode(uint32_t mode)1011 status_t SensorDevice::setMode(uint32_t mode) {
1012 if (mSensors == nullptr) return NO_INIT;
1013 return checkReturnAndGetStatus(mSensors->setOperationMode(
1014 static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
1015 }
1016
registerDirectChannel(const sensors_direct_mem_t * memory)1017 int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
1018 if (mSensors == nullptr) return NO_INIT;
1019 Mutex::Autolock _l(mLock);
1020
1021 SharedMemType type;
1022 switch (memory->type) {
1023 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
1024 type = SharedMemType::ASHMEM;
1025 break;
1026 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
1027 type = SharedMemType::GRALLOC;
1028 break;
1029 default:
1030 return BAD_VALUE;
1031 }
1032
1033 SharedMemFormat format;
1034 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
1035 return BAD_VALUE;
1036 }
1037 format = SharedMemFormat::SENSORS_EVENT;
1038
1039 SharedMemInfo mem = {
1040 .type = type,
1041 .format = format,
1042 .size = static_cast<uint32_t>(memory->size),
1043 .memoryHandle = memory->handle,
1044 };
1045
1046 int32_t ret;
1047 checkReturn(mSensors->registerDirectChannel(mem,
1048 [&ret](auto result, auto channelHandle) {
1049 if (result == Result::OK) {
1050 ret = channelHandle;
1051 } else {
1052 ret = statusFromResult(result);
1053 }
1054 }));
1055 return ret;
1056 }
1057
unregisterDirectChannel(int32_t channelHandle)1058 void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
1059 if (mSensors == nullptr) return;
1060 Mutex::Autolock _l(mLock);
1061 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
1062 }
1063
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)1064 int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
1065 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
1066 if (mSensors == nullptr) return NO_INIT;
1067 Mutex::Autolock _l(mLock);
1068
1069 RateLevel rate;
1070 switch(config->rate_level) {
1071 case SENSOR_DIRECT_RATE_STOP:
1072 rate = RateLevel::STOP;
1073 break;
1074 case SENSOR_DIRECT_RATE_NORMAL:
1075 rate = RateLevel::NORMAL;
1076 break;
1077 case SENSOR_DIRECT_RATE_FAST:
1078 rate = RateLevel::FAST;
1079 break;
1080 case SENSOR_DIRECT_RATE_VERY_FAST:
1081 rate = RateLevel::VERY_FAST;
1082 break;
1083 default:
1084 return BAD_VALUE;
1085 }
1086
1087 int32_t ret;
1088 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
1089 [&ret, rate] (auto result, auto token) {
1090 if (rate == RateLevel::STOP) {
1091 ret = statusFromResult(result);
1092 } else {
1093 if (result == Result::OK) {
1094 ret = token;
1095 } else {
1096 ret = statusFromResult(result);
1097 }
1098 }
1099 }));
1100
1101 return ret;
1102 }
1103
1104 // ---------------------------------------------------------------------------
1105
numActiveClients() const1106 int SensorDevice::Info::numActiveClients() const {
1107 SensorDevice& device(SensorDevice::getInstance());
1108 int num = 0;
1109 for (size_t i = 0; i < batchParams.size(); ++i) {
1110 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
1111 ++num;
1112 }
1113 }
1114 return num;
1115 }
1116
setBatchParamsForIdent(void * ident,int,int64_t samplingPeriodNs,int64_t maxBatchReportLatencyNs)1117 status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
1118 int64_t samplingPeriodNs,
1119 int64_t maxBatchReportLatencyNs) {
1120 ssize_t index = batchParams.indexOfKey(ident);
1121 if (index < 0) {
1122 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
1123 " timeout=%" PRId64 ") failed (%s)",
1124 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
1125 return BAD_INDEX;
1126 }
1127 BatchParams& params = batchParams.editValueAt(index);
1128 params.mTSample = samplingPeriodNs;
1129 params.mTBatch = maxBatchReportLatencyNs;
1130 return NO_ERROR;
1131 }
1132
selectBatchParams()1133 void SensorDevice::Info::selectBatchParams() {
1134 BatchParams bestParams; // default to max Tsample and max Tbatch
1135 SensorDevice& device(SensorDevice::getInstance());
1136
1137 for (size_t i = 0; i < batchParams.size(); ++i) {
1138 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
1139 continue;
1140 }
1141 bestParams.merge(batchParams[i]);
1142 }
1143 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
1144 if (bestParams.mTBatch <= bestParams.mTSample) {
1145 bestParams.mTBatch = 0;
1146 }
1147 bestBatchParams = bestParams;
1148 }
1149
removeBatchParamsForIdent(void * ident)1150 ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
1151 ssize_t idx = batchParams.removeItem(ident);
1152 if (idx >= 0) {
1153 selectBatchParams();
1154 }
1155 return idx;
1156 }
1157
notifyConnectionDestroyed(void * ident)1158 void SensorDevice::notifyConnectionDestroyed(void* ident) {
1159 Mutex::Autolock _l(mLock);
1160 mDisabledClients.erase(ident);
1161 }
1162
isDirectReportSupported() const1163 bool SensorDevice::isDirectReportSupported() const {
1164 return mIsDirectReportSupported;
1165 }
1166
convertToSensorEvent(const Event & src,sensors_event_t * dst)1167 void SensorDevice::convertToSensorEvent(
1168 const Event &src, sensors_event_t *dst) {
1169 V2_1::implementation::convertToSensorEvent(src, dst);
1170
1171 if (src.sensorType == V2_1::SensorType::DYNAMIC_SENSOR_META) {
1172 const DynamicSensorInfo &dyn = src.u.dynamic;
1173
1174 dst->dynamic_sensor_meta.connected = dyn.connected;
1175 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
1176 if (dyn.connected) {
1177 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
1178 CHECK(it != mConnectedDynamicSensors.end());
1179
1180 dst->dynamic_sensor_meta.sensor = it->second;
1181
1182 memcpy(dst->dynamic_sensor_meta.uuid,
1183 dyn.uuid.data(),
1184 sizeof(dst->dynamic_sensor_meta.uuid));
1185 }
1186 }
1187 }
1188
convertToSensorEventsAndQuantize(const hidl_vec<Event> & src,const hidl_vec<SensorInfo> & dynamicSensorsAdded,sensors_event_t * dst)1189 void SensorDevice::convertToSensorEventsAndQuantize(
1190 const hidl_vec<Event> &src,
1191 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
1192 sensors_event_t *dst) {
1193
1194 if (dynamicSensorsAdded.size() > 0) {
1195 onDynamicSensorsConnected(dynamicSensorsAdded);
1196 }
1197
1198 for (size_t i = 0; i < src.size(); ++i) {
1199 V2_1::implementation::convertToSensorEvent(src[i], &dst[i]);
1200 android::SensorDeviceUtils::quantizeSensorEventValues(&dst[i],
1201 getResolutionForSensor(dst[i].sensor));
1202 }
1203 }
1204
getResolutionForSensor(int sensorHandle)1205 float SensorDevice::getResolutionForSensor(int sensorHandle) {
1206 for (size_t i = 0; i < mSensorList.size(); i++) {
1207 if (sensorHandle == mSensorList[i].handle) {
1208 return mSensorList[i].resolution;
1209 }
1210 }
1211
1212 auto it = mConnectedDynamicSensors.find(sensorHandle);
1213 if (it != mConnectedDynamicSensors.end()) {
1214 return it->second->resolution;
1215 }
1216
1217 return 0;
1218 }
1219
handleHidlDeath(const std::string & detail)1220 void SensorDevice::handleHidlDeath(const std::string & detail) {
1221 if (!mSensors->supportsMessageQueues()) {
1222 // restart is the only option at present.
1223 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
1224 } else {
1225 ALOGD("ISensors HAL died, death recipient will attempt reconnect");
1226 }
1227 }
1228
checkReturnAndGetStatus(const Return<Result> & ret)1229 status_t SensorDevice::checkReturnAndGetStatus(const Return<Result>& ret) {
1230 checkReturn(ret);
1231 return (!ret.isOk()) ? DEAD_OBJECT : statusFromResult(ret);
1232 }
1233
1234 // ---------------------------------------------------------------------------
1235 }; // namespace android
1236