blob: ae3f42f7bc030e141a93a838807a48c3092d48ac [file] [log] [blame]
Mathias Agopianf001c922010-11-11 17:58:51 -08001/*
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 */
Peng Xu3889e6e2017-03-02 19:10:38 -080016#include "SensorDevice.h"
17#include "SensorService.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080018
Steven Morelandd15c0302016-12-20 11:14:50 -080019#include <android-base/logging.h>
Peng Xu3889e6e2017-03-02 19:10:38 -080020#include <sensors/convert.h>
Steven Moreland2716e112018-02-23 14:57:20 -080021#include <cutils/atomic.h>
Ashutosh Joshi5cafc1e2017-02-09 21:44:04 +000022#include <utils/Errors.h>
23#include <utils/Singleton.h>
Steven Morelandd3335112016-12-20 11:14:50 -080024
Peng Xu3889e6e2017-03-02 19:10:38 -080025#include <chrono>
26#include <cinttypes>
27#include <thread>
Steven Morelandd15c0302016-12-20 11:14:50 -080028
Steven Morelandd15c0302016-12-20 11:14:50 -080029using namespace android::hardware::sensors::V1_0;
30using namespace android::hardware::sensors::V1_0::implementation;
Peng Xu1a00e2d2017-09-27 23:08:30 -070031using android::hardware::hidl_vec;
32using android::SensorDeviceUtils::HidlServiceRegistrationWaiter;
Peng Xu2bec6232016-07-01 17:13:10 -070033
Mathias Agopianf001c922010-11-11 17:58:51 -080034namespace android {
35// ---------------------------------------------------------------------------
Mathias Agopianf001c922010-11-11 17:58:51 -080036
37ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
38
Steven Morelandd15c0302016-12-20 11:14:50 -080039static status_t StatusFromResult(Result result) {
40 switch (result) {
41 case Result::OK:
42 return OK;
43 case Result::BAD_VALUE:
44 return BAD_VALUE;
45 case Result::PERMISSION_DENIED:
46 return PERMISSION_DENIED;
47 case Result::INVALID_OPERATION:
48 return INVALID_OPERATION;
49 case Result::NO_MEMORY:
50 return NO_MEMORY;
Mathias Agopianf001c922010-11-11 17:58:51 -080051 }
52}
53
Peng Xu1a00e2d2017-09-27 23:08:30 -070054SensorDevice::SensorDevice()
55 : mHidlTransportErrors(20), mRestartWaiter(new HidlServiceRegistrationWaiter()) {
Peng Xua8fad9b2017-03-17 12:20:27 -070056 if (!connectHidlService()) {
57 return;
58 }
Ashutosh Joshifea2d262017-04-19 23:27:49 -070059
60 float minPowerMa = 0.001; // 1 microAmp
61
Peng Xua8fad9b2017-03-17 12:20:27 -070062 checkReturn(mSensors->getSensorsList(
63 [&](const auto &list) {
64 const size_t count = list.size();
65
66 mActivationCount.setCapacity(count);
67 Info model;
68 for (size_t i=0 ; i < count; i++) {
69 sensor_t sensor;
70 convertToSensor(list[i], &sensor);
Ashutosh Joshifea2d262017-04-19 23:27:49 -070071 // Sanity check and clamp power if it is 0 (or close)
72 if (sensor.power < minPowerMa) {
73 ALOGE("Reported power %f not deemed sane, clamping to %f",
74 sensor.power, minPowerMa);
75 sensor.power = minPowerMa;
76 }
Peng Xua8fad9b2017-03-17 12:20:27 -070077 mSensorList.push_back(sensor);
78
79 mActivationCount.add(list[i].sensorHandle, model);
80
81 checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
82 }
83 }));
84
85 mIsDirectReportSupported =
86 (checkReturn(mSensors->unregisterDirectChannel(-1)) != Result::INVALID_OPERATION);
87}
88
89bool SensorDevice::connectHidlService() {
Peng Xu1a00e2d2017-09-27 23:08:30 -070090 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
Peng Xu3889e6e2017-03-02 19:10:38 -080091 size_t retry = 10;
Steven Morelandd15c0302016-12-20 11:14:50 -080092
Peng Xu1a00e2d2017-09-27 23:08:30 -070093 while (retry-- > 0) {
Peng Xu3889e6e2017-03-02 19:10:38 -080094 mSensors = ISensors::getService();
Peng Xu1a00e2d2017-09-27 23:08:30 -070095 if (mSensors == nullptr) {
96 // no sensor hidl service found
Peng Xua8fad9b2017-03-17 12:20:27 -070097 break;
Peng Xu3889e6e2017-03-02 19:10:38 -080098 }
Peng Xu1a00e2d2017-09-27 23:08:30 -070099
100 mRestartWaiter->reset();
101 // Poke ISensor service. If it has lingering connection from previous generation of
102 // system server, it will kill itself. There is no intention to handle the poll result,
103 // which will be done since the size is 0.
104 if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
105 // ok to continue
106 break;
107 }
108
109 // hidl service is restarting, pointer is invalid.
110 mSensors = nullptr;
111 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
112 mRestartWaiter->wait();
Steven Morelandd15c0302016-12-20 11:14:50 -0800113 }
Peng Xua8fad9b2017-03-17 12:20:27 -0700114 return (mSensors != nullptr);
Steven Morelandd15c0302016-12-20 11:14:50 -0800115}
116
Peng Xu2576cb62016-01-20 00:22:09 -0800117void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700118 // not need to check mSensors because this is is only called after successful poll()
Peng Xu2576cb62016-01-20 00:22:09 -0800119 if (connected) {
120 Info model;
121 mActivationCount.add(handle, model);
Peng Xu3889e6e2017-03-02 19:10:38 -0800122 checkReturn(mSensors->activate(handle, 0 /* enabled */));
Peng Xu2576cb62016-01-20 00:22:09 -0800123 } else {
124 mActivationCount.removeItem(handle);
125 }
126}
127
Peng Xu6a2d3a02015-12-21 12:00:23 -0800128std::string SensorDevice::dump() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700129 if (mSensors == nullptr) return "HAL not initialized\n";
Mathias Agopianf001c922010-11-11 17:58:51 -0800130
Peng Xu6a2d3a02015-12-21 12:00:23 -0800131 String8 result;
Peng Xua8fad9b2017-03-17 12:20:27 -0700132 result.appendFormat("Total %zu h/w sensors, %zu running:\n",
133 mSensorList.size(), mActivationCount.size());
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700134
Peng Xua8fad9b2017-03-17 12:20:27 -0700135 Mutex::Autolock _l(mLock);
136 for (const auto & s : mSensorList) {
137 int32_t handle = s.handle;
138 const Info& info = mActivationCount.valueFor(handle);
139 if (info.batchParams.isEmpty()) continue;
140
141 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
142
143 result.append("sampling_period(ms) = {");
144 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700145 const BatchParams& params = info.batchParams[j];
146 result.appendFormat("%.1f%s", params.mTSample / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700147 j < info.batchParams.size() - 1 ? ", " : "");
148 }
Peng Xu2bec6232016-07-01 17:13:10 -0700149 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
Peng Xua8fad9b2017-03-17 12:20:27 -0700150
151 result.append("batching_period(ms) = {");
152 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700153 const BatchParams& params = info.batchParams[j];
154 result.appendFormat("%.1f%s", params.mTBatch / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700155 j < info.batchParams.size() - 1 ? ", " : "");
156 }
Peng Xu2bec6232016-07-01 17:13:10 -0700157 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700158 }
159
Peng Xu6a2d3a02015-12-21 12:00:23 -0800160 return result.string();
Mathias Agopianf001c922010-11-11 17:58:51 -0800161}
162
163ssize_t SensorDevice::getSensorList(sensor_t const** list) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800164 *list = &mSensorList[0];
165
166 return mSensorList.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800167}
168
169status_t SensorDevice::initCheck() const {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700170 return mSensors != nullptr ? NO_ERROR : NO_INIT;
Mathias Agopianf001c922010-11-11 17:58:51 -0800171}
172
173ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700174 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800175
176 ssize_t err;
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700177 int numHidlTransportErrors = 0;
178 bool hidlTransportError = false;
Steven Morelandd15c0302016-12-20 11:14:50 -0800179
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700180 do {
181 auto ret = mSensors->poll(
182 count,
183 [&](auto result,
184 const auto &events,
185 const auto &dynamicSensorsAdded) {
186 if (result == Result::OK) {
187 convertToSensorEvents(events, dynamicSensorsAdded, buffer);
188 err = (ssize_t)events.size();
189 } else {
190 err = StatusFromResult(result);
191 }
192 });
193
194 if (ret.isOk()) {
195 hidlTransportError = false;
196 } else {
197 hidlTransportError = true;
198 numHidlTransportErrors++;
199 if (numHidlTransportErrors > 50) {
200 // Log error and bail
201 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
202 handleHidlDeath(ret.description());
203 } else {
204 std::this_thread::sleep_for(std::chrono::milliseconds(10));
205 }
206 }
207 } while (hidlTransportError);
208
209 if(numHidlTransportErrors > 0) {
210 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
Yi Kong8f313e32018-07-17 14:13:29 -0700211 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700212 mHidlTransportErrors.add(errLog);
213 mTotalHidlTransportErrors++;
214 }
Steven Morelandd15c0302016-12-20 11:14:50 -0800215
216 return err;
Mathias Agopianf001c922010-11-11 17:58:51 -0800217}
218
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700219void SensorDevice::autoDisable(void *ident, int handle) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700220 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700221 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
222 if (activationIndex < 0) {
223 ALOGW("Handle %d cannot be found in activation record", handle);
224 return;
225 }
226 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700227 info.removeBatchParamsForIdent(ident);
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700228}
229
Peng Xu6a2d3a02015-12-21 12:00:23 -0800230status_t SensorDevice::activate(void* ident, int handle, int enabled) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700231 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800232
Mathias Agopianf001c922010-11-11 17:58:51 -0800233 status_t err(NO_ERROR);
234 bool actuateHardware = false;
235
Aravind Akella724d91d2013-06-27 12:04:23 -0700236 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700237 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
238 if (activationIndex < 0) {
239 ALOGW("Handle %d cannot be found in activation record", handle);
240 return BAD_VALUE;
241 }
242 Info& info(mActivationCount.editValueAt(activationIndex));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700243
Steve Blocka5512372011-12-20 16:23:08 +0000244 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700245 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
Aravind Akella724d91d2013-06-27 12:04:23 -0700246 ident, handle, enabled, info.batchParams.size());
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700247
Mathias Agopianf001c922010-11-11 17:58:51 -0800248 if (enabled) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700249 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700250
Aravind Akella4949c502015-02-11 15:54:35 -0800251 if (isClientDisabledLocked(ident)) {
Peng Xu966fa882016-09-01 16:13:15 -0700252 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
253 ident, handle);
Aravind Akella4949c502015-02-11 15:54:35 -0800254 return INVALID_OPERATION;
255 }
256
Aravind Akella724d91d2013-06-27 12:04:23 -0700257 if (info.batchParams.indexOfKey(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800258 if (info.numActiveClients() == 1) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700259 // This is the first connection, we need to activate the underlying h/w sensor.
260 actuateHardware = true;
261 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800262 } else {
Aravind Akella724d91d2013-06-27 12:04:23 -0700263 // Log error. Every activate call should be preceded by a batch() call.
264 ALOGE("\t >>>ERROR: activate called without batch");
Mathias Agopianf001c922010-11-11 17:58:51 -0800265 }
266 } else {
Mark Salyzyndb458612014-06-10 14:50:02 -0700267 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700268
Steven Morelandd15c0302016-12-20 11:14:50 -0800269 // If a connected dynamic sensor is deactivated, remove it from the
270 // dictionary.
271 auto it = mConnectedDynamicSensors.find(handle);
272 if (it != mConnectedDynamicSensors.end()) {
273 delete it->second;
274 mConnectedDynamicSensors.erase(it);
275 }
276
Aravind Akella724d91d2013-06-27 12:04:23 -0700277 if (info.removeBatchParamsForIdent(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800278 if (info.numActiveClients() == 0) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700279 // This is the last connection, we need to de-activate the underlying h/w sensor.
Mathias Agopian50b66762010-11-29 17:26:51 -0800280 actuateHardware = true;
Aravind Akella724d91d2013-06-27 12:04:23 -0700281 } else {
Steven Morelandd15c0302016-12-20 11:14:50 -0800282 // Call batch for this sensor with the previously calculated best effort
283 // batch_rate and timeout. One of the apps has unregistered for sensor
284 // events, and the best effort batch parameters might have changed.
285 ALOGD_IF(DEBUG_CONNECTIONS,
Peng Xu2bec6232016-07-01 17:13:10 -0700286 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
287 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Peng Xu3889e6e2017-03-02 19:10:38 -0800288 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700289 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Mathias Agopian50b66762010-11-29 17:26:51 -0800290 }
291 } else {
292 // sensor wasn't enabled for this ident
293 }
Aravind Akella4949c502015-02-11 15:54:35 -0800294
295 if (isClientDisabledLocked(ident)) {
296 return NO_ERROR;
297 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800298 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800299
Mathias Agopianf001c922010-11-11 17:58:51 -0800300 if (actuateHardware) {
Aravind Akella4949c502015-02-11 15:54:35 -0800301 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
302 enabled);
Peng Xu3889e6e2017-03-02 19:10:38 -0800303 err = StatusFromResult(checkReturn(mSensors->activate(handle, enabled)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700304 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
305 strerror(-err));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700306
Aravind Akella724d91d2013-06-27 12:04:23 -0700307 if (err != NO_ERROR && enabled) {
308 // Failure when enabling the sensor. Clean up on failure.
309 info.removeBatchParamsForIdent(ident);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700310 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800311 }
312
Mathias Agopianf001c922010-11-11 17:58:51 -0800313 return err;
314}
315
Steven Morelandd15c0302016-12-20 11:14:50 -0800316status_t SensorDevice::batch(
317 void* ident,
318 int handle,
319 int flags,
320 int64_t samplingPeriodNs,
321 int64_t maxBatchReportLatencyNs) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700322 if (mSensors == nullptr) return NO_INIT;
Aravind Akella724d91d2013-06-27 12:04:23 -0700323
324 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
325 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
326 }
Peng Xu2bec6232016-07-01 17:13:10 -0700327 if (maxBatchReportLatencyNs < 0) {
328 maxBatchReportLatencyNs = 0;
329 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700330
Aravind Akella724d91d2013-06-27 12:04:23 -0700331 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700332 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700333 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
334
335 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700336 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
337 if (activationIndex < 0) {
338 ALOGW("Handle %d cannot be found in activation record", handle);
339 return BAD_VALUE;
340 }
341 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700342
343 if (info.batchParams.indexOfKey(ident) < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700344 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
Aravind Akella724d91d2013-06-27 12:04:23 -0700345 info.batchParams.add(ident, params);
346 } else {
347 // A batch has already been called with this ident. Update the batch parameters.
348 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
349 }
350
351 BatchParams prevBestBatchParams = info.bestBatchParams;
352 // Find the minimum of all timeouts and batch_rates for this sensor.
353 info.selectBatchParams();
354
355 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700356 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
357 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
Peng Xu2bec6232016-07-01 17:13:10 -0700358 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
359 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
Aravind Akella724d91d2013-06-27 12:04:23 -0700360
361 status_t err(NO_ERROR);
362 // If the min period or min timeout has changed since the last batch call, call batch.
363 if (prevBestBatchParams != info.bestBatchParams) {
Peng Xu2bec6232016-07-01 17:13:10 -0700364 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
365 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Steven Morelandd15c0302016-12-20 11:14:50 -0800366 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800367 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700368 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700369 if (err != NO_ERROR) {
Peng Xu2bec6232016-07-01 17:13:10 -0700370 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
371 mSensors.get(), handle, info.bestBatchParams.mTSample,
372 info.bestBatchParams.mTBatch, strerror(-err));
Aravind Akella724d91d2013-06-27 12:04:23 -0700373 info.removeBatchParamsForIdent(ident);
374 }
375 }
376 return err;
377}
378
Peng Xu6a2d3a02015-12-21 12:00:23 -0800379status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
Peng Xu2bec6232016-07-01 17:13:10 -0700380 return batch(ident, handle, 0, samplingPeriodNs, 0);
Mathias Agopian667102f2011-09-14 16:43:34 -0700381}
382
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700383int SensorDevice::getHalDeviceVersion() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700384 if (mSensors == nullptr) return -1;
Steven Morelandd15c0302016-12-20 11:14:50 -0800385 return SENSORS_DEVICE_API_VERSION_1_4;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700386}
387
Aravind Akella9a844cf2014-02-11 18:58:52 -0800388status_t SensorDevice::flush(void* ident, int handle) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700389 if (mSensors == nullptr) return NO_INIT;
Aravind Akella4949c502015-02-11 15:54:35 -0800390 if (isClientDisabled(ident)) return INVALID_OPERATION;
Aravind Akella724d91d2013-06-27 12:04:23 -0700391 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800392 return StatusFromResult(checkReturn(mSensors->flush(handle)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700393}
394
Aravind Akella4949c502015-02-11 15:54:35 -0800395bool SensorDevice::isClientDisabled(void* ident) {
396 Mutex::Autolock _l(mLock);
397 return isClientDisabledLocked(ident);
398}
399
400bool SensorDevice::isClientDisabledLocked(void* ident) {
401 return mDisabledClients.indexOf(ident) >= 0;
402}
403
404void SensorDevice::enableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700405 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800406 Mutex::Autolock _l(mLock);
407 mDisabledClients.clear();
Peng Xu966fa882016-09-01 16:13:15 -0700408 ALOGI("cleared mDisabledClients");
Aravind Akella4949c502015-02-11 15:54:35 -0800409 for (size_t i = 0; i< mActivationCount.size(); ++i) {
410 Info& info = mActivationCount.editValueAt(i);
411 if (info.batchParams.isEmpty()) continue;
412 info.selectBatchParams();
413 const int sensor_handle = mActivationCount.keyAt(i);
414 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
415 sensor_handle);
Steven Morelandd15c0302016-12-20 11:14:50 -0800416 status_t err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800417 checkReturn(mSensors->batch(
Steven Morelandd15c0302016-12-20 11:14:50 -0800418 sensor_handle,
Peng Xu2bec6232016-07-01 17:13:10 -0700419 info.bestBatchParams.mTSample,
420 info.bestBatchParams.mTBatch)));
Steven Morelandd15c0302016-12-20 11:14:50 -0800421 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
Aravind Akella4949c502015-02-11 15:54:35 -0800422
423 if (err == NO_ERROR) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800424 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800425 checkReturn(mSensors->activate(sensor_handle, 1 /* enabled */)));
Aravind Akella4949c502015-02-11 15:54:35 -0800426 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
427 }
Aravind Akella4949c502015-02-11 15:54:35 -0800428 }
429}
430
431void SensorDevice::disableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700432 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800433 Mutex::Autolock _l(mLock);
Peng Xua8fad9b2017-03-17 12:20:27 -0700434 for (size_t i = 0; i< mActivationCount.size(); ++i) {
Aravind Akella4949c502015-02-11 15:54:35 -0800435 const Info& info = mActivationCount.valueAt(i);
436 // Check if this sensor has been activated previously and disable it.
437 if (info.batchParams.size() > 0) {
438 const int sensor_handle = mActivationCount.keyAt(i);
439 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
440 sensor_handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800441 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
Steven Morelandd15c0302016-12-20 11:14:50 -0800442
Aravind Akella4949c502015-02-11 15:54:35 -0800443 // Add all the connections that were registered for this sensor to the disabled
444 // clients list.
Svetoslavb412f6e2015-04-29 16:50:41 -0700445 for (size_t j = 0; j < info.batchParams.size(); ++j) {
Aravind Akella4949c502015-02-11 15:54:35 -0800446 mDisabledClients.add(info.batchParams.keyAt(j));
Peng Xu966fa882016-09-01 16:13:15 -0700447 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
Aravind Akella4949c502015-02-11 15:54:35 -0800448 }
449 }
450 }
451}
452
Steven Morelandd15c0302016-12-20 11:14:50 -0800453status_t SensorDevice::injectSensorData(
454 const sensors_event_t *injected_sensor_event) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700455 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800456 ALOGD_IF(DEBUG_CONNECTIONS,
457 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
458 injected_sensor_event->sensor,
459 injected_sensor_event->timestamp, injected_sensor_event->data[0],
460 injected_sensor_event->data[1], injected_sensor_event->data[2],
461 injected_sensor_event->data[3], injected_sensor_event->data[4],
462 injected_sensor_event->data[5]);
463
464 Event ev;
465 convertFromSensorEvent(*injected_sensor_event, &ev);
466
Peng Xu3889e6e2017-03-02 19:10:38 -0800467 return StatusFromResult(checkReturn(mSensors->injectSensorData(ev)));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700468}
469
470status_t SensorDevice::setMode(uint32_t mode) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700471 if (mSensors == nullptr) return NO_INIT;
472 return StatusFromResult(
473 checkReturn(mSensors->setOperationMode(
474 static_cast<hardware::sensors::V1_0::OperationMode>(mode))));
475}
Steven Morelandd15c0302016-12-20 11:14:50 -0800476
Peng Xua8fad9b2017-03-17 12:20:27 -0700477int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
478 if (mSensors == nullptr) return NO_INIT;
479 Mutex::Autolock _l(mLock);
480
481 SharedMemType type;
482 switch (memory->type) {
483 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
484 type = SharedMemType::ASHMEM;
485 break;
486 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
487 type = SharedMemType::GRALLOC;
488 break;
489 default:
490 return BAD_VALUE;
491 }
492
493 SharedMemFormat format;
494 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
495 return BAD_VALUE;
496 }
497 format = SharedMemFormat::SENSORS_EVENT;
498
499 SharedMemInfo mem = {
500 .type = type,
501 .format = format,
502 .size = static_cast<uint32_t>(memory->size),
503 .memoryHandle = memory->handle,
504 };
505
506 int32_t ret;
507 checkReturn(mSensors->registerDirectChannel(mem,
508 [&ret](auto result, auto channelHandle) {
509 if (result == Result::OK) {
510 ret = channelHandle;
511 } else {
512 ret = StatusFromResult(result);
513 }
514 }));
515 return ret;
516}
517
518void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
519 if (mSensors == nullptr) return;
520 Mutex::Autolock _l(mLock);
521 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
522}
523
524int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
525 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
526 if (mSensors == nullptr) return NO_INIT;
527 Mutex::Autolock _l(mLock);
528
529 RateLevel rate;
530 switch(config->rate_level) {
531 case SENSOR_DIRECT_RATE_STOP:
532 rate = RateLevel::STOP;
533 break;
534 case SENSOR_DIRECT_RATE_NORMAL:
535 rate = RateLevel::NORMAL;
536 break;
537 case SENSOR_DIRECT_RATE_FAST:
538 rate = RateLevel::FAST;
539 break;
540 case SENSOR_DIRECT_RATE_VERY_FAST:
541 rate = RateLevel::VERY_FAST;
542 break;
543 default:
544 return BAD_VALUE;
545 }
546
547 int32_t ret;
548 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
549 [&ret, rate] (auto result, auto token) {
550 if (rate == RateLevel::STOP) {
551 ret = StatusFromResult(result);
552 } else {
553 if (result == Result::OK) {
554 ret = token;
555 } else {
556 ret = StatusFromResult(result);
557 }
558 }
559 }));
560
561 return ret;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700562}
563
Mathias Agopian667102f2011-09-14 16:43:34 -0700564// ---------------------------------------------------------------------------
565
Aravind Akella4949c502015-02-11 15:54:35 -0800566int SensorDevice::Info::numActiveClients() {
567 SensorDevice& device(SensorDevice::getInstance());
568 int num = 0;
569 for (size_t i = 0; i < batchParams.size(); ++i) {
570 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
571 ++num;
572 }
573 }
574 return num;
575}
576
Peng Xu2bec6232016-07-01 17:13:10 -0700577status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
Aravind Akella724d91d2013-06-27 12:04:23 -0700578 int64_t samplingPeriodNs,
579 int64_t maxBatchReportLatencyNs) {
580 ssize_t index = batchParams.indexOfKey(ident);
Mathias Agopian667102f2011-09-14 16:43:34 -0700581 if (index < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700582 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
583 " timeout=%" PRId64 ") failed (%s)",
Aravind Akella724d91d2013-06-27 12:04:23 -0700584 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
Mathias Agopian667102f2011-09-14 16:43:34 -0700585 return BAD_INDEX;
586 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700587 BatchParams& params = batchParams.editValueAt(index);
Peng Xu2bec6232016-07-01 17:13:10 -0700588 params.mTSample = samplingPeriodNs;
589 params.mTBatch = maxBatchReportLatencyNs;
Mathias Agopian667102f2011-09-14 16:43:34 -0700590 return NO_ERROR;
591}
592
Aravind Akella724d91d2013-06-27 12:04:23 -0700593void SensorDevice::Info::selectBatchParams() {
Peng Xu2bec6232016-07-01 17:13:10 -0700594 BatchParams bestParams; // default to max Tsample and max Tbatch
Aravind Akella4949c502015-02-11 15:54:35 -0800595 SensorDevice& device(SensorDevice::getInstance());
Aravind Akella724d91d2013-06-27 12:04:23 -0700596
Aravind Akella4949c502015-02-11 15:54:35 -0800597 for (size_t i = 0; i < batchParams.size(); ++i) {
Peng Xu2bec6232016-07-01 17:13:10 -0700598 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
599 continue;
Aravind Akella724d91d2013-06-27 12:04:23 -0700600 }
Peng Xu2bec6232016-07-01 17:13:10 -0700601 bestParams.merge(batchParams[i]);
602 }
603 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
604 if (bestParams.mTBatch <= bestParams.mTSample) {
605 bestParams.mTBatch = 0;
Mathias Agopianf001c922010-11-11 17:58:51 -0800606 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700607 bestBatchParams = bestParams;
608}
609
610ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
611 ssize_t idx = batchParams.removeItem(ident);
612 if (idx >= 0) {
613 selectBatchParams();
614 }
615 return idx;
Mathias Agopianf001c922010-11-11 17:58:51 -0800616}
617
Peng Xu4f707f82016-09-26 11:28:32 -0700618void SensorDevice::notifyConnectionDestroyed(void* ident) {
619 Mutex::Autolock _l(mLock);
620 mDisabledClients.remove(ident);
621}
622
Peng Xu53632542017-01-23 20:06:27 -0800623bool SensorDevice::isDirectReportSupported() const {
Steven Morelandd15c0302016-12-20 11:14:50 -0800624 return mIsDirectReportSupported;
Peng Xu53632542017-01-23 20:06:27 -0800625}
Steven Morelandd15c0302016-12-20 11:14:50 -0800626
627void SensorDevice::convertToSensorEvent(
628 const Event &src, sensors_event_t *dst) {
629 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
630 src, dst);
631
632 if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
633 const DynamicSensorInfo &dyn = src.u.dynamic;
634
635 dst->dynamic_sensor_meta.connected = dyn.connected;
636 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
637 if (dyn.connected) {
638 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
639 CHECK(it != mConnectedDynamicSensors.end());
640
641 dst->dynamic_sensor_meta.sensor = it->second;
642
643 memcpy(dst->dynamic_sensor_meta.uuid,
644 dyn.uuid.data(),
645 sizeof(dst->dynamic_sensor_meta.uuid));
646 }
647 }
648}
649
650void SensorDevice::convertToSensorEvents(
651 const hidl_vec<Event> &src,
652 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
653 sensors_event_t *dst) {
654 // Allocate a sensor_t structure for each dynamic sensor added and insert
655 // it into the dictionary of connected dynamic sensors keyed by handle.
656 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
657 const SensorInfo &info = dynamicSensorsAdded[i];
658
659 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
660 CHECK(it == mConnectedDynamicSensors.end());
661
662 sensor_t *sensor = new sensor_t;
663 convertToSensor(info, sensor);
664
665 mConnectedDynamicSensors.insert(
666 std::make_pair(sensor->handle, sensor));
667 }
668
669 for (size_t i = 0; i < src.size(); ++i) {
670 convertToSensorEvent(src[i], &dst[i]);
671 }
672}
673
Peng Xu3889e6e2017-03-02 19:10:38 -0800674void SensorDevice::handleHidlDeath(const std::string & detail) {
675 // restart is the only option at present.
676 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
677}
678
Mathias Agopianf001c922010-11-11 17:58:51 -0800679// ---------------------------------------------------------------------------
680}; // namespace android