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 "HidlSensorHalWrapper.h"
21 #include "ISensorHalWrapper.h"
22 
23 #include "ISensorsWrapper.h"
24 #include "SensorDeviceUtils.h"
25 #include "SensorService.h"
26 #include "SensorServiceUtils.h"
27 
28 #include <sensor/Sensor.h>
29 #include <sensor/SensorEventQueue.h>
30 #include <stdint.h>
31 #include <sys/types.h>
32 #include <utils/KeyedVector.h>
33 #include <utils/Singleton.h>
34 #include <utils/String8.h>
35 #include <utils/Timers.h>
36 
37 #include <algorithm> //std::max std::min
38 #include <condition_variable>
39 #include <mutex>
40 #include <queue>
41 #include <string>
42 #include <unordered_map>
43 #include <vector>
44 
45 #include "RingBuffer.h"
46 
47 // ---------------------------------------------------------------------------
48 
49 namespace android {
50 
51 // ---------------------------------------------------------------------------
52 
53 class SensorDevice : public Singleton<SensorDevice>,
54                      public SensorServiceUtil::Dumpable,
55                      public ISensorHalWrapper::SensorDeviceCallback {
56 public:
57     ~SensorDevice();
58     void prepareForReconnect();
59     void reconnect();
60 
61     ssize_t getSensorList(sensor_t const** list);
62 
63     std::vector<int32_t> getDynamicSensorHandles();
64 
65     void handleDynamicSensorConnection(int handle, bool connected);
66     /**
67      * Removes handle from connected dynamic sensor list. Note that this method must be called after
68      * SensorService has done using sensor data.
69      *
70      * @param handle of the disconnected dynamic sensor.
71      */
72     void cleanupDisconnectedDynamicSensor(int handle);
73 
74     status_t initCheck() const;
75     int getHalDeviceVersion() const;
76 
77     ssize_t poll(sensors_event_t* buffer, size_t count);
78     void writeWakeLockHandled(uint32_t count);
79 
80     status_t activate(void* ident, int handle, int enabled);
81     status_t batch(void* ident, int handle, int flags, int64_t samplingPeriodNs,
82                    int64_t maxBatchReportLatencyNs);
83     // Call batch with timeout zero instead of calling setDelay() for newer devices.
84     status_t setDelay(void* ident, int handle, int64_t ns);
85     status_t flush(void* ident, int handle);
86     status_t setMode(uint32_t mode);
87 
88     bool isDirectReportSupported() const;
89     int32_t registerDirectChannel(const sensors_direct_mem_t* memory);
90     void unregisterDirectChannel(int32_t channelHandle);
91     int32_t configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
92                                    const struct sensors_direct_cfg_t* config);
93 
94     void disableAllSensors();
95     void enableAllSensors();
96     void autoDisable(void* ident, int handle);
97 
98     status_t injectSensorData(const sensors_event_t* event);
99     void notifyConnectionDestroyed(void* ident);
100 
101     // SensorDeviceCallback
102     virtual void onDynamicSensorsConnected(
103             const std::vector<sensor_t>& dynamicSensorsAdded) override;
104     virtual void onDynamicSensorsDisconnected(
105             const std::vector<int32_t>& dynamicSensorHandlesRemoved) override;
106 
107     void setUidStateForConnection(void* ident, SensorService::UidState state);
108 
isReconnecting()109     bool isReconnecting() const { return mHalWrapper->mReconnecting; }
110 
111     bool isSensorActive(int handle) const;
112 
113     // To update the BatchParams of a SensorEventConnection when the mic toggle changes its state
114     // while the Sensors Off toggle is on.
115     void onMicSensorAccessChanged(void* ident, int handle, nsecs_t samplingPeriodNs);
116 
117     // Dumpable
118     virtual std::string dump() const override;
119     virtual void dump(util::ProtoOutputStream* proto) const override;
120 
121 private:
122     friend class Singleton<SensorDevice>;
123 
124     std::unique_ptr<ISensorHalWrapper> mHalWrapper;
125 
126     std::vector<sensor_t> mSensorList;
127     std::unordered_map<int32_t, sensor_t> mConnectedDynamicSensors;
128 
129     // A bug in the Sensors HIDL spec which marks onDynamicSensorsConnected as oneway causes dynamic
130     // meta events and onDynamicSensorsConnected to be received out of order. This mutex + CV are
131     // used to block meta event processing until onDynamicSensorsConnected is received to simplify
132     // HAL implementations.
133     std::mutex mDynamicSensorsMutex;
134     std::condition_variable mDynamicSensorsCv;
135     static constexpr std::chrono::seconds MAX_DYN_SENSOR_WAIT{5};
136 
137     static const nsecs_t MINIMUM_EVENTS_PERIOD = 1000000; // 1000 Hz
138     mutable Mutex mLock;                                  // protect mActivationCount[].batchParams
139     // fixed-size array after construction
140 
141     // Struct to store all the parameters(samplingPeriod, maxBatchReportLatency and flags) from
142     // batch call. For continous mode clients, maxBatchReportLatency is set to zero.
143     struct BatchParams {
144         nsecs_t mTSample, mTBatch;
BatchParamsBatchParams145         BatchParams() : mTSample(INT64_MAX), mTBatch(INT64_MAX) {}
BatchParamsBatchParams146         BatchParams(nsecs_t tSample, nsecs_t tBatch) : mTSample(tSample), mTBatch(tBatch) {}
147         bool operator!=(const BatchParams& other) {
148             return !(mTSample == other.mTSample && mTBatch == other.mTBatch);
149         }
150         // Merge another parameter with this one. The updated mTSample will be the min of the two.
151         // The update mTBatch will be the min of original mTBatch and the apparent batch period
152         // of the other. the apparent batch is the maximum of mTBatch and mTSample,
mergeBatchParams153         void merge(const BatchParams& other) {
154             mTSample = std::min(mTSample, other.mTSample);
155             mTBatch = std::min(mTBatch, std::max(other.mTBatch, other.mTSample));
156         }
157     };
158 
159     // Store batch parameters in the KeyedVector and the optimal batch_rate and timeout in
160     // bestBatchParams. For every batch() call corresponding params are stored in batchParams
161     // vector. A continuous mode request is batch(... timeout=0 ..) followed by activate(). A batch
162     // mode request is batch(... timeout > 0 ...) followed by activate().
163     // Info is a per-sensor data structure which contains the batch parameters for each client that
164     // has registered for this sensor.
165     struct Info {
166         BatchParams bestBatchParams;
167         // Key is the unique identifier(ident) for each client, value is the batch parameters
168         // requested by the client.
169         KeyedVector<void*, BatchParams> batchParams;
170 
171         // Flag to track if the sensor is active
172         bool isActive = false;
173 
174         // Sets batch parameters for this ident. Returns error if this ident is not already present
175         // in the KeyedVector above.
176         status_t setBatchParamsForIdent(void* ident, int flags, int64_t samplingPeriodNs,
177                                         int64_t maxBatchReportLatencyNs);
178         // Finds the optimal parameters for batching and stores them in bestBatchParams variable.
179         void selectBatchParams();
180         // Removes batchParams for an ident and re-computes bestBatchParams. Returns the index of
181         // the removed ident. If index >=0, ident is present and successfully removed.
182         ssize_t removeBatchParamsForIdent(void* ident);
183 
hasBatchParamsForIdentInfo184         bool hasBatchParamsForIdent(void* ident) const {
185             return batchParams.indexOfKey(ident) >= 0;
186         }
187 
188         /**
189          * @return The number of active clients of this sensor.
190          */
191         int numActiveClients() const;
192     };
193     DefaultKeyedVector<int, Info> mActivationCount;
194 
195     int mTotalHidlTransportErrors;
196 
197     /**
198      * Enums describing the reason why a client was disabled.
199      */
200     enum DisabledReason : uint8_t {
201         // UID becomes idle (e.g. app goes to background).
202         DISABLED_REASON_UID_IDLE = 0,
203 
204         // Sensors are restricted for all clients.
205         DISABLED_REASON_SERVICE_RESTRICTED,
206         DISABLED_REASON_MAX,
207     };
208 
209     static_assert(DisabledReason::DISABLED_REASON_MAX < sizeof(uint8_t) * CHAR_BIT);
210 
211     // Use this map to determine which client is activated or deactivated.
212     std::unordered_map<void*, uint8_t> mDisabledClients;
213 
214     void addDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
215     void removeDisabledReasonForIdentLocked(void* ident, DisabledReason reason);
216 
217     SensorDevice();
218     bool connectHalService();
219     void initializeSensorList();
220     void reactivateSensors(const DefaultKeyedVector<int, Info>& previousActivations);
221     static bool sensorHandlesChanged(const std::vector<sensor_t>& oldSensorList,
222                                      const std::vector<sensor_t>& newSensorList);
223     static bool sensorIsEquivalent(const sensor_t& prevSensor, const sensor_t& newSensor);
224 
225     status_t activateLocked(void* ident, int handle, int enabled);
226     status_t batchLocked(void* ident, int handle, int flags, int64_t samplingPeriodNs,
227                          int64_t maxBatchReportLatencyNs);
228 
229     status_t updateBatchParamsLocked(int handle, Info& info);
230     status_t doActivateHardwareLocked(int handle, bool enable);
231 
232     bool isClientDisabled(void* ident) const;
233     bool isClientDisabledLocked(void* ident) const;
234     std::vector<void*> getDisabledClientsLocked() const;
235 
236     bool clientHasNoAccessLocked(void* ident) const;
237 
238     float getResolutionForSensor(int sensorHandle);
239 
240     bool mIsDirectReportSupported;
241 
242     std::mutex mHalBypassLock;
243     std::condition_variable mHalBypassCV;
244     std::queue<sensors_event_t> mHalBypassInjectedEventQueue;
245     ssize_t getHalBypassInjectedEvents(sensors_event_t* buffer, size_t count);
246     bool mInHalBypassMode;
247 };
248 
249 // ---------------------------------------------------------------------------
250 }; // namespace android
251 
252 #endif // ANDROID_SENSOR_DEVICE_H
253