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