blob: fcd4f29adf957b682c60e22689650e163c1a3982 [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 */
Brian Stacka28e9212018-09-19 15:20:30 -070016
Peng Xu3889e6e2017-03-02 19:10:38 -080017#include "SensorDevice.h"
Brian Stacka28e9212018-09-19 15:20:30 -070018
Brian Stackbbab1ea2018-10-01 10:49:07 -070019#include "android/hardware/sensors/2.0/ISensorsCallback.h"
Brian Stacka28e9212018-09-19 15:20:30 -070020#include "android/hardware/sensors/2.0/types.h"
Peng Xu3889e6e2017-03-02 19:10:38 -080021#include "SensorService.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080022
Steven Morelandd15c0302016-12-20 11:14:50 -080023#include <android-base/logging.h>
Peng Xu3889e6e2017-03-02 19:10:38 -080024#include <sensors/convert.h>
Steven Moreland2716e112018-02-23 14:57:20 -080025#include <cutils/atomic.h>
Ashutosh Joshi5cafc1e2017-02-09 21:44:04 +000026#include <utils/Errors.h>
27#include <utils/Singleton.h>
Steven Morelandd3335112016-12-20 11:14:50 -080028
Peng Xu3889e6e2017-03-02 19:10:38 -080029#include <chrono>
30#include <cinttypes>
31#include <thread>
Steven Morelandd15c0302016-12-20 11:14:50 -080032
Brian Stack12f4d322018-09-14 16:18:59 -070033using namespace android::hardware::sensors;
Steven Morelandd15c0302016-12-20 11:14:50 -080034using namespace android::hardware::sensors::V1_0;
35using namespace android::hardware::sensors::V1_0::implementation;
Brian Stackbbab1ea2018-10-01 10:49:07 -070036using android::hardware::sensors::V2_0::ISensorsCallback;
Brian Stacka28e9212018-09-19 15:20:30 -070037using android::hardware::sensors::V2_0::EventQueueFlagBits;
Brian Stacka24e7d42019-01-08 12:56:09 -080038using android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
Peng Xu1a00e2d2017-09-27 23:08:30 -070039using android::hardware::hidl_vec;
Brian Stack6c49e6f2018-09-24 15:44:32 -070040using android::hardware::Return;
Peng Xu1a00e2d2017-09-27 23:08:30 -070041using android::SensorDeviceUtils::HidlServiceRegistrationWaiter;
Peng Xu2bec6232016-07-01 17:13:10 -070042
Mathias Agopianf001c922010-11-11 17:58:51 -080043namespace android {
44// ---------------------------------------------------------------------------
Mathias Agopianf001c922010-11-11 17:58:51 -080045
46ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
47
Steven Morelandd15c0302016-12-20 11:14:50 -080048static status_t StatusFromResult(Result result) {
49 switch (result) {
50 case Result::OK:
51 return OK;
52 case Result::BAD_VALUE:
53 return BAD_VALUE;
54 case Result::PERMISSION_DENIED:
55 return PERMISSION_DENIED;
56 case Result::INVALID_OPERATION:
57 return INVALID_OPERATION;
58 case Result::NO_MEMORY:
59 return NO_MEMORY;
Mathias Agopianf001c922010-11-11 17:58:51 -080060 }
61}
62
Brian Stack156da082018-10-01 15:58:53 -070063template<typename EnumType>
64constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
65 return static_cast<typename std::underlying_type<EnumType>::type>(value);
66}
67
68// Used internally by the framework to wake the Event FMQ. These values must start after
69// the last value of EventQueueFlagBits
70enum EventQueueFlagBitsInternal : uint32_t {
71 INTERNAL_WAKE = 1 << 16,
72};
73
Brian Stack574cda32018-10-01 11:18:51 -070074void SensorsHalDeathReceivier::serviceDied(
75 uint64_t /* cookie */,
76 const wp<::android::hidl::base::V1_0::IBase>& /* service */) {
77 ALOGW("Sensors HAL died, attempting to reconnect.");
Brian Stack156da082018-10-01 15:58:53 -070078 SensorDevice::getInstance().prepareForReconnect();
Brian Stack574cda32018-10-01 11:18:51 -070079}
80
Brian Stackbbab1ea2018-10-01 10:49:07 -070081struct SensorsCallback : public ISensorsCallback {
82 using Result = ::android::hardware::sensors::V1_0::Result;
83 Return<void> onDynamicSensorsConnected(
84 const hidl_vec<SensorInfo> &dynamicSensorsAdded) override {
85 return SensorDevice::getInstance().onDynamicSensorsConnected(dynamicSensorsAdded);
86 }
87
88 Return<void> onDynamicSensorsDisconnected(
89 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) override {
90 return SensorDevice::getInstance().onDynamicSensorsDisconnected(
91 dynamicSensorHandlesRemoved);
92 }
93};
94
Peng Xu1a00e2d2017-09-27 23:08:30 -070095SensorDevice::SensorDevice()
Brian Stack156da082018-10-01 15:58:53 -070096 : mHidlTransportErrors(20),
97 mRestartWaiter(new HidlServiceRegistrationWaiter()),
Brian Stacka24e7d42019-01-08 12:56:09 -080098 mEventQueueFlag(nullptr),
99 mWakeLockQueueFlag(nullptr),
Brian Stack156da082018-10-01 15:58:53 -0700100 mReconnecting(false) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700101 if (!connectHidlService()) {
102 return;
103 }
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700104
Brian Stack156da082018-10-01 15:58:53 -0700105 initializeSensorList();
106
107 mIsDirectReportSupported =
108 (checkReturn(mSensors->unregisterDirectChannel(-1)) != Result::INVALID_OPERATION);
109}
110
111void SensorDevice::initializeSensorList() {
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700112 float minPowerMa = 0.001; // 1 microAmp
113
Peng Xua8fad9b2017-03-17 12:20:27 -0700114 checkReturn(mSensors->getSensorsList(
115 [&](const auto &list) {
116 const size_t count = list.size();
117
118 mActivationCount.setCapacity(count);
119 Info model;
120 for (size_t i=0 ; i < count; i++) {
121 sensor_t sensor;
122 convertToSensor(list[i], &sensor);
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700123 // Sanity check and clamp power if it is 0 (or close)
124 if (sensor.power < minPowerMa) {
125 ALOGE("Reported power %f not deemed sane, clamping to %f",
126 sensor.power, minPowerMa);
127 sensor.power = minPowerMa;
128 }
Peng Xua8fad9b2017-03-17 12:20:27 -0700129 mSensorList.push_back(sensor);
130
131 mActivationCount.add(list[i].sensorHandle, model);
132
133 checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
134 }
135 }));
Peng Xua8fad9b2017-03-17 12:20:27 -0700136}
137
Brian Stacka28e9212018-09-19 15:20:30 -0700138SensorDevice::~SensorDevice() {
139 if (mEventQueueFlag != nullptr) {
140 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
141 mEventQueueFlag = nullptr;
142 }
Brian Stacka24e7d42019-01-08 12:56:09 -0800143
144 if (mWakeLockQueueFlag != nullptr) {
145 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
146 mWakeLockQueueFlag = nullptr;
147 }
Brian Stacka28e9212018-09-19 15:20:30 -0700148}
149
Peng Xua8fad9b2017-03-17 12:20:27 -0700150bool SensorDevice::connectHidlService() {
Brian Stack979887b2018-09-19 15:27:48 -0700151 HalConnectionStatus status = connectHidlServiceV2_0();
152 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
153 status = connectHidlServiceV1_0();
Brian Stack12f4d322018-09-14 16:18:59 -0700154 }
Brian Stack979887b2018-09-19 15:27:48 -0700155 return (status == HalConnectionStatus::CONNECTED);
Brian Stack12f4d322018-09-14 16:18:59 -0700156}
157
Brian Stack979887b2018-09-19 15:27:48 -0700158SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700159 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
Peng Xu3889e6e2017-03-02 19:10:38 -0800160 size_t retry = 10;
Brian Stack979887b2018-09-19 15:27:48 -0700161 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Steven Morelandd15c0302016-12-20 11:14:50 -0800162
Peng Xu1a00e2d2017-09-27 23:08:30 -0700163 while (retry-- > 0) {
Brian Stack12f4d322018-09-14 16:18:59 -0700164 sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
165 if (sensors == nullptr) {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700166 // no sensor hidl service found
Brian Stack979887b2018-09-19 15:27:48 -0700167 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
Peng Xua8fad9b2017-03-17 12:20:27 -0700168 break;
Peng Xu3889e6e2017-03-02 19:10:38 -0800169 }
Peng Xu1a00e2d2017-09-27 23:08:30 -0700170
Brian Stack12f4d322018-09-14 16:18:59 -0700171 mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors);
Peng Xu1a00e2d2017-09-27 23:08:30 -0700172 mRestartWaiter->reset();
173 // Poke ISensor service. If it has lingering connection from previous generation of
174 // system server, it will kill itself. There is no intention to handle the poll result,
175 // which will be done since the size is 0.
176 if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
177 // ok to continue
Brian Stack979887b2018-09-19 15:27:48 -0700178 connectionStatus = HalConnectionStatus::CONNECTED;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700179 break;
180 }
181
182 // hidl service is restarting, pointer is invalid.
183 mSensors = nullptr;
Brian Stack979887b2018-09-19 15:27:48 -0700184 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700185 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
186 mRestartWaiter->wait();
Steven Morelandd15c0302016-12-20 11:14:50 -0800187 }
Brian Stack979887b2018-09-19 15:27:48 -0700188
189 return connectionStatus;
Steven Morelandd15c0302016-12-20 11:14:50 -0800190}
191
Brian Stack979887b2018-09-19 15:27:48 -0700192SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
193 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Brian Stack12f4d322018-09-14 16:18:59 -0700194 sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
Brian Stack979887b2018-09-19 15:27:48 -0700195
196 if (sensors == nullptr) {
197 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
198 } else {
Brian Stack12f4d322018-09-14 16:18:59 -0700199 mSensors = new SensorServiceUtil::SensorsWrapperV2_0(sensors);
200
Brian Stack979887b2018-09-19 15:27:48 -0700201 mEventQueue = std::make_unique<EventMessageQueue>(
202 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
203 true /* configureEventFlagWord */);
204
205 mWakeLockQueue = std::make_unique<WakeLockQueue>(
206 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
207 true /* configureEventFlagWord */);
208
Brian Stacka24e7d42019-01-08 12:56:09 -0800209 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
Brian Stacka28e9212018-09-19 15:20:30 -0700210 hardware::EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
211
Brian Stacka24e7d42019-01-08 12:56:09 -0800212 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
213 hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(),
214 &mWakeLockQueueFlag);
215
Brian Stack979887b2018-09-19 15:27:48 -0700216 CHECK(mSensors != nullptr && mEventQueue != nullptr &&
Brian Stacka24e7d42019-01-08 12:56:09 -0800217 mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
218 mWakeLockQueueFlag != nullptr);
Brian Stack979887b2018-09-19 15:27:48 -0700219
Brian Stack6c49e6f2018-09-24 15:44:32 -0700220 status_t status = StatusFromResult(checkReturn(mSensors->initialize(
Brian Stack979887b2018-09-19 15:27:48 -0700221 *mEventQueue->getDesc(),
Brian Stack6c49e6f2018-09-24 15:44:32 -0700222 *mWakeLockQueue->getDesc(),
Brian Stackbbab1ea2018-10-01 10:49:07 -0700223 new SensorsCallback())));
Brian Stack979887b2018-09-19 15:27:48 -0700224
225 if (status != NO_ERROR) {
226 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Brian Stack6c49e6f2018-09-24 15:44:32 -0700227 ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
Brian Stack979887b2018-09-19 15:27:48 -0700228 } else {
229 connectionStatus = HalConnectionStatus::CONNECTED;
Brian Stack574cda32018-10-01 11:18:51 -0700230 mSensorsHalDeathReceiver = new SensorsHalDeathReceivier();
231 sensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
Brian Stack979887b2018-09-19 15:27:48 -0700232 }
Brian Stack12f4d322018-09-14 16:18:59 -0700233 }
Brian Stack979887b2018-09-19 15:27:48 -0700234
235 return connectionStatus;
Brian Stack12f4d322018-09-14 16:18:59 -0700236}
237
Brian Stack156da082018-10-01 15:58:53 -0700238void SensorDevice::prepareForReconnect() {
239 mReconnecting = true;
240
241 // Wake up the polling thread so it returns and allows the SensorService to initiate
242 // a reconnect.
243 mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
244}
245
246void SensorDevice::reconnect() {
247 Mutex::Autolock _l(mLock);
248 mSensors = nullptr;
249
250 auto previousActivations = mActivationCount;
251 auto previousSensorList = mSensorList;
252
253 mActivationCount.clear();
254 mSensorList.clear();
255
256 if (connectHidlServiceV2_0() == HalConnectionStatus::CONNECTED) {
257 initializeSensorList();
258
259 if (sensorHandlesChanged(previousSensorList, mSensorList)) {
260 LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
261 } else {
262 reactivateSensors(previousActivations);
263 }
264 }
265 mReconnecting = false;
266}
267
268bool SensorDevice::sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
269 const Vector<sensor_t>& newSensorList) {
270 bool didChange = false;
271
272 if (oldSensorList.size() != newSensorList.size()) {
273 didChange = true;
274 }
275
276 for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
277 bool found = false;
278 const sensor_t& newSensor = newSensorList[i];
279 for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
280 const sensor_t& prevSensor = oldSensorList[j];
281 if (prevSensor.handle == newSensor.handle) {
282 found = true;
283 if (!sensorIsEquivalent(prevSensor, newSensor)) {
284 didChange = true;
285 }
286 }
287 }
288
289 if (!found) {
290 // Could not find the new sensor in the old list of sensors, the lists must
291 // have changed.
292 didChange = true;
293 }
294 }
295 return didChange;
296}
297
298bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
299 bool equivalent = true;
300 if (prevSensor.handle != newSensor.handle ||
301 (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
302 (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
303 (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
304 (prevSensor.version != newSensor.version) ||
305 (prevSensor.type != newSensor.type) ||
306 (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
307 (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
308 (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
309 (prevSensor.minDelay != newSensor.minDelay) ||
310 (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
311 (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
312 (prevSensor.maxDelay != newSensor.maxDelay) ||
313 (prevSensor.flags != newSensor.flags)) {
314 equivalent = false;
315 }
316 return equivalent;
317}
318
319void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
320 for (size_t i = 0; i < mSensorList.size(); i++) {
321 int handle = mSensorList[i].handle;
322 ssize_t activationIndex = previousActivations.indexOfKey(handle);
323 if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
324 continue;
325 }
326
327 const Info& info = previousActivations[activationIndex];
328 for (size_t j = 0; j < info.batchParams.size(); j++) {
329 const BatchParams& batchParams = info.batchParams[j];
330 status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
331 batchParams.mTSample, batchParams.mTBatch);
332
333 if (res == NO_ERROR) {
334 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
335 }
336 }
337 }
338}
339
Peng Xu2576cb62016-01-20 00:22:09 -0800340void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700341 // not need to check mSensors because this is is only called after successful poll()
Peng Xu2576cb62016-01-20 00:22:09 -0800342 if (connected) {
343 Info model;
344 mActivationCount.add(handle, model);
Peng Xu3889e6e2017-03-02 19:10:38 -0800345 checkReturn(mSensors->activate(handle, 0 /* enabled */));
Peng Xu2576cb62016-01-20 00:22:09 -0800346 } else {
347 mActivationCount.removeItem(handle);
348 }
349}
350
Peng Xu6a2d3a02015-12-21 12:00:23 -0800351std::string SensorDevice::dump() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700352 if (mSensors == nullptr) return "HAL not initialized\n";
Mathias Agopianf001c922010-11-11 17:58:51 -0800353
Peng Xu6a2d3a02015-12-21 12:00:23 -0800354 String8 result;
Peng Xua8fad9b2017-03-17 12:20:27 -0700355 result.appendFormat("Total %zu h/w sensors, %zu running:\n",
356 mSensorList.size(), mActivationCount.size());
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700357
Peng Xua8fad9b2017-03-17 12:20:27 -0700358 Mutex::Autolock _l(mLock);
359 for (const auto & s : mSensorList) {
360 int32_t handle = s.handle;
361 const Info& info = mActivationCount.valueFor(handle);
Brian Stackbce04d72019-03-21 10:54:10 -0700362 if (info.numActiveClients() == 0) continue;
Peng Xua8fad9b2017-03-17 12:20:27 -0700363
364 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
365
366 result.append("sampling_period(ms) = {");
367 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700368 const BatchParams& params = info.batchParams[j];
369 result.appendFormat("%.1f%s", params.mTSample / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700370 j < info.batchParams.size() - 1 ? ", " : "");
371 }
Peng Xu2bec6232016-07-01 17:13:10 -0700372 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
Peng Xua8fad9b2017-03-17 12:20:27 -0700373
374 result.append("batching_period(ms) = {");
375 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700376 const BatchParams& params = info.batchParams[j];
377 result.appendFormat("%.1f%s", params.mTBatch / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700378 j < info.batchParams.size() - 1 ? ", " : "");
379 }
Peng Xu2bec6232016-07-01 17:13:10 -0700380 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700381 }
382
Peng Xu6a2d3a02015-12-21 12:00:23 -0800383 return result.string();
Mathias Agopianf001c922010-11-11 17:58:51 -0800384}
385
386ssize_t SensorDevice::getSensorList(sensor_t const** list) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800387 *list = &mSensorList[0];
388
389 return mSensorList.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800390}
391
392status_t SensorDevice::initCheck() const {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700393 return mSensors != nullptr ? NO_ERROR : NO_INIT;
Mathias Agopianf001c922010-11-11 17:58:51 -0800394}
395
396ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
Brian Stack156da082018-10-01 15:58:53 -0700397 if (mSensors == nullptr) return NO_INIT;
398
Brian Stacka28e9212018-09-19 15:20:30 -0700399 ssize_t eventsRead = 0;
400 if (mSensors->supportsMessageQueues()) {
401 eventsRead = pollFmq(buffer, count);
402 } else if (mSensors->supportsPolling()) {
403 eventsRead = pollHal(buffer, count);
404 } else {
405 ALOGE("Must support polling or FMQ");
406 eventsRead = -1;
407 }
408 return eventsRead;
409}
410
411ssize_t SensorDevice::pollHal(sensors_event_t* buffer, size_t count) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800412 ssize_t err;
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700413 int numHidlTransportErrors = 0;
414 bool hidlTransportError = false;
Steven Morelandd15c0302016-12-20 11:14:50 -0800415
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700416 do {
417 auto ret = mSensors->poll(
418 count,
419 [&](auto result,
420 const auto &events,
421 const auto &dynamicSensorsAdded) {
422 if (result == Result::OK) {
423 convertToSensorEvents(events, dynamicSensorsAdded, buffer);
424 err = (ssize_t)events.size();
425 } else {
426 err = StatusFromResult(result);
427 }
428 });
429
430 if (ret.isOk()) {
431 hidlTransportError = false;
432 } else {
433 hidlTransportError = true;
434 numHidlTransportErrors++;
435 if (numHidlTransportErrors > 50) {
436 // Log error and bail
437 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
438 handleHidlDeath(ret.description());
439 } else {
440 std::this_thread::sleep_for(std::chrono::milliseconds(10));
441 }
442 }
443 } while (hidlTransportError);
444
445 if(numHidlTransportErrors > 0) {
446 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
Yi Kong8f313e32018-07-17 14:13:29 -0700447 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700448 mHidlTransportErrors.add(errLog);
449 mTotalHidlTransportErrors++;
450 }
Steven Morelandd15c0302016-12-20 11:14:50 -0800451
452 return err;
Mathias Agopianf001c922010-11-11 17:58:51 -0800453}
454
Brian Stacka28e9212018-09-19 15:20:30 -0700455ssize_t SensorDevice::pollFmq(sensors_event_t* buffer, size_t maxNumEventsToRead) {
Brian Stacka28e9212018-09-19 15:20:30 -0700456 ssize_t eventsRead = 0;
457 size_t availableEvents = mEventQueue->availableToRead();
458
459 if (availableEvents == 0) {
460 uint32_t eventFlagState = 0;
461
462 // Wait for events to become available. This is necessary so that the Event FMQ's read() is
463 // able to be called with the correct number of events to read. If the specified number of
464 // events is not available, then read() would return no events, possibly introducing
465 // additional latency in delivering events to applications.
Brian Stack156da082018-10-01 15:58:53 -0700466 mEventQueueFlag->wait(asBaseType(EventQueueFlagBits::READ_AND_PROCESS) |
467 asBaseType(INTERNAL_WAKE), &eventFlagState);
Brian Stacka28e9212018-09-19 15:20:30 -0700468 availableEvents = mEventQueue->availableToRead();
469
Brian Stack156da082018-10-01 15:58:53 -0700470 if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
471 ALOGD("Event FMQ internal wake, returning from poll with no events");
472 return DEAD_OBJECT;
473 }
Brian Stacka28e9212018-09-19 15:20:30 -0700474 }
475
476 size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
477 if (eventsToRead > 0) {
478 if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
Brian Stackaf1b54c2018-11-09 10:20:01 -0800479 // Notify the Sensors HAL that sensor events have been read. This is required to support
480 // the use of writeBlocking by the Sensors HAL.
481 mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
482
Brian Stacka28e9212018-09-19 15:20:30 -0700483 for (size_t i = 0; i < eventsToRead; i++) {
484 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
485 }
486 eventsRead = eventsToRead;
487 } else {
488 ALOGW("Failed to read %zu events, currently %zu events available",
489 eventsToRead, availableEvents);
490 }
491 }
492
493 return eventsRead;
494}
495
Brian Stack6c49e6f2018-09-24 15:44:32 -0700496Return<void> SensorDevice::onDynamicSensorsConnected(
497 const hidl_vec<SensorInfo> &dynamicSensorsAdded) {
498 // Allocate a sensor_t structure for each dynamic sensor added and insert
499 // it into the dictionary of connected dynamic sensors keyed by handle.
500 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
501 const SensorInfo &info = dynamicSensorsAdded[i];
502
503 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
504 CHECK(it == mConnectedDynamicSensors.end());
505
506 sensor_t *sensor = new sensor_t();
507 convertToSensor(info, sensor);
508
509 mConnectedDynamicSensors.insert(
510 std::make_pair(sensor->handle, sensor));
511 }
512
513 return Return<void>();
514}
515
516Return<void> SensorDevice::onDynamicSensorsDisconnected(
517 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) {
518 (void) dynamicSensorHandlesRemoved;
519 // TODO: Currently dynamic sensors do not seem to be removed
520 return Return<void>();
521}
522
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700523void SensorDevice::writeWakeLockHandled(uint32_t count) {
Brian Stacka24e7d42019-01-08 12:56:09 -0800524 if (mSensors != nullptr && mSensors->supportsMessageQueues()) {
525 if (mWakeLockQueue->write(&count)) {
526 mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
527 } else {
528 ALOGW("Failed to write wake lock handled");
529 }
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700530 }
531}
532
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700533void SensorDevice::autoDisable(void *ident, int handle) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700534 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700535 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
536 if (activationIndex < 0) {
537 ALOGW("Handle %d cannot be found in activation record", handle);
538 return;
539 }
540 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700541 info.removeBatchParamsForIdent(ident);
Brian Stackaa6dc092019-05-10 13:36:40 -0700542 if (info.numActiveClients() == 0) {
543 info.isActive = false;
544 }
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700545}
546
Peng Xu6a2d3a02015-12-21 12:00:23 -0800547status_t SensorDevice::activate(void* ident, int handle, int enabled) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700548 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800549
Brian Stack156da082018-10-01 15:58:53 -0700550 Mutex::Autolock _l(mLock);
551 return activateLocked(ident, handle, enabled);
552}
553
554status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800555 bool actuateHardware = false;
556
Brian Stack156da082018-10-01 15:58:53 -0700557 status_t err(NO_ERROR);
558
Peng Xu042baec2017-08-09 19:28:27 -0700559 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
560 if (activationIndex < 0) {
561 ALOGW("Handle %d cannot be found in activation record", handle);
562 return BAD_VALUE;
563 }
564 Info& info(mActivationCount.editValueAt(activationIndex));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700565
Steve Blocka5512372011-12-20 16:23:08 +0000566 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700567 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
Aravind Akella724d91d2013-06-27 12:04:23 -0700568 ident, handle, enabled, info.batchParams.size());
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700569
Mathias Agopianf001c922010-11-11 17:58:51 -0800570 if (enabled) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700571 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700572
Aravind Akella4949c502015-02-11 15:54:35 -0800573 if (isClientDisabledLocked(ident)) {
Peng Xu966fa882016-09-01 16:13:15 -0700574 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
575 ident, handle);
Aravind Akella4949c502015-02-11 15:54:35 -0800576 return INVALID_OPERATION;
577 }
578
Aravind Akella724d91d2013-06-27 12:04:23 -0700579 if (info.batchParams.indexOfKey(ident) >= 0) {
Brian Stack0c305fe2019-04-09 12:49:24 -0700580 if (info.numActiveClients() > 0 && !info.isActive) {
581 actuateHardware = true;
582 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800583 } else {
Aravind Akella724d91d2013-06-27 12:04:23 -0700584 // Log error. Every activate call should be preceded by a batch() call.
585 ALOGE("\t >>>ERROR: activate called without batch");
Mathias Agopianf001c922010-11-11 17:58:51 -0800586 }
587 } else {
Mark Salyzyndb458612014-06-10 14:50:02 -0700588 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700589
Steven Morelandd15c0302016-12-20 11:14:50 -0800590 // If a connected dynamic sensor is deactivated, remove it from the
591 // dictionary.
592 auto it = mConnectedDynamicSensors.find(handle);
593 if (it != mConnectedDynamicSensors.end()) {
594 delete it->second;
595 mConnectedDynamicSensors.erase(it);
596 }
597
Aravind Akella724d91d2013-06-27 12:04:23 -0700598 if (info.removeBatchParamsForIdent(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800599 if (info.numActiveClients() == 0) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700600 // This is the last connection, we need to de-activate the underlying h/w sensor.
Mathias Agopian50b66762010-11-29 17:26:51 -0800601 actuateHardware = true;
Aravind Akella724d91d2013-06-27 12:04:23 -0700602 } else {
Steven Morelandd15c0302016-12-20 11:14:50 -0800603 // Call batch for this sensor with the previously calculated best effort
604 // batch_rate and timeout. One of the apps has unregistered for sensor
605 // events, and the best effort batch parameters might have changed.
606 ALOGD_IF(DEBUG_CONNECTIONS,
Peng Xu2bec6232016-07-01 17:13:10 -0700607 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
608 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Peng Xu3889e6e2017-03-02 19:10:38 -0800609 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700610 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Mathias Agopian50b66762010-11-29 17:26:51 -0800611 }
612 } else {
613 // sensor wasn't enabled for this ident
614 }
Aravind Akella4949c502015-02-11 15:54:35 -0800615
616 if (isClientDisabledLocked(ident)) {
617 return NO_ERROR;
618 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800619 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800620
Mathias Agopianf001c922010-11-11 17:58:51 -0800621 if (actuateHardware) {
Aravind Akella4949c502015-02-11 15:54:35 -0800622 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
623 enabled);
Peng Xu3889e6e2017-03-02 19:10:38 -0800624 err = StatusFromResult(checkReturn(mSensors->activate(handle, enabled)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700625 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
626 strerror(-err));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700627
Aravind Akella724d91d2013-06-27 12:04:23 -0700628 if (err != NO_ERROR && enabled) {
629 // Failure when enabling the sensor. Clean up on failure.
630 info.removeBatchParamsForIdent(ident);
Brian Stack0c305fe2019-04-09 12:49:24 -0700631 } else {
632 // Update the isActive flag if there is no error. If there is an error when disabling a
633 // sensor, still set the flag to false since the batch parameters have already been
634 // removed. This ensures that everything remains in-sync.
635 info.isActive = enabled;
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700636 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800637 }
638
Mathias Agopianf001c922010-11-11 17:58:51 -0800639 return err;
640}
641
Steven Morelandd15c0302016-12-20 11:14:50 -0800642status_t SensorDevice::batch(
643 void* ident,
644 int handle,
645 int flags,
646 int64_t samplingPeriodNs,
647 int64_t maxBatchReportLatencyNs) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700648 if (mSensors == nullptr) return NO_INIT;
Aravind Akella724d91d2013-06-27 12:04:23 -0700649
650 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
651 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
652 }
Peng Xu2bec6232016-07-01 17:13:10 -0700653 if (maxBatchReportLatencyNs < 0) {
654 maxBatchReportLatencyNs = 0;
655 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700656
Aravind Akella724d91d2013-06-27 12:04:23 -0700657 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700658 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700659 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
660
661 Mutex::Autolock _l(mLock);
Brian Stack156da082018-10-01 15:58:53 -0700662 return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
663}
664
665status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
666 int64_t maxBatchReportLatencyNs) {
Peng Xu042baec2017-08-09 19:28:27 -0700667 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
668 if (activationIndex < 0) {
669 ALOGW("Handle %d cannot be found in activation record", handle);
670 return BAD_VALUE;
671 }
672 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700673
674 if (info.batchParams.indexOfKey(ident) < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700675 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
Aravind Akella724d91d2013-06-27 12:04:23 -0700676 info.batchParams.add(ident, params);
677 } else {
678 // A batch has already been called with this ident. Update the batch parameters.
679 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
680 }
681
682 BatchParams prevBestBatchParams = info.bestBatchParams;
683 // Find the minimum of all timeouts and batch_rates for this sensor.
684 info.selectBatchParams();
685
686 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700687 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
688 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
Peng Xu2bec6232016-07-01 17:13:10 -0700689 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
690 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
Aravind Akella724d91d2013-06-27 12:04:23 -0700691
692 status_t err(NO_ERROR);
693 // If the min period or min timeout has changed since the last batch call, call batch.
694 if (prevBestBatchParams != info.bestBatchParams) {
Peng Xu2bec6232016-07-01 17:13:10 -0700695 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
696 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Steven Morelandd15c0302016-12-20 11:14:50 -0800697 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800698 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700699 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700700 if (err != NO_ERROR) {
Peng Xu2bec6232016-07-01 17:13:10 -0700701 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
702 mSensors.get(), handle, info.bestBatchParams.mTSample,
703 info.bestBatchParams.mTBatch, strerror(-err));
Aravind Akella724d91d2013-06-27 12:04:23 -0700704 info.removeBatchParamsForIdent(ident);
705 }
706 }
707 return err;
708}
709
Peng Xu6a2d3a02015-12-21 12:00:23 -0800710status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
Peng Xu2bec6232016-07-01 17:13:10 -0700711 return batch(ident, handle, 0, samplingPeriodNs, 0);
Mathias Agopian667102f2011-09-14 16:43:34 -0700712}
713
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700714int SensorDevice::getHalDeviceVersion() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700715 if (mSensors == nullptr) return -1;
Steven Morelandd15c0302016-12-20 11:14:50 -0800716 return SENSORS_DEVICE_API_VERSION_1_4;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700717}
718
Aravind Akella9a844cf2014-02-11 18:58:52 -0800719status_t SensorDevice::flush(void* ident, int handle) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700720 if (mSensors == nullptr) return NO_INIT;
Aravind Akella4949c502015-02-11 15:54:35 -0800721 if (isClientDisabled(ident)) return INVALID_OPERATION;
Aravind Akella724d91d2013-06-27 12:04:23 -0700722 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800723 return StatusFromResult(checkReturn(mSensors->flush(handle)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700724}
725
Aravind Akella4949c502015-02-11 15:54:35 -0800726bool SensorDevice::isClientDisabled(void* ident) {
727 Mutex::Autolock _l(mLock);
728 return isClientDisabledLocked(ident);
729}
730
731bool SensorDevice::isClientDisabledLocked(void* ident) {
732 return mDisabledClients.indexOf(ident) >= 0;
733}
734
Brian Stackbce04d72019-03-21 10:54:10 -0700735bool SensorDevice::isSensorActive(int handle) const {
736 Mutex::Autolock _l(mLock);
737 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
738 if (activationIndex < 0) {
739 return false;
740 }
741 return mActivationCount.valueAt(activationIndex).numActiveClients() > 0;
742}
743
Aravind Akella4949c502015-02-11 15:54:35 -0800744void SensorDevice::enableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700745 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800746 Mutex::Autolock _l(mLock);
747 mDisabledClients.clear();
Peng Xu966fa882016-09-01 16:13:15 -0700748 ALOGI("cleared mDisabledClients");
Aravind Akella4949c502015-02-11 15:54:35 -0800749 for (size_t i = 0; i< mActivationCount.size(); ++i) {
750 Info& info = mActivationCount.editValueAt(i);
751 if (info.batchParams.isEmpty()) continue;
752 info.selectBatchParams();
753 const int sensor_handle = mActivationCount.keyAt(i);
754 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
755 sensor_handle);
Steven Morelandd15c0302016-12-20 11:14:50 -0800756 status_t err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800757 checkReturn(mSensors->batch(
Steven Morelandd15c0302016-12-20 11:14:50 -0800758 sensor_handle,
Peng Xu2bec6232016-07-01 17:13:10 -0700759 info.bestBatchParams.mTSample,
760 info.bestBatchParams.mTBatch)));
Steven Morelandd15c0302016-12-20 11:14:50 -0800761 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
Aravind Akella4949c502015-02-11 15:54:35 -0800762
763 if (err == NO_ERROR) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800764 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800765 checkReturn(mSensors->activate(sensor_handle, 1 /* enabled */)));
Aravind Akella4949c502015-02-11 15:54:35 -0800766 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
767 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700768
769 if (err == NO_ERROR) {
770 info.isActive = true;
771 }
Aravind Akella4949c502015-02-11 15:54:35 -0800772 }
773}
774
775void SensorDevice::disableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700776 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800777 Mutex::Autolock _l(mLock);
Peng Xua8fad9b2017-03-17 12:20:27 -0700778 for (size_t i = 0; i< mActivationCount.size(); ++i) {
Brian Stack4a11fed2019-04-22 15:07:50 -0700779 Info& info = mActivationCount.editValueAt(i);
Aravind Akella4949c502015-02-11 15:54:35 -0800780 // Check if this sensor has been activated previously and disable it.
781 if (info.batchParams.size() > 0) {
782 const int sensor_handle = mActivationCount.keyAt(i);
783 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
784 sensor_handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800785 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
Steven Morelandd15c0302016-12-20 11:14:50 -0800786
Aravind Akella4949c502015-02-11 15:54:35 -0800787 // Add all the connections that were registered for this sensor to the disabled
788 // clients list.
Svetoslavb412f6e2015-04-29 16:50:41 -0700789 for (size_t j = 0; j < info.batchParams.size(); ++j) {
Aravind Akella4949c502015-02-11 15:54:35 -0800790 mDisabledClients.add(info.batchParams.keyAt(j));
Peng Xu966fa882016-09-01 16:13:15 -0700791 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
Aravind Akella4949c502015-02-11 15:54:35 -0800792 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700793
794 info.isActive = false;
Aravind Akella4949c502015-02-11 15:54:35 -0800795 }
796 }
797}
798
Steven Morelandd15c0302016-12-20 11:14:50 -0800799status_t SensorDevice::injectSensorData(
800 const sensors_event_t *injected_sensor_event) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700801 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800802 ALOGD_IF(DEBUG_CONNECTIONS,
803 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
804 injected_sensor_event->sensor,
805 injected_sensor_event->timestamp, injected_sensor_event->data[0],
806 injected_sensor_event->data[1], injected_sensor_event->data[2],
807 injected_sensor_event->data[3], injected_sensor_event->data[4],
808 injected_sensor_event->data[5]);
809
810 Event ev;
811 convertFromSensorEvent(*injected_sensor_event, &ev);
812
Peng Xu3889e6e2017-03-02 19:10:38 -0800813 return StatusFromResult(checkReturn(mSensors->injectSensorData(ev)));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700814}
815
816status_t SensorDevice::setMode(uint32_t mode) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700817 if (mSensors == nullptr) return NO_INIT;
818 return StatusFromResult(
819 checkReturn(mSensors->setOperationMode(
820 static_cast<hardware::sensors::V1_0::OperationMode>(mode))));
821}
Steven Morelandd15c0302016-12-20 11:14:50 -0800822
Peng Xua8fad9b2017-03-17 12:20:27 -0700823int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
824 if (mSensors == nullptr) return NO_INIT;
825 Mutex::Autolock _l(mLock);
826
827 SharedMemType type;
828 switch (memory->type) {
829 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
830 type = SharedMemType::ASHMEM;
831 break;
832 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
833 type = SharedMemType::GRALLOC;
834 break;
835 default:
836 return BAD_VALUE;
837 }
838
839 SharedMemFormat format;
840 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
841 return BAD_VALUE;
842 }
843 format = SharedMemFormat::SENSORS_EVENT;
844
845 SharedMemInfo mem = {
846 .type = type,
847 .format = format,
848 .size = static_cast<uint32_t>(memory->size),
849 .memoryHandle = memory->handle,
850 };
851
852 int32_t ret;
853 checkReturn(mSensors->registerDirectChannel(mem,
854 [&ret](auto result, auto channelHandle) {
855 if (result == Result::OK) {
856 ret = channelHandle;
857 } else {
858 ret = StatusFromResult(result);
859 }
860 }));
861 return ret;
862}
863
864void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
865 if (mSensors == nullptr) return;
866 Mutex::Autolock _l(mLock);
867 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
868}
869
870int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
871 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
872 if (mSensors == nullptr) return NO_INIT;
873 Mutex::Autolock _l(mLock);
874
875 RateLevel rate;
876 switch(config->rate_level) {
877 case SENSOR_DIRECT_RATE_STOP:
878 rate = RateLevel::STOP;
879 break;
880 case SENSOR_DIRECT_RATE_NORMAL:
881 rate = RateLevel::NORMAL;
882 break;
883 case SENSOR_DIRECT_RATE_FAST:
884 rate = RateLevel::FAST;
885 break;
886 case SENSOR_DIRECT_RATE_VERY_FAST:
887 rate = RateLevel::VERY_FAST;
888 break;
889 default:
890 return BAD_VALUE;
891 }
892
893 int32_t ret;
894 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
895 [&ret, rate] (auto result, auto token) {
896 if (rate == RateLevel::STOP) {
897 ret = StatusFromResult(result);
898 } else {
899 if (result == Result::OK) {
900 ret = token;
901 } else {
902 ret = StatusFromResult(result);
903 }
904 }
905 }));
906
907 return ret;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700908}
909
Mathias Agopian667102f2011-09-14 16:43:34 -0700910// ---------------------------------------------------------------------------
911
Brian Stack156da082018-10-01 15:58:53 -0700912int SensorDevice::Info::numActiveClients() const {
Aravind Akella4949c502015-02-11 15:54:35 -0800913 SensorDevice& device(SensorDevice::getInstance());
914 int num = 0;
915 for (size_t i = 0; i < batchParams.size(); ++i) {
916 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
917 ++num;
918 }
919 }
920 return num;
921}
922
Peng Xu2bec6232016-07-01 17:13:10 -0700923status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
Aravind Akella724d91d2013-06-27 12:04:23 -0700924 int64_t samplingPeriodNs,
925 int64_t maxBatchReportLatencyNs) {
926 ssize_t index = batchParams.indexOfKey(ident);
Mathias Agopian667102f2011-09-14 16:43:34 -0700927 if (index < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700928 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
929 " timeout=%" PRId64 ") failed (%s)",
Aravind Akella724d91d2013-06-27 12:04:23 -0700930 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
Mathias Agopian667102f2011-09-14 16:43:34 -0700931 return BAD_INDEX;
932 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700933 BatchParams& params = batchParams.editValueAt(index);
Peng Xu2bec6232016-07-01 17:13:10 -0700934 params.mTSample = samplingPeriodNs;
935 params.mTBatch = maxBatchReportLatencyNs;
Mathias Agopian667102f2011-09-14 16:43:34 -0700936 return NO_ERROR;
937}
938
Aravind Akella724d91d2013-06-27 12:04:23 -0700939void SensorDevice::Info::selectBatchParams() {
Peng Xu2bec6232016-07-01 17:13:10 -0700940 BatchParams bestParams; // default to max Tsample and max Tbatch
Aravind Akella4949c502015-02-11 15:54:35 -0800941 SensorDevice& device(SensorDevice::getInstance());
Aravind Akella724d91d2013-06-27 12:04:23 -0700942
Aravind Akella4949c502015-02-11 15:54:35 -0800943 for (size_t i = 0; i < batchParams.size(); ++i) {
Peng Xu2bec6232016-07-01 17:13:10 -0700944 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
945 continue;
Aravind Akella724d91d2013-06-27 12:04:23 -0700946 }
Peng Xu2bec6232016-07-01 17:13:10 -0700947 bestParams.merge(batchParams[i]);
948 }
949 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
950 if (bestParams.mTBatch <= bestParams.mTSample) {
951 bestParams.mTBatch = 0;
Mathias Agopianf001c922010-11-11 17:58:51 -0800952 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700953 bestBatchParams = bestParams;
954}
955
956ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
957 ssize_t idx = batchParams.removeItem(ident);
958 if (idx >= 0) {
959 selectBatchParams();
960 }
961 return idx;
Mathias Agopianf001c922010-11-11 17:58:51 -0800962}
963
Peng Xu4f707f82016-09-26 11:28:32 -0700964void SensorDevice::notifyConnectionDestroyed(void* ident) {
965 Mutex::Autolock _l(mLock);
966 mDisabledClients.remove(ident);
967}
968
Peng Xu53632542017-01-23 20:06:27 -0800969bool SensorDevice::isDirectReportSupported() const {
Steven Morelandd15c0302016-12-20 11:14:50 -0800970 return mIsDirectReportSupported;
Peng Xu53632542017-01-23 20:06:27 -0800971}
Steven Morelandd15c0302016-12-20 11:14:50 -0800972
973void SensorDevice::convertToSensorEvent(
974 const Event &src, sensors_event_t *dst) {
975 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
976 src, dst);
977
978 if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
979 const DynamicSensorInfo &dyn = src.u.dynamic;
980
981 dst->dynamic_sensor_meta.connected = dyn.connected;
982 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
983 if (dyn.connected) {
984 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
985 CHECK(it != mConnectedDynamicSensors.end());
986
987 dst->dynamic_sensor_meta.sensor = it->second;
988
989 memcpy(dst->dynamic_sensor_meta.uuid,
990 dyn.uuid.data(),
991 sizeof(dst->dynamic_sensor_meta.uuid));
992 }
993 }
994}
995
996void SensorDevice::convertToSensorEvents(
997 const hidl_vec<Event> &src,
998 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
999 sensors_event_t *dst) {
Steven Morelandd15c0302016-12-20 11:14:50 -08001000
Brian Stack6c49e6f2018-09-24 15:44:32 -07001001 if (dynamicSensorsAdded.size() > 0) {
1002 onDynamicSensorsConnected(dynamicSensorsAdded);
Steven Morelandd15c0302016-12-20 11:14:50 -08001003 }
1004
1005 for (size_t i = 0; i < src.size(); ++i) {
1006 convertToSensorEvent(src[i], &dst[i]);
1007 }
1008}
1009
Peng Xu3889e6e2017-03-02 19:10:38 -08001010void SensorDevice::handleHidlDeath(const std::string & detail) {
Brian Stack156da082018-10-01 15:58:53 -07001011 if (!SensorDevice::getInstance().mSensors->supportsMessageQueues()) {
1012 // restart is the only option at present.
1013 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
1014 } else {
1015 ALOGD("ISensors HAL died, death recipient will attempt reconnect");
1016 }
Peng Xu3889e6e2017-03-02 19:10:38 -08001017}
1018
Mathias Agopianf001c922010-11-11 17:58:51 -08001019// ---------------------------------------------------------------------------
1020}; // namespace android