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