1 /*
2  * Copyright (C) 2021 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 <aidl/Gtest.h>
17 #include <aidl/Vintf.h>
18 
19 #include <aidl/android/hardware/sensors/BnSensors.h>
20 #include <aidl/android/hardware/sensors/ISensors.h>
21 #include <android/binder_manager.h>
22 #include <binder/IServiceManager.h>
23 #include <binder/ProcessState.h>
24 #include <hardware/sensors.h>
25 #include <log/log.h>
26 #include <utils/SystemClock.h>
27 
28 #include "SensorsAidlEnvironment.h"
29 #include "SensorsAidlTestSharedMemory.h"
30 #include "sensors-vts-utils/SensorsVtsEnvironmentBase.h"
31 
32 #include <cinttypes>
33 #include <condition_variable>
34 #include <map>
35 #include <unordered_map>
36 #include <unordered_set>
37 #include <vector>
38 
39 using aidl::android::hardware::sensors::Event;
40 using aidl::android::hardware::sensors::ISensors;
41 using aidl::android::hardware::sensors::SensorInfo;
42 using aidl::android::hardware::sensors::SensorStatus;
43 using aidl::android::hardware::sensors::SensorType;
44 using aidl::android::hardware::sensors::AdditionalInfo;
45 using android::ProcessState;
46 using std::chrono::duration_cast;
47 
48 constexpr size_t kEventSize =
49         static_cast<size_t>(ISensors::DIRECT_REPORT_SENSOR_EVENT_TOTAL_LENGTH);
50 
51 namespace {
52 
assertTypeMatchStringType(SensorType type,const std::string & stringType)53 static void assertTypeMatchStringType(SensorType type, const std::string& stringType) {
54     if (type >= SensorType::DEVICE_PRIVATE_BASE) {
55         return;
56     }
57 
58     switch (type) {
59 #define CHECK_TYPE_STRING_FOR_SENSOR_TYPE(type)                      \
60     case SensorType::type:                                           \
61         ASSERT_STREQ(SENSOR_STRING_TYPE_##type, stringType.c_str()); \
62         break;
63         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER);
64         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_LIMITED_AXES);
65         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_LIMITED_AXES_UNCALIBRATED);
66         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_UNCALIBRATED);
67         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ADDITIONAL_INFO);
68         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(AMBIENT_TEMPERATURE);
69         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DEVICE_ORIENTATION);
70         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DYNAMIC_SENSOR_META);
71         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GAME_ROTATION_VECTOR);
72         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GEOMAGNETIC_ROTATION_VECTOR);
73         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GLANCE_GESTURE);
74         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GRAVITY);
75         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE);
76         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_LIMITED_AXES);
77         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_LIMITED_AXES_UNCALIBRATED);
78         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_UNCALIBRATED);
79         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEADING);
80         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_BEAT);
81         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_RATE);
82         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LIGHT);
83         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LINEAR_ACCELERATION);
84         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LOW_LATENCY_OFFBODY_DETECT);
85         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD);
86         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD_UNCALIBRATED);
87         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MOTION_DETECT);
88         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ORIENTATION);
89         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PICK_UP_GESTURE);
90         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(POSE_6DOF);
91         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PRESSURE);
92         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PROXIMITY);
93         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(RELATIVE_HUMIDITY);
94         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ROTATION_VECTOR);
95         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(SIGNIFICANT_MOTION);
96         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STATIONARY_DETECT);
97         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_COUNTER);
98         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_DETECTOR);
99         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TILT_DETECTOR);
100         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WAKE_GESTURE);
101         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WRIST_TILT_GESTURE);
102         CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HINGE_ANGLE);
103         default:
104             FAIL() << "Type " << static_cast<int>(type)
105                    << " in android defined range is not checked, "
106                    << "stringType = " << stringType;
107 #undef CHECK_TYPE_STRING_FOR_SENSOR_TYPE
108     }
109 }
110 
isDirectChannelTypeSupported(SensorInfo sensor,ISensors::SharedMemInfo::SharedMemType type)111 bool isDirectChannelTypeSupported(SensorInfo sensor, ISensors::SharedMemInfo::SharedMemType type) {
112     switch (type) {
113         case ISensors::SharedMemInfo::SharedMemType::ASHMEM:
114             return (sensor.flags & SensorInfo::SENSOR_FLAG_BITS_DIRECT_CHANNEL_ASHMEM) != 0;
115         case ISensors::SharedMemInfo::SharedMemType::GRALLOC:
116             return (sensor.flags & SensorInfo::SENSOR_FLAG_BITS_DIRECT_CHANNEL_GRALLOC) != 0;
117         default:
118             return false;
119     }
120 }
121 
isDirectReportRateSupported(SensorInfo sensor,ISensors::RateLevel rate)122 bool isDirectReportRateSupported(SensorInfo sensor, ISensors::RateLevel rate) {
123     unsigned int r = static_cast<unsigned int>(sensor.flags &
124                                                SensorInfo::SENSOR_FLAG_BITS_MASK_DIRECT_REPORT) >>
125                      static_cast<unsigned int>(SensorInfo::SENSOR_FLAG_SHIFT_DIRECT_REPORT);
126     return r >= static_cast<unsigned int>(rate);
127 }
128 
expectedReportModeForType(SensorType type)129 int expectedReportModeForType(SensorType type) {
130     switch (type) {
131         case SensorType::ACCELEROMETER:
132         case SensorType::ACCELEROMETER_LIMITED_AXES:
133         case SensorType::ACCELEROMETER_UNCALIBRATED:
134         case SensorType::ACCELEROMETER_LIMITED_AXES_UNCALIBRATED:
135         case SensorType::GYROSCOPE:
136         case SensorType::GYROSCOPE_LIMITED_AXES:
137         case SensorType::MAGNETIC_FIELD:
138         case SensorType::ORIENTATION:
139         case SensorType::PRESSURE:
140         case SensorType::GRAVITY:
141         case SensorType::LINEAR_ACCELERATION:
142         case SensorType::ROTATION_VECTOR:
143         case SensorType::MAGNETIC_FIELD_UNCALIBRATED:
144         case SensorType::GAME_ROTATION_VECTOR:
145         case SensorType::GYROSCOPE_UNCALIBRATED:
146         case SensorType::GYROSCOPE_LIMITED_AXES_UNCALIBRATED:
147         case SensorType::GEOMAGNETIC_ROTATION_VECTOR:
148         case SensorType::POSE_6DOF:
149         case SensorType::HEART_BEAT:
150         case SensorType::HEADING:
151             return SensorInfo::SENSOR_FLAG_BITS_CONTINUOUS_MODE;
152 
153         case SensorType::LIGHT:
154         case SensorType::PROXIMITY:
155         case SensorType::RELATIVE_HUMIDITY:
156         case SensorType::AMBIENT_TEMPERATURE:
157         case SensorType::HEART_RATE:
158         case SensorType::DEVICE_ORIENTATION:
159         case SensorType::STEP_COUNTER:
160         case SensorType::LOW_LATENCY_OFFBODY_DETECT:
161             return SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE;
162 
163         case SensorType::SIGNIFICANT_MOTION:
164         case SensorType::WAKE_GESTURE:
165         case SensorType::GLANCE_GESTURE:
166         case SensorType::PICK_UP_GESTURE:
167         case SensorType::MOTION_DETECT:
168         case SensorType::STATIONARY_DETECT:
169             return SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE;
170 
171         case SensorType::STEP_DETECTOR:
172         case SensorType::TILT_DETECTOR:
173         case SensorType::WRIST_TILT_GESTURE:
174         case SensorType::DYNAMIC_SENSOR_META:
175             return SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE;
176 
177         default:
178             ALOGW("Type %d is not implemented in expectedReportModeForType", (int)type);
179             return INT32_MAX;
180     }
181 }
182 
assertTypeMatchReportMode(SensorType type,int reportMode)183 void assertTypeMatchReportMode(SensorType type, int reportMode) {
184     if (type >= SensorType::DEVICE_PRIVATE_BASE) {
185         return;
186     }
187 
188     int expected = expectedReportModeForType(type);
189 
190     ASSERT_TRUE(expected == INT32_MAX || expected == reportMode)
191             << "reportMode=" << static_cast<int>(reportMode)
192             << "expected=" << static_cast<int>(expected);
193 }
194 
assertDelayMatchReportMode(int32_t minDelayUs,int32_t maxDelayUs,int reportMode)195 void assertDelayMatchReportMode(int32_t minDelayUs, int32_t maxDelayUs, int reportMode) {
196     switch (reportMode) {
197         case SensorInfo::SENSOR_FLAG_BITS_CONTINUOUS_MODE:
198             ASSERT_LT(0, minDelayUs);
199             ASSERT_LE(0, maxDelayUs);
200             break;
201         case SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE:
202             ASSERT_LE(0, minDelayUs);
203             ASSERT_LE(0, maxDelayUs);
204             break;
205         case SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE:
206             ASSERT_EQ(-1, minDelayUs);
207             ASSERT_EQ(0, maxDelayUs);
208             break;
209         case SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE:
210             // do not enforce anything for special reporting mode
211             break;
212         default:
213             FAIL() << "Report mode " << static_cast<int>(reportMode) << " not checked";
214     }
215 }
216 
checkIsOk(ndk::ScopedAStatus status)217 void checkIsOk(ndk::ScopedAStatus status) {
218     ASSERT_TRUE(status.isOk());
219 }
220 
221 }  // namespace
222 
223 class EventCallback : public IEventCallback<Event> {
224   public:
reset()225     void reset() {
226         mFlushMap.clear();
227         mEventMap.clear();
228     }
229 
onEvent(const Event & event)230     void onEvent(const Event& event) override {
231         if (event.sensorType == SensorType::META_DATA &&
232             event.payload.get<Event::EventPayload::Tag::meta>().what ==
233                     Event::EventPayload::MetaData::MetaDataEventType::META_DATA_FLUSH_COMPLETE) {
234             std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
235             mFlushMap[event.sensorHandle]++;
236             mFlushCV.notify_all();
237         } else if (event.sensorType != SensorType::ADDITIONAL_INFO) {
238             std::unique_lock<std::recursive_mutex> lock(mEventMutex);
239             mEventMap[event.sensorHandle].push_back(event);
240             mEventCV.notify_all();
241         }
242     }
243 
getFlushCount(int32_t sensorHandle)244     int32_t getFlushCount(int32_t sensorHandle) {
245         std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
246         return mFlushMap[sensorHandle];
247     }
248 
waitForFlushEvents(const std::vector<SensorInfo> & sensorsToWaitFor,int32_t numCallsToFlush,std::chrono::milliseconds timeout)249     void waitForFlushEvents(const std::vector<SensorInfo>& sensorsToWaitFor,
250                             int32_t numCallsToFlush, std::chrono::milliseconds timeout) {
251         std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
252         mFlushCV.wait_for(lock, timeout,
253                           [&] { return flushesReceived(sensorsToWaitFor, numCallsToFlush); });
254     }
255 
getEvents(int32_t sensorHandle)256     const std::vector<Event> getEvents(int32_t sensorHandle) {
257         std::unique_lock<std::recursive_mutex> lock(mEventMutex);
258         return mEventMap[sensorHandle];
259     }
260 
waitForEvents(const std::vector<SensorInfo> & sensorsToWaitFor,std::chrono::milliseconds timeout)261     void waitForEvents(const std::vector<SensorInfo>& sensorsToWaitFor,
262                        std::chrono::milliseconds timeout) {
263         std::unique_lock<std::recursive_mutex> lock(mEventMutex);
264         mEventCV.wait_for(lock, timeout, [&] { return eventsReceived(sensorsToWaitFor); });
265     }
266 
267   protected:
flushesReceived(const std::vector<SensorInfo> & sensorsToWaitFor,int32_t numCallsToFlush)268     bool flushesReceived(const std::vector<SensorInfo>& sensorsToWaitFor, int32_t numCallsToFlush) {
269         for (const SensorInfo& sensor : sensorsToWaitFor) {
270             if (getFlushCount(sensor.sensorHandle) < numCallsToFlush) {
271                 return false;
272             }
273         }
274         return true;
275     }
276 
eventsReceived(const std::vector<SensorInfo> & sensorsToWaitFor)277     bool eventsReceived(const std::vector<SensorInfo>& sensorsToWaitFor) {
278         for (const SensorInfo& sensor : sensorsToWaitFor) {
279             if (getEvents(sensor.sensorHandle).size() == 0) {
280                 return false;
281             }
282         }
283         return true;
284     }
285 
286     std::map<int32_t, int32_t> mFlushMap;
287     std::recursive_mutex mFlushMutex;
288     std::condition_variable_any mFlushCV;
289 
290     std::map<int32_t, std::vector<Event>> mEventMap;
291     std::recursive_mutex mEventMutex;
292     std::condition_variable_any mEventCV;
293 };
294 
295 class SensorsAidlTest : public testing::TestWithParam<std::string> {
296   public:
SetUp()297     virtual void SetUp() override {
298         mEnvironment = new SensorsAidlEnvironment(GetParam());
299         mEnvironment->SetUp();
300 
301         // Ensure that we have a valid environment before performing tests
302         ASSERT_NE(getSensors(), nullptr);
303     }
304 
TearDown()305     virtual void TearDown() override {
306         for (int32_t handle : mSensorHandles) {
307             activate(handle, false);
308         }
309         mSensorHandles.clear();
310 
311         mEnvironment->TearDown();
312         delete mEnvironment;
313         mEnvironment = nullptr;
314     }
315 
316   protected:
317     std::vector<SensorInfo> getNonOneShotSensors();
318     std::vector<SensorInfo> getNonOneShotAndNonSpecialSensors();
319     std::vector<SensorInfo> getNonOneShotAndNonOnChangeAndNonSpecialSensors();
320     std::vector<SensorInfo> getOneShotSensors();
321     std::vector<SensorInfo> getInjectEventSensors();
322 
323     void verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType memType);
324 
325     void verifyRegisterDirectChannel(
326             std::shared_ptr<SensorsAidlTestSharedMemory<SensorType, Event>> mem,
327             int32_t* directChannelHandle, bool supportsSharedMemType,
328             bool supportsAnyDirectChannel);
329 
330     void verifyConfigure(const SensorInfo& sensor, ISensors::SharedMemInfo::SharedMemType memType,
331                          int32_t directChannelHandle, bool directChannelSupported);
332 
333     void queryDirectChannelSupport(ISensors::SharedMemInfo::SharedMemType memType,
334                                    bool* supportsSharedMemType, bool* supportsAnyDirectChannel);
335 
336     void verifyUnregisterDirectChannel(int32_t* directChannelHandle, bool supportsAnyDirectChannel);
337 
338     void checkRateLevel(const SensorInfo& sensor, int32_t directChannelHandle,
339                         ISensors::RateLevel rateLevel, int32_t* reportToken);
340 
getSensors()341     inline std::shared_ptr<ISensors>& getSensors() { return mEnvironment->mSensors; }
342 
getEnvironment()343     inline SensorsAidlEnvironment* getEnvironment() { return mEnvironment; }
344 
isValidType(SensorType sensorType)345     inline bool isValidType(SensorType sensorType) { return (int)sensorType > 0; }
346 
347     std::vector<SensorInfo> getSensorsList();
348 
getInvalidSensorHandle()349     int32_t getInvalidSensorHandle() {
350         // Find a sensor handle that does not exist in the sensor list
351         int32_t maxHandle = 0;
352         for (const SensorInfo& sensor : getSensorsList()) {
353             maxHandle = std::max(maxHandle, sensor.sensorHandle);
354         }
355         return maxHandle + 1;
356     }
357 
358     ndk::ScopedAStatus activate(int32_t sensorHandle, bool enable);
359     void activateAllSensors(bool enable);
360 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)361     ndk::ScopedAStatus batch(int32_t sensorHandle, int64_t samplingPeriodNs,
362                              int64_t maxReportLatencyNs) {
363         return getSensors()->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs);
364     }
365 
flush(int32_t sensorHandle)366     ndk::ScopedAStatus flush(int32_t sensorHandle) { return getSensors()->flush(sensorHandle); }
367 
368     ndk::ScopedAStatus registerDirectChannel(const ISensors::SharedMemInfo& mem,
369                                              int32_t* aidlReturn);
370 
unregisterDirectChannel(int32_t * channelHandle)371     ndk::ScopedAStatus unregisterDirectChannel(int32_t* channelHandle) {
372         return getSensors()->unregisterDirectChannel(*channelHandle);
373     }
374 
configDirectReport(int32_t sensorHandle,int32_t channelHandle,ISensors::RateLevel rate,int32_t * reportToken)375     ndk::ScopedAStatus configDirectReport(int32_t sensorHandle, int32_t channelHandle,
376                                           ISensors::RateLevel rate, int32_t* reportToken) {
377         return getSensors()->configDirectReport(sensorHandle, channelHandle, rate, reportToken);
378     }
379 
380     void runSingleFlushTest(const std::vector<SensorInfo>& sensors, bool activateSensor,
381                             int32_t expectedFlushCount, bool expectedResult);
382 
383     void runFlushTest(const std::vector<SensorInfo>& sensors, bool activateSensor,
384                       int32_t flushCalls, int32_t expectedFlushCount, bool expectedResult);
385 
extractReportMode(int32_t flag)386     inline static int32_t extractReportMode(int32_t flag) {
387         return (flag & (SensorInfo::SENSOR_FLAG_BITS_CONTINUOUS_MODE |
388                         SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE |
389                         SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE |
390                         SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE));
391     }
392 
393     // All sensors and direct channnels used
394     std::unordered_set<int32_t> mSensorHandles;
395     std::unordered_set<int32_t> mDirectChannelHandles;
396 
397   private:
398     SensorsAidlEnvironment* mEnvironment;
399 };
400 
registerDirectChannel(const ISensors::SharedMemInfo & mem,int32_t * aidlReturn)401 ndk::ScopedAStatus SensorsAidlTest::registerDirectChannel(const ISensors::SharedMemInfo& mem,
402                                                           int32_t* aidlReturn) {
403     // If registeration of a channel succeeds, add the handle of channel to a set so that it can be
404     // unregistered when test fails. Unregister a channel does not remove the handle on purpose.
405     // Unregistering a channel more than once should not have negative effect.
406 
407     ndk::ScopedAStatus status = getSensors()->registerDirectChannel(mem, aidlReturn);
408     if (status.isOk()) {
409         mDirectChannelHandles.insert(*aidlReturn);
410     }
411     return status;
412 }
413 
getSensorsList()414 std::vector<SensorInfo> SensorsAidlTest::getSensorsList() {
415     std::vector<SensorInfo> sensorInfoList;
416     checkIsOk(getSensors()->getSensorsList(&sensorInfoList));
417     return sensorInfoList;
418 }
419 
activate(int32_t sensorHandle,bool enable)420 ndk::ScopedAStatus SensorsAidlTest::activate(int32_t sensorHandle, bool enable) {
421     // If activating a sensor, add the handle in a set so that when test fails it can be turned off.
422     // The handle is not removed when it is deactivating on purpose so that it is not necessary to
423     // check the return value of deactivation. Deactivating a sensor more than once does not have
424     // negative effect.
425     if (enable) {
426         mSensorHandles.insert(sensorHandle);
427     }
428     return getSensors()->activate(sensorHandle, enable);
429 }
430 
activateAllSensors(bool enable)431 void SensorsAidlTest::activateAllSensors(bool enable) {
432     for (const SensorInfo& sensorInfo : getSensorsList()) {
433         if (isValidType(sensorInfo.type)) {
434             checkIsOk(batch(sensorInfo.sensorHandle, sensorInfo.minDelayUs,
435                             0 /* maxReportLatencyNs */));
436             checkIsOk(activate(sensorInfo.sensorHandle, enable));
437         }
438     }
439 }
440 
getNonOneShotSensors()441 std::vector<SensorInfo> SensorsAidlTest::getNonOneShotSensors() {
442     std::vector<SensorInfo> sensors;
443     for (const SensorInfo& info : getSensorsList()) {
444         if (extractReportMode(info.flags) != SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE) {
445             sensors.push_back(info);
446         }
447     }
448     return sensors;
449 }
450 
getNonOneShotAndNonSpecialSensors()451 std::vector<SensorInfo> SensorsAidlTest::getNonOneShotAndNonSpecialSensors() {
452     std::vector<SensorInfo> sensors;
453     for (const SensorInfo& info : getSensorsList()) {
454         int reportMode = extractReportMode(info.flags);
455         if (reportMode != SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE &&
456             reportMode != SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE) {
457             sensors.push_back(info);
458         }
459     }
460     return sensors;
461 }
462 
getNonOneShotAndNonOnChangeAndNonSpecialSensors()463 std::vector<SensorInfo> SensorsAidlTest::getNonOneShotAndNonOnChangeAndNonSpecialSensors() {
464     std::vector<SensorInfo> sensors;
465     for (const SensorInfo& info : getSensorsList()) {
466         int reportMode = extractReportMode(info.flags);
467         if (reportMode != SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE &&
468             reportMode != SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE &&
469             reportMode != SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE) {
470             sensors.push_back(info);
471         }
472     }
473     return sensors;
474 }
475 
getOneShotSensors()476 std::vector<SensorInfo> SensorsAidlTest::getOneShotSensors() {
477     std::vector<SensorInfo> sensors;
478     for (const SensorInfo& info : getSensorsList()) {
479         if (extractReportMode(info.flags) == SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE) {
480             sensors.push_back(info);
481         }
482     }
483     return sensors;
484 }
485 
getInjectEventSensors()486 std::vector<SensorInfo> SensorsAidlTest::getInjectEventSensors() {
487     std::vector<SensorInfo> out;
488     std::vector<SensorInfo> sensorInfoList = getSensorsList();
489     for (const SensorInfo& info : sensorInfoList) {
490         if (info.flags & SensorInfo::SENSOR_FLAG_BITS_DATA_INJECTION) {
491             out.push_back(info);
492         }
493     }
494     return out;
495 }
496 
runSingleFlushTest(const std::vector<SensorInfo> & sensors,bool activateSensor,int32_t expectedFlushCount,bool expectedResult)497 void SensorsAidlTest::runSingleFlushTest(const std::vector<SensorInfo>& sensors,
498                                          bool activateSensor, int32_t expectedFlushCount,
499                                          bool expectedResult) {
500     runFlushTest(sensors, activateSensor, 1 /* flushCalls */, expectedFlushCount, expectedResult);
501 }
502 
runFlushTest(const std::vector<SensorInfo> & sensors,bool activateSensor,int32_t flushCalls,int32_t expectedFlushCount,bool expectedResult)503 void SensorsAidlTest::runFlushTest(const std::vector<SensorInfo>& sensors, bool activateSensor,
504                                    int32_t flushCalls, int32_t expectedFlushCount,
505                                    bool expectedResult) {
506     EventCallback callback;
507     getEnvironment()->registerCallback(&callback);
508 
509     for (const SensorInfo& sensor : sensors) {
510         // Configure and activate the sensor
511         batch(sensor.sensorHandle, sensor.maxDelayUs, 0 /* maxReportLatencyNs */);
512         activate(sensor.sensorHandle, activateSensor);
513 
514         // Flush the sensor
515         for (int32_t i = 0; i < flushCalls; i++) {
516             SCOPED_TRACE(::testing::Message()
517                          << "Flush " << i << "/" << flushCalls << ": "
518                          << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
519                          << sensor.sensorHandle << std::dec
520                          << " type=" << static_cast<int>(sensor.type) << " name=" << sensor.name);
521 
522             EXPECT_EQ(flush(sensor.sensorHandle).isOk(), expectedResult);
523         }
524     }
525 
526     // Wait up to one second for the flush events
527     callback.waitForFlushEvents(sensors, flushCalls, std::chrono::milliseconds(1000) /* timeout */);
528 
529     // Deactivate all sensors after waiting for flush events so pending flush events are not
530     // abandoned by the HAL.
531     for (const SensorInfo& sensor : sensors) {
532         activate(sensor.sensorHandle, false);
533     }
534     getEnvironment()->unregisterCallback();
535 
536     // Check that the correct number of flushes are present for each sensor
537     for (const SensorInfo& sensor : sensors) {
538         SCOPED_TRACE(::testing::Message()
539                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
540                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
541                      << " name=" << sensor.name);
542         ASSERT_EQ(callback.getFlushCount(sensor.sensorHandle), expectedFlushCount);
543     }
544 }
545 
TEST_P(SensorsAidlTest,SensorListValid)546 TEST_P(SensorsAidlTest, SensorListValid) {
547     std::vector<SensorInfo> sensorInfoList = getSensorsList();
548     std::unordered_map<int32_t, std::vector<std::string>> sensorTypeNameMap;
549     for (size_t i = 0; i < sensorInfoList.size(); ++i) {
550         const SensorInfo& info = sensorInfoList[i];
551         SCOPED_TRACE(::testing::Message()
552                      << i << "/" << sensorInfoList.size() << ": "
553                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
554                      << info.sensorHandle << std::dec << " type=" << static_cast<int>(info.type)
555                      << " name=" << info.name);
556 
557         // Test type string non-empty only for private sensor typeinfo.
558         if (info.type >= SensorType::DEVICE_PRIVATE_BASE) {
559             EXPECT_FALSE(info.typeAsString.empty());
560         } else if (!info.typeAsString.empty()) {
561             // Test type string matches framework string if specified for non-private typeinfo.
562             EXPECT_NO_FATAL_FAILURE(assertTypeMatchStringType(info.type, info.typeAsString));
563         }
564 
565         // Test if all sensors have name and vendor
566         EXPECT_FALSE(info.name.empty());
567         EXPECT_FALSE(info.vendor.empty());
568 
569         // Make sure that the sensor handle is not within the reserved range for runtime
570         // sensors.
571         EXPECT_FALSE(ISensors::RUNTIME_SENSORS_HANDLE_BASE <= info.sensorHandle &&
572                      info.sensorHandle <= ISensors::RUNTIME_SENSORS_HANDLE_END);
573 
574         // Make sure that sensors of the same type have a unique name.
575         std::vector<std::string>& v = sensorTypeNameMap[static_cast<int32_t>(info.type)];
576         bool isUniqueName = std::find(v.begin(), v.end(), info.name) == v.end();
577         EXPECT_TRUE(isUniqueName) << "Duplicate sensor Name: " << info.name;
578         if (isUniqueName) {
579             v.push_back(info.name);
580         }
581 
582         EXPECT_LE(0, info.power);
583         EXPECT_LT(0, info.maxRange);
584 
585         // Info type, should have no sensor
586         EXPECT_FALSE(info.type == SensorType::ADDITIONAL_INFO ||
587                      info.type == SensorType::META_DATA);
588 
589         EXPECT_GE(info.fifoMaxEventCount, info.fifoReservedEventCount);
590 
591         // Test Reporting mode valid
592         EXPECT_NO_FATAL_FAILURE(
593                 assertTypeMatchReportMode(info.type, extractReportMode(info.flags)));
594 
595         // Test min max are in the right order
596         EXPECT_LE(info.minDelayUs, info.maxDelayUs);
597         // Test min/max delay matches reporting mode
598         EXPECT_NO_FATAL_FAILURE(assertDelayMatchReportMode(info.minDelayUs, info.maxDelayUs,
599                                                            extractReportMode(info.flags)));
600     }
601 }
602 
TEST_P(SensorsAidlTest,SetOperationMode)603 TEST_P(SensorsAidlTest, SetOperationMode) {
604     if (getInjectEventSensors().size() > 0) {
605         ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
606         ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::DATA_INJECTION).isOk());
607         ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
608     } else {
609       int errorCode =
610           getSensors()
611               ->setOperationMode(ISensors::OperationMode::DATA_INJECTION)
612               .getExceptionCode();
613       ASSERT_TRUE((errorCode == EX_UNSUPPORTED_OPERATION) ||
614                   (errorCode == EX_ILLEGAL_ARGUMENT));
615     }
616 }
617 
TEST_P(SensorsAidlTest,InjectSensorEventData)618 TEST_P(SensorsAidlTest, InjectSensorEventData) {
619     std::vector<SensorInfo> sensors = getInjectEventSensors();
620     if (sensors.size() == 0) {
621         return;
622     }
623 
624     ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::DATA_INJECTION).isOk());
625 
626     EventCallback callback;
627     getEnvironment()->registerCallback(&callback);
628 
629     // AdditionalInfo event should not be sent to Event FMQ
630     Event additionalInfoEvent;
631     additionalInfoEvent.sensorType = SensorType::ADDITIONAL_INFO;
632     additionalInfoEvent.timestamp = android::elapsedRealtimeNano();
633     AdditionalInfo info;
634     info.type = AdditionalInfo::AdditionalInfoType::AINFO_BEGIN;
635     info.serial = 1;
636     AdditionalInfo::AdditionalInfoPayload::Int32Values infoData;
637     for (int32_t i = 0; i < 14; i++) {
638         infoData.values[i] = i;
639     }
640     info.payload.set<AdditionalInfo::AdditionalInfoPayload::Tag::dataInt32>(infoData);
641     additionalInfoEvent.payload.set<Event::EventPayload::Tag::additional>(info);
642 
643     Event injectedEvent;
644     injectedEvent.timestamp = android::elapsedRealtimeNano();
645     Event::EventPayload::Vec3 data = {1, 2, 3, SensorStatus::ACCURACY_HIGH};
646     injectedEvent.payload.set<Event::EventPayload::Tag::vec3>(data);
647 
648     for (const auto& s : sensors) {
649         additionalInfoEvent.sensorHandle = s.sensorHandle;
650         ASSERT_TRUE(getSensors()->injectSensorData(additionalInfoEvent).isOk());
651 
652         injectedEvent.sensorType = s.type;
653         injectedEvent.sensorHandle = s.sensorHandle;
654         ASSERT_TRUE(getSensors()->injectSensorData(injectedEvent).isOk());
655     }
656 
657     // Wait for events to be written back to the Event FMQ
658     callback.waitForEvents(sensors, std::chrono::milliseconds(1000) /* timeout */);
659     getEnvironment()->unregisterCallback();
660 
661     for (const auto& s : sensors) {
662         auto events = callback.getEvents(s.sensorHandle);
663         if (events.empty()) {
664             FAIL() << "Received no events";
665         } else {
666             auto lastEvent = events.back();
667             SCOPED_TRACE(::testing::Message()
668                          << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
669                          << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
670                          << " name=" << s.name);
671 
672             // Verify that only a single event has been received
673             ASSERT_EQ(events.size(), 1);
674 
675             // Verify that the event received matches the event injected and is not the additional
676             // info event
677             ASSERT_EQ(lastEvent.sensorType, s.type);
678             ASSERT_EQ(lastEvent.timestamp, injectedEvent.timestamp);
679             ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().x,
680                       injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().x);
681             ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().y,
682                       injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().y);
683             ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().z,
684                       injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().z);
685             ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().status,
686                       injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().status);
687         }
688     }
689 
690     ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
691 }
692 
TEST_P(SensorsAidlTest,CallInitializeTwice)693 TEST_P(SensorsAidlTest, CallInitializeTwice) {
694     // Create a helper class so that a second environment is able to be instantiated
695     class SensorsAidlEnvironmentTest : public SensorsAidlEnvironment {
696       public:
697         SensorsAidlEnvironmentTest(const std::string& service_name)
698             : SensorsAidlEnvironment(service_name) {}
699     };
700 
701     if (getSensorsList().size() == 0) {
702         // No sensors
703         return;
704     }
705 
706     constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000;  // 1s
707     constexpr int32_t kNumEvents = 1;
708 
709     // Create a new environment that calls initialize()
710     std::unique_ptr<SensorsAidlEnvironmentTest> newEnv =
711             std::make_unique<SensorsAidlEnvironmentTest>(GetParam());
712     newEnv->SetUp();
713     if (HasFatalFailure()) {
714         return;  // Exit early if setting up the new environment failed
715     }
716 
717     activateAllSensors(true);
718     // Verify that the old environment does not receive any events
719     EXPECT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
720     // Verify that the new event queue receives sensor events
721     EXPECT_GE(newEnv.get()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
722     activateAllSensors(false);
723 
724     // Cleanup the test environment
725     newEnv->TearDown();
726 
727     // Restore the test environment for future tests
728     getEnvironment()->TearDown();
729     getEnvironment()->SetUp();
730     if (HasFatalFailure()) {
731         return;  // Exit early if resetting the environment failed
732     }
733 
734     // Ensure that the original environment is receiving events
735     activateAllSensors(true);
736     EXPECT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
737     activateAllSensors(false);
738 }
739 
TEST_P(SensorsAidlTest,CleanupConnectionsOnInitialize)740 TEST_P(SensorsAidlTest, CleanupConnectionsOnInitialize) {
741     activateAllSensors(true);
742 
743     // Verify that events are received
744     constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000;  // 1s
745     constexpr int32_t kNumEvents = 1;
746     ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
747 
748     // Clear the active sensor handles so they are not disabled during TearDown
749     auto handles = mSensorHandles;
750     mSensorHandles.clear();
751     getEnvironment()->TearDown();
752     getEnvironment()->SetUp();
753     if (HasFatalFailure()) {
754         return;  // Exit early if resetting the environment failed
755     }
756 
757     // Verify no events are received until sensors are re-activated
758     ASSERT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
759     activateAllSensors(true);
760     ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
761 
762     // Disable sensors
763     activateAllSensors(false);
764 
765     // Restore active sensors prior to clearing the environment
766     mSensorHandles = handles;
767 }
768 
TEST_P(SensorsAidlTest,FlushSensor)769 TEST_P(SensorsAidlTest, FlushSensor) {
770     std::vector<SensorInfo> sensors = getNonOneShotSensors();
771     if (sensors.size() == 0) {
772         return;
773     }
774 
775     constexpr int32_t kFlushes = 5;
776     runSingleFlushTest(sensors, true /* activateSensor */, 1 /* expectedFlushCount */,
777                        true /* expectedResult */);
778     runFlushTest(sensors, true /* activateSensor */, kFlushes, kFlushes, true /* expectedResult */);
779 }
780 
TEST_P(SensorsAidlTest,FlushOneShotSensor)781 TEST_P(SensorsAidlTest, FlushOneShotSensor) {
782     // Find a sensor that is a one-shot sensor
783     std::vector<SensorInfo> sensors = getOneShotSensors();
784     if (sensors.size() == 0) {
785         return;
786     }
787 
788     runSingleFlushTest(sensors, true /* activateSensor */, 0 /* expectedFlushCount */,
789                        false /* expectedResult */);
790 }
791 
TEST_P(SensorsAidlTest,FlushInactiveSensor)792 TEST_P(SensorsAidlTest, FlushInactiveSensor) {
793     // Attempt to find a non-one shot sensor, then a one-shot sensor if necessary
794     std::vector<SensorInfo> sensors = getNonOneShotSensors();
795     if (sensors.size() == 0) {
796         sensors = getOneShotSensors();
797         if (sensors.size() == 0) {
798             return;
799         }
800     }
801 
802     runSingleFlushTest(sensors, false /* activateSensor */, 0 /* expectedFlushCount */,
803                        false /* expectedResult */);
804 }
805 
TEST_P(SensorsAidlTest,Batch)806 TEST_P(SensorsAidlTest, Batch) {
807     if (getSensorsList().size() == 0) {
808         return;
809     }
810 
811     activateAllSensors(false /* enable */);
812     for (const SensorInfo& sensor : getSensorsList()) {
813         SCOPED_TRACE(::testing::Message()
814                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
815                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
816                      << " name=" << sensor.name);
817 
818         // Call batch on inactive sensor
819         // One shot sensors have minDelay set to -1 which is an invalid
820         // parameter. Use 0 instead to avoid errors.
821         int64_t samplingPeriodNs =
822                 extractReportMode(sensor.flags) == SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE
823                         ? 0
824                         : sensor.minDelayUs;
825         checkIsOk(batch(sensor.sensorHandle, samplingPeriodNs, 0 /* maxReportLatencyNs */));
826 
827         // Activate the sensor
828         activate(sensor.sensorHandle, true /* enabled */);
829 
830         // Call batch on an active sensor
831         checkIsOk(batch(sensor.sensorHandle, sensor.maxDelayUs, 0 /* maxReportLatencyNs */));
832     }
833     activateAllSensors(false /* enable */);
834 
835     // Call batch on an invalid sensor
836     SensorInfo sensor = getSensorsList().front();
837     sensor.sensorHandle = getInvalidSensorHandle();
838     ASSERT_EQ(batch(sensor.sensorHandle, sensor.minDelayUs, 0 /* maxReportLatencyNs */)
839                       .getExceptionCode(),
840               EX_ILLEGAL_ARGUMENT);
841 }
842 
TEST_P(SensorsAidlTest,Activate)843 TEST_P(SensorsAidlTest, Activate) {
844     if (getSensorsList().size() == 0) {
845         return;
846     }
847 
848     // Verify that sensor events are generated when activate is called
849     for (const SensorInfo& sensor : getSensorsList()) {
850         SCOPED_TRACE(::testing::Message()
851                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
852                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
853                      << " name=" << sensor.name);
854 
855         checkIsOk(batch(sensor.sensorHandle, sensor.minDelayUs, 0 /* maxReportLatencyNs */));
856         checkIsOk(activate(sensor.sensorHandle, true));
857 
858         // Call activate on a sensor that is already activated
859         checkIsOk(activate(sensor.sensorHandle, true));
860 
861         // Deactivate the sensor
862         checkIsOk(activate(sensor.sensorHandle, false));
863 
864         // Call deactivate on a sensor that is already deactivated
865         checkIsOk(activate(sensor.sensorHandle, false));
866     }
867 
868     // Attempt to activate an invalid sensor
869     int32_t invalidHandle = getInvalidSensorHandle();
870     ASSERT_EQ(activate(invalidHandle, true).getExceptionCode(), EX_ILLEGAL_ARGUMENT);
871     ASSERT_EQ(activate(invalidHandle, false).getExceptionCode(), EX_ILLEGAL_ARGUMENT);
872 }
873 
TEST_P(SensorsAidlTest,NoStaleEvents)874 TEST_P(SensorsAidlTest, NoStaleEvents) {
875     constexpr std::chrono::milliseconds kFiveHundredMs(500);
876     constexpr std::chrono::milliseconds kOneSecond(1000);
877 
878     // Register the callback to receive sensor events
879     EventCallback callback;
880     getEnvironment()->registerCallback(&callback);
881 
882     // This test is not valid for one-shot, on-change or special-report-mode sensors
883     const std::vector<SensorInfo> sensors = getNonOneShotAndNonOnChangeAndNonSpecialSensors();
884     std::chrono::milliseconds maxMinDelay(0);
885     for (const SensorInfo& sensor : sensors) {
886         std::chrono::milliseconds minDelay = duration_cast<std::chrono::milliseconds>(
887                 std::chrono::microseconds(sensor.minDelayUs));
888         maxMinDelay = std::chrono::milliseconds(std::max(maxMinDelay.count(), minDelay.count()));
889     }
890 
891     // Activate the sensors so that they start generating events
892     activateAllSensors(true);
893 
894     // According to the CDD, the first sample must be generated within 400ms + 2 * sample_time
895     // and the maximum reporting latency is 100ms + 2 * sample_time. Wait a sufficient amount
896     // of time to guarantee that a sample has arrived.
897     callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
898     activateAllSensors(false);
899 
900     // Save the last received event for each sensor
901     std::map<int32_t, int64_t> lastEventTimestampMap;
902     for (const SensorInfo& sensor : sensors) {
903         SCOPED_TRACE(::testing::Message()
904                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
905                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
906                      << " name=" << sensor.name);
907 
908         if (callback.getEvents(sensor.sensorHandle).size() >= 1) {
909             lastEventTimestampMap[sensor.sensorHandle] =
910                     callback.getEvents(sensor.sensorHandle).back().timestamp;
911         }
912     }
913 
914     // Allow some time to pass, reset the callback, then reactivate the sensors
915     usleep(duration_cast<std::chrono::microseconds>(kOneSecond + (5 * maxMinDelay)).count());
916     callback.reset();
917     activateAllSensors(true);
918     callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
919     activateAllSensors(false);
920 
921     getEnvironment()->unregisterCallback();
922 
923     for (const SensorInfo& sensor : sensors) {
924         SCOPED_TRACE(::testing::Message()
925                      << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
926                      << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
927                      << " name=" << sensor.name);
928 
929         // Skip sensors that did not previously report an event
930         if (lastEventTimestampMap.find(sensor.sensorHandle) == lastEventTimestampMap.end()) {
931             continue;
932         }
933 
934         // Skip sensors with no events
935         const std::vector<Event> events = callback.getEvents(sensor.sensorHandle);
936         if (events.empty()) {
937             continue;
938         }
939 
940         // Ensure that the first event received is not stale by ensuring that its timestamp is
941         // sufficiently different from the previous event
942         const Event newEvent = events.front();
943         std::chrono::milliseconds delta =
944                 duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds(
945                         newEvent.timestamp - lastEventTimestampMap[sensor.sensorHandle]));
946         std::chrono::milliseconds sensorMinDelay = duration_cast<std::chrono::milliseconds>(
947                 std::chrono::microseconds(sensor.minDelayUs));
948         ASSERT_GE(delta, kFiveHundredMs + (3 * sensorMinDelay));
949     }
950 }
951 
checkRateLevel(const SensorInfo & sensor,int32_t directChannelHandle,ISensors::RateLevel rateLevel,int32_t * reportToken)952 void SensorsAidlTest::checkRateLevel(const SensorInfo& sensor, int32_t directChannelHandle,
953                                      ISensors::RateLevel rateLevel, int32_t* reportToken) {
954     ndk::ScopedAStatus status =
955             configDirectReport(sensor.sensorHandle, directChannelHandle, rateLevel, reportToken);
956 
957     SCOPED_TRACE(::testing::Message()
958                  << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
959                  << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
960                  << " name=" << sensor.name);
961 
962     if (isDirectReportRateSupported(sensor, rateLevel)) {
963         ASSERT_TRUE(status.isOk());
964         if (rateLevel != ISensors::RateLevel::STOP) {
965           ASSERT_GT(*reportToken, 0);
966         }
967     } else {
968       ASSERT_EQ(status.getExceptionCode(), EX_ILLEGAL_ARGUMENT);
969     }
970 }
971 
queryDirectChannelSupport(ISensors::SharedMemInfo::SharedMemType memType,bool * supportsSharedMemType,bool * supportsAnyDirectChannel)972 void SensorsAidlTest::queryDirectChannelSupport(ISensors::SharedMemInfo::SharedMemType memType,
973                                                 bool* supportsSharedMemType,
974                                                 bool* supportsAnyDirectChannel) {
975     *supportsSharedMemType = false;
976     *supportsAnyDirectChannel = false;
977     for (const SensorInfo& curSensor : getSensorsList()) {
978         if (isDirectChannelTypeSupported(curSensor, memType)) {
979             *supportsSharedMemType = true;
980         }
981         if (isDirectChannelTypeSupported(curSensor,
982                                          ISensors::SharedMemInfo::SharedMemType::ASHMEM) ||
983             isDirectChannelTypeSupported(curSensor,
984                                          ISensors::SharedMemInfo::SharedMemType::GRALLOC)) {
985             *supportsAnyDirectChannel = true;
986         }
987 
988         if (*supportsSharedMemType && *supportsAnyDirectChannel) {
989             break;
990         }
991     }
992 }
993 
verifyRegisterDirectChannel(std::shared_ptr<SensorsAidlTestSharedMemory<SensorType,Event>> mem,int32_t * directChannelHandle,bool supportsSharedMemType,bool supportsAnyDirectChannel)994 void SensorsAidlTest::verifyRegisterDirectChannel(
995         std::shared_ptr<SensorsAidlTestSharedMemory<SensorType, Event>> mem,
996         int32_t* directChannelHandle, bool supportsSharedMemType, bool supportsAnyDirectChannel) {
997     char* buffer = mem->getBuffer();
998     size_t size = mem->getSize();
999 
1000     if (supportsSharedMemType) {
1001         memset(buffer, 0xff, size);
1002     }
1003 
1004     int32_t channelHandle;
1005 
1006     ::ndk::ScopedAStatus status = registerDirectChannel(mem->getSharedMemInfo(), &channelHandle);
1007     if (supportsSharedMemType) {
1008         ASSERT_TRUE(status.isOk());
1009         ASSERT_GT(channelHandle, 0);
1010 
1011         // Verify that the memory has been zeroed
1012         for (size_t i = 0; i < mem->getSize(); i++) {
1013           ASSERT_EQ(buffer[i], 0x00);
1014         }
1015     } else {
1016         int32_t error = supportsAnyDirectChannel ? EX_ILLEGAL_ARGUMENT : EX_UNSUPPORTED_OPERATION;
1017         ASSERT_EQ(status.getExceptionCode(), error);
1018     }
1019     *directChannelHandle = channelHandle;
1020 }
1021 
verifyUnregisterDirectChannel(int32_t * channelHandle,bool supportsAnyDirectChannel)1022 void SensorsAidlTest::verifyUnregisterDirectChannel(int32_t* channelHandle,
1023                                                     bool supportsAnyDirectChannel) {
1024     int result = supportsAnyDirectChannel ? EX_NONE : EX_UNSUPPORTED_OPERATION;
1025     ndk::ScopedAStatus status = unregisterDirectChannel(channelHandle);
1026     ASSERT_EQ(status.getExceptionCode(), result);
1027 }
1028 
verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType memType)1029 void SensorsAidlTest::verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType memType) {
1030     constexpr size_t kNumEvents = 1;
1031     constexpr size_t kMemSize = kNumEvents * kEventSize;
1032 
1033     std::shared_ptr<SensorsAidlTestSharedMemory<SensorType, Event>> mem(
1034             SensorsAidlTestSharedMemory<SensorType, Event>::create(memType, kMemSize));
1035     ASSERT_NE(mem, nullptr);
1036 
1037     bool supportsSharedMemType;
1038     bool supportsAnyDirectChannel;
1039     queryDirectChannelSupport(memType, &supportsSharedMemType, &supportsAnyDirectChannel);
1040 
1041     for (const SensorInfo& sensor : getSensorsList()) {
1042         int32_t directChannelHandle = 0;
1043         verifyRegisterDirectChannel(mem, &directChannelHandle, supportsSharedMemType,
1044                                     supportsAnyDirectChannel);
1045         verifyConfigure(sensor, memType, directChannelHandle, supportsAnyDirectChannel);
1046         verifyUnregisterDirectChannel(&directChannelHandle, supportsAnyDirectChannel);
1047     }
1048 }
1049 
verifyConfigure(const SensorInfo & sensor,ISensors::SharedMemInfo::SharedMemType memType,int32_t directChannelHandle,bool supportsAnyDirectChannel)1050 void SensorsAidlTest::verifyConfigure(const SensorInfo& sensor,
1051                                       ISensors::SharedMemInfo::SharedMemType memType,
1052                                       int32_t directChannelHandle, bool supportsAnyDirectChannel) {
1053     SCOPED_TRACE(::testing::Message()
1054                  << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
1055                  << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
1056                  << " name=" << sensor.name);
1057 
1058     int32_t reportToken = 0;
1059     if (isDirectChannelTypeSupported(sensor, memType)) {
1060         // Verify that each rate level is properly supported
1061         checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::NORMAL, &reportToken);
1062         checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::FAST, &reportToken);
1063         checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::VERY_FAST, &reportToken);
1064         checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::STOP, &reportToken);
1065 
1066         // Verify that a sensor handle of -1 is only acceptable when using RateLevel::STOP
1067         ndk::ScopedAStatus status = configDirectReport(-1 /* sensorHandle */, directChannelHandle,
1068                                                        ISensors::RateLevel::NORMAL, &reportToken);
1069         ASSERT_EQ(status.getExceptionCode(), EX_ILLEGAL_ARGUMENT);
1070 
1071         status = configDirectReport(-1 /* sensorHandle */, directChannelHandle,
1072                                     ISensors::RateLevel::STOP, &reportToken);
1073         ASSERT_TRUE(status.isOk());
1074     } else {
1075         // directChannelHandle will be -1 here, HAL should either reject it as a bad value if there
1076         // is some level of direct channel report, otherwise return INVALID_OPERATION if direct
1077         // channel is not supported at all
1078         int error = supportsAnyDirectChannel ? EX_ILLEGAL_ARGUMENT : EX_UNSUPPORTED_OPERATION;
1079         ndk::ScopedAStatus status = configDirectReport(sensor.sensorHandle, directChannelHandle,
1080                                                        ISensors::RateLevel::NORMAL, &reportToken);
1081         ASSERT_EQ(status.getExceptionCode(), error);
1082     }
1083 }
1084 
TEST_P(SensorsAidlTest,DirectChannelAshmem)1085 TEST_P(SensorsAidlTest, DirectChannelAshmem) {
1086     verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType::ASHMEM);
1087 }
1088 
TEST_P(SensorsAidlTest,DirectChannelGralloc)1089 TEST_P(SensorsAidlTest, DirectChannelGralloc) {
1090     verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType::GRALLOC);
1091 }
1092 
1093 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SensorsAidlTest);
1094 INSTANTIATE_TEST_SUITE_P(Sensors, SensorsAidlTest,
1095                          testing::ValuesIn(android::getAidlHalInstanceNames(ISensors::descriptor)),
1096                          android::PrintInstanceNameToString);
1097 
main(int argc,char ** argv)1098 int main(int argc, char** argv) {
1099     ::testing::InitGoogleTest(&argc, argv);
1100     ProcessState::self()->setThreadPoolMaxThreadCount(1);
1101     ProcessState::self()->startThreadPool();
1102     return RUN_ALL_TESTS();
1103 }
1104