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