blob: bbceba5ce5b7f55e25a7c2f555f286b83a0a6f33 [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>
Brian Stack979887b2018-09-19 15:27:48 -070020#include <sensor/SensorEventQueue.h>
Peng Xu3889e6e2017-03-02 19:10:38 -080021#include <sensors/convert.h>
Steven Moreland2716e112018-02-23 14:57:20 -080022#include <cutils/atomic.h>
Ashutosh Joshi5cafc1e2017-02-09 21:44:04 +000023#include <utils/Errors.h>
24#include <utils/Singleton.h>
Steven Morelandd3335112016-12-20 11:14:50 -080025
Peng Xu3889e6e2017-03-02 19:10:38 -080026#include <chrono>
27#include <cinttypes>
28#include <thread>
Steven Morelandd15c0302016-12-20 11:14:50 -080029
Brian Stack12f4d322018-09-14 16:18:59 -070030using namespace android::hardware::sensors;
Steven Morelandd15c0302016-12-20 11:14:50 -080031using namespace android::hardware::sensors::V1_0;
32using namespace android::hardware::sensors::V1_0::implementation;
Peng Xu1a00e2d2017-09-27 23:08:30 -070033using android::hardware::hidl_vec;
34using android::SensorDeviceUtils::HidlServiceRegistrationWaiter;
Peng Xu2bec6232016-07-01 17:13:10 -070035
Mathias Agopianf001c922010-11-11 17:58:51 -080036namespace android {
37// ---------------------------------------------------------------------------
Mathias Agopianf001c922010-11-11 17:58:51 -080038
39ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
40
Steven Morelandd15c0302016-12-20 11:14:50 -080041static status_t StatusFromResult(Result result) {
42 switch (result) {
43 case Result::OK:
44 return OK;
45 case Result::BAD_VALUE:
46 return BAD_VALUE;
47 case Result::PERMISSION_DENIED:
48 return PERMISSION_DENIED;
49 case Result::INVALID_OPERATION:
50 return INVALID_OPERATION;
51 case Result::NO_MEMORY:
52 return NO_MEMORY;
Mathias Agopianf001c922010-11-11 17:58:51 -080053 }
54}
55
Peng Xu1a00e2d2017-09-27 23:08:30 -070056SensorDevice::SensorDevice()
57 : mHidlTransportErrors(20), mRestartWaiter(new HidlServiceRegistrationWaiter()) {
Peng Xua8fad9b2017-03-17 12:20:27 -070058 if (!connectHidlService()) {
59 return;
60 }
Ashutosh Joshifea2d262017-04-19 23:27:49 -070061
62 float minPowerMa = 0.001; // 1 microAmp
63
Peng Xua8fad9b2017-03-17 12:20:27 -070064 checkReturn(mSensors->getSensorsList(
65 [&](const auto &list) {
66 const size_t count = list.size();
67
68 mActivationCount.setCapacity(count);
69 Info model;
70 for (size_t i=0 ; i < count; i++) {
71 sensor_t sensor;
72 convertToSensor(list[i], &sensor);
Ashutosh Joshifea2d262017-04-19 23:27:49 -070073 // Sanity check and clamp power if it is 0 (or close)
74 if (sensor.power < minPowerMa) {
75 ALOGE("Reported power %f not deemed sane, clamping to %f",
76 sensor.power, minPowerMa);
77 sensor.power = minPowerMa;
78 }
Peng Xua8fad9b2017-03-17 12:20:27 -070079 mSensorList.push_back(sensor);
80
81 mActivationCount.add(list[i].sensorHandle, model);
82
83 checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
84 }
85 }));
86
87 mIsDirectReportSupported =
88 (checkReturn(mSensors->unregisterDirectChannel(-1)) != Result::INVALID_OPERATION);
89}
90
91bool SensorDevice::connectHidlService() {
Brian Stack979887b2018-09-19 15:27:48 -070092 HalConnectionStatus status = connectHidlServiceV2_0();
93 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
94 status = connectHidlServiceV1_0();
Brian Stack12f4d322018-09-14 16:18:59 -070095 }
Brian Stack979887b2018-09-19 15:27:48 -070096 return (status == HalConnectionStatus::CONNECTED);
Brian Stack12f4d322018-09-14 16:18:59 -070097}
98
Brian Stack979887b2018-09-19 15:27:48 -070099SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700100 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
Peng Xu3889e6e2017-03-02 19:10:38 -0800101 size_t retry = 10;
Brian Stack979887b2018-09-19 15:27:48 -0700102 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Steven Morelandd15c0302016-12-20 11:14:50 -0800103
Peng Xu1a00e2d2017-09-27 23:08:30 -0700104 while (retry-- > 0) {
Brian Stack12f4d322018-09-14 16:18:59 -0700105 sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
106 if (sensors == nullptr) {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700107 // no sensor hidl service found
Brian Stack979887b2018-09-19 15:27:48 -0700108 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
Peng Xua8fad9b2017-03-17 12:20:27 -0700109 break;
Peng Xu3889e6e2017-03-02 19:10:38 -0800110 }
Peng Xu1a00e2d2017-09-27 23:08:30 -0700111
Brian Stack12f4d322018-09-14 16:18:59 -0700112 mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors);
Peng Xu1a00e2d2017-09-27 23:08:30 -0700113 mRestartWaiter->reset();
114 // Poke ISensor service. If it has lingering connection from previous generation of
115 // system server, it will kill itself. There is no intention to handle the poll result,
116 // which will be done since the size is 0.
117 if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
118 // ok to continue
Brian Stack979887b2018-09-19 15:27:48 -0700119 connectionStatus = HalConnectionStatus::CONNECTED;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700120 break;
121 }
122
123 // hidl service is restarting, pointer is invalid.
124 mSensors = nullptr;
Brian Stack979887b2018-09-19 15:27:48 -0700125 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700126 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
127 mRestartWaiter->wait();
Steven Morelandd15c0302016-12-20 11:14:50 -0800128 }
Brian Stack979887b2018-09-19 15:27:48 -0700129
130 return connectionStatus;
Steven Morelandd15c0302016-12-20 11:14:50 -0800131}
132
Brian Stack979887b2018-09-19 15:27:48 -0700133SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
134 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Brian Stack12f4d322018-09-14 16:18:59 -0700135 sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
Brian Stack979887b2018-09-19 15:27:48 -0700136
137 if (sensors == nullptr) {
138 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
139 } else {
Brian Stack12f4d322018-09-14 16:18:59 -0700140 mSensors = new SensorServiceUtil::SensorsWrapperV2_0(sensors);
141
Brian Stack979887b2018-09-19 15:27:48 -0700142 mEventQueue = std::make_unique<EventMessageQueue>(
143 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
144 true /* configureEventFlagWord */);
145
146 mWakeLockQueue = std::make_unique<WakeLockQueue>(
147 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
148 true /* configureEventFlagWord */);
149
150 CHECK(mSensors != nullptr && mEventQueue != nullptr &&
151 mWakeLockQueue != nullptr);
152
153 status_t status = StatusFromResult(checkReturn(mSensors->initializeMessageQueues(
154 *mEventQueue->getDesc(),
155 *mWakeLockQueue->getDesc())));
156
157 if (status != NO_ERROR) {
158 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
159 ALOGE("Failed to initialize message queues (%s)", strerror(-status));
160 } else {
161 connectionStatus = HalConnectionStatus::CONNECTED;
162 }
Brian Stack12f4d322018-09-14 16:18:59 -0700163 }
Brian Stack979887b2018-09-19 15:27:48 -0700164
165 return connectionStatus;
Brian Stack12f4d322018-09-14 16:18:59 -0700166}
167
Peng Xu2576cb62016-01-20 00:22:09 -0800168void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700169 // not need to check mSensors because this is is only called after successful poll()
Peng Xu2576cb62016-01-20 00:22:09 -0800170 if (connected) {
171 Info model;
172 mActivationCount.add(handle, model);
Peng Xu3889e6e2017-03-02 19:10:38 -0800173 checkReturn(mSensors->activate(handle, 0 /* enabled */));
Peng Xu2576cb62016-01-20 00:22:09 -0800174 } else {
175 mActivationCount.removeItem(handle);
176 }
177}
178
Peng Xu6a2d3a02015-12-21 12:00:23 -0800179std::string SensorDevice::dump() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700180 if (mSensors == nullptr) return "HAL not initialized\n";
Mathias Agopianf001c922010-11-11 17:58:51 -0800181
Peng Xu6a2d3a02015-12-21 12:00:23 -0800182 String8 result;
Peng Xua8fad9b2017-03-17 12:20:27 -0700183 result.appendFormat("Total %zu h/w sensors, %zu running:\n",
184 mSensorList.size(), mActivationCount.size());
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700185
Peng Xua8fad9b2017-03-17 12:20:27 -0700186 Mutex::Autolock _l(mLock);
187 for (const auto & s : mSensorList) {
188 int32_t handle = s.handle;
189 const Info& info = mActivationCount.valueFor(handle);
190 if (info.batchParams.isEmpty()) continue;
191
192 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
193
194 result.append("sampling_period(ms) = {");
195 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700196 const BatchParams& params = info.batchParams[j];
197 result.appendFormat("%.1f%s", params.mTSample / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700198 j < info.batchParams.size() - 1 ? ", " : "");
199 }
Peng Xu2bec6232016-07-01 17:13:10 -0700200 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
Peng Xua8fad9b2017-03-17 12:20:27 -0700201
202 result.append("batching_period(ms) = {");
203 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700204 const BatchParams& params = info.batchParams[j];
205 result.appendFormat("%.1f%s", params.mTBatch / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700206 j < info.batchParams.size() - 1 ? ", " : "");
207 }
Peng Xu2bec6232016-07-01 17:13:10 -0700208 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700209 }
210
Peng Xu6a2d3a02015-12-21 12:00:23 -0800211 return result.string();
Mathias Agopianf001c922010-11-11 17:58:51 -0800212}
213
214ssize_t SensorDevice::getSensorList(sensor_t const** list) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800215 *list = &mSensorList[0];
216
217 return mSensorList.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800218}
219
220status_t SensorDevice::initCheck() const {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700221 return mSensors != nullptr ? NO_ERROR : NO_INIT;
Mathias Agopianf001c922010-11-11 17:58:51 -0800222}
223
224ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700225 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800226
227 ssize_t err;
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700228 int numHidlTransportErrors = 0;
229 bool hidlTransportError = false;
Steven Morelandd15c0302016-12-20 11:14:50 -0800230
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700231 do {
232 auto ret = mSensors->poll(
233 count,
234 [&](auto result,
235 const auto &events,
236 const auto &dynamicSensorsAdded) {
237 if (result == Result::OK) {
238 convertToSensorEvents(events, dynamicSensorsAdded, buffer);
239 err = (ssize_t)events.size();
240 } else {
241 err = StatusFromResult(result);
242 }
243 });
244
245 if (ret.isOk()) {
246 hidlTransportError = false;
247 } else {
248 hidlTransportError = true;
249 numHidlTransportErrors++;
250 if (numHidlTransportErrors > 50) {
251 // Log error and bail
252 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
253 handleHidlDeath(ret.description());
254 } else {
255 std::this_thread::sleep_for(std::chrono::milliseconds(10));
256 }
257 }
258 } while (hidlTransportError);
259
260 if(numHidlTransportErrors > 0) {
261 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
Yi Kong8f313e32018-07-17 14:13:29 -0700262 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700263 mHidlTransportErrors.add(errLog);
264 mTotalHidlTransportErrors++;
265 }
Steven Morelandd15c0302016-12-20 11:14:50 -0800266
267 return err;
Mathias Agopianf001c922010-11-11 17:58:51 -0800268}
269
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700270void SensorDevice::autoDisable(void *ident, int handle) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700271 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700272 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
273 if (activationIndex < 0) {
274 ALOGW("Handle %d cannot be found in activation record", handle);
275 return;
276 }
277 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700278 info.removeBatchParamsForIdent(ident);
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700279}
280
Peng Xu6a2d3a02015-12-21 12:00:23 -0800281status_t SensorDevice::activate(void* ident, int handle, int enabled) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700282 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800283
Mathias Agopianf001c922010-11-11 17:58:51 -0800284 status_t err(NO_ERROR);
285 bool actuateHardware = false;
286
Aravind Akella724d91d2013-06-27 12:04:23 -0700287 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700288 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
289 if (activationIndex < 0) {
290 ALOGW("Handle %d cannot be found in activation record", handle);
291 return BAD_VALUE;
292 }
293 Info& info(mActivationCount.editValueAt(activationIndex));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700294
Steve Blocka5512372011-12-20 16:23:08 +0000295 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700296 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
Aravind Akella724d91d2013-06-27 12:04:23 -0700297 ident, handle, enabled, info.batchParams.size());
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700298
Mathias Agopianf001c922010-11-11 17:58:51 -0800299 if (enabled) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700300 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700301
Aravind Akella4949c502015-02-11 15:54:35 -0800302 if (isClientDisabledLocked(ident)) {
Peng Xu966fa882016-09-01 16:13:15 -0700303 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
304 ident, handle);
Aravind Akella4949c502015-02-11 15:54:35 -0800305 return INVALID_OPERATION;
306 }
307
Aravind Akella724d91d2013-06-27 12:04:23 -0700308 if (info.batchParams.indexOfKey(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800309 if (info.numActiveClients() == 1) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700310 // This is the first connection, we need to activate the underlying h/w sensor.
311 actuateHardware = true;
312 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800313 } else {
Aravind Akella724d91d2013-06-27 12:04:23 -0700314 // Log error. Every activate call should be preceded by a batch() call.
315 ALOGE("\t >>>ERROR: activate called without batch");
Mathias Agopianf001c922010-11-11 17:58:51 -0800316 }
317 } else {
Mark Salyzyndb458612014-06-10 14:50:02 -0700318 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700319
Steven Morelandd15c0302016-12-20 11:14:50 -0800320 // If a connected dynamic sensor is deactivated, remove it from the
321 // dictionary.
322 auto it = mConnectedDynamicSensors.find(handle);
323 if (it != mConnectedDynamicSensors.end()) {
324 delete it->second;
325 mConnectedDynamicSensors.erase(it);
326 }
327
Aravind Akella724d91d2013-06-27 12:04:23 -0700328 if (info.removeBatchParamsForIdent(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800329 if (info.numActiveClients() == 0) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700330 // This is the last connection, we need to de-activate the underlying h/w sensor.
Mathias Agopian50b66762010-11-29 17:26:51 -0800331 actuateHardware = true;
Aravind Akella724d91d2013-06-27 12:04:23 -0700332 } else {
Steven Morelandd15c0302016-12-20 11:14:50 -0800333 // Call batch for this sensor with the previously calculated best effort
334 // batch_rate and timeout. One of the apps has unregistered for sensor
335 // events, and the best effort batch parameters might have changed.
336 ALOGD_IF(DEBUG_CONNECTIONS,
Peng Xu2bec6232016-07-01 17:13:10 -0700337 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
338 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Peng Xu3889e6e2017-03-02 19:10:38 -0800339 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700340 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Mathias Agopian50b66762010-11-29 17:26:51 -0800341 }
342 } else {
343 // sensor wasn't enabled for this ident
344 }
Aravind Akella4949c502015-02-11 15:54:35 -0800345
346 if (isClientDisabledLocked(ident)) {
347 return NO_ERROR;
348 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800349 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800350
Mathias Agopianf001c922010-11-11 17:58:51 -0800351 if (actuateHardware) {
Aravind Akella4949c502015-02-11 15:54:35 -0800352 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
353 enabled);
Peng Xu3889e6e2017-03-02 19:10:38 -0800354 err = StatusFromResult(checkReturn(mSensors->activate(handle, enabled)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700355 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
356 strerror(-err));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700357
Aravind Akella724d91d2013-06-27 12:04:23 -0700358 if (err != NO_ERROR && enabled) {
359 // Failure when enabling the sensor. Clean up on failure.
360 info.removeBatchParamsForIdent(ident);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700361 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800362 }
363
Mathias Agopianf001c922010-11-11 17:58:51 -0800364 return err;
365}
366
Steven Morelandd15c0302016-12-20 11:14:50 -0800367status_t SensorDevice::batch(
368 void* ident,
369 int handle,
370 int flags,
371 int64_t samplingPeriodNs,
372 int64_t maxBatchReportLatencyNs) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700373 if (mSensors == nullptr) return NO_INIT;
Aravind Akella724d91d2013-06-27 12:04:23 -0700374
375 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
376 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
377 }
Peng Xu2bec6232016-07-01 17:13:10 -0700378 if (maxBatchReportLatencyNs < 0) {
379 maxBatchReportLatencyNs = 0;
380 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700381
Aravind Akella724d91d2013-06-27 12:04:23 -0700382 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700383 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700384 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
385
386 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700387 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
388 if (activationIndex < 0) {
389 ALOGW("Handle %d cannot be found in activation record", handle);
390 return BAD_VALUE;
391 }
392 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700393
394 if (info.batchParams.indexOfKey(ident) < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700395 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
Aravind Akella724d91d2013-06-27 12:04:23 -0700396 info.batchParams.add(ident, params);
397 } else {
398 // A batch has already been called with this ident. Update the batch parameters.
399 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
400 }
401
402 BatchParams prevBestBatchParams = info.bestBatchParams;
403 // Find the minimum of all timeouts and batch_rates for this sensor.
404 info.selectBatchParams();
405
406 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700407 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
408 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
Peng Xu2bec6232016-07-01 17:13:10 -0700409 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
410 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
Aravind Akella724d91d2013-06-27 12:04:23 -0700411
412 status_t err(NO_ERROR);
413 // If the min period or min timeout has changed since the last batch call, call batch.
414 if (prevBestBatchParams != info.bestBatchParams) {
Peng Xu2bec6232016-07-01 17:13:10 -0700415 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
416 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Steven Morelandd15c0302016-12-20 11:14:50 -0800417 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800418 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700419 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700420 if (err != NO_ERROR) {
Peng Xu2bec6232016-07-01 17:13:10 -0700421 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
422 mSensors.get(), handle, info.bestBatchParams.mTSample,
423 info.bestBatchParams.mTBatch, strerror(-err));
Aravind Akella724d91d2013-06-27 12:04:23 -0700424 info.removeBatchParamsForIdent(ident);
425 }
426 }
427 return err;
428}
429
Peng Xu6a2d3a02015-12-21 12:00:23 -0800430status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
Peng Xu2bec6232016-07-01 17:13:10 -0700431 return batch(ident, handle, 0, samplingPeriodNs, 0);
Mathias Agopian667102f2011-09-14 16:43:34 -0700432}
433
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700434int SensorDevice::getHalDeviceVersion() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700435 if (mSensors == nullptr) return -1;
Steven Morelandd15c0302016-12-20 11:14:50 -0800436 return SENSORS_DEVICE_API_VERSION_1_4;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700437}
438
Aravind Akella9a844cf2014-02-11 18:58:52 -0800439status_t SensorDevice::flush(void* ident, int handle) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700440 if (mSensors == nullptr) return NO_INIT;
Aravind Akella4949c502015-02-11 15:54:35 -0800441 if (isClientDisabled(ident)) return INVALID_OPERATION;
Aravind Akella724d91d2013-06-27 12:04:23 -0700442 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800443 return StatusFromResult(checkReturn(mSensors->flush(handle)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700444}
445
Aravind Akella4949c502015-02-11 15:54:35 -0800446bool SensorDevice::isClientDisabled(void* ident) {
447 Mutex::Autolock _l(mLock);
448 return isClientDisabledLocked(ident);
449}
450
451bool SensorDevice::isClientDisabledLocked(void* ident) {
452 return mDisabledClients.indexOf(ident) >= 0;
453}
454
455void SensorDevice::enableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700456 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800457 Mutex::Autolock _l(mLock);
458 mDisabledClients.clear();
Peng Xu966fa882016-09-01 16:13:15 -0700459 ALOGI("cleared mDisabledClients");
Aravind Akella4949c502015-02-11 15:54:35 -0800460 for (size_t i = 0; i< mActivationCount.size(); ++i) {
461 Info& info = mActivationCount.editValueAt(i);
462 if (info.batchParams.isEmpty()) continue;
463 info.selectBatchParams();
464 const int sensor_handle = mActivationCount.keyAt(i);
465 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
466 sensor_handle);
Steven Morelandd15c0302016-12-20 11:14:50 -0800467 status_t err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800468 checkReturn(mSensors->batch(
Steven Morelandd15c0302016-12-20 11:14:50 -0800469 sensor_handle,
Peng Xu2bec6232016-07-01 17:13:10 -0700470 info.bestBatchParams.mTSample,
471 info.bestBatchParams.mTBatch)));
Steven Morelandd15c0302016-12-20 11:14:50 -0800472 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
Aravind Akella4949c502015-02-11 15:54:35 -0800473
474 if (err == NO_ERROR) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800475 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800476 checkReturn(mSensors->activate(sensor_handle, 1 /* enabled */)));
Aravind Akella4949c502015-02-11 15:54:35 -0800477 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
478 }
Aravind Akella4949c502015-02-11 15:54:35 -0800479 }
480}
481
482void SensorDevice::disableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700483 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800484 Mutex::Autolock _l(mLock);
Peng Xua8fad9b2017-03-17 12:20:27 -0700485 for (size_t i = 0; i< mActivationCount.size(); ++i) {
Aravind Akella4949c502015-02-11 15:54:35 -0800486 const Info& info = mActivationCount.valueAt(i);
487 // Check if this sensor has been activated previously and disable it.
488 if (info.batchParams.size() > 0) {
489 const int sensor_handle = mActivationCount.keyAt(i);
490 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
491 sensor_handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800492 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
Steven Morelandd15c0302016-12-20 11:14:50 -0800493
Aravind Akella4949c502015-02-11 15:54:35 -0800494 // Add all the connections that were registered for this sensor to the disabled
495 // clients list.
Svetoslavb412f6e2015-04-29 16:50:41 -0700496 for (size_t j = 0; j < info.batchParams.size(); ++j) {
Aravind Akella4949c502015-02-11 15:54:35 -0800497 mDisabledClients.add(info.batchParams.keyAt(j));
Peng Xu966fa882016-09-01 16:13:15 -0700498 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
Aravind Akella4949c502015-02-11 15:54:35 -0800499 }
500 }
501 }
502}
503
Steven Morelandd15c0302016-12-20 11:14:50 -0800504status_t SensorDevice::injectSensorData(
505 const sensors_event_t *injected_sensor_event) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700506 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800507 ALOGD_IF(DEBUG_CONNECTIONS,
508 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
509 injected_sensor_event->sensor,
510 injected_sensor_event->timestamp, injected_sensor_event->data[0],
511 injected_sensor_event->data[1], injected_sensor_event->data[2],
512 injected_sensor_event->data[3], injected_sensor_event->data[4],
513 injected_sensor_event->data[5]);
514
515 Event ev;
516 convertFromSensorEvent(*injected_sensor_event, &ev);
517
Peng Xu3889e6e2017-03-02 19:10:38 -0800518 return StatusFromResult(checkReturn(mSensors->injectSensorData(ev)));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700519}
520
521status_t SensorDevice::setMode(uint32_t mode) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700522 if (mSensors == nullptr) return NO_INIT;
523 return StatusFromResult(
524 checkReturn(mSensors->setOperationMode(
525 static_cast<hardware::sensors::V1_0::OperationMode>(mode))));
526}
Steven Morelandd15c0302016-12-20 11:14:50 -0800527
Peng Xua8fad9b2017-03-17 12:20:27 -0700528int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
529 if (mSensors == nullptr) return NO_INIT;
530 Mutex::Autolock _l(mLock);
531
532 SharedMemType type;
533 switch (memory->type) {
534 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
535 type = SharedMemType::ASHMEM;
536 break;
537 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
538 type = SharedMemType::GRALLOC;
539 break;
540 default:
541 return BAD_VALUE;
542 }
543
544 SharedMemFormat format;
545 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
546 return BAD_VALUE;
547 }
548 format = SharedMemFormat::SENSORS_EVENT;
549
550 SharedMemInfo mem = {
551 .type = type,
552 .format = format,
553 .size = static_cast<uint32_t>(memory->size),
554 .memoryHandle = memory->handle,
555 };
556
557 int32_t ret;
558 checkReturn(mSensors->registerDirectChannel(mem,
559 [&ret](auto result, auto channelHandle) {
560 if (result == Result::OK) {
561 ret = channelHandle;
562 } else {
563 ret = StatusFromResult(result);
564 }
565 }));
566 return ret;
567}
568
569void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
570 if (mSensors == nullptr) return;
571 Mutex::Autolock _l(mLock);
572 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
573}
574
575int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
576 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
577 if (mSensors == nullptr) return NO_INIT;
578 Mutex::Autolock _l(mLock);
579
580 RateLevel rate;
581 switch(config->rate_level) {
582 case SENSOR_DIRECT_RATE_STOP:
583 rate = RateLevel::STOP;
584 break;
585 case SENSOR_DIRECT_RATE_NORMAL:
586 rate = RateLevel::NORMAL;
587 break;
588 case SENSOR_DIRECT_RATE_FAST:
589 rate = RateLevel::FAST;
590 break;
591 case SENSOR_DIRECT_RATE_VERY_FAST:
592 rate = RateLevel::VERY_FAST;
593 break;
594 default:
595 return BAD_VALUE;
596 }
597
598 int32_t ret;
599 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
600 [&ret, rate] (auto result, auto token) {
601 if (rate == RateLevel::STOP) {
602 ret = StatusFromResult(result);
603 } else {
604 if (result == Result::OK) {
605 ret = token;
606 } else {
607 ret = StatusFromResult(result);
608 }
609 }
610 }));
611
612 return ret;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700613}
614
Mathias Agopian667102f2011-09-14 16:43:34 -0700615// ---------------------------------------------------------------------------
616
Aravind Akella4949c502015-02-11 15:54:35 -0800617int SensorDevice::Info::numActiveClients() {
618 SensorDevice& device(SensorDevice::getInstance());
619 int num = 0;
620 for (size_t i = 0; i < batchParams.size(); ++i) {
621 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
622 ++num;
623 }
624 }
625 return num;
626}
627
Peng Xu2bec6232016-07-01 17:13:10 -0700628status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
Aravind Akella724d91d2013-06-27 12:04:23 -0700629 int64_t samplingPeriodNs,
630 int64_t maxBatchReportLatencyNs) {
631 ssize_t index = batchParams.indexOfKey(ident);
Mathias Agopian667102f2011-09-14 16:43:34 -0700632 if (index < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700633 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
634 " timeout=%" PRId64 ") failed (%s)",
Aravind Akella724d91d2013-06-27 12:04:23 -0700635 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
Mathias Agopian667102f2011-09-14 16:43:34 -0700636 return BAD_INDEX;
637 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700638 BatchParams& params = batchParams.editValueAt(index);
Peng Xu2bec6232016-07-01 17:13:10 -0700639 params.mTSample = samplingPeriodNs;
640 params.mTBatch = maxBatchReportLatencyNs;
Mathias Agopian667102f2011-09-14 16:43:34 -0700641 return NO_ERROR;
642}
643
Aravind Akella724d91d2013-06-27 12:04:23 -0700644void SensorDevice::Info::selectBatchParams() {
Peng Xu2bec6232016-07-01 17:13:10 -0700645 BatchParams bestParams; // default to max Tsample and max Tbatch
Aravind Akella4949c502015-02-11 15:54:35 -0800646 SensorDevice& device(SensorDevice::getInstance());
Aravind Akella724d91d2013-06-27 12:04:23 -0700647
Aravind Akella4949c502015-02-11 15:54:35 -0800648 for (size_t i = 0; i < batchParams.size(); ++i) {
Peng Xu2bec6232016-07-01 17:13:10 -0700649 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
650 continue;
Aravind Akella724d91d2013-06-27 12:04:23 -0700651 }
Peng Xu2bec6232016-07-01 17:13:10 -0700652 bestParams.merge(batchParams[i]);
653 }
654 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
655 if (bestParams.mTBatch <= bestParams.mTSample) {
656 bestParams.mTBatch = 0;
Mathias Agopianf001c922010-11-11 17:58:51 -0800657 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700658 bestBatchParams = bestParams;
659}
660
661ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
662 ssize_t idx = batchParams.removeItem(ident);
663 if (idx >= 0) {
664 selectBatchParams();
665 }
666 return idx;
Mathias Agopianf001c922010-11-11 17:58:51 -0800667}
668
Peng Xu4f707f82016-09-26 11:28:32 -0700669void SensorDevice::notifyConnectionDestroyed(void* ident) {
670 Mutex::Autolock _l(mLock);
671 mDisabledClients.remove(ident);
672}
673
Peng Xu53632542017-01-23 20:06:27 -0800674bool SensorDevice::isDirectReportSupported() const {
Steven Morelandd15c0302016-12-20 11:14:50 -0800675 return mIsDirectReportSupported;
Peng Xu53632542017-01-23 20:06:27 -0800676}
Steven Morelandd15c0302016-12-20 11:14:50 -0800677
678void SensorDevice::convertToSensorEvent(
679 const Event &src, sensors_event_t *dst) {
680 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
681 src, dst);
682
683 if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
684 const DynamicSensorInfo &dyn = src.u.dynamic;
685
686 dst->dynamic_sensor_meta.connected = dyn.connected;
687 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
688 if (dyn.connected) {
689 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
690 CHECK(it != mConnectedDynamicSensors.end());
691
692 dst->dynamic_sensor_meta.sensor = it->second;
693
694 memcpy(dst->dynamic_sensor_meta.uuid,
695 dyn.uuid.data(),
696 sizeof(dst->dynamic_sensor_meta.uuid));
697 }
698 }
699}
700
701void SensorDevice::convertToSensorEvents(
702 const hidl_vec<Event> &src,
703 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
704 sensors_event_t *dst) {
705 // Allocate a sensor_t structure for each dynamic sensor added and insert
706 // it into the dictionary of connected dynamic sensors keyed by handle.
707 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
708 const SensorInfo &info = dynamicSensorsAdded[i];
709
710 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
711 CHECK(it == mConnectedDynamicSensors.end());
712
713 sensor_t *sensor = new sensor_t;
714 convertToSensor(info, sensor);
715
716 mConnectedDynamicSensors.insert(
717 std::make_pair(sensor->handle, sensor));
718 }
719
720 for (size_t i = 0; i < src.size(); ++i) {
721 convertToSensorEvent(src[i], &dst[i]);
722 }
723}
724
Peng Xu3889e6e2017-03-02 19:10:38 -0800725void SensorDevice::handleHidlDeath(const std::string & detail) {
726 // restart is the only option at present.
727 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
728}
729
Mathias Agopianf001c922010-11-11 17:58:51 -0800730// ---------------------------------------------------------------------------
731}; // namespace android