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 #include "SensorsHidlEnvironmentV2_X.h"
17 #include "convertV2_1.h"
18 #include "sensors-vts-utils/SensorsHidlTestBase.h"
19 #include "sensors-vts-utils/SensorsTestSharedMemory.h"
20 
21 #include <android/hardware/sensors/2.1/ISensors.h>
22 #include <android/hardware/sensors/2.1/types.h>
23 
24 #include <hidl/GtestPrinter.h>
25 #include <hidl/ServiceManagement.h>
26 #include <log/log.h>
27 #include <utils/SystemClock.h>
28 
29 #include <cinttypes>
30 #include <condition_variable>
31 #include <cstring>
32 #include <map>
33 #include <vector>
34 
35 /**
36  * This file contains the core tests and test logic for both sensors HAL 2.0
37  * and 2.1. To make it easier to share the code between both VTS test suites,
38  * this is defined as a header so they can both include and use all pieces of
39  * code.
40  */
41 
42 using ::android::sp;
43 using ::android::hardware::Return;
44 using ::android::hardware::Void;
45 using ::android::hardware::sensors::V1_0::MetaDataEventType;
46 using ::android::hardware::sensors::V1_0::OperationMode;
47 using ::android::hardware::sensors::V1_0::SensorsEventFormatOffset;
48 using ::android::hardware::sensors::V1_0::SensorStatus;
49 using ::android::hardware::sensors::V1_0::SharedMemType;
50 using ::android::hardware::sensors::V1_0::Vec3;
51 using ::android::hardware::sensors::V2_1::implementation::convertToOldSensorInfos;
52 using std::chrono::duration_cast;
53 using std::chrono::microseconds;
54 using std::chrono::milliseconds;
55 using std::chrono::nanoseconds;
56 
57 using EventV1_0 = ::android::hardware::sensors::V1_0::Event;
58 using ISensorsType = ::android::hardware::sensors::V2_1::ISensors;
59 using SensorTypeVersion = ::android::hardware::sensors::V2_1::SensorType;
60 using EventType = ::android::hardware::sensors::V2_1::Event;
61 using SensorInfoType = ::android::hardware::sensors::V2_1::SensorInfo;
62 using SensorsHidlTestBaseV2_X = SensorsHidlTestBase<SensorTypeVersion, EventType, SensorInfoType>;
63 
64 constexpr size_t kEventSize = static_cast<size_t>(SensorsEventFormatOffset::TOTAL_LENGTH);
65 
66 class EventCallback : public IEventCallback<EventType> {
67   public:
reset()68     void reset() {
69         mFlushMap.clear();
70         mEventMap.clear();
71     }
72 
onEvent(const EventType & event)73     void onEvent(const EventType& event) override {
74         if (event.sensorType == SensorTypeVersion::META_DATA &&
75             event.u.meta.what == MetaDataEventType::META_DATA_FLUSH_COMPLETE) {
76             std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
77             mFlushMap[event.sensorHandle]++;
78             mFlushCV.notify_all();
79         } else if (event.sensorType != SensorTypeVersion::ADDITIONAL_INFO) {
80             std::unique_lock<std::recursive_mutex> lock(mEventMutex);
81             mEventMap[event.sensorHandle].push_back(event);
82             mEventCV.notify_all();
83         }
84     }
85 
getFlushCount(int32_t sensorHandle)86     int32_t getFlushCount(int32_t sensorHandle) {
87         std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
88         return mFlushMap[sensorHandle];
89     }
90 
waitForFlushEvents(const std::vector<SensorInfoType> & sensorsToWaitFor,int32_t numCallsToFlush,milliseconds timeout)91     void waitForFlushEvents(const std::vector<SensorInfoType>& sensorsToWaitFor,
92                             int32_t numCallsToFlush, milliseconds timeout) {
93         std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
94         mFlushCV.wait_for(lock, timeout,
95                           [&] { return flushesReceived(sensorsToWaitFor, numCallsToFlush); });
96     }
97 
getEvents(int32_t sensorHandle)98     const std::vector<EventType> getEvents(int32_t sensorHandle) {
99         std::unique_lock<std::recursive_mutex> lock(mEventMutex);
100         return mEventMap[sensorHandle];
101     }
102 
waitForEvents(const std::vector<SensorInfoType> & sensorsToWaitFor,milliseconds timeout)103     void waitForEvents(const std::vector<SensorInfoType>& sensorsToWaitFor, milliseconds timeout) {
104         std::unique_lock<std::recursive_mutex> lock(mEventMutex);
105         mEventCV.wait_for(lock, timeout, [&] { return eventsReceived(sensorsToWaitFor); });
106     }
107 
108   protected:
flushesReceived(const std::vector<SensorInfoType> & sensorsToWaitFor,int32_t numCallsToFlush)109     bool flushesReceived(const std::vector<SensorInfoType>& sensorsToWaitFor,
110                          int32_t numCallsToFlush) {
111         for (const SensorInfoType& sensor : sensorsToWaitFor) {
112             if (getFlushCount(sensor.sensorHandle) < numCallsToFlush) {
113                 return false;
114             }
115         }
116         return true;
117     }
118 
eventsReceived(const std::vector<SensorInfoType> & sensorsToWaitFor)119     bool eventsReceived(const std::vector<SensorInfoType>& sensorsToWaitFor) {
120         for (const SensorInfoType& sensor : sensorsToWaitFor) {
121             if (getEvents(sensor.sensorHandle).size() == 0) {
122                 return false;
123             }
124         }
125         return true;
126     }
127 
128     std::map<int32_t, int32_t> mFlushMap;
129     std::recursive_mutex mFlushMutex;
130     std::condition_variable_any mFlushCV;
131 
132     std::map<int32_t, std::vector<EventType>> mEventMap;
133     std::recursive_mutex mEventMutex;
134     std::condition_variable_any mEventCV;
135 };
136 
137 /**
138  * Define the template specific versions of the static helper methods in
139  * SensorsHidlTestBase used to test that hinge angle is exposed properly.
140  */
141 template <>
expectedReportModeForType(::android::hardware::sensors::V2_1::SensorType type)142 SensorFlagBits expectedReportModeForType(::android::hardware::sensors::V2_1::SensorType type) {
143     switch (type) {
144         case ::android::hardware::sensors::V2_1::SensorType::HINGE_ANGLE:
145             return SensorFlagBits::ON_CHANGE_MODE;
146         default:
147             return expectedReportModeForType(
148                     static_cast<::android::hardware::sensors::V1_0::SensorType>(type));
149     }
150 }
151 
152 template <>
assertTypeMatchStringType(::android::hardware::sensors::V2_1::SensorType type,const hidl_string & stringType)153 void assertTypeMatchStringType(::android::hardware::sensors::V2_1::SensorType type,
154                                const hidl_string& stringType) {
155     switch (type) {
156         case (::android::hardware::sensors::V2_1::SensorType::HINGE_ANGLE):
157             ASSERT_STREQ(SENSOR_STRING_TYPE_HINGE_ANGLE, stringType.c_str());
158             break;
159         default:
160             assertTypeMatchStringType(
161                     static_cast<::android::hardware::sensors::V1_0::SensorType>(type), stringType);
162             break;
163     }
164 }
165 
166 // The main test class for SENSORS HIDL HAL.
167 class SensorsHidlTest : public SensorsHidlTestBaseV2_X {
168   public:
SetUp()169     virtual void SetUp() override {
170         mEnvironment = new SensorsHidlEnvironmentV2_X(GetParam());
171         mEnvironment->HidlSetUp();
172         // Ensure that we have a valid environment before performing tests
173         ASSERT_NE(getSensors(), nullptr);
174     }
175 
TearDown()176     virtual void TearDown() override { mEnvironment->HidlTearDown(); }
177 
178   protected:
179     SensorInfoType defaultSensorByType(SensorTypeVersion type) override;
180     std::vector<SensorInfoType> getSensorsList();
181     // implementation wrapper
182 
getSensorsList(ISensorsType::getSensorsList_cb _hidl_cb)183     Return<void> getSensorsList(ISensorsType::getSensorsList_cb _hidl_cb) override {
184         return getSensors()->getSensorsList(
185                 [&](const auto& list) { _hidl_cb(convertToOldSensorInfos(list)); });
186     }
187 
188     Return<Result> activate(int32_t sensorHandle, bool enabled) override;
189 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)190     Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
191                          int64_t maxReportLatencyNs) override {
192         return getSensors()->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs);
193     }
194 
flush(int32_t sensorHandle)195     Return<Result> flush(int32_t sensorHandle) override {
196         return getSensors()->flush(sensorHandle);
197     }
198 
injectSensorData(const EventType & event)199     Return<Result> injectSensorData(const EventType& event) override {
200         return getSensors()->injectSensorData(event);
201     }
202 
203     Return<void> registerDirectChannel(const SharedMemInfo& mem,
204                                        ISensorsType::registerDirectChannel_cb _hidl_cb) override;
205 
unregisterDirectChannel(int32_t channelHandle)206     Return<Result> unregisterDirectChannel(int32_t channelHandle) override {
207         return getSensors()->unregisterDirectChannel(channelHandle);
208     }
209 
configDirectReport(int32_t sensorHandle,int32_t channelHandle,RateLevel rate,ISensorsType::configDirectReport_cb _hidl_cb)210     Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
211                                     ISensorsType::configDirectReport_cb _hidl_cb) override {
212         return getSensors()->configDirectReport(sensorHandle, channelHandle, rate, _hidl_cb);
213     }
214 
getSensors()215     inline sp<ISensorsWrapperBase>& getSensors() { return mEnvironment->mSensors; }
216 
getEnvironment()217     SensorsHidlEnvironmentBase<EventType>* getEnvironment() override { return mEnvironment; }
218 
219     // Test helpers
220     void runSingleFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
221                             int32_t expectedFlushCount, Result expectedResponse);
222     void runFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
223                       int32_t flushCalls, int32_t expectedFlushCount, Result expectedResponse);
224 
225     // Helper functions
226     void activateAllSensors(bool enable);
227     std::vector<SensorInfoType> getNonOneShotSensors();
228     std::vector<SensorInfoType> getNonOneShotAndNonSpecialSensors();
229     std::vector<SensorInfoType> getOneShotSensors();
230     std::vector<SensorInfoType> getInjectEventSensors();
231     int32_t getInvalidSensorHandle();
232     bool getDirectChannelSensor(SensorInfoType* sensor, SharedMemType* memType, RateLevel* rate);
233     void verifyDirectChannel(SharedMemType memType);
234     void verifyRegisterDirectChannel(
235             std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem,
236             int32_t* directChannelHandle, bool supportsSharedMemType,
237             bool supportsAnyDirectChannel);
238     void verifyConfigure(const SensorInfoType& sensor, SharedMemType memType,
239                          int32_t directChannelHandle, bool directChannelSupported);
240     void verifyUnregisterDirectChannel(int32_t directChannelHandle, bool directChannelSupported);
241     void checkRateLevel(const SensorInfoType& sensor, int32_t directChannelHandle,
242                         RateLevel rateLevel);
243     void queryDirectChannelSupport(SharedMemType memType, bool* supportsSharedMemType,
244                                    bool* supportsAnyDirectChannel);
245 
246   private:
247     // Test environment for sensors HAL.
248     SensorsHidlEnvironmentV2_X* mEnvironment;
249 };
250 
activate(int32_t sensorHandle,bool enabled)251 Return<Result> SensorsHidlTest::activate(int32_t sensorHandle, bool enabled) {
252     // If activating a sensor, add the handle in a set so that when test fails it can be turned off.
253     // The handle is not removed when it is deactivating on purpose so that it is not necessary to
254     // check the return value of deactivation. Deactivating a sensor more than once does not have
255     // negative effect.
256     if (enabled) {
257         mSensorHandles.insert(sensorHandle);
258     }
259     return getSensors()->activate(sensorHandle, enabled);
260 }
261 
registerDirectChannel(const SharedMemInfo & mem,ISensors::registerDirectChannel_cb cb)262 Return<void> SensorsHidlTest::registerDirectChannel(const SharedMemInfo& mem,
263                                                     ISensors::registerDirectChannel_cb cb) {
264     // If registeration of a channel succeeds, add the handle of channel to a set so that it can be
265     // unregistered when test fails. Unregister a channel does not remove the handle on purpose.
266     // Unregistering a channel more than once should not have negative effect.
267     getSensors()->registerDirectChannel(mem, [&](auto result, auto channelHandle) {
268         if (result == Result::OK) {
269             mDirectChannelHandles.insert(channelHandle);
270         }
271         cb(result, channelHandle);
272     });
273     return Void();
274 }
275 
defaultSensorByType(SensorTypeVersion type)276 SensorInfoType SensorsHidlTest::defaultSensorByType(SensorTypeVersion type) {
277     SensorInfoType ret;
278 
279     ret.type = (SensorTypeVersion)-1;
280     getSensors()->getSensorsList([&](const auto& list) {
281         const size_t count = list.size();
282         for (size_t i = 0; i < count; ++i) {
283             if (list[i].type == type) {
284                 ret = list[i];
285                 return;
286             }
287         }
288     });
289 
290     return ret;
291 }
292 
getSensorsList()293 std::vector<SensorInfoType> SensorsHidlTest::getSensorsList() {
294     std::vector<SensorInfoType> ret;
295 
296     getSensors()->getSensorsList([&](const auto& list) {
297         const size_t count = list.size();
298         ret.reserve(list.size());
299         for (size_t i = 0; i < count; ++i) {
300             ret.push_back(list[i]);
301         }
302     });
303 
304     return ret;
305 }
306 
getNonOneShotSensors()307 std::vector<SensorInfoType> SensorsHidlTest::getNonOneShotSensors() {
308     std::vector<SensorInfoType> sensors;
309     for (const SensorInfoType& info : getSensorsList()) {
310         if (extractReportMode(info.flags) != SensorFlagBits::ONE_SHOT_MODE) {
311             sensors.push_back(info);
312         }
313     }
314     return sensors;
315 }
316 
getNonOneShotAndNonSpecialSensors()317 std::vector<SensorInfoType> SensorsHidlTest::getNonOneShotAndNonSpecialSensors() {
318     std::vector<SensorInfoType> sensors;
319     for (const SensorInfoType& info : getSensorsList()) {
320         SensorFlagBits reportMode = extractReportMode(info.flags);
321         if (reportMode != SensorFlagBits::ONE_SHOT_MODE &&
322             reportMode != SensorFlagBits::SPECIAL_REPORTING_MODE) {
323             sensors.push_back(info);
324         }
325     }
326     return sensors;
327 }
328 
getOneShotSensors()329 std::vector<SensorInfoType> SensorsHidlTest::getOneShotSensors() {
330     std::vector<SensorInfoType> sensors;
331     for (const SensorInfoType& info : getSensorsList()) {
332         if (extractReportMode(info.flags) == SensorFlagBits::ONE_SHOT_MODE) {
333             sensors.push_back(info);
334         }
335     }
336     return sensors;
337 }
338 
getInjectEventSensors()339 std::vector<SensorInfoType> SensorsHidlTest::getInjectEventSensors() {
340     std::vector<SensorInfoType> sensors;
341     for (const SensorInfoType& info : getSensorsList()) {
342         if (info.flags & static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION)) {
343             sensors.push_back(info);
344         }
345     }
346     return sensors;
347 }
348 
getInvalidSensorHandle()349 int32_t SensorsHidlTest::getInvalidSensorHandle() {
350     // Find a sensor handle that does not exist in the sensor list
351     int32_t maxHandle = 0;
352     for (const SensorInfoType& sensor : getSensorsList()) {
353         maxHandle = std::max(maxHandle, sensor.sensorHandle);
354     }
355     return maxHandle + 1;
356 }
357 
358 // Test if sensor list returned is valid
TEST_P(SensorsHidlTest,SensorListValid)359 TEST_P(SensorsHidlTest, SensorListValid) {
360     getSensors()->getSensorsList([&](const auto& list) {
361         const size_t count = list.size();
362         for (size_t i = 0; i < count; ++i) {
363             const auto& s = list[i];
364             SCOPED_TRACE(::testing::Message()
365                          << i << "/" << count << ": "
366                          << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
367                          << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
368                          << " name=" << s.name);
369 
370             // Test type string non-empty only for private sensor types.
371             if (s.type >= SensorTypeVersion::DEVICE_PRIVATE_BASE) {
372                 EXPECT_FALSE(s.typeAsString.empty());
373             } else if (!s.typeAsString.empty()) {
374                 // Test type string matches framework string if specified for non-private types.
375                 EXPECT_NO_FATAL_FAILURE(assertTypeMatchStringType(s.type, s.typeAsString));
376             }
377 
378             // Test if all sensor has name and vendor
379             EXPECT_FALSE(s.name.empty());
380             EXPECT_FALSE(s.vendor.empty());
381 
382             // Test power > 0, maxRange > 0
383             EXPECT_LE(0, s.power);
384             EXPECT_LT(0, s.maxRange);
385 
386             // Info type, should have no sensor
387             EXPECT_FALSE(s.type == SensorTypeVersion::ADDITIONAL_INFO ||
388                          s.type == SensorTypeVersion::META_DATA);
389 
390             // Test fifoMax >= fifoReserved
391             EXPECT_GE(s.fifoMaxEventCount, s.fifoReservedEventCount)
392                     << "max=" << s.fifoMaxEventCount << " reserved=" << s.fifoReservedEventCount;
393 
394             // Test Reporting mode valid
395             EXPECT_NO_FATAL_FAILURE(assertTypeMatchReportMode(s.type, extractReportMode(s.flags)));
396 
397             // Test min max are in the right order
398             EXPECT_LE(s.minDelay, s.maxDelay);
399             // Test min/max delay matches reporting mode
400             EXPECT_NO_FATAL_FAILURE(
401                     assertDelayMatchReportMode(s.minDelay, s.maxDelay, extractReportMode(s.flags)));
402         }
403     });
404 }
405 
406 // Test that SetOperationMode returns the expected value
TEST_P(SensorsHidlTest,SetOperationMode)407 TEST_P(SensorsHidlTest, SetOperationMode) {
408     std::vector<SensorInfoType> sensors = getInjectEventSensors();
409     if (getInjectEventSensors().size() > 0) {
410         ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::NORMAL));
411         ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::DATA_INJECTION));
412         ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::NORMAL));
413     } else {
414         ASSERT_EQ(Result::BAD_VALUE, getSensors()->setOperationMode(OperationMode::DATA_INJECTION));
415     }
416 }
417 
418 // Test that an injected event is written back to the Event FMQ
TEST_P(SensorsHidlTest,InjectSensorEventData)419 TEST_P(SensorsHidlTest, InjectSensorEventData) {
420     std::vector<SensorInfoType> sensors = getInjectEventSensors();
421     if (sensors.size() == 0) {
422         return;
423     }
424 
425     ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::DATA_INJECTION));
426 
427     EventCallback callback;
428     getEnvironment()->registerCallback(&callback);
429 
430     // AdditionalInfo event should not be sent to Event FMQ
431     EventType additionalInfoEvent;
432     additionalInfoEvent.sensorType = SensorTypeVersion::ADDITIONAL_INFO;
433     additionalInfoEvent.timestamp = android::elapsedRealtimeNano();
434 
435     EventType injectedEvent;
436     injectedEvent.timestamp = android::elapsedRealtimeNano();
437     Vec3 data = {1, 2, 3, SensorStatus::ACCURACY_HIGH};
438     injectedEvent.u.vec3 = data;
439 
440     for (const auto& s : sensors) {
441         additionalInfoEvent.sensorHandle = s.sensorHandle;
442         EXPECT_EQ(Result::OK, getSensors()->injectSensorData(additionalInfoEvent));
443 
444         injectedEvent.sensorType = s.type;
445         injectedEvent.sensorHandle = s.sensorHandle;
446         EXPECT_EQ(Result::OK, getSensors()->injectSensorData(injectedEvent));
447     }
448 
449     // Wait for events to be written back to the Event FMQ
450     callback.waitForEvents(sensors, milliseconds(1000) /* timeout */);
451 
452     for (const auto& s : sensors) {
453         auto events = callback.getEvents(s.sensorHandle);
454         auto lastEvent = events.back();
455         SCOPED_TRACE(::testing::Message()
456                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
457                      << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
458                      << " name=" << s.name);
459 
460         // Verify that only a single event has been received
461         ASSERT_EQ(events.size(), 1);
462 
463         // Verify that the event received matches the event injected and is not the additional
464         // info event
465         ASSERT_EQ(lastEvent.sensorType, s.type);
466         ASSERT_EQ(lastEvent.sensorType, s.type);
467         ASSERT_EQ(lastEvent.timestamp, injectedEvent.timestamp);
468         ASSERT_EQ(lastEvent.u.vec3.x, injectedEvent.u.vec3.x);
469         ASSERT_EQ(lastEvent.u.vec3.y, injectedEvent.u.vec3.y);
470         ASSERT_EQ(lastEvent.u.vec3.z, injectedEvent.u.vec3.z);
471         ASSERT_EQ(lastEvent.u.vec3.status, injectedEvent.u.vec3.status);
472     }
473 
474     getEnvironment()->unregisterCallback();
475     ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::NORMAL));
476 }
477 
activateAllSensors(bool enable)478 void SensorsHidlTest::activateAllSensors(bool enable) {
479     for (const SensorInfoType& sensorInfo : getSensorsList()) {
480         if (isValidType(sensorInfo.type)) {
481             batch(sensorInfo.sensorHandle, sensorInfo.minDelay, 0 /* maxReportLatencyNs */);
482             activate(sensorInfo.sensorHandle, enable);
483         }
484     }
485 }
486 
487 // Test that if initialize is called twice, then the HAL writes events to the FMQs from the second
488 // call to the function.
TEST_P(SensorsHidlTest,CallInitializeTwice)489 TEST_P(SensorsHidlTest, CallInitializeTwice) {
490     // Create a helper class so that a second environment is able to be instantiated
491     class SensorsHidlEnvironmentTest : public SensorsHidlEnvironmentV2_X {
492       public:
493         SensorsHidlEnvironmentTest(const std::string& service_name)
494             : SensorsHidlEnvironmentV2_X(service_name) {}
495     };
496 
497     if (getSensorsList().size() == 0) {
498         // No sensors
499         return;
500     }
501 
502     constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000;  // 1s
503     constexpr int32_t kNumEvents = 1;
504 
505     // Create a new environment that calls initialize()
506     std::unique_ptr<SensorsHidlEnvironmentTest> newEnv =
507             std::make_unique<SensorsHidlEnvironmentTest>(GetParam());
508     newEnv->HidlSetUp();
509     if (HasFatalFailure()) {
510         return;  // Exit early if setting up the new environment failed
511     }
512 
513     activateAllSensors(true);
514     // Verify that the old environment does not receive any events
515     EXPECT_EQ(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), 0);
516     // Verify that the new event queue receives sensor events
517     EXPECT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents, newEnv.get(), newEnv.get()).size(),
518               kNumEvents);
519     activateAllSensors(false);
520 
521     // Cleanup the test environment
522     newEnv->HidlTearDown();
523 
524     // Restore the test environment for future tests
525     getEnvironment()->HidlTearDown();
526     getEnvironment()->HidlSetUp();
527     if (HasFatalFailure()) {
528         return;  // Exit early if resetting the environment failed
529     }
530 
531     // Ensure that the original environment is receiving events
532     activateAllSensors(true);
533     EXPECT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
534     activateAllSensors(false);
535 }
536 
TEST_P(SensorsHidlTest,CleanupConnectionsOnInitialize)537 TEST_P(SensorsHidlTest, CleanupConnectionsOnInitialize) {
538     activateAllSensors(true);
539 
540     // Verify that events are received
541     constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000;  // 1s
542     constexpr int32_t kNumEvents = 1;
543     ASSERT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), kNumEvents);
544 
545     // Clear the active sensor handles so they are not disabled during TearDown
546     auto handles = mSensorHandles;
547     mSensorHandles.clear();
548     getEnvironment()->HidlTearDown();
549     getEnvironment()->HidlSetUp();
550     if (HasFatalFailure()) {
551         return;  // Exit early if resetting the environment failed
552     }
553 
554     // Verify no events are received until sensors are re-activated
555     ASSERT_EQ(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), 0);
556     activateAllSensors(true);
557     ASSERT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), kNumEvents);
558 
559     // Disable sensors
560     activateAllSensors(false);
561 
562     // Restore active sensors prior to clearing the environment
563     mSensorHandles = handles;
564 }
565 
runSingleFlushTest(const std::vector<SensorInfoType> & sensors,bool activateSensor,int32_t expectedFlushCount,Result expectedResponse)566 void SensorsHidlTest::runSingleFlushTest(const std::vector<SensorInfoType>& sensors,
567                                          bool activateSensor, int32_t expectedFlushCount,
568                                          Result expectedResponse) {
569     runFlushTest(sensors, activateSensor, 1 /* flushCalls */, expectedFlushCount, expectedResponse);
570 }
571 
runFlushTest(const std::vector<SensorInfoType> & sensors,bool activateSensor,int32_t flushCalls,int32_t expectedFlushCount,Result expectedResponse)572 void SensorsHidlTest::runFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
573                                    int32_t flushCalls, int32_t expectedFlushCount,
574                                    Result expectedResponse) {
575     EventCallback callback;
576     getEnvironment()->registerCallback(&callback);
577 
578     for (const SensorInfoType& sensor : sensors) {
579         // Configure and activate the sensor
580         batch(sensor.sensorHandle, sensor.maxDelay, 0 /* maxReportLatencyNs */);
581         activate(sensor.sensorHandle, activateSensor);
582 
583         // Flush the sensor
584         for (int32_t i = 0; i < flushCalls; i++) {
585             SCOPED_TRACE(::testing::Message()
586                          << "Flush " << i << "/" << flushCalls << ": "
587                          << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
588                          << sensor.sensorHandle << std::dec
589                          << " type=" << static_cast<int>(sensor.type) << " name=" << sensor.name);
590 
591             Result flushResult = flush(sensor.sensorHandle);
592             ASSERT_EQ(flushResult, expectedResponse);
593         }
594     }
595 
596     // Wait up to one second for the flush events
597     callback.waitForFlushEvents(sensors, flushCalls, milliseconds(1000) /* timeout */);
598 
599     // Deactivate all sensors after waiting for flush events so pending flush events are not
600     // abandoned by the HAL.
601     for (const SensorInfoType& sensor : sensors) {
602         activate(sensor.sensorHandle, false);
603     }
604     getEnvironment()->unregisterCallback();
605 
606     // Check that the correct number of flushes are present for each sensor
607     for (const SensorInfoType& sensor : sensors) {
608         SCOPED_TRACE(::testing::Message()
609                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
610                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
611                      << " name=" << sensor.name);
612         ASSERT_EQ(callback.getFlushCount(sensor.sensorHandle), expectedFlushCount);
613     }
614 }
615 
TEST_P(SensorsHidlTest,FlushSensor)616 TEST_P(SensorsHidlTest, FlushSensor) {
617     // Find a sensor that is not a one-shot sensor
618     std::vector<SensorInfoType> sensors = getNonOneShotSensors();
619     if (sensors.size() == 0) {
620         return;
621     }
622 
623     constexpr int32_t kFlushes = 5;
624     runSingleFlushTest(sensors, true /* activateSensor */, 1 /* expectedFlushCount */, Result::OK);
625     runFlushTest(sensors, true /* activateSensor */, kFlushes, kFlushes, Result::OK);
626 }
627 
TEST_P(SensorsHidlTest,FlushOneShotSensor)628 TEST_P(SensorsHidlTest, FlushOneShotSensor) {
629     // Find a sensor that is a one-shot sensor
630     std::vector<SensorInfoType> sensors = getOneShotSensors();
631     if (sensors.size() == 0) {
632         return;
633     }
634 
635     runSingleFlushTest(sensors, true /* activateSensor */, 0 /* expectedFlushCount */,
636                        Result::BAD_VALUE);
637 }
638 
TEST_P(SensorsHidlTest,FlushInactiveSensor)639 TEST_P(SensorsHidlTest, FlushInactiveSensor) {
640     // Attempt to find a non-one shot sensor, then a one-shot sensor if necessary
641     std::vector<SensorInfoType> sensors = getNonOneShotSensors();
642     if (sensors.size() == 0) {
643         sensors = getOneShotSensors();
644         if (sensors.size() == 0) {
645             return;
646         }
647     }
648 
649     runSingleFlushTest(sensors, false /* activateSensor */, 0 /* expectedFlushCount */,
650                        Result::BAD_VALUE);
651 }
652 
TEST_P(SensorsHidlTest,Batch)653 TEST_P(SensorsHidlTest, Batch) {
654     if (getSensorsList().size() == 0) {
655         return;
656     }
657 
658     activateAllSensors(false /* enable */);
659     for (const SensorInfoType& sensor : getSensorsList()) {
660         SCOPED_TRACE(::testing::Message()
661                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
662                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
663                      << " name=" << sensor.name);
664 
665         // Call batch on inactive sensor
666         // One shot sensors have minDelay set to -1 which is an invalid
667         // parameter. Use 0 instead to avoid errors.
668         int64_t samplingPeriodNs = extractReportMode(sensor.flags) == SensorFlagBits::ONE_SHOT_MODE
669                                            ? 0
670                                            : sensor.minDelay;
671         ASSERT_EQ(batch(sensor.sensorHandle, samplingPeriodNs, 0 /* maxReportLatencyNs */),
672                   Result::OK);
673 
674         // Activate the sensor
675         activate(sensor.sensorHandle, true /* enabled */);
676 
677         // Call batch on an active sensor
678         ASSERT_EQ(batch(sensor.sensorHandle, sensor.maxDelay, 0 /* maxReportLatencyNs */),
679                   Result::OK);
680     }
681     activateAllSensors(false /* enable */);
682 
683     // Call batch on an invalid sensor
684     SensorInfoType sensor = getSensorsList().front();
685     sensor.sensorHandle = getInvalidSensorHandle();
686     ASSERT_EQ(batch(sensor.sensorHandle, sensor.minDelay, 0 /* maxReportLatencyNs */),
687               Result::BAD_VALUE);
688 }
689 
TEST_P(SensorsHidlTest,Activate)690 TEST_P(SensorsHidlTest, Activate) {
691     if (getSensorsList().size() == 0) {
692         return;
693     }
694 
695     // Verify that sensor events are generated when activate is called
696     for (const SensorInfoType& sensor : getSensorsList()) {
697         SCOPED_TRACE(::testing::Message()
698                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
699                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
700                      << " name=" << sensor.name);
701 
702         batch(sensor.sensorHandle, sensor.minDelay, 0 /* maxReportLatencyNs */);
703         ASSERT_EQ(activate(sensor.sensorHandle, true), Result::OK);
704 
705         // Call activate on a sensor that is already activated
706         ASSERT_EQ(activate(sensor.sensorHandle, true), Result::OK);
707 
708         // Deactivate the sensor
709         ASSERT_EQ(activate(sensor.sensorHandle, false), Result::OK);
710 
711         // Call deactivate on a sensor that is already deactivated
712         ASSERT_EQ(activate(sensor.sensorHandle, false), Result::OK);
713     }
714 
715     // Attempt to activate an invalid sensor
716     int32_t invalidHandle = getInvalidSensorHandle();
717     ASSERT_EQ(activate(invalidHandle, true), Result::BAD_VALUE);
718     ASSERT_EQ(activate(invalidHandle, false), Result::BAD_VALUE);
719 }
720 
TEST_P(SensorsHidlTest,NoStaleEvents)721 TEST_P(SensorsHidlTest, NoStaleEvents) {
722     constexpr milliseconds kFiveHundredMs(500);
723     constexpr milliseconds kOneSecond(1000);
724 
725     // Register the callback to receive sensor events
726     EventCallback callback;
727     getEnvironment()->registerCallback(&callback);
728 
729     // This test is not valid for one-shot or special-report-mode sensors
730     const std::vector<SensorInfoType> sensors = getNonOneShotAndNonSpecialSensors();
731     milliseconds maxMinDelay(0);
732     for (const SensorInfoType& sensor : sensors) {
733         milliseconds minDelay = duration_cast<milliseconds>(microseconds(sensor.minDelay));
734         maxMinDelay = milliseconds(std::max(maxMinDelay.count(), minDelay.count()));
735     }
736 
737     // Activate the sensors so that they start generating events
738     activateAllSensors(true);
739 
740     // According to the CDD, the first sample must be generated within 400ms + 2 * sample_time
741     // and the maximum reporting latency is 100ms + 2 * sample_time. Wait a sufficient amount
742     // of time to guarantee that a sample has arrived.
743     callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
744     activateAllSensors(false);
745 
746     // Save the last received event for each sensor
747     std::map<int32_t, int64_t> lastEventTimestampMap;
748     for (const SensorInfoType& sensor : sensors) {
749         SCOPED_TRACE(::testing::Message()
750                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
751                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
752                      << " name=" << sensor.name);
753         // Some on-change sensors may not report an event without stimulus
754         if (extractReportMode(sensor.flags) != SensorFlagBits::ON_CHANGE_MODE) {
755             ASSERT_GE(callback.getEvents(sensor.sensorHandle).size(), 1);
756         }
757         if (callback.getEvents(sensor.sensorHandle).size() >= 1) {
758             lastEventTimestampMap[sensor.sensorHandle] =
759                     callback.getEvents(sensor.sensorHandle).back().timestamp;
760         }
761     }
762 
763     // Allow some time to pass, reset the callback, then reactivate the sensors
764     usleep(duration_cast<microseconds>(kOneSecond + (5 * maxMinDelay)).count());
765     callback.reset();
766     activateAllSensors(true);
767     callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
768     activateAllSensors(false);
769 
770     getEnvironment()->unregisterCallback();
771 
772     for (const SensorInfoType& sensor : sensors) {
773         SCOPED_TRACE(::testing::Message()
774                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
775                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
776                      << " name=" << sensor.name);
777 
778         // Skip sensors that did not previously report an event
779         if (lastEventTimestampMap.find(sensor.sensorHandle) == lastEventTimestampMap.end()) {
780             continue;
781         }
782         // Skip on-change sensors that do not consistently report an initial event
783         if (callback.getEvents(sensor.sensorHandle).size() < 1) {
784             continue;
785         }
786         // Ensure that the first event received is not stale by ensuring that its timestamp is
787         // sufficiently different from the previous event
788         const EventType newEvent = callback.getEvents(sensor.sensorHandle).front();
789         milliseconds delta = duration_cast<milliseconds>(
790                 nanoseconds(newEvent.timestamp - lastEventTimestampMap[sensor.sensorHandle]));
791         milliseconds sensorMinDelay = duration_cast<milliseconds>(microseconds(sensor.minDelay));
792         ASSERT_GE(delta, kFiveHundredMs + (3 * sensorMinDelay));
793     }
794 }
795 
checkRateLevel(const SensorInfoType & sensor,int32_t directChannelHandle,RateLevel rateLevel)796 void SensorsHidlTest::checkRateLevel(const SensorInfoType& sensor, int32_t directChannelHandle,
797                                      RateLevel rateLevel) {
798     configDirectReport(sensor.sensorHandle, directChannelHandle, rateLevel,
799                        [&](Result result, int32_t reportToken) {
800                            SCOPED_TRACE(::testing::Message()
801                                         << " handle=0x" << std::hex << std::setw(8)
802                                         << std::setfill('0') << sensor.sensorHandle << std::dec
803                                         << " type=" << static_cast<int>(sensor.type)
804                                         << " name=" << sensor.name);
805 
806                            if (isDirectReportRateSupported(sensor, rateLevel)) {
807                                ASSERT_EQ(result, Result::OK);
808                                if (rateLevel != RateLevel::STOP) {
809                                    ASSERT_GT(reportToken, 0);
810                                }
811                            } else {
812                                ASSERT_EQ(result, Result::BAD_VALUE);
813                            }
814                        });
815 }
816 
queryDirectChannelSupport(SharedMemType memType,bool * supportsSharedMemType,bool * supportsAnyDirectChannel)817 void SensorsHidlTest::queryDirectChannelSupport(SharedMemType memType, bool* supportsSharedMemType,
818                                                 bool* supportsAnyDirectChannel) {
819     *supportsSharedMemType = false;
820     *supportsAnyDirectChannel = false;
821     for (const SensorInfoType& curSensor : getSensorsList()) {
822         if (isDirectChannelTypeSupported(curSensor, memType)) {
823             *supportsSharedMemType = true;
824         }
825         if (isDirectChannelTypeSupported(curSensor, SharedMemType::ASHMEM) ||
826             isDirectChannelTypeSupported(curSensor, SharedMemType::GRALLOC)) {
827             *supportsAnyDirectChannel = true;
828         }
829 
830         if (*supportsSharedMemType && *supportsAnyDirectChannel) {
831             break;
832         }
833     }
834 }
835 
verifyRegisterDirectChannel(std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion,EventType>> mem,int32_t * directChannelHandle,bool supportsSharedMemType,bool supportsAnyDirectChannel)836 void SensorsHidlTest::verifyRegisterDirectChannel(
837         std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem,
838         int32_t* directChannelHandle, bool supportsSharedMemType, bool supportsAnyDirectChannel) {
839     char* buffer = mem->getBuffer();
840     memset(buffer, 0xff, mem->getSize());
841 
842     registerDirectChannel(mem->getSharedMemInfo(), [&](Result result, int32_t channelHandle) {
843         if (supportsSharedMemType) {
844             ASSERT_EQ(result, Result::OK);
845             ASSERT_GT(channelHandle, 0);
846 
847             // Verify that the memory has been zeroed
848             for (size_t i = 0; i < mem->getSize(); i++) {
849                 ASSERT_EQ(buffer[i], 0x00);
850             }
851         } else {
852             Result expectedResult =
853                     supportsAnyDirectChannel ? Result::BAD_VALUE : Result::INVALID_OPERATION;
854             ASSERT_EQ(result, expectedResult);
855             ASSERT_EQ(channelHandle, -1);
856         }
857         *directChannelHandle = channelHandle;
858     });
859 }
860 
verifyConfigure(const SensorInfoType & sensor,SharedMemType memType,int32_t directChannelHandle,bool supportsAnyDirectChannel)861 void SensorsHidlTest::verifyConfigure(const SensorInfoType& sensor, SharedMemType memType,
862                                       int32_t directChannelHandle, bool supportsAnyDirectChannel) {
863     SCOPED_TRACE(::testing::Message()
864                  << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
865                  << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
866                  << " name=" << sensor.name);
867 
868     if (isDirectChannelTypeSupported(sensor, memType)) {
869         // Verify that each rate level is properly supported
870         checkRateLevel(sensor, directChannelHandle, RateLevel::NORMAL);
871         checkRateLevel(sensor, directChannelHandle, RateLevel::FAST);
872         checkRateLevel(sensor, directChannelHandle, RateLevel::VERY_FAST);
873         checkRateLevel(sensor, directChannelHandle, RateLevel::STOP);
874 
875         // Verify that a sensor handle of -1 is only acceptable when using RateLevel::STOP
876         configDirectReport(-1 /* sensorHandle */, directChannelHandle, RateLevel::NORMAL,
877                            [](Result result, int32_t /* reportToken */) {
878                                ASSERT_EQ(result, Result::BAD_VALUE);
879                            });
880         configDirectReport(
881                 -1 /* sensorHandle */, directChannelHandle, RateLevel::STOP,
882                 [](Result result, int32_t /* reportToken */) { ASSERT_EQ(result, Result::OK); });
883     } else {
884         // directChannelHandle will be -1 here, HAL should either reject it as a bad value if there
885         // is some level of direct channel report, otherwise return INVALID_OPERATION if direct
886         // channel is not supported at all
887         Result expectedResult =
888                 supportsAnyDirectChannel ? Result::BAD_VALUE : Result::INVALID_OPERATION;
889         configDirectReport(sensor.sensorHandle, directChannelHandle, RateLevel::NORMAL,
890                            [expectedResult](Result result, int32_t /* reportToken */) {
891                                ASSERT_EQ(result, expectedResult);
892                            });
893     }
894 }
895 
verifyUnregisterDirectChannel(int32_t directChannelHandle,bool supportsAnyDirectChannel)896 void SensorsHidlTest::verifyUnregisterDirectChannel(int32_t directChannelHandle,
897                                                     bool supportsAnyDirectChannel) {
898     Result expectedResult = supportsAnyDirectChannel ? Result::OK : Result::INVALID_OPERATION;
899     ASSERT_EQ(unregisterDirectChannel(directChannelHandle), expectedResult);
900 }
901 
verifyDirectChannel(SharedMemType memType)902 void SensorsHidlTest::verifyDirectChannel(SharedMemType memType) {
903     constexpr size_t kNumEvents = 1;
904     constexpr size_t kMemSize = kNumEvents * kEventSize;
905 
906     std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem(
907             SensorsTestSharedMemory<SensorTypeVersion, EventType>::create(memType, kMemSize));
908     ASSERT_NE(mem, nullptr);
909 
910     bool supportsSharedMemType;
911     bool supportsAnyDirectChannel;
912     queryDirectChannelSupport(memType, &supportsSharedMemType, &supportsAnyDirectChannel);
913 
914     for (const SensorInfoType& sensor : getSensorsList()) {
915         int32_t directChannelHandle = 0;
916         verifyRegisterDirectChannel(mem, &directChannelHandle, supportsSharedMemType,
917                                     supportsAnyDirectChannel);
918         verifyConfigure(sensor, memType, directChannelHandle, supportsAnyDirectChannel);
919         verifyUnregisterDirectChannel(directChannelHandle, supportsAnyDirectChannel);
920     }
921 }
922 
TEST_P(SensorsHidlTest,DirectChannelAshmem)923 TEST_P(SensorsHidlTest, DirectChannelAshmem) {
924     verifyDirectChannel(SharedMemType::ASHMEM);
925 }
926 
TEST_P(SensorsHidlTest,DirectChannelGralloc)927 TEST_P(SensorsHidlTest, DirectChannelGralloc) {
928     verifyDirectChannel(SharedMemType::GRALLOC);
929 }
930 
getDirectChannelSensor(SensorInfoType * sensor,SharedMemType * memType,RateLevel * rate)931 bool SensorsHidlTest::getDirectChannelSensor(SensorInfoType* sensor, SharedMemType* memType,
932                                              RateLevel* rate) {
933     bool found = false;
934     for (const SensorInfoType& curSensor : getSensorsList()) {
935         if (isDirectChannelTypeSupported(curSensor, SharedMemType::ASHMEM)) {
936             *memType = SharedMemType::ASHMEM;
937             *sensor = curSensor;
938             found = true;
939             break;
940         } else if (isDirectChannelTypeSupported(curSensor, SharedMemType::GRALLOC)) {
941             *memType = SharedMemType::GRALLOC;
942             *sensor = curSensor;
943             found = true;
944             break;
945         }
946     }
947 
948     if (found) {
949         // Find a supported rate level
950         constexpr int kNumRateLevels = 3;
951         RateLevel rates[kNumRateLevels] = {RateLevel::NORMAL, RateLevel::FAST,
952                                            RateLevel::VERY_FAST};
953         *rate = RateLevel::STOP;
954         for (int i = 0; i < kNumRateLevels; i++) {
955             if (isDirectReportRateSupported(*sensor, rates[i])) {
956                 *rate = rates[i];
957             }
958         }
959 
960         // At least one rate level must be supported
961         EXPECT_NE(*rate, RateLevel::STOP);
962     }
963     return found;
964 }
965