blob: 33f940fe80319470a4298d1e16342a9dddeb3d5c [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>
Mike Ma24743862020-01-29 00:36:55 -080024#include <android/util/ProtoOutputStream.h>
25#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
Peng Xu3889e6e2017-03-02 19:10:38 -080026#include <sensors/convert.h>
Steven Moreland2716e112018-02-23 14:57:20 -080027#include <cutils/atomic.h>
Ashutosh Joshi5cafc1e2017-02-09 21:44:04 +000028#include <utils/Errors.h>
29#include <utils/Singleton.h>
Steven Morelandd3335112016-12-20 11:14:50 -080030
Peng Xu3889e6e2017-03-02 19:10:38 -080031#include <chrono>
32#include <cinttypes>
33#include <thread>
Steven Morelandd15c0302016-12-20 11:14:50 -080034
Brian Stack12f4d322018-09-14 16:18:59 -070035using namespace android::hardware::sensors;
Steven Morelandd15c0302016-12-20 11:14:50 -080036using namespace android::hardware::sensors::V1_0;
37using namespace android::hardware::sensors::V1_0::implementation;
Brian Stackbbab1ea2018-10-01 10:49:07 -070038using android::hardware::sensors::V2_0::ISensorsCallback;
Brian Stacka28e9212018-09-19 15:20:30 -070039using android::hardware::sensors::V2_0::EventQueueFlagBits;
Brian Stacka24e7d42019-01-08 12:56:09 -080040using android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
Peng Xu1a00e2d2017-09-27 23:08:30 -070041using android::hardware::hidl_vec;
Brian Stack6c49e6f2018-09-24 15:44:32 -070042using android::hardware::Return;
Peng Xu1a00e2d2017-09-27 23:08:30 -070043using android::SensorDeviceUtils::HidlServiceRegistrationWaiter;
Mike Ma24743862020-01-29 00:36:55 -080044using android::util::ProtoOutputStream;
Peng Xu2bec6232016-07-01 17:13:10 -070045
Mathias Agopianf001c922010-11-11 17:58:51 -080046namespace android {
47// ---------------------------------------------------------------------------
Mathias Agopianf001c922010-11-11 17:58:51 -080048
49ANDROID_SINGLETON_STATIC_INSTANCE(SensorDevice)
50
Brian Duddie8e6f31c2019-05-29 13:19:13 -070051namespace {
52
53status_t statusFromResult(Result result) {
Steven Morelandd15c0302016-12-20 11:14:50 -080054 switch (result) {
55 case Result::OK:
56 return OK;
57 case Result::BAD_VALUE:
58 return BAD_VALUE;
59 case Result::PERMISSION_DENIED:
60 return PERMISSION_DENIED;
61 case Result::INVALID_OPERATION:
62 return INVALID_OPERATION;
63 case Result::NO_MEMORY:
64 return NO_MEMORY;
Mathias Agopianf001c922010-11-11 17:58:51 -080065 }
66}
67
Brian Stack156da082018-10-01 15:58:53 -070068template<typename EnumType>
69constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
70 return static_cast<typename std::underlying_type<EnumType>::type>(value);
71}
72
73// Used internally by the framework to wake the Event FMQ. These values must start after
74// the last value of EventQueueFlagBits
75enum EventQueueFlagBitsInternal : uint32_t {
76 INTERNAL_WAKE = 1 << 16,
77};
78
Brian Duddie8e6f31c2019-05-29 13:19:13 -070079} // anonymous namespace
80
Brian Stack574cda32018-10-01 11:18:51 -070081void SensorsHalDeathReceivier::serviceDied(
82 uint64_t /* cookie */,
83 const wp<::android::hidl::base::V1_0::IBase>& /* service */) {
84 ALOGW("Sensors HAL died, attempting to reconnect.");
Brian Stack156da082018-10-01 15:58:53 -070085 SensorDevice::getInstance().prepareForReconnect();
Brian Stack574cda32018-10-01 11:18:51 -070086}
87
Brian Stackbbab1ea2018-10-01 10:49:07 -070088struct SensorsCallback : public ISensorsCallback {
89 using Result = ::android::hardware::sensors::V1_0::Result;
90 Return<void> onDynamicSensorsConnected(
91 const hidl_vec<SensorInfo> &dynamicSensorsAdded) override {
92 return SensorDevice::getInstance().onDynamicSensorsConnected(dynamicSensorsAdded);
93 }
94
95 Return<void> onDynamicSensorsDisconnected(
96 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) override {
97 return SensorDevice::getInstance().onDynamicSensorsDisconnected(
98 dynamicSensorHandlesRemoved);
99 }
100};
101
Peng Xu1a00e2d2017-09-27 23:08:30 -0700102SensorDevice::SensorDevice()
Brian Stack156da082018-10-01 15:58:53 -0700103 : mHidlTransportErrors(20),
104 mRestartWaiter(new HidlServiceRegistrationWaiter()),
Brian Stacka24e7d42019-01-08 12:56:09 -0800105 mEventQueueFlag(nullptr),
106 mWakeLockQueueFlag(nullptr),
Brian Stack156da082018-10-01 15:58:53 -0700107 mReconnecting(false) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700108 if (!connectHidlService()) {
109 return;
110 }
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700111
Brian Stack156da082018-10-01 15:58:53 -0700112 initializeSensorList();
113
114 mIsDirectReportSupported =
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700115 (checkReturnAndGetStatus(mSensors->unregisterDirectChannel(-1)) != INVALID_OPERATION);
Brian Stack156da082018-10-01 15:58:53 -0700116}
117
118void SensorDevice::initializeSensorList() {
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700119 float minPowerMa = 0.001; // 1 microAmp
120
Peng Xua8fad9b2017-03-17 12:20:27 -0700121 checkReturn(mSensors->getSensorsList(
122 [&](const auto &list) {
123 const size_t count = list.size();
124
125 mActivationCount.setCapacity(count);
126 Info model;
127 for (size_t i=0 ; i < count; i++) {
128 sensor_t sensor;
129 convertToSensor(list[i], &sensor);
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700130 // Sanity check and clamp power if it is 0 (or close)
131 if (sensor.power < minPowerMa) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700132 ALOGI("Reported power %f not deemed sane, clamping to %f",
Ashutosh Joshifea2d262017-04-19 23:27:49 -0700133 sensor.power, minPowerMa);
134 sensor.power = minPowerMa;
135 }
Peng Xua8fad9b2017-03-17 12:20:27 -0700136 mSensorList.push_back(sensor);
137
138 mActivationCount.add(list[i].sensorHandle, model);
139
Stan Rokita7c9d8952019-08-01 14:24:25 -0700140 // Only disable all sensors on HAL 1.0 since HAL 2.0
141 // handles this in its initialize method
142 if (!mSensors->supportsMessageQueues()) {
143 checkReturn(mSensors->activate(list[i].sensorHandle,
144 0 /* enabled */));
145 }
Peng Xua8fad9b2017-03-17 12:20:27 -0700146 }
147 }));
Peng Xua8fad9b2017-03-17 12:20:27 -0700148}
149
Brian Stacka28e9212018-09-19 15:20:30 -0700150SensorDevice::~SensorDevice() {
151 if (mEventQueueFlag != nullptr) {
152 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
153 mEventQueueFlag = nullptr;
154 }
Brian Stacka24e7d42019-01-08 12:56:09 -0800155
156 if (mWakeLockQueueFlag != nullptr) {
157 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
158 mWakeLockQueueFlag = nullptr;
159 }
Brian Stacka28e9212018-09-19 15:20:30 -0700160}
161
Peng Xua8fad9b2017-03-17 12:20:27 -0700162bool SensorDevice::connectHidlService() {
Brian Stack979887b2018-09-19 15:27:48 -0700163 HalConnectionStatus status = connectHidlServiceV2_0();
164 if (status == HalConnectionStatus::DOES_NOT_EXIST) {
165 status = connectHidlServiceV1_0();
Brian Stack12f4d322018-09-14 16:18:59 -0700166 }
Brian Stack979887b2018-09-19 15:27:48 -0700167 return (status == HalConnectionStatus::CONNECTED);
Brian Stack12f4d322018-09-14 16:18:59 -0700168}
169
Brian Stack979887b2018-09-19 15:27:48 -0700170SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV1_0() {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700171 // SensorDevice will wait for HAL service to start if HAL is declared in device manifest.
Peng Xu3889e6e2017-03-02 19:10:38 -0800172 size_t retry = 10;
Brian Stack979887b2018-09-19 15:27:48 -0700173 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Steven Morelandd15c0302016-12-20 11:14:50 -0800174
Peng Xu1a00e2d2017-09-27 23:08:30 -0700175 while (retry-- > 0) {
Brian Stack12f4d322018-09-14 16:18:59 -0700176 sp<V1_0::ISensors> sensors = V1_0::ISensors::getService();
177 if (sensors == nullptr) {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700178 // no sensor hidl service found
Brian Stack979887b2018-09-19 15:27:48 -0700179 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
Peng Xua8fad9b2017-03-17 12:20:27 -0700180 break;
Peng Xu3889e6e2017-03-02 19:10:38 -0800181 }
Peng Xu1a00e2d2017-09-27 23:08:30 -0700182
Brian Stack12f4d322018-09-14 16:18:59 -0700183 mSensors = new SensorServiceUtil::SensorsWrapperV1_0(sensors);
Peng Xu1a00e2d2017-09-27 23:08:30 -0700184 mRestartWaiter->reset();
185 // Poke ISensor service. If it has lingering connection from previous generation of
186 // system server, it will kill itself. There is no intention to handle the poll result,
187 // which will be done since the size is 0.
188 if(mSensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
189 // ok to continue
Brian Stack979887b2018-09-19 15:27:48 -0700190 connectionStatus = HalConnectionStatus::CONNECTED;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700191 break;
192 }
193
194 // hidl service is restarting, pointer is invalid.
195 mSensors = nullptr;
Brian Stack979887b2018-09-19 15:27:48 -0700196 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Peng Xu1a00e2d2017-09-27 23:08:30 -0700197 ALOGI("%s unsuccessful, remaining retry %zu.", __FUNCTION__, retry);
198 mRestartWaiter->wait();
Steven Morelandd15c0302016-12-20 11:14:50 -0800199 }
Brian Stack979887b2018-09-19 15:27:48 -0700200
201 return connectionStatus;
Steven Morelandd15c0302016-12-20 11:14:50 -0800202}
203
Brian Stack979887b2018-09-19 15:27:48 -0700204SensorDevice::HalConnectionStatus SensorDevice::connectHidlServiceV2_0() {
205 HalConnectionStatus connectionStatus = HalConnectionStatus::UNKNOWN;
Brian Stack12f4d322018-09-14 16:18:59 -0700206 sp<V2_0::ISensors> sensors = V2_0::ISensors::getService();
Brian Stack979887b2018-09-19 15:27:48 -0700207
208 if (sensors == nullptr) {
209 connectionStatus = HalConnectionStatus::DOES_NOT_EXIST;
210 } else {
Brian Stack12f4d322018-09-14 16:18:59 -0700211 mSensors = new SensorServiceUtil::SensorsWrapperV2_0(sensors);
212
Brian Stack979887b2018-09-19 15:27:48 -0700213 mEventQueue = std::make_unique<EventMessageQueue>(
214 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
215 true /* configureEventFlagWord */);
216
217 mWakeLockQueue = std::make_unique<WakeLockQueue>(
218 SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT,
219 true /* configureEventFlagWord */);
220
Brian Stacka24e7d42019-01-08 12:56:09 -0800221 hardware::EventFlag::deleteEventFlag(&mEventQueueFlag);
Brian Stacka28e9212018-09-19 15:20:30 -0700222 hardware::EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
223
Brian Stacka24e7d42019-01-08 12:56:09 -0800224 hardware::EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
225 hardware::EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(),
226 &mWakeLockQueueFlag);
227
Brian Stack979887b2018-09-19 15:27:48 -0700228 CHECK(mSensors != nullptr && mEventQueue != nullptr &&
Brian Stacka24e7d42019-01-08 12:56:09 -0800229 mWakeLockQueue != nullptr && mEventQueueFlag != nullptr &&
230 mWakeLockQueueFlag != nullptr);
Brian Stack979887b2018-09-19 15:27:48 -0700231
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700232 status_t status = checkReturnAndGetStatus(mSensors->initialize(
Brian Stack979887b2018-09-19 15:27:48 -0700233 *mEventQueue->getDesc(),
Brian Stack6c49e6f2018-09-24 15:44:32 -0700234 *mWakeLockQueue->getDesc(),
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700235 new SensorsCallback()));
Brian Stack979887b2018-09-19 15:27:48 -0700236
237 if (status != NO_ERROR) {
238 connectionStatus = HalConnectionStatus::FAILED_TO_CONNECT;
Brian Stack6c49e6f2018-09-24 15:44:32 -0700239 ALOGE("Failed to initialize Sensors HAL (%s)", strerror(-status));
Brian Stack979887b2018-09-19 15:27:48 -0700240 } else {
241 connectionStatus = HalConnectionStatus::CONNECTED;
Brian Stack574cda32018-10-01 11:18:51 -0700242 mSensorsHalDeathReceiver = new SensorsHalDeathReceivier();
243 sensors->linkToDeath(mSensorsHalDeathReceiver, 0 /* cookie */);
Brian Stack979887b2018-09-19 15:27:48 -0700244 }
Brian Stack12f4d322018-09-14 16:18:59 -0700245 }
Brian Stack979887b2018-09-19 15:27:48 -0700246
247 return connectionStatus;
Brian Stack12f4d322018-09-14 16:18:59 -0700248}
249
Brian Stack156da082018-10-01 15:58:53 -0700250void SensorDevice::prepareForReconnect() {
251 mReconnecting = true;
252
253 // Wake up the polling thread so it returns and allows the SensorService to initiate
254 // a reconnect.
255 mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
256}
257
258void SensorDevice::reconnect() {
259 Mutex::Autolock _l(mLock);
260 mSensors = nullptr;
261
262 auto previousActivations = mActivationCount;
263 auto previousSensorList = mSensorList;
264
265 mActivationCount.clear();
266 mSensorList.clear();
267
268 if (connectHidlServiceV2_0() == HalConnectionStatus::CONNECTED) {
269 initializeSensorList();
270
271 if (sensorHandlesChanged(previousSensorList, mSensorList)) {
272 LOG_ALWAYS_FATAL("Sensor handles changed, cannot re-enable sensors.");
273 } else {
274 reactivateSensors(previousActivations);
275 }
276 }
277 mReconnecting = false;
278}
279
280bool SensorDevice::sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
281 const Vector<sensor_t>& newSensorList) {
282 bool didChange = false;
283
284 if (oldSensorList.size() != newSensorList.size()) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700285 ALOGI("Sensor list size changed from %zu to %zu", oldSensorList.size(),
286 newSensorList.size());
Brian Stack156da082018-10-01 15:58:53 -0700287 didChange = true;
288 }
289
290 for (size_t i = 0; i < newSensorList.size() && !didChange; i++) {
291 bool found = false;
292 const sensor_t& newSensor = newSensorList[i];
293 for (size_t j = 0; j < oldSensorList.size() && !found; j++) {
294 const sensor_t& prevSensor = oldSensorList[j];
295 if (prevSensor.handle == newSensor.handle) {
296 found = true;
297 if (!sensorIsEquivalent(prevSensor, newSensor)) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700298 ALOGI("Sensor %s not equivalent to previous version", newSensor.name);
Brian Stack156da082018-10-01 15:58:53 -0700299 didChange = true;
300 }
301 }
302 }
303
304 if (!found) {
305 // Could not find the new sensor in the old list of sensors, the lists must
306 // have changed.
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700307 ALOGI("Sensor %s (handle %d) did not exist before", newSensor.name, newSensor.handle);
Brian Stack156da082018-10-01 15:58:53 -0700308 didChange = true;
309 }
310 }
311 return didChange;
312}
313
314bool SensorDevice::sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor) {
315 bool equivalent = true;
316 if (prevSensor.handle != newSensor.handle ||
317 (strcmp(prevSensor.vendor, newSensor.vendor) != 0) ||
318 (strcmp(prevSensor.stringType, newSensor.stringType) != 0) ||
319 (strcmp(prevSensor.requiredPermission, newSensor.requiredPermission) != 0) ||
320 (prevSensor.version != newSensor.version) ||
321 (prevSensor.type != newSensor.type) ||
322 (std::abs(prevSensor.maxRange - newSensor.maxRange) > 0.001f) ||
323 (std::abs(prevSensor.resolution - newSensor.resolution) > 0.001f) ||
324 (std::abs(prevSensor.power - newSensor.power) > 0.001f) ||
325 (prevSensor.minDelay != newSensor.minDelay) ||
326 (prevSensor.fifoReservedEventCount != newSensor.fifoReservedEventCount) ||
327 (prevSensor.fifoMaxEventCount != newSensor.fifoMaxEventCount) ||
328 (prevSensor.maxDelay != newSensor.maxDelay) ||
329 (prevSensor.flags != newSensor.flags)) {
330 equivalent = false;
331 }
332 return equivalent;
333}
334
335void SensorDevice::reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations) {
336 for (size_t i = 0; i < mSensorList.size(); i++) {
337 int handle = mSensorList[i].handle;
338 ssize_t activationIndex = previousActivations.indexOfKey(handle);
339 if (activationIndex < 0 || previousActivations[activationIndex].numActiveClients() <= 0) {
340 continue;
341 }
342
343 const Info& info = previousActivations[activationIndex];
344 for (size_t j = 0; j < info.batchParams.size(); j++) {
345 const BatchParams& batchParams = info.batchParams[j];
346 status_t res = batchLocked(info.batchParams.keyAt(j), handle, 0 /* flags */,
347 batchParams.mTSample, batchParams.mTBatch);
348
349 if (res == NO_ERROR) {
350 activateLocked(info.batchParams.keyAt(j), handle, true /* enabled */);
351 }
352 }
353 }
354}
355
Peng Xu2576cb62016-01-20 00:22:09 -0800356void SensorDevice::handleDynamicSensorConnection(int handle, bool connected) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700357 // not need to check mSensors because this is is only called after successful poll()
Peng Xu2576cb62016-01-20 00:22:09 -0800358 if (connected) {
359 Info model;
360 mActivationCount.add(handle, model);
Peng Xu3889e6e2017-03-02 19:10:38 -0800361 checkReturn(mSensors->activate(handle, 0 /* enabled */));
Peng Xu2576cb62016-01-20 00:22:09 -0800362 } else {
363 mActivationCount.removeItem(handle);
364 }
365}
366
Peng Xu6a2d3a02015-12-21 12:00:23 -0800367std::string SensorDevice::dump() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700368 if (mSensors == nullptr) return "HAL not initialized\n";
Mathias Agopianf001c922010-11-11 17:58:51 -0800369
Peng Xu6a2d3a02015-12-21 12:00:23 -0800370 String8 result;
Peng Xua8fad9b2017-03-17 12:20:27 -0700371 result.appendFormat("Total %zu h/w sensors, %zu running:\n",
372 mSensorList.size(), mActivationCount.size());
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700373
Peng Xua8fad9b2017-03-17 12:20:27 -0700374 Mutex::Autolock _l(mLock);
375 for (const auto & s : mSensorList) {
376 int32_t handle = s.handle;
377 const Info& info = mActivationCount.valueFor(handle);
Brian Stackbce04d72019-03-21 10:54:10 -0700378 if (info.numActiveClients() == 0) continue;
Peng Xua8fad9b2017-03-17 12:20:27 -0700379
380 result.appendFormat("0x%08x) active-count = %zu; ", handle, info.batchParams.size());
381
382 result.append("sampling_period(ms) = {");
383 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700384 const BatchParams& params = info.batchParams[j];
385 result.appendFormat("%.1f%s", params.mTSample / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700386 j < info.batchParams.size() - 1 ? ", " : "");
387 }
Peng Xu2bec6232016-07-01 17:13:10 -0700388 result.appendFormat("}, selected = %.2f ms; ", info.bestBatchParams.mTSample / 1e6f);
Peng Xua8fad9b2017-03-17 12:20:27 -0700389
390 result.append("batching_period(ms) = {");
391 for (size_t j = 0; j < info.batchParams.size(); j++) {
Peng Xu2bec6232016-07-01 17:13:10 -0700392 const BatchParams& params = info.batchParams[j];
393 result.appendFormat("%.1f%s", params.mTBatch / 1e6f,
Peng Xua8fad9b2017-03-17 12:20:27 -0700394 j < info.batchParams.size() - 1 ? ", " : "");
395 }
Peng Xu2bec6232016-07-01 17:13:10 -0700396 result.appendFormat("}, selected = %.2f ms\n", info.bestBatchParams.mTBatch / 1e6f);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700397 }
398
Peng Xu6a2d3a02015-12-21 12:00:23 -0800399 return result.string();
Mathias Agopianf001c922010-11-11 17:58:51 -0800400}
401
Mike Ma24743862020-01-29 00:36:55 -0800402/**
403 * Dump debugging information as android.service.SensorDeviceProto protobuf message using
404 * ProtoOutputStream.
405 *
406 * See proto definition and some notes about ProtoOutputStream in
407 * frameworks/base/core/proto/android/service/sensor_service.proto
408 */
409void SensorDevice::dump(ProtoOutputStream* proto) const {
410 using namespace service::SensorDeviceProto;
411 if (mSensors == nullptr) {
412 proto->write(INITIALIZED , false);
413 return;
414 }
415 proto->write(INITIALIZED , true);
416 proto->write(TOTAL_SENSORS , int(mSensorList.size()));
417 proto->write(ACTIVE_SENSORS , int(mActivationCount.size()));
418
419 Mutex::Autolock _l(mLock);
420 for (const auto & s : mSensorList) {
421 int32_t handle = s.handle;
422 const Info& info = mActivationCount.valueFor(handle);
423 if (info.numActiveClients() == 0) continue;
424
425 uint64_t token = proto->start(SENSORS);
426 proto->write(SensorProto::HANDLE , handle);
427 proto->write(SensorProto::ACTIVE_COUNT , int(info.batchParams.size()));
428 for (size_t j = 0; j < info.batchParams.size(); j++) {
429 const BatchParams& params = info.batchParams[j];
430 proto->write(SensorProto::SAMPLING_PERIOD_MS , params.mTSample / 1e6f);
431 proto->write(SensorProto::BATCHING_PERIOD_MS , params.mTBatch / 1e6f);
432 }
433 proto->write(SensorProto::SAMPLING_PERIOD_SELECTED , info.bestBatchParams.mTSample / 1e6f);
434 proto->write(SensorProto::BATCHING_PERIOD_SELECTED , info.bestBatchParams.mTBatch / 1e6f);
435 proto->end(token);
436 }
437}
438
Mathias Agopianf001c922010-11-11 17:58:51 -0800439ssize_t SensorDevice::getSensorList(sensor_t const** list) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800440 *list = &mSensorList[0];
441
442 return mSensorList.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800443}
444
445status_t SensorDevice::initCheck() const {
Peng Xu1a00e2d2017-09-27 23:08:30 -0700446 return mSensors != nullptr ? NO_ERROR : NO_INIT;
Mathias Agopianf001c922010-11-11 17:58:51 -0800447}
448
449ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) {
Brian Stack156da082018-10-01 15:58:53 -0700450 if (mSensors == nullptr) return NO_INIT;
451
Brian Stacka28e9212018-09-19 15:20:30 -0700452 ssize_t eventsRead = 0;
453 if (mSensors->supportsMessageQueues()) {
454 eventsRead = pollFmq(buffer, count);
455 } else if (mSensors->supportsPolling()) {
456 eventsRead = pollHal(buffer, count);
457 } else {
458 ALOGE("Must support polling or FMQ");
459 eventsRead = -1;
460 }
461 return eventsRead;
462}
463
464ssize_t SensorDevice::pollHal(sensors_event_t* buffer, size_t count) {
Steven Morelandd15c0302016-12-20 11:14:50 -0800465 ssize_t err;
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700466 int numHidlTransportErrors = 0;
467 bool hidlTransportError = false;
Steven Morelandd15c0302016-12-20 11:14:50 -0800468
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700469 do {
470 auto ret = mSensors->poll(
471 count,
472 [&](auto result,
473 const auto &events,
474 const auto &dynamicSensorsAdded) {
475 if (result == Result::OK) {
476 convertToSensorEvents(events, dynamicSensorsAdded, buffer);
477 err = (ssize_t)events.size();
478 } else {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700479 err = statusFromResult(result);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700480 }
481 });
482
483 if (ret.isOk()) {
484 hidlTransportError = false;
485 } else {
486 hidlTransportError = true;
487 numHidlTransportErrors++;
488 if (numHidlTransportErrors > 50) {
489 // Log error and bail
490 ALOGE("Max Hidl transport errors this cycle : %d", numHidlTransportErrors);
491 handleHidlDeath(ret.description());
492 } else {
493 std::this_thread::sleep_for(std::chrono::milliseconds(10));
494 }
495 }
496 } while (hidlTransportError);
497
498 if(numHidlTransportErrors > 0) {
499 ALOGE("Saw %d Hidl transport failures", numHidlTransportErrors);
Yi Kong8f313e32018-07-17 14:13:29 -0700500 HidlTransportErrorLog errLog(time(nullptr), numHidlTransportErrors);
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700501 mHidlTransportErrors.add(errLog);
502 mTotalHidlTransportErrors++;
503 }
Steven Morelandd15c0302016-12-20 11:14:50 -0800504
505 return err;
Mathias Agopianf001c922010-11-11 17:58:51 -0800506}
507
Brian Stacka28e9212018-09-19 15:20:30 -0700508ssize_t SensorDevice::pollFmq(sensors_event_t* buffer, size_t maxNumEventsToRead) {
Brian Stacka28e9212018-09-19 15:20:30 -0700509 ssize_t eventsRead = 0;
510 size_t availableEvents = mEventQueue->availableToRead();
511
512 if (availableEvents == 0) {
513 uint32_t eventFlagState = 0;
514
515 // Wait for events to become available. This is necessary so that the Event FMQ's read() is
516 // able to be called with the correct number of events to read. If the specified number of
517 // events is not available, then read() would return no events, possibly introducing
518 // additional latency in delivering events to applications.
Brian Stack156da082018-10-01 15:58:53 -0700519 mEventQueueFlag->wait(asBaseType(EventQueueFlagBits::READ_AND_PROCESS) |
520 asBaseType(INTERNAL_WAKE), &eventFlagState);
Brian Stacka28e9212018-09-19 15:20:30 -0700521 availableEvents = mEventQueue->availableToRead();
522
Brian Stack156da082018-10-01 15:58:53 -0700523 if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
524 ALOGD("Event FMQ internal wake, returning from poll with no events");
525 return DEAD_OBJECT;
526 }
Brian Stacka28e9212018-09-19 15:20:30 -0700527 }
528
529 size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
530 if (eventsToRead > 0) {
531 if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
Brian Stackaf1b54c2018-11-09 10:20:01 -0800532 // Notify the Sensors HAL that sensor events have been read. This is required to support
533 // the use of writeBlocking by the Sensors HAL.
534 mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
535
Brian Stacka28e9212018-09-19 15:20:30 -0700536 for (size_t i = 0; i < eventsToRead; i++) {
537 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
538 }
539 eventsRead = eventsToRead;
540 } else {
541 ALOGW("Failed to read %zu events, currently %zu events available",
542 eventsToRead, availableEvents);
543 }
544 }
545
546 return eventsRead;
547}
548
Brian Stack6c49e6f2018-09-24 15:44:32 -0700549Return<void> SensorDevice::onDynamicSensorsConnected(
550 const hidl_vec<SensorInfo> &dynamicSensorsAdded) {
551 // Allocate a sensor_t structure for each dynamic sensor added and insert
552 // it into the dictionary of connected dynamic sensors keyed by handle.
553 for (size_t i = 0; i < dynamicSensorsAdded.size(); ++i) {
554 const SensorInfo &info = dynamicSensorsAdded[i];
555
556 auto it = mConnectedDynamicSensors.find(info.sensorHandle);
557 CHECK(it == mConnectedDynamicSensors.end());
558
559 sensor_t *sensor = new sensor_t();
560 convertToSensor(info, sensor);
561
562 mConnectedDynamicSensors.insert(
563 std::make_pair(sensor->handle, sensor));
564 }
565
566 return Return<void>();
567}
568
569Return<void> SensorDevice::onDynamicSensorsDisconnected(
570 const hidl_vec<int32_t> &dynamicSensorHandlesRemoved) {
571 (void) dynamicSensorHandlesRemoved;
572 // TODO: Currently dynamic sensors do not seem to be removed
573 return Return<void>();
574}
575
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700576void SensorDevice::writeWakeLockHandled(uint32_t count) {
Brian Stacka24e7d42019-01-08 12:56:09 -0800577 if (mSensors != nullptr && mSensors->supportsMessageQueues()) {
578 if (mWakeLockQueue->write(&count)) {
579 mWakeLockQueueFlag->wake(asBaseType(WakeLockQueueFlagBits::DATA_WRITTEN));
580 } else {
581 ALOGW("Failed to write wake lock handled");
582 }
Brian Stackb7bfc0f2018-09-25 09:41:16 -0700583 }
584}
585
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700586void SensorDevice::autoDisable(void *ident, int handle) {
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700587 Mutex::Autolock _l(mLock);
Peng Xu042baec2017-08-09 19:28:27 -0700588 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
589 if (activationIndex < 0) {
590 ALOGW("Handle %d cannot be found in activation record", handle);
591 return;
592 }
593 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700594 info.removeBatchParamsForIdent(ident);
Brian Stackaa6dc092019-05-10 13:36:40 -0700595 if (info.numActiveClients() == 0) {
596 info.isActive = false;
597 }
Jaikumar Ganesh4c01b1a2013-04-16 15:52:23 -0700598}
599
Peng Xu6a2d3a02015-12-21 12:00:23 -0800600status_t SensorDevice::activate(void* ident, int handle, int enabled) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700601 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800602
Brian Stack156da082018-10-01 15:58:53 -0700603 Mutex::Autolock _l(mLock);
604 return activateLocked(ident, handle, enabled);
605}
606
607status_t SensorDevice::activateLocked(void* ident, int handle, int enabled) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800608 bool actuateHardware = false;
609
Brian Stack156da082018-10-01 15:58:53 -0700610 status_t err(NO_ERROR);
611
Peng Xu042baec2017-08-09 19:28:27 -0700612 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
613 if (activationIndex < 0) {
614 ALOGW("Handle %d cannot be found in activation record", handle);
615 return BAD_VALUE;
616 }
617 Info& info(mActivationCount.editValueAt(activationIndex));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700618
Steve Blocka5512372011-12-20 16:23:08 +0000619 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700620 "SensorDevice::activate: ident=%p, handle=0x%08x, enabled=%d, count=%zu",
Aravind Akella724d91d2013-06-27 12:04:23 -0700621 ident, handle, enabled, info.batchParams.size());
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700622
Mathias Agopianf001c922010-11-11 17:58:51 -0800623 if (enabled) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700624 ALOGD_IF(DEBUG_CONNECTIONS, "enable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700625
Aravind Akella4949c502015-02-11 15:54:35 -0800626 if (isClientDisabledLocked(ident)) {
Peng Xu966fa882016-09-01 16:13:15 -0700627 ALOGE("SensorDevice::activate, isClientDisabledLocked(%p):true, handle:%d",
628 ident, handle);
Aravind Akella4949c502015-02-11 15:54:35 -0800629 return INVALID_OPERATION;
630 }
631
Aravind Akella724d91d2013-06-27 12:04:23 -0700632 if (info.batchParams.indexOfKey(ident) >= 0) {
Brian Stack0c305fe2019-04-09 12:49:24 -0700633 if (info.numActiveClients() > 0 && !info.isActive) {
634 actuateHardware = true;
635 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800636 } else {
Aravind Akella724d91d2013-06-27 12:04:23 -0700637 // Log error. Every activate call should be preceded by a batch() call.
638 ALOGE("\t >>>ERROR: activate called without batch");
Mathias Agopianf001c922010-11-11 17:58:51 -0800639 }
640 } else {
Mark Salyzyndb458612014-06-10 14:50:02 -0700641 ALOGD_IF(DEBUG_CONNECTIONS, "disable index=%zd", info.batchParams.indexOfKey(ident));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700642
Steven Morelandd15c0302016-12-20 11:14:50 -0800643 // If a connected dynamic sensor is deactivated, remove it from the
644 // dictionary.
645 auto it = mConnectedDynamicSensors.find(handle);
646 if (it != mConnectedDynamicSensors.end()) {
647 delete it->second;
648 mConnectedDynamicSensors.erase(it);
649 }
650
Aravind Akella724d91d2013-06-27 12:04:23 -0700651 if (info.removeBatchParamsForIdent(ident) >= 0) {
Aravind Akella4949c502015-02-11 15:54:35 -0800652 if (info.numActiveClients() == 0) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700653 // This is the last connection, we need to de-activate the underlying h/w sensor.
Mathias Agopian50b66762010-11-29 17:26:51 -0800654 actuateHardware = true;
Aravind Akella724d91d2013-06-27 12:04:23 -0700655 } else {
Steven Morelandd15c0302016-12-20 11:14:50 -0800656 // Call batch for this sensor with the previously calculated best effort
657 // batch_rate and timeout. One of the apps has unregistered for sensor
658 // events, and the best effort batch parameters might have changed.
659 ALOGD_IF(DEBUG_CONNECTIONS,
Peng Xu2bec6232016-07-01 17:13:10 -0700660 "\t>>> actuating h/w batch 0x%08x %" PRId64 " %" PRId64, handle,
661 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Peng Xu3889e6e2017-03-02 19:10:38 -0800662 checkReturn(mSensors->batch(
Peng Xu2bec6232016-07-01 17:13:10 -0700663 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Mathias Agopian50b66762010-11-29 17:26:51 -0800664 }
665 } else {
666 // sensor wasn't enabled for this ident
667 }
Aravind Akella4949c502015-02-11 15:54:35 -0800668
669 if (isClientDisabledLocked(ident)) {
670 return NO_ERROR;
671 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800672 }
Mathias Agopian50b66762010-11-29 17:26:51 -0800673
Mathias Agopianf001c922010-11-11 17:58:51 -0800674 if (actuateHardware) {
Aravind Akella4949c502015-02-11 15:54:35 -0800675 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w activate handle=%d enabled=%d", handle,
676 enabled);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700677 err = checkReturnAndGetStatus(mSensors->activate(handle, enabled));
Aravind Akella724d91d2013-06-27 12:04:23 -0700678 ALOGE_IF(err, "Error %s sensor %d (%s)", enabled ? "activating" : "disabling", handle,
679 strerror(-err));
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700680
Aravind Akella724d91d2013-06-27 12:04:23 -0700681 if (err != NO_ERROR && enabled) {
682 // Failure when enabling the sensor. Clean up on failure.
683 info.removeBatchParamsForIdent(ident);
Brian Stack0c305fe2019-04-09 12:49:24 -0700684 } else {
685 // Update the isActive flag if there is no error. If there is an error when disabling a
686 // sensor, still set the flag to false since the batch parameters have already been
687 // removed. This ensures that everything remains in-sync.
688 info.isActive = enabled;
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700689 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800690 }
691
Mathias Agopianf001c922010-11-11 17:58:51 -0800692 return err;
693}
694
Steven Morelandd15c0302016-12-20 11:14:50 -0800695status_t SensorDevice::batch(
696 void* ident,
697 int handle,
698 int flags,
699 int64_t samplingPeriodNs,
700 int64_t maxBatchReportLatencyNs) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700701 if (mSensors == nullptr) return NO_INIT;
Aravind Akella724d91d2013-06-27 12:04:23 -0700702
703 if (samplingPeriodNs < MINIMUM_EVENTS_PERIOD) {
704 samplingPeriodNs = MINIMUM_EVENTS_PERIOD;
705 }
Peng Xu2bec6232016-07-01 17:13:10 -0700706 if (maxBatchReportLatencyNs < 0) {
707 maxBatchReportLatencyNs = 0;
708 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700709
Aravind Akella724d91d2013-06-27 12:04:23 -0700710 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700711 "SensorDevice::batch: ident=%p, handle=0x%08x, flags=%d, period_ns=%" PRId64 " timeout=%" PRId64,
Aravind Akella724d91d2013-06-27 12:04:23 -0700712 ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
713
714 Mutex::Autolock _l(mLock);
Brian Stack156da082018-10-01 15:58:53 -0700715 return batchLocked(ident, handle, flags, samplingPeriodNs, maxBatchReportLatencyNs);
716}
717
718status_t SensorDevice::batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
719 int64_t maxBatchReportLatencyNs) {
Peng Xu042baec2017-08-09 19:28:27 -0700720 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
721 if (activationIndex < 0) {
722 ALOGW("Handle %d cannot be found in activation record", handle);
723 return BAD_VALUE;
724 }
725 Info& info(mActivationCount.editValueAt(activationIndex));
Aravind Akella724d91d2013-06-27 12:04:23 -0700726
727 if (info.batchParams.indexOfKey(ident) < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700728 BatchParams params(samplingPeriodNs, maxBatchReportLatencyNs);
Aravind Akella724d91d2013-06-27 12:04:23 -0700729 info.batchParams.add(ident, params);
730 } else {
731 // A batch has already been called with this ident. Update the batch parameters.
732 info.setBatchParamsForIdent(ident, flags, samplingPeriodNs, maxBatchReportLatencyNs);
733 }
734
735 BatchParams prevBestBatchParams = info.bestBatchParams;
736 // Find the minimum of all timeouts and batch_rates for this sensor.
737 info.selectBatchParams();
738
739 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700740 "\t>>> curr_period=%" PRId64 " min_period=%" PRId64
741 " curr_timeout=%" PRId64 " min_timeout=%" PRId64,
Peng Xu2bec6232016-07-01 17:13:10 -0700742 prevBestBatchParams.mTSample, info.bestBatchParams.mTSample,
743 prevBestBatchParams.mTBatch, info.bestBatchParams.mTBatch);
Aravind Akella724d91d2013-06-27 12:04:23 -0700744
745 status_t err(NO_ERROR);
746 // If the min period or min timeout has changed since the last batch call, call batch.
747 if (prevBestBatchParams != info.bestBatchParams) {
Peng Xu2bec6232016-07-01 17:13:10 -0700748 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w BATCH 0x%08x %" PRId64 " %" PRId64, handle,
749 info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700750 err = checkReturnAndGetStatus(mSensors->batch(
751 handle, info.bestBatchParams.mTSample, info.bestBatchParams.mTBatch));
Aravind Akella724d91d2013-06-27 12:04:23 -0700752 if (err != NO_ERROR) {
Peng Xu2bec6232016-07-01 17:13:10 -0700753 ALOGE("sensor batch failed %p 0x%08x %" PRId64 " %" PRId64 " err=%s",
754 mSensors.get(), handle, info.bestBatchParams.mTSample,
755 info.bestBatchParams.mTBatch, strerror(-err));
Aravind Akella724d91d2013-06-27 12:04:23 -0700756 info.removeBatchParamsForIdent(ident);
757 }
758 }
759 return err;
760}
761
Peng Xu6a2d3a02015-12-21 12:00:23 -0800762status_t SensorDevice::setDelay(void* ident, int handle, int64_t samplingPeriodNs) {
Peng Xu2bec6232016-07-01 17:13:10 -0700763 return batch(ident, handle, 0, samplingPeriodNs, 0);
Mathias Agopian667102f2011-09-14 16:43:34 -0700764}
765
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700766int SensorDevice::getHalDeviceVersion() const {
Peng Xua8fad9b2017-03-17 12:20:27 -0700767 if (mSensors == nullptr) return -1;
Steven Morelandd15c0302016-12-20 11:14:50 -0800768 return SENSORS_DEVICE_API_VERSION_1_4;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700769}
770
Aravind Akella9a844cf2014-02-11 18:58:52 -0800771status_t SensorDevice::flush(void* ident, int handle) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700772 if (mSensors == nullptr) return NO_INIT;
Aravind Akella4949c502015-02-11 15:54:35 -0800773 if (isClientDisabled(ident)) return INVALID_OPERATION;
Aravind Akella724d91d2013-06-27 12:04:23 -0700774 ALOGD_IF(DEBUG_CONNECTIONS, "\t>>> actuating h/w flush %d", handle);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700775 return checkReturnAndGetStatus(mSensors->flush(handle));
Aravind Akella724d91d2013-06-27 12:04:23 -0700776}
777
Aravind Akella4949c502015-02-11 15:54:35 -0800778bool SensorDevice::isClientDisabled(void* ident) {
779 Mutex::Autolock _l(mLock);
780 return isClientDisabledLocked(ident);
781}
782
783bool SensorDevice::isClientDisabledLocked(void* ident) {
784 return mDisabledClients.indexOf(ident) >= 0;
785}
786
Brian Stackbce04d72019-03-21 10:54:10 -0700787bool SensorDevice::isSensorActive(int handle) const {
788 Mutex::Autolock _l(mLock);
789 ssize_t activationIndex = mActivationCount.indexOfKey(handle);
790 if (activationIndex < 0) {
791 return false;
792 }
793 return mActivationCount.valueAt(activationIndex).numActiveClients() > 0;
794}
795
Aravind Akella4949c502015-02-11 15:54:35 -0800796void SensorDevice::enableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700797 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800798 Mutex::Autolock _l(mLock);
799 mDisabledClients.clear();
Peng Xu966fa882016-09-01 16:13:15 -0700800 ALOGI("cleared mDisabledClients");
Aravind Akella4949c502015-02-11 15:54:35 -0800801 for (size_t i = 0; i< mActivationCount.size(); ++i) {
802 Info& info = mActivationCount.editValueAt(i);
803 if (info.batchParams.isEmpty()) continue;
804 info.selectBatchParams();
805 const int sensor_handle = mActivationCount.keyAt(i);
806 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> reenable actuating h/w sensor enable handle=%d ",
807 sensor_handle);
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700808 status_t err = checkReturnAndGetStatus(mSensors->batch(
809 sensor_handle,
810 info.bestBatchParams.mTSample,
811 info.bestBatchParams.mTBatch));
Steven Morelandd15c0302016-12-20 11:14:50 -0800812 ALOGE_IF(err, "Error calling batch on sensor %d (%s)", sensor_handle, strerror(-err));
Aravind Akella4949c502015-02-11 15:54:35 -0800813
814 if (err == NO_ERROR) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700815 err = checkReturnAndGetStatus(mSensors->activate(sensor_handle, 1 /* enabled */));
Aravind Akella4949c502015-02-11 15:54:35 -0800816 ALOGE_IF(err, "Error activating sensor %d (%s)", sensor_handle, strerror(-err));
817 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700818
819 if (err == NO_ERROR) {
820 info.isActive = true;
821 }
Aravind Akella4949c502015-02-11 15:54:35 -0800822 }
823}
824
825void SensorDevice::disableAllSensors() {
Peng Xua8fad9b2017-03-17 12:20:27 -0700826 if (mSensors == nullptr) return;
Aravind Akella4949c502015-02-11 15:54:35 -0800827 Mutex::Autolock _l(mLock);
Peng Xua8fad9b2017-03-17 12:20:27 -0700828 for (size_t i = 0; i< mActivationCount.size(); ++i) {
Brian Stack4a11fed2019-04-22 15:07:50 -0700829 Info& info = mActivationCount.editValueAt(i);
Aravind Akella4949c502015-02-11 15:54:35 -0800830 // Check if this sensor has been activated previously and disable it.
831 if (info.batchParams.size() > 0) {
832 const int sensor_handle = mActivationCount.keyAt(i);
833 ALOGD_IF(DEBUG_CONNECTIONS, "\t>> actuating h/w sensor disable handle=%d ",
834 sensor_handle);
Peng Xu3889e6e2017-03-02 19:10:38 -0800835 checkReturn(mSensors->activate(sensor_handle, 0 /* enabled */));
Steven Morelandd15c0302016-12-20 11:14:50 -0800836
Aravind Akella4949c502015-02-11 15:54:35 -0800837 // Add all the connections that were registered for this sensor to the disabled
838 // clients list.
Svetoslavb412f6e2015-04-29 16:50:41 -0700839 for (size_t j = 0; j < info.batchParams.size(); ++j) {
Aravind Akella4949c502015-02-11 15:54:35 -0800840 mDisabledClients.add(info.batchParams.keyAt(j));
Peng Xu966fa882016-09-01 16:13:15 -0700841 ALOGI("added %p to mDisabledClients", info.batchParams.keyAt(j));
Aravind Akella4949c502015-02-11 15:54:35 -0800842 }
Brian Stack4a11fed2019-04-22 15:07:50 -0700843
844 info.isActive = false;
Aravind Akella4949c502015-02-11 15:54:35 -0800845 }
846 }
847}
848
Steven Morelandd15c0302016-12-20 11:14:50 -0800849status_t SensorDevice::injectSensorData(
850 const sensors_event_t *injected_sensor_event) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700851 if (mSensors == nullptr) return NO_INIT;
Steven Morelandd15c0302016-12-20 11:14:50 -0800852 ALOGD_IF(DEBUG_CONNECTIONS,
853 "sensor_event handle=%d ts=%" PRId64 " data=%.2f, %.2f, %.2f %.2f %.2f %.2f",
854 injected_sensor_event->sensor,
855 injected_sensor_event->timestamp, injected_sensor_event->data[0],
856 injected_sensor_event->data[1], injected_sensor_event->data[2],
857 injected_sensor_event->data[3], injected_sensor_event->data[4],
858 injected_sensor_event->data[5]);
859
860 Event ev;
861 convertFromSensorEvent(*injected_sensor_event, &ev);
862
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700863 return checkReturnAndGetStatus(mSensors->injectSensorData(ev));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700864}
865
866status_t SensorDevice::setMode(uint32_t mode) {
Peng Xua8fad9b2017-03-17 12:20:27 -0700867 if (mSensors == nullptr) return NO_INIT;
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700868 return checkReturnAndGetStatus(mSensors->setOperationMode(
869 static_cast<hardware::sensors::V1_0::OperationMode>(mode)));
Peng Xua8fad9b2017-03-17 12:20:27 -0700870}
Steven Morelandd15c0302016-12-20 11:14:50 -0800871
Peng Xua8fad9b2017-03-17 12:20:27 -0700872int32_t SensorDevice::registerDirectChannel(const sensors_direct_mem_t* memory) {
873 if (mSensors == nullptr) return NO_INIT;
874 Mutex::Autolock _l(mLock);
875
876 SharedMemType type;
877 switch (memory->type) {
878 case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
879 type = SharedMemType::ASHMEM;
880 break;
881 case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
882 type = SharedMemType::GRALLOC;
883 break;
884 default:
885 return BAD_VALUE;
886 }
887
888 SharedMemFormat format;
889 if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
890 return BAD_VALUE;
891 }
892 format = SharedMemFormat::SENSORS_EVENT;
893
894 SharedMemInfo mem = {
895 .type = type,
896 .format = format,
897 .size = static_cast<uint32_t>(memory->size),
898 .memoryHandle = memory->handle,
899 };
900
901 int32_t ret;
902 checkReturn(mSensors->registerDirectChannel(mem,
903 [&ret](auto result, auto channelHandle) {
904 if (result == Result::OK) {
905 ret = channelHandle;
906 } else {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700907 ret = statusFromResult(result);
Peng Xua8fad9b2017-03-17 12:20:27 -0700908 }
909 }));
910 return ret;
911}
912
913void SensorDevice::unregisterDirectChannel(int32_t channelHandle) {
914 if (mSensors == nullptr) return;
915 Mutex::Autolock _l(mLock);
916 checkReturn(mSensors->unregisterDirectChannel(channelHandle));
917}
918
919int32_t SensorDevice::configureDirectChannel(int32_t sensorHandle,
920 int32_t channelHandle, const struct sensors_direct_cfg_t *config) {
921 if (mSensors == nullptr) return NO_INIT;
922 Mutex::Autolock _l(mLock);
923
924 RateLevel rate;
925 switch(config->rate_level) {
926 case SENSOR_DIRECT_RATE_STOP:
927 rate = RateLevel::STOP;
928 break;
929 case SENSOR_DIRECT_RATE_NORMAL:
930 rate = RateLevel::NORMAL;
931 break;
932 case SENSOR_DIRECT_RATE_FAST:
933 rate = RateLevel::FAST;
934 break;
935 case SENSOR_DIRECT_RATE_VERY_FAST:
936 rate = RateLevel::VERY_FAST;
937 break;
938 default:
939 return BAD_VALUE;
940 }
941
942 int32_t ret;
943 checkReturn(mSensors->configDirectReport(sensorHandle, channelHandle, rate,
944 [&ret, rate] (auto result, auto token) {
945 if (rate == RateLevel::STOP) {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700946 ret = statusFromResult(result);
Peng Xua8fad9b2017-03-17 12:20:27 -0700947 } else {
948 if (result == Result::OK) {
949 ret = token;
950 } else {
Brian Duddie8e6f31c2019-05-29 13:19:13 -0700951 ret = statusFromResult(result);
Peng Xua8fad9b2017-03-17 12:20:27 -0700952 }
953 }
954 }));
955
956 return ret;
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700957}
958
Mathias Agopian667102f2011-09-14 16:43:34 -0700959// ---------------------------------------------------------------------------
960
Brian Stack156da082018-10-01 15:58:53 -0700961int SensorDevice::Info::numActiveClients() const {
Aravind Akella4949c502015-02-11 15:54:35 -0800962 SensorDevice& device(SensorDevice::getInstance());
963 int num = 0;
964 for (size_t i = 0; i < batchParams.size(); ++i) {
965 if (!device.isClientDisabledLocked(batchParams.keyAt(i))) {
966 ++num;
967 }
968 }
969 return num;
970}
971
Peng Xu2bec6232016-07-01 17:13:10 -0700972status_t SensorDevice::Info::setBatchParamsForIdent(void* ident, int,
Aravind Akella724d91d2013-06-27 12:04:23 -0700973 int64_t samplingPeriodNs,
974 int64_t maxBatchReportLatencyNs) {
975 ssize_t index = batchParams.indexOfKey(ident);
Mathias Agopian667102f2011-09-14 16:43:34 -0700976 if (index < 0) {
Peng Xu2bec6232016-07-01 17:13:10 -0700977 ALOGE("Info::setBatchParamsForIdent(ident=%p, period_ns=%" PRId64
978 " timeout=%" PRId64 ") failed (%s)",
Aravind Akella724d91d2013-06-27 12:04:23 -0700979 ident, samplingPeriodNs, maxBatchReportLatencyNs, strerror(-index));
Mathias Agopian667102f2011-09-14 16:43:34 -0700980 return BAD_INDEX;
981 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700982 BatchParams& params = batchParams.editValueAt(index);
Peng Xu2bec6232016-07-01 17:13:10 -0700983 params.mTSample = samplingPeriodNs;
984 params.mTBatch = maxBatchReportLatencyNs;
Mathias Agopian667102f2011-09-14 16:43:34 -0700985 return NO_ERROR;
986}
987
Aravind Akella724d91d2013-06-27 12:04:23 -0700988void SensorDevice::Info::selectBatchParams() {
Peng Xu2bec6232016-07-01 17:13:10 -0700989 BatchParams bestParams; // default to max Tsample and max Tbatch
Aravind Akella4949c502015-02-11 15:54:35 -0800990 SensorDevice& device(SensorDevice::getInstance());
Aravind Akella724d91d2013-06-27 12:04:23 -0700991
Aravind Akella4949c502015-02-11 15:54:35 -0800992 for (size_t i = 0; i < batchParams.size(); ++i) {
Peng Xu2bec6232016-07-01 17:13:10 -0700993 if (device.isClientDisabledLocked(batchParams.keyAt(i))) {
994 continue;
Aravind Akella724d91d2013-06-27 12:04:23 -0700995 }
Peng Xu2bec6232016-07-01 17:13:10 -0700996 bestParams.merge(batchParams[i]);
997 }
998 // if mTBatch <= mTSample, it is in streaming mode. set mTbatch to 0 to demand this explicitly.
999 if (bestParams.mTBatch <= bestParams.mTSample) {
1000 bestParams.mTBatch = 0;
Mathias Agopianf001c922010-11-11 17:58:51 -08001001 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001002 bestBatchParams = bestParams;
1003}
1004
1005ssize_t SensorDevice::Info::removeBatchParamsForIdent(void* ident) {
1006 ssize_t idx = batchParams.removeItem(ident);
1007 if (idx >= 0) {
1008 selectBatchParams();
1009 }
1010 return idx;
Mathias Agopianf001c922010-11-11 17:58:51 -08001011}
1012
Peng Xu4f707f82016-09-26 11:28:32 -07001013void SensorDevice::notifyConnectionDestroyed(void* ident) {
1014 Mutex::Autolock _l(mLock);
1015 mDisabledClients.remove(ident);
1016}
1017
Peng Xu53632542017-01-23 20:06:27 -08001018bool SensorDevice::isDirectReportSupported() const {
Steven Morelandd15c0302016-12-20 11:14:50 -08001019 return mIsDirectReportSupported;
Peng Xu53632542017-01-23 20:06:27 -08001020}
Steven Morelandd15c0302016-12-20 11:14:50 -08001021
1022void SensorDevice::convertToSensorEvent(
1023 const Event &src, sensors_event_t *dst) {
1024 ::android::hardware::sensors::V1_0::implementation::convertToSensorEvent(
1025 src, dst);
1026
1027 if (src.sensorType == SensorType::DYNAMIC_SENSOR_META) {
1028 const DynamicSensorInfo &dyn = src.u.dynamic;
1029
1030 dst->dynamic_sensor_meta.connected = dyn.connected;
1031 dst->dynamic_sensor_meta.handle = dyn.sensorHandle;
1032 if (dyn.connected) {
1033 auto it = mConnectedDynamicSensors.find(dyn.sensorHandle);
1034 CHECK(it != mConnectedDynamicSensors.end());
1035
1036 dst->dynamic_sensor_meta.sensor = it->second;
1037
1038 memcpy(dst->dynamic_sensor_meta.uuid,
1039 dyn.uuid.data(),
1040 sizeof(dst->dynamic_sensor_meta.uuid));
1041 }
1042 }
1043}
1044
1045void SensorDevice::convertToSensorEvents(
1046 const hidl_vec<Event> &src,
1047 const hidl_vec<SensorInfo> &dynamicSensorsAdded,
1048 sensors_event_t *dst) {
Steven Morelandd15c0302016-12-20 11:14:50 -08001049
Brian Stack6c49e6f2018-09-24 15:44:32 -07001050 if (dynamicSensorsAdded.size() > 0) {
1051 onDynamicSensorsConnected(dynamicSensorsAdded);
Steven Morelandd15c0302016-12-20 11:14:50 -08001052 }
1053
1054 for (size_t i = 0; i < src.size(); ++i) {
1055 convertToSensorEvent(src[i], &dst[i]);
1056 }
1057}
1058
Peng Xu3889e6e2017-03-02 19:10:38 -08001059void SensorDevice::handleHidlDeath(const std::string & detail) {
Brian Duddie6d2e3752019-05-30 09:52:28 -07001060 if (!mSensors->supportsMessageQueues()) {
Brian Stack156da082018-10-01 15:58:53 -07001061 // restart is the only option at present.
1062 LOG_ALWAYS_FATAL("Abort due to ISensors hidl service failure, detail: %s.", detail.c_str());
1063 } else {
1064 ALOGD("ISensors HAL died, death recipient will attempt reconnect");
1065 }
Peng Xu3889e6e2017-03-02 19:10:38 -08001066}
1067
Brian Duddie8e6f31c2019-05-29 13:19:13 -07001068status_t SensorDevice::checkReturnAndGetStatus(const Return<Result>& ret) {
1069 checkReturn(ret);
1070 return (!ret.isOk()) ? DEAD_OBJECT : statusFromResult(ret);
1071}
1072
Mathias Agopianf001c922010-11-11 17:58:51 -08001073// ---------------------------------------------------------------------------
1074}; // namespace android