blob: be75c6426adf186a2652af444614ebad767f69fb [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);
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700542}
543
Peng Xu6a2d3a02015-12-21 12:00:23 -0800544status_t SensorDevice::activate(void* ident, int handle, int enabled) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700545 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800546
Brian Stack156da082018-10-01 15:58:53 -0700547 Mutex::Autolock _l(mLock);
548 return activateLocked(ident, handle, enabled);
549}
550
551status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800552 bool actuateHardware = false;
553
Brian Stack156da082018-10-01 15:58:53 -0700554 status_t err(NO_ERROR);
555
Peng Xu042baec2017-08-09 19:28:27 -0700556 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
557 if (activationIndex < 0) {
558 ALOGW("Handle %d cannot be found in activation record", handle);
559 return BAD_VALUE;
560 }
561 Info& info(mActivationCount.editValueAt(activationIndex));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700562
Steve Blocka5512372011-12-20 16:23:08 +0000563 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700564 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
Aravind Akella724d91d2013-06-27 12:04:23 -0700565 ident, handle, enabled, info.batchParams.size());
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700566
Mathias Agopianf001c922010-11-11 17:58:51 -0800567 if (enabled) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700568 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700569
Aravind Akella4949c502015-02-11 15:54:35 -0800570 if (isClientDisabledLocked(ident)) {
Peng Xu966fa882016-09-01 16:13:15 -0700571 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
572 ident, handle);
Aravind Akella4949c502015-02-11 15:54:35 -0800573 return INVALID_OPERATION;
574 }
575
Aravind Akella724d91d2013-06-27 12:04:23 -0700576 if (info.batchParams.indexOfKey(ident) >= 0) {
Brian Stack0c305fe2019-04-09 12:49:24 -0700577 if (info.numActiveClients() > 0 && !info.isActive) {
578 actuateHardware = true;
579 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800580 } else {
Aravind Akella724d91d2013-06-27 12:04:23 -0700581 // Log error. Every activate call should be preceded by a batch() call.
582 ALOGE("\t >>>ERROR: activate called without batch");
Mathias Agopianf001c922010-11-11 17:58:51 -0800583 }
584 } else {
Mark Salyzyndb458612014-06-10 14:50:02 -0700585 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700586
Steven Morelandd15c0302016-12-20 11:14:50 -0800587 // If a connected dynamic sensor is deactivated, remove it from the
588 // dictionary.
589 auto it = mConnectedDynamicSensors.find(handle);
590 if (it != mConnectedDynamicSensors.end()) {
591 delete it->second;
592 mConnectedDynamicSensors.erase(it);
593 }
594
Aravind Akella724d91d2013-06-27 12:04:23 -0700595 if (info.removeBatchParamsForIdent(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800596 if (info.numActiveClients() == 0) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700597 // This is the last connection, we need to de-activate the underlying h/w sensor.
Mathias Agopian50b66762010-11-29 17:26:51 -0800598 actuateHardware = true;
Aravind Akella724d91d2013-06-27 12:04:23 -0700599 } else {
Steven Morelandd15c0302016-12-20 11:14:50 -0800600 // Call batch for this sensor with the previously calculated best effort
601 // batch_rate and timeout. One of the apps has unregistered for sensor
602 // events, and the best effort batch parameters might have changed.
603 ALOGD_IF(DEBUG_CONNECTIONS,
Peng Xu2bec6232016-07-01 17:13:10 -0700604 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
605 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Peng Xu3889e6e2017-03-02 19:10:38 -0800606 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700607 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Mathias Agopian50b66762010-11-29 17:26:51 -0800608 }
609 } else {
610 // sensor wasn't enabled for this ident
611 }
Aravind Akella4949c502015-02-11 15:54:35 -0800612
613 if (isClientDisabledLocked(ident)) {
614 return NO_ERROR;
615 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800616 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800617
Mathias Agopianf001c922010-11-11 17:58:51 -0800618 if (actuateHardware) {
Aravind Akella4949c502015-02-11 15:54:35 -0800619 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
620 enabled);
Peng Xu3889e6e2017-03-02 19:10:38 -0800621 err = StatusFromResult(checkReturn(mSensors->activate(handle, enabled)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700622 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
623 strerror(-err));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700624
Aravind Akella724d91d2013-06-27 12:04:23 -0700625 if (err != NO_ERROR && enabled) {
626 // Failure when enabling the sensor. Clean up on failure.
627 info.removeBatchParamsForIdent(ident);
Brian Stack0c305fe2019-04-09 12:49:24 -0700628 } else {
629 // Update the isActive flag if there is no error. If there is an error when disabling a
630 // sensor, still set the flag to false since the batch parameters have already been
631 // removed. This ensures that everything remains in-sync.
632 info.isActive = enabled;
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700633 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800634 }
635
Mathias Agopianf001c922010-11-11 17:58:51 -0800636 return err;
637}
638
Steven Morelandd15c0302016-12-20 11:14:50 -0800639status_t SensorDevice::batch(
640 void* ident,
641 int handle,
642 int flags,
643 int64_t samplingPeriodNs,
644 int64_t maxBatchReportLatencyNs) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700645 if (mSensors == nullptr) return NO_INIT;
Aravind Akella724d91d2013-06-27 12:04:23 -0700646
647 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
648 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
649 }
Peng Xu2bec6232016-07-01 17:13:10 -0700650 if (maxBatchReportLatencyNs < 0) {
651 maxBatchReportLatencyNs = 0;
652 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700653
Aravind Akella724d91d2013-06-27 12:04:23 -0700654 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700655 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700656 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
657
658 Mutex::Autolock _l(mLock);
Brian Stack156da082018-10-01 15:58:53 -0700659 return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
660}
661
662status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
663 int64_t maxBatchReportLatencyNs) {
Peng Xu042baec2017-08-09 19:28:27 -0700664 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
665 if (activationIndex < 0) {
666 ALOGW("Handle %d cannot be found in activation record", handle);
667 return BAD_VALUE;
668 }
669 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700670
671 if (info.batchParams.indexOfKey(ident) < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700672 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
Aravind Akella724d91d2013-06-27 12:04:23 -0700673 info.batchParams.add(ident, params);
674 } else {
675 // A batch has already been called with this ident. Update the batch parameters.
676 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
677 }
678
679 BatchParams prevBestBatchParams = info.bestBatchParams;
680 // Find the minimum of all timeouts and batch_rates for this sensor.
681 info.selectBatchParams();
682
683 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700684 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
685 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
Peng Xu2bec6232016-07-01 17:13:10 -0700686 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
687 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
Aravind Akella724d91d2013-06-27 12:04:23 -0700688
689 status_t err(NO_ERROR);
690 // If the min period or min timeout has changed since the last batch call, call batch.
691 if (prevBestBatchParams != info.bestBatchParams) {
Peng Xu2bec6232016-07-01 17:13:10 -0700692 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
693 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Steven Morelandd15c0302016-12-20 11:14:50 -0800694 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800695 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700696 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700697 if (err != NO_ERROR) {
Peng Xu2bec6232016-07-01 17:13:10 -0700698 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
699 mSensors.get(), handle, info.bestBatchParams.mTSample,
700 info.bestBatchParams.mTBatch, strerror(-err));
Aravind Akella724d91d2013-06-27 12:04:23 -0700701 info.removeBatchParamsForIdent(ident);
702 }
703 }
704 return err;
705}
706
Peng Xu6a2d3a02015-12-21 12:00:23 -0800707status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
Peng Xu2bec6232016-07-01 17:13:10 -0700708 return batch(ident, handle, 0, samplingPeriodNs, 0);
Mathias Agopian667102f2011-09-14 16:43:34 -0700709}
710
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700711int SensorDevice::getHalDeviceVersion() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700712 if (mSensors == nullptr) return -1;
Steven Morelandd15c0302016-12-20 11:14:50 -0800713 return SENSORS_DEVICE_API_VERSION_1_4;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700714}
715
Aravind Akella9a844cf2014-02-11 18:58:52 -0800716status_t SensorDevice::flush(void* ident, int handle) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700717 if (mSensors == nullptr) return NO_INIT;
Aravind Akella4949c502015-02-11 15:54:35 -0800718 if (isClientDisabled(ident)) return INVALID_OPERATION;
Aravind Akella724d91d2013-06-27 12:04:23 -0700719 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800720 return StatusFromResult(checkReturn(mSensors->flush(handle)));
Aravind Akella724d91d2013-06-27 12:04:23 -0700721}
722
Aravind Akella4949c502015-02-11 15:54:35 -0800723bool SensorDevice::isClientDisabled(void* ident) {
724 Mutex::Autolock _l(mLock);
725 return isClientDisabledLocked(ident);
726}
727
728bool SensorDevice::isClientDisabledLocked(void* ident) {
729 return mDisabledClients.indexOf(ident) >= 0;
730}
731
Brian Stackbce04d72019-03-21 10:54:10 -0700732bool SensorDevice::isSensorActive(int handle) const {
733 Mutex::Autolock _l(mLock);
734 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
735 if (activationIndex < 0) {
736 return false;
737 }
738 return mActivationCount.valueAt(activationIndex).numActiveClients() > 0;
739}
740
Aravind Akella4949c502015-02-11 15:54:35 -0800741void SensorDevice::enableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700742 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800743 Mutex::Autolock _l(mLock);
744 mDisabledClients.clear();
Peng Xu966fa882016-09-01 16:13:15 -0700745 ALOGI("cleared mDisabledClients");
Aravind Akella4949c502015-02-11 15:54:35 -0800746 for (size_t i = 0; i< mActivationCount.size(); ++i) {
747 Info& info = mActivationCount.editValueAt(i);
748 if (info.batchParams.isEmpty()) continue;
749 info.selectBatchParams();
750 const int sensor_handle = mActivationCount.keyAt(i);
751 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
752 sensor_handle);
Steven Morelandd15c0302016-12-20 11:14:50 -0800753 status_t err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800754 checkReturn(mSensors->batch(
Steven Morelandd15c0302016-12-20 11:14:50 -0800755 sensor_handle,
Peng Xu2bec6232016-07-01 17:13:10 -0700756 info.bestBatchParams.mTSample,
757 info.bestBatchParams.mTBatch)));
Steven Morelandd15c0302016-12-20 11:14:50 -0800758 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
Aravind Akella4949c502015-02-11 15:54:35 -0800759
760 if (err == NO_ERROR) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800761 err = StatusFromResult(
Peng Xu3889e6e2017-03-02 19:10:38 -0800762 checkReturn(mSensors->activate(sensor_handle, 1 /* enabled */)));
Aravind Akella4949c502015-02-11 15:54:35 -0800763 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
764 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700765
766 if (err == NO_ERROR) {
767 info.isActive = true;
768 }
Aravind Akella4949c502015-02-11 15:54:35 -0800769 }
770}
771
772void SensorDevice::disableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700773 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800774 Mutex::Autolock _l(mLock);
Peng Xua8fad9b2017-03-17 12:20:27 -0700775 for (size_t i = 0; i< mActivationCount.size(); ++i) {
Brian Stack4a11fed2019-04-22 15:07:50 -0700776 Info& info = mActivationCount.editValueAt(i);
Aravind Akella4949c502015-02-11 15:54:35 -0800777 // Check if this sensor has been activated previously and disable it.
778 if (info.batchParams.size() > 0) {
779 const int sensor_handle = mActivationCount.keyAt(i);
780 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
781 sensor_handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800782 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
Steven Morelandd15c0302016-12-20 11:14:50 -0800783
Aravind Akella4949c502015-02-11 15:54:35 -0800784 // Add all the connections that were registered for this sensor to the disabled
785 // clients list.
Svetoslavb412f6e2015-04-29 16:50:41 -0700786 for (size_t j = 0; j < info.batchParams.size(); ++j) {
Aravind Akella4949c502015-02-11 15:54:35 -0800787 mDisabledClients.add(info.batchParams.keyAt(j));
Peng Xu966fa882016-09-01 16:13:15 -0700788 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
Aravind Akella4949c502015-02-11 15:54:35 -0800789 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700790
791 info.isActive = false;
Aravind Akella4949c502015-02-11 15:54:35 -0800792 }
793 }
794}
795
Steven Morelandd15c0302016-12-20 11:14:50 -0800796status_t SensorDevice::injectSensorData(
797 const sensors_event_t *injected_sensor_event) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700798 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800799 ALOGD_IF(DEBUG_CONNECTIONS,
800 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
801 injected_sensor_event->sensor,
802 injected_sensor_event->timestamp, injected_sensor_event->data[0],
803 injected_sensor_event->data[1], injected_sensor_event->data[2],
804 injected_sensor_event->data[3], injected_sensor_event->data[4],
805 injected_sensor_event->data[5]);
806
807 Event ev;
808 convertFromSensorEvent(*injected_sensor_event, &ev);
809
Peng Xu3889e6e2017-03-02 19:10:38 -0800810 return StatusFromResult(checkReturn(mSensors->injectSensorData(ev)));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700811}
812
813status_t SensorDevice::setMode(uint32_t mode) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700814 if (mSensors == nullptr) return NO_INIT;
815 return StatusFromResult(
816 checkReturn(mSensors->setOperationMode(
817 static_cast<hardware::sensors::V1_0::OperationMode>(mode))));
818}
Steven Morelandd15c0302016-12-20 11:14:50 -0800819
Peng Xua8fad9b2017-03-17 12:20:27 -0700820int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
821 if (mSensors == nullptr) return NO_INIT;
822 Mutex::Autolock _l(mLock);
823
824 SharedMemType type;
825 switch (memory->type) {
826 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
827 type = SharedMemType::ASHMEM;
828 break;
829 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
830 type = SharedMemType::GRALLOC;
831 break;
832 default:
833 return BAD_VALUE;
834 }
835
836 SharedMemFormat format;
837 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
838 return BAD_VALUE;
839 }
840 format = SharedMemFormat::SENSORS_EVENT;
841
842 SharedMemInfo mem = {
843 .type = type,
844 .format = format,
845 .size = static_cast<uint32_t>(memory->size),
846 .memoryHandle = memory->handle,
847 };
848
849 int32_t ret;
850 checkReturn(mSensors->registerDirectChannel(mem,
851 [&ret](auto result, auto channelHandle) {
852 if (result == Result::OK) {
853 ret = channelHandle;
854 } else {
855 ret = StatusFromResult(result);
856 }
857 }));
858 return ret;
859}
860
861void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
862 if (mSensors == nullptr) return;
863 Mutex::Autolock _l(mLock);
864 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
865}
866
867int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
868 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
869 if (mSensors == nullptr) return NO_INIT;
870 Mutex::Autolock _l(mLock);
871
872 RateLevel rate;
873 switch(config->rate_level) {
874 case SENSOR_DIRECT_RATE_STOP:
875 rate = RateLevel::STOP;
876 break;
877 case SENSOR_DIRECT_RATE_NORMAL:
878 rate = RateLevel::NORMAL;
879 break;
880 case SENSOR_DIRECT_RATE_FAST:
881 rate = RateLevel::FAST;
882 break;
883 case SENSOR_DIRECT_RATE_VERY_FAST:
884 rate = RateLevel::VERY_FAST;
885 break;
886 default:
887 return BAD_VALUE;
888 }
889
890 int32_t ret;
891 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
892 [&ret, rate] (auto result, auto token) {
893 if (rate == RateLevel::STOP) {
894 ret = StatusFromResult(result);
895 } else {
896 if (result == Result::OK) {
897 ret = token;
898 } else {
899 ret = StatusFromResult(result);
900 }
901 }
902 }));
903
904 return ret;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700905}
906
Mathias Agopian667102f2011-09-14 16:43:34 -0700907// ---------------------------------------------------------------------------
908
Brian Stack156da082018-10-01 15:58:53 -0700909int SensorDevice::Info::numActiveClients() const {
Aravind Akella4949c502015-02-11 15:54:35 -0800910 SensorDevice& device(SensorDevice::getInstance());
911 int num = 0;
912 for (size_t i = 0; i < batchParams.size(); ++i) {
913 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
914 ++num;
915 }
916 }
917 return num;
918}
919
Peng Xu2bec6232016-07-01 17:13:10 -0700920status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
Aravind Akella724d91d2013-06-27 12:04:23 -0700921 int64_t samplingPeriodNs,
922 int64_t maxBatchReportLatencyNs) {
923 ssize_t index = batchParams.indexOfKey(ident);
Mathias Agopian667102f2011-09-14 16:43:34 -0700924 if (index < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700925 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
926 " timeout=%" PRId64 ") failed (%s)",
Aravind Akella724d91d2013-06-27 12:04:23 -0700927 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
Mathias Agopian667102f2011-09-14 16:43:34 -0700928 return BAD_INDEX;
929 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700930 BatchParams& params = batchParams.editValueAt(index);
Peng Xu2bec6232016-07-01 17:13:10 -0700931 params.mTSample = samplingPeriodNs;
932 params.mTBatch = maxBatchReportLatencyNs;
Mathias Agopian667102f2011-09-14 16:43:34 -0700933 return NO_ERROR;
934}
935
Aravind Akella724d91d2013-06-27 12:04:23 -0700936void SensorDevice::Info::selectBatchParams() {
Peng Xu2bec6232016-07-01 17:13:10 -0700937 BatchParams bestParams; // default to max Tsample and max Tbatch
Aravind Akella4949c502015-02-11 15:54:35 -0800938 SensorDevice& device(SensorDevice::getInstance());
Aravind Akella724d91d2013-06-27 12:04:23 -0700939
Aravind Akella4949c502015-02-11 15:54:35 -0800940 for (size_t i = 0; i < batchParams.size(); ++i) {
Peng Xu2bec6232016-07-01 17:13:10 -0700941 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
942 continue;
Aravind Akella724d91d2013-06-27 12:04:23 -0700943 }
Peng Xu2bec6232016-07-01 17:13:10 -0700944 bestParams.merge(batchParams[i]);
945 }
946 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
947 if (bestParams.mTBatch <= bestParams.mTSample) {
948 bestParams.mTBatch = 0;
Mathias Agopianf001c922010-11-11 17:58:51 -0800949 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700950 bestBatchParams = bestParams;
951}
952
953ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
954 ssize_t idx = batchParams.removeItem(ident);
955 if (idx >= 0) {
956 selectBatchParams();
957 }
958 return idx;
Mathias Agopianf001c922010-11-11 17:58:51 -0800959}
960
Peng Xu4f707f82016-09-26 11:28:32 -0700961void SensorDevice::notifyConnectionDestroyed(void* ident) {
962 Mutex::Autolock _l(mLock);
963 mDisabledClients.remove(ident);
964}
965
Peng Xu53632542017-01-23 20:06:27 -0800966bool SensorDevice::isDirectReportSupported() const {
Steven Morelandd15c0302016-12-20 11:14:50 -0800967 return mIsDirectReportSupported;
Peng Xu53632542017-01-23 20:06:27 -0800968}
Steven Morelandd15c0302016-12-20 11:14:50 -0800969
970void SensorDevice::convertToSensorEvent(
971 const Event &src, sensors_event_t *dst) {
972 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
973 src, dst);
974
975 if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
976 const DynamicSensorInfo &dyn = src.u.dynamic;
977
978 dst->dynamic_sensor_meta.connected = dyn.connected;
979 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
980 if (dyn.connected) {
981 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
982 CHECK(it != mConnectedDynamicSensors.end());
983
984 dst->dynamic_sensor_meta.sensor = it->second;
985
986 memcpy(dst->dynamic_sensor_meta.uuid,
987 dyn.uuid.data(),
988 sizeof(dst->dynamic_sensor_meta.uuid));
989 }
990 }
991}
992
993void SensorDevice::convertToSensorEvents(
994 const hidl_vec<Event> &src,
995 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
996 sensors_event_t *dst) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800997
Brian Stack6c49e6f2018-09-24 15:44:32 -0700998 if (dynamicSensorsAdded.size() > 0) {
999 onDynamicSensorsConnected(dynamicSensorsAdded);
Steven Morelandd15c0302016-12-20 11:14:50 -08001000 }
1001
1002 for (size_t i = 0; i < src.size(); ++i) {
1003 convertToSensorEvent(src[i], &dst[i]);
1004 }
1005}
1006
Peng Xu3889e6e2017-03-02 19:10:38 -08001007void SensorDevice::handleHidlDeath(const std::string & detail) {
Brian Stack156da082018-10-01 15:58:53 -07001008 if (!SensorDevice::getInstance().mSensors->supportsMessageQueues()) {
1009 // restart is the only option at present.
1010 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
1011 } else {
1012 ALOGD("ISensors HAL died, death recipient will attempt reconnect");
1013 }
Peng Xu3889e6e2017-03-02 19:10:38 -08001014}
1015
Mathias Agopianf001c922010-11-11 17:58:51 -08001016// ---------------------------------------------------------------------------
1017}; // namespace android