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->SetUp();
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->TearDown(); }
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 SensorsVtsEnvironmentBase<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->SetUp();
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(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
541 // Verify that the new event queue receives sensor events
542 EXPECT_GE(newEnv.get()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
543 activateAllSensors(false);
544
545 // Cleanup the test environment
546 newEnv->TearDown();
547
548 // Restore the test environment for future tests
549 getEnvironment()->TearDown();
550 getEnvironment()->SetUp();
551 if (HasFatalFailure()) {
552 return; // Exit early if resetting the environment failed
553 }
554
555 // Ensure that the original environment is receiving events
556 activateAllSensors(true);
557 EXPECT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
558 activateAllSensors(false);
559 }
560
TEST_P(SensorsHidlTest,CleanupConnectionsOnInitialize)561 TEST_P(SensorsHidlTest, CleanupConnectionsOnInitialize) {
562 if (getSensorsList().size() == 0) {
563 // No sensors
564 return;
565 }
566
567 activateAllSensors(true);
568
569 // Verify that events are received
570 constexpr useconds_t kCollectionTimeoutUs = 1000 * 1000; // 1s
571 constexpr int32_t kNumEvents = 1;
572 ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
573
574 // Clear the active sensor handles so they are not disabled during TearDown
575 auto handles = mSensorHandles;
576 mSensorHandles.clear();
577 getEnvironment()->TearDown();
578 getEnvironment()->SetUp();
579 if (HasFatalFailure()) {
580 return; // Exit early if resetting the environment failed
581 }
582
583 // Verify no events are received until sensors are re-activated
584 ASSERT_EQ(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), 0);
585 activateAllSensors(true);
586 ASSERT_GE(getEnvironment()->collectEvents(kCollectionTimeoutUs, kNumEvents).size(), kNumEvents);
587
588 // Disable sensors
589 activateAllSensors(false);
590
591 // Restore active sensors prior to clearing the environment
592 mSensorHandles = handles;
593 }
594
runSingleFlushTest(const std::vector<SensorInfoType> & sensors,bool activateSensor,int32_t expectedFlushCount,Result expectedResponse)595 void SensorsHidlTest::runSingleFlushTest(const std::vector<SensorInfoType>& sensors,
596 bool activateSensor, int32_t expectedFlushCount,
597 Result expectedResponse) {
598 runFlushTest(sensors, activateSensor, 1 /* flushCalls */, expectedFlushCount, expectedResponse);
599 }
600
runFlushTest(const std::vector<SensorInfoType> & sensors,bool activateSensor,int32_t flushCalls,int32_t expectedFlushCount,Result expectedResponse)601 void SensorsHidlTest::runFlushTest(const std::vector<SensorInfoType>& sensors, bool activateSensor,
602 int32_t flushCalls, int32_t expectedFlushCount,
603 Result expectedResponse) {
604 EventCallback callback;
605 getEnvironment()->registerCallback(&callback);
606
607 for (const SensorInfoType& sensor : sensors) {
608 // Configure and activate the sensor
609 batch(sensor.sensorHandle, sensor.maxDelay, 0 /* maxReportLatencyNs */);
610 activate(sensor.sensorHandle, activateSensor);
611
612 // Flush the sensor
613 for (int32_t i = 0; i < flushCalls; i++) {
614 SCOPED_TRACE(::testing::Message()
615 << "Flush " << i << "/" << flushCalls << ": "
616 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
617 << sensor.sensorHandle << std::dec
618 << " type=" << static_cast<int>(sensor.type) << " name=" << sensor.name);
619
620 Result flushResult = flush(sensor.sensorHandle);
621 EXPECT_EQ(flushResult, expectedResponse);
622 }
623 }
624
625 // Wait up to one second for the flush events
626 callback.waitForFlushEvents(sensors, flushCalls, milliseconds(1000) /* timeout */);
627
628 // Deactivate all sensors after waiting for flush events so pending flush events are not
629 // abandoned by the HAL.
630 for (const SensorInfoType& sensor : sensors) {
631 activate(sensor.sensorHandle, false);
632 }
633 getEnvironment()->unregisterCallback();
634
635 // Check that the correct number of flushes are present for each sensor
636 for (const SensorInfoType& sensor : sensors) {
637 SCOPED_TRACE(::testing::Message()
638 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
639 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
640 << " name=" << sensor.name);
641 ASSERT_EQ(callback.getFlushCount(sensor.sensorHandle), expectedFlushCount);
642 }
643 }
644
TEST_P(SensorsHidlTest,FlushSensor)645 TEST_P(SensorsHidlTest, FlushSensor) {
646 // Find a sensor that is not a one-shot sensor
647 std::vector<SensorInfoType> sensors = getNonOneShotSensors();
648 if (sensors.size() == 0) {
649 return;
650 }
651
652 constexpr int32_t kFlushes = 5;
653 runSingleFlushTest(sensors, true /* activateSensor */, 1 /* expectedFlushCount */, Result::OK);
654 runFlushTest(sensors, true /* activateSensor */, kFlushes, kFlushes, Result::OK);
655 }
656
TEST_P(SensorsHidlTest,FlushOneShotSensor)657 TEST_P(SensorsHidlTest, FlushOneShotSensor) {
658 // Find a sensor that is a one-shot sensor
659 std::vector<SensorInfoType> sensors = getOneShotSensors();
660 if (sensors.size() == 0) {
661 return;
662 }
663
664 runSingleFlushTest(sensors, true /* activateSensor */, 0 /* expectedFlushCount */,
665 Result::BAD_VALUE);
666 }
667
TEST_P(SensorsHidlTest,FlushInactiveSensor)668 TEST_P(SensorsHidlTest, FlushInactiveSensor) {
669 // Attempt to find a non-one shot sensor, then a one-shot sensor if necessary
670 std::vector<SensorInfoType> sensors = getNonOneShotSensors();
671 if (sensors.size() == 0) {
672 sensors = getOneShotSensors();
673 if (sensors.size() == 0) {
674 return;
675 }
676 }
677
678 runSingleFlushTest(sensors, false /* activateSensor */, 0 /* expectedFlushCount */,
679 Result::BAD_VALUE);
680 }
681
TEST_P(SensorsHidlTest,Batch)682 TEST_P(SensorsHidlTest, Batch) {
683 if (getSensorsList().size() == 0) {
684 return;
685 }
686
687 activateAllSensors(false /* enable */);
688 for (const SensorInfoType& sensor : getSensorsList()) {
689 SCOPED_TRACE(::testing::Message()
690 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
691 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
692 << " name=" << sensor.name);
693
694 // Call batch on inactive sensor
695 // One shot sensors have minDelay set to -1 which is an invalid
696 // parameter. Use 0 instead to avoid errors.
697 int64_t samplingPeriodNs = extractReportMode(sensor.flags) == SensorFlagBits::ONE_SHOT_MODE
698 ? 0
699 : sensor.minDelay;
700 ASSERT_EQ(batch(sensor.sensorHandle, samplingPeriodNs, 0 /* maxReportLatencyNs */),
701 Result::OK);
702
703 // Activate the sensor
704 activate(sensor.sensorHandle, true /* enabled */);
705
706 // Call batch on an active sensor
707 ASSERT_EQ(batch(sensor.sensorHandle, sensor.maxDelay, 0 /* maxReportLatencyNs */),
708 Result::OK);
709 }
710 activateAllSensors(false /* enable */);
711
712 // Call batch on an invalid sensor
713 SensorInfoType sensor = getSensorsList().front();
714 sensor.sensorHandle = getInvalidSensorHandle();
715 ASSERT_EQ(batch(sensor.sensorHandle, sensor.minDelay, 0 /* maxReportLatencyNs */),
716 Result::BAD_VALUE);
717 }
718
TEST_P(SensorsHidlTest,Activate)719 TEST_P(SensorsHidlTest, Activate) {
720 if (getSensorsList().size() == 0) {
721 return;
722 }
723
724 // Verify that sensor events are generated when activate is called
725 for (const SensorInfoType& sensor : getSensorsList()) {
726 SCOPED_TRACE(::testing::Message()
727 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
728 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
729 << " name=" << sensor.name);
730
731 batch(sensor.sensorHandle, sensor.minDelay, 0 /* maxReportLatencyNs */);
732 ASSERT_EQ(activate(sensor.sensorHandle, true), Result::OK);
733
734 // Call activate on a sensor that is already activated
735 ASSERT_EQ(activate(sensor.sensorHandle, true), Result::OK);
736
737 // Deactivate the sensor
738 ASSERT_EQ(activate(sensor.sensorHandle, false), Result::OK);
739
740 // Call deactivate on a sensor that is already deactivated
741 ASSERT_EQ(activate(sensor.sensorHandle, false), Result::OK);
742 }
743
744 // Attempt to activate an invalid sensor
745 int32_t invalidHandle = getInvalidSensorHandle();
746 ASSERT_EQ(activate(invalidHandle, true), Result::BAD_VALUE);
747 ASSERT_EQ(activate(invalidHandle, false), Result::BAD_VALUE);
748 }
749
TEST_P(SensorsHidlTest,NoStaleEvents)750 TEST_P(SensorsHidlTest, NoStaleEvents) {
751 constexpr milliseconds kFiveHundredMs(500);
752 constexpr milliseconds kOneSecond(1000);
753
754 // Register the callback to receive sensor events
755 EventCallback callback;
756 getEnvironment()->registerCallback(&callback);
757
758 // This test is not valid for one-shot, on-change or special-report-mode sensors
759 const std::vector<SensorInfoType> sensors = getNonOneShotAndNonOnChangeAndNonSpecialSensors();
760 milliseconds maxMinDelay(0);
761 for (const SensorInfoType& sensor : sensors) {
762 milliseconds minDelay = duration_cast<milliseconds>(microseconds(sensor.minDelay));
763 maxMinDelay = milliseconds(std::max(maxMinDelay.count(), minDelay.count()));
764 }
765
766 // Activate the sensors so that they start generating events
767 activateAllSensors(true);
768
769 // According to the CDD, the first sample must be generated within 400ms + 2 * sample_time
770 // and the maximum reporting latency is 100ms + 2 * sample_time. Wait a sufficient amount
771 // of time to guarantee that a sample has arrived.
772 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
773 activateAllSensors(false);
774
775 // Save the last received event for each sensor
776 std::map<int32_t, int64_t> lastEventTimestampMap;
777 for (const SensorInfoType& sensor : sensors) {
778 SCOPED_TRACE(::testing::Message()
779 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
780 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
781 << " name=" << sensor.name);
782
783 if (callback.getEvents(sensor.sensorHandle).size() >= 1) {
784 lastEventTimestampMap[sensor.sensorHandle] =
785 callback.getEvents(sensor.sensorHandle).back().timestamp;
786 }
787 }
788
789 // Allow some time to pass, reset the callback, then reactivate the sensors
790 usleep(duration_cast<microseconds>(kOneSecond + (5 * maxMinDelay)).count());
791 callback.reset();
792 activateAllSensors(true);
793 callback.waitForEvents(sensors, kFiveHundredMs + (5 * maxMinDelay));
794 activateAllSensors(false);
795
796 getEnvironment()->unregisterCallback();
797
798 for (const SensorInfoType& sensor : sensors) {
799 SCOPED_TRACE(::testing::Message()
800 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
801 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
802 << " name=" << sensor.name);
803
804 // Skip sensors that did not previously report an event
805 if (lastEventTimestampMap.find(sensor.sensorHandle) == lastEventTimestampMap.end()) {
806 continue;
807 }
808
809 // Ensure that the first event received is not stale by ensuring that its timestamp is
810 // sufficiently different from the previous event
811 const EventType newEvent = callback.getEvents(sensor.sensorHandle).front();
812 milliseconds delta = duration_cast<milliseconds>(
813 nanoseconds(newEvent.timestamp - lastEventTimestampMap[sensor.sensorHandle]));
814 milliseconds sensorMinDelay = duration_cast<milliseconds>(microseconds(sensor.minDelay));
815 ASSERT_GE(delta, kFiveHundredMs + (3 * sensorMinDelay));
816 }
817 }
818
checkRateLevel(const SensorInfoType & sensor,int32_t directChannelHandle,RateLevel rateLevel)819 void SensorsHidlTest::checkRateLevel(const SensorInfoType& sensor, int32_t directChannelHandle,
820 RateLevel rateLevel) {
821 configDirectReport(sensor.sensorHandle, directChannelHandle, rateLevel,
822 [&](Result result, int32_t reportToken) {
823 SCOPED_TRACE(::testing::Message()
824 << " handle=0x" << std::hex << std::setw(8)
825 << std::setfill('0') << sensor.sensorHandle << std::dec
826 << " type=" << static_cast<int>(sensor.type)
827 << " name=" << sensor.name);
828
829 if (isDirectReportRateSupported(sensor, rateLevel)) {
830 ASSERT_EQ(result, Result::OK);
831 if (rateLevel != RateLevel::STOP) {
832 ASSERT_GT(reportToken, 0);
833 }
834 } else {
835 ASSERT_EQ(result, Result::BAD_VALUE);
836 }
837 });
838 }
839
queryDirectChannelSupport(SharedMemType memType,bool * supportsSharedMemType,bool * supportsAnyDirectChannel)840 void SensorsHidlTest::queryDirectChannelSupport(SharedMemType memType, bool* supportsSharedMemType,
841 bool* supportsAnyDirectChannel) {
842 *supportsSharedMemType = false;
843 *supportsAnyDirectChannel = false;
844 for (const SensorInfoType& curSensor : getSensorsList()) {
845 if (isDirectChannelTypeSupported(curSensor, memType)) {
846 *supportsSharedMemType = true;
847 }
848 if (isDirectChannelTypeSupported(curSensor, SharedMemType::ASHMEM) ||
849 isDirectChannelTypeSupported(curSensor, SharedMemType::GRALLOC)) {
850 *supportsAnyDirectChannel = true;
851 }
852
853 if (*supportsSharedMemType && *supportsAnyDirectChannel) {
854 break;
855 }
856 }
857 }
858
verifyRegisterDirectChannel(std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion,EventType>> mem,int32_t * directChannelHandle,bool supportsSharedMemType,bool supportsAnyDirectChannel)859 void SensorsHidlTest::verifyRegisterDirectChannel(
860 std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem,
861 int32_t* directChannelHandle, bool supportsSharedMemType, bool supportsAnyDirectChannel) {
862 char* buffer = mem->getBuffer();
863 size_t size = mem->getSize();
864
865 if (supportsSharedMemType) {
866 memset(buffer, 0xff, size);
867 }
868
869 registerDirectChannel(mem->getSharedMemInfo(), [&](Result result, int32_t channelHandle) {
870 if (supportsSharedMemType) {
871 ASSERT_EQ(result, Result::OK);
872 ASSERT_GT(channelHandle, 0);
873
874 // Verify that the memory has been zeroed
875 for (size_t i = 0; i < mem->getSize(); i++) {
876 ASSERT_EQ(buffer[i], 0x00);
877 }
878 } else {
879 Result expectedResult =
880 supportsAnyDirectChannel ? Result::BAD_VALUE : Result::INVALID_OPERATION;
881 ASSERT_EQ(result, expectedResult);
882 ASSERT_EQ(channelHandle, -1);
883 }
884 *directChannelHandle = channelHandle;
885 });
886 }
887
verifyConfigure(const SensorInfoType & sensor,SharedMemType memType,int32_t directChannelHandle,bool supportsAnyDirectChannel)888 void SensorsHidlTest::verifyConfigure(const SensorInfoType& sensor, SharedMemType memType,
889 int32_t directChannelHandle, bool supportsAnyDirectChannel) {
890 SCOPED_TRACE(::testing::Message()
891 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
892 << sensor.sensorHandle << std::dec << " type=" << static_cast<int>(sensor.type)
893 << " name=" << sensor.name);
894
895 if (isDirectChannelTypeSupported(sensor, memType)) {
896 // Verify that each rate level is properly supported
897 checkRateLevel(sensor, directChannelHandle, RateLevel::NORMAL);
898 checkRateLevel(sensor, directChannelHandle, RateLevel::FAST);
899 checkRateLevel(sensor, directChannelHandle, RateLevel::VERY_FAST);
900 checkRateLevel(sensor, directChannelHandle, RateLevel::STOP);
901
902 // Verify that a sensor handle of -1 is only acceptable when using RateLevel::STOP
903 configDirectReport(-1 /* sensorHandle */, directChannelHandle, RateLevel::NORMAL,
904 [](Result result, int32_t /* reportToken */) {
905 ASSERT_EQ(result, Result::BAD_VALUE);
906 });
907 configDirectReport(
908 -1 /* sensorHandle */, directChannelHandle, RateLevel::STOP,
909 [](Result result, int32_t /* reportToken */) { ASSERT_EQ(result, Result::OK); });
910 } else {
911 // directChannelHandle will be -1 here, HAL should either reject it as a bad value if there
912 // is some level of direct channel report, otherwise return INVALID_OPERATION if direct
913 // channel is not supported at all
914 Result expectedResult =
915 supportsAnyDirectChannel ? Result::BAD_VALUE : Result::INVALID_OPERATION;
916 configDirectReport(sensor.sensorHandle, directChannelHandle, RateLevel::NORMAL,
917 [expectedResult](Result result, int32_t /* reportToken */) {
918 ASSERT_EQ(result, expectedResult);
919 });
920 }
921 }
922
verifyUnregisterDirectChannel(int32_t directChannelHandle,bool supportsAnyDirectChannel)923 void SensorsHidlTest::verifyUnregisterDirectChannel(int32_t directChannelHandle,
924 bool supportsAnyDirectChannel) {
925 Result expectedResult = supportsAnyDirectChannel ? Result::OK : Result::INVALID_OPERATION;
926 ASSERT_EQ(unregisterDirectChannel(directChannelHandle), expectedResult);
927 }
928
verifyDirectChannel(SharedMemType memType)929 void SensorsHidlTest::verifyDirectChannel(SharedMemType memType) {
930 constexpr size_t kNumEvents = 1;
931 constexpr size_t kMemSize = kNumEvents * kEventSize;
932
933 std::shared_ptr<SensorsTestSharedMemory<SensorTypeVersion, EventType>> mem(
934 SensorsTestSharedMemory<SensorTypeVersion, EventType>::create(memType, kMemSize));
935 ASSERT_NE(mem, nullptr);
936
937 bool supportsSharedMemType;
938 bool supportsAnyDirectChannel;
939 queryDirectChannelSupport(memType, &supportsSharedMemType, &supportsAnyDirectChannel);
940
941 for (const SensorInfoType& sensor : getSensorsList()) {
942 int32_t directChannelHandle = 0;
943 verifyRegisterDirectChannel(mem, &directChannelHandle, supportsSharedMemType,
944 supportsAnyDirectChannel);
945 verifyConfigure(sensor, memType, directChannelHandle, supportsAnyDirectChannel);
946 verifyUnregisterDirectChannel(directChannelHandle, supportsAnyDirectChannel);
947 }
948 }
949
TEST_P(SensorsHidlTest,DirectChannelAshmem)950 TEST_P(SensorsHidlTest, DirectChannelAshmem) {
951 verifyDirectChannel(SharedMemType::ASHMEM);
952 }
953
TEST_P(SensorsHidlTest,DirectChannelGralloc)954 TEST_P(SensorsHidlTest, DirectChannelGralloc) {
955 verifyDirectChannel(SharedMemType::GRALLOC);
956 }
957
getDirectChannelSensor(SensorInfoType * sensor,SharedMemType * memType,RateLevel * rate)958 bool SensorsHidlTest::getDirectChannelSensor(SensorInfoType* sensor, SharedMemType* memType,
959 RateLevel* rate) {
960 bool found = false;
961 for (const SensorInfoType& curSensor : getSensorsList()) {
962 if (isDirectChannelTypeSupported(curSensor, SharedMemType::ASHMEM)) {
963 *memType = SharedMemType::ASHMEM;
964 *sensor = curSensor;
965 found = true;
966 break;
967 } else if (isDirectChannelTypeSupported(curSensor, SharedMemType::GRALLOC)) {
968 *memType = SharedMemType::GRALLOC;
969 *sensor = curSensor;
970 found = true;
971 break;
972 }
973 }
974
975 if (found) {
976 // Find a supported rate level
977 constexpr int kNumRateLevels = 3;
978 RateLevel rates[kNumRateLevels] = {RateLevel::NORMAL, RateLevel::FAST,
979 RateLevel::VERY_FAST};
980 *rate = RateLevel::STOP;
981 for (int i = 0; i < kNumRateLevels; i++) {
982 if (isDirectReportRateSupported(*sensor, rates[i])) {
983 *rate = rates[i];
984 }
985 }
986
987 // At least one rate level must be supported
988 EXPECT_NE(*rate, RateLevel::STOP);
989 }
990 return found;
991 }
992