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