1 /*
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 
20 #include "SensorDeviceUtils.h"
21 #include "SensorServiceUtils.h"
22 #include "SensorsWrapper.h"
23 
24 #include <fmq/MessageQueue.h>
25 #include <sensor/SensorEventQueue.h>
26 #include <sensor/Sensor.h>
27 #include <stdint.h>
28 #include <sys/types.h>
29 #include <utils/KeyedVector.h>
30 #include <utils/Singleton.h>
31 #include <utils/String8.h>
32 #include <utils/Timers.h>
33 
34 #include <string>
35 #include <unordered_map>
36 #include <algorithm> //std::max std::min
37 
38 #include "RingBuffer.h"
39 
40 // ---------------------------------------------------------------------------
41 
42 namespace android {
43 
44 // ---------------------------------------------------------------------------
45 class SensorsHalDeathReceivier : public android::hardware::hidl_death_recipient {
46     virtual void serviceDied(uint64_t cookie,
47                              const wp<::android::hidl::base::V1_0::IBase>& service) override;
48 };
49 
50 class SensorDevice : public Singleton<SensorDevice>,
51                      public SensorServiceUtil::Dumpable {
52 public:
53     class HidlTransportErrorLog {
54      public:
55 
HidlTransportErrorLog()56         HidlTransportErrorLog() {
57             mTs = 0;
58             mCount = 0;
59         }
60 
HidlTransportErrorLog(time_t ts,int count)61         HidlTransportErrorLog(time_t ts, int count) {
62             mTs = ts;
63             mCount = count;
64         }
65 
toString()66         String8 toString() const {
67             String8 result;
68             struct tm *timeInfo = localtime(&mTs);
69             result.appendFormat("%02d:%02d:%02d :: %d", timeInfo->tm_hour, timeInfo->tm_min,
70                                 timeInfo->tm_sec, mCount);
71             return result;
72         }
73 
74     private:
75         time_t mTs; // timestamp of the error
76         int mCount;   // number of transport errors observed
77     };
78 
79     ~SensorDevice();
80     void prepareForReconnect();
81     void reconnect();
82 
83     ssize_t getSensorList(sensor_t const** list);
84 
85     void handleDynamicSensorConnection(int handle, bool connected);
86     status_t initCheck() const;
87     int getHalDeviceVersion() const;
88 
89     ssize_t poll(sensors_event_t* buffer, size_t count);
90     void writeWakeLockHandled(uint32_t count);
91 
92     status_t activate(void* ident, int handle, int enabled);
93     status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
94                    int64_t maxBatchReportLatencyNs);
95     // Call batch with timeout zero instead of calling setDelay() for newer devices.
96     status_t setDelay(void* ident, int handle, int64_t ns);
97     status_t flush(void* ident, int handle);
98     status_t setMode(uint32_t mode);
99 
100     bool isDirectReportSupported() const;
101     int32_t registerDirectChannel(const sensors_direct_mem_t *memory);
102     void unregisterDirectChannel(int32_t channelHandle);
103     int32_t configureDirectChannel(int32_t sensorHandle,
104             int32_t channelHandle, const struct sensors_direct_cfg_t *config);
105 
106     void disableAllSensors();
107     void enableAllSensors();
108     void autoDisable(void *ident, int handle);
109 
110     status_t injectSensorData(const sensors_event_t *event);
111     void notifyConnectionDestroyed(void *ident);
112 
113     using Result = ::android::hardware::sensors::V1_0::Result;
114     hardware::Return<void> onDynamicSensorsConnected(
115             const hardware::hidl_vec<hardware::sensors::V1_0::SensorInfo> &dynamicSensorsAdded);
116     hardware::Return<void> onDynamicSensorsDisconnected(
117             const hardware::hidl_vec<int32_t> &dynamicSensorHandlesRemoved);
118 
isReconnecting()119     bool isReconnecting() const {
120         return mReconnecting;
121     }
122 
123     bool isSensorActive(int handle) const;
124 
125     // Dumpable
126     virtual std::string dump() const;
127 private:
128     friend class Singleton<SensorDevice>;
129 
130     sp<SensorServiceUtil::ISensorsWrapper> mSensors;
131     Vector<sensor_t> mSensorList;
132     std::unordered_map<int32_t, sensor_t*> mConnectedDynamicSensors;
133 
134     static const nsecs_t MINIMUM_EVENTS_PERIOD =   1000000; // 1000 Hz
135     mutable Mutex mLock; // protect mActivationCount[].batchParams
136     // fixed-size array after construction
137 
138     // Struct to store all the parameters(samplingPeriod, maxBatchReportLatency and flags) from
139     // batch call. For continous mode clients, maxBatchReportLatency is set to zero.
140     struct BatchParams {
141       nsecs_t mTSample, mTBatch;
BatchParamsBatchParams142       BatchParams() : mTSample(INT64_MAX), mTBatch(INT64_MAX) {}
BatchParamsBatchParams143       BatchParams(nsecs_t tSample, nsecs_t tBatch): mTSample(tSample), mTBatch(tBatch) {}
144       bool operator != (const BatchParams& other) {
145           return !(mTSample == other.mTSample && mTBatch == other.mTBatch);
146       }
147       // Merge another parameter with this one. The updated mTSample will be the min of the two.
148       // The update mTBatch will be the min of original mTBatch and the apparent batch period
149       // of the other. the apparent batch is the maximum of mTBatch and mTSample,
mergeBatchParams150       void merge(const BatchParams &other) {
151           mTSample = std::min(mTSample, other.mTSample);
152           mTBatch = std::min(mTBatch, std::max(other.mTBatch, other.mTSample));
153       }
154     };
155 
156     // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
157     // bestBatchParams. For every batch() call corresponding params are stored in batchParams
158     // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
159     // mode request is batch(... timeout > 0 ...) followed by activate().
160     // Info is a per-sensor data structure which contains the batch parameters for each client that
161     // has registered for this sensor.
162     struct Info {
163         BatchParams bestBatchParams;
164         // Key is the unique identifier(ident) for each client, value is the batch parameters
165         // requested by the client.
166         KeyedVector<void*, BatchParams> batchParams;
167 
168         // Flag to track if the sensor is active
169         bool isActive = false;
170 
171         // Sets batch parameters for this ident. Returns error if this ident is not already present
172         // in the KeyedVector above.
173         status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
174                                         int64_t maxBatchReportLatencyNs);
175         // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
176         void selectBatchParams();
177         // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
178         // the removed ident. If index >=0, ident is present and successfully removed.
179         ssize_t removeBatchParamsForIdent(void* ident);
180 
181         int numActiveClients() const;
182     };
183     DefaultKeyedVector<int, Info> mActivationCount;
184 
185     // Keep track of any hidl transport failures
186     SensorServiceUtil::RingBuffer<HidlTransportErrorLog> mHidlTransportErrors;
187     int mTotalHidlTransportErrors;
188 
189     // Use this vector to determine which client is activated or deactivated.
190     SortedVector<void *> mDisabledClients;
191     SensorDevice();
192     bool connectHidlService();
193     void initializeSensorList();
194     void reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations);
195     static bool sensorHandlesChanged(const Vector<sensor_t>& oldSensorList,
196                                      const Vector<sensor_t>& newSensorList);
197     static bool sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor);
198 
199     enum HalConnectionStatus {
200         CONNECTED, // Successfully connected to the HAL
201         DOES_NOT_EXIST, // Could not find the HAL
202         FAILED_TO_CONNECT, // Found the HAL but failed to connect/initialize
203         UNKNOWN,
204     };
205     HalConnectionStatus connectHidlServiceV1_0();
206     HalConnectionStatus connectHidlServiceV2_0();
207 
208     ssize_t pollHal(sensors_event_t* buffer, size_t count);
209     ssize_t pollFmq(sensors_event_t* buffer, size_t count);
210     status_t activateLocked(void* ident, int handle, int enabled);
211     status_t batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
212                          int64_t maxBatchReportLatencyNs);
213 
214     void handleHidlDeath(const std::string &detail);
215     template<typename T>
checkReturn(const Return<T> & ret)216     void checkReturn(const Return<T>& ret) {
217         if (!ret.isOk()) {
218             handleHidlDeath(ret.description());
219         }
220     }
221     status_t checkReturnAndGetStatus(const Return<Result>& ret);
222     //TODO(b/67425500): remove waiter after bug is resolved.
223     sp<SensorDeviceUtils::HidlServiceRegistrationWaiter> mRestartWaiter;
224 
225     bool isClientDisabled(void* ident);
226     bool isClientDisabledLocked(void* ident);
227 
228     using Event = hardware::sensors::V1_0::Event;
229     using SensorInfo = hardware::sensors::V1_0::SensorInfo;
230 
231     void convertToSensorEvent(const Event &src, sensors_event_t *dst);
232 
233     void convertToSensorEvents(
234             const hardware::hidl_vec<Event> &src,
235             const hardware::hidl_vec<SensorInfo> &dynamicSensorsAdded,
236             sensors_event_t *dst);
237 
238     bool mIsDirectReportSupported;
239 
240     typedef hardware::MessageQueue<Event, hardware::kSynchronizedReadWrite> EventMessageQueue;
241     typedef hardware::MessageQueue<uint32_t, hardware::kSynchronizedReadWrite> WakeLockQueue;
242     std::unique_ptr<EventMessageQueue> mEventQueue;
243     std::unique_ptr<WakeLockQueue> mWakeLockQueue;
244 
245     hardware::EventFlag* mEventQueueFlag;
246     hardware::EventFlag* mWakeLockQueueFlag;
247 
248     std::array<Event, SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT> mEventBuffer;
249 
250     sp<SensorsHalDeathReceivier> mSensorsHalDeathReceiver;
251     std::atomic_bool mReconnecting;
252 };
253 
254 // ---------------------------------------------------------------------------
255 }; // namespace android
256 
257 #endif // ANDROID_SENSOR_DEVICE_H
258