1 /*
2  * Copyright (C) 2018 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 #include "Sensor.h"
18 
19 #include <utils/SystemClock.h>
20 
21 #include <cmath>
22 
23 namespace android {
24 namespace hardware {
25 namespace sensors {
26 namespace V2_X {
27 namespace implementation {
28 
29 using ::android::hardware::sensors::V1_0::EventPayload;
30 using ::android::hardware::sensors::V1_0::MetaDataEventType;
31 using ::android::hardware::sensors::V1_0::OperationMode;
32 using ::android::hardware::sensors::V1_0::Result;
33 using ::android::hardware::sensors::V1_0::SensorFlagBits;
34 using ::android::hardware::sensors::V1_0::SensorStatus;
35 using ::android::hardware::sensors::V2_1::Event;
36 using ::android::hardware::sensors::V2_1::SensorInfo;
37 using ::android::hardware::sensors::V2_1::SensorType;
38 
Sensor(ISensorsEventCallback * callback)39 Sensor::Sensor(ISensorsEventCallback* callback)
40     : mIsEnabled(false),
41       mSamplingPeriodNs(0),
42       mLastSampleTimeNs(0),
43       mStopThread(false),
44       mCallback(callback),
45       mMode(OperationMode::NORMAL) {
46     mRunThread = std::thread(startThread, this);
47 }
48 
~Sensor()49 Sensor::~Sensor() {
50     std::unique_lock<std::mutex> lock(mRunMutex);
51     mStopThread = true;
52     mIsEnabled = false;
53     mWaitCV.notify_all();
54     lock.release();
55     mRunThread.join();
56 }
57 
getSensorInfo() const58 const SensorInfo& Sensor::getSensorInfo() const {
59     return mSensorInfo;
60 }
61 
batch(int64_t samplingPeriodNs)62 void Sensor::batch(int64_t samplingPeriodNs) {
63     if (samplingPeriodNs < mSensorInfo.minDelay * 1000LL) {
64         samplingPeriodNs = mSensorInfo.minDelay * 1000LL;
65     } else if (samplingPeriodNs > mSensorInfo.maxDelay * 1000LL) {
66         samplingPeriodNs = mSensorInfo.maxDelay * 1000LL;
67     }
68 
69     if (mSamplingPeriodNs != samplingPeriodNs) {
70         mSamplingPeriodNs = samplingPeriodNs;
71         // Wake up the 'run' thread to check if a new event should be generated now
72         mWaitCV.notify_all();
73     }
74 }
75 
activate(bool enable)76 void Sensor::activate(bool enable) {
77     if (mIsEnabled != enable) {
78         std::unique_lock<std::mutex> lock(mRunMutex);
79         mIsEnabled = enable;
80         mWaitCV.notify_all();
81     }
82 }
83 
flush()84 Result Sensor::flush() {
85     // Only generate a flush complete event if the sensor is enabled and if the sensor is not a
86     // one-shot sensor.
87     if (!mIsEnabled || (mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::ONE_SHOT_MODE))) {
88         return Result::BAD_VALUE;
89     }
90 
91     // Note: If a sensor supports batching, write all of the currently batched events for the sensor
92     // to the Event FMQ prior to writing the flush complete event.
93     Event ev;
94     ev.sensorHandle = mSensorInfo.sensorHandle;
95     ev.sensorType = SensorType::META_DATA;
96     ev.u.meta.what = MetaDataEventType::META_DATA_FLUSH_COMPLETE;
97     std::vector<Event> evs{ev};
98     mCallback->postEvents(evs, isWakeUpSensor());
99 
100     return Result::OK;
101 }
102 
startThread(Sensor * sensor)103 void Sensor::startThread(Sensor* sensor) {
104     sensor->run();
105 }
106 
run()107 void Sensor::run() {
108     std::unique_lock<std::mutex> runLock(mRunMutex);
109     constexpr int64_t kNanosecondsInSeconds = 1000 * 1000 * 1000;
110 
111     while (!mStopThread) {
112         if (!mIsEnabled || mMode == OperationMode::DATA_INJECTION) {
113             mWaitCV.wait(runLock, [&] {
114                 return ((mIsEnabled && mMode == OperationMode::NORMAL) || mStopThread);
115             });
116         } else {
117             timespec curTime;
118             clock_gettime(CLOCK_BOOTTIME, &curTime);
119             int64_t now = (curTime.tv_sec * kNanosecondsInSeconds) + curTime.tv_nsec;
120             int64_t nextSampleTime = mLastSampleTimeNs + mSamplingPeriodNs;
121 
122             if (now >= nextSampleTime) {
123                 mLastSampleTimeNs = now;
124                 nextSampleTime = mLastSampleTimeNs + mSamplingPeriodNs;
125                 mCallback->postEvents(readEvents(), isWakeUpSensor());
126             }
127 
128             mWaitCV.wait_for(runLock, std::chrono::nanoseconds(nextSampleTime - now));
129         }
130     }
131 }
132 
isWakeUpSensor()133 bool Sensor::isWakeUpSensor() {
134     return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::WAKE_UP);
135 }
136 
readEvents()137 std::vector<Event> Sensor::readEvents() {
138     std::vector<Event> events;
139     Event event;
140     event.sensorHandle = mSensorInfo.sensorHandle;
141     event.sensorType = mSensorInfo.type;
142     event.timestamp = ::android::elapsedRealtimeNano();
143     memset(&event.u, 0, sizeof(event.u));
144     readEventPayload(event.u);
145     events.push_back(event);
146     return events;
147 }
148 
setOperationMode(OperationMode mode)149 void Sensor::setOperationMode(OperationMode mode) {
150     if (mMode != mode) {
151         std::unique_lock<std::mutex> lock(mRunMutex);
152         mMode = mode;
153         mWaitCV.notify_all();
154     }
155 }
156 
supportsDataInjection() const157 bool Sensor::supportsDataInjection() const {
158     return mSensorInfo.flags & static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION);
159 }
160 
injectEvent(const Event & event)161 Result Sensor::injectEvent(const Event& event) {
162     Result result = Result::OK;
163     if (event.sensorType == SensorType::ADDITIONAL_INFO) {
164         // When in OperationMode::NORMAL, SensorType::ADDITIONAL_INFO is used to push operation
165         // environment data into the device.
166     } else if (!supportsDataInjection()) {
167         result = Result::INVALID_OPERATION;
168     } else if (mMode == OperationMode::DATA_INJECTION) {
169         mCallback->postEvents(std::vector<Event>{event}, isWakeUpSensor());
170     } else {
171         result = Result::BAD_VALUE;
172     }
173     return result;
174 }
175 
OnChangeSensor(ISensorsEventCallback * callback)176 OnChangeSensor::OnChangeSensor(ISensorsEventCallback* callback)
177     : Sensor(callback), mPreviousEventSet(false) {}
178 
activate(bool enable)179 void OnChangeSensor::activate(bool enable) {
180     Sensor::activate(enable);
181     if (!enable) {
182         mPreviousEventSet = false;
183     }
184 }
185 
readEvents()186 std::vector<Event> OnChangeSensor::readEvents() {
187     std::vector<Event> events = Sensor::readEvents();
188     std::vector<Event> outputEvents;
189 
190     for (auto iter = events.begin(); iter != events.end(); ++iter) {
191         Event ev = *iter;
192         if (!mPreviousEventSet || memcmp(&mPreviousEvent.u, &ev.u, sizeof(ev.u)) != 0) {
193             outputEvents.push_back(ev);
194             mPreviousEvent = ev;
195             mPreviousEventSet = true;
196         }
197     }
198     return outputEvents;
199 }
200 
AccelSensor(int32_t sensorHandle,ISensorsEventCallback * callback)201 AccelSensor::AccelSensor(int32_t sensorHandle, ISensorsEventCallback* callback) : Sensor(callback) {
202     mSensorInfo.sensorHandle = sensorHandle;
203     mSensorInfo.name = "Accel Sensor";
204     mSensorInfo.vendor = "Vendor String";
205     mSensorInfo.version = 1;
206     mSensorInfo.type = SensorType::ACCELEROMETER;
207     mSensorInfo.typeAsString = "";
208     mSensorInfo.maxRange = 78.4f;  // +/- 8g
209     mSensorInfo.resolution = 1.52e-5;
210     mSensorInfo.power = 0.001f;        // mA
211     mSensorInfo.minDelay = 10 * 1000;  // microseconds
212     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
213     mSensorInfo.fifoReservedEventCount = 0;
214     mSensorInfo.fifoMaxEventCount = 0;
215     mSensorInfo.requiredPermission = "";
216     mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION);
217 };
218 
readEventPayload(EventPayload & payload)219 void AccelSensor::readEventPayload(EventPayload& payload) {
220     payload.vec3.x = 0;
221     payload.vec3.y = 0;
222     payload.vec3.z = 9.8;
223     payload.vec3.status = SensorStatus::ACCURACY_HIGH;
224 }
225 
PressureSensor(int32_t sensorHandle,ISensorsEventCallback * callback)226 PressureSensor::PressureSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
227     : Sensor(callback) {
228     mSensorInfo.sensorHandle = sensorHandle;
229     mSensorInfo.name = "Pressure Sensor";
230     mSensorInfo.vendor = "Vendor String";
231     mSensorInfo.version = 1;
232     mSensorInfo.type = SensorType::PRESSURE;
233     mSensorInfo.typeAsString = "";
234     mSensorInfo.maxRange = 1100.0f;     // hPa
235     mSensorInfo.resolution = 0.005f;    // hPa
236     mSensorInfo.power = 0.001f;         // mA
237     mSensorInfo.minDelay = 100 * 1000;  // microseconds
238     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
239     mSensorInfo.fifoReservedEventCount = 0;
240     mSensorInfo.fifoMaxEventCount = 0;
241     mSensorInfo.requiredPermission = "";
242     mSensorInfo.flags = 0;
243 };
244 
readEventPayload(EventPayload & payload)245 void PressureSensor::readEventPayload(EventPayload& payload) {
246     payload.scalar = 1013.25f;
247 }
248 
MagnetometerSensor(int32_t sensorHandle,ISensorsEventCallback * callback)249 MagnetometerSensor::MagnetometerSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
250     : Sensor(callback) {
251     mSensorInfo.sensorHandle = sensorHandle;
252     mSensorInfo.name = "Magnetic Field Sensor";
253     mSensorInfo.vendor = "Vendor String";
254     mSensorInfo.version = 1;
255     mSensorInfo.type = SensorType::MAGNETIC_FIELD;
256     mSensorInfo.typeAsString = "";
257     mSensorInfo.maxRange = 1300.0f;
258     mSensorInfo.resolution = 0.01f;
259     mSensorInfo.power = 0.001f;        // mA
260     mSensorInfo.minDelay = 20 * 1000;  // microseconds
261     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
262     mSensorInfo.fifoReservedEventCount = 0;
263     mSensorInfo.fifoMaxEventCount = 0;
264     mSensorInfo.requiredPermission = "";
265     mSensorInfo.flags = 0;
266 };
267 
LightSensor(int32_t sensorHandle,ISensorsEventCallback * callback)268 LightSensor::LightSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
269     : OnChangeSensor(callback) {
270     mSensorInfo.sensorHandle = sensorHandle;
271     mSensorInfo.name = "Light Sensor";
272     mSensorInfo.vendor = "Vendor String";
273     mSensorInfo.version = 1;
274     mSensorInfo.type = SensorType::LIGHT;
275     mSensorInfo.typeAsString = "";
276     mSensorInfo.maxRange = 43000.0f;
277     mSensorInfo.resolution = 10.0f;
278     mSensorInfo.power = 0.001f;         // mA
279     mSensorInfo.minDelay = 200 * 1000;  // microseconds
280     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
281     mSensorInfo.fifoReservedEventCount = 0;
282     mSensorInfo.fifoMaxEventCount = 0;
283     mSensorInfo.requiredPermission = "";
284     mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
285 };
286 
ProximitySensor(int32_t sensorHandle,ISensorsEventCallback * callback)287 ProximitySensor::ProximitySensor(int32_t sensorHandle, ISensorsEventCallback* callback)
288     : OnChangeSensor(callback) {
289     mSensorInfo.sensorHandle = sensorHandle;
290     mSensorInfo.name = "Proximity Sensor";
291     mSensorInfo.vendor = "Vendor String";
292     mSensorInfo.version = 1;
293     mSensorInfo.type = SensorType::PROXIMITY;
294     mSensorInfo.typeAsString = "";
295     mSensorInfo.maxRange = 5.0f;
296     mSensorInfo.resolution = 1.0f;
297     mSensorInfo.power = 0.012f;         // mA
298     mSensorInfo.minDelay = 200 * 1000;  // microseconds
299     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
300     mSensorInfo.fifoReservedEventCount = 0;
301     mSensorInfo.fifoMaxEventCount = 0;
302     mSensorInfo.requiredPermission = "";
303     mSensorInfo.flags =
304             static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE | SensorFlagBits::WAKE_UP);
305 };
306 
GyroSensor(int32_t sensorHandle,ISensorsEventCallback * callback)307 GyroSensor::GyroSensor(int32_t sensorHandle, ISensorsEventCallback* callback) : Sensor(callback) {
308     mSensorInfo.sensorHandle = sensorHandle;
309     mSensorInfo.name = "Gyro Sensor";
310     mSensorInfo.vendor = "Vendor String";
311     mSensorInfo.version = 1;
312     mSensorInfo.type = SensorType::GYROSCOPE;
313     mSensorInfo.typeAsString = "";
314     mSensorInfo.maxRange = 1000.0f * M_PI / 180.0f;
315     mSensorInfo.resolution = 1000.0f * M_PI / (180.0f * 32768.0f);
316     mSensorInfo.power = 0.001f;
317     mSensorInfo.minDelay = 10 * 1000;  // microseconds
318     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
319     mSensorInfo.fifoReservedEventCount = 0;
320     mSensorInfo.fifoMaxEventCount = 0;
321     mSensorInfo.requiredPermission = "";
322     mSensorInfo.flags = 0;
323 };
324 
AmbientTempSensor(int32_t sensorHandle,ISensorsEventCallback * callback)325 AmbientTempSensor::AmbientTempSensor(int32_t sensorHandle, ISensorsEventCallback* callback)
326     : OnChangeSensor(callback) {
327     mSensorInfo.sensorHandle = sensorHandle;
328     mSensorInfo.name = "Ambient Temp Sensor";
329     mSensorInfo.vendor = "Vendor String";
330     mSensorInfo.version = 1;
331     mSensorInfo.type = SensorType::AMBIENT_TEMPERATURE;
332     mSensorInfo.typeAsString = "";
333     mSensorInfo.maxRange = 80.0f;
334     mSensorInfo.resolution = 0.01f;
335     mSensorInfo.power = 0.001f;
336     mSensorInfo.minDelay = 40 * 1000;  // microseconds
337     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
338     mSensorInfo.fifoReservedEventCount = 0;
339     mSensorInfo.fifoMaxEventCount = 0;
340     mSensorInfo.requiredPermission = "";
341     mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
342 };
343 
RelativeHumiditySensor(int32_t sensorHandle,ISensorsEventCallback * callback)344 RelativeHumiditySensor::RelativeHumiditySensor(int32_t sensorHandle,
345                                                ISensorsEventCallback* callback)
346     : OnChangeSensor(callback) {
347     mSensorInfo.sensorHandle = sensorHandle;
348     mSensorInfo.name = "Relative Humidity Sensor";
349     mSensorInfo.vendor = "Vendor String";
350     mSensorInfo.version = 1;
351     mSensorInfo.type = SensorType::RELATIVE_HUMIDITY;
352     mSensorInfo.typeAsString = "";
353     mSensorInfo.maxRange = 100.0f;
354     mSensorInfo.resolution = 0.1f;
355     mSensorInfo.power = 0.001f;
356     mSensorInfo.minDelay = 40 * 1000;  // microseconds
357     mSensorInfo.maxDelay = kDefaultMaxDelayUs;
358     mSensorInfo.fifoReservedEventCount = 0;
359     mSensorInfo.fifoMaxEventCount = 0;
360     mSensorInfo.requiredPermission = "";
361     mSensorInfo.flags = static_cast<uint32_t>(SensorFlagBits::ON_CHANGE_MODE);
362 }
363 
364 }  // namespace implementation
365 }  // namespace V2_X
366 }  // namespace sensors
367 }  // namespace hardware
368 }  // namespace android
369