blob: d536e290b235629cdae74206ffb03dfae2a326b3 [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 {
Arthur Ishiguroe9cb2932022-04-12 15:43:51 +0000602 int errorCode =
603 getSensors()
604 ->setOperationMode(ISensors::OperationMode::DATA_INJECTION)
605 .getExceptionCode();
606 ASSERT_TRUE((errorCode == EX_UNSUPPORTED_OPERATION) ||
607 (errorCode == EX_ILLEGAL_ARGUMENT));
Arthur Ishiguroc7ac0b22021-10-13 16:12:37 +0000608 }
609}
610
611TEST_P(SensorsAidlTest, InjectSensorEventData) {
612 std::vector<SensorInfo> sensors = getInjectEventSensors();
613 if (sensors.size() == 0) {
614 return;
615 }
616
617 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::DATA_INJECTION).isOk());
618
619 EventCallback callback;
620 getEnvironment()->registerCallback(&callback);
621
622 // AdditionalInfo event should not be sent to Event FMQ
623 Event additionalInfoEvent;
624 additionalInfoEvent.sensorType = SensorType::ADDITIONAL_INFO;
625 additionalInfoEvent.timestamp = android::elapsedRealtimeNano();
626
627 Event injectedEvent;
628 injectedEvent.timestamp = android::elapsedRealtimeNano();
629 Event::EventPayload::Vec3 data = {1, 2, 3, SensorStatus::ACCURACY_HIGH};
630 injectedEvent.payload.set<Event::EventPayload::Tag::vec3>(data);
631
632 for (const auto& s : sensors) {
633 additionalInfoEvent.sensorHandle = s.sensorHandle;
634 ASSERT_TRUE(getSensors()->injectSensorData(additionalInfoEvent).isOk());
635
636 injectedEvent.sensorType = s.type;
637 injectedEvent.sensorHandle = s.sensorHandle;
638 ASSERT_TRUE(getSensors()->injectSensorData(injectedEvent).isOk());
639 }
640
641 // Wait for events to be written back to the Event FMQ
642 callback.waitForEvents(sensors, std::chrono::milliseconds(1000) /* timeout */);
643 getEnvironment()->unregisterCallback();
644
645 for (const auto& s : sensors) {
646 auto events = callback.getEvents(s.sensorHandle);
647 if (events.empty()) {
648 FAIL() << "Received no events";
649 } else {
650 auto lastEvent = events.back();
651 SCOPED_TRACE(::testing::Message()
652 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
653 << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
654 << " name=" << s.name);
655
656 // Verify that only a single event has been received
657 ASSERT_EQ(events.size(), 1);
658
659 // Verify that the event received matches the event injected and is not the additional
660 // info event
661 ASSERT_EQ(lastEvent.sensorType, s.type);
662 ASSERT_EQ(lastEvent.timestamp, injectedEvent.timestamp);
663 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().x,
664 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().x);
665 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().y,
666 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().y);
667 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().z,
668 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().z);
669 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().status,
670 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().status);
671 }
672 }
673
674 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
675}
676
677TEST_P(SensorsAidlTest, CallInitializeTwice) {
678 // Create a helper class so that a second environment is able to be instantiated
679 class SensorsAidlEnvironmentTest : public SensorsAidlEnvironment {
680 public:
681 SensorsAidlEnvironmentTest(const std::string& service_name)
682 : SensorsAidlEnvironment(service_name) {}
683 };
684
685 if (getSensorsList().size() == 0) {
686 // No sensors
687 return;
688 }
689
690 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
691 constexpr int32_t kNumEvents = 1;
692
693 // Create a new environment that calls initialize()
694 std::unique_ptr<SensorsAidlEnvironmentTest> newEnv =
695 std::make_unique<SensorsAidlEnvironmentTest>(GetParam());
696 newEnv->SetUp();
697 if (HasFatalFailure()) {
698 return; // Exit early if setting up the new environment failed
699 }
700
701 activateAllSensors(true);
702 // Verify that the old environment does not receive any events
703 EXPECT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
704 // Verify that the new event queue receives sensor events
705 EXPECT_GE(newEnv.get()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
706 activateAllSensors(false);
707
708 // Cleanup the test environment
709 newEnv->TearDown();
710
711 // Restore the test environment for future tests
712 getEnvironment()->TearDown();
713 getEnvironment()->SetUp();
714 if (HasFatalFailure()) {
715 return; // Exit early if resetting the environment failed
716 }
717
718 // Ensure that the original environment is receiving events
719 activateAllSensors(true);
720 EXPECT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
721 activateAllSensors(false);
722}
723
724TEST_P(SensorsAidlTest, CleanupConnectionsOnInitialize) {
725 activateAllSensors(true);
726
727 // Verify that events are received
728 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
729 constexpr int32_t kNumEvents = 1;
730 ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
731
732 // Clear the active sensor handles so they are not disabled during TearDown
733 auto handles = mSensorHandles;
734 mSensorHandles.clear();
735 getEnvironment()->TearDown();
736 getEnvironment()->SetUp();
737 if (HasFatalFailure()) {
738 return; // Exit early if resetting the environment failed
739 }
740
741 // Verify no events are received until sensors are re-activated
742 ASSERT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
743 activateAllSensors(true);
744 ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
745
746 // Disable sensors
747 activateAllSensors(false);
748
749 // Restore active sensors prior to clearing the environment
750 mSensorHandles = handles;
751}
752
753TEST_P(SensorsAidlTest, FlushSensor) {
754 std::vector<SensorInfo> sensors = getNonOneShotSensors();
755 if (sensors.size() == 0) {
756 return;
757 }
758
759 constexpr int32_t kFlushes = 5;
760 runSingleFlushTest(sensors, true /* activateSensor */, 1 /* expectedFlushCount */,
761 true /* expectedResult */);
762 runFlushTest(sensors, true /* activateSensor */, kFlushes, kFlushes, true /* expectedResult */);
763}
764
765TEST_P(SensorsAidlTest, FlushOneShotSensor) {
766 // Find a sensor that is a one-shot sensor
767 std::vector<SensorInfo> sensors = getOneShotSensors();
768 if (sensors.size() == 0) {
769 return;
770 }
771
772 runSingleFlushTest(sensors, true /* activateSensor */, 0 /* expectedFlushCount */,
773 false /* expectedResult */);
774}
775
776TEST_P(SensorsAidlTest, FlushInactiveSensor) {
777 // Attempt to find a non-one shot sensor, then a one-shot sensor if necessary
778 std::vector<SensorInfo> sensors = getNonOneShotSensors();
779 if (sensors.size() == 0) {
780 sensors = getOneShotSensors();
781 if (sensors.size() == 0) {
782 return;
783 }
784 }
785
786 runSingleFlushTest(sensors, false /* activateSensor */, 0 /* expectedFlushCount */,
787 false /* expectedResult */);
788}
789
790TEST_P(SensorsAidlTest, Batch) {
791 if (getSensorsList().size() == 0) {
792 return;
793 }
794
795 activateAllSensors(false /* enable */);
796 for (const SensorInfo& sensor : getSensorsList()) {
797 SCOPED_TRACE(::testing::Message()
798 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
799 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
800 << " name=" << sensor.name);
801
802 // Call batch on inactive sensor
803 // One shot sensors have minDelay set to -1 which is an invalid
804 // parameter. Use 0 instead to avoid errors.
805 int64_t samplingPeriodNs =
806 extractReportMode(sensor.flags) == SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE
807 ? 0
808 : sensor.minDelayUs;
809 checkIsOk(batch(sensor.sensorHandle, samplingPeriodNs, 0 /* maxReportLatencyNs */));
810
811 // Activate the sensor
812 activate(sensor.sensorHandle, true /* enabled */);
813
814 // Call batch on an active sensor
815 checkIsOk(batch(sensor.sensorHandle, sensor.maxDelayUs, 0 /* maxReportLatencyNs */));
816 }
817 activateAllSensors(false /* enable */);
818
819 // Call batch on an invalid sensor
820 SensorInfo sensor = getSensorsList().front();
821 sensor.sensorHandle = getInvalidSensorHandle();
822 ASSERT_EQ(batch(sensor.sensorHandle, sensor.minDelayUs, 0 /* maxReportLatencyNs */)
823 .getExceptionCode(),
824 EX_ILLEGAL_ARGUMENT);
825}
826
827TEST_P(SensorsAidlTest, Activate) {
828 if (getSensorsList().size() == 0) {
829 return;
830 }
831
832 // Verify that sensor events are generated when activate is called
833 for (const SensorInfo& sensor : getSensorsList()) {
834 SCOPED_TRACE(::testing::Message()
835 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
836 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
837 << " name=" << sensor.name);
838
839 checkIsOk(batch(sensor.sensorHandle, sensor.minDelayUs, 0 /* maxReportLatencyNs */));
840 checkIsOk(activate(sensor.sensorHandle, true));
841
842 // Call activate on a sensor that is already activated
843 checkIsOk(activate(sensor.sensorHandle, true));
844
845 // Deactivate the sensor
846 checkIsOk(activate(sensor.sensorHandle, false));
847
848 // Call deactivate on a sensor that is already deactivated
849 checkIsOk(activate(sensor.sensorHandle, false));
850 }
851
852 // Attempt to activate an invalid sensor
853 int32_t invalidHandle = getInvalidSensorHandle();
854 ASSERT_EQ(activate(invalidHandle, true).getExceptionCode(), EX_ILLEGAL_ARGUMENT);
855 ASSERT_EQ(activate(invalidHandle, false).getExceptionCode(), EX_ILLEGAL_ARGUMENT);
856}
857
858TEST_P(SensorsAidlTest, NoStaleEvents) {
859 constexpr std::chrono::milliseconds kFiveHundredMs(500);
860 constexpr std::chrono::milliseconds kOneSecond(1000);
861
862 // Register the callback to receive sensor events
863 EventCallback callback;
864 getEnvironment()->registerCallback(&callback);
865
866 // This test is not valid for one-shot, on-change or special-report-mode sensors
867 const std::vector<SensorInfo> sensors = getNonOneShotAndNonOnChangeAndNonSpecialSensors();
868 std::chrono::milliseconds maxMinDelay(0);
869 for (const SensorInfo& sensor : sensors) {
870 std::chrono::milliseconds minDelay = duration_cast<std::chrono::milliseconds>(
871 std::chrono::microseconds(sensor.minDelayUs));
872 maxMinDelay = std::chrono::milliseconds(std::max(maxMinDelay.count(), minDelay.count()));
873 }
874
875 // Activate the sensors so that they start generating events
876 activateAllSensors(true);
877
878 // According to the CDD, the first sample must be generated within 400ms + 2 * sample_time
879 // and the maximum reporting latency is 100ms + 2 * sample_time. Wait a sufficient amount
880 // of time to guarantee that a sample has arrived.
881 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
882 activateAllSensors(false);
883
884 // Save the last received event for each sensor
885 std::map<int32_t, int64_t> lastEventTimestampMap;
886 for (const SensorInfo& sensor : sensors) {
887 SCOPED_TRACE(::testing::Message()
888 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
889 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
890 << " name=" << sensor.name);
891
892 if (callback.getEvents(sensor.sensorHandle).size() >= 1) {
893 lastEventTimestampMap[sensor.sensorHandle] =
894 callback.getEvents(sensor.sensorHandle).back().timestamp;
895 }
896 }
897
898 // Allow some time to pass, reset the callback, then reactivate the sensors
899 usleep(duration_cast<std::chrono::microseconds>(kOneSecond + (5 * maxMinDelay)).count());
900 callback.reset();
901 activateAllSensors(true);
902 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
903 activateAllSensors(false);
904
905 getEnvironment()->unregisterCallback();
906
907 for (const SensorInfo& sensor : sensors) {
908 SCOPED_TRACE(::testing::Message()
909 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
910 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
911 << " name=" << sensor.name);
912
913 // Skip sensors that did not previously report an event
914 if (lastEventTimestampMap.find(sensor.sensorHandle) == lastEventTimestampMap.end()) {
915 continue;
916 }
917
918 // Ensure that the first event received is not stale by ensuring that its timestamp is
919 // sufficiently different from the previous event
920 const Event newEvent = callback.getEvents(sensor.sensorHandle).front();
921 std::chrono::milliseconds delta =
922 duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds(
923 newEvent.timestamp - lastEventTimestampMap[sensor.sensorHandle]));
924 std::chrono::milliseconds sensorMinDelay = duration_cast<std::chrono::milliseconds>(
925 std::chrono::microseconds(sensor.minDelayUs));
926 ASSERT_GE(delta, kFiveHundredMs + (3 * sensorMinDelay));
927 }
928}
929
Grace Cheng629b3a42022-01-06 12:19:17 +0000930void SensorsAidlTest::checkRateLevel(const SensorInfo& sensor, int32_t directChannelHandle,
931 ISensors::RateLevel rateLevel, int32_t* reportToken) {
932 ndk::ScopedAStatus status =
933 configDirectReport(sensor.sensorHandle, directChannelHandle, rateLevel, reportToken);
934
935 SCOPED_TRACE(::testing::Message()
936 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
937 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
938 << " name=" << sensor.name);
939
940 if (isDirectReportRateSupported(sensor, rateLevel)) {
941 ASSERT_TRUE(status.isOk());
942 if (rateLevel != ISensors::RateLevel::STOP) {
Arthur Ishiguroe9cb2932022-04-12 15:43:51 +0000943 ASSERT_GT(*reportToken, 0);
Grace Cheng629b3a42022-01-06 12:19:17 +0000944 }
Arthur Ishiguroe9cb2932022-04-12 15:43:51 +0000945 } else {
946 ASSERT_EQ(status.getExceptionCode(), EX_ILLEGAL_ARGUMENT);
Grace Cheng629b3a42022-01-06 12:19:17 +0000947 }
948}
949
950void SensorsAidlTest::queryDirectChannelSupport(ISensors::SharedMemInfo::SharedMemType memType,
951 bool* supportsSharedMemType,
952 bool* supportsAnyDirectChannel) {
953 *supportsSharedMemType = false;
954 *supportsAnyDirectChannel = false;
955 for (const SensorInfo& curSensor : getSensorsList()) {
956 if (isDirectChannelTypeSupported(curSensor, memType)) {
957 *supportsSharedMemType = true;
958 }
959 if (isDirectChannelTypeSupported(curSensor,
960 ISensors::SharedMemInfo::SharedMemType::ASHMEM) ||
961 isDirectChannelTypeSupported(curSensor,
962 ISensors::SharedMemInfo::SharedMemType::GRALLOC)) {
963 *supportsAnyDirectChannel = true;
964 }
965
966 if (*supportsSharedMemType && *supportsAnyDirectChannel) {
967 break;
968 }
969 }
970}
971
972void SensorsAidlTest::verifyRegisterDirectChannel(
973 std::shared_ptr<SensorsAidlTestSharedMemory<SensorType, Event>> mem,
974 int32_t* directChannelHandle, bool supportsSharedMemType, bool supportsAnyDirectChannel) {
975 char* buffer = mem->getBuffer();
976 size_t size = mem->getSize();
977
978 if (supportsSharedMemType) {
979 memset(buffer, 0xff, size);
980 }
981
982 int32_t channelHandle;
983
984 ::ndk::ScopedAStatus status = registerDirectChannel(mem->getSharedMemInfo(), &channelHandle);
985 if (supportsSharedMemType) {
986 ASSERT_TRUE(status.isOk());
Arthur Ishiguroe9cb2932022-04-12 15:43:51 +0000987 ASSERT_GT(channelHandle, 0);
988
989 // Verify that the memory has been zeroed
990 for (size_t i = 0; i < mem->getSize(); i++) {
991 ASSERT_EQ(buffer[i], 0x00);
992 }
Grace Cheng629b3a42022-01-06 12:19:17 +0000993 } else {
994 int32_t error = supportsAnyDirectChannel ? EX_ILLEGAL_ARGUMENT : EX_UNSUPPORTED_OPERATION;
995 ASSERT_EQ(status.getExceptionCode(), error);
Grace Cheng629b3a42022-01-06 12:19:17 +0000996 }
Greg Kaiseraae30612022-01-14 07:54:49 -0800997 *directChannelHandle = channelHandle;
Grace Cheng629b3a42022-01-06 12:19:17 +0000998}
999
1000void SensorsAidlTest::verifyUnregisterDirectChannel(int32_t* channelHandle,
1001 bool supportsAnyDirectChannel) {
1002 int result = supportsAnyDirectChannel ? EX_NONE : EX_UNSUPPORTED_OPERATION;
1003 ndk::ScopedAStatus status = unregisterDirectChannel(channelHandle);
1004 ASSERT_EQ(status.getExceptionCode(), result);
1005}
1006
1007void SensorsAidlTest::verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType memType) {
1008 constexpr size_t kNumEvents = 1;
1009 constexpr size_t kMemSize = kNumEvents * kEventSize;
1010
1011 std::shared_ptr<SensorsAidlTestSharedMemory<SensorType, Event>> mem(
1012 SensorsAidlTestSharedMemory<SensorType, Event>::create(memType, kMemSize));
1013 ASSERT_NE(mem, nullptr);
1014
1015 bool supportsSharedMemType;
1016 bool supportsAnyDirectChannel;
1017 queryDirectChannelSupport(memType, &supportsSharedMemType, &supportsAnyDirectChannel);
1018
1019 for (const SensorInfo& sensor : getSensorsList()) {
1020 int32_t directChannelHandle = 0;
1021 verifyRegisterDirectChannel(mem, &directChannelHandle, supportsSharedMemType,
1022 supportsAnyDirectChannel);
1023 verifyConfigure(sensor, memType, directChannelHandle, supportsAnyDirectChannel);
1024 verifyUnregisterDirectChannel(&directChannelHandle, supportsAnyDirectChannel);
1025 }
1026}
1027
1028void SensorsAidlTest::verifyConfigure(const SensorInfo& sensor,
1029 ISensors::SharedMemInfo::SharedMemType memType,
1030 int32_t directChannelHandle, bool supportsAnyDirectChannel) {
1031 SCOPED_TRACE(::testing::Message()
1032 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
1033 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
1034 << " name=" << sensor.name);
1035
1036 int32_t reportToken = 0;
1037 if (isDirectChannelTypeSupported(sensor, memType)) {
1038 // Verify that each rate level is properly supported
1039 checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::NORMAL, &reportToken);
1040 checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::FAST, &reportToken);
1041 checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::VERY_FAST, &reportToken);
1042 checkRateLevel(sensor, directChannelHandle, ISensors::RateLevel::STOP, &reportToken);
1043
1044 // Verify that a sensor handle of -1 is only acceptable when using RateLevel::STOP
1045 ndk::ScopedAStatus status = configDirectReport(-1 /* sensorHandle */, directChannelHandle,
1046 ISensors::RateLevel::NORMAL, &reportToken);
Arthur Ishiguroe9cb2932022-04-12 15:43:51 +00001047 ASSERT_EQ(status.getExceptionCode(), EX_ILLEGAL_ARGUMENT);
Grace Cheng629b3a42022-01-06 12:19:17 +00001048
1049 status = configDirectReport(-1 /* sensorHandle */, directChannelHandle,
1050 ISensors::RateLevel::STOP, &reportToken);
1051 ASSERT_TRUE(status.isOk());
1052 } else {
1053 // directChannelHandle will be -1 here, HAL should either reject it as a bad value if there
1054 // is some level of direct channel report, otherwise return INVALID_OPERATION if direct
1055 // channel is not supported at all
1056 int error = supportsAnyDirectChannel ? EX_ILLEGAL_ARGUMENT : EX_UNSUPPORTED_OPERATION;
1057 ndk::ScopedAStatus status = configDirectReport(sensor.sensorHandle, directChannelHandle,
1058 ISensors::RateLevel::NORMAL, &reportToken);
1059 ASSERT_EQ(status.getExceptionCode(), error);
1060 }
1061}
1062
Arthur Ishiguroc7ac0b22021-10-13 16:12:37 +00001063TEST_P(SensorsAidlTest, DirectChannelAshmem) {
Grace Cheng629b3a42022-01-06 12:19:17 +00001064 verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType::ASHMEM);
Arthur Ishiguroc7ac0b22021-10-13 16:12:37 +00001065}
1066
1067TEST_P(SensorsAidlTest, DirectChannelGralloc) {
Grace Cheng629b3a42022-01-06 12:19:17 +00001068 verifyDirectChannel(ISensors::SharedMemInfo::SharedMemType::GRALLOC);
Arthur Ishiguroc7ac0b22021-10-13 16:12:37 +00001069}
1070
1071GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SensorsAidlTest);
1072INSTANTIATE_TEST_SUITE_P(Sensors, SensorsAidlTest,
1073 testing::ValuesIn(android::getAidlHalInstanceNames(ISensors::descriptor)),
1074 android::PrintInstanceNameToString);
1075
1076int main(int argc, char** argv) {
1077 ::testing::InitGoogleTest(&argc, argv);
1078 ProcessState::self()->setThreadPoolMaxThreadCount(1);
1079 ProcessState::self()->startThreadPool();
1080 return RUN_ALL_TESTS();
1081}