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