blob: 5e7d3da39853182d464265166e090b90d5089e0d [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 */
16
17#ifndef ANDROID_SENSOR_DEVICE_H
18#define ANDROID_SENSOR_DEVICE_H
19
Peng Xu1a00e2d2017-09-27 23:08:30 -070020#include "SensorDeviceUtils.h"
Arthur Ishiguro539c27c2020-04-13 09:47:59 -070021#include "SensorService.h"
Peng Xu6a2d3a02015-12-21 12:00:23 -080022#include "SensorServiceUtils.h"
Anthony Stangee38a1412020-02-13 21:28:37 -050023#include "ISensorsWrapper.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080024
Brian Stack979887b2018-09-19 15:27:48 -070025#include <fmq/MessageQueue.h>
Brian Stacka28e9212018-09-19 15:20:30 -070026#include <sensor/SensorEventQueue.h>
Mathias Agopian801ea092017-03-06 15:05:04 -080027#include <sensor/Sensor.h>
Steven Morelandd15c0302016-12-20 11:14:50 -080028#include <stdint.h>
29#include <sys/types.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080030#include <utils/KeyedVector.h>
31#include <utils/Singleton.h>
32#include <utils/String8.h>
Brian Stacka28e9212018-09-19 15:20:30 -070033#include <utils/Timers.h>
Mathias Agopianf001c922010-11-11 17:58:51 -080034
Peng Xue36e3472016-11-03 11:57:10 -070035#include <string>
Peng Xu2bec6232016-07-01 17:13:10 -070036#include <unordered_map>
37#include <algorithm> //std::max std::min
Andreas Huber99fdbb52016-10-10 13:22:58 -070038
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070039#include "RingBuffer.h"
40
Mathias Agopianf001c922010-11-11 17:58:51 -080041// ---------------------------------------------------------------------------
42
43namespace android {
Andreas Huber99fdbb52016-10-10 13:22:58 -070044
Mathias Agopianf001c922010-11-11 17:58:51 -080045// ---------------------------------------------------------------------------
Brian Stack574cda32018-10-01 11:18:51 -070046class SensorsHalDeathReceivier : public android::hardware::hidl_death_recipient {
47 virtual void serviceDied(uint64_t cookie,
48 const wp<::android::hidl::base::V1_0::IBase>& service) override;
49};
Mathias Agopianf001c922010-11-11 17:58:51 -080050
Brian Stack6c49e6f2018-09-24 15:44:32 -070051class SensorDevice : public Singleton<SensorDevice>,
Brian Stack6c49e6f2018-09-24 15:44:32 -070052 public SensorServiceUtil::Dumpable {
Peng Xu6a2d3a02015-12-21 12:00:23 -080053public:
Ashutosh Joshi96b12d82017-03-15 16:27:12 -070054 class HidlTransportErrorLog {
55 public:
56
57 HidlTransportErrorLog() {
58 mTs = 0;
59 mCount = 0;
60 }
61
62 HidlTransportErrorLog(time_t ts, int count) {
63 mTs = ts;
64 mCount = count;
65 }
66
67 String8 toString() const {
68 String8 result;
69 struct tm *timeInfo = localtime(&mTs);
70 result.appendFormat("%02d:%02d:%02d :: %d", timeInfo->tm_hour, timeInfo->tm_min,
71 timeInfo->tm_sec, mCount);
72 return result;
73 }
74
75 private:
76 time_t mTs; // timestamp of the error
77 int mCount; // number of transport errors observed
78 };
79
Brian Stacka28e9212018-09-19 15:20:30 -070080 ~SensorDevice();
Brian Stack156da082018-10-01 15:58:53 -070081 void prepareForReconnect();
82 void reconnect();
Brian Stacka28e9212018-09-19 15:20:30 -070083
Peng Xu6a2d3a02015-12-21 12:00:23 -080084 ssize_t getSensorList(sensor_t const** list);
Andreas Huber99fdbb52016-10-10 13:22:58 -070085
Peng Xu6a2d3a02015-12-21 12:00:23 -080086 void handleDynamicSensorConnection(int handle, bool connected);
87 status_t initCheck() const;
88 int getHalDeviceVersion() const;
Andreas Huber99fdbb52016-10-10 13:22:58 -070089
Peng Xu6a2d3a02015-12-21 12:00:23 -080090 ssize_t poll(sensors_event_t* buffer, size_t count);
Brian Stackb7bfc0f2018-09-25 09:41:16 -070091 void writeWakeLockHandled(uint32_t count);
Andreas Huber99fdbb52016-10-10 13:22:58 -070092
Peng Xu6a2d3a02015-12-21 12:00:23 -080093 status_t activate(void* ident, int handle, int enabled);
94 status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
95 int64_t maxBatchReportLatencyNs);
96 // Call batch with timeout zero instead of calling setDelay() for newer devices.
97 status_t setDelay(void* ident, int handle, int64_t ns);
98 status_t flush(void* ident, int handle);
99 status_t setMode(uint32_t mode);
Peng Xue36e3472016-11-03 11:57:10 -0700100
Peng Xu53632542017-01-23 20:06:27 -0800101 bool isDirectReportSupported() const;
Peng Xue36e3472016-11-03 11:57:10 -0700102 int32_t registerDirectChannel(const sensors_direct_mem_t *memory);
103 void unregisterDirectChannel(int32_t channelHandle);
104 int32_t configureDirectChannel(int32_t sensorHandle,
105 int32_t channelHandle, const struct sensors_direct_cfg_t *config);
106
Peng Xu6a2d3a02015-12-21 12:00:23 -0800107 void disableAllSensors();
108 void enableAllSensors();
109 void autoDisable(void *ident, int handle);
Andreas Huber99fdbb52016-10-10 13:22:58 -0700110
Peng Xu6a2d3a02015-12-21 12:00:23 -0800111 status_t injectSensorData(const sensors_event_t *event);
Peng Xu4f707f82016-09-26 11:28:32 -0700112 void notifyConnectionDestroyed(void *ident);
Peng Xu6a2d3a02015-12-21 12:00:23 -0800113
Brian Stack6c49e6f2018-09-24 15:44:32 -0700114 using Result = ::android::hardware::sensors::V1_0::Result;
115 hardware::Return<void> onDynamicSensorsConnected(
Anthony Stangee38a1412020-02-13 21:28:37 -0500116 const hardware::hidl_vec<hardware::sensors::V2_1::SensorInfo> &dynamicSensorsAdded);
Brian Stack6c49e6f2018-09-24 15:44:32 -0700117 hardware::Return<void> onDynamicSensorsDisconnected(
Brian Stackbbab1ea2018-10-01 10:49:07 -0700118 const hardware::hidl_vec<int32_t> &dynamicSensorHandlesRemoved);
Brian Stack6c49e6f2018-09-24 15:44:32 -0700119
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700120 void setUidStateForConnection(void* ident, SensorService::UidState state);
121
Brian Stack156da082018-10-01 15:58:53 -0700122 bool isReconnecting() const {
123 return mReconnecting;
124 }
125
Brian Stackbce04d72019-03-21 10:54:10 -0700126 bool isSensorActive(int handle) const;
127
Peng Xu6a2d3a02015-12-21 12:00:23 -0800128 // Dumpable
Mike Ma24743862020-01-29 00:36:55 -0800129 virtual std::string dump() const override;
130 virtual void dump(util::ProtoOutputStream* proto) const override;
Peng Xu6a2d3a02015-12-21 12:00:23 -0800131private:
Mathias Agopianf001c922010-11-11 17:58:51 -0800132 friend class Singleton<SensorDevice>;
Steven Morelandd15c0302016-12-20 11:14:50 -0800133
Anthony Stangee38a1412020-02-13 21:28:37 -0500134 sp<::android::hardware::sensors::V2_1::implementation::ISensorsWrapperBase> mSensors;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700135 Vector<sensor_t> mSensorList;
Peng Xu2bec6232016-07-01 17:13:10 -0700136 std::unordered_map<int32_t, sensor_t*> mConnectedDynamicSensors;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700137
Aravind Akella724d91d2013-06-27 12:04:23 -0700138 static const nsecs_t MINIMUM_EVENTS_PERIOD = 1000000; // 1000 Hz
139 mutable Mutex mLock; // protect mActivationCount[].batchParams
Mathias Agopianf001c922010-11-11 17:58:51 -0800140 // fixed-size array after construction
Aravind Akella724d91d2013-06-27 12:04:23 -0700141
142 // Struct to store all the parameters(samplingPeriod, maxBatchReportLatency and flags) from
143 // batch call. For continous mode clients, maxBatchReportLatency is set to zero.
144 struct BatchParams {
Peng Xu2bec6232016-07-01 17:13:10 -0700145 nsecs_t mTSample, mTBatch;
146 BatchParams() : mTSample(INT64_MAX), mTBatch(INT64_MAX) {}
147 BatchParams(nsecs_t tSample, nsecs_t tBatch): mTSample(tSample), mTBatch(tBatch) {}
Aravind Akella724d91d2013-06-27 12:04:23 -0700148 bool operator != (const BatchParams& other) {
Peng Xu2bec6232016-07-01 17:13:10 -0700149 return !(mTSample == other.mTSample && mTBatch == other.mTBatch);
150 }
151 // Merge another parameter with this one. The updated mTSample will be the min of the two.
152 // The update mTBatch will be the min of original mTBatch and the apparent batch period
153 // of the other. the apparent batch is the maximum of mTBatch and mTSample,
154 void merge(const BatchParams &other) {
155 mTSample = std::min(mTSample, other.mTSample);
156 mTBatch = std::min(mTBatch, std::max(other.mTBatch, other.mTSample));
Aravind Akella724d91d2013-06-27 12:04:23 -0700157 }
158 };
159
160 // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
161 // bestBatchParams. For every batch() call corresponding params are stored in batchParams
162 // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
163 // mode request is batch(... timeout > 0 ...) followed by activate().
164 // Info is a per-sensor data structure which contains the batch parameters for each client that
165 // has registered for this sensor.
Mathias Agopianf001c922010-11-11 17:58:51 -0800166 struct Info {
Aravind Akella724d91d2013-06-27 12:04:23 -0700167 BatchParams bestBatchParams;
168 // Key is the unique identifier(ident) for each client, value is the batch parameters
169 // requested by the client.
170 KeyedVector<void*, BatchParams> batchParams;
171
Brian Stack0c305fe2019-04-09 12:49:24 -0700172 // Flag to track if the sensor is active
173 bool isActive = false;
174
Aravind Akella724d91d2013-06-27 12:04:23 -0700175 // Sets batch parameters for this ident. Returns error if this ident is not already present
176 // in the KeyedVector above.
177 status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
178 int64_t maxBatchReportLatencyNs);
179 // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
180 void selectBatchParams();
181 // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
182 // the removed ident. If index >=0, ident is present and successfully removed.
183 ssize_t removeBatchParamsForIdent(void* ident);
Aravind Akella4949c502015-02-11 15:54:35 -0800184
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700185 bool hasBatchParamsForIdent(void* ident) const {
186 return batchParams.indexOfKey(ident) >= 0;
187 }
188
189 /**
190 * @return The number of active clients of this sensor.
191 */
Brian Stack156da082018-10-01 15:58:53 -0700192 int numActiveClients() const;
Mathias Agopianf001c922010-11-11 17:58:51 -0800193 };
194 DefaultKeyedVector<int, Info> mActivationCount;
195
Ashutosh Joshi96b12d82017-03-15 16:27:12 -0700196 // Keep track of any hidl transport failures
197 SensorServiceUtil::RingBuffer<HidlTransportErrorLog> mHidlTransportErrors;
198 int mTotalHidlTransportErrors;
199
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700200 /**
201 * Enums describing the reason why a client was disabled.
202 */
203 enum DisabledReason : uint8_t {
204 // UID becomes idle (e.g. app goes to background).
205 DISABLED_REASON_UID_IDLE = 0,
206
207 // Sensors are restricted for all clients.
208 DISABLED_REASON_SERVICE_RESTRICTED,
209 DISABLED_REASON_MAX,
210 };
211
212 static_assert(DisabledReason::DISABLED_REASON_MAX < sizeof(uint8_t) * CHAR_BIT);
213
214 // Use this map to determine which client is activated or deactivated.
215 std::unordered_map<void *, uint8_t> mDisabledClients;
216
217 void addDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
218 void removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
219
Mathias Agopianf001c922010-11-11 17:58:51 -0800220 SensorDevice();
Peng Xua8fad9b2017-03-17 12:20:27 -0700221 bool connectHidlService();
Brian Stack156da082018-10-01 15:58:53 -0700222 void initializeSensorList();
223 void reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations);
224 static bool sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
225 const Vector<sensor_t>& newSensorList);
226 static bool sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor);
Brian Stack979887b2018-09-19 15:27:48 -0700227
228 enum HalConnectionStatus {
229 CONNECTED, // Successfully connected to the HAL
230 DOES_NOT_EXIST, // Could not find the HAL
231 FAILED_TO_CONNECT, // Found the HAL but failed to connect/initialize
232 UNKNOWN,
233 };
234 HalConnectionStatus connectHidlServiceV1_0();
235 HalConnectionStatus connectHidlServiceV2_0();
Anthony Stangee38a1412020-02-13 21:28:37 -0500236 HalConnectionStatus connectHidlServiceV2_1();
237 HalConnectionStatus initializeHidlServiceV2_X();
Aravind Akella4949c502015-02-11 15:54:35 -0800238
Brian Stacka28e9212018-09-19 15:20:30 -0700239 ssize_t pollHal(sensors_event_t* buffer, size_t count);
240 ssize_t pollFmq(sensors_event_t* buffer, size_t count);
Brian Stack156da082018-10-01 15:58:53 -0700241 status_t activateLocked(void* ident, int handle, int enabled);
242 status_t batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
243 int64_t maxBatchReportLatencyNs);
Brian Stacka28e9212018-09-19 15:20:30 -0700244
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700245 status_t updateBatchParamsLocked(int handle, Info& info);
246 status_t doActivateHardwareLocked(int handle, bool enable);
247
Brian Duddie6d2e3752019-05-30 09:52:28 -0700248 void handleHidlDeath(const std::string &detail);
Peng Xu3889e6e2017-03-02 19:10:38 -0800249 template<typename T>
Brian Duddie6d2e3752019-05-30 09:52:28 -0700250 void checkReturn(const Return<T>& ret) {
Peng Xu3889e6e2017-03-02 19:10:38 -0800251 if (!ret.isOk()) {
252 handleHidlDeath(ret.description());
253 }
Peng Xu3889e6e2017-03-02 19:10:38 -0800254 }
Brian Duddie6d2e3752019-05-30 09:52:28 -0700255 status_t checkReturnAndGetStatus(const Return<Result>& ret);
Peng Xu1a00e2d2017-09-27 23:08:30 -0700256 //TODO(b/67425500): remove waiter after bug is resolved.
257 sp<SensorDeviceUtils::HidlServiceRegistrationWaiter> mRestartWaiter;
Peng Xu3889e6e2017-03-02 19:10:38 -0800258
Arthur Ishiguro539c27c2020-04-13 09:47:59 -0700259 bool isClientDisabled(void* ident) const;
260 bool isClientDisabledLocked(void* ident) const;
261 std::vector<void *> getDisabledClientsLocked() const;
262
263 bool clientHasNoAccessLocked(void* ident) const;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700264
Anthony Stangee38a1412020-02-13 21:28:37 -0500265 using Event = hardware::sensors::V2_1::Event;
266 using SensorInfo = hardware::sensors::V2_1::SensorInfo;
Andreas Huber99fdbb52016-10-10 13:22:58 -0700267
268 void convertToSensorEvent(const Event &src, sensors_event_t *dst);
269
Anthony Stange12924862020-03-20 10:46:15 -0400270 void convertToSensorEventsAndQuantize(
Andreas Huber99fdbb52016-10-10 13:22:58 -0700271 const hardware::hidl_vec<Event> &src,
272 const hardware::hidl_vec<SensorInfo> &dynamicSensorsAdded,
273 sensors_event_t *dst);
Peng Xu53632542017-01-23 20:06:27 -0800274
Anthony Stange12924862020-03-20 10:46:15 -0400275 float getResolutionForSensor(int sensorHandle);
276
Peng Xu53632542017-01-23 20:06:27 -0800277 bool mIsDirectReportSupported;
Brian Stack979887b2018-09-19 15:27:48 -0700278
Brian Stack979887b2018-09-19 15:27:48 -0700279 typedef hardware::MessageQueue<uint32_t, hardware::kSynchronizedReadWrite> WakeLockQueue;
Brian Stack979887b2018-09-19 15:27:48 -0700280 std::unique_ptr<WakeLockQueue> mWakeLockQueue;
Brian Stacka28e9212018-09-19 15:20:30 -0700281
282 hardware::EventFlag* mEventQueueFlag;
Brian Stacka24e7d42019-01-08 12:56:09 -0800283 hardware::EventFlag* mWakeLockQueueFlag;
Brian Stacka28e9212018-09-19 15:20:30 -0700284
285 std::array<Event, SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT> mEventBuffer;
Brian Stack574cda32018-10-01 11:18:51 -0700286
287 sp<SensorsHalDeathReceivier> mSensorsHalDeathReceiver;
Brian Stack156da082018-10-01 15:58:53 -0700288 std::atomic_bool mReconnecting;
Mathias Agopianf001c922010-11-11 17:58:51 -0800289};
290
291// ---------------------------------------------------------------------------
292}; // namespace android
293
294#endif // ANDROID_SENSOR_DEVICE_H