1 /*
2 * Copyright (C) 2016 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 #include <VtsHalHidlTargetTestBase.h>
19 #include <VtsHalHidlTargetTestEnvBase.h>
20 #include <android-base/logging.h>
21 #include <android/hardware/sensors/1.0/ISensors.h>
22 #include <android/hardware/sensors/1.0/types.h>
23 #include <cutils/ashmem.h>
24 #include <hardware/sensors.h> // for sensor type strings
25 #include <log/log.h>
26 #include <utils/SystemClock.h>
27 #include "GrallocWrapper.h"
28
29 #include <algorithm>
30 #include <cinttypes>
31 #include <cmath>
32 #include <memory>
33 #include <mutex>
34 #include <thread>
35 #include <unordered_set>
36 #include <vector>
37
38 #include <sys/mman.h>
39 #include <unistd.h>
40
41 using ::android::GrallocWrapper;
42 using ::android::hardware::Return;
43 using ::android::hardware::Void;
44 using ::android::hardware::hidl_string;
45 using ::android::sp;
46 using namespace ::android::hardware::sensors::V1_0;
47
48 // Test environment for sensors
49 class SensorsHidlTest;
50 class SensorsHidlEnvironment : public ::testing::VtsHalHidlTargetTestEnvBase {
51 public:
52 // get the test environment singleton
Instance()53 static SensorsHidlEnvironment* Instance() {
54 static SensorsHidlEnvironment* instance = new SensorsHidlEnvironment;
55 return instance;
56 }
57
58 virtual void HidlSetUp() override;
59 virtual void HidlTearDown() override;
60
registerTestServices()61 virtual void registerTestServices() override { registerTestService<ISensors>(); }
62
63 // Get and clear all events collected so far (like "cat" shell command).
64 // If output is nullptr, it clears all collected events.
65 void catEvents(std::vector<Event>* output);
66
67 // set sensor event collection status
68 void setCollection(bool enable);
69
70 private:
71 friend SensorsHidlTest;
72 // sensors hidl service
73 sp<ISensors> sensors;
74
SensorsHidlEnvironment()75 SensorsHidlEnvironment() {}
76
77 void addEvent(const Event& ev);
78 void startPollingThread();
79 void resetHal();
80 static void pollingThread(SensorsHidlEnvironment* env, std::shared_ptr<bool> stop);
81
82 bool collectionEnabled;
83 std::shared_ptr<bool> stopThread;
84 std::thread pollThread;
85 std::vector<Event> events;
86 std::mutex events_mutex;
87
88 GTEST_DISALLOW_COPY_AND_ASSIGN_(SensorsHidlEnvironment);
89 };
90
HidlSetUp()91 void SensorsHidlEnvironment::HidlSetUp() {
92 resetHal();
93
94 ASSERT_NE(sensors, nullptr) << "sensors is nullptr, cannot get hidl service";
95
96 collectionEnabled = false;
97 startPollingThread();
98
99 // In case framework just stopped for test and there is sensor events in the pipe,
100 // wait some time for those events to be cleared to avoid them messing up the test.
101 std::this_thread::sleep_for(std::chrono::seconds(3));
102 }
103
HidlTearDown()104 void SensorsHidlEnvironment::HidlTearDown() {
105 if (stopThread) {
106 *stopThread = true;
107 }
108 pollThread.detach();
109 }
110
resetHal()111 void SensorsHidlEnvironment::resetHal() {
112 // wait upto 100ms * 10 = 1s for hidl service.
113 constexpr auto RETRY_DELAY = std::chrono::milliseconds(100);
114
115 std::string step;
116 bool succeed = false;
117 for (size_t retry = 10; retry > 0; --retry) {
118 // this do ... while is for easy error handling
119 do {
120 step = "getService()";
121 sensors = ISensors::getService(
122 SensorsHidlEnvironment::Instance()->getServiceName<ISensors>());
123 if (sensors == nullptr) {
124 break;
125 }
126
127 step = "poll() check";
128 // Poke ISensor service. If it has lingering connection from previous generation of
129 // system server, it will kill itself. There is no intention to handle the poll result,
130 // which will be done since the size is 0.
131 if(!sensors->poll(0, [](auto, const auto &, const auto &) {}).isOk()) {
132 break;
133 }
134
135 step = "getSensorList";
136 std::vector<SensorInfo> sensorList;
137 if (!sensors->getSensorsList(
138 [&] (const ::android::hardware::hidl_vec<SensorInfo> &list) {
139 sensorList.reserve(list.size());
140 for (size_t i = 0; i < list.size(); ++i) {
141 sensorList.push_back(list[i]);
142 }
143 }).isOk()) {
144 break;
145 }
146
147 // stop each sensor individually
148 step = "stop each sensor";
149 bool ok = true;
150 for (const auto &i : sensorList) {
151 if (!sensors->activate(i.sensorHandle, false).isOk()) {
152 ok = false;
153 break;
154 }
155 }
156 if (!ok) {
157 break;
158 }
159
160 // mark it done
161 step = "done";
162 succeed = true;
163 } while(0);
164
165 if (succeed) {
166 return;
167 }
168
169 // Delay 100ms before retry, hidl service is expected to come up in short time after crash.
170 ALOGI("%s unsuccessful, try again soon (remaining retry %zu).", step.c_str(), retry - 1);
171 std::this_thread::sleep_for(RETRY_DELAY);
172 }
173
174 sensors = nullptr;
175 }
176
catEvents(std::vector<Event> * output)177 void SensorsHidlEnvironment::catEvents(std::vector<Event>* output) {
178 std::lock_guard<std::mutex> lock(events_mutex);
179 if (output) {
180 output->insert(output->end(), events.begin(), events.end());
181 }
182 events.clear();
183 }
184
setCollection(bool enable)185 void SensorsHidlEnvironment::setCollection(bool enable) {
186 std::lock_guard<std::mutex> lock(events_mutex);
187 collectionEnabled = enable;
188 }
189
addEvent(const Event & ev)190 void SensorsHidlEnvironment::addEvent(const Event& ev) {
191 std::lock_guard<std::mutex> lock(events_mutex);
192 if (collectionEnabled) {
193 events.push_back(ev);
194 }
195 }
196
startPollingThread()197 void SensorsHidlEnvironment::startPollingThread() {
198 stopThread = std::shared_ptr<bool>(new bool(false));
199 pollThread = std::thread(pollingThread, this, stopThread);
200 events.reserve(128);
201 }
202
pollingThread(SensorsHidlEnvironment * env,std::shared_ptr<bool> stop)203 void SensorsHidlEnvironment::pollingThread(
204 SensorsHidlEnvironment* env, std::shared_ptr<bool> stop) {
205 ALOGD("polling thread start");
206 bool needExit = *stop;
207
208 while(!needExit) {
209 env->sensors->poll(64, [&](auto result, const auto& events, const auto& dynamicSensorsAdded) {
210 if (result != Result::OK
211 || (events.size() == 0 && dynamicSensorsAdded.size() == 0)
212 || *stop) {
213 needExit = true;
214 return;
215 }
216
217 for (const auto& e : events) {
218 env->addEvent(e);
219 }
220 });
221 }
222 ALOGD("polling thread end");
223 }
224
225 class SensorsTestSharedMemory {
226 public:
227 static SensorsTestSharedMemory* create(SharedMemType type, size_t size);
228 SharedMemInfo getSharedMemInfo() const;
229 char * getBuffer() const;
230 std::vector<Event> parseEvents(int64_t lastCounter = -1, size_t offset = 0) const;
231 virtual ~SensorsTestSharedMemory();
232 private:
233 SensorsTestSharedMemory(SharedMemType type, size_t size);
234
235 SharedMemType mType;
236 native_handle_t* mNativeHandle;
237 size_t mSize;
238 char* mBuffer;
239 std::unique_ptr<GrallocWrapper> mGrallocWrapper;
240
241 DISALLOW_COPY_AND_ASSIGN(SensorsTestSharedMemory);
242 };
243
getSharedMemInfo() const244 SharedMemInfo SensorsTestSharedMemory::getSharedMemInfo() const {
245 SharedMemInfo mem = {
246 .type = mType,
247 .format = SharedMemFormat::SENSORS_EVENT,
248 .size = static_cast<uint32_t>(mSize),
249 .memoryHandle = mNativeHandle
250 };
251 return mem;
252 }
253
getBuffer() const254 char * SensorsTestSharedMemory::getBuffer() const {
255 return mBuffer;
256 }
257
parseEvents(int64_t lastCounter,size_t offset) const258 std::vector<Event> SensorsTestSharedMemory::parseEvents(int64_t lastCounter, size_t offset) const {
259
260 constexpr size_t kEventSize = static_cast<size_t>(SensorsEventFormatOffset::TOTAL_LENGTH);
261 constexpr size_t kOffsetSize = static_cast<size_t>(SensorsEventFormatOffset::SIZE_FIELD);
262 constexpr size_t kOffsetToken = static_cast<size_t>(SensorsEventFormatOffset::REPORT_TOKEN);
263 constexpr size_t kOffsetType = static_cast<size_t>(SensorsEventFormatOffset::SENSOR_TYPE);
264 constexpr size_t kOffsetAtomicCounter =
265 static_cast<size_t>(SensorsEventFormatOffset::ATOMIC_COUNTER);
266 constexpr size_t kOffsetTimestamp = static_cast<size_t>(SensorsEventFormatOffset::TIMESTAMP);
267 constexpr size_t kOffsetData = static_cast<size_t>(SensorsEventFormatOffset::DATA);
268
269 std::vector<Event> events;
270 std::vector<float> data(16);
271
272 while (offset + kEventSize <= mSize) {
273 int64_t atomicCounter = *reinterpret_cast<uint32_t *>(mBuffer + offset + kOffsetAtomicCounter);
274 if (atomicCounter <= lastCounter) {
275 ALOGV("atomicCounter = %" PRId64 ", lastCounter = %" PRId64, atomicCounter, lastCounter);
276 break;
277 }
278
279 int32_t size = *reinterpret_cast<int32_t *>(mBuffer + offset + kOffsetSize);
280 if (size != kEventSize) {
281 // unknown error, events parsed may be wrong, remove all
282 events.clear();
283 break;
284 }
285
286 int32_t token = *reinterpret_cast<int32_t *>(mBuffer + offset + kOffsetToken);
287 int32_t type = *reinterpret_cast<int32_t *>(mBuffer + offset + kOffsetType);
288 int64_t timestamp = *reinterpret_cast<int64_t *>(mBuffer + offset + kOffsetTimestamp);
289
290 ALOGV("offset = %zu, cnt %" PRId64 ", token %" PRId32 ", type %" PRId32 ", timestamp %" PRId64,
291 offset, atomicCounter, token, type, timestamp);
292
293 Event event = {
294 .timestamp = timestamp,
295 .sensorHandle = token,
296 .sensorType = static_cast<SensorType>(type),
297 };
298 event.u.data = android::hardware::hidl_array<float, 16>
299 (reinterpret_cast<float*>(mBuffer + offset + kOffsetData));
300
301 events.push_back(event);
302
303 lastCounter = atomicCounter;
304 offset += kEventSize;
305 }
306
307 return events;
308 }
309
SensorsTestSharedMemory(SharedMemType type,size_t size)310 SensorsTestSharedMemory::SensorsTestSharedMemory(SharedMemType type, size_t size)
311 : mType(type), mSize(0), mBuffer(nullptr) {
312 native_handle_t *handle = nullptr;
313 char *buffer = nullptr;
314 switch(type) {
315 case SharedMemType::ASHMEM: {
316 int fd;
317 handle = ::native_handle_create(1 /*nFds*/, 0/*nInts*/);
318 if (handle != nullptr) {
319 handle->data[0] = fd = ::ashmem_create_region("SensorsTestSharedMemory", size);
320 if (handle->data[0] > 0) {
321 // memory is pinned by default
322 buffer = static_cast<char *>
323 (::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
324 if (buffer != reinterpret_cast<char*>(MAP_FAILED)) {
325 break;
326 }
327 ::native_handle_close(handle);
328 }
329 ::native_handle_delete(handle);
330 handle = nullptr;
331 }
332 break;
333 }
334 case SharedMemType::GRALLOC: {
335 mGrallocWrapper = std::make_unique<GrallocWrapper>();
336 if (mGrallocWrapper->getAllocator() == nullptr || mGrallocWrapper->getMapper() == nullptr) {
337 break;
338 }
339 using android::hardware::graphics::common::V1_0::BufferUsage;
340 using android::hardware::graphics::common::V1_0::PixelFormat;
341 mapper2::IMapper::BufferDescriptorInfo buf_desc_info = {
342 .width = static_cast<uint32_t>(size),
343 .height = 1,
344 .layerCount = 1,
345 .usage = static_cast<uint64_t> (BufferUsage::SENSOR_DIRECT_DATA |
346 BufferUsage::CPU_READ_OFTEN),
347 .format = PixelFormat::BLOB
348 };
349
350 handle = const_cast<native_handle_t *>(mGrallocWrapper->allocate(buf_desc_info));
351 if (handle != nullptr) {
352 mapper2::IMapper::Rect region{0, 0,
353 static_cast<int32_t>(buf_desc_info.width),
354 static_cast<int32_t>(buf_desc_info.height)};
355 buffer = static_cast<char *>
356 (mGrallocWrapper->lock(handle, buf_desc_info.usage, region, /*fence=*/-1));
357 if (buffer != nullptr) {
358 break;
359 }
360 mGrallocWrapper->freeBuffer(handle);
361 handle = nullptr;
362 }
363 break;
364 }
365 default:
366 break;
367 }
368
369 if (buffer != nullptr) {
370 mNativeHandle = handle;
371 mSize = size;
372 mBuffer = buffer;
373 }
374 }
375
~SensorsTestSharedMemory()376 SensorsTestSharedMemory::~SensorsTestSharedMemory() {
377 switch(mType) {
378 case SharedMemType::ASHMEM: {
379 if (mSize != 0) {
380 ::munmap(mBuffer, mSize);
381 mBuffer = nullptr;
382
383 ::native_handle_close(mNativeHandle);
384 ::native_handle_delete(mNativeHandle);
385
386 mNativeHandle = nullptr;
387 mSize = 0;
388 }
389 break;
390 }
391 case SharedMemType::GRALLOC: {
392 if (mSize != 0) {
393 mGrallocWrapper->unlock(mNativeHandle);
394 mGrallocWrapper->freeBuffer(mNativeHandle);
395
396 mNativeHandle = nullptr;
397 mSize = 0;
398 }
399 break;
400 }
401 default: {
402 if (mNativeHandle != nullptr || mSize != 0 || mBuffer != nullptr) {
403 ALOGE("SensorsTestSharedMemory %p not properly destructed: "
404 "type %d, native handle %p, size %zu, buffer %p",
405 this, static_cast<int>(mType), mNativeHandle, mSize, mBuffer);
406 }
407 break;
408 }
409 }
410 }
411
create(SharedMemType type,size_t size)412 SensorsTestSharedMemory* SensorsTestSharedMemory::create(SharedMemType type, size_t size) {
413 constexpr size_t kMaxSize = 128*1024*1024; // sensor test should not need more than 128M
414 if (size == 0 || size >= kMaxSize) {
415 return nullptr;
416 }
417
418 auto m = new SensorsTestSharedMemory(type, size);
419 if (m->mSize != size || m->mBuffer == nullptr) {
420 delete m;
421 m = nullptr;
422 }
423 return m;
424 }
425
426 class SensorEventsChecker {
427 public:
428 virtual bool check(const std::vector<Event> &events, std::string *out) const = 0;
~SensorEventsChecker()429 virtual ~SensorEventsChecker() {}
430 };
431
432 class NullChecker : public SensorEventsChecker {
433 public:
check(const std::vector<Event> &,std::string *) const434 virtual bool check(const std::vector<Event> &, std::string *) const {
435 return true;
436 }
437 };
438
439 class SensorEventPerEventChecker : public SensorEventsChecker {
440 public:
441 virtual bool checkEvent(const Event &event, std::string *out) const = 0;
check(const std::vector<Event> & events,std::string * out) const442 virtual bool check(const std::vector<Event> &events, std::string *out) const {
443 for (const auto &e : events) {
444 if (!checkEvent(e, out)) {
445 return false;
446 }
447 }
448 return true;
449 }
450 };
451
452 class Vec3NormChecker : public SensorEventPerEventChecker {
453 public:
Vec3NormChecker(float min,float max)454 Vec3NormChecker(float min, float max) : mRange(min, max) {}
byNominal(float nominal,float allowedError)455 static Vec3NormChecker byNominal(float nominal, float allowedError) {
456 return Vec3NormChecker(nominal - allowedError, nominal + allowedError);
457 }
458
checkEvent(const Event & event,std::string * out) const459 virtual bool checkEvent(const Event &event, std::string *out) const {
460 Vec3 v = event.u.vec3;
461 float norm = std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
462 if (norm < mRange.first || norm > mRange.second) {
463 if (out != nullptr) {
464 std::ostringstream ss;
465 ss << "Event @ " << event.timestamp << " (" << v.x << ", " << v.y << ", " << v.z << ")"
466 << " has norm " << norm << ", which is beyond range"
467 << " [" << mRange.first << ", " << mRange.second << "]";
468 *out = ss.str();
469 }
470 return false;
471 }
472 return true;
473 }
474 protected:
475 std::pair<float, float> mRange;
476 };
477
478 // The main test class for SENSORS HIDL HAL.
479 class SensorsHidlTest : public ::testing::VtsHalHidlTargetTestBase {
480 public:
SetUp()481 virtual void SetUp() override {
482 }
483
TearDown()484 virtual void TearDown() override {
485 // stop all sensors
486 for (auto s : mSensorHandles) {
487 S()->activate(s, false);
488 }
489 mSensorHandles.clear();
490
491 // stop all direct report and channels
492 for (auto c : mDirectChannelHandles) {
493 // disable all reports
494 S()->configDirectReport(-1, c, RateLevel::STOP, [] (auto, auto){});
495 S()->unregisterDirectChannel(c);
496 }
497 mDirectChannelHandles.clear();
498 }
499
500 protected:
501 SensorInfo defaultSensorByType(SensorType type);
502 std::vector<SensorInfo> getSensorsList();
503 std::vector<Event> collectEvents(useconds_t timeLimitUs, size_t nEventLimit,
504 bool clearBeforeStart = true, bool changeCollection = true);
505
506 // implementation wrapper
getSensorsList(ISensors::getSensorsList_cb _hidl_cb)507 Return<void> getSensorsList(ISensors::getSensorsList_cb _hidl_cb) {
508 return S()->getSensorsList(_hidl_cb);
509 }
510
511 Return<Result> activate(
512 int32_t sensorHandle, bool enabled);
513
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)514 Return<Result> batch(
515 int32_t sensorHandle,
516 int64_t samplingPeriodNs,
517 int64_t maxReportLatencyNs) {
518 return S()->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs);
519 }
520
flush(int32_t sensorHandle)521 Return<Result> flush(int32_t sensorHandle) {
522 return S()->flush(sensorHandle);
523 }
524
injectSensorData(const Event & event)525 Return<Result> injectSensorData(const Event& event) {
526 return S()->injectSensorData(event);
527 }
528
529 Return<void> registerDirectChannel(
530 const SharedMemInfo& mem, ISensors::registerDirectChannel_cb _hidl_cb);
531
unregisterDirectChannel(int32_t channelHandle)532 Return<Result> unregisterDirectChannel(int32_t channelHandle) {
533 return S()->unregisterDirectChannel(channelHandle);
534 }
535
configDirectReport(int32_t sensorHandle,int32_t channelHandle,RateLevel rate,ISensors::configDirectReport_cb _hidl_cb)536 Return<void> configDirectReport(
537 int32_t sensorHandle, int32_t channelHandle, RateLevel rate,
538 ISensors::configDirectReport_cb _hidl_cb) {
539 return S()->configDirectReport(sensorHandle, channelHandle, rate, _hidl_cb);
540 }
541
S()542 inline sp<ISensors>& S() {
543 return SensorsHidlEnvironment::Instance()->sensors;
544 }
545
extractReportMode(uint64_t flag)546 inline static SensorFlagBits extractReportMode(uint64_t flag) {
547 return (SensorFlagBits) (flag
548 & ((uint64_t) SensorFlagBits::CONTINUOUS_MODE
549 | (uint64_t) SensorFlagBits::ON_CHANGE_MODE
550 | (uint64_t) SensorFlagBits::ONE_SHOT_MODE
551 | (uint64_t) SensorFlagBits::SPECIAL_REPORTING_MODE));
552 }
553
isMetaSensorType(SensorType type)554 inline static bool isMetaSensorType(SensorType type) {
555 return (type == SensorType::META_DATA
556 || type == SensorType::DYNAMIC_SENSOR_META
557 || type == SensorType::ADDITIONAL_INFO);
558 }
559
isValidType(SensorType type)560 inline static bool isValidType(SensorType type) {
561 return (int32_t) type > 0;
562 }
563
564 void testStreamingOperation(SensorType type,
565 std::chrono::nanoseconds samplingPeriod,
566 std::chrono::seconds duration,
567 const SensorEventsChecker &checker);
568 void testSamplingRateHotSwitchOperation(SensorType type, bool fastToSlow = true);
569 void testBatchingOperation(SensorType type);
570 void testDirectReportOperation(
571 SensorType type, SharedMemType memType, RateLevel rate, const SensorEventsChecker &checker);
572
573 static void assertTypeMatchStringType(SensorType type, const hidl_string& stringType);
574 static void assertTypeMatchReportMode(SensorType type, SensorFlagBits reportMode);
575 static void assertDelayMatchReportMode(
576 int32_t minDelay, int32_t maxDelay, SensorFlagBits reportMode);
577 static SensorFlagBits expectedReportModeForType(SensorType type);
578 static bool isDirectReportRateSupported(SensorInfo sensor, RateLevel rate);
579 static bool isDirectChannelTypeSupported(SensorInfo sensor, SharedMemType type);
580
581 // checkers
582 static const Vec3NormChecker sAccelNormChecker;
583 static const Vec3NormChecker sGyroNormChecker;
584
585 // all sensors and direct channnels used
586 std::unordered_set<int32_t> mSensorHandles;
587 std::unordered_set<int32_t> mDirectChannelHandles;
588 };
589
590 const Vec3NormChecker SensorsHidlTest::sAccelNormChecker(
591 Vec3NormChecker::byNominal(GRAVITY_EARTH, 1.0f/*m/s^2*/));
592 const Vec3NormChecker SensorsHidlTest::sGyroNormChecker(
593 Vec3NormChecker::byNominal(0.f, 0.1f/*rad/s*/));
594
activate(int32_t sensorHandle,bool enabled)595 Return<Result> SensorsHidlTest::activate(int32_t sensorHandle, bool enabled) {
596 // If activating a sensor, add the handle in a set so that when test fails it can be turned off.
597 // The handle is not removed when it is deactivating on purpose so that it is not necessary to
598 // check the return value of deactivation. Deactivating a sensor more than once does not have
599 // negative effect.
600 if (enabled) {
601 mSensorHandles.insert(sensorHandle);
602 }
603 return S()->activate(sensorHandle, enabled);
604 }
605
registerDirectChannel(const SharedMemInfo & mem,ISensors::registerDirectChannel_cb cb)606 Return<void> SensorsHidlTest::registerDirectChannel(
607 const SharedMemInfo& mem, ISensors::registerDirectChannel_cb cb) {
608 // If registeration of a channel succeeds, add the handle of channel to a set so that it can be
609 // unregistered when test fails. Unregister a channel does not remove the handle on purpose.
610 // Unregistering a channel more than once should not have negative effect.
611 S()->registerDirectChannel(mem,
612 [&] (auto result, auto channelHandle) {
613 if (result == Result::OK) {
614 mDirectChannelHandles.insert(channelHandle);
615 }
616 cb(result, channelHandle);
617 });
618 return Void();
619 }
620
collectEvents(useconds_t timeLimitUs,size_t nEventLimit,bool clearBeforeStart,bool changeCollection)621 std::vector<Event> SensorsHidlTest::collectEvents(useconds_t timeLimitUs, size_t nEventLimit,
622 bool clearBeforeStart, bool changeCollection) {
623 std::vector<Event> events;
624 constexpr useconds_t SLEEP_GRANULARITY = 100*1000; //granularity 100 ms
625
626 ALOGI("collect max of %zu events for %d us, clearBeforeStart %d",
627 nEventLimit, timeLimitUs, clearBeforeStart);
628
629 if (changeCollection) {
630 SensorsHidlEnvironment::Instance()->setCollection(true);
631 }
632 if (clearBeforeStart) {
633 SensorsHidlEnvironment::Instance()->catEvents(nullptr);
634 }
635
636 while (timeLimitUs > 0) {
637 useconds_t duration = std::min(SLEEP_GRANULARITY, timeLimitUs);
638 usleep(duration);
639 timeLimitUs -= duration;
640
641 SensorsHidlEnvironment::Instance()->catEvents(&events);
642 if (events.size() >= nEventLimit) {
643 break;
644 }
645 ALOGV("time to go = %d, events to go = %d",
646 (int)timeLimitUs, (int)(nEventLimit - events.size()));
647 }
648
649 if (changeCollection) {
650 SensorsHidlEnvironment::Instance()->setCollection(false);
651 }
652 return events;
653 }
654
assertTypeMatchStringType(SensorType type,const hidl_string & stringType)655 void SensorsHidlTest::assertTypeMatchStringType(SensorType type, const hidl_string& stringType) {
656
657 if (type >= SensorType::DEVICE_PRIVATE_BASE) {
658 return;
659 }
660
661 switch (type) {
662 #define CHECK_TYPE_STRING_FOR_SENSOR_TYPE(type) \
663 case SensorType::type: ASSERT_STREQ(SENSOR_STRING_TYPE_ ## type, stringType.c_str()); break;
664 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER);
665 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ACCELEROMETER_UNCALIBRATED);
666 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ADDITIONAL_INFO);
667 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(AMBIENT_TEMPERATURE);
668 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DEVICE_ORIENTATION);
669 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(DYNAMIC_SENSOR_META);
670 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GAME_ROTATION_VECTOR);
671 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GEOMAGNETIC_ROTATION_VECTOR);
672 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GLANCE_GESTURE);
673 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GRAVITY);
674 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE);
675 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(GYROSCOPE_UNCALIBRATED);
676 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_BEAT);
677 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(HEART_RATE);
678 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LIGHT);
679 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LINEAR_ACCELERATION);
680 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(LOW_LATENCY_OFFBODY_DETECT);
681 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD);
682 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MAGNETIC_FIELD_UNCALIBRATED);
683 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(MOTION_DETECT);
684 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ORIENTATION);
685 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PICK_UP_GESTURE);
686 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(POSE_6DOF);
687 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PRESSURE);
688 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(PROXIMITY);
689 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(RELATIVE_HUMIDITY);
690 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(ROTATION_VECTOR);
691 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(SIGNIFICANT_MOTION);
692 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STATIONARY_DETECT);
693 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_COUNTER);
694 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(STEP_DETECTOR);
695 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TEMPERATURE);
696 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(TILT_DETECTOR);
697 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WAKE_GESTURE);
698 CHECK_TYPE_STRING_FOR_SENSOR_TYPE(WRIST_TILT_GESTURE);
699 default:
700 FAIL() << "Type " << static_cast<int>(type) << " in android defined range is not checked, "
701 << "stringType = " << stringType;
702 #undef CHECK_TYPE_STRING_FOR_SENSOR_TYPE
703 }
704 }
705
assertTypeMatchReportMode(SensorType type,SensorFlagBits reportMode)706 void SensorsHidlTest::assertTypeMatchReportMode(SensorType type, SensorFlagBits reportMode) {
707 if (type >= SensorType::DEVICE_PRIVATE_BASE) {
708 return;
709 }
710
711 SensorFlagBits expected = expectedReportModeForType(type);
712
713 ASSERT_TRUE(expected == (SensorFlagBits) -1 || expected == reportMode)
714 << "reportMode=" << static_cast<int>(reportMode)
715 << "expected=" << static_cast<int>(expected);
716 }
717
assertDelayMatchReportMode(int32_t minDelay,int32_t maxDelay,SensorFlagBits reportMode)718 void SensorsHidlTest::assertDelayMatchReportMode(
719 int32_t minDelay, int32_t maxDelay, SensorFlagBits reportMode) {
720 switch(reportMode) {
721 case SensorFlagBits::CONTINUOUS_MODE:
722 ASSERT_LT(0, minDelay);
723 ASSERT_LE(0, maxDelay);
724 break;
725 case SensorFlagBits::ON_CHANGE_MODE:
726 ASSERT_LE(0, minDelay);
727 ASSERT_LE(0, maxDelay);
728 break;
729 case SensorFlagBits::ONE_SHOT_MODE:
730 ASSERT_EQ(-1, minDelay);
731 ASSERT_EQ(0, maxDelay);
732 break;
733 case SensorFlagBits::SPECIAL_REPORTING_MODE:
734 // do not enforce anything for special reporting mode
735 break;
736 default:
737 FAIL() << "Report mode " << static_cast<int>(reportMode) << " not checked";
738 }
739 }
740
741 // return -1 means no expectation for this type
expectedReportModeForType(SensorType type)742 SensorFlagBits SensorsHidlTest::expectedReportModeForType(SensorType type) {
743 switch (type) {
744 case SensorType::ACCELEROMETER:
745 case SensorType::ACCELEROMETER_UNCALIBRATED:
746 case SensorType::GYROSCOPE:
747 case SensorType::MAGNETIC_FIELD:
748 case SensorType::ORIENTATION:
749 case SensorType::PRESSURE:
750 case SensorType::TEMPERATURE:
751 case SensorType::GRAVITY:
752 case SensorType::LINEAR_ACCELERATION:
753 case SensorType::ROTATION_VECTOR:
754 case SensorType::MAGNETIC_FIELD_UNCALIBRATED:
755 case SensorType::GAME_ROTATION_VECTOR:
756 case SensorType::GYROSCOPE_UNCALIBRATED:
757 case SensorType::GEOMAGNETIC_ROTATION_VECTOR:
758 case SensorType::POSE_6DOF:
759 case SensorType::HEART_BEAT:
760 return SensorFlagBits::CONTINUOUS_MODE;
761
762 case SensorType::LIGHT:
763 case SensorType::PROXIMITY:
764 case SensorType::RELATIVE_HUMIDITY:
765 case SensorType::AMBIENT_TEMPERATURE:
766 case SensorType::HEART_RATE:
767 case SensorType::DEVICE_ORIENTATION:
768 case SensorType::STEP_COUNTER:
769 case SensorType::LOW_LATENCY_OFFBODY_DETECT:
770 return SensorFlagBits::ON_CHANGE_MODE;
771
772 case SensorType::SIGNIFICANT_MOTION:
773 case SensorType::WAKE_GESTURE:
774 case SensorType::GLANCE_GESTURE:
775 case SensorType::PICK_UP_GESTURE:
776 case SensorType::MOTION_DETECT:
777 case SensorType::STATIONARY_DETECT:
778 return SensorFlagBits::ONE_SHOT_MODE;
779
780 case SensorType::STEP_DETECTOR:
781 case SensorType::TILT_DETECTOR:
782 case SensorType::WRIST_TILT_GESTURE:
783 case SensorType::DYNAMIC_SENSOR_META:
784 return SensorFlagBits::SPECIAL_REPORTING_MODE;
785
786 default:
787 ALOGW("Type %d is not implemented in expectedReportModeForType", (int)type);
788 return (SensorFlagBits)-1;
789 }
790 }
791
isDirectReportRateSupported(SensorInfo sensor,RateLevel rate)792 bool SensorsHidlTest::isDirectReportRateSupported(SensorInfo sensor, RateLevel rate) {
793 unsigned int r =
794 static_cast<unsigned int>(sensor.flags & SensorFlagBits::MASK_DIRECT_REPORT)
795 >> static_cast<unsigned int>(SensorFlagShift::DIRECT_REPORT);
796 return r >= static_cast<unsigned int>(rate);
797 }
798
isDirectChannelTypeSupported(SensorInfo sensor,SharedMemType type)799 bool SensorsHidlTest::isDirectChannelTypeSupported(SensorInfo sensor, SharedMemType type) {
800 switch (type) {
801 case SharedMemType::ASHMEM:
802 return (sensor.flags & SensorFlagBits::DIRECT_CHANNEL_ASHMEM) != 0;
803 case SharedMemType::GRALLOC:
804 return (sensor.flags & SensorFlagBits::DIRECT_CHANNEL_GRALLOC) != 0;
805 default:
806 return false;
807 }
808 }
809
defaultSensorByType(SensorType type)810 SensorInfo SensorsHidlTest::defaultSensorByType(SensorType type) {
811 SensorInfo ret;
812
813 ret.type = (SensorType) -1;
814 S()->getSensorsList(
815 [&] (const auto &list) {
816 const size_t count = list.size();
817 for (size_t i = 0; i < count; ++i) {
818 if (list[i].type == type) {
819 ret = list[i];
820 return;
821 }
822 }
823 });
824
825 return ret;
826 }
827
getSensorsList()828 std::vector<SensorInfo> SensorsHidlTest::getSensorsList() {
829 std::vector<SensorInfo> ret;
830
831 S()->getSensorsList(
832 [&] (const auto &list) {
833 const size_t count = list.size();
834 ret.reserve(list.size());
835 for (size_t i = 0; i < count; ++i) {
836 ret.push_back(list[i]);
837 }
838 });
839
840 return ret;
841 }
842
843 // Test if sensor list returned is valid
TEST_F(SensorsHidlTest,SensorListValid)844 TEST_F(SensorsHidlTest, SensorListValid) {
845 S()->getSensorsList(
846 [&] (const auto &list) {
847 const size_t count = list.size();
848 for (size_t i = 0; i < count; ++i) {
849 const auto &s = list[i];
850 SCOPED_TRACE(::testing::Message() << i << "/" << count << ": "
851 << " handle=0x" << std::hex << std::setw(8) << std::setfill('0')
852 << s.sensorHandle << std::dec
853 << " type=" << static_cast<int>(s.type)
854 << " name=" << s.name);
855
856 // Test non-empty type string
857 EXPECT_FALSE(s.typeAsString.empty());
858
859 // Test defined type matches defined string type
860 EXPECT_NO_FATAL_FAILURE(assertTypeMatchStringType(s.type, s.typeAsString));
861
862 // Test if all sensor has name and vendor
863 EXPECT_FALSE(s.name.empty());
864 EXPECT_FALSE(s.vendor.empty());
865
866 // Test power > 0, maxRange > 0
867 EXPECT_LE(0, s.power);
868 EXPECT_LT(0, s.maxRange);
869
870 // Info type, should have no sensor
871 EXPECT_FALSE(
872 s.type == SensorType::ADDITIONAL_INFO
873 || s.type == SensorType::META_DATA);
874
875 // Test fifoMax >= fifoReserved
876 EXPECT_GE(s.fifoMaxEventCount, s.fifoReservedEventCount)
877 << "max=" << s.fifoMaxEventCount << " reserved=" << s.fifoReservedEventCount;
878
879 // Test Reporting mode valid
880 EXPECT_NO_FATAL_FAILURE(assertTypeMatchReportMode(s.type, extractReportMode(s.flags)));
881
882 // Test min max are in the right order
883 EXPECT_LE(s.minDelay, s.maxDelay);
884 // Test min/max delay matches reporting mode
885 EXPECT_NO_FATAL_FAILURE(
886 assertDelayMatchReportMode(s.minDelay, s.maxDelay, extractReportMode(s.flags)));
887 }
888 });
889 }
890
891 // Test if sensor list returned is valid
TEST_F(SensorsHidlTest,SetOperationMode)892 TEST_F(SensorsHidlTest, SetOperationMode) {
893 std::vector<SensorInfo> sensorList = getSensorsList();
894
895 bool needOperationModeSupport =
896 std::any_of(sensorList.begin(), sensorList.end(),
897 [] (const auto& s) {
898 return (s.flags & SensorFlagBits::DATA_INJECTION) != 0;
899 });
900 if (!needOperationModeSupport) {
901 return;
902 }
903
904 ASSERT_EQ(Result::OK, S()->setOperationMode(OperationMode::NORMAL));
905 ASSERT_EQ(Result::OK, S()->setOperationMode(OperationMode::DATA_INJECTION));
906 ASSERT_EQ(Result::OK, S()->setOperationMode(OperationMode::NORMAL));
907 }
908
909 // Test if sensor list returned is valid
TEST_F(SensorsHidlTest,InjectSensorEventData)910 TEST_F(SensorsHidlTest, InjectSensorEventData) {
911 std::vector<SensorInfo> sensorList = getSensorsList();
912 std::vector<SensorInfo> sensorSupportInjection;
913
914 bool needOperationModeSupport =
915 std::any_of(sensorList.begin(), sensorList.end(),
916 [&sensorSupportInjection] (const auto& s) {
917 bool ret = (s.flags & SensorFlagBits::DATA_INJECTION) != 0;
918 if (ret) {
919 sensorSupportInjection.push_back(s);
920 }
921 return ret;
922 });
923 if (!needOperationModeSupport) {
924 return;
925 }
926
927 ASSERT_EQ(Result::OK, S()->setOperationMode(OperationMode::NORMAL));
928 ASSERT_EQ(Result::OK, S()->setOperationMode(OperationMode::DATA_INJECTION));
929
930 for (const auto &s : sensorSupportInjection) {
931 switch (s.type) {
932 case SensorType::ACCELEROMETER:
933 case SensorType::GYROSCOPE:
934 case SensorType::MAGNETIC_FIELD: {
935 usleep(100000); // sleep 100ms
936
937 Event dummy;
938 dummy.timestamp = android::elapsedRealtimeNano();
939 dummy.sensorType = s.type;
940 dummy.sensorHandle = s.sensorHandle;
941 Vec3 v = {1, 2, 3, SensorStatus::ACCURACY_HIGH};
942 dummy.u.vec3 = v;
943
944 EXPECT_EQ(Result::OK, S()->injectSensorData(dummy));
945 break;
946 }
947 default:
948 break;
949 }
950 }
951 ASSERT_EQ(Result::OK, S()->setOperationMode(OperationMode::NORMAL));
952 }
953
testStreamingOperation(SensorType type,std::chrono::nanoseconds samplingPeriod,std::chrono::seconds duration,const SensorEventsChecker & checker)954 void SensorsHidlTest::testStreamingOperation(SensorType type,
955 std::chrono::nanoseconds samplingPeriod,
956 std::chrono::seconds duration,
957 const SensorEventsChecker &checker) {
958 std::vector<Event> events;
959 std::vector<Event> sensorEvents;
960
961 const int64_t samplingPeriodInNs = samplingPeriod.count();
962 const int64_t batchingPeriodInNs = 0; // no batching
963 const useconds_t minTimeUs = std::chrono::microseconds(duration).count();
964 const size_t minNEvent = duration / samplingPeriod;
965
966 SensorInfo sensor = defaultSensorByType(type);
967
968 if (!isValidType(sensor.type)) {
969 // no default sensor of this type
970 return;
971 }
972
973 if (std::chrono::microseconds(sensor.minDelay) > samplingPeriod) {
974 // rate not supported
975 return;
976 }
977
978 int32_t handle = sensor.sensorHandle;
979
980 ASSERT_EQ(batch(handle, samplingPeriodInNs, batchingPeriodInNs), Result::OK);
981 ASSERT_EQ(activate(handle, 1), Result::OK);
982 events = collectEvents(minTimeUs, minNEvent, true /*clearBeforeStart*/);
983 ASSERT_EQ(activate(handle, 0), Result::OK);
984
985 ALOGI("Collected %zu samples", events.size());
986
987 ASSERT_GT(events.size(), 0u);
988
989 bool handleMismatchReported = false;
990 bool metaSensorTypeErrorReported = false;
991 for (auto & e : events) {
992 if (e.sensorType == type) {
993 // avoid generating hundreds of error
994 if (!handleMismatchReported) {
995 EXPECT_EQ(e.sensorHandle, handle)
996 << (handleMismatchReported = true,
997 "Event of the same type must come from the sensor registered");
998 }
999 sensorEvents.push_back(e);
1000 } else {
1001 // avoid generating hundreds of error
1002 if (!metaSensorTypeErrorReported) {
1003 EXPECT_TRUE(isMetaSensorType(e.sensorType))
1004 << (metaSensorTypeErrorReported = true,
1005 "Only meta types are allowed besides the type registered");
1006 }
1007 }
1008 }
1009
1010 std::string s;
1011 EXPECT_TRUE(checker.check(sensorEvents, &s)) << s;
1012
1013 EXPECT_GE(sensorEvents.size(),
1014 minNEvent / 2); // make sure returned events are not all meta
1015 }
1016
1017 // Test if sensor hal can do UI speed accelerometer streaming properly
TEST_F(SensorsHidlTest,AccelerometerStreamingOperationSlow)1018 TEST_F(SensorsHidlTest, AccelerometerStreamingOperationSlow) {
1019 testStreamingOperation(SensorType::ACCELEROMETER,
1020 std::chrono::milliseconds(200),
1021 std::chrono::seconds(5),
1022 sAccelNormChecker);
1023 }
1024
1025 // Test if sensor hal can do normal speed accelerometer streaming properly
TEST_F(SensorsHidlTest,AccelerometerStreamingOperationNormal)1026 TEST_F(SensorsHidlTest, AccelerometerStreamingOperationNormal) {
1027 testStreamingOperation(SensorType::ACCELEROMETER,
1028 std::chrono::milliseconds(20),
1029 std::chrono::seconds(5),
1030 sAccelNormChecker);
1031 }
1032
1033 // Test if sensor hal can do game speed accelerometer streaming properly
TEST_F(SensorsHidlTest,AccelerometerStreamingOperationFast)1034 TEST_F(SensorsHidlTest, AccelerometerStreamingOperationFast) {
1035 testStreamingOperation(SensorType::ACCELEROMETER,
1036 std::chrono::milliseconds(5),
1037 std::chrono::seconds(5),
1038 sAccelNormChecker);
1039 }
1040
1041 // Test if sensor hal can do UI speed gyroscope streaming properly
TEST_F(SensorsHidlTest,GyroscopeStreamingOperationSlow)1042 TEST_F(SensorsHidlTest, GyroscopeStreamingOperationSlow) {
1043 testStreamingOperation(SensorType::GYROSCOPE,
1044 std::chrono::milliseconds(200),
1045 std::chrono::seconds(5),
1046 sGyroNormChecker);
1047 }
1048
1049 // Test if sensor hal can do normal speed gyroscope streaming properly
TEST_F(SensorsHidlTest,GyroscopeStreamingOperationNormal)1050 TEST_F(SensorsHidlTest, GyroscopeStreamingOperationNormal) {
1051 testStreamingOperation(SensorType::GYROSCOPE,
1052 std::chrono::milliseconds(20),
1053 std::chrono::seconds(5),
1054 sGyroNormChecker);
1055 }
1056
1057 // Test if sensor hal can do game speed gyroscope streaming properly
TEST_F(SensorsHidlTest,GyroscopeStreamingOperationFast)1058 TEST_F(SensorsHidlTest, GyroscopeStreamingOperationFast) {
1059 testStreamingOperation(SensorType::GYROSCOPE,
1060 std::chrono::milliseconds(5),
1061 std::chrono::seconds(5),
1062 sGyroNormChecker);
1063 }
1064
1065 // Test if sensor hal can do UI speed magnetometer streaming properly
TEST_F(SensorsHidlTest,MagnetometerStreamingOperationSlow)1066 TEST_F(SensorsHidlTest, MagnetometerStreamingOperationSlow) {
1067 testStreamingOperation(SensorType::MAGNETIC_FIELD,
1068 std::chrono::milliseconds(200),
1069 std::chrono::seconds(5),
1070 NullChecker());
1071 }
1072
1073 // Test if sensor hal can do normal speed magnetometer streaming properly
TEST_F(SensorsHidlTest,MagnetometerStreamingOperationNormal)1074 TEST_F(SensorsHidlTest, MagnetometerStreamingOperationNormal) {
1075 testStreamingOperation(SensorType::MAGNETIC_FIELD,
1076 std::chrono::milliseconds(20),
1077 std::chrono::seconds(5),
1078 NullChecker());
1079 }
1080
1081 // Test if sensor hal can do game speed magnetometer streaming properly
TEST_F(SensorsHidlTest,MagnetometerStreamingOperationFast)1082 TEST_F(SensorsHidlTest, MagnetometerStreamingOperationFast) {
1083 testStreamingOperation(SensorType::MAGNETIC_FIELD,
1084 std::chrono::milliseconds(5),
1085 std::chrono::seconds(5),
1086 NullChecker());
1087 }
1088
testSamplingRateHotSwitchOperation(SensorType type,bool fastToSlow)1089 void SensorsHidlTest::testSamplingRateHotSwitchOperation(SensorType type, bool fastToSlow) {
1090 std::vector<Event> events1, events2;
1091
1092 constexpr int64_t batchingPeriodInNs = 0; // no batching
1093 constexpr int64_t collectionTimeoutUs = 60000000; // 60s
1094 constexpr size_t minNEvent = 50;
1095
1096 SensorInfo sensor = defaultSensorByType(type);
1097
1098 if (!isValidType(sensor.type)) {
1099 // no default sensor of this type
1100 return;
1101 }
1102
1103 int32_t handle = sensor.sensorHandle;
1104 int64_t minSamplingPeriodInNs = sensor.minDelay * 1000ll;
1105 int64_t maxSamplingPeriodInNs = sensor.maxDelay * 1000ll;
1106
1107 if (minSamplingPeriodInNs == maxSamplingPeriodInNs) {
1108 // only support single rate
1109 return;
1110 }
1111
1112 int64_t firstCollectionPeriod = fastToSlow ? minSamplingPeriodInNs : maxSamplingPeriodInNs;
1113 int64_t secondCollectionPeriod = !fastToSlow ? minSamplingPeriodInNs : maxSamplingPeriodInNs;
1114
1115 // first collection
1116 ASSERT_EQ(batch(handle, firstCollectionPeriod, batchingPeriodInNs), Result::OK);
1117 ASSERT_EQ(activate(handle, 1), Result::OK);
1118
1119 usleep(500000); // sleep 0.5 sec to wait for change rate to happen
1120 events1 = collectEvents(collectionTimeoutUs, minNEvent);
1121
1122 // second collection, without stop sensor
1123 ASSERT_EQ(batch(handle, secondCollectionPeriod, batchingPeriodInNs), Result::OK);
1124
1125 usleep(500000); // sleep 0.5 sec to wait for change rate to happen
1126 events2 = collectEvents(collectionTimeoutUs, minNEvent);
1127
1128 // end of collection, stop sensor
1129 ASSERT_EQ(activate(handle, 0), Result::OK);
1130
1131 ALOGI("Collected %zu fast samples and %zu slow samples", events1.size(), events2.size());
1132
1133 ASSERT_GT(events1.size(), 0u);
1134 ASSERT_GT(events2.size(), 0u);
1135
1136 int64_t minDelayAverageInterval, maxDelayAverageInterval;
1137 std::vector<Event> &minDelayEvents(fastToSlow ? events1 : events2);
1138 std::vector<Event> &maxDelayEvents(fastToSlow ? events2 : events1);
1139
1140 size_t nEvent = 0;
1141 int64_t prevTimestamp = -1;
1142 int64_t timestampInterval = 0;
1143 for (auto & e : minDelayEvents) {
1144 if (e.sensorType == type) {
1145 ASSERT_EQ(e.sensorHandle, handle);
1146 if (prevTimestamp > 0) {
1147 timestampInterval += e.timestamp - prevTimestamp;
1148 }
1149 prevTimestamp = e.timestamp;
1150 ++ nEvent;
1151 }
1152 }
1153 ASSERT_GT(nEvent, 2u);
1154 minDelayAverageInterval = timestampInterval / (nEvent - 1);
1155
1156 nEvent = 0;
1157 prevTimestamp = -1;
1158 timestampInterval = 0;
1159 for (auto & e : maxDelayEvents) {
1160 if (e.sensorType == type) {
1161 ASSERT_EQ(e.sensorHandle, handle);
1162 if (prevTimestamp > 0) {
1163 timestampInterval += e.timestamp - prevTimestamp;
1164 }
1165 prevTimestamp = e.timestamp;
1166 ++ nEvent;
1167 }
1168 }
1169 ASSERT_GT(nEvent, 2u);
1170 maxDelayAverageInterval = timestampInterval / (nEvent - 1);
1171
1172 // change of rate is significant.
1173 ALOGI("min/maxDelayAverageInterval = %" PRId64 " %" PRId64,
1174 minDelayAverageInterval, maxDelayAverageInterval);
1175 EXPECT_GT((maxDelayAverageInterval - minDelayAverageInterval), minDelayAverageInterval / 10);
1176
1177 // fastest rate sampling time is close to spec
1178 EXPECT_LT(std::abs(minDelayAverageInterval - minSamplingPeriodInNs),
1179 minSamplingPeriodInNs / 10);
1180
1181 // slowest rate sampling time is close to spec
1182 EXPECT_LT(std::abs(maxDelayAverageInterval - maxSamplingPeriodInNs),
1183 maxSamplingPeriodInNs / 10);
1184 }
1185
1186 // Test if sensor hal can do accelerometer sampling rate switch properly when sensor is active
TEST_F(SensorsHidlTest,AccelerometerSamplingPeriodHotSwitchOperation)1187 TEST_F(SensorsHidlTest, AccelerometerSamplingPeriodHotSwitchOperation) {
1188 testSamplingRateHotSwitchOperation(SensorType::ACCELEROMETER);
1189 testSamplingRateHotSwitchOperation(SensorType::ACCELEROMETER, false /*fastToSlow*/);
1190 }
1191
1192 // Test if sensor hal can do gyroscope sampling rate switch properly when sensor is active
TEST_F(SensorsHidlTest,GyroscopeSamplingPeriodHotSwitchOperation)1193 TEST_F(SensorsHidlTest, GyroscopeSamplingPeriodHotSwitchOperation) {
1194 testSamplingRateHotSwitchOperation(SensorType::GYROSCOPE);
1195 testSamplingRateHotSwitchOperation(SensorType::GYROSCOPE, false /*fastToSlow*/);
1196 }
1197
1198 // Test if sensor hal can do magnetometer sampling rate switch properly when sensor is active
TEST_F(SensorsHidlTest,MagnetometerSamplingPeriodHotSwitchOperation)1199 TEST_F(SensorsHidlTest, MagnetometerSamplingPeriodHotSwitchOperation) {
1200 testSamplingRateHotSwitchOperation(SensorType::MAGNETIC_FIELD);
1201 testSamplingRateHotSwitchOperation(SensorType::MAGNETIC_FIELD, false /*fastToSlow*/);
1202 }
1203
testBatchingOperation(SensorType type)1204 void SensorsHidlTest::testBatchingOperation(SensorType type) {
1205 std::vector<Event> events;
1206
1207 constexpr int64_t maxBatchingTestTimeNs = 30ull * 1000 * 1000 * 1000;
1208 constexpr int64_t oneSecondInNs = 1ull * 1000 * 1000 * 1000;
1209
1210 SensorInfo sensor = defaultSensorByType(type);
1211
1212 if (!isValidType(sensor.type)) {
1213 // no default sensor of this type
1214 return;
1215 }
1216
1217 int32_t handle = sensor.sensorHandle;
1218 int64_t minSamplingPeriodInNs = sensor.minDelay * 1000ll;
1219 uint32_t minFifoCount = sensor.fifoReservedEventCount;
1220 int64_t batchingPeriodInNs = minFifoCount * minSamplingPeriodInNs;
1221
1222 if (batchingPeriodInNs < oneSecondInNs) {
1223 // batching size too small to test reliably
1224 return;
1225 }
1226
1227 batchingPeriodInNs = std::min(batchingPeriodInNs, maxBatchingTestTimeNs);
1228
1229 ALOGI("Test batching for %d ms", (int)(batchingPeriodInNs / 1000 / 1000));
1230
1231 int64_t allowedBatchDeliverTimeNs =
1232 std::max(oneSecondInNs, batchingPeriodInNs / 10);
1233
1234 ASSERT_EQ(batch(handle, minSamplingPeriodInNs, INT64_MAX), Result::OK);
1235 ASSERT_EQ(activate(handle, 1), Result::OK);
1236
1237 usleep(500000); // sleep 0.5 sec to wait for initialization
1238 ASSERT_EQ(flush(handle), Result::OK);
1239
1240 // wait for 80% of the reserved batching period
1241 // there should not be any significant amount of events
1242 // since collection is not enabled all events will go down the drain
1243 usleep(batchingPeriodInNs / 1000 * 8 / 10);
1244
1245 SensorsHidlEnvironment::Instance()->setCollection(true);
1246 // clean existing collections
1247 collectEvents(0 /*timeLimitUs*/, 0/*nEventLimit*/,
1248 true /*clearBeforeStart*/, false /*change collection*/);
1249
1250 // 0.8 + 0.2 times the batching period
1251 usleep(batchingPeriodInNs / 1000 * 8 / 10);
1252 ASSERT_EQ(flush(handle), Result::OK);
1253
1254 // plus some time for the event to deliver
1255 events = collectEvents(allowedBatchDeliverTimeNs / 1000,
1256 minFifoCount, false /*clearBeforeStart*/, false /*change collection*/);
1257
1258 SensorsHidlEnvironment::Instance()->setCollection(false);
1259 ASSERT_EQ(activate(handle, 0), Result::OK);
1260
1261 size_t nEvent = 0;
1262 for (auto & e : events) {
1263 if (e.sensorType == type && e.sensorHandle == handle) {
1264 ++ nEvent;
1265 }
1266 }
1267
1268 // at least reach 90% of advertised capacity
1269 ASSERT_GT(nEvent, (size_t)(minFifoCount * 9 / 10));
1270 }
1271
1272 // Test if sensor hal can do accelerometer batching properly
TEST_F(SensorsHidlTest,AccelerometerBatchingOperation)1273 TEST_F(SensorsHidlTest, AccelerometerBatchingOperation) {
1274 testBatchingOperation(SensorType::ACCELEROMETER);
1275 }
1276
1277 // Test if sensor hal can do gyroscope batching properly
TEST_F(SensorsHidlTest,GyroscopeBatchingOperation)1278 TEST_F(SensorsHidlTest, GyroscopeBatchingOperation) {
1279 testBatchingOperation(SensorType::GYROSCOPE);
1280 }
1281
1282 // Test if sensor hal can do magnetometer batching properly
TEST_F(SensorsHidlTest,MagnetometerBatchingOperation)1283 TEST_F(SensorsHidlTest, MagnetometerBatchingOperation) {
1284 testBatchingOperation(SensorType::MAGNETIC_FIELD);
1285 }
1286
testDirectReportOperation(SensorType type,SharedMemType memType,RateLevel rate,const SensorEventsChecker & checker)1287 void SensorsHidlTest::testDirectReportOperation(
1288 SensorType type, SharedMemType memType, RateLevel rate, const SensorEventsChecker &checker) {
1289 constexpr size_t kEventSize = static_cast<size_t>(SensorsEventFormatOffset::TOTAL_LENGTH);
1290 constexpr size_t kNEvent = 4096;
1291 constexpr size_t kMemSize = kEventSize * kNEvent;
1292
1293 constexpr float kNormalNominal = 50;
1294 constexpr float kFastNominal = 200;
1295 constexpr float kVeryFastNominal = 800;
1296
1297 constexpr float kNominalTestTimeSec = 1.f;
1298 constexpr float kMaxTestTimeSec = kNominalTestTimeSec + 0.5f; // 0.5 second for initialization
1299
1300 SensorInfo sensor = defaultSensorByType(type);
1301
1302 if (!isValidType(sensor.type)) {
1303 // no default sensor of this type
1304 return;
1305 }
1306
1307 if (!isDirectReportRateSupported(sensor, rate)) {
1308 return;
1309 }
1310
1311 if (!isDirectChannelTypeSupported(sensor, memType)) {
1312 return;
1313 }
1314
1315 std::unique_ptr<SensorsTestSharedMemory>
1316 mem(SensorsTestSharedMemory::create(memType, kMemSize));
1317 ASSERT_NE(mem, nullptr);
1318
1319 char* buffer = mem->getBuffer();
1320 // fill memory with data
1321 for (size_t i = 0; i < kMemSize; ++i) {
1322 buffer[i] = '\xcc';
1323 }
1324
1325 int32_t channelHandle;
1326 registerDirectChannel(mem->getSharedMemInfo(),
1327 [&channelHandle] (auto result, auto channelHandle_) {
1328 ASSERT_EQ(result, Result::OK);
1329 channelHandle = channelHandle_;
1330 });
1331
1332 // check memory is zeroed
1333 for (size_t i = 0; i < kMemSize; ++i) {
1334 ASSERT_EQ(buffer[i], '\0');
1335 }
1336
1337 int32_t eventToken;
1338 configDirectReport(sensor.sensorHandle, channelHandle, rate,
1339 [&eventToken] (auto result, auto token) {
1340 ASSERT_EQ(result, Result::OK);
1341 eventToken = token;
1342 });
1343
1344 usleep(static_cast<useconds_t>(kMaxTestTimeSec * 1e6f));
1345 auto events = mem->parseEvents();
1346
1347 // find norminal rate
1348 float nominalFreq = 0.f;
1349 switch (rate) {
1350 case RateLevel::NORMAL:
1351 nominalFreq = kNormalNominal;
1352 break;
1353 case RateLevel::FAST:
1354 nominalFreq = kFastNominal;
1355 break;
1356 case RateLevel::VERY_FAST:
1357 nominalFreq = kVeryFastNominal;
1358 break;
1359 case RateLevel::STOP:
1360 FAIL();
1361 }
1362
1363 // allowed to be between 55% and 220% of nominal freq
1364 ASSERT_GT(events.size(), static_cast<size_t>(nominalFreq * 0.55f * kNominalTestTimeSec));
1365 ASSERT_LT(events.size(), static_cast<size_t>(nominalFreq * 2.2f * kMaxTestTimeSec));
1366
1367 int64_t lastTimestamp = 0;
1368 bool typeErrorReported = false;
1369 bool tokenErrorReported = false;
1370 bool timestampErrorReported = false;
1371 std::vector<Event> sensorEvents;
1372 for (auto &e : events) {
1373 if (!tokenErrorReported) {
1374 EXPECT_EQ(eventToken, e.sensorHandle)
1375 << (tokenErrorReported = true,
1376 "Event token does not match that retured from configDirectReport");
1377 }
1378
1379 if (isMetaSensorType(e.sensorType)) {
1380 continue;
1381 }
1382 sensorEvents.push_back(e);
1383
1384 if (!typeErrorReported) {
1385 EXPECT_EQ(type, e.sensorType)
1386 << (typeErrorReported = true,
1387 "Type in event does not match type of sensor registered.");
1388 }
1389 if (!timestampErrorReported) {
1390 EXPECT_GT(e.timestamp, lastTimestamp)
1391 << (timestampErrorReported = true, "Timestamp not monotonically increasing");
1392 }
1393 lastTimestamp = e.timestamp;
1394 }
1395
1396 std::string s;
1397 EXPECT_TRUE(checker.check(sensorEvents, &s)) << s;
1398
1399 // stop sensor and unregister channel
1400 configDirectReport(sensor.sensorHandle, channelHandle, RateLevel::STOP,
1401 [](auto result, auto) { EXPECT_EQ(result, Result::OK); });
1402 EXPECT_EQ(unregisterDirectChannel(channelHandle), Result::OK);
1403 }
1404
1405 // Test sensor event direct report with ashmem for accel sensor at normal rate
TEST_F(SensorsHidlTest,AccelerometerAshmemDirectReportOperationNormal)1406 TEST_F(SensorsHidlTest, AccelerometerAshmemDirectReportOperationNormal) {
1407 testDirectReportOperation(SensorType::ACCELEROMETER, SharedMemType::ASHMEM, RateLevel::NORMAL,
1408 sAccelNormChecker);
1409 }
1410
1411 // Test sensor event direct report with ashmem for accel sensor at fast rate
TEST_F(SensorsHidlTest,AccelerometerAshmemDirectReportOperationFast)1412 TEST_F(SensorsHidlTest, AccelerometerAshmemDirectReportOperationFast) {
1413 testDirectReportOperation(SensorType::ACCELEROMETER, SharedMemType::ASHMEM, RateLevel::FAST,
1414 sAccelNormChecker);
1415 }
1416
1417 // Test sensor event direct report with ashmem for accel sensor at very fast rate
TEST_F(SensorsHidlTest,AccelerometerAshmemDirectReportOperationVeryFast)1418 TEST_F(SensorsHidlTest, AccelerometerAshmemDirectReportOperationVeryFast) {
1419 testDirectReportOperation(SensorType::ACCELEROMETER, SharedMemType::ASHMEM, RateLevel::VERY_FAST,
1420 sAccelNormChecker);
1421 }
1422
1423 // Test sensor event direct report with ashmem for gyro sensor at normal rate
TEST_F(SensorsHidlTest,GyroscopeAshmemDirectReportOperationNormal)1424 TEST_F(SensorsHidlTest, GyroscopeAshmemDirectReportOperationNormal) {
1425 testDirectReportOperation(SensorType::GYROSCOPE, SharedMemType::ASHMEM, RateLevel::NORMAL,
1426 sGyroNormChecker);
1427 }
1428
1429 // Test sensor event direct report with ashmem for gyro sensor at fast rate
TEST_F(SensorsHidlTest,GyroscopeAshmemDirectReportOperationFast)1430 TEST_F(SensorsHidlTest, GyroscopeAshmemDirectReportOperationFast) {
1431 testDirectReportOperation(SensorType::GYROSCOPE, SharedMemType::ASHMEM, RateLevel::FAST,
1432 sGyroNormChecker);
1433 }
1434
1435 // Test sensor event direct report with ashmem for gyro sensor at very fast rate
TEST_F(SensorsHidlTest,GyroscopeAshmemDirectReportOperationVeryFast)1436 TEST_F(SensorsHidlTest, GyroscopeAshmemDirectReportOperationVeryFast) {
1437 testDirectReportOperation(SensorType::GYROSCOPE, SharedMemType::ASHMEM, RateLevel::VERY_FAST,
1438 sGyroNormChecker);
1439 }
1440
1441 // Test sensor event direct report with ashmem for mag sensor at normal rate
TEST_F(SensorsHidlTest,MagnetometerAshmemDirectReportOperationNormal)1442 TEST_F(SensorsHidlTest, MagnetometerAshmemDirectReportOperationNormal) {
1443 testDirectReportOperation(SensorType::MAGNETIC_FIELD, SharedMemType::ASHMEM, RateLevel::NORMAL,
1444 NullChecker());
1445 }
1446
1447 // Test sensor event direct report with ashmem for mag sensor at fast rate
TEST_F(SensorsHidlTest,MagnetometerAshmemDirectReportOperationFast)1448 TEST_F(SensorsHidlTest, MagnetometerAshmemDirectReportOperationFast) {
1449 testDirectReportOperation(SensorType::MAGNETIC_FIELD, SharedMemType::ASHMEM, RateLevel::FAST,
1450 NullChecker());
1451 }
1452
1453 // Test sensor event direct report with ashmem for mag sensor at very fast rate
TEST_F(SensorsHidlTest,MagnetometerAshmemDirectReportOperationVeryFast)1454 TEST_F(SensorsHidlTest, MagnetometerAshmemDirectReportOperationVeryFast) {
1455 testDirectReportOperation(
1456 SensorType::MAGNETIC_FIELD, SharedMemType::ASHMEM, RateLevel::VERY_FAST, NullChecker());
1457 }
1458
1459 // Test sensor event direct report with gralloc for accel sensor at normal rate
TEST_F(SensorsHidlTest,AccelerometerGrallocDirectReportOperationNormal)1460 TEST_F(SensorsHidlTest, AccelerometerGrallocDirectReportOperationNormal) {
1461 testDirectReportOperation(SensorType::ACCELEROMETER, SharedMemType::GRALLOC, RateLevel::NORMAL,
1462 sAccelNormChecker);
1463 }
1464
1465 // Test sensor event direct report with gralloc for accel sensor at fast rate
TEST_F(SensorsHidlTest,AccelerometerGrallocDirectReportOperationFast)1466 TEST_F(SensorsHidlTest, AccelerometerGrallocDirectReportOperationFast) {
1467 testDirectReportOperation(SensorType::ACCELEROMETER, SharedMemType::GRALLOC, RateLevel::FAST,
1468 sAccelNormChecker);
1469 }
1470
1471 // Test sensor event direct report with gralloc for accel sensor at very fast rate
TEST_F(SensorsHidlTest,AccelerometerGrallocDirectReportOperationVeryFast)1472 TEST_F(SensorsHidlTest, AccelerometerGrallocDirectReportOperationVeryFast) {
1473 testDirectReportOperation(SensorType::ACCELEROMETER, SharedMemType::GRALLOC, RateLevel::VERY_FAST,
1474 sAccelNormChecker);
1475 }
1476
1477 // Test sensor event direct report with gralloc for gyro sensor at normal rate
TEST_F(SensorsHidlTest,GyroscopeGrallocDirectReportOperationNormal)1478 TEST_F(SensorsHidlTest, GyroscopeGrallocDirectReportOperationNormal) {
1479 testDirectReportOperation(SensorType::GYROSCOPE, SharedMemType::GRALLOC, RateLevel::NORMAL,
1480 sGyroNormChecker);
1481 }
1482
1483 // Test sensor event direct report with gralloc for gyro sensor at fast rate
TEST_F(SensorsHidlTest,GyroscopeGrallocDirectReportOperationFast)1484 TEST_F(SensorsHidlTest, GyroscopeGrallocDirectReportOperationFast) {
1485 testDirectReportOperation(SensorType::GYROSCOPE, SharedMemType::GRALLOC, RateLevel::FAST,
1486 sGyroNormChecker);
1487 }
1488
1489 // Test sensor event direct report with gralloc for gyro sensor at very fast rate
TEST_F(SensorsHidlTest,GyroscopeGrallocDirectReportOperationVeryFast)1490 TEST_F(SensorsHidlTest, GyroscopeGrallocDirectReportOperationVeryFast) {
1491 testDirectReportOperation(SensorType::GYROSCOPE, SharedMemType::GRALLOC, RateLevel::VERY_FAST,
1492 sGyroNormChecker);
1493 }
1494
1495 // Test sensor event direct report with gralloc for mag sensor at normal rate
TEST_F(SensorsHidlTest,MagnetometerGrallocDirectReportOperationNormal)1496 TEST_F(SensorsHidlTest, MagnetometerGrallocDirectReportOperationNormal) {
1497 testDirectReportOperation(SensorType::MAGNETIC_FIELD, SharedMemType::GRALLOC, RateLevel::NORMAL,
1498 NullChecker());
1499 }
1500
1501 // Test sensor event direct report with gralloc for mag sensor at fast rate
TEST_F(SensorsHidlTest,MagnetometerGrallocDirectReportOperationFast)1502 TEST_F(SensorsHidlTest, MagnetometerGrallocDirectReportOperationFast) {
1503 testDirectReportOperation(SensorType::MAGNETIC_FIELD, SharedMemType::GRALLOC, RateLevel::FAST,
1504 NullChecker());
1505 }
1506
1507 // Test sensor event direct report with gralloc for mag sensor at very fast rate
TEST_F(SensorsHidlTest,MagnetometerGrallocDirectReportOperationVeryFast)1508 TEST_F(SensorsHidlTest, MagnetometerGrallocDirectReportOperationVeryFast) {
1509 testDirectReportOperation(
1510 SensorType::MAGNETIC_FIELD, SharedMemType::GRALLOC, RateLevel::VERY_FAST, NullChecker());
1511 }
1512
main(int argc,char ** argv)1513 int main(int argc, char **argv) {
1514 ::testing::AddGlobalTestEnvironment(SensorsHidlEnvironment::Instance());
1515 ::testing::InitGoogleTest(&argc, argv);
1516 SensorsHidlEnvironment::Instance()->init(&argc, argv);
1517 int status = RUN_ALL_TESTS();
1518 ALOGI("Test result = %d", status);
1519 return status;
1520 }
1521 // vim: set ts=2 sw=2
1522