blob: c7a8f5bee32f2327c5645cda6d21542d40ba043c [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
Brian Duddie8e6f31c2019-05-29 13:19:13 -070048namespace {
49
50status_t statusFromResult(Result result) {
Steven Morelandd15c0302016-12-20 11:14:50 -080051 switch (result) {
52 case Result::OK:
53 return OK;
54 case Result::BAD_VALUE:
55 return BAD_VALUE;
56 case Result::PERMISSION_DENIED:
57 return PERMISSION_DENIED;
58 case Result::INVALID_OPERATION:
59 return INVALID_OPERATION;
60 case Result::NO_MEMORY:
61 return NO_MEMORY;
Mathias Agopianf001c922010-11-11 17:58:51 -080062 }
63}
64
Brian Stack156da082018-10-01 15:58:53 -070065template<typename EnumType>
66constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
67 return static_cast<typename std::underlying_type<EnumType>::type>(value);
68}
69
70// Used internally by the framework to wake the Event FMQ. These values must start after
71// the last value of EventQueueFlagBits
72enum EventQueueFlagBitsInternal : uint32_t {
73 INTERNAL_WAKE = 1 << 16,
74};
75
Brian Duddie8e6f31c2019-05-29 13:19:13 -070076} // anonymous namespace
77
Brian Stack574cda32018-10-01 11:18:51 -070078void SensorsHalDeathReceivier::serviceDied(
79 uint64_t /* cookie */,
80 const wp<::android::hidl::base::V1_0::IBase>& /* service */) {
81 ALOGW("Sensors HAL died, attempting to reconnect.");
Brian Stack156da082018-10-01 15:58:53 -070082 SensorDevice::getInstance().prepareForReconnect();
Brian Stack574cda32018-10-01 11:18:51 -070083}
84
Brian Stackbbab1ea2018-10-01 10:49:07 -070085struct SensorsCallback : public ISensorsCallback {
86 using Result = ::android::hardware::sensors::V1_0::Result;
87 Return<void> onDynamicSensorsConnected(
88 const hidl_vec<SensorInfo> &dynamicSensorsAdded) override {
89 return SensorDevice::getInstance().onDynamicSensorsConnected(dynamicSensorsAdded);
90 }
91
92 Return<void> onDynamicSensorsDisconnected(
93 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) override {
94 return SensorDevice::getInstance().onDynamicSensorsDisconnected(
95 dynamicSensorHandlesRemoved);
96 }
97};
98
Peng Xu1a00e2d2017-09-27 23:08:30 -070099SensorDevice::SensorDevice()
Brian Stack156da082018-10-01 15:58:53 -0700100 : mHidlTransportErrors(20),
101 mRestartWaiter(new HidlServiceRegistrationWaiter()),
Brian Stacka24e7d42019-01-08 12:56:09 -0800102 mEventQueueFlag(nullptr),
103 mWakeLockQueueFlag(nullptr),
Brian Stack156da082018-10-01 15:58:53 -0700104 mReconnecting(false) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700105 if (!connectHidlService()) {
106 return;
107 }
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700108
Brian Stack156da082018-10-01 15:58:53 -0700109 initializeSensorList();
110
111 mIsDirectReportSupported =
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700112 (checkReturnAndGetStatus(mSensors->unregisterDirectChannel(-1)) != INVALID_OPERATION);
Brian Stack156da082018-10-01 15:58:53 -0700113}
114
115void SensorDevice::initializeSensorList() {
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700116 float minPowerMa = 0.001; // 1 microAmp
117
Peng Xua8fad9b2017-03-17 12:20:27 -0700118 checkReturn(mSensors->getSensorsList(
119 [&](const auto &list) {
120 const size_t count = list.size();
121
122 mActivationCount.setCapacity(count);
123 Info model;
124 for (size_t i=0 ; i < count; i++) {
125 sensor_t sensor;
126 convertToSensor(list[i], &sensor);
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700127 // Sanity check and clamp power if it is 0 (or close)
128 if (sensor.power < minPowerMa) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700129 ALOGI("Reported power %f not deemed sane, clamping to %f",
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700130 sensor.power, minPowerMa);
131 sensor.power = minPowerMa;
132 }
Peng Xua8fad9b2017-03-17 12:20:27 -0700133 mSensorList.push_back(sensor);
134
135 mActivationCount.add(list[i].sensorHandle, model);
136
Stan Rokita7c9d8952019-08-01 14:24:25 -0700137 // Only disable all sensors on HAL 1.0 since HAL 2.0
138 // handles this in its initialize method
139 if (!mSensors->supportsMessageQueues()) {
140 checkReturn(mSensors->activate(list[i].sensorHandle,
141 0 /* enabled */));
142 }
Peng Xua8fad9b2017-03-17 12:20:27 -0700143 }
144 }));
Peng Xua8fad9b2017-03-17 12:20:27 -0700145}
146
Brian Stacka28e9212018-09-19 15:20:30 -0700147SensorDevice::~SensorDevice() {
148 if (mEventQueueFlag != nullptr) {
149 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
150 mEventQueueFlag = nullptr;
151 }
Brian Stacka24e7d42019-01-08 12:56:09 -0800152
153 if (mWakeLockQueueFlag != nullptr) {
154 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
155 mWakeLockQueueFlag = nullptr;
156 }
Brian Stacka28e9212018-09-19 15:20:30 -0700157}
158
Peng Xua8fad9b2017-03-17 12:20:27 -0700159bool SensorDevice::connectHidlService() {
Brian Stack979887b2018-09-19 15:27:48 -0700160 HalConnectionStatus status = connectHidlServiceV2_0();
161 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
162 status = connectHidlServiceV1_0();
Brian Stack12f4d322018-09-14 16:18:59 -0700163 }
Brian Stack979887b2018-09-19 15:27:48 -0700164 return (status == HalConnectionStatus::CONNECTED);
Brian Stack12f4d322018-09-14 16:18:59 -0700165}
166
Brian Stack979887b2018-09-19 15:27:48 -0700167SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700168 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
Peng Xu3889e6e2017-03-02 19:10:38 -0800169 size_t retry = 10;
Brian Stack979887b2018-09-19 15:27:48 -0700170 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Steven Morelandd15c0302016-12-20 11:14:50 -0800171
Peng Xu1a00e2d2017-09-27 23:08:30 -0700172 while (retry-- > 0) {
Brian Stack12f4d322018-09-14 16:18:59 -0700173 sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
174 if (sensors == nullptr) {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700175 // no sensor hidl service found
Brian Stack979887b2018-09-19 15:27:48 -0700176 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
Peng Xua8fad9b2017-03-17 12:20:27 -0700177 break;
Peng Xu3889e6e2017-03-02 19:10:38 -0800178 }
Peng Xu1a00e2d2017-09-27 23:08:30 -0700179
Brian Stack12f4d322018-09-14 16:18:59 -0700180 mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors);
Peng Xu1a00e2d2017-09-27 23:08:30 -0700181 mRestartWaiter->reset();
182 // Poke ISensor service. If it has lingering connection from previous generation of
183 // system server, it will kill itself. There is no intention to handle the poll result,
184 // which will be done since the size is 0.
185 if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
186 // ok to continue
Brian Stack979887b2018-09-19 15:27:48 -0700187 connectionStatus = HalConnectionStatus::CONNECTED;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700188 break;
189 }
190
191 // hidl service is restarting, pointer is invalid.
192 mSensors = nullptr;
Brian Stack979887b2018-09-19 15:27:48 -0700193 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700194 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
195 mRestartWaiter->wait();
Steven Morelandd15c0302016-12-20 11:14:50 -0800196 }
Brian Stack979887b2018-09-19 15:27:48 -0700197
198 return connectionStatus;
Steven Morelandd15c0302016-12-20 11:14:50 -0800199}
200
Brian Stack979887b2018-09-19 15:27:48 -0700201SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
202 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Brian Stack12f4d322018-09-14 16:18:59 -0700203 sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
Brian Stack979887b2018-09-19 15:27:48 -0700204
205 if (sensors == nullptr) {
206 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
207 } else {
Brian Stack12f4d322018-09-14 16:18:59 -0700208 mSensors = new SensorServiceUtil::SensorsWrapperV2_0(sensors);
209
Brian Stack979887b2018-09-19 15:27:48 -0700210 mEventQueue = std::make_unique<EventMessageQueue>(
211 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
212 true /* configureEventFlagWord */);
213
214 mWakeLockQueue = std::make_unique<WakeLockQueue>(
215 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
216 true /* configureEventFlagWord */);
217
Brian Stacka24e7d42019-01-08 12:56:09 -0800218 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
Brian Stacka28e9212018-09-19 15:20:30 -0700219 hardware::EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
220
Brian Stacka24e7d42019-01-08 12:56:09 -0800221 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
222 hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(),
223 &mWakeLockQueueFlag);
224
Brian Stack979887b2018-09-19 15:27:48 -0700225 CHECK(mSensors != nullptr && mEventQueue != nullptr &&
Brian Stacka24e7d42019-01-08 12:56:09 -0800226 mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
227 mWakeLockQueueFlag != nullptr);
Brian Stack979887b2018-09-19 15:27:48 -0700228
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700229 status_t status = checkReturnAndGetStatus(mSensors->initialize(
Brian Stack979887b2018-09-19 15:27:48 -0700230 *mEventQueue->getDesc(),
Brian Stack6c49e6f2018-09-24 15:44:32 -0700231 *mWakeLockQueue->getDesc(),
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700232 new SensorsCallback()));
Brian Stack979887b2018-09-19 15:27:48 -0700233
234 if (status != NO_ERROR) {
235 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Brian Stack6c49e6f2018-09-24 15:44:32 -0700236 ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
Brian Stack979887b2018-09-19 15:27:48 -0700237 } else {
238 connectionStatus = HalConnectionStatus::CONNECTED;
Brian Stack574cda32018-10-01 11:18:51 -0700239 mSensorsHalDeathReceiver = new SensorsHalDeathReceivier();
240 sensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
Brian Stack979887b2018-09-19 15:27:48 -0700241 }
Brian Stack12f4d322018-09-14 16:18:59 -0700242 }
Brian Stack979887b2018-09-19 15:27:48 -0700243
244 return connectionStatus;
Brian Stack12f4d322018-09-14 16:18:59 -0700245}
246
Brian Stack156da082018-10-01 15:58:53 -0700247void SensorDevice::prepareForReconnect() {
248 mReconnecting = true;
249
250 // Wake up the polling thread so it returns and allows the SensorService to initiate
251 // a reconnect.
252 mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
253}
254
255void SensorDevice::reconnect() {
256 Mutex::Autolock _l(mLock);
257 mSensors = nullptr;
258
259 auto previousActivations = mActivationCount;
260 auto previousSensorList = mSensorList;
261
262 mActivationCount.clear();
263 mSensorList.clear();
264
265 if (connectHidlServiceV2_0() == HalConnectionStatus::CONNECTED) {
266 initializeSensorList();
267
268 if (sensorHandlesChanged(previousSensorList, mSensorList)) {
269 LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
270 } else {
271 reactivateSensors(previousActivations);
272 }
273 }
274 mReconnecting = false;
275}
276
277bool SensorDevice::sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
278 const Vector<sensor_t>& newSensorList) {
279 bool didChange = false;
280
281 if (oldSensorList.size() != newSensorList.size()) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700282 ALOGI("Sensor list size changed from %zu to %zu", oldSensorList.size(),
283 newSensorList.size());
Brian Stack156da082018-10-01 15:58:53 -0700284 didChange = true;
285 }
286
287 for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
288 bool found = false;
289 const sensor_t& newSensor = newSensorList[i];
290 for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
291 const sensor_t& prevSensor = oldSensorList[j];
292 if (prevSensor.handle == newSensor.handle) {
293 found = true;
294 if (!sensorIsEquivalent(prevSensor, newSensor)) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700295 ALOGI("Sensor %s not equivalent to previous version", newSensor.name);
Brian Stack156da082018-10-01 15:58:53 -0700296 didChange = true;
297 }
298 }
299 }
300
301 if (!found) {
302 // Could not find the new sensor in the old list of sensors, the lists must
303 // have changed.
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700304 ALOGI("Sensor %s (handle %d) did not exist before", newSensor.name, newSensor.handle);
Brian Stack156da082018-10-01 15:58:53 -0700305 didChange = true;
306 }
307 }
308 return didChange;
309}
310
311bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
312 bool equivalent = true;
313 if (prevSensor.handle != newSensor.handle ||
314 (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
315 (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
316 (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
317 (prevSensor.version != newSensor.version) ||
318 (prevSensor.type != newSensor.type) ||
319 (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
320 (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
321 (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
322 (prevSensor.minDelay != newSensor.minDelay) ||
323 (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
324 (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
325 (prevSensor.maxDelay != newSensor.maxDelay) ||
326 (prevSensor.flags != newSensor.flags)) {
327 equivalent = false;
328 }
329 return equivalent;
330}
331
332void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
333 for (size_t i = 0; i < mSensorList.size(); i++) {
334 int handle = mSensorList[i].handle;
335 ssize_t activationIndex = previousActivations.indexOfKey(handle);
336 if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
337 continue;
338 }
339
340 const Info& info = previousActivations[activationIndex];
341 for (size_t j = 0; j < info.batchParams.size(); j++) {
342 const BatchParams& batchParams = info.batchParams[j];
343 status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
344 batchParams.mTSample, batchParams.mTBatch);
345
346 if (res == NO_ERROR) {
347 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
348 }
349 }
350 }
351}
352
Peng Xu2576cb62016-01-20 00:22:09 -0800353void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700354 // not need to check mSensors because this is is only called after successful poll()
Peng Xu2576cb62016-01-20 00:22:09 -0800355 if (connected) {
356 Info model;
357 mActivationCount.add(handle, model);
Peng Xu3889e6e2017-03-02 19:10:38 -0800358 checkReturn(mSensors->activate(handle, 0 /* enabled */));
Peng Xu2576cb62016-01-20 00:22:09 -0800359 } else {
360 mActivationCount.removeItem(handle);
361 }
362}
363
Peng Xu6a2d3a02015-12-21 12:00:23 -0800364std::string SensorDevice::dump() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700365 if (mSensors == nullptr) return "HAL not initialized\n";
Mathias Agopianf001c922010-11-11 17:58:51 -0800366
Peng Xu6a2d3a02015-12-21 12:00:23 -0800367 String8 result;
Peng Xua8fad9b2017-03-17 12:20:27 -0700368 result.appendFormat("Total %zu h/w sensors, %zu running:\n",
369 mSensorList.size(), mActivationCount.size());
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700370
Peng Xua8fad9b2017-03-17 12:20:27 -0700371 Mutex::Autolock _l(mLock);
372 for (const auto & s : mSensorList) {
373 int32_t handle = s.handle;
374 const Info& info = mActivationCount.valueFor(handle);
Brian Stackbce04d72019-03-21 10:54:10 -0700375 if (info.numActiveClients() == 0) continue;
Peng Xua8fad9b2017-03-17 12:20:27 -0700376
377 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
378
379 result.append("sampling_period(ms) = {");
380 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700381 const BatchParams& params = info.batchParams[j];
382 result.appendFormat("%.1f%s", params.mTSample / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700383 j < info.batchParams.size() - 1 ? ", " : "");
384 }
Peng Xu2bec6232016-07-01 17:13:10 -0700385 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
Peng Xua8fad9b2017-03-17 12:20:27 -0700386
387 result.append("batching_period(ms) = {");
388 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700389 const BatchParams& params = info.batchParams[j];
390 result.appendFormat("%.1f%s", params.mTBatch / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700391 j < info.batchParams.size() - 1 ? ", " : "");
392 }
Peng Xu2bec6232016-07-01 17:13:10 -0700393 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700394 }
395
Peng Xu6a2d3a02015-12-21 12:00:23 -0800396 return result.string();
Mathias Agopianf001c922010-11-11 17:58:51 -0800397}
398
399ssize_t SensorDevice::getSensorList(sensor_t const** list) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800400 *list = &mSensorList[0];
401
402 return mSensorList.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800403}
404
405status_t SensorDevice::initCheck() const {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700406 return mSensors != nullptr ? NO_ERROR : NO_INIT;
Mathias Agopianf001c922010-11-11 17:58:51 -0800407}
408
409ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
Brian Stack156da082018-10-01 15:58:53 -0700410 if (mSensors == nullptr) return NO_INIT;
411
Brian Stacka28e9212018-09-19 15:20:30 -0700412 ssize_t eventsRead = 0;
413 if (mSensors->supportsMessageQueues()) {
414 eventsRead = pollFmq(buffer, count);
415 } else if (mSensors->supportsPolling()) {
416 eventsRead = pollHal(buffer, count);
417 } else {
418 ALOGE("Must support polling or FMQ");
419 eventsRead = -1;
420 }
421 return eventsRead;
422}
423
424ssize_t SensorDevice::pollHal(sensors_event_t* buffer, size_t count) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800425 ssize_t err;
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700426 int numHidlTransportErrors = 0;
427 bool hidlTransportError = false;
Steven Morelandd15c0302016-12-20 11:14:50 -0800428
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700429 do {
430 auto ret = mSensors->poll(
431 count,
432 [&](auto result,
433 const auto &events,
434 const auto &dynamicSensorsAdded) {
435 if (result == Result::OK) {
436 convertToSensorEvents(events, dynamicSensorsAdded, buffer);
437 err = (ssize_t)events.size();
438 } else {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700439 err = statusFromResult(result);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700440 }
441 });
442
443 if (ret.isOk()) {
444 hidlTransportError = false;
445 } else {
446 hidlTransportError = true;
447 numHidlTransportErrors++;
448 if (numHidlTransportErrors > 50) {
449 // Log error and bail
450 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
451 handleHidlDeath(ret.description());
452 } else {
453 std::this_thread::sleep_for(std::chrono::milliseconds(10));
454 }
455 }
456 } while (hidlTransportError);
457
458 if(numHidlTransportErrors > 0) {
459 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
Yi Kong8f313e32018-07-17 14:13:29 -0700460 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700461 mHidlTransportErrors.add(errLog);
462 mTotalHidlTransportErrors++;
463 }
Steven Morelandd15c0302016-12-20 11:14:50 -0800464
465 return err;
Mathias Agopianf001c922010-11-11 17:58:51 -0800466}
467
Brian Stacka28e9212018-09-19 15:20:30 -0700468ssize_t SensorDevice::pollFmq(sensors_event_t* buffer, size_t maxNumEventsToRead) {
Brian Stacka28e9212018-09-19 15:20:30 -0700469 ssize_t eventsRead = 0;
470 size_t availableEvents = mEventQueue->availableToRead();
471
472 if (availableEvents == 0) {
473 uint32_t eventFlagState = 0;
474
475 // Wait for events to become available. This is necessary so that the Event FMQ's read() is
476 // able to be called with the correct number of events to read. If the specified number of
477 // events is not available, then read() would return no events, possibly introducing
478 // additional latency in delivering events to applications.
Brian Stack156da082018-10-01 15:58:53 -0700479 mEventQueueFlag->wait(asBaseType(EventQueueFlagBits::READ_AND_PROCESS) |
480 asBaseType(INTERNAL_WAKE), &eventFlagState);
Brian Stacka28e9212018-09-19 15:20:30 -0700481 availableEvents = mEventQueue->availableToRead();
482
Brian Stack156da082018-10-01 15:58:53 -0700483 if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
484 ALOGD("Event FMQ internal wake, returning from poll with no events");
485 return DEAD_OBJECT;
486 }
Brian Stacka28e9212018-09-19 15:20:30 -0700487 }
488
489 size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
490 if (eventsToRead > 0) {
491 if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
Brian Stackaf1b54c2018-11-09 10:20:01 -0800492 // Notify the Sensors HAL that sensor events have been read. This is required to support
493 // the use of writeBlocking by the Sensors HAL.
494 mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
495
Brian Stacka28e9212018-09-19 15:20:30 -0700496 for (size_t i = 0; i < eventsToRead; i++) {
497 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
498 }
499 eventsRead = eventsToRead;
500 } else {
501 ALOGW("Failed to read %zu events, currently %zu events available",
502 eventsToRead, availableEvents);
503 }
504 }
505
506 return eventsRead;
507}
508
Brian Stack6c49e6f2018-09-24 15:44:32 -0700509Return<void> SensorDevice::onDynamicSensorsConnected(
510 const hidl_vec<SensorInfo> &dynamicSensorsAdded) {
511 // Allocate a sensor_t structure for each dynamic sensor added and insert
512 // it into the dictionary of connected dynamic sensors keyed by handle.
513 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
514 const SensorInfo &info = dynamicSensorsAdded[i];
515
516 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
517 CHECK(it == mConnectedDynamicSensors.end());
518
519 sensor_t *sensor = new sensor_t();
520 convertToSensor(info, sensor);
521
522 mConnectedDynamicSensors.insert(
523 std::make_pair(sensor->handle, sensor));
524 }
525
526 return Return<void>();
527}
528
529Return<void> SensorDevice::onDynamicSensorsDisconnected(
530 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) {
531 (void) dynamicSensorHandlesRemoved;
532 // TODO: Currently dynamic sensors do not seem to be removed
533 return Return<void>();
534}
535
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700536void SensorDevice::writeWakeLockHandled(uint32_t count) {
Brian Stacka24e7d42019-01-08 12:56:09 -0800537 if (mSensors != nullptr && mSensors->supportsMessageQueues()) {
538 if (mWakeLockQueue->write(&count)) {
539 mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
540 } else {
541 ALOGW("Failed to write wake lock handled");
542 }
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700543 }
544}
545
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700546void SensorDevice::autoDisable(void *ident, int handle) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700547 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700548 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
549 if (activationIndex < 0) {
550 ALOGW("Handle %d cannot be found in activation record", handle);
551 return;
552 }
553 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700554 info.removeBatchParamsForIdent(ident);
Brian Stackaa6dc092019-05-10 13:36:40 -0700555 if (info.numActiveClients() == 0) {
556 info.isActive = false;
557 }
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700558}
559
Peng Xu6a2d3a02015-12-21 12:00:23 -0800560status_t SensorDevice::activate(void* ident, int handle, int enabled) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700561 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800562
Brian Stack156da082018-10-01 15:58:53 -0700563 Mutex::Autolock _l(mLock);
564 return activateLocked(ident, handle, enabled);
565}
566
567status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800568 bool actuateHardware = false;
569
Brian Stack156da082018-10-01 15:58:53 -0700570 status_t err(NO_ERROR);
571
Peng Xu042baec2017-08-09 19:28:27 -0700572 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
573 if (activationIndex < 0) {
574 ALOGW("Handle %d cannot be found in activation record", handle);
575 return BAD_VALUE;
576 }
577 Info& info(mActivationCount.editValueAt(activationIndex));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700578
Steve Blocka5512372011-12-20 16:23:08 +0000579 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700580 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
Aravind Akella724d91d2013-06-27 12:04:23 -0700581 ident, handle, enabled, info.batchParams.size());
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700582
Mathias Agopianf001c922010-11-11 17:58:51 -0800583 if (enabled) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700584 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700585
Aravind Akella4949c502015-02-11 15:54:35 -0800586 if (isClientDisabledLocked(ident)) {
Peng Xu966fa882016-09-01 16:13:15 -0700587 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
588 ident, handle);
Aravind Akella4949c502015-02-11 15:54:35 -0800589 return INVALID_OPERATION;
590 }
591
Aravind Akella724d91d2013-06-27 12:04:23 -0700592 if (info.batchParams.indexOfKey(ident) >= 0) {
Brian Stack0c305fe2019-04-09 12:49:24 -0700593 if (info.numActiveClients() > 0 && !info.isActive) {
594 actuateHardware = true;
595 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800596 } else {
Aravind Akella724d91d2013-06-27 12:04:23 -0700597 // Log error. Every activate call should be preceded by a batch() call.
598 ALOGE("\t >>>ERROR: activate called without batch");
Mathias Agopianf001c922010-11-11 17:58:51 -0800599 }
600 } else {
Mark Salyzyndb458612014-06-10 14:50:02 -0700601 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700602
Steven Morelandd15c0302016-12-20 11:14:50 -0800603 // If a connected dynamic sensor is deactivated, remove it from the
604 // dictionary.
605 auto it = mConnectedDynamicSensors.find(handle);
606 if (it != mConnectedDynamicSensors.end()) {
607 delete it->second;
608 mConnectedDynamicSensors.erase(it);
609 }
610
Aravind Akella724d91d2013-06-27 12:04:23 -0700611 if (info.removeBatchParamsForIdent(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800612 if (info.numActiveClients() == 0) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700613 // This is the last connection, we need to de-activate the underlying h/w sensor.
Mathias Agopian50b66762010-11-29 17:26:51 -0800614 actuateHardware = true;
Aravind Akella724d91d2013-06-27 12:04:23 -0700615 } else {
Steven Morelandd15c0302016-12-20 11:14:50 -0800616 // Call batch for this sensor with the previously calculated best effort
617 // batch_rate and timeout. One of the apps has unregistered for sensor
618 // events, and the best effort batch parameters might have changed.
619 ALOGD_IF(DEBUG_CONNECTIONS,
Peng Xu2bec6232016-07-01 17:13:10 -0700620 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
621 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Peng Xu3889e6e2017-03-02 19:10:38 -0800622 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700623 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Mathias Agopian50b66762010-11-29 17:26:51 -0800624 }
625 } else {
626 // sensor wasn't enabled for this ident
627 }
Aravind Akella4949c502015-02-11 15:54:35 -0800628
629 if (isClientDisabledLocked(ident)) {
630 return NO_ERROR;
631 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800632 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800633
Mathias Agopianf001c922010-11-11 17:58:51 -0800634 if (actuateHardware) {
Aravind Akella4949c502015-02-11 15:54:35 -0800635 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
636 enabled);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700637 err = checkReturnAndGetStatus(mSensors->activate(handle, enabled));
Aravind Akella724d91d2013-06-27 12:04:23 -0700638 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
639 strerror(-err));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700640
Aravind Akella724d91d2013-06-27 12:04:23 -0700641 if (err != NO_ERROR && enabled) {
642 // Failure when enabling the sensor. Clean up on failure.
643 info.removeBatchParamsForIdent(ident);
Brian Stack0c305fe2019-04-09 12:49:24 -0700644 } else {
645 // Update the isActive flag if there is no error. If there is an error when disabling a
646 // sensor, still set the flag to false since the batch parameters have already been
647 // removed. This ensures that everything remains in-sync.
648 info.isActive = enabled;
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700649 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800650 }
651
Mathias Agopianf001c922010-11-11 17:58:51 -0800652 return err;
653}
654
Steven Morelandd15c0302016-12-20 11:14:50 -0800655status_t SensorDevice::batch(
656 void* ident,
657 int handle,
658 int flags,
659 int64_t samplingPeriodNs,
660 int64_t maxBatchReportLatencyNs) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700661 if (mSensors == nullptr) return NO_INIT;
Aravind Akella724d91d2013-06-27 12:04:23 -0700662
663 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
664 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
665 }
Peng Xu2bec6232016-07-01 17:13:10 -0700666 if (maxBatchReportLatencyNs < 0) {
667 maxBatchReportLatencyNs = 0;
668 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700669
Aravind Akella724d91d2013-06-27 12:04:23 -0700670 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700671 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700672 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
673
674 Mutex::Autolock _l(mLock);
Brian Stack156da082018-10-01 15:58:53 -0700675 return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
676}
677
678status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
679 int64_t maxBatchReportLatencyNs) {
Peng Xu042baec2017-08-09 19:28:27 -0700680 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
681 if (activationIndex < 0) {
682 ALOGW("Handle %d cannot be found in activation record", handle);
683 return BAD_VALUE;
684 }
685 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700686
687 if (info.batchParams.indexOfKey(ident) < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700688 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
Aravind Akella724d91d2013-06-27 12:04:23 -0700689 info.batchParams.add(ident, params);
690 } else {
691 // A batch has already been called with this ident. Update the batch parameters.
692 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
693 }
694
695 BatchParams prevBestBatchParams = info.bestBatchParams;
696 // Find the minimum of all timeouts and batch_rates for this sensor.
697 info.selectBatchParams();
698
699 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700700 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
701 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
Peng Xu2bec6232016-07-01 17:13:10 -0700702 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
703 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
Aravind Akella724d91d2013-06-27 12:04:23 -0700704
705 status_t err(NO_ERROR);
706 // If the min period or min timeout has changed since the last batch call, call batch.
707 if (prevBestBatchParams != info.bestBatchParams) {
Peng Xu2bec6232016-07-01 17:13:10 -0700708 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
709 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700710 err = checkReturnAndGetStatus(mSensors->batch(
711 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Aravind Akella724d91d2013-06-27 12:04:23 -0700712 if (err != NO_ERROR) {
Peng Xu2bec6232016-07-01 17:13:10 -0700713 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
714 mSensors.get(), handle, info.bestBatchParams.mTSample,
715 info.bestBatchParams.mTBatch, strerror(-err));
Aravind Akella724d91d2013-06-27 12:04:23 -0700716 info.removeBatchParamsForIdent(ident);
717 }
718 }
719 return err;
720}
721
Peng Xu6a2d3a02015-12-21 12:00:23 -0800722status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
Peng Xu2bec6232016-07-01 17:13:10 -0700723 return batch(ident, handle, 0, samplingPeriodNs, 0);
Mathias Agopian667102f2011-09-14 16:43:34 -0700724}
725
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700726int SensorDevice::getHalDeviceVersion() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700727 if (mSensors == nullptr) return -1;
Steven Morelandd15c0302016-12-20 11:14:50 -0800728 return SENSORS_DEVICE_API_VERSION_1_4;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700729}
730
Aravind Akella9a844cf2014-02-11 18:58:52 -0800731status_t SensorDevice::flush(void* ident, int handle) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700732 if (mSensors == nullptr) return NO_INIT;
Aravind Akella4949c502015-02-11 15:54:35 -0800733 if (isClientDisabled(ident)) return INVALID_OPERATION;
Aravind Akella724d91d2013-06-27 12:04:23 -0700734 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700735 return checkReturnAndGetStatus(mSensors->flush(handle));
Aravind Akella724d91d2013-06-27 12:04:23 -0700736}
737
Aravind Akella4949c502015-02-11 15:54:35 -0800738bool SensorDevice::isClientDisabled(void* ident) {
739 Mutex::Autolock _l(mLock);
740 return isClientDisabledLocked(ident);
741}
742
743bool SensorDevice::isClientDisabledLocked(void* ident) {
744 return mDisabledClients.indexOf(ident) >= 0;
745}
746
Brian Stackbce04d72019-03-21 10:54:10 -0700747bool SensorDevice::isSensorActive(int handle) const {
748 Mutex::Autolock _l(mLock);
749 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
750 if (activationIndex < 0) {
751 return false;
752 }
753 return mActivationCount.valueAt(activationIndex).numActiveClients() > 0;
754}
755
Aravind Akella4949c502015-02-11 15:54:35 -0800756void SensorDevice::enableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700757 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800758 Mutex::Autolock _l(mLock);
759 mDisabledClients.clear();
Peng Xu966fa882016-09-01 16:13:15 -0700760 ALOGI("cleared mDisabledClients");
Aravind Akella4949c502015-02-11 15:54:35 -0800761 for (size_t i = 0; i< mActivationCount.size(); ++i) {
762 Info& info = mActivationCount.editValueAt(i);
763 if (info.batchParams.isEmpty()) continue;
764 info.selectBatchParams();
765 const int sensor_handle = mActivationCount.keyAt(i);
766 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
767 sensor_handle);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700768 status_t err = checkReturnAndGetStatus(mSensors->batch(
769 sensor_handle,
770 info.bestBatchParams.mTSample,
771 info.bestBatchParams.mTBatch));
Steven Morelandd15c0302016-12-20 11:14:50 -0800772 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
Aravind Akella4949c502015-02-11 15:54:35 -0800773
774 if (err == NO_ERROR) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700775 err = checkReturnAndGetStatus(mSensors->activate(sensor_handle, 1 /* enabled */));
Aravind Akella4949c502015-02-11 15:54:35 -0800776 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
777 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700778
779 if (err == NO_ERROR) {
780 info.isActive = true;
781 }
Aravind Akella4949c502015-02-11 15:54:35 -0800782 }
783}
784
785void SensorDevice::disableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700786 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800787 Mutex::Autolock _l(mLock);
Peng Xua8fad9b2017-03-17 12:20:27 -0700788 for (size_t i = 0; i< mActivationCount.size(); ++i) {
Brian Stack4a11fed2019-04-22 15:07:50 -0700789 Info& info = mActivationCount.editValueAt(i);
Aravind Akella4949c502015-02-11 15:54:35 -0800790 // Check if this sensor has been activated previously and disable it.
791 if (info.batchParams.size() > 0) {
792 const int sensor_handle = mActivationCount.keyAt(i);
793 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
794 sensor_handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800795 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
Steven Morelandd15c0302016-12-20 11:14:50 -0800796
Aravind Akella4949c502015-02-11 15:54:35 -0800797 // Add all the connections that were registered for this sensor to the disabled
798 // clients list.
Svetoslavb412f6e2015-04-29 16:50:41 -0700799 for (size_t j = 0; j < info.batchParams.size(); ++j) {
Aravind Akella4949c502015-02-11 15:54:35 -0800800 mDisabledClients.add(info.batchParams.keyAt(j));
Peng Xu966fa882016-09-01 16:13:15 -0700801 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
Aravind Akella4949c502015-02-11 15:54:35 -0800802 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700803
804 info.isActive = false;
Aravind Akella4949c502015-02-11 15:54:35 -0800805 }
806 }
807}
808
Steven Morelandd15c0302016-12-20 11:14:50 -0800809status_t SensorDevice::injectSensorData(
810 const sensors_event_t *injected_sensor_event) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700811 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800812 ALOGD_IF(DEBUG_CONNECTIONS,
813 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
814 injected_sensor_event->sensor,
815 injected_sensor_event->timestamp, injected_sensor_event->data[0],
816 injected_sensor_event->data[1], injected_sensor_event->data[2],
817 injected_sensor_event->data[3], injected_sensor_event->data[4],
818 injected_sensor_event->data[5]);
819
820 Event ev;
821 convertFromSensorEvent(*injected_sensor_event, &ev);
822
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700823 return checkReturnAndGetStatus(mSensors->injectSensorData(ev));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700824}
825
826status_t SensorDevice::setMode(uint32_t mode) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700827 if (mSensors == nullptr) return NO_INIT;
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700828 return checkReturnAndGetStatus(mSensors->setOperationMode(
829 static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
Peng Xua8fad9b2017-03-17 12:20:27 -0700830}
Steven Morelandd15c0302016-12-20 11:14:50 -0800831
Peng Xua8fad9b2017-03-17 12:20:27 -0700832int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
833 if (mSensors == nullptr) return NO_INIT;
834 Mutex::Autolock _l(mLock);
835
836 SharedMemType type;
837 switch (memory->type) {
838 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
839 type = SharedMemType::ASHMEM;
840 break;
841 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
842 type = SharedMemType::GRALLOC;
843 break;
844 default:
845 return BAD_VALUE;
846 }
847
848 SharedMemFormat format;
849 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
850 return BAD_VALUE;
851 }
852 format = SharedMemFormat::SENSORS_EVENT;
853
854 SharedMemInfo mem = {
855 .type = type,
856 .format = format,
857 .size = static_cast<uint32_t>(memory->size),
858 .memoryHandle = memory->handle,
859 };
860
861 int32_t ret;
862 checkReturn(mSensors->registerDirectChannel(mem,
863 [&ret](auto result, auto channelHandle) {
864 if (result == Result::OK) {
865 ret = channelHandle;
866 } else {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700867 ret = statusFromResult(result);
Peng Xua8fad9b2017-03-17 12:20:27 -0700868 }
869 }));
870 return ret;
871}
872
873void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
874 if (mSensors == nullptr) return;
875 Mutex::Autolock _l(mLock);
876 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
877}
878
879int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
880 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
881 if (mSensors == nullptr) return NO_INIT;
882 Mutex::Autolock _l(mLock);
883
884 RateLevel rate;
885 switch(config->rate_level) {
886 case SENSOR_DIRECT_RATE_STOP:
887 rate = RateLevel::STOP;
888 break;
889 case SENSOR_DIRECT_RATE_NORMAL:
890 rate = RateLevel::NORMAL;
891 break;
892 case SENSOR_DIRECT_RATE_FAST:
893 rate = RateLevel::FAST;
894 break;
895 case SENSOR_DIRECT_RATE_VERY_FAST:
896 rate = RateLevel::VERY_FAST;
897 break;
898 default:
899 return BAD_VALUE;
900 }
901
902 int32_t ret;
903 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
904 [&ret, rate] (auto result, auto token) {
905 if (rate == RateLevel::STOP) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700906 ret = statusFromResult(result);
Peng Xua8fad9b2017-03-17 12:20:27 -0700907 } else {
908 if (result == Result::OK) {
909 ret = token;
910 } else {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700911 ret = statusFromResult(result);
Peng Xua8fad9b2017-03-17 12:20:27 -0700912 }
913 }
914 }));
915
916 return ret;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700917}
918
Mathias Agopian667102f2011-09-14 16:43:34 -0700919// ---------------------------------------------------------------------------
920
Brian Stack156da082018-10-01 15:58:53 -0700921int SensorDevice::Info::numActiveClients() const {
Aravind Akella4949c502015-02-11 15:54:35 -0800922 SensorDevice& device(SensorDevice::getInstance());
923 int num = 0;
924 for (size_t i = 0; i < batchParams.size(); ++i) {
925 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
926 ++num;
927 }
928 }
929 return num;
930}
931
Peng Xu2bec6232016-07-01 17:13:10 -0700932status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
Aravind Akella724d91d2013-06-27 12:04:23 -0700933 int64_t samplingPeriodNs,
934 int64_t maxBatchReportLatencyNs) {
935 ssize_t index = batchParams.indexOfKey(ident);
Mathias Agopian667102f2011-09-14 16:43:34 -0700936 if (index < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700937 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
938 " timeout=%" PRId64 ") failed (%s)",
Aravind Akella724d91d2013-06-27 12:04:23 -0700939 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
Mathias Agopian667102f2011-09-14 16:43:34 -0700940 return BAD_INDEX;
941 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700942 BatchParams& params = batchParams.editValueAt(index);
Peng Xu2bec6232016-07-01 17:13:10 -0700943 params.mTSample = samplingPeriodNs;
944 params.mTBatch = maxBatchReportLatencyNs;
Mathias Agopian667102f2011-09-14 16:43:34 -0700945 return NO_ERROR;
946}
947
Aravind Akella724d91d2013-06-27 12:04:23 -0700948void SensorDevice::Info::selectBatchParams() {
Peng Xu2bec6232016-07-01 17:13:10 -0700949 BatchParams bestParams; // default to max Tsample and max Tbatch
Aravind Akella4949c502015-02-11 15:54:35 -0800950 SensorDevice& device(SensorDevice::getInstance());
Aravind Akella724d91d2013-06-27 12:04:23 -0700951
Aravind Akella4949c502015-02-11 15:54:35 -0800952 for (size_t i = 0; i < batchParams.size(); ++i) {
Peng Xu2bec6232016-07-01 17:13:10 -0700953 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
954 continue;
Aravind Akella724d91d2013-06-27 12:04:23 -0700955 }
Peng Xu2bec6232016-07-01 17:13:10 -0700956 bestParams.merge(batchParams[i]);
957 }
958 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
959 if (bestParams.mTBatch <= bestParams.mTSample) {
960 bestParams.mTBatch = 0;
Mathias Agopianf001c922010-11-11 17:58:51 -0800961 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700962 bestBatchParams = bestParams;
963}
964
965ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
966 ssize_t idx = batchParams.removeItem(ident);
967 if (idx >= 0) {
968 selectBatchParams();
969 }
970 return idx;
Mathias Agopianf001c922010-11-11 17:58:51 -0800971}
972
Peng Xu4f707f82016-09-26 11:28:32 -0700973void SensorDevice::notifyConnectionDestroyed(void* ident) {
974 Mutex::Autolock _l(mLock);
975 mDisabledClients.remove(ident);
976}
977
Peng Xu53632542017-01-23 20:06:27 -0800978bool SensorDevice::isDirectReportSupported() const {
Steven Morelandd15c0302016-12-20 11:14:50 -0800979 return mIsDirectReportSupported;
Peng Xu53632542017-01-23 20:06:27 -0800980}
Steven Morelandd15c0302016-12-20 11:14:50 -0800981
982void SensorDevice::convertToSensorEvent(
983 const Event &src, sensors_event_t *dst) {
984 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
985 src, dst);
986
987 if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
988 const DynamicSensorInfo &dyn = src.u.dynamic;
989
990 dst->dynamic_sensor_meta.connected = dyn.connected;
991 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
992 if (dyn.connected) {
993 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
994 CHECK(it != mConnectedDynamicSensors.end());
995
996 dst->dynamic_sensor_meta.sensor = it->second;
997
998 memcpy(dst->dynamic_sensor_meta.uuid,
999 dyn.uuid.data(),
1000 sizeof(dst->dynamic_sensor_meta.uuid));
1001 }
1002 }
1003}
1004
1005void SensorDevice::convertToSensorEvents(
1006 const hidl_vec<Event> &src,
1007 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
1008 sensors_event_t *dst) {
Steven Morelandd15c0302016-12-20 11:14:50 -08001009
Brian Stack6c49e6f2018-09-24 15:44:32 -07001010 if (dynamicSensorsAdded.size() > 0) {
1011 onDynamicSensorsConnected(dynamicSensorsAdded);
Steven Morelandd15c0302016-12-20 11:14:50 -08001012 }
1013
1014 for (size_t i = 0; i < src.size(); ++i) {
1015 convertToSensorEvent(src[i], &dst[i]);
1016 }
1017}
1018
Peng Xu3889e6e2017-03-02 19:10:38 -08001019void SensorDevice::handleHidlDeath(const std::string & detail) {
Brian Duddie6d2e3752019-05-30 09:52:28 -07001020 if (!mSensors->supportsMessageQueues()) {
Brian Stack156da082018-10-01 15:58:53 -07001021 // restart is the only option at present.
1022 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
1023 } else {
1024 ALOGD("ISensors HAL died, death recipient will attempt reconnect");
1025 }
Peng Xu3889e6e2017-03-02 19:10:38 -08001026}
1027
Brian Duddie8e6f31c2019-05-29 13:19:13 -07001028status_t SensorDevice::checkReturnAndGetStatus(const Return<Result>& ret) {
1029 checkReturn(ret);
1030 return (!ret.isOk()) ? DEAD_OBJECT : statusFromResult(ret);
1031}
1032
Mathias Agopianf001c922010-11-11 17:58:51 -08001033// ---------------------------------------------------------------------------
1034}; // namespace android