1 /*
2 * Copyright (C) 2018 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 "SensorsHidlEnvironmentV2_X.h"
17 #include "convertV2_1.h"
18 #include "sensors-vts-utils/SensorsHidlTestBase.h"
19 #include "sensors-vts-utils/SensorsTestSharedMemory.h"
20
21 #include <android/hardware/sensors/2.1/ISensors.h>
22 #include <android/hardware/sensors/2.1/types.h>
23
24 #include <hidl/GtestPrinter.h>
25 #include <hidl/ServiceManagement.h>
26 #include <log/log.h>
27 #include <utils/SystemClock.h>
28
29 #include <algorithm>
30 #include <cinttypes>
31 #include <condition_variable>
32 #include <cstring>
33 #include <map>
34 #include <unordered_map>
35 #include <vector>
36
37 /**
38 * This file contains the core tests and test logic for both sensors HAL 2.0
39 * and 2.1. To make it easier to share the code between both VTS test suites,
40 * this is defined as a header so they can both include and use all pieces of
41 * code.
42 */
43
44 using ::android::sp;
45 using ::android::hardware::Return;
46 using ::android::hardware::Void;
47 using ::android::hardware::sensors::V1_0::MetaDataEventType;
48 using ::android::hardware::sensors::V1_0::OperationMode;
49 using ::android::hardware::sensors::V1_0::SensorsEventFormatOffset;
50 using ::android::hardware::sensors::V1_0::SensorStatus;
51 using ::android::hardware::sensors::V1_0::SharedMemType;
52 using ::android::hardware::sensors::V1_0::Vec3;
53 using ::android::hardware::sensors::V2_1::implementation::convertToOldSensorInfos;
54 using std::chrono::duration_cast;
55 using std::chrono::microseconds;
56 using std::chrono::milliseconds;
57 using std::chrono::nanoseconds;
58
59 using EventV1_0 = ::android::hardware::sensors::V1_0::Event;
60 using ISensorsType = ::android::hardware::sensors::V2_1::ISensors;
61 using SensorTypeVersion = ::android::hardware::sensors::V2_1::SensorType;
62 using EventType = ::android::hardware::sensors::V2_1::Event;
63 using SensorInfoType = ::android::hardware::sensors::V2_1::SensorInfo;
64 using SensorsHidlTestBaseV2_X = SensorsHidlTestBase<SensorTypeVersion, EventType, SensorInfoType>;
65
66 constexpr size_t kEventSize = static_cast<size_t>(SensorsEventFormatOffset::TOTAL_LENGTH);
67
68 class EventCallback : public IEventCallback<EventType> {
69 public:
reset()70 void reset() {
71 mFlushMap.clear();
72 mEventMap.clear();
73 }
74
onEvent(const EventType & event)75 void onEvent(const EventType& event) override {
76 if (event.sensorType == SensorTypeVersion::META_DATA &&
77 event.u.meta.what == MetaDataEventType::META_DATA_FLUSH_COMPLETE) {
78 std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
79 mFlushMap[event.sensorHandle]++;
80 mFlushCV.notify_all();
81 } else if (event.sensorType != SensorTypeVersion::ADDITIONAL_INFO) {
82 std::unique_lock<std::recursive_mutex> lock(mEventMutex);
83 mEventMap[event.sensorHandle].push_back(event);
84 mEventCV.notify_all();
85 }
86 }
87
getFlushCount(int32_t sensorHandle)88 int32_t getFlushCount(int32_t sensorHandle) {
89 std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
90 return mFlushMap[sensorHandle];
91 }
92
waitForFlushEvents(const std::vector<SensorInfoType> & sensorsToWaitFor,int32_t numCallsToFlush,milliseconds timeout)93 void waitForFlushEvents(const std::vector<SensorInfoType>& sensorsToWaitFor,
94 int32_t numCallsToFlush, milliseconds timeout) {
95 std::unique_lock<std::recursive_mutex> lock(mFlushMutex);
96 mFlushCV.wait_for(lock, timeout,
97 [&] { return flushesReceived(sensorsToWaitFor, numCallsToFlush); });
98 }
99
getEvents(int32_t sensorHandle)100 const std::vector<EventType> getEvents(int32_t sensorHandle) {
101 std::unique_lock<std::recursive_mutex> lock(mEventMutex);
102 return mEventMap[sensorHandle];
103 }
104
waitForEvents(const std::vector<SensorInfoType> & sensorsToWaitFor,milliseconds timeout)105 void waitForEvents(const std::vector<SensorInfoType>& sensorsToWaitFor, milliseconds timeout) {
106 std::unique_lock<std::recursive_mutex> lock(mEventMutex);
107 mEventCV.wait_for(lock, timeout, [&] { return eventsReceived(sensorsToWaitFor); });
108 }
109
110 protected:
flushesReceived(const std::vector<SensorInfoType> & sensorsToWaitFor,int32_t numCallsToFlush)111 bool flushesReceived(const std::vector<SensorInfoType>& sensorsToWaitFor,
112 int32_t numCallsToFlush) {
113 for (const SensorInfoType& sensor : sensorsToWaitFor) {
114 if (getFlushCount(sensor.sensorHandle) < numCallsToFlush) {
115 return false;
116 }
117 }
118 return true;
119 }
120
eventsReceived(const std::vector<SensorInfoType> & sensorsToWaitFor)121 bool eventsReceived(const std::vector<SensorInfoType>& sensorsToWaitFor) {
122 for (const SensorInfoType& sensor : sensorsToWaitFor) {
123 if (getEvents(sensor.sensorHandle).size() == 0) {
124 return false;
125 }
126 }
127 return true;
128 }
129
130 std::map<int32_t, int32_t> mFlushMap;
131 std::recursive_mutex mFlushMutex;
132 std::condition_variable_any mFlushCV;
133
134 std::map<int32_t, std::vector<EventType>> mEventMap;
135 std::recursive_mutex mEventMutex;
136 std::condition_variable_any mEventCV;
137 };
138
139 /**
140 * Define the template specific versions of the static helper methods in
141 * SensorsHidlTestBase used to test that hinge angle is exposed properly.
142 */
143 template <>
expectedReportModeForType(::android::hardware::sensors::V2_1::SensorType type)144 SensorFlagBits expectedReportModeForType(::android::hardware::sensors::V2_1::SensorType type) {
145 switch (type) {
146 case ::android::hardware::sensors::V2_1::SensorType::HINGE_ANGLE:
147 return SensorFlagBits::ON_CHANGE_MODE;
148 default:
149 return expectedReportModeForType(
150 static_cast<::android::hardware::sensors::V1_0::SensorType>(type));
151 }
152 }
153
154 template <>
assertTypeMatchStringType(::android::hardware::sensors::V2_1::SensorType type,const hidl_string & stringType)155 void assertTypeMatchStringType(::android::hardware::sensors::V2_1::SensorType type,
156 const hidl_string& stringType) {
157 switch (type) {
158 case (::android::hardware::sensors::V2_1::SensorType::HINGE_ANGLE):
159 ASSERT_STREQ(SENSOR_STRING_TYPE_HINGE_ANGLE, stringType.c_str());
160 break;
161 default:
162 assertTypeMatchStringType(
163 static_cast<::android::hardware::sensors::V1_0::SensorType>(type), stringType);
164 break;
165 }
166 }
167
168 // The main test class for SENSORS HIDL HAL.
169 class SensorsHidlTest : public SensorsHidlTestBaseV2_X {
170 public:
SetUp()171 virtual void SetUp() override {
172 mEnvironment = new SensorsHidlEnvironmentV2_X(GetParam());
173 mEnvironment->HidlSetUp();
174 // Ensure that we have a valid environment before performing tests
175 ASSERT_NE(getSensors(), nullptr);
176 }
177
TearDown()178 virtual void TearDown() override { mEnvironment->HidlTearDown(); }
179
180 protected:
181 SensorInfoType defaultSensorByType(SensorTypeVersion type) override;
182 std::vector<SensorInfoType> getSensorsList();
183 // implementation wrapper
184
getSensorsList(ISensorsType::getSensorsList_cb _hidl_cb)185 Return<void> getSensorsList(ISensorsType::getSensorsList_cb _hidl_cb) override {
186 return getSensors()->getSensorsList(
187 [&](const auto& list) { _hidl_cb(convertToOldSensorInfos(list)); });
188 }
189
190 Return<Result> activate(int32_t sensorHandle, bool enabled) override;
191
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)192 Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
193 int64_t maxReportLatencyNs) override {
194 return getSensors()->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs);
195 }
196
flush(int32_t sensorHandle)197 Return<Result> flush(int32_t sensorHandle) override {
198 return getSensors()->flush(sensorHandle);
199 }
200
injectSensorData(const EventType & event)201 Return<Result> injectSensorData(const EventType& event) override {
202 return getSensors()->injectSensorData(event);
203 }
204
205 Return<void> registerDirectChannel(const SharedMemInfo& mem,
206 ISensorsType::registerDirectChannel_cb _hidl_cb) override;
207
unregisterDirectChannel(int32_t channelHandle)208 Return<Result> unregisterDirectChannel(int32_t channelHandle) override {
209 return getSensors()->unregisterDirectChannel(channelHandle);
210 }
211
configDirectReport(int32_t sensorHandle,int32_t channelHandle,RateLevel rate,ISensorsType::configDirectReport_cb _hidl_cb)212 Return<void> configDirectReport(int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
213 ISensorsType::configDirectReport_cb _hidl_cb) override {
214 return getSensors()->configDirectReport(sensorHandle, channelHandle, rate, _hidl_cb);
215 }
216
getSensors()217 inline sp<ISensorsWrapperBase>& getSensors() { return mEnvironment->mSensors; }
218
getEnvironment()219 SensorsHidlEnvironmentBase<EventType>* getEnvironment() override { return mEnvironment; }
220
221 // Test helpers
222 void runSingleFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
223 int32_t expectedFlushCount, Result expectedResponse);
224 void runFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
225 int32_t flushCalls, int32_t expectedFlushCount, Result expectedResponse);
226
227 // Helper functions
228 void activateAllSensors(bool enable);
229 std::vector<SensorInfoType> getNonOneShotSensors();
230 std::vector<SensorInfoType> getNonOneShotAndNonSpecialSensors();
231 std::vector<SensorInfoType> getNonOneShotAndNonOnChangeAndNonSpecialSensors();
232 std::vector<SensorInfoType> getOneShotSensors();
233 std::vector<SensorInfoType> getInjectEventSensors();
234 int32_t getInvalidSensorHandle();
235 bool getDirectChannelSensor(SensorInfoType* sensor, SharedMemType* memType, RateLevel* rate);
236 void verifyDirectChannel(SharedMemType memType);
237 void verifyRegisterDirectChannel(
238 std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem,
239 int32_t* directChannelHandle, bool supportsSharedMemType,
240 bool supportsAnyDirectChannel);
241 void verifyConfigure(const SensorInfoType& sensor, SharedMemType memType,
242 int32_t directChannelHandle, bool directChannelSupported);
243 void verifyUnregisterDirectChannel(int32_t directChannelHandle, bool directChannelSupported);
244 void checkRateLevel(const SensorInfoType& sensor, int32_t directChannelHandle,
245 RateLevel rateLevel);
246 void queryDirectChannelSupport(SharedMemType memType, bool* supportsSharedMemType,
247 bool* supportsAnyDirectChannel);
248
249 private:
250 // Test environment for sensors HAL.
251 SensorsHidlEnvironmentV2_X* mEnvironment;
252 };
253
activate(int32_t sensorHandle,bool enabled)254 Return<Result> SensorsHidlTest::activate(int32_t sensorHandle, bool enabled) {
255 // If activating a sensor, add the handle in a set so that when test fails it can be turned off.
256 // The handle is not removed when it is deactivating on purpose so that it is not necessary to
257 // check the return value of deactivation. Deactivating a sensor more than once does not have
258 // negative effect.
259 if (enabled) {
260 mSensorHandles.insert(sensorHandle);
261 }
262 return getSensors()->activate(sensorHandle, enabled);
263 }
264
registerDirectChannel(const SharedMemInfo & mem,ISensors::registerDirectChannel_cb cb)265 Return<void> SensorsHidlTest::registerDirectChannel(const SharedMemInfo& mem,
266 ISensors::registerDirectChannel_cb cb) {
267 // If registeration of a channel succeeds, add the handle of channel to a set so that it can be
268 // unregistered when test fails. Unregister a channel does not remove the handle on purpose.
269 // Unregistering a channel more than once should not have negative effect.
270 getSensors()->registerDirectChannel(mem, [&](auto result, auto channelHandle) {
271 if (result == Result::OK) {
272 mDirectChannelHandles.insert(channelHandle);
273 }
274 cb(result, channelHandle);
275 });
276 return Void();
277 }
278
defaultSensorByType(SensorTypeVersion type)279 SensorInfoType SensorsHidlTest::defaultSensorByType(SensorTypeVersion type) {
280 SensorInfoType ret;
281
282 ret.type = (SensorTypeVersion)-1;
283 getSensors()->getSensorsList([&](const auto& list) {
284 const size_t count = list.size();
285 for (size_t i = 0; i < count; ++i) {
286 if (list[i].type == type) {
287 ret = list[i];
288 return;
289 }
290 }
291 });
292
293 return ret;
294 }
295
getSensorsList()296 std::vector<SensorInfoType> SensorsHidlTest::getSensorsList() {
297 std::vector<SensorInfoType> ret;
298
299 getSensors()->getSensorsList([&](const auto& list) {
300 const size_t count = list.size();
301 ret.reserve(list.size());
302 for (size_t i = 0; i < count; ++i) {
303 ret.push_back(list[i]);
304 }
305 });
306
307 return ret;
308 }
309
getNonOneShotSensors()310 std::vector<SensorInfoType> SensorsHidlTest::getNonOneShotSensors() {
311 std::vector<SensorInfoType> sensors;
312 for (const SensorInfoType& info : getSensorsList()) {
313 if (extractReportMode(info.flags) != SensorFlagBits::ONE_SHOT_MODE) {
314 sensors.push_back(info);
315 }
316 }
317 return sensors;
318 }
319
getNonOneShotAndNonSpecialSensors()320 std::vector<SensorInfoType> SensorsHidlTest::getNonOneShotAndNonSpecialSensors() {
321 std::vector<SensorInfoType> sensors;
322 for (const SensorInfoType& info : getSensorsList()) {
323 SensorFlagBits reportMode = extractReportMode(info.flags);
324 if (reportMode != SensorFlagBits::ONE_SHOT_MODE &&
325 reportMode != SensorFlagBits::SPECIAL_REPORTING_MODE) {
326 sensors.push_back(info);
327 }
328 }
329 return sensors;
330 }
331
getNonOneShotAndNonOnChangeAndNonSpecialSensors()332 std::vector<SensorInfoType> SensorsHidlTest::getNonOneShotAndNonOnChangeAndNonSpecialSensors() {
333 std::vector<SensorInfoType> sensors;
334 for (const SensorInfoType& info : getSensorsList()) {
335 SensorFlagBits reportMode = extractReportMode(info.flags);
336 if (reportMode != SensorFlagBits::ONE_SHOT_MODE &&
337 reportMode != SensorFlagBits::ON_CHANGE_MODE &&
338 reportMode != SensorFlagBits::SPECIAL_REPORTING_MODE) {
339 sensors.push_back(info);
340 }
341 }
342 return sensors;
343 }
344
getOneShotSensors()345 std::vector<SensorInfoType> SensorsHidlTest::getOneShotSensors() {
346 std::vector<SensorInfoType> sensors;
347 for (const SensorInfoType& info : getSensorsList()) {
348 if (extractReportMode(info.flags) == SensorFlagBits::ONE_SHOT_MODE) {
349 sensors.push_back(info);
350 }
351 }
352 return sensors;
353 }
354
getInjectEventSensors()355 std::vector<SensorInfoType> SensorsHidlTest::getInjectEventSensors() {
356 std::vector<SensorInfoType> sensors;
357 for (const SensorInfoType& info : getSensorsList()) {
358 if (info.flags & static_cast<uint32_t>(SensorFlagBits::DATA_INJECTION)) {
359 sensors.push_back(info);
360 }
361 }
362 return sensors;
363 }
364
getInvalidSensorHandle()365 int32_t SensorsHidlTest::getInvalidSensorHandle() {
366 // Find a sensor handle that does not exist in the sensor list
367 int32_t maxHandle = 0;
368 for (const SensorInfoType& sensor : getSensorsList()) {
369 maxHandle = std::max(maxHandle, sensor.sensorHandle);
370 }
371 return maxHandle + 42;
372 }
373
374 // Test if sensor list returned is valid
TEST_P(SensorsHidlTest,SensorListValid)375 TEST_P(SensorsHidlTest, SensorListValid) {
376 getSensors()->getSensorsList([&](const auto& list) {
377 const size_t count = list.size();
378 std::unordered_map<int32_t, std::vector<std::string>> sensorTypeNameMap;
379 for (size_t i = 0; i < count; ++i) {
380 const auto& s = list[i];
381 SCOPED_TRACE(::testing::Message()
382 << i << "/" << count << ": "
383 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
384 << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
385 << " name=" << s.name);
386
387 // Test type string non-empty only for private sensor types.
388 if (s.type >= SensorTypeVersion::DEVICE_PRIVATE_BASE) {
389 EXPECT_FALSE(s.typeAsString.empty());
390 } else if (!s.typeAsString.empty()) {
391 // Test type string matches framework string if specified for non-private types.
392 EXPECT_NO_FATAL_FAILURE(assertTypeMatchStringType(s.type, s.typeAsString));
393 }
394
395 // Test if all sensor has name and vendor
396 EXPECT_FALSE(s.name.empty());
397 EXPECT_FALSE(s.vendor.empty());
398
399 // Make sure that sensors of the same type have a unique name.
400 std::vector<std::string>& v = sensorTypeNameMap[static_cast<int32_t>(s.type)];
401 bool isUniqueName = std::find(v.begin(), v.end(), s.name) == v.end();
402 EXPECT_TRUE(isUniqueName) << "Duplicate sensor Name: " << s.name;
403 if (isUniqueName) {
404 v.push_back(s.name);
405 }
406
407 // Test power > 0, maxRange > 0
408 EXPECT_LE(0, s.power);
409 EXPECT_LT(0, s.maxRange);
410
411 // Info type, should have no sensor
412 EXPECT_FALSE(s.type == SensorTypeVersion::ADDITIONAL_INFO ||
413 s.type == SensorTypeVersion::META_DATA);
414
415 // Test fifoMax >= fifoReserved
416 EXPECT_GE(s.fifoMaxEventCount, s.fifoReservedEventCount)
417 << "max=" << s.fifoMaxEventCount << " reserved=" << s.fifoReservedEventCount;
418
419 // Test Reporting mode valid
420 EXPECT_NO_FATAL_FAILURE(assertTypeMatchReportMode(s.type, extractReportMode(s.flags)));
421
422 // Test min max are in the right order
423 EXPECT_LE(s.minDelay, s.maxDelay);
424 // Test min/max delay matches reporting mode
425 EXPECT_NO_FATAL_FAILURE(
426 assertDelayMatchReportMode(s.minDelay, s.maxDelay, extractReportMode(s.flags)));
427 }
428 });
429 }
430
431 // Test that SetOperationMode returns the expected value
TEST_P(SensorsHidlTest,SetOperationMode)432 TEST_P(SensorsHidlTest, SetOperationMode) {
433 std::vector<SensorInfoType> sensors = getInjectEventSensors();
434 if (getInjectEventSensors().size() > 0) {
435 ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::NORMAL));
436 ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::DATA_INJECTION));
437 ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::NORMAL));
438 } else {
439 ASSERT_EQ(Result::BAD_VALUE, getSensors()->setOperationMode(OperationMode::DATA_INJECTION));
440 }
441 }
442
443 // Test that an injected event is written back to the Event FMQ
TEST_P(SensorsHidlTest,InjectSensorEventData)444 TEST_P(SensorsHidlTest, InjectSensorEventData) {
445 std::vector<SensorInfoType> sensors = getInjectEventSensors();
446 if (sensors.size() == 0) {
447 return;
448 }
449
450 ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::DATA_INJECTION));
451
452 EventCallback callback;
453 getEnvironment()->registerCallback(&callback);
454
455 // AdditionalInfo event should not be sent to Event FMQ
456 EventType additionalInfoEvent;
457 additionalInfoEvent.sensorType = SensorTypeVersion::ADDITIONAL_INFO;
458 additionalInfoEvent.timestamp = android::elapsedRealtimeNano();
459
460 EventType injectedEvent;
461 injectedEvent.timestamp = android::elapsedRealtimeNano();
462 Vec3 data = {1, 2, 3, SensorStatus::ACCURACY_HIGH};
463 injectedEvent.u.vec3 = data;
464
465 for (const auto& s : sensors) {
466 additionalInfoEvent.sensorHandle = s.sensorHandle;
467 EXPECT_EQ(Result::OK, getSensors()->injectSensorData(additionalInfoEvent));
468
469 injectedEvent.sensorType = s.type;
470 injectedEvent.sensorHandle = s.sensorHandle;
471 EXPECT_EQ(Result::OK, getSensors()->injectSensorData(injectedEvent));
472 }
473
474 // Wait for events to be written back to the Event FMQ
475 callback.waitForEvents(sensors, milliseconds(1000) /* timeout */);
476 getEnvironment()->unregisterCallback();
477
478 for (const auto& s : sensors) {
479 auto events = callback.getEvents(s.sensorHandle);
480 auto lastEvent = events.back();
481 SCOPED_TRACE(::testing::Message()
482 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
483 << s.sensorHandle << std::dec << " type=" << static_cast<int>(s.type)
484 << " name=" << s.name);
485
486 // Verify that only a single event has been received
487 ASSERT_EQ(events.size(), 1);
488
489 // Verify that the event received matches the event injected and is not the additional
490 // info event
491 ASSERT_EQ(lastEvent.sensorType, s.type);
492 ASSERT_EQ(lastEvent.sensorType, s.type);
493 ASSERT_EQ(lastEvent.timestamp, injectedEvent.timestamp);
494 ASSERT_EQ(lastEvent.u.vec3.x, injectedEvent.u.vec3.x);
495 ASSERT_EQ(lastEvent.u.vec3.y, injectedEvent.u.vec3.y);
496 ASSERT_EQ(lastEvent.u.vec3.z, injectedEvent.u.vec3.z);
497 ASSERT_EQ(lastEvent.u.vec3.status, injectedEvent.u.vec3.status);
498 }
499
500 ASSERT_EQ(Result::OK, getSensors()->setOperationMode(OperationMode::NORMAL));
501 }
502
activateAllSensors(bool enable)503 void SensorsHidlTest::activateAllSensors(bool enable) {
504 for (const SensorInfoType& sensorInfo : getSensorsList()) {
505 if (isValidType(sensorInfo.type)) {
506 batch(sensorInfo.sensorHandle, sensorInfo.minDelay, 0 /* maxReportLatencyNs */);
507 activate(sensorInfo.sensorHandle, enable);
508 }
509 }
510 }
511
512 // Test that if initialize is called twice, then the HAL writes events to the FMQs from the second
513 // call to the function.
TEST_P(SensorsHidlTest,CallInitializeTwice)514 TEST_P(SensorsHidlTest, CallInitializeTwice) {
515 // Create a helper class so that a second environment is able to be instantiated
516 class SensorsHidlEnvironmentTest : public SensorsHidlEnvironmentV2_X {
517 public:
518 SensorsHidlEnvironmentTest(const std::string& service_name)
519 : SensorsHidlEnvironmentV2_X(service_name) {}
520 };
521
522 if (getSensorsList().size() == 0) {
523 // No sensors
524 return;
525 }
526
527 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
528 constexpr int32_t kNumEvents = 1;
529
530 // Create a new environment that calls initialize()
531 std::unique_ptr<SensorsHidlEnvironmentTest> newEnv =
532 std::make_unique<SensorsHidlEnvironmentTest>(GetParam());
533 newEnv->HidlSetUp();
534 if (HasFatalFailure()) {
535 return; // Exit early if setting up the new environment failed
536 }
537
538 activateAllSensors(true);
539 // Verify that the old environment does not receive any events
540 EXPECT_EQ(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), 0);
541 // Verify that the new event queue receives sensor events
542 EXPECT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents, newEnv.get(), newEnv.get()).size(),
543 kNumEvents);
544 activateAllSensors(false);
545
546 // Cleanup the test environment
547 newEnv->HidlTearDown();
548
549 // Restore the test environment for future tests
550 getEnvironment()->HidlTearDown();
551 getEnvironment()->HidlSetUp();
552 if (HasFatalFailure()) {
553 return; // Exit early if resetting the environment failed
554 }
555
556 // Ensure that the original environment is receiving events
557 activateAllSensors(true);
558 EXPECT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
559 activateAllSensors(false);
560 }
561
TEST_P(SensorsHidlTest,CleanupConnectionsOnInitialize)562 TEST_P(SensorsHidlTest, CleanupConnectionsOnInitialize) {
563 activateAllSensors(true);
564
565 // Verify that events are received
566 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
567 constexpr int32_t kNumEvents = 1;
568 ASSERT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), kNumEvents);
569
570 // Clear the active sensor handles so they are not disabled during TearDown
571 auto handles = mSensorHandles;
572 mSensorHandles.clear();
573 getEnvironment()->HidlTearDown();
574 getEnvironment()->HidlSetUp();
575 if (HasFatalFailure()) {
576 return; // Exit early if resetting the environment failed
577 }
578
579 // Verify no events are received until sensors are re-activated
580 ASSERT_EQ(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), 0);
581 activateAllSensors(true);
582 ASSERT_GE(collectEvents(kCollectionTimeoutUs, kNumEvents, getEnvironment()).size(), kNumEvents);
583
584 // Disable sensors
585 activateAllSensors(false);
586
587 // Restore active sensors prior to clearing the environment
588 mSensorHandles = handles;
589 }
590
runSingleFlushTest(const std::vector<SensorInfoType> & sensors,bool activateSensor,int32_t expectedFlushCount,Result expectedResponse)591 void SensorsHidlTest::runSingleFlushTest(const std::vector<SensorInfoType>& sensors,
592 bool activateSensor, int32_t expectedFlushCount,
593 Result expectedResponse) {
594 runFlushTest(sensors, activateSensor, 1 /* flushCalls */, expectedFlushCount, expectedResponse);
595 }
596
runFlushTest(const std::vector<SensorInfoType> & sensors,bool activateSensor,int32_t flushCalls,int32_t expectedFlushCount,Result expectedResponse)597 void SensorsHidlTest::runFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
598 int32_t flushCalls, int32_t expectedFlushCount,
599 Result expectedResponse) {
600 EventCallback callback;
601 getEnvironment()->registerCallback(&callback);
602
603 for (const SensorInfoType& sensor : sensors) {
604 // Configure and activate the sensor
605 batch(sensor.sensorHandle, sensor.maxDelay, 0 /* maxReportLatencyNs */);
606 activate(sensor.sensorHandle, activateSensor);
607
608 // Flush the sensor
609 for (int32_t i = 0; i < flushCalls; i++) {
610 SCOPED_TRACE(::testing::Message()
611 << "Flush " << i << "/" << flushCalls << ": "
612 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
613 << sensor.sensorHandle << std::dec
614 << " type=" << static_cast<int>(sensor.type) << " name=" << sensor.name);
615
616 Result flushResult = flush(sensor.sensorHandle);
617 EXPECT_EQ(flushResult, expectedResponse);
618 }
619 }
620
621 // Wait up to one second for the flush events
622 callback.waitForFlushEvents(sensors, flushCalls, milliseconds(1000) /* timeout */);
623
624 // Deactivate all sensors after waiting for flush events so pending flush events are not
625 // abandoned by the HAL.
626 for (const SensorInfoType& sensor : sensors) {
627 activate(sensor.sensorHandle, false);
628 }
629 getEnvironment()->unregisterCallback();
630
631 // Check that the correct number of flushes are present for each sensor
632 for (const SensorInfoType& sensor : sensors) {
633 SCOPED_TRACE(::testing::Message()
634 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
635 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
636 << " name=" << sensor.name);
637 ASSERT_EQ(callback.getFlushCount(sensor.sensorHandle), expectedFlushCount);
638 }
639 }
640
TEST_P(SensorsHidlTest,FlushSensor)641 TEST_P(SensorsHidlTest, FlushSensor) {
642 // Find a sensor that is not a one-shot sensor
643 std::vector<SensorInfoType> sensors = getNonOneShotSensors();
644 if (sensors.size() == 0) {
645 return;
646 }
647
648 constexpr int32_t kFlushes = 5;
649 runSingleFlushTest(sensors, true /* activateSensor */, 1 /* expectedFlushCount */, Result::OK);
650 runFlushTest(sensors, true /* activateSensor */, kFlushes, kFlushes, Result::OK);
651 }
652
TEST_P(SensorsHidlTest,FlushOneShotSensor)653 TEST_P(SensorsHidlTest, FlushOneShotSensor) {
654 // Find a sensor that is a one-shot sensor
655 std::vector<SensorInfoType> sensors = getOneShotSensors();
656 if (sensors.size() == 0) {
657 return;
658 }
659
660 runSingleFlushTest(sensors, true /* activateSensor */, 0 /* expectedFlushCount */,
661 Result::BAD_VALUE);
662 }
663
TEST_P(SensorsHidlTest,FlushInactiveSensor)664 TEST_P(SensorsHidlTest, FlushInactiveSensor) {
665 // Attempt to find a non-one shot sensor, then a one-shot sensor if necessary
666 std::vector<SensorInfoType> sensors = getNonOneShotSensors();
667 if (sensors.size() == 0) {
668 sensors = getOneShotSensors();
669 if (sensors.size() == 0) {
670 return;
671 }
672 }
673
674 runSingleFlushTest(sensors, false /* activateSensor */, 0 /* expectedFlushCount */,
675 Result::BAD_VALUE);
676 }
677
TEST_P(SensorsHidlTest,Batch)678 TEST_P(SensorsHidlTest, Batch) {
679 if (getSensorsList().size() == 0) {
680 return;
681 }
682
683 activateAllSensors(false /* enable */);
684 for (const SensorInfoType& sensor : getSensorsList()) {
685 SCOPED_TRACE(::testing::Message()
686 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
687 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
688 << " name=" << sensor.name);
689
690 // Call batch on inactive sensor
691 // One shot sensors have minDelay set to -1 which is an invalid
692 // parameter. Use 0 instead to avoid errors.
693 int64_t samplingPeriodNs = extractReportMode(sensor.flags) == SensorFlagBits::ONE_SHOT_MODE
694 ? 0
695 : sensor.minDelay;
696 ASSERT_EQ(batch(sensor.sensorHandle, samplingPeriodNs, 0 /* maxReportLatencyNs */),
697 Result::OK);
698
699 // Activate the sensor
700 activate(sensor.sensorHandle, true /* enabled */);
701
702 // Call batch on an active sensor
703 ASSERT_EQ(batch(sensor.sensorHandle, sensor.maxDelay, 0 /* maxReportLatencyNs */),
704 Result::OK);
705 }
706 activateAllSensors(false /* enable */);
707
708 // Call batch on an invalid sensor
709 SensorInfoType sensor = getSensorsList().front();
710 sensor.sensorHandle = getInvalidSensorHandle();
711 ASSERT_EQ(batch(sensor.sensorHandle, sensor.minDelay, 0 /* maxReportLatencyNs */),
712 Result::BAD_VALUE);
713 }
714
TEST_P(SensorsHidlTest,Activate)715 TEST_P(SensorsHidlTest, Activate) {
716 if (getSensorsList().size() == 0) {
717 return;
718 }
719
720 // Verify that sensor events are generated when activate is called
721 for (const SensorInfoType& sensor : getSensorsList()) {
722 SCOPED_TRACE(::testing::Message()
723 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
724 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
725 << " name=" << sensor.name);
726
727 batch(sensor.sensorHandle, sensor.minDelay, 0 /* maxReportLatencyNs */);
728 ASSERT_EQ(activate(sensor.sensorHandle, true), Result::OK);
729
730 // Call activate on a sensor that is already activated
731 ASSERT_EQ(activate(sensor.sensorHandle, true), Result::OK);
732
733 // Deactivate the sensor
734 ASSERT_EQ(activate(sensor.sensorHandle, false), Result::OK);
735
736 // Call deactivate on a sensor that is already deactivated
737 ASSERT_EQ(activate(sensor.sensorHandle, false), Result::OK);
738 }
739
740 // Attempt to activate an invalid sensor
741 int32_t invalidHandle = getInvalidSensorHandle();
742 ASSERT_EQ(activate(invalidHandle, true), Result::BAD_VALUE);
743 ASSERT_EQ(activate(invalidHandle, false), Result::BAD_VALUE);
744 }
745
TEST_P(SensorsHidlTest,NoStaleEvents)746 TEST_P(SensorsHidlTest, NoStaleEvents) {
747 constexpr milliseconds kFiveHundredMs(500);
748 constexpr milliseconds kOneSecond(1000);
749
750 // Register the callback to receive sensor events
751 EventCallback callback;
752 getEnvironment()->registerCallback(&callback);
753
754 // This test is not valid for one-shot, on-change or special-report-mode sensors
755 const std::vector<SensorInfoType> sensors = getNonOneShotAndNonOnChangeAndNonSpecialSensors();
756 milliseconds maxMinDelay(0);
757 for (const SensorInfoType& sensor : sensors) {
758 milliseconds minDelay = duration_cast<milliseconds>(microseconds(sensor.minDelay));
759 maxMinDelay = milliseconds(std::max(maxMinDelay.count(), minDelay.count()));
760 }
761
762 // Activate the sensors so that they start generating events
763 activateAllSensors(true);
764
765 // According to the CDD, the first sample must be generated within 400ms + 2 * sample_time
766 // and the maximum reporting latency is 100ms + 2 * sample_time. Wait a sufficient amount
767 // of time to guarantee that a sample has arrived.
768 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
769 activateAllSensors(false);
770
771 // Save the last received event for each sensor
772 std::map<int32_t, int64_t> lastEventTimestampMap;
773 for (const SensorInfoType& sensor : sensors) {
774 SCOPED_TRACE(::testing::Message()
775 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
776 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
777 << " name=" << sensor.name);
778
779 if (callback.getEvents(sensor.sensorHandle).size() >= 1) {
780 lastEventTimestampMap[sensor.sensorHandle] =
781 callback.getEvents(sensor.sensorHandle).back().timestamp;
782 }
783 }
784
785 // Allow some time to pass, reset the callback, then reactivate the sensors
786 usleep(duration_cast<microseconds>(kOneSecond + (5 * maxMinDelay)).count());
787 callback.reset();
788 activateAllSensors(true);
789 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
790 activateAllSensors(false);
791
792 getEnvironment()->unregisterCallback();
793
794 for (const SensorInfoType& sensor : sensors) {
795 SCOPED_TRACE(::testing::Message()
796 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
797 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
798 << " name=" << sensor.name);
799
800 // Skip sensors that did not previously report an event
801 if (lastEventTimestampMap.find(sensor.sensorHandle) == lastEventTimestampMap.end()) {
802 continue;
803 }
804
805 // Ensure that the first event received is not stale by ensuring that its timestamp is
806 // sufficiently different from the previous event
807 const EventType newEvent = callback.getEvents(sensor.sensorHandle).front();
808 milliseconds delta = duration_cast<milliseconds>(
809 nanoseconds(newEvent.timestamp - lastEventTimestampMap[sensor.sensorHandle]));
810 milliseconds sensorMinDelay = duration_cast<milliseconds>(microseconds(sensor.minDelay));
811 ASSERT_GE(delta, kFiveHundredMs + (3 * sensorMinDelay));
812 }
813 }
814
checkRateLevel(const SensorInfoType & sensor,int32_t directChannelHandle,RateLevel rateLevel)815 void SensorsHidlTest::checkRateLevel(const SensorInfoType& sensor, int32_t directChannelHandle,
816 RateLevel rateLevel) {
817 configDirectReport(sensor.sensorHandle, directChannelHandle, rateLevel,
818 [&](Result result, int32_t reportToken) {
819 SCOPED_TRACE(::testing::Message()
820 << " handle=0x" << std::hex << std::setw(8)
821 << std::setfill('0') << sensor.sensorHandle << std::dec
822 << " type=" << static_cast<int>(sensor.type)
823 << " name=" << sensor.name);
824
825 if (isDirectReportRateSupported(sensor, rateLevel)) {
826 ASSERT_EQ(result, Result::OK);
827 if (rateLevel != RateLevel::STOP) {
828 ASSERT_GT(reportToken, 0);
829 }
830 } else {
831 ASSERT_EQ(result, Result::BAD_VALUE);
832 }
833 });
834 }
835
queryDirectChannelSupport(SharedMemType memType,bool * supportsSharedMemType,bool * supportsAnyDirectChannel)836 void SensorsHidlTest::queryDirectChannelSupport(SharedMemType memType, bool* supportsSharedMemType,
837 bool* supportsAnyDirectChannel) {
838 *supportsSharedMemType = false;
839 *supportsAnyDirectChannel = false;
840 for (const SensorInfoType& curSensor : getSensorsList()) {
841 if (isDirectChannelTypeSupported(curSensor, memType)) {
842 *supportsSharedMemType = true;
843 }
844 if (isDirectChannelTypeSupported(curSensor, SharedMemType::ASHMEM) ||
845 isDirectChannelTypeSupported(curSensor, SharedMemType::GRALLOC)) {
846 *supportsAnyDirectChannel = true;
847 }
848
849 if (*supportsSharedMemType && *supportsAnyDirectChannel) {
850 break;
851 }
852 }
853 }
854
verifyRegisterDirectChannel(std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion,EventType>> mem,int32_t * directChannelHandle,bool supportsSharedMemType,bool supportsAnyDirectChannel)855 void SensorsHidlTest::verifyRegisterDirectChannel(
856 std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem,
857 int32_t* directChannelHandle, bool supportsSharedMemType, bool supportsAnyDirectChannel) {
858 char* buffer = mem->getBuffer();
859 size_t size = mem->getSize();
860
861 if (supportsSharedMemType) {
862 memset(buffer, 0xff, size);
863 }
864
865 registerDirectChannel(mem->getSharedMemInfo(), [&](Result result, int32_t channelHandle) {
866 if (supportsSharedMemType) {
867 ASSERT_EQ(result, Result::OK);
868 ASSERT_GT(channelHandle, 0);
869
870 // Verify that the memory has been zeroed
871 for (size_t i = 0; i < mem->getSize(); i++) {
872 ASSERT_EQ(buffer[i], 0x00);
873 }
874 } else {
875 Result expectedResult =
876 supportsAnyDirectChannel ? Result::BAD_VALUE : Result::INVALID_OPERATION;
877 ASSERT_EQ(result, expectedResult);
878 ASSERT_EQ(channelHandle, -1);
879 }
880 *directChannelHandle = channelHandle;
881 });
882 }
883
verifyConfigure(const SensorInfoType & sensor,SharedMemType memType,int32_t directChannelHandle,bool supportsAnyDirectChannel)884 void SensorsHidlTest::verifyConfigure(const SensorInfoType& sensor, SharedMemType memType,
885 int32_t directChannelHandle, bool supportsAnyDirectChannel) {
886 SCOPED_TRACE(::testing::Message()
887 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
888 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
889 << " name=" << sensor.name);
890
891 if (isDirectChannelTypeSupported(sensor, memType)) {
892 // Verify that each rate level is properly supported
893 checkRateLevel(sensor, directChannelHandle, RateLevel::NORMAL);
894 checkRateLevel(sensor, directChannelHandle, RateLevel::FAST);
895 checkRateLevel(sensor, directChannelHandle, RateLevel::VERY_FAST);
896 checkRateLevel(sensor, directChannelHandle, RateLevel::STOP);
897
898 // Verify that a sensor handle of -1 is only acceptable when using RateLevel::STOP
899 configDirectReport(-1 /* sensorHandle */, directChannelHandle, RateLevel::NORMAL,
900 [](Result result, int32_t /* reportToken */) {
901 ASSERT_EQ(result, Result::BAD_VALUE);
902 });
903 configDirectReport(
904 -1 /* sensorHandle */, directChannelHandle, RateLevel::STOP,
905 [](Result result, int32_t /* reportToken */) { ASSERT_EQ(result, Result::OK); });
906 } else {
907 // directChannelHandle will be -1 here, HAL should either reject it as a bad value if there
908 // is some level of direct channel report, otherwise return INVALID_OPERATION if direct
909 // channel is not supported at all
910 Result expectedResult =
911 supportsAnyDirectChannel ? Result::BAD_VALUE : Result::INVALID_OPERATION;
912 configDirectReport(sensor.sensorHandle, directChannelHandle, RateLevel::NORMAL,
913 [expectedResult](Result result, int32_t /* reportToken */) {
914 ASSERT_EQ(result, expectedResult);
915 });
916 }
917 }
918
verifyUnregisterDirectChannel(int32_t directChannelHandle,bool supportsAnyDirectChannel)919 void SensorsHidlTest::verifyUnregisterDirectChannel(int32_t directChannelHandle,
920 bool supportsAnyDirectChannel) {
921 Result expectedResult = supportsAnyDirectChannel ? Result::OK : Result::INVALID_OPERATION;
922 ASSERT_EQ(unregisterDirectChannel(directChannelHandle), expectedResult);
923 }
924
verifyDirectChannel(SharedMemType memType)925 void SensorsHidlTest::verifyDirectChannel(SharedMemType memType) {
926 constexpr size_t kNumEvents = 1;
927 constexpr size_t kMemSize = kNumEvents * kEventSize;
928
929 std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem(
930 SensorsTestSharedMemory<SensorTypeVersion, EventType>::create(memType, kMemSize));
931 ASSERT_NE(mem, nullptr);
932
933 bool supportsSharedMemType;
934 bool supportsAnyDirectChannel;
935 queryDirectChannelSupport(memType, &supportsSharedMemType, &supportsAnyDirectChannel);
936
937 for (const SensorInfoType& sensor : getSensorsList()) {
938 int32_t directChannelHandle = 0;
939 verifyRegisterDirectChannel(mem, &directChannelHandle, supportsSharedMemType,
940 supportsAnyDirectChannel);
941 verifyConfigure(sensor, memType, directChannelHandle, supportsAnyDirectChannel);
942 verifyUnregisterDirectChannel(directChannelHandle, supportsAnyDirectChannel);
943 }
944 }
945
TEST_P(SensorsHidlTest,DirectChannelAshmem)946 TEST_P(SensorsHidlTest, DirectChannelAshmem) {
947 verifyDirectChannel(SharedMemType::ASHMEM);
948 }
949
TEST_P(SensorsHidlTest,DirectChannelGralloc)950 TEST_P(SensorsHidlTest, DirectChannelGralloc) {
951 verifyDirectChannel(SharedMemType::GRALLOC);
952 }
953
getDirectChannelSensor(SensorInfoType * sensor,SharedMemType * memType,RateLevel * rate)954 bool SensorsHidlTest::getDirectChannelSensor(SensorInfoType* sensor, SharedMemType* memType,
955 RateLevel* rate) {
956 bool found = false;
957 for (const SensorInfoType& curSensor : getSensorsList()) {
958 if (isDirectChannelTypeSupported(curSensor, SharedMemType::ASHMEM)) {
959 *memType = SharedMemType::ASHMEM;
960 *sensor = curSensor;
961 found = true;
962 break;
963 } else if (isDirectChannelTypeSupported(curSensor, SharedMemType::GRALLOC)) {
964 *memType = SharedMemType::GRALLOC;
965 *sensor = curSensor;
966 found = true;
967 break;
968 }
969 }
970
971 if (found) {
972 // Find a supported rate level
973 constexpr int kNumRateLevels = 3;
974 RateLevel rates[kNumRateLevels] = {RateLevel::NORMAL, RateLevel::FAST,
975 RateLevel::VERY_FAST};
976 *rate = RateLevel::STOP;
977 for (int i = 0; i < kNumRateLevels; i++) {
978 if (isDirectReportRateSupported(*sensor, rates[i])) {
979 *rate = rates[i];
980 }
981 }
982
983 // At least one rate level must be supported
984 EXPECT_NE(*rate, RateLevel::STOP);
985 }
986 return found;
987 }
988