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