blob: 33645b2a953310f75e3689dc92fac61fe80cf867 [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"
29#include "sensors-vts-utils/SensorsVtsEnvironmentBase.h"
30
31#include <cinttypes>
32#include <condition_variable>
33#include <map>
34#include <unordered_map>
35#include <unordered_set>
36#include <vector>
37
38using aidl::android::hardware::sensors::Event;
39using aidl::android::hardware::sensors::ISensors;
40using aidl::android::hardware::sensors::SensorInfo;
41using aidl::android::hardware::sensors::SensorStatus;
42using aidl::android::hardware::sensors::SensorType;
43using android::ProcessState;
44using std::chrono::duration_cast;
45
46namespace {
47
48static void assertTypeMatchStringType(SensorType type, const std::string& stringType) {
49 if (type >= SensorType::DEVICE_PRIVATE_BASE) {
50 return;
51 }
52
53 switch (type) {
54#define CHECK_TYPE_STRING_FOR_SENSOR_TYPE(type) \
55 case SensorType::type: \
56 ASSERT_STREQ(SENSOR_STRING_TYPE_##type, stringType.c_str()); \
57 break;
58 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER);
59 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_UNCALIBRATED);
60 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ADDITIONAL_INFO);
61 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(AMBIENT_TEMPERATURE);
62 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DEVICE_ORIENTATION);
63 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DYNAMIC_SENSOR_META);
64 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GAME_ROTATION_VECTOR);
65 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GEOMAGNETIC_ROTATION_VECTOR);
66 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GLANCE_GESTURE);
67 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GRAVITY);
68 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE);
69 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_UNCALIBRATED);
70 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_BEAT);
71 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_RATE);
72 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LIGHT);
73 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LINEAR_ACCELERATION);
74 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LOW_LATENCY_OFFBODY_DETECT);
75 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD);
76 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD_UNCALIBRATED);
77 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MOTION_DETECT);
78 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ORIENTATION);
79 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PICK_UP_GESTURE);
80 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(POSE_6DOF);
81 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PRESSURE);
82 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PROXIMITY);
83 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(RELATIVE_HUMIDITY);
84 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ROTATION_VECTOR);
85 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(SIGNIFICANT_MOTION);
86 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STATIONARY_DETECT);
87 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_COUNTER);
88 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_DETECTOR);
89 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TILT_DETECTOR);
90 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WAKE_GESTURE);
91 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WRIST_TILT_GESTURE);
92 default:
93 FAIL() << "Type " << static_cast<int>(type)
94 << " in android defined range is not checked, "
95 << "stringType = " << stringType;
96#undef CHECK_TYPE_STRING_FOR_SENSOR_TYPE
97 }
98}
99
100int expectedReportModeForType(SensorType type) {
101 switch (type) {
102 case SensorType::ACCELEROMETER:
103 case SensorType::ACCELEROMETER_UNCALIBRATED:
104 case SensorType::GYROSCOPE:
105 case SensorType::MAGNETIC_FIELD:
106 case SensorType::ORIENTATION:
107 case SensorType::PRESSURE:
108 case SensorType::GRAVITY:
109 case SensorType::LINEAR_ACCELERATION:
110 case SensorType::ROTATION_VECTOR:
111 case SensorType::MAGNETIC_FIELD_UNCALIBRATED:
112 case SensorType::GAME_ROTATION_VECTOR:
113 case SensorType::GYROSCOPE_UNCALIBRATED:
114 case SensorType::GEOMAGNETIC_ROTATION_VECTOR:
115 case SensorType::POSE_6DOF:
116 case SensorType::HEART_BEAT:
117 return SensorInfo::SENSOR_FLAG_BITS_CONTINUOUS_MODE;
118
119 case SensorType::LIGHT:
120 case SensorType::PROXIMITY:
121 case SensorType::RELATIVE_HUMIDITY:
122 case SensorType::AMBIENT_TEMPERATURE:
123 case SensorType::HEART_RATE:
124 case SensorType::DEVICE_ORIENTATION:
125 case SensorType::STEP_COUNTER:
126 case SensorType::LOW_LATENCY_OFFBODY_DETECT:
127 return SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE;
128
129 case SensorType::SIGNIFICANT_MOTION:
130 case SensorType::WAKE_GESTURE:
131 case SensorType::GLANCE_GESTURE:
132 case SensorType::PICK_UP_GESTURE:
133 case SensorType::MOTION_DETECT:
134 case SensorType::STATIONARY_DETECT:
135 return SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE;
136
137 case SensorType::STEP_DETECTOR:
138 case SensorType::TILT_DETECTOR:
139 case SensorType::WRIST_TILT_GESTURE:
140 case SensorType::DYNAMIC_SENSOR_META:
141 return SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE;
142
143 default:
144 ALOGW("Type %d is not implemented in expectedReportModeForType", (int)type);
145 return INT32_MAX;
146 }
147}
148
149void assertTypeMatchReportMode(SensorType type, int reportMode) {
150 if (type >= SensorType::DEVICE_PRIVATE_BASE) {
151 return;
152 }
153
154 int expected = expectedReportModeForType(type);
155
156 ASSERT_TRUE(expected == INT32_MAX || expected == reportMode)
157 << "reportMode=" << static_cast<int>(reportMode)
158 << "expected=" << static_cast<int>(expected);
159}
160
161void assertDelayMatchReportMode(int32_t minDelayUs, int32_t maxDelayUs, int reportMode) {
162 switch (reportMode) {
163 case SensorInfo::SENSOR_FLAG_BITS_CONTINUOUS_MODE:
164 ASSERT_LT(0, minDelayUs);
165 ASSERT_LE(0, maxDelayUs);
166 break;
167 case SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE:
168 ASSERT_LE(0, minDelayUs);
169 ASSERT_LE(0, maxDelayUs);
170 break;
171 case SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE:
172 ASSERT_EQ(-1, minDelayUs);
173 ASSERT_EQ(0, maxDelayUs);
174 break;
175 case SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE:
176 // do not enforce anything for special reporting mode
177 break;
178 default:
179 FAIL() << "Report mode " << static_cast<int>(reportMode) << " not checked";
180 }
181}
182
183void checkIsOk(ndk::ScopedAStatus status) {
184 ASSERT_TRUE(status.isOk());
185}
186
187} // namespace
188
189class EventCallback : public IEventCallback<Event> {
190 public:
191 void reset() {
192 mFlushMap.clear();
193 mEventMap.clear();
194 }
195
196 void onEvent(const Event& event) override {
197 if (event.sensorType == SensorType::META_DATA &&
198 event.payload.get<Event::EventPayload::Tag::meta>().what ==
199 Event::EventPayload::MetaData::MetaDataEventType::META_DATA_FLUSH_COMPLETE) {
200 std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
201 mFlushMap[event.sensorHandle]++;
202 mFlushCV.notify_all();
203 } else if (event.sensorType != SensorType::ADDITIONAL_INFO) {
204 std::unique_lock<std::recursive_mutex> lock(mEventMutex);
205 mEventMap[event.sensorHandle].push_back(event);
206 mEventCV.notify_all();
207 }
208 }
209
210 int32_t getFlushCount(int32_t sensorHandle) {
211 std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
212 return mFlushMap[sensorHandle];
213 }
214
215 void waitForFlushEvents(const std::vector<SensorInfo>& sensorsToWaitFor,
216 int32_t numCallsToFlush, std::chrono::milliseconds timeout) {
217 std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
218 mFlushCV.wait_for(lock, timeout,
219 [&] { return flushesReceived(sensorsToWaitFor, numCallsToFlush); });
220 }
221
222 const std::vector<Event> getEvents(int32_t sensorHandle) {
223 std::unique_lock<std::recursive_mutex> lock(mEventMutex);
224 return mEventMap[sensorHandle];
225 }
226
227 void waitForEvents(const std::vector<SensorInfo>& sensorsToWaitFor,
228 std::chrono::milliseconds timeout) {
229 std::unique_lock<std::recursive_mutex> lock(mEventMutex);
230 mEventCV.wait_for(lock, timeout, [&] { return eventsReceived(sensorsToWaitFor); });
231 }
232
233 protected:
234 bool flushesReceived(const std::vector<SensorInfo>& sensorsToWaitFor, int32_t numCallsToFlush) {
235 for (const SensorInfo& sensor : sensorsToWaitFor) {
236 if (getFlushCount(sensor.sensorHandle) < numCallsToFlush) {
237 return false;
238 }
239 }
240 return true;
241 }
242
243 bool eventsReceived(const std::vector<SensorInfo>& sensorsToWaitFor) {
244 for (const SensorInfo& sensor : sensorsToWaitFor) {
245 if (getEvents(sensor.sensorHandle).size() == 0) {
246 return false;
247 }
248 }
249 return true;
250 }
251
252 std::map<int32_t, int32_t> mFlushMap;
253 std::recursive_mutex mFlushMutex;
254 std::condition_variable_any mFlushCV;
255
256 std::map<int32_t, std::vector<Event>> mEventMap;
257 std::recursive_mutex mEventMutex;
258 std::condition_variable_any mEventCV;
259};
260
261class SensorsAidlTest : public testing::TestWithParam<std::string> {
262 public:
263 virtual void SetUp() override {
264 mEnvironment = new SensorsAidlEnvironment(GetParam());
265 mEnvironment->SetUp();
266
267 // Ensure that we have a valid environment before performing tests
268 ASSERT_NE(getSensors(), nullptr);
269 }
270
271 virtual void TearDown() override {
272 for (int32_t handle : mSensorHandles) {
273 activate(handle, false);
274 }
275 mSensorHandles.clear();
276
277 mEnvironment->TearDown();
278 delete mEnvironment;
279 mEnvironment = nullptr;
280 }
281
282 protected:
283 std::vector<SensorInfo> getNonOneShotSensors();
284 std::vector<SensorInfo> getNonOneShotAndNonSpecialSensors();
285 std::vector<SensorInfo> getNonOneShotAndNonOnChangeAndNonSpecialSensors();
286 std::vector<SensorInfo> getOneShotSensors();
287 std::vector<SensorInfo> getInjectEventSensors();
288
289 inline std::shared_ptr<ISensors>& getSensors() { return mEnvironment->mSensors; }
290
291 inline SensorsAidlEnvironment* getEnvironment() { return mEnvironment; }
292
293 inline bool isValidType(SensorType sensorType) { return (int)sensorType > 0; }
294
295 std::vector<SensorInfo> getSensorsList();
296
297 int32_t getInvalidSensorHandle() {
298 // Find a sensor handle that does not exist in the sensor list
299 int32_t maxHandle = 0;
300 for (const SensorInfo& sensor : getSensorsList()) {
301 maxHandle = std::max(maxHandle, sensor.sensorHandle);
302 }
303 return maxHandle + 1;
304 }
305
306 ndk::ScopedAStatus activate(int32_t sensorHandle, bool enable);
307 void activateAllSensors(bool enable);
308
309 ndk::ScopedAStatus batch(int32_t sensorHandle, int64_t samplingPeriodNs,
310 int64_t maxReportLatencyNs) {
311 return getSensors()->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs);
312 }
313
314 ndk::ScopedAStatus flush(int32_t sensorHandle) { return getSensors()->flush(sensorHandle); }
315
316 void runSingleFlushTest(const std::vector<SensorInfo>& sensors, bool activateSensor,
317 int32_t expectedFlushCount, bool expectedResult);
318
319 void runFlushTest(const std::vector<SensorInfo>& sensors, bool activateSensor,
320 int32_t flushCalls, int32_t expectedFlushCount, bool expectedResult);
321
322 inline static int32_t extractReportMode(int32_t flag) {
323 return (flag & (SensorInfo::SENSOR_FLAG_BITS_CONTINUOUS_MODE |
324 SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE |
325 SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE |
326 SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE));
327 }
328
329 // All sensors and direct channnels used
330 std::unordered_set<int32_t> mSensorHandles;
331 std::unordered_set<int32_t> mDirectChannelHandles;
332
333 private:
334 SensorsAidlEnvironment* mEnvironment;
335};
336
337std::vector<SensorInfo> SensorsAidlTest::getSensorsList() {
338 std::vector<SensorInfo> sensorInfoList;
339 checkIsOk(getSensors()->getSensorsList(&sensorInfoList));
340 return sensorInfoList;
341}
342
343ndk::ScopedAStatus SensorsAidlTest::activate(int32_t sensorHandle, bool enable) {
344 // If activating a sensor, add the handle in a set so that when test fails it can be turned off.
345 // The handle is not removed when it is deactivating on purpose so that it is not necessary to
346 // check the return value of deactivation. Deactivating a sensor more than once does not have
347 // negative effect.
348 if (enable) {
349 mSensorHandles.insert(sensorHandle);
350 }
351 return getSensors()->activate(sensorHandle, enable);
352}
353
354void SensorsAidlTest::activateAllSensors(bool enable) {
355 for (const SensorInfo& sensorInfo : getSensorsList()) {
356 if (isValidType(sensorInfo.type)) {
357 checkIsOk(batch(sensorInfo.sensorHandle, sensorInfo.minDelayUs,
358 0 /* maxReportLatencyNs */));
359 checkIsOk(activate(sensorInfo.sensorHandle, enable));
360 }
361 }
362}
363
364std::vector<SensorInfo> SensorsAidlTest::getNonOneShotSensors() {
365 std::vector<SensorInfo> sensors;
366 for (const SensorInfo& info : getSensorsList()) {
367 if (extractReportMode(info.flags) != SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE) {
368 sensors.push_back(info);
369 }
370 }
371 return sensors;
372}
373
374std::vector<SensorInfo> SensorsAidlTest::getNonOneShotAndNonSpecialSensors() {
375 std::vector<SensorInfo> sensors;
376 for (const SensorInfo& info : getSensorsList()) {
377 int reportMode = extractReportMode(info.flags);
378 if (reportMode != SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE &&
379 reportMode != SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE) {
380 sensors.push_back(info);
381 }
382 }
383 return sensors;
384}
385
386std::vector<SensorInfo> SensorsAidlTest::getNonOneShotAndNonOnChangeAndNonSpecialSensors() {
387 std::vector<SensorInfo> sensors;
388 for (const SensorInfo& info : getSensorsList()) {
389 int reportMode = extractReportMode(info.flags);
390 if (reportMode != SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE &&
391 reportMode != SensorInfo::SENSOR_FLAG_BITS_ON_CHANGE_MODE &&
392 reportMode != SensorInfo::SENSOR_FLAG_BITS_SPECIAL_REPORTING_MODE) {
393 sensors.push_back(info);
394 }
395 }
396 return sensors;
397}
398
399std::vector<SensorInfo> SensorsAidlTest::getOneShotSensors() {
400 std::vector<SensorInfo> sensors;
401 for (const SensorInfo& info : getSensorsList()) {
402 if (extractReportMode(info.flags) == SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE) {
403 sensors.push_back(info);
404 }
405 }
406 return sensors;
407}
408
409std::vector<SensorInfo> SensorsAidlTest::getInjectEventSensors() {
410 std::vector<SensorInfo> out;
411 std::vector<SensorInfo> sensorInfoList = getSensorsList();
412 for (const SensorInfo& info : sensorInfoList) {
413 if (info.flags & SensorInfo::SENSOR_FLAG_BITS_DATA_INJECTION) {
414 out.push_back(info);
415 }
416 }
417 return out;
418}
419
420void SensorsAidlTest::runSingleFlushTest(const std::vector<SensorInfo>& sensors,
421 bool activateSensor, int32_t expectedFlushCount,
422 bool expectedResult) {
423 runFlushTest(sensors, activateSensor, 1 /* flushCalls */, expectedFlushCount, expectedResult);
424}
425
426void SensorsAidlTest::runFlushTest(const std::vector<SensorInfo>& sensors, bool activateSensor,
427 int32_t flushCalls, int32_t expectedFlushCount,
428 bool expectedResult) {
429 EventCallback callback;
430 getEnvironment()->registerCallback(&callback);
431
432 for (const SensorInfo& sensor : sensors) {
433 // Configure and activate the sensor
434 batch(sensor.sensorHandle, sensor.maxDelayUs, 0 /* maxReportLatencyNs */);
435 activate(sensor.sensorHandle, activateSensor);
436
437 // Flush the sensor
438 for (int32_t i = 0; i < flushCalls; i++) {
439 SCOPED_TRACE(::testing::Message()
440 << "Flush " << i << "/" << flushCalls << ": "
441 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
442 << sensor.sensorHandle << std::dec
443 << " type=" << static_cast<int>(sensor.type) << " name=" << sensor.name);
444
445 EXPECT_EQ(flush(sensor.sensorHandle).isOk(), expectedResult);
446 }
447 }
448
449 // Wait up to one second for the flush events
450 callback.waitForFlushEvents(sensors, flushCalls, std::chrono::milliseconds(1000) /* timeout */);
451
452 // Deactivate all sensors after waiting for flush events so pending flush events are not
453 // abandoned by the HAL.
454 for (const SensorInfo& sensor : sensors) {
455 activate(sensor.sensorHandle, false);
456 }
457 getEnvironment()->unregisterCallback();
458
459 // Check that the correct number of flushes are present for each sensor
460 for (const SensorInfo& sensor : sensors) {
461 SCOPED_TRACE(::testing::Message()
462 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
463 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
464 << " name=" << sensor.name);
465 ASSERT_EQ(callback.getFlushCount(sensor.sensorHandle), expectedFlushCount);
466 }
467}
468
469TEST_P(SensorsAidlTest, SensorListValid) {
470 std::vector<SensorInfo> sensorInfoList = getSensorsList();
471 std::unordered_map<int32_t, std::vector<std::string>> sensorTypeNameMap;
472 for (size_t i = 0; i < sensorInfoList.size(); ++i) {
473 const SensorInfo& info = sensorInfoList[i];
474 SCOPED_TRACE(::testing::Message()
475 << i << "/" << sensorInfoList.size() << ": "
476 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
477 << info.sensorHandle << std::dec << " type=" << static_cast<int>(info.type)
478 << " name=" << info.name);
479
480 // Test type string non-empty only for private sensor typeinfo.
481 if (info.type >= SensorType::DEVICE_PRIVATE_BASE) {
482 EXPECT_FALSE(info.typeAsString.empty());
483 } else if (!info.typeAsString.empty()) {
484 // Test type string matches framework string if specified for non-private typeinfo.
485 EXPECT_NO_FATAL_FAILURE(assertTypeMatchStringType(info.type, info.typeAsString));
486 }
487
488 // Test if all sensor has name and vendor
489 EXPECT_FALSE(info.name.empty());
490 EXPECT_FALSE(info.vendor.empty());
491
492 // Make sure that sensors of the same type have a unique name.
493 std::vector<std::string>& v = sensorTypeNameMap[static_cast<int32_t>(info.type)];
494 bool isUniqueName = std::find(v.begin(), v.end(), info.name) == v.end();
495 EXPECT_TRUE(isUniqueName) << "Duplicate sensor Name: " << info.name;
496 if (isUniqueName) {
497 v.push_back(info.name);
498 }
499
500 EXPECT_LE(0, info.power);
501 EXPECT_LT(0, info.maxRange);
502
503 // Info type, should have no sensor
504 EXPECT_FALSE(info.type == SensorType::ADDITIONAL_INFO ||
505 info.type == SensorType::META_DATA);
506
507 EXPECT_GE(info.fifoMaxEventCount, info.fifoReservedEventCount);
508
509 // Test Reporting mode valid
510 EXPECT_NO_FATAL_FAILURE(
511 assertTypeMatchReportMode(info.type, extractReportMode(info.flags)));
512
513 // Test min max are in the right order
514 EXPECT_LE(info.minDelayUs, info.maxDelayUs);
515 // Test min/max delay matches reporting mode
516 EXPECT_NO_FATAL_FAILURE(assertDelayMatchReportMode(info.minDelayUs, info.maxDelayUs,
517 extractReportMode(info.flags)));
518 }
519}
520
521TEST_P(SensorsAidlTest, SetOperationMode) {
522 if (getInjectEventSensors().size() > 0) {
523 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
524 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::DATA_INJECTION).isOk());
525 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
526 } else {
527 ASSERT_EQ(getSensors()
528 ->setOperationMode(ISensors::OperationMode::DATA_INJECTION)
529 .getExceptionCode(),
530 EX_UNSUPPORTED_OPERATION);
531 }
532}
533
534TEST_P(SensorsAidlTest, InjectSensorEventData) {
535 std::vector<SensorInfo> sensors = getInjectEventSensors();
536 if (sensors.size() == 0) {
537 return;
538 }
539
540 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::DATA_INJECTION).isOk());
541
542 EventCallback callback;
543 getEnvironment()->registerCallback(&callback);
544
545 // AdditionalInfo event should not be sent to Event FMQ
546 Event additionalInfoEvent;
547 additionalInfoEvent.sensorType = SensorType::ADDITIONAL_INFO;
548 additionalInfoEvent.timestamp = android::elapsedRealtimeNano();
549
550 Event injectedEvent;
551 injectedEvent.timestamp = android::elapsedRealtimeNano();
552 Event::EventPayload::Vec3 data = {1, 2, 3, SensorStatus::ACCURACY_HIGH};
553 injectedEvent.payload.set<Event::EventPayload::Tag::vec3>(data);
554
555 for (const auto& s : sensors) {
556 additionalInfoEvent.sensorHandle = s.sensorHandle;
557 ASSERT_TRUE(getSensors()->injectSensorData(additionalInfoEvent).isOk());
558
559 injectedEvent.sensorType = s.type;
560 injectedEvent.sensorHandle = s.sensorHandle;
561 ASSERT_TRUE(getSensors()->injectSensorData(injectedEvent).isOk());
562 }
563
564 // Wait for events to be written back to the Event FMQ
565 callback.waitForEvents(sensors, std::chrono::milliseconds(1000) /* timeout */);
566 getEnvironment()->unregisterCallback();
567
568 for (const auto& s : sensors) {
569 auto events = callback.getEvents(s.sensorHandle);
570 if (events.empty()) {
571 FAIL() << "Received no events";
572 } else {
573 auto lastEvent = events.back();
574 SCOPED_TRACE(::testing::Message()
575 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
576 << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
577 << " name=" << s.name);
578
579 // Verify that only a single event has been received
580 ASSERT_EQ(events.size(), 1);
581
582 // Verify that the event received matches the event injected and is not the additional
583 // info event
584 ASSERT_EQ(lastEvent.sensorType, s.type);
585 ASSERT_EQ(lastEvent.timestamp, injectedEvent.timestamp);
586 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().x,
587 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().x);
588 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().y,
589 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().y);
590 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().z,
591 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().z);
592 ASSERT_EQ(lastEvent.payload.get<Event::EventPayload::Tag::vec3>().status,
593 injectedEvent.payload.get<Event::EventPayload::Tag::vec3>().status);
594 }
595 }
596
597 ASSERT_TRUE(getSensors()->setOperationMode(ISensors::OperationMode::NORMAL).isOk());
598}
599
600TEST_P(SensorsAidlTest, CallInitializeTwice) {
601 // Create a helper class so that a second environment is able to be instantiated
602 class SensorsAidlEnvironmentTest : public SensorsAidlEnvironment {
603 public:
604 SensorsAidlEnvironmentTest(const std::string& service_name)
605 : SensorsAidlEnvironment(service_name) {}
606 };
607
608 if (getSensorsList().size() == 0) {
609 // No sensors
610 return;
611 }
612
613 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
614 constexpr int32_t kNumEvents = 1;
615
616 // Create a new environment that calls initialize()
617 std::unique_ptr<SensorsAidlEnvironmentTest> newEnv =
618 std::make_unique<SensorsAidlEnvironmentTest>(GetParam());
619 newEnv->SetUp();
620 if (HasFatalFailure()) {
621 return; // Exit early if setting up the new environment failed
622 }
623
624 activateAllSensors(true);
625 // Verify that the old environment does not receive any events
626 EXPECT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
627 // Verify that the new event queue receives sensor events
628 EXPECT_GE(newEnv.get()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
629 activateAllSensors(false);
630
631 // Cleanup the test environment
632 newEnv->TearDown();
633
634 // Restore the test environment for future tests
635 getEnvironment()->TearDown();
636 getEnvironment()->SetUp();
637 if (HasFatalFailure()) {
638 return; // Exit early if resetting the environment failed
639 }
640
641 // Ensure that the original environment is receiving events
642 activateAllSensors(true);
643 EXPECT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
644 activateAllSensors(false);
645}
646
647TEST_P(SensorsAidlTest, CleanupConnectionsOnInitialize) {
648 activateAllSensors(true);
649
650 // Verify that events are received
651 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
652 constexpr int32_t kNumEvents = 1;
653 ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
654
655 // Clear the active sensor handles so they are not disabled during TearDown
656 auto handles = mSensorHandles;
657 mSensorHandles.clear();
658 getEnvironment()->TearDown();
659 getEnvironment()->SetUp();
660 if (HasFatalFailure()) {
661 return; // Exit early if resetting the environment failed
662 }
663
664 // Verify no events are received until sensors are re-activated
665 ASSERT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
666 activateAllSensors(true);
667 ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
668
669 // Disable sensors
670 activateAllSensors(false);
671
672 // Restore active sensors prior to clearing the environment
673 mSensorHandles = handles;
674}
675
676TEST_P(SensorsAidlTest, FlushSensor) {
677 std::vector<SensorInfo> sensors = getNonOneShotSensors();
678 if (sensors.size() == 0) {
679 return;
680 }
681
682 constexpr int32_t kFlushes = 5;
683 runSingleFlushTest(sensors, true /* activateSensor */, 1 /* expectedFlushCount */,
684 true /* expectedResult */);
685 runFlushTest(sensors, true /* activateSensor */, kFlushes, kFlushes, true /* expectedResult */);
686}
687
688TEST_P(SensorsAidlTest, FlushOneShotSensor) {
689 // Find a sensor that is a one-shot sensor
690 std::vector<SensorInfo> sensors = getOneShotSensors();
691 if (sensors.size() == 0) {
692 return;
693 }
694
695 runSingleFlushTest(sensors, true /* activateSensor */, 0 /* expectedFlushCount */,
696 false /* expectedResult */);
697}
698
699TEST_P(SensorsAidlTest, FlushInactiveSensor) {
700 // Attempt to find a non-one shot sensor, then a one-shot sensor if necessary
701 std::vector<SensorInfo> sensors = getNonOneShotSensors();
702 if (sensors.size() == 0) {
703 sensors = getOneShotSensors();
704 if (sensors.size() == 0) {
705 return;
706 }
707 }
708
709 runSingleFlushTest(sensors, false /* activateSensor */, 0 /* expectedFlushCount */,
710 false /* expectedResult */);
711}
712
713TEST_P(SensorsAidlTest, Batch) {
714 if (getSensorsList().size() == 0) {
715 return;
716 }
717
718 activateAllSensors(false /* enable */);
719 for (const SensorInfo& sensor : getSensorsList()) {
720 SCOPED_TRACE(::testing::Message()
721 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
722 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
723 << " name=" << sensor.name);
724
725 // Call batch on inactive sensor
726 // One shot sensors have minDelay set to -1 which is an invalid
727 // parameter. Use 0 instead to avoid errors.
728 int64_t samplingPeriodNs =
729 extractReportMode(sensor.flags) == SensorInfo::SENSOR_FLAG_BITS_ONE_SHOT_MODE
730 ? 0
731 : sensor.minDelayUs;
732 checkIsOk(batch(sensor.sensorHandle, samplingPeriodNs, 0 /* maxReportLatencyNs */));
733
734 // Activate the sensor
735 activate(sensor.sensorHandle, true /* enabled */);
736
737 // Call batch on an active sensor
738 checkIsOk(batch(sensor.sensorHandle, sensor.maxDelayUs, 0 /* maxReportLatencyNs */));
739 }
740 activateAllSensors(false /* enable */);
741
742 // Call batch on an invalid sensor
743 SensorInfo sensor = getSensorsList().front();
744 sensor.sensorHandle = getInvalidSensorHandle();
745 ASSERT_EQ(batch(sensor.sensorHandle, sensor.minDelayUs, 0 /* maxReportLatencyNs */)
746 .getExceptionCode(),
747 EX_ILLEGAL_ARGUMENT);
748}
749
750TEST_P(SensorsAidlTest, Activate) {
751 if (getSensorsList().size() == 0) {
752 return;
753 }
754
755 // Verify that sensor events are generated when activate is called
756 for (const SensorInfo& sensor : getSensorsList()) {
757 SCOPED_TRACE(::testing::Message()
758 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
759 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
760 << " name=" << sensor.name);
761
762 checkIsOk(batch(sensor.sensorHandle, sensor.minDelayUs, 0 /* maxReportLatencyNs */));
763 checkIsOk(activate(sensor.sensorHandle, true));
764
765 // Call activate on a sensor that is already activated
766 checkIsOk(activate(sensor.sensorHandle, true));
767
768 // Deactivate the sensor
769 checkIsOk(activate(sensor.sensorHandle, false));
770
771 // Call deactivate on a sensor that is already deactivated
772 checkIsOk(activate(sensor.sensorHandle, false));
773 }
774
775 // Attempt to activate an invalid sensor
776 int32_t invalidHandle = getInvalidSensorHandle();
777 ASSERT_EQ(activate(invalidHandle, true).getExceptionCode(), EX_ILLEGAL_ARGUMENT);
778 ASSERT_EQ(activate(invalidHandle, false).getExceptionCode(), EX_ILLEGAL_ARGUMENT);
779}
780
781TEST_P(SensorsAidlTest, NoStaleEvents) {
782 constexpr std::chrono::milliseconds kFiveHundredMs(500);
783 constexpr std::chrono::milliseconds kOneSecond(1000);
784
785 // Register the callback to receive sensor events
786 EventCallback callback;
787 getEnvironment()->registerCallback(&callback);
788
789 // This test is not valid for one-shot, on-change or special-report-mode sensors
790 const std::vector<SensorInfo> sensors = getNonOneShotAndNonOnChangeAndNonSpecialSensors();
791 std::chrono::milliseconds maxMinDelay(0);
792 for (const SensorInfo& sensor : sensors) {
793 std::chrono::milliseconds minDelay = duration_cast<std::chrono::milliseconds>(
794 std::chrono::microseconds(sensor.minDelayUs));
795 maxMinDelay = std::chrono::milliseconds(std::max(maxMinDelay.count(), minDelay.count()));
796 }
797
798 // Activate the sensors so that they start generating events
799 activateAllSensors(true);
800
801 // According to the CDD, the first sample must be generated within 400ms + 2 * sample_time
802 // and the maximum reporting latency is 100ms + 2 * sample_time. Wait a sufficient amount
803 // of time to guarantee that a sample has arrived.
804 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
805 activateAllSensors(false);
806
807 // Save the last received event for each sensor
808 std::map<int32_t, int64_t> lastEventTimestampMap;
809 for (const SensorInfo& sensor : sensors) {
810 SCOPED_TRACE(::testing::Message()
811 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
812 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
813 << " name=" << sensor.name);
814
815 if (callback.getEvents(sensor.sensorHandle).size() >= 1) {
816 lastEventTimestampMap[sensor.sensorHandle] =
817 callback.getEvents(sensor.sensorHandle).back().timestamp;
818 }
819 }
820
821 // Allow some time to pass, reset the callback, then reactivate the sensors
822 usleep(duration_cast<std::chrono::microseconds>(kOneSecond + (5 * maxMinDelay)).count());
823 callback.reset();
824 activateAllSensors(true);
825 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
826 activateAllSensors(false);
827
828 getEnvironment()->unregisterCallback();
829
830 for (const SensorInfo& sensor : sensors) {
831 SCOPED_TRACE(::testing::Message()
832 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
833 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
834 << " name=" << sensor.name);
835
836 // Skip sensors that did not previously report an event
837 if (lastEventTimestampMap.find(sensor.sensorHandle) == lastEventTimestampMap.end()) {
838 continue;
839 }
840
841 // Ensure that the first event received is not stale by ensuring that its timestamp is
842 // sufficiently different from the previous event
843 const Event newEvent = callback.getEvents(sensor.sensorHandle).front();
844 std::chrono::milliseconds delta =
845 duration_cast<std::chrono::milliseconds>(std::chrono::nanoseconds(
846 newEvent.timestamp - lastEventTimestampMap[sensor.sensorHandle]));
847 std::chrono::milliseconds sensorMinDelay = duration_cast<std::chrono::milliseconds>(
848 std::chrono::microseconds(sensor.minDelayUs));
849 ASSERT_GE(delta, kFiveHundredMs + (3 * sensorMinDelay));
850 }
851}
852
853TEST_P(SensorsAidlTest, DirectChannelAshmem) {
854 // TODO(b/195593357): Implement this
855}
856
857TEST_P(SensorsAidlTest, DirectChannelGralloc) {
858 // TODO(b/195593357): Implement this
859}
860
861GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SensorsAidlTest);
862INSTANTIATE_TEST_SUITE_P(Sensors, SensorsAidlTest,
863 testing::ValuesIn(android::getAidlHalInstanceNames(ISensors::descriptor)),
864 android::PrintInstanceNameToString);
865
866int main(int argc, char** argv) {
867 ::testing::InitGoogleTest(&argc, argv);
868 ProcessState::self()->setThreadPoolMaxThreadCount(1);
869 ProcessState::self()->startThreadPool();
870 return RUN_ALL_TESTS();
871}