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