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 #ifndef ANDROID_SENSORS_HIDL_TEST_BASE_H
18 #define ANDROID_SENSORS_HIDL_TEST_BASE_H
19
20 #include "sensors-vts-utils/SensorEventsChecker.h"
21 #include "sensors-vts-utils/SensorsTestSharedMemory.h"
22 #include "sensors-vts-utils/SensorsVtsEnvironmentBase.h"
23
24 #include <android/hardware/sensors/1.0/ISensors.h>
25 #include <android/hardware/sensors/1.0/types.h>
26 #include <gtest/gtest.h>
27 #include <hardware/sensors.h>
28 #include <log/log.h>
29
30 #include <cinttypes>
31 #include <unordered_set>
32 #include <vector>
33
34 using ::android::sp;
35 using ::android::hardware::hidl_string;
36 using ::android::hardware::Return;
37 using ::android::hardware::Void;
38
39 using ::android::sp;
40 using ::android::hardware::hidl_string;
41 using ::android::hardware::sensors::V1_0::RateLevel;
42 using ::android::hardware::sensors::V1_0::Result;
43 using ::android::hardware::sensors::V1_0::SensorFlagBits;
44 using ::android::hardware::sensors::V1_0::SensorFlagShift;
45 using ::android::hardware::sensors::V1_0::SensorsEventFormatOffset;
46 using ::android::hardware::sensors::V1_0::SharedMemInfo;
47 using ::android::hardware::sensors::V1_0::SharedMemType;
48
49 template <class SensorTypeT>
assertTypeMatchStringType(SensorTypeT type,const hidl_string & stringType)50 static void assertTypeMatchStringType(SensorTypeT type, const hidl_string& stringType) {
51 if (type >= SensorTypeT::DEVICE_PRIVATE_BASE) {
52 return;
53 }
54
55 switch (type) {
56 #define CHECK_TYPE_STRING_FOR_SENSOR_TYPE(type) \
57 case SensorTypeT::type: \
58 ASSERT_STREQ(SENSOR_STRING_TYPE_##type, stringType.c_str()); \
59 break;
60 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER);
61 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_UNCALIBRATED);
62 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ADDITIONAL_INFO);
63 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(AMBIENT_TEMPERATURE);
64 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DEVICE_ORIENTATION);
65 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DYNAMIC_SENSOR_META);
66 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GAME_ROTATION_VECTOR);
67 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GEOMAGNETIC_ROTATION_VECTOR);
68 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GLANCE_GESTURE);
69 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GRAVITY);
70 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE);
71 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_UNCALIBRATED);
72 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_BEAT);
73 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_RATE);
74 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LIGHT);
75 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LINEAR_ACCELERATION);
76 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LOW_LATENCY_OFFBODY_DETECT);
77 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD);
78 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD_UNCALIBRATED);
79 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MOTION_DETECT);
80 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ORIENTATION);
81 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PICK_UP_GESTURE);
82 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(POSE_6DOF);
83 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PRESSURE);
84 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PROXIMITY);
85 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(RELATIVE_HUMIDITY);
86 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ROTATION_VECTOR);
87 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(SIGNIFICANT_MOTION);
88 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STATIONARY_DETECT);
89 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_COUNTER);
90 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_DETECTOR);
91 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TEMPERATURE);
92 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TILT_DETECTOR);
93 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WAKE_GESTURE);
94 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WRIST_TILT_GESTURE);
95 default:
96 FAIL() << "Type " << static_cast<int>(type)
97 << " in android defined range is not checked, "
98 << "stringType = " << stringType;
99 #undef CHECK_TYPE_STRING_FOR_SENSOR_TYPE
100 }
101 }
102
103 template <class SensorTypeT>
expectedReportModeForType(SensorTypeT type)104 static SensorFlagBits expectedReportModeForType(SensorTypeT type) {
105 switch (type) {
106 case SensorTypeT::ACCELEROMETER:
107 case SensorTypeT::ACCELEROMETER_UNCALIBRATED:
108 case SensorTypeT::GYROSCOPE:
109 case SensorTypeT::MAGNETIC_FIELD:
110 case SensorTypeT::ORIENTATION:
111 case SensorTypeT::PRESSURE:
112 case SensorTypeT::GRAVITY:
113 case SensorTypeT::LINEAR_ACCELERATION:
114 case SensorTypeT::ROTATION_VECTOR:
115 case SensorTypeT::MAGNETIC_FIELD_UNCALIBRATED:
116 case SensorTypeT::GAME_ROTATION_VECTOR:
117 case SensorTypeT::GYROSCOPE_UNCALIBRATED:
118 case SensorTypeT::GEOMAGNETIC_ROTATION_VECTOR:
119 case SensorTypeT::POSE_6DOF:
120 case SensorTypeT::HEART_BEAT:
121 return SensorFlagBits::CONTINUOUS_MODE;
122
123 case SensorTypeT::LIGHT:
124 case SensorTypeT::PROXIMITY:
125 case SensorTypeT::RELATIVE_HUMIDITY:
126 case SensorTypeT::AMBIENT_TEMPERATURE:
127 case SensorTypeT::HEART_RATE:
128 case SensorTypeT::DEVICE_ORIENTATION:
129 case SensorTypeT::STEP_COUNTER:
130 case SensorTypeT::LOW_LATENCY_OFFBODY_DETECT:
131 return SensorFlagBits::ON_CHANGE_MODE;
132
133 case SensorTypeT::SIGNIFICANT_MOTION:
134 case SensorTypeT::WAKE_GESTURE:
135 case SensorTypeT::GLANCE_GESTURE:
136 case SensorTypeT::PICK_UP_GESTURE:
137 case SensorTypeT::MOTION_DETECT:
138 case SensorTypeT::STATIONARY_DETECT:
139 return SensorFlagBits::ONE_SHOT_MODE;
140
141 case SensorTypeT::STEP_DETECTOR:
142 case SensorTypeT::TILT_DETECTOR:
143 case SensorTypeT::WRIST_TILT_GESTURE:
144 case SensorTypeT::DYNAMIC_SENSOR_META:
145 return SensorFlagBits::SPECIAL_REPORTING_MODE;
146
147 case SensorTypeT::TEMPERATURE:
148 ALOGW("Device temperature sensor is deprecated, ignoring for test");
149 return (SensorFlagBits)-1;
150
151 default:
152 ALOGW("Type %d is not implemented in expectedReportModeForType", (int)type);
153 return (SensorFlagBits)-1;
154 }
155 }
156
157 template <class SensorTypeVersion, class EventType, class SensorInfoType>
158 class SensorsHidlTestBase : public testing::TestWithParam<std::string> {
159 public:
160 using ISensors = ::android::hardware::sensors::V1_0::ISensors;
161
SensorsHidlTestBase()162 SensorsHidlTestBase()
163 : mAccelNormChecker(Vec3NormChecker<EventType>::byNominal(GRAVITY_EARTH, 1.0f /*m/s^2*/)),
164 mGyroNormChecker(Vec3NormChecker<EventType>::byNominal(0.f, 0.1f /*rad/s*/)) {}
165
166 virtual SensorsVtsEnvironmentBase<EventType>* getEnvironment() = 0;
167
SetUp()168 virtual void SetUp() override {}
169
TearDown()170 virtual void TearDown() override {
171 // stop all sensors
172 for (auto s : mSensorHandles) {
173 activate(s, false);
174 }
175 mSensorHandles.clear();
176
177 // stop all direct report and channels
178 for (auto c : mDirectChannelHandles) {
179 // disable all reports
180 configDirectReport(-1, c, RateLevel::STOP, [](auto, auto) {});
181 unregisterDirectChannel(c);
182 }
183 mDirectChannelHandles.clear();
184 }
185
186 // implementation wrapper
187 virtual SensorInfoType defaultSensorByType(SensorTypeVersion type) = 0;
188 virtual Return<void> getSensorsList(ISensors::getSensorsList_cb _hidl_cb) = 0;
189 virtual Return<Result> injectSensorData(const EventType& event) = 0;
190 virtual Return<Result> activate(int32_t sensorHandle, bool enabled) = 0;
191 virtual Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
192 int64_t maxReportLatencyNs) = 0;
193 virtual Return<Result> flush(int32_t sensorHandle) = 0;
194 virtual Return<void> registerDirectChannel(const SharedMemInfo& mem,
195 ISensors::registerDirectChannel_cb _hidl_cb) = 0;
196 virtual Return<Result> unregisterDirectChannel(int32_t channelHandle) = 0;
197 virtual Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle,
198 RateLevel rate,
199 ISensors::configDirectReport_cb _hidl_cb) = 0;
200
testStreamingOperation(SensorTypeVersion type,std::chrono::nanoseconds samplingPeriod,std::chrono::seconds duration,const SensorEventsChecker<EventType> & checker)201 void testStreamingOperation(SensorTypeVersion type, std::chrono::nanoseconds samplingPeriod,
202 std::chrono::seconds duration,
203 const SensorEventsChecker<EventType>& checker) {
204 std::vector<EventType> events;
205 std::vector<EventType> sensorEvents;
206
207 const int64_t samplingPeriodInNs = samplingPeriod.count();
208 const int64_t batchingPeriodInNs = 0; // no batching
209 const useconds_t minTimeUs = std::chrono::microseconds(duration).count();
210 const size_t minNEvent = duration / samplingPeriod;
211
212 SensorInfoType sensor = defaultSensorByType(type);
213
214 if (!isValidType(sensor.type)) {
215 // no default sensor of this type
216 return;
217 }
218
219 if (std::chrono::microseconds(sensor.minDelay) > samplingPeriod) {
220 // rate not supported
221 return;
222 }
223
224 int32_t handle = sensor.sensorHandle;
225
226 ASSERT_EQ(batch(handle, samplingPeriodInNs, batchingPeriodInNs), Result::OK);
227 ASSERT_EQ(activate(handle, 1), Result::OK);
228 events = getEnvironment()->collectEvents(minTimeUs, minNEvent, true /*clearBeforeStart*/);
229 ASSERT_EQ(activate(handle, 0), Result::OK);
230
231 ALOGI("Collected %zu samples", events.size());
232
233 ASSERT_GT(events.size(), 0u);
234
235 bool handleMismatchReported = false;
236 bool metaSensorTypeErrorReported = false;
237 for (auto& e : events) {
238 if (e.sensorType == type) {
239 // avoid generating hundreds of error
240 if (!handleMismatchReported) {
241 EXPECT_EQ(e.sensorHandle, handle)
242 << (handleMismatchReported = true,
243 "Event of the same type must come from the sensor registered");
244 }
245 sensorEvents.push_back(e);
246 } else {
247 // avoid generating hundreds of error
248 if (!metaSensorTypeErrorReported) {
249 EXPECT_TRUE(isMetaSensorType(e.sensorType))
250 << (metaSensorTypeErrorReported = true,
251 "Only meta types are allowed besides the type registered");
252 }
253 }
254 }
255
256 std::string s;
257 EXPECT_TRUE(checker.check(sensorEvents, &s)) << s;
258
259 EXPECT_GE(sensorEvents.size(),
260 minNEvent / 2); // make sure returned events are not all meta
261 }
262
263 void testSamplingRateHotSwitchOperation(SensorTypeVersion type, bool fastToSlow = true) {
264 std::vector<EventType> events1, events2;
265
266 constexpr int64_t batchingPeriodInNs = 0; // no batching
267 constexpr int64_t collectionTimeoutUs = 60000000; // 60s
268 constexpr size_t minNEvent = 50;
269
270 SensorInfoType sensor = defaultSensorByType(type);
271
272 if (!isValidType(sensor.type)) {
273 // no default sensor of this type
274 return;
275 }
276
277 int32_t handle = sensor.sensorHandle;
278 int64_t minSamplingPeriodInNs = sensor.minDelay * 1000ll;
279 int64_t maxSamplingPeriodInNs = sensor.maxDelay * 1000ll;
280
281 if (minSamplingPeriodInNs == maxSamplingPeriodInNs) {
282 // only support single rate
283 return;
284 }
285
286 int64_t firstCollectionPeriod = fastToSlow ? minSamplingPeriodInNs : maxSamplingPeriodInNs;
287 int64_t secondCollectionPeriod =
288 !fastToSlow ? minSamplingPeriodInNs : maxSamplingPeriodInNs;
289
290 // first collection
291 ASSERT_EQ(batch(handle, firstCollectionPeriod, batchingPeriodInNs), Result::OK);
292 ASSERT_EQ(activate(handle, 1), Result::OK);
293
294 usleep(500000); // sleep 0.5 sec to wait for change rate to happen
295 events1 = getEnvironment()->collectEvents(collectionTimeoutUs, minNEvent);
296
297 // second collection, without stopping the sensor
298 ASSERT_EQ(batch(handle, secondCollectionPeriod, batchingPeriodInNs), Result::OK);
299
300 usleep(500000); // sleep 0.5 sec to wait for change rate to happen
301 events2 = getEnvironment()->collectEvents(collectionTimeoutUs, minNEvent);
302
303 // end of collection, stop sensor
304 ASSERT_EQ(activate(handle, 0), Result::OK);
305
306 ALOGI("Collected %zu fast samples and %zu slow samples", events1.size(), events2.size());
307
308 ASSERT_GT(events1.size(), 0u);
309 ASSERT_GT(events2.size(), 0u);
310
311 int64_t minDelayAverageInterval, maxDelayAverageInterval;
312 std::vector<EventType>& minDelayEvents(fastToSlow ? events1 : events2);
313 std::vector<EventType>& maxDelayEvents(fastToSlow ? events2 : events1);
314
315 size_t nEvent = 0;
316 int64_t prevTimestamp = -1;
317 int64_t timestampInterval = 0;
318 for (auto& e : minDelayEvents) {
319 if (e.sensorType == type) {
320 ASSERT_EQ(e.sensorHandle, handle);
321 if (prevTimestamp > 0) {
322 timestampInterval += e.timestamp - prevTimestamp;
323 }
324 prevTimestamp = e.timestamp;
325 ++nEvent;
326 }
327 }
328 ASSERT_GT(nEvent, 2u);
329 minDelayAverageInterval = timestampInterval / (nEvent - 1);
330
331 nEvent = 0;
332 prevTimestamp = -1;
333 timestampInterval = 0;
334 for (auto& e : maxDelayEvents) {
335 if (e.sensorType == type) {
336 ASSERT_EQ(e.sensorHandle, handle);
337 if (prevTimestamp > 0) {
338 timestampInterval += e.timestamp - prevTimestamp;
339 }
340 prevTimestamp = e.timestamp;
341 ++nEvent;
342 }
343 }
344 ASSERT_GT(nEvent, 2u);
345 maxDelayAverageInterval = timestampInterval / (nEvent - 1);
346
347 // change of rate is significant.
348 ALOGI("min/maxDelayAverageInterval = %" PRId64 " %" PRId64, minDelayAverageInterval,
349 maxDelayAverageInterval);
350 EXPECT_GT((maxDelayAverageInterval - minDelayAverageInterval),
351 minDelayAverageInterval / 10);
352
353 // fastest rate sampling time is close to spec
354 EXPECT_LT(std::abs(minDelayAverageInterval - minSamplingPeriodInNs),
355 minSamplingPeriodInNs / 10);
356
357 // slowest rate sampling time is close to spec
358 EXPECT_LT(std::abs(maxDelayAverageInterval - maxSamplingPeriodInNs),
359 maxSamplingPeriodInNs / 10);
360 }
361
testBatchingOperation(SensorTypeVersion type)362 void testBatchingOperation(SensorTypeVersion type) {
363 std::vector<EventType> events;
364
365 constexpr int64_t maxBatchingTestTimeNs = 30ull * 1000 * 1000 * 1000;
366 constexpr int64_t oneSecondInNs = 1ull * 1000 * 1000 * 1000;
367
368 SensorInfoType sensor = defaultSensorByType(type);
369
370 if (!isValidType(sensor.type)) {
371 // no default sensor of this type
372 return;
373 }
374
375 int32_t handle = sensor.sensorHandle;
376 int64_t minSamplingPeriodInNs = sensor.minDelay * 1000ll;
377 uint32_t minFifoCount = sensor.fifoReservedEventCount;
378 int64_t batchingPeriodInNs = minFifoCount * minSamplingPeriodInNs;
379
380 if (batchingPeriodInNs < oneSecondInNs) {
381 // batching size too small to test reliably
382 return;
383 }
384
385 if (batchingPeriodInNs > maxBatchingTestTimeNs) {
386 batchingPeriodInNs = maxBatchingTestTimeNs;
387 minFifoCount = (uint32_t)(batchingPeriodInNs / minSamplingPeriodInNs);
388 }
389
390 ALOGI("Test batching for %d ms", (int)(batchingPeriodInNs / 1000 / 1000));
391
392 int64_t allowedBatchDeliverTimeNs = std::max(oneSecondInNs, batchingPeriodInNs / 10);
393
394 ASSERT_EQ(batch(handle, minSamplingPeriodInNs, INT64_MAX), Result::OK);
395 ASSERT_EQ(activate(handle, 1), Result::OK);
396
397 usleep(500000); // sleep 0.5 sec to wait for initialization
398 ASSERT_EQ(flush(handle), Result::OK);
399
400 // wait for 80% of the reserved batching period
401 // there should not be any significant amount of events
402 // since collection is not enabled all events will go down the drain
403 usleep(batchingPeriodInNs / 1000 * 8 / 10);
404
405 getEnvironment()->setCollection(true);
406 // clean existing collections
407 getEnvironment()->collectEvents(0 /*timeLimitUs*/, 0 /*nEventLimit*/,
408 true /*clearBeforeStart*/, false /*change collection*/);
409
410 // 0.8 + 0.2 times the batching period
411 usleep(batchingPeriodInNs / 1000 * 2 / 10);
412 ASSERT_EQ(flush(handle), Result::OK);
413
414 // plus some time for the event to deliver
415 events = getEnvironment()->collectEvents(allowedBatchDeliverTimeNs / 1000, minFifoCount,
416 false /*clearBeforeStart*/,
417 false /*change collection*/);
418
419 getEnvironment()->setCollection(false);
420 ASSERT_EQ(activate(handle, 0), Result::OK);
421
422 size_t nEvent = 0;
423 for (auto& e : events) {
424 if (e.sensorType == type && e.sensorHandle == handle) {
425 ++nEvent;
426 }
427 }
428
429 // at least reach 90% of advertised capacity
430 ASSERT_GT(nEvent, (size_t)(minFifoCount * 9 / 10));
431 }
432
testDirectReportOperation(SensorTypeVersion type,SharedMemType memType,RateLevel rate,const SensorEventsChecker<EventType> & checker)433 void testDirectReportOperation(SensorTypeVersion type, SharedMemType memType, RateLevel rate,
434 const SensorEventsChecker<EventType>& checker) {
435 constexpr size_t kEventSize = static_cast<size_t>(SensorsEventFormatOffset::TOTAL_LENGTH);
436 constexpr size_t kNEvent = 4096;
437 constexpr size_t kMemSize = kEventSize * kNEvent;
438
439 constexpr float kNormalNominal = 50;
440 constexpr float kFastNominal = 200;
441 constexpr float kVeryFastNominal = 800;
442
443 constexpr float kNominalTestTimeSec = 1.f;
444 constexpr float kMaxTestTimeSec =
445 kNominalTestTimeSec + 0.5f; // 0.5 second for initialization
446
447 SensorInfoType sensor = defaultSensorByType(type);
448
449 if (!isValidType(sensor.type)) {
450 // no default sensor of this type
451 return;
452 }
453
454 if (!isDirectReportRateSupported(sensor, rate)) {
455 return;
456 }
457
458 if (!isDirectChannelTypeSupported(sensor, memType)) {
459 return;
460 }
461
462 std::unique_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem(
463 SensorsTestSharedMemory<SensorTypeVersion, EventType>::create(memType, kMemSize));
464 ASSERT_NE(mem, nullptr);
465
466 char* buffer = mem->getBuffer();
467 // fill memory with data
468 for (size_t i = 0; i < kMemSize; ++i) {
469 buffer[i] = '\xcc';
470 }
471
472 int32_t channelHandle;
473 registerDirectChannel(mem->getSharedMemInfo(),
474 [&channelHandle](auto result, auto channelHandle_) {
475 ASSERT_EQ(result, Result::OK);
476 channelHandle = channelHandle_;
477 });
478
479 // check memory is zeroed
480 for (size_t i = 0; i < kMemSize; ++i) {
481 ASSERT_EQ(buffer[i], '\0');
482 }
483
484 int32_t eventToken;
485 configDirectReport(sensor.sensorHandle, channelHandle, rate,
486 [&eventToken](auto result, auto token) {
487 ASSERT_EQ(result, Result::OK);
488 eventToken = token;
489 });
490
491 usleep(static_cast<useconds_t>(kMaxTestTimeSec * 1e6f));
492 auto events = mem->parseEvents();
493
494 // find norminal rate
495 float nominalFreq = 0.f;
496 switch (rate) {
497 case RateLevel::NORMAL:
498 nominalFreq = kNormalNominal;
499 break;
500 case RateLevel::FAST:
501 nominalFreq = kFastNominal;
502 break;
503 case RateLevel::VERY_FAST:
504 nominalFreq = kVeryFastNominal;
505 break;
506 case RateLevel::STOP:
507 FAIL();
508 }
509
510 // allowed to be between 55% and 220% of nominal freq
511 ASSERT_GT(events.size(), static_cast<size_t>(nominalFreq * 0.55f * kNominalTestTimeSec));
512 ASSERT_LT(events.size(), static_cast<size_t>(nominalFreq * 2.2f * kMaxTestTimeSec));
513
514 int64_t lastTimestamp = 0;
515 bool typeErrorReported = false;
516 bool tokenErrorReported = false;
517 bool timestampErrorReported = false;
518 std::vector<EventType> sensorEvents;
519 for (auto& e : events) {
520 if (!tokenErrorReported) {
521 EXPECT_EQ(eventToken, e.sensorHandle)
522 << (tokenErrorReported = true,
523 "Event token does not match that retured from configDirectReport");
524 }
525
526 if (isMetaSensorType(e.sensorType)) {
527 continue;
528 }
529 sensorEvents.push_back(e);
530
531 if (!typeErrorReported) {
532 EXPECT_EQ(type, e.sensorType)
533 << (typeErrorReported = true,
534 "Type in event does not match type of sensor registered.");
535 }
536 if (!timestampErrorReported) {
537 EXPECT_GT(e.timestamp, lastTimestamp) << (timestampErrorReported = true,
538 "Timestamp not monotonically increasing");
539 }
540 lastTimestamp = e.timestamp;
541 }
542
543 std::string s;
544 EXPECT_TRUE(checker.check(sensorEvents, &s)) << s;
545
546 // stop sensor and unregister channel
547 configDirectReport(sensor.sensorHandle, channelHandle, RateLevel::STOP,
548 [](auto result, auto) { EXPECT_EQ(result, Result::OK); });
549 EXPECT_EQ(unregisterDirectChannel(channelHandle), Result::OK);
550 }
551
extractReportMode(uint64_t flag)552 inline static SensorFlagBits extractReportMode(uint64_t flag) {
553 return (SensorFlagBits)(flag & ((uint64_t)SensorFlagBits::CONTINUOUS_MODE |
554 (uint64_t)SensorFlagBits::ON_CHANGE_MODE |
555 (uint64_t)SensorFlagBits::ONE_SHOT_MODE |
556 (uint64_t)SensorFlagBits::SPECIAL_REPORTING_MODE));
557 }
558
isMetaSensorType(SensorTypeVersion type)559 inline static bool isMetaSensorType(SensorTypeVersion type) {
560 return (type == SensorTypeVersion::META_DATA ||
561 type == SensorTypeVersion::DYNAMIC_SENSOR_META ||
562 type == SensorTypeVersion::ADDITIONAL_INFO);
563 }
564
isValidType(SensorTypeVersion type)565 inline static bool isValidType(SensorTypeVersion type) { return (int32_t)type > 0; }
566
assertDelayMatchReportMode(int32_t minDelay,int32_t maxDelay,SensorFlagBits reportMode)567 static void assertDelayMatchReportMode(int32_t minDelay, int32_t maxDelay,
568 SensorFlagBits reportMode) {
569 switch (reportMode) {
570 case SensorFlagBits::CONTINUOUS_MODE:
571 ASSERT_LT(0, minDelay);
572 ASSERT_LE(0, maxDelay);
573 break;
574 case SensorFlagBits::ON_CHANGE_MODE:
575 ASSERT_LE(0, minDelay);
576 ASSERT_LE(0, maxDelay);
577 break;
578 case SensorFlagBits::ONE_SHOT_MODE:
579 ASSERT_EQ(-1, minDelay);
580 ASSERT_EQ(0, maxDelay);
581 break;
582 case SensorFlagBits::SPECIAL_REPORTING_MODE:
583 // do not enforce anything for special reporting mode
584 break;
585 default:
586 FAIL() << "Report mode " << static_cast<int>(reportMode) << " not checked";
587 }
588 }
589
590 protected:
assertTypeMatchReportMode(SensorTypeVersion type,SensorFlagBits reportMode)591 static void assertTypeMatchReportMode(SensorTypeVersion type, SensorFlagBits reportMode) {
592 if (type >= SensorTypeVersion::DEVICE_PRIVATE_BASE) {
593 return;
594 }
595
596 SensorFlagBits expected = expectedReportModeForType(type);
597
598 ASSERT_TRUE(expected == (SensorFlagBits)-1 || expected == reportMode)
599 << "reportMode=" << static_cast<int>(reportMode)
600 << "expected=" << static_cast<int>(expected);
601 }
602
isDirectReportRateSupported(SensorInfoType sensor,RateLevel rate)603 static bool isDirectReportRateSupported(SensorInfoType sensor, RateLevel rate) {
604 unsigned int r =
605 static_cast<unsigned int>(sensor.flags & SensorFlagBits::MASK_DIRECT_REPORT) >>
606 static_cast<unsigned int>(SensorFlagShift::DIRECT_REPORT);
607 return r >= static_cast<unsigned int>(rate);
608 }
609
isDirectChannelTypeSupported(SensorInfoType sensor,SharedMemType type)610 static bool isDirectChannelTypeSupported(SensorInfoType sensor, SharedMemType type) {
611 switch (type) {
612 case SharedMemType::ASHMEM:
613 return (sensor.flags & SensorFlagBits::DIRECT_CHANNEL_ASHMEM) != 0;
614 case SharedMemType::GRALLOC:
615 return (sensor.flags & SensorFlagBits::DIRECT_CHANNEL_GRALLOC) != 0;
616 default:
617 return false;
618 }
619 }
620
621 // Checkers
622 Vec3NormChecker<EventType> mAccelNormChecker;
623 Vec3NormChecker<EventType> mGyroNormChecker;
624
625 // all sensors and direct channnels used
626 std::unordered_set<int32_t> mSensorHandles;
627 std::unordered_set<int32_t> mDirectChannelHandles;
628 };
629
630 #endif // ANDROID_SENSORS_HIDL_TEST_BASE_H
631