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