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 #include "SensorsHidlTestBase.h"
18
19 #include "sensors-vts-utils/GrallocWrapper.h"
20 #include "sensors-vts-utils/SensorsTestSharedMemory.h"
21
22 #include <hardware/sensors.h> // for sensor type strings
23 #include <log/log.h>
24 #include <utils/SystemClock.h>
25
26 #include <cinttypes>
27
28 using ::android::sp;
29 using ::android::hardware::hidl_string;
30 using ::android::hardware::Return;
31 using ::android::hardware::Void;
32 using ::android::hardware::sensors::V1_0::SensorFlagShift;
33 using ::android::hardware::sensors::V1_0::SensorsEventFormatOffset;
34
35 const Vec3NormChecker SensorsHidlTestBase::sAccelNormChecker(
36 Vec3NormChecker::byNominal(GRAVITY_EARTH, 1.0f /*m/s^2*/));
37 const Vec3NormChecker SensorsHidlTestBase::sGyroNormChecker(
38 Vec3NormChecker::byNominal(0.f, 0.1f /*rad/s*/));
39
collectEvents(useconds_t timeLimitUs,size_t nEventLimit,bool clearBeforeStart,bool changeCollection)40 std::vector<Event> SensorsHidlTestBase::collectEvents(useconds_t timeLimitUs, size_t nEventLimit,
41 bool clearBeforeStart,
42 bool changeCollection) {
43 return collectEvents(timeLimitUs, nEventLimit, getEnvironment(), clearBeforeStart,
44 changeCollection);
45 }
46
collectEvents(useconds_t timeLimitUs,size_t nEventLimit,SensorsHidlEnvironmentBase * environment,bool clearBeforeStart,bool changeCollection)47 std::vector<Event> SensorsHidlTestBase::collectEvents(useconds_t timeLimitUs, size_t nEventLimit,
48 SensorsHidlEnvironmentBase* environment,
49 bool clearBeforeStart,
50 bool changeCollection) {
51 std::vector<Event> events;
52 constexpr useconds_t SLEEP_GRANULARITY = 100 * 1000; // granularity 100 ms
53
54 ALOGI("collect max of %zu events for %d us, clearBeforeStart %d", nEventLimit, timeLimitUs,
55 clearBeforeStart);
56
57 if (changeCollection) {
58 environment->setCollection(true);
59 }
60 if (clearBeforeStart) {
61 environment->catEvents(nullptr);
62 }
63
64 while (timeLimitUs > 0) {
65 useconds_t duration = std::min(SLEEP_GRANULARITY, timeLimitUs);
66 usleep(duration);
67 timeLimitUs -= duration;
68
69 environment->catEvents(&events);
70 if (events.size() >= nEventLimit) {
71 break;
72 }
73 ALOGV("time to go = %d, events to go = %d", (int)timeLimitUs,
74 (int)(nEventLimit - events.size()));
75 }
76
77 if (changeCollection) {
78 environment->setCollection(false);
79 }
80 return events;
81 }
82
assertTypeMatchStringType(SensorType type,const hidl_string & stringType)83 void SensorsHidlTestBase::assertTypeMatchStringType(SensorType type,
84 const hidl_string& stringType) {
85 if (type >= SensorType::DEVICE_PRIVATE_BASE) {
86 return;
87 }
88
89 switch (type) {
90 #define CHECK_TYPE_STRING_FOR_SENSOR_TYPE(type) \
91 case SensorType::type: \
92 ASSERT_STREQ(SENSOR_STRING_TYPE_##type, stringType.c_str()); \
93 break;
94 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER);
95 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_UNCALIBRATED);
96 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ADDITIONAL_INFO);
97 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(AMBIENT_TEMPERATURE);
98 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DEVICE_ORIENTATION);
99 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DYNAMIC_SENSOR_META);
100 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GAME_ROTATION_VECTOR);
101 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GEOMAGNETIC_ROTATION_VECTOR);
102 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GLANCE_GESTURE);
103 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GRAVITY);
104 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE);
105 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_UNCALIBRATED);
106 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_BEAT);
107 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_RATE);
108 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LIGHT);
109 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LINEAR_ACCELERATION);
110 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LOW_LATENCY_OFFBODY_DETECT);
111 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD);
112 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD_UNCALIBRATED);
113 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MOTION_DETECT);
114 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ORIENTATION);
115 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PICK_UP_GESTURE);
116 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(POSE_6DOF);
117 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PRESSURE);
118 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PROXIMITY);
119 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(RELATIVE_HUMIDITY);
120 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ROTATION_VECTOR);
121 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(SIGNIFICANT_MOTION);
122 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STATIONARY_DETECT);
123 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_COUNTER);
124 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_DETECTOR);
125 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TEMPERATURE);
126 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TILT_DETECTOR);
127 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WAKE_GESTURE);
128 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WRIST_TILT_GESTURE);
129 default:
130 FAIL() << "Type " << static_cast<int>(type)
131 << " in android defined range is not checked, "
132 << "stringType = " << stringType;
133 #undef CHECK_TYPE_STRING_FOR_SENSOR_TYPE
134 }
135 }
136
assertTypeMatchReportMode(SensorType type,SensorFlagBits reportMode)137 void SensorsHidlTestBase::assertTypeMatchReportMode(SensorType type, SensorFlagBits reportMode) {
138 if (type >= SensorType::DEVICE_PRIVATE_BASE) {
139 return;
140 }
141
142 SensorFlagBits expected = expectedReportModeForType(type);
143
144 ASSERT_TRUE(expected == (SensorFlagBits)-1 || expected == reportMode)
145 << "reportMode=" << static_cast<int>(reportMode)
146 << "expected=" << static_cast<int>(expected);
147 }
148
assertDelayMatchReportMode(int32_t minDelay,int32_t maxDelay,SensorFlagBits reportMode)149 void SensorsHidlTestBase::assertDelayMatchReportMode(int32_t minDelay, int32_t maxDelay,
150 SensorFlagBits reportMode) {
151 switch (reportMode) {
152 case SensorFlagBits::CONTINUOUS_MODE:
153 ASSERT_LT(0, minDelay);
154 ASSERT_LE(0, maxDelay);
155 break;
156 case SensorFlagBits::ON_CHANGE_MODE:
157 ASSERT_LE(0, minDelay);
158 ASSERT_LE(0, maxDelay);
159 break;
160 case SensorFlagBits::ONE_SHOT_MODE:
161 ASSERT_EQ(-1, minDelay);
162 ASSERT_EQ(0, maxDelay);
163 break;
164 case SensorFlagBits::SPECIAL_REPORTING_MODE:
165 // do not enforce anything for special reporting mode
166 break;
167 default:
168 FAIL() << "Report mode " << static_cast<int>(reportMode) << " not checked";
169 }
170 }
171
172 // return -1 means no expectation for this type
expectedReportModeForType(SensorType type)173 SensorFlagBits SensorsHidlTestBase::expectedReportModeForType(SensorType type) {
174 switch (type) {
175 case SensorType::ACCELEROMETER:
176 case SensorType::ACCELEROMETER_UNCALIBRATED:
177 case SensorType::GYROSCOPE:
178 case SensorType::MAGNETIC_FIELD:
179 case SensorType::ORIENTATION:
180 case SensorType::PRESSURE:
181 case SensorType::TEMPERATURE:
182 case SensorType::GRAVITY:
183 case SensorType::LINEAR_ACCELERATION:
184 case SensorType::ROTATION_VECTOR:
185 case SensorType::MAGNETIC_FIELD_UNCALIBRATED:
186 case SensorType::GAME_ROTATION_VECTOR:
187 case SensorType::GYROSCOPE_UNCALIBRATED:
188 case SensorType::GEOMAGNETIC_ROTATION_VECTOR:
189 case SensorType::POSE_6DOF:
190 case SensorType::HEART_BEAT:
191 return SensorFlagBits::CONTINUOUS_MODE;
192
193 case SensorType::LIGHT:
194 case SensorType::PROXIMITY:
195 case SensorType::RELATIVE_HUMIDITY:
196 case SensorType::AMBIENT_TEMPERATURE:
197 case SensorType::HEART_RATE:
198 case SensorType::DEVICE_ORIENTATION:
199 case SensorType::STEP_COUNTER:
200 case SensorType::LOW_LATENCY_OFFBODY_DETECT:
201 return SensorFlagBits::ON_CHANGE_MODE;
202
203 case SensorType::SIGNIFICANT_MOTION:
204 case SensorType::WAKE_GESTURE:
205 case SensorType::GLANCE_GESTURE:
206 case SensorType::PICK_UP_GESTURE:
207 case SensorType::MOTION_DETECT:
208 case SensorType::STATIONARY_DETECT:
209 return SensorFlagBits::ONE_SHOT_MODE;
210
211 case SensorType::STEP_DETECTOR:
212 case SensorType::TILT_DETECTOR:
213 case SensorType::WRIST_TILT_GESTURE:
214 case SensorType::DYNAMIC_SENSOR_META:
215 return SensorFlagBits::SPECIAL_REPORTING_MODE;
216
217 default:
218 ALOGW("Type %d is not implemented in expectedReportModeForType", (int)type);
219 return (SensorFlagBits)-1;
220 }
221 }
222
isDirectReportRateSupported(SensorInfo sensor,RateLevel rate)223 bool SensorsHidlTestBase::isDirectReportRateSupported(SensorInfo sensor, RateLevel rate) {
224 unsigned int r = static_cast<unsigned int>(sensor.flags & SensorFlagBits::MASK_DIRECT_REPORT) >>
225 static_cast<unsigned int>(SensorFlagShift::DIRECT_REPORT);
226 return r >= static_cast<unsigned int>(rate);
227 }
228
isDirectChannelTypeSupported(SensorInfo sensor,SharedMemType type)229 bool SensorsHidlTestBase::isDirectChannelTypeSupported(SensorInfo sensor, SharedMemType type) {
230 switch (type) {
231 case SharedMemType::ASHMEM:
232 return (sensor.flags & SensorFlagBits::DIRECT_CHANNEL_ASHMEM) != 0;
233 case SharedMemType::GRALLOC:
234 return (sensor.flags & SensorFlagBits::DIRECT_CHANNEL_GRALLOC) != 0;
235 default:
236 return false;
237 }
238 }
239
testDirectReportOperation(SensorType type,SharedMemType memType,RateLevel rate,const SensorEventsChecker & checker)240 void SensorsHidlTestBase::testDirectReportOperation(SensorType type, SharedMemType memType,
241 RateLevel rate,
242 const SensorEventsChecker& checker) {
243 constexpr size_t kEventSize = static_cast<size_t>(SensorsEventFormatOffset::TOTAL_LENGTH);
244 constexpr size_t kNEvent = 4096;
245 constexpr size_t kMemSize = kEventSize * kNEvent;
246
247 constexpr float kNormalNominal = 50;
248 constexpr float kFastNominal = 200;
249 constexpr float kVeryFastNominal = 800;
250
251 constexpr float kNominalTestTimeSec = 1.f;
252 constexpr float kMaxTestTimeSec = kNominalTestTimeSec + 0.5f; // 0.5 second for initialization
253
254 SensorInfo sensor = defaultSensorByType(type);
255
256 if (!isValidType(sensor.type)) {
257 // no default sensor of this type
258 return;
259 }
260
261 if (!isDirectReportRateSupported(sensor, rate)) {
262 return;
263 }
264
265 if (!isDirectChannelTypeSupported(sensor, memType)) {
266 return;
267 }
268
269 std::unique_ptr<SensorsTestSharedMemory> mem(
270 SensorsTestSharedMemory::create(memType, kMemSize));
271 ASSERT_NE(mem, nullptr);
272
273 char* buffer = mem->getBuffer();
274 // fill memory with data
275 for (size_t i = 0; i < kMemSize; ++i) {
276 buffer[i] = '\xcc';
277 }
278
279 int32_t channelHandle;
280 registerDirectChannel(mem->getSharedMemInfo(),
281 [&channelHandle](auto result, auto channelHandle_) {
282 ASSERT_EQ(result, Result::OK);
283 channelHandle = channelHandle_;
284 });
285
286 // check memory is zeroed
287 for (size_t i = 0; i < kMemSize; ++i) {
288 ASSERT_EQ(buffer[i], '\0');
289 }
290
291 int32_t eventToken;
292 configDirectReport(sensor.sensorHandle, channelHandle, rate,
293 [&eventToken](auto result, auto token) {
294 ASSERT_EQ(result, Result::OK);
295 eventToken = token;
296 });
297
298 usleep(static_cast<useconds_t>(kMaxTestTimeSec * 1e6f));
299 auto events = mem->parseEvents();
300
301 // find norminal rate
302 float nominalFreq = 0.f;
303 switch (rate) {
304 case RateLevel::NORMAL:
305 nominalFreq = kNormalNominal;
306 break;
307 case RateLevel::FAST:
308 nominalFreq = kFastNominal;
309 break;
310 case RateLevel::VERY_FAST:
311 nominalFreq = kVeryFastNominal;
312 break;
313 case RateLevel::STOP:
314 FAIL();
315 }
316
317 // allowed to be between 55% and 220% of nominal freq
318 ASSERT_GT(events.size(), static_cast<size_t>(nominalFreq * 0.55f * kNominalTestTimeSec));
319 ASSERT_LT(events.size(), static_cast<size_t>(nominalFreq * 2.2f * kMaxTestTimeSec));
320
321 int64_t lastTimestamp = 0;
322 bool typeErrorReported = false;
323 bool tokenErrorReported = false;
324 bool timestampErrorReported = false;
325 std::vector<Event> sensorEvents;
326 for (auto& e : events) {
327 if (!tokenErrorReported) {
328 EXPECT_EQ(eventToken, e.sensorHandle)
329 << (tokenErrorReported = true,
330 "Event token does not match that retured from configDirectReport");
331 }
332
333 if (isMetaSensorType(e.sensorType)) {
334 continue;
335 }
336 sensorEvents.push_back(e);
337
338 if (!typeErrorReported) {
339 EXPECT_EQ(type, e.sensorType)
340 << (typeErrorReported = true,
341 "Type in event does not match type of sensor registered.");
342 }
343 if (!timestampErrorReported) {
344 EXPECT_GT(e.timestamp, lastTimestamp)
345 << (timestampErrorReported = true, "Timestamp not monotonically increasing");
346 }
347 lastTimestamp = e.timestamp;
348 }
349
350 std::string s;
351 EXPECT_TRUE(checker.check(sensorEvents, &s)) << s;
352
353 // stop sensor and unregister channel
354 configDirectReport(sensor.sensorHandle, channelHandle, RateLevel::STOP,
355 [](auto result, auto) { EXPECT_EQ(result, Result::OK); });
356 EXPECT_EQ(unregisterDirectChannel(channelHandle), Result::OK);
357 }
358
testStreamingOperation(SensorType type,std::chrono::nanoseconds samplingPeriod,std::chrono::seconds duration,const SensorEventsChecker & checker)359 void SensorsHidlTestBase::testStreamingOperation(SensorType type,
360 std::chrono::nanoseconds samplingPeriod,
361 std::chrono::seconds duration,
362 const SensorEventsChecker& checker) {
363 std::vector<Event> events;
364 std::vector<Event> sensorEvents;
365
366 const int64_t samplingPeriodInNs = samplingPeriod.count();
367 const int64_t batchingPeriodInNs = 0; // no batching
368 const useconds_t minTimeUs = std::chrono::microseconds(duration).count();
369 const size_t minNEvent = duration / samplingPeriod;
370
371 SensorInfo sensor = defaultSensorByType(type);
372
373 if (!isValidType(sensor.type)) {
374 // no default sensor of this type
375 return;
376 }
377
378 if (std::chrono::microseconds(sensor.minDelay) > samplingPeriod) {
379 // rate not supported
380 return;
381 }
382
383 int32_t handle = sensor.sensorHandle;
384
385 ASSERT_EQ(batch(handle, samplingPeriodInNs, batchingPeriodInNs), Result::OK);
386 ASSERT_EQ(activate(handle, 1), Result::OK);
387 events = collectEvents(minTimeUs, minNEvent, true /*clearBeforeStart*/);
388 ASSERT_EQ(activate(handle, 0), Result::OK);
389
390 ALOGI("Collected %zu samples", events.size());
391
392 ASSERT_GT(events.size(), 0u);
393
394 bool handleMismatchReported = false;
395 bool metaSensorTypeErrorReported = false;
396 for (auto& e : events) {
397 if (e.sensorType == type) {
398 // avoid generating hundreds of error
399 if (!handleMismatchReported) {
400 EXPECT_EQ(e.sensorHandle, handle)
401 << (handleMismatchReported = true,
402 "Event of the same type must come from the sensor registered");
403 }
404 sensorEvents.push_back(e);
405 } else {
406 // avoid generating hundreds of error
407 if (!metaSensorTypeErrorReported) {
408 EXPECT_TRUE(isMetaSensorType(e.sensorType))
409 << (metaSensorTypeErrorReported = true,
410 "Only meta types are allowed besides the type registered");
411 }
412 }
413 }
414
415 std::string s;
416 EXPECT_TRUE(checker.check(sensorEvents, &s)) << s;
417
418 EXPECT_GE(sensorEvents.size(),
419 minNEvent / 2); // make sure returned events are not all meta
420 }
421
testSamplingRateHotSwitchOperation(SensorType type,bool fastToSlow)422 void SensorsHidlTestBase::testSamplingRateHotSwitchOperation(SensorType type, bool fastToSlow) {
423 std::vector<Event> events1, events2;
424
425 constexpr int64_t batchingPeriodInNs = 0; // no batching
426 constexpr int64_t collectionTimeoutUs = 60000000; // 60s
427 constexpr size_t minNEvent = 50;
428
429 SensorInfo sensor = defaultSensorByType(type);
430
431 if (!isValidType(sensor.type)) {
432 // no default sensor of this type
433 return;
434 }
435
436 int32_t handle = sensor.sensorHandle;
437 int64_t minSamplingPeriodInNs = sensor.minDelay * 1000ll;
438 int64_t maxSamplingPeriodInNs = sensor.maxDelay * 1000ll;
439
440 if (minSamplingPeriodInNs == maxSamplingPeriodInNs) {
441 // only support single rate
442 return;
443 }
444
445 int64_t firstCollectionPeriod = fastToSlow ? minSamplingPeriodInNs : maxSamplingPeriodInNs;
446 int64_t secondCollectionPeriod = !fastToSlow ? minSamplingPeriodInNs : maxSamplingPeriodInNs;
447
448 // first collection
449 ASSERT_EQ(batch(handle, firstCollectionPeriod, batchingPeriodInNs), Result::OK);
450 ASSERT_EQ(activate(handle, 1), Result::OK);
451
452 usleep(500000); // sleep 0.5 sec to wait for change rate to happen
453 events1 = collectEvents(collectionTimeoutUs, minNEvent);
454
455 // second collection, without stop sensor
456 ASSERT_EQ(batch(handle, secondCollectionPeriod, batchingPeriodInNs), Result::OK);
457
458 usleep(500000); // sleep 0.5 sec to wait for change rate to happen
459 events2 = collectEvents(collectionTimeoutUs, minNEvent);
460
461 // end of collection, stop sensor
462 ASSERT_EQ(activate(handle, 0), Result::OK);
463
464 ALOGI("Collected %zu fast samples and %zu slow samples", events1.size(), events2.size());
465
466 ASSERT_GT(events1.size(), 0u);
467 ASSERT_GT(events2.size(), 0u);
468
469 int64_t minDelayAverageInterval, maxDelayAverageInterval;
470 std::vector<Event>& minDelayEvents(fastToSlow ? events1 : events2);
471 std::vector<Event>& maxDelayEvents(fastToSlow ? events2 : events1);
472
473 size_t nEvent = 0;
474 int64_t prevTimestamp = -1;
475 int64_t timestampInterval = 0;
476 for (auto& e : minDelayEvents) {
477 if (e.sensorType == type) {
478 ASSERT_EQ(e.sensorHandle, handle);
479 if (prevTimestamp > 0) {
480 timestampInterval += e.timestamp - prevTimestamp;
481 }
482 prevTimestamp = e.timestamp;
483 ++nEvent;
484 }
485 }
486 ASSERT_GT(nEvent, 2u);
487 minDelayAverageInterval = timestampInterval / (nEvent - 1);
488
489 nEvent = 0;
490 prevTimestamp = -1;
491 timestampInterval = 0;
492 for (auto& e : maxDelayEvents) {
493 if (e.sensorType == type) {
494 ASSERT_EQ(e.sensorHandle, handle);
495 if (prevTimestamp > 0) {
496 timestampInterval += e.timestamp - prevTimestamp;
497 }
498 prevTimestamp = e.timestamp;
499 ++nEvent;
500 }
501 }
502 ASSERT_GT(nEvent, 2u);
503 maxDelayAverageInterval = timestampInterval / (nEvent - 1);
504
505 // change of rate is significant.
506 ALOGI("min/maxDelayAverageInterval = %" PRId64 " %" PRId64, minDelayAverageInterval,
507 maxDelayAverageInterval);
508 EXPECT_GT((maxDelayAverageInterval - minDelayAverageInterval), minDelayAverageInterval / 10);
509
510 // fastest rate sampling time is close to spec
511 EXPECT_LT(std::abs(minDelayAverageInterval - minSamplingPeriodInNs),
512 minSamplingPeriodInNs / 10);
513
514 // slowest rate sampling time is close to spec
515 EXPECT_LT(std::abs(maxDelayAverageInterval - maxSamplingPeriodInNs),
516 maxSamplingPeriodInNs / 10);
517 }
518
testBatchingOperation(SensorType type)519 void SensorsHidlTestBase::testBatchingOperation(SensorType type) {
520 std::vector<Event> events;
521
522 constexpr int64_t maxBatchingTestTimeNs = 30ull * 1000 * 1000 * 1000;
523 constexpr int64_t oneSecondInNs = 1ull * 1000 * 1000 * 1000;
524
525 SensorInfo sensor = defaultSensorByType(type);
526
527 if (!isValidType(sensor.type)) {
528 // no default sensor of this type
529 return;
530 }
531
532 int32_t handle = sensor.sensorHandle;
533 int64_t minSamplingPeriodInNs = sensor.minDelay * 1000ll;
534 uint32_t minFifoCount = sensor.fifoReservedEventCount;
535 int64_t batchingPeriodInNs = minFifoCount * minSamplingPeriodInNs;
536
537 if (batchingPeriodInNs < oneSecondInNs) {
538 // batching size too small to test reliably
539 return;
540 }
541
542 batchingPeriodInNs = std::min(batchingPeriodInNs, maxBatchingTestTimeNs);
543
544 ALOGI("Test batching for %d ms", (int)(batchingPeriodInNs / 1000 / 1000));
545
546 int64_t allowedBatchDeliverTimeNs = std::max(oneSecondInNs, batchingPeriodInNs / 10);
547
548 ASSERT_EQ(batch(handle, minSamplingPeriodInNs, INT64_MAX), Result::OK);
549 ASSERT_EQ(activate(handle, 1), Result::OK);
550
551 usleep(500000); // sleep 0.5 sec to wait for initialization
552 ASSERT_EQ(flush(handle), Result::OK);
553
554 // wait for 80% of the reserved batching period
555 // there should not be any significant amount of events
556 // since collection is not enabled all events will go down the drain
557 usleep(batchingPeriodInNs / 1000 * 8 / 10);
558
559 getEnvironment()->setCollection(true);
560 // clean existing collections
561 collectEvents(0 /*timeLimitUs*/, 0 /*nEventLimit*/, true /*clearBeforeStart*/,
562 false /*change collection*/);
563
564 // 0.8 + 0.2 times the batching period
565 usleep(batchingPeriodInNs / 1000 * 8 / 10);
566 ASSERT_EQ(flush(handle), Result::OK);
567
568 // plus some time for the event to deliver
569 events = collectEvents(allowedBatchDeliverTimeNs / 1000, minFifoCount,
570 false /*clearBeforeStart*/, false /*change collection*/);
571
572 getEnvironment()->setCollection(false);
573 ASSERT_EQ(activate(handle, 0), Result::OK);
574
575 size_t nEvent = 0;
576 for (auto& e : events) {
577 if (e.sensorType == type && e.sensorHandle == handle) {
578 ++nEvent;
579 }
580 }
581
582 // at least reach 90% of advertised capacity
583 ASSERT_GT(nEvent, (size_t)(minFifoCount * 9 / 10));
584 }
585