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