1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <aidl/Gtest.h>
17 #include <aidl/Vintf.h>
18 #include <android/hardware/vibrator/BnVibratorCallback.h>
19 #include <android/hardware/vibrator/IVibrator.h>
20 #include <android/hardware/vibrator/IVibratorManager.h>
21 #include <binder/IServiceManager.h>
22 #include <binder/ProcessState.h>
23 
24 #include <cmath>
25 #include <future>
26 
27 using android::ProcessState;
28 using android::sp;
29 using android::String16;
30 using android::binder::Status;
31 using android::hardware::vibrator::ActivePwle;
32 using android::hardware::vibrator::BnVibratorCallback;
33 using android::hardware::vibrator::Braking;
34 using android::hardware::vibrator::BrakingPwle;
35 using android::hardware::vibrator::CompositeEffect;
36 using android::hardware::vibrator::CompositePrimitive;
37 using android::hardware::vibrator::Effect;
38 using android::hardware::vibrator::EffectStrength;
39 using android::hardware::vibrator::IVibrator;
40 using android::hardware::vibrator::IVibratorManager;
41 using android::hardware::vibrator::PrimitivePwle;
42 using std::chrono::high_resolution_clock;
43 
44 using namespace ::std::chrono_literals;
45 
46 const std::vector<Effect> kEffects{android::enum_range<Effect>().begin(),
47                                    android::enum_range<Effect>().end()};
48 const std::vector<EffectStrength> kEffectStrengths{android::enum_range<EffectStrength>().begin(),
49                                                    android::enum_range<EffectStrength>().end()};
50 
51 const std::vector<Effect> kInvalidEffects = {
52     static_cast<Effect>(static_cast<int32_t>(kEffects.front()) - 1),
53     static_cast<Effect>(static_cast<int32_t>(kEffects.back()) + 1),
54 };
55 
56 const std::vector<EffectStrength> kInvalidEffectStrengths = {
57     static_cast<EffectStrength>(static_cast<int8_t>(kEffectStrengths.front()) - 1),
58     static_cast<EffectStrength>(static_cast<int8_t>(kEffectStrengths.back()) + 1),
59 };
60 
61 const std::vector<CompositePrimitive> kCompositePrimitives{
62     android::enum_range<CompositePrimitive>().begin(),
63     android::enum_range<CompositePrimitive>().end()};
64 
65 const std::vector<CompositePrimitive> kRequiredPrimitives = {
66         CompositePrimitive::CLICK,      CompositePrimitive::LIGHT_TICK,
67         CompositePrimitive::QUICK_RISE, CompositePrimitive::SLOW_RISE,
68         CompositePrimitive::QUICK_FALL,
69 };
70 
71 const std::vector<CompositePrimitive> kInvalidPrimitives = {
72     static_cast<CompositePrimitive>(static_cast<int32_t>(kCompositePrimitives.front()) - 1),
73     static_cast<CompositePrimitive>(static_cast<int32_t>(kCompositePrimitives.back()) + 1),
74 };
75 
76 // Timeout to wait for vibration callback completion.
77 static constexpr auto VIBRATION_CALLBACK_TIMEOUT = 100ms;
78 
79 class CompletionCallback : public BnVibratorCallback {
80   public:
CompletionCallback(const std::function<void ()> & callback)81     CompletionCallback(const std::function<void()> &callback) : mCallback(callback) {}
onComplete()82     Status onComplete() override {
83         mCallback();
84         return Status::ok();
85     }
86 
87   private:
88     std::function<void()> mCallback;
89 };
90 
91 class VibratorAidl : public testing::TestWithParam<std::tuple<int32_t, int32_t>> {
92   public:
SetUp()93     virtual void SetUp() override {
94         int32_t managerIdx = std::get<0>(GetParam());
95         int32_t vibratorId = std::get<1>(GetParam());
96         auto managerAidlNames = android::getAidlHalInstanceNames(IVibratorManager::descriptor);
97 
98         if (managerIdx < 0) {
99             // Testing a unmanaged vibrator, using vibratorId as index from registered HALs
100             auto vibratorAidlNames = android::getAidlHalInstanceNames(IVibrator::descriptor);
101             ASSERT_LT(vibratorId, vibratorAidlNames.size());
102             auto vibratorName = String16(vibratorAidlNames[vibratorId].c_str());
103             vibrator = android::waitForDeclaredService<IVibrator>(vibratorName);
104         } else {
105             // Testing a managed vibrator, using vibratorId to retrieve it from the manager
106             ASSERT_LT(managerIdx, managerAidlNames.size());
107             auto managerName = String16(managerAidlNames[managerIdx].c_str());
108             auto vibratorManager = android::waitForDeclaredService<IVibratorManager>(managerName);
109             auto vibratorResult = vibratorManager->getVibrator(vibratorId, &vibrator);
110             ASSERT_TRUE(vibratorResult.isOk());
111         }
112 
113         ASSERT_NE(vibrator, nullptr);
114         ASSERT_TRUE(vibrator->getCapabilities(&capabilities).isOk());
115     }
116 
TearDown()117     virtual void TearDown() override {
118         // Reset vibrator state between tests.
119         EXPECT_TRUE(vibrator->off().isOk());
120     }
121 
122     sp<IVibrator> vibrator;
123     int32_t capabilities;
124 };
125 
isUnknownOrUnsupported(Status status)126 inline bool isUnknownOrUnsupported(Status status) {
127     return status.exceptionCode() == Status::EX_UNSUPPORTED_OPERATION ||
128            status.transactionError() == android::UNKNOWN_TRANSACTION;
129 }
130 
getResonantFrequencyHz(sp<IVibrator> vibrator,int32_t capabilities)131 static float getResonantFrequencyHz(sp<IVibrator> vibrator, int32_t capabilities) {
132     float resonantFrequencyHz;
133     Status status = vibrator->getResonantFrequency(&resonantFrequencyHz);
134     if (capabilities & IVibrator::CAP_GET_RESONANT_FREQUENCY) {
135         EXPECT_GT(resonantFrequencyHz, 0);
136         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
137     } else {
138         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
139     }
140     return resonantFrequencyHz;
141 }
142 
getFrequencyResolutionHz(sp<IVibrator> vibrator,int32_t capabilities)143 static float getFrequencyResolutionHz(sp<IVibrator> vibrator, int32_t capabilities) {
144     float freqResolutionHz;
145     Status status = vibrator->getFrequencyResolution(&freqResolutionHz);
146     if (capabilities & IVibrator::CAP_FREQUENCY_CONTROL) {
147         EXPECT_GT(freqResolutionHz, 0);
148         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
149     } else {
150         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
151     }
152     return freqResolutionHz;
153 }
154 
getFrequencyMinimumHz(sp<IVibrator> vibrator,int32_t capabilities)155 static float getFrequencyMinimumHz(sp<IVibrator> vibrator, int32_t capabilities) {
156     float freqMinimumHz;
157     Status status = vibrator->getFrequencyMinimum(&freqMinimumHz);
158     if (capabilities & IVibrator::CAP_FREQUENCY_CONTROL) {
159         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
160 
161         float resonantFrequencyHz = getResonantFrequencyHz(vibrator, capabilities);
162 
163         EXPECT_GT(freqMinimumHz, 0);
164         EXPECT_LE(freqMinimumHz, resonantFrequencyHz);
165     } else {
166         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
167     }
168     return freqMinimumHz;
169 }
170 
getFrequencyMaximumHz(sp<IVibrator> vibrator,int32_t capabilities)171 static float getFrequencyMaximumHz(sp<IVibrator> vibrator, int32_t capabilities) {
172     std::vector<float> bandwidthAmplitudeMap;
173     Status status = vibrator->getBandwidthAmplitudeMap(&bandwidthAmplitudeMap);
174     if (capabilities & IVibrator::CAP_FREQUENCY_CONTROL) {
175         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
176     } else {
177         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
178     }
179 
180     float freqMaximumHz = ((bandwidthAmplitudeMap.size() - 1) *
181                            getFrequencyResolutionHz(vibrator, capabilities)) +
182                           getFrequencyMinimumHz(vibrator, capabilities);
183     return freqMaximumHz;
184 }
185 
getAmplitudeMin()186 static float getAmplitudeMin() {
187     return 0.0;
188 }
189 
getAmplitudeMax()190 static float getAmplitudeMax() {
191     return 1.0;
192 }
193 
composeValidActivePwle(sp<IVibrator> vibrator,int32_t capabilities)194 static ActivePwle composeValidActivePwle(sp<IVibrator> vibrator, int32_t capabilities) {
195     float frequencyHz;
196     if (capabilities & IVibrator::CAP_GET_RESONANT_FREQUENCY) {
197         frequencyHz = getResonantFrequencyHz(vibrator, capabilities);
198     } else if (capabilities & IVibrator::CAP_FREQUENCY_CONTROL) {
199         frequencyHz = getFrequencyMinimumHz(vibrator, capabilities);
200     } else {
201         frequencyHz = 150.0;  // default value commonly used
202     }
203 
204     ActivePwle active;
205     active.startAmplitude = (getAmplitudeMin() + getAmplitudeMax()) / 2;
206     active.startFrequency = frequencyHz;
207     active.endAmplitude = (getAmplitudeMin() + getAmplitudeMax()) / 2;
208     active.endFrequency = frequencyHz;
209     vibrator->getPwlePrimitiveDurationMax(&(active.duration));
210 
211     return active;
212 }
213 
TEST_P(VibratorAidl,OnThenOffBeforeTimeout)214 TEST_P(VibratorAidl, OnThenOffBeforeTimeout) {
215     EXPECT_TRUE(vibrator->on(2000, nullptr /*callback*/).isOk());
216     sleep(1);
217     EXPECT_TRUE(vibrator->off().isOk());
218 }
219 
TEST_P(VibratorAidl,OnWithCallback)220 TEST_P(VibratorAidl, OnWithCallback) {
221     if (!(capabilities & IVibrator::CAP_ON_CALLBACK))
222         return;
223 
224     std::promise<void> completionPromise;
225     std::future<void> completionFuture{completionPromise.get_future()};
226     sp<CompletionCallback> callback =
227         new CompletionCallback([&completionPromise] { completionPromise.set_value(); });
228     uint32_t durationMs = 250;
229     auto timeout = std::chrono::milliseconds(durationMs) + VIBRATION_CALLBACK_TIMEOUT;
230     EXPECT_TRUE(vibrator->on(durationMs, callback).isOk());
231     EXPECT_EQ(completionFuture.wait_for(timeout), std::future_status::ready);
232     EXPECT_TRUE(vibrator->off().isOk());
233 }
234 
TEST_P(VibratorAidl,OnCallbackNotSupported)235 TEST_P(VibratorAidl, OnCallbackNotSupported) {
236     if (!(capabilities & IVibrator::CAP_ON_CALLBACK)) {
237         sp<CompletionCallback> callback = new CompletionCallback([] {});
238         Status status = vibrator->on(250, callback);
239         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
240     }
241 }
242 
TEST_P(VibratorAidl,ValidateEffect)243 TEST_P(VibratorAidl, ValidateEffect) {
244     std::vector<Effect> supported;
245     ASSERT_TRUE(vibrator->getSupportedEffects(&supported).isOk());
246 
247     for (Effect effect : kEffects) {
248         bool isEffectSupported =
249             std::find(supported.begin(), supported.end(), effect) != supported.end();
250 
251         for (EffectStrength strength : kEffectStrengths) {
252             int32_t lengthMs = 0;
253             Status status = vibrator->perform(effect, strength, nullptr /*callback*/, &lengthMs);
254 
255             if (isEffectSupported) {
256                 EXPECT_TRUE(status.isOk()) << toString(effect) << " " << toString(strength);
257                 EXPECT_GT(lengthMs, 0);
258                 usleep(lengthMs * 1000);
259             } else {
260                 EXPECT_TRUE(isUnknownOrUnsupported(status))
261                         << status << " " << toString(effect) << " " << toString(strength);
262             }
263         }
264     }
265 }
266 
TEST_P(VibratorAidl,ValidateEffectWithCallback)267 TEST_P(VibratorAidl, ValidateEffectWithCallback) {
268     if (!(capabilities & IVibrator::CAP_PERFORM_CALLBACK))
269         return;
270 
271     std::vector<Effect> supported;
272     ASSERT_TRUE(vibrator->getSupportedEffects(&supported).isOk());
273 
274     for (Effect effect : kEffects) {
275         bool isEffectSupported =
276             std::find(supported.begin(), supported.end(), effect) != supported.end();
277 
278         for (EffectStrength strength : kEffectStrengths) {
279             std::promise<void> completionPromise;
280             std::future<void> completionFuture{completionPromise.get_future()};
281             sp<CompletionCallback> callback =
282                 new CompletionCallback([&completionPromise] { completionPromise.set_value(); });
283             int lengthMs = 0;
284             Status status = vibrator->perform(effect, strength, callback, &lengthMs);
285 
286             if (isEffectSupported) {
287                 EXPECT_TRUE(status.isOk());
288                 EXPECT_GT(lengthMs, 0);
289             } else {
290                 EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
291             }
292 
293             if (!status.isOk())
294                 continue;
295 
296             auto timeout = std::chrono::milliseconds(lengthMs) + VIBRATION_CALLBACK_TIMEOUT;
297             EXPECT_EQ(completionFuture.wait_for(timeout), std::future_status::ready);
298 
299             EXPECT_TRUE(vibrator->off().isOk());
300         }
301     }
302 }
303 
TEST_P(VibratorAidl,ValidateEffectWithCallbackNotSupported)304 TEST_P(VibratorAidl, ValidateEffectWithCallbackNotSupported) {
305     if (capabilities & IVibrator::CAP_PERFORM_CALLBACK)
306         return;
307 
308     for (Effect effect : kEffects) {
309         for (EffectStrength strength : kEffectStrengths) {
310             sp<CompletionCallback> callback = new CompletionCallback([] {});
311             int lengthMs;
312             Status status = vibrator->perform(effect, strength, callback, &lengthMs);
313             EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
314         }
315     }
316 }
317 
TEST_P(VibratorAidl,InvalidEffectsUnsupported)318 TEST_P(VibratorAidl, InvalidEffectsUnsupported) {
319     for (Effect effect : kInvalidEffects) {
320         for (EffectStrength strength : kEffectStrengths) {
321             int32_t lengthMs;
322             Status status = vibrator->perform(effect, strength, nullptr /*callback*/, &lengthMs);
323             EXPECT_TRUE(isUnknownOrUnsupported(status))
324                     << status << toString(effect) << " " << toString(strength);
325         }
326     }
327     for (Effect effect : kEffects) {
328         for (EffectStrength strength : kInvalidEffectStrengths) {
329             int32_t lengthMs;
330             Status status = vibrator->perform(effect, strength, nullptr /*callback*/, &lengthMs);
331             EXPECT_TRUE(isUnknownOrUnsupported(status))
332                     << status << " " << toString(effect) << " " << toString(strength);
333         }
334     }
335 }
336 
TEST_P(VibratorAidl,ChangeVibrationAmplitude)337 TEST_P(VibratorAidl, ChangeVibrationAmplitude) {
338     if (capabilities & IVibrator::CAP_AMPLITUDE_CONTROL) {
339         EXPECT_EQ(Status::EX_NONE, vibrator->setAmplitude(0.1f).exceptionCode());
340         EXPECT_TRUE(vibrator->on(2000, nullptr /*callback*/).isOk());
341         EXPECT_EQ(Status::EX_NONE, vibrator->setAmplitude(0.5f).exceptionCode());
342         sleep(1);
343         EXPECT_EQ(Status::EX_NONE, vibrator->setAmplitude(1.0f).exceptionCode());
344         sleep(1);
345         EXPECT_TRUE(vibrator->off().isOk());
346     }
347 }
348 
TEST_P(VibratorAidl,AmplitudeOutsideRangeFails)349 TEST_P(VibratorAidl, AmplitudeOutsideRangeFails) {
350     if (capabilities & IVibrator::CAP_AMPLITUDE_CONTROL) {
351         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->setAmplitude(-1).exceptionCode());
352         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->setAmplitude(0).exceptionCode());
353         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->setAmplitude(1.1).exceptionCode());
354     }
355 }
356 
TEST_P(VibratorAidl,AmplitudeReturnsUnsupportedMatchingCapabilities)357 TEST_P(VibratorAidl, AmplitudeReturnsUnsupportedMatchingCapabilities) {
358     if ((capabilities & IVibrator::CAP_AMPLITUDE_CONTROL) == 0) {
359         Status status = vibrator->setAmplitude(1);
360         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
361     }
362 }
363 
TEST_P(VibratorAidl,ChangeVibrationExternalControl)364 TEST_P(VibratorAidl, ChangeVibrationExternalControl) {
365     if (capabilities & IVibrator::CAP_EXTERNAL_CONTROL) {
366         EXPECT_TRUE(vibrator->setExternalControl(true).isOk());
367         sleep(1);
368         EXPECT_TRUE(vibrator->setExternalControl(false).isOk());
369         sleep(1);
370     }
371 }
372 
TEST_P(VibratorAidl,ExternalAmplitudeControl)373 TEST_P(VibratorAidl, ExternalAmplitudeControl) {
374     const bool supportsExternalAmplitudeControl =
375         (capabilities & IVibrator::CAP_EXTERNAL_AMPLITUDE_CONTROL) > 0;
376 
377     if (capabilities & IVibrator::CAP_EXTERNAL_CONTROL) {
378         EXPECT_TRUE(vibrator->setExternalControl(true).isOk());
379 
380         Status amplitudeStatus = vibrator->setAmplitude(0.5);
381         if (supportsExternalAmplitudeControl) {
382             EXPECT_TRUE(amplitudeStatus.isOk());
383         } else {
384             EXPECT_TRUE(isUnknownOrUnsupported(amplitudeStatus)) << amplitudeStatus;
385         }
386         EXPECT_TRUE(vibrator->setExternalControl(false).isOk());
387     } else {
388         EXPECT_FALSE(supportsExternalAmplitudeControl);
389     }
390 }
391 
TEST_P(VibratorAidl,ExternalControlUnsupportedMatchingCapabilities)392 TEST_P(VibratorAidl, ExternalControlUnsupportedMatchingCapabilities) {
393     if ((capabilities & IVibrator::CAP_EXTERNAL_CONTROL) == 0) {
394         Status status = vibrator->setExternalControl(true);
395         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
396     }
397 }
398 
TEST_P(VibratorAidl,GetSupportedPrimitives)399 TEST_P(VibratorAidl, GetSupportedPrimitives) {
400     if (capabilities & IVibrator::CAP_COMPOSE_EFFECTS) {
401         std::vector<CompositePrimitive> supported;
402 
403         EXPECT_EQ(Status::EX_NONE, vibrator->getSupportedPrimitives(&supported).exceptionCode());
404 
405         for (auto primitive : kCompositePrimitives) {
406             bool isPrimitiveSupported =
407                 std::find(supported.begin(), supported.end(), primitive) != supported.end();
408             bool isPrimitiveRequired =
409                     std::find(kRequiredPrimitives.begin(), kRequiredPrimitives.end(), primitive) !=
410                     kRequiredPrimitives.end();
411 
412             EXPECT_TRUE(isPrimitiveSupported || !isPrimitiveRequired) << toString(primitive);
413         }
414     }
415 }
416 
TEST_P(VibratorAidl,GetPrimitiveDuration)417 TEST_P(VibratorAidl, GetPrimitiveDuration) {
418     if (capabilities & IVibrator::CAP_COMPOSE_EFFECTS) {
419         std::vector<CompositePrimitive> supported;
420         ASSERT_TRUE(vibrator->getSupportedPrimitives(&supported).isOk());
421 
422         for (auto primitive : kCompositePrimitives) {
423             bool isPrimitiveSupported =
424                 std::find(supported.begin(), supported.end(), primitive) != supported.end();
425             int32_t duration;
426 
427             Status status = vibrator->getPrimitiveDuration(primitive, &duration);
428 
429             if (isPrimitiveSupported) {
430                 EXPECT_EQ(Status::EX_NONE, status.exceptionCode());
431                 if (primitive != CompositePrimitive::NOOP) {
432                     ASSERT_GT(duration, 0) << toString(primitive) << " " << duration;
433                 }
434             } else {
435                 EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
436             }
437         }
438     }
439 }
440 
TEST_P(VibratorAidl,ComposeValidPrimitives)441 TEST_P(VibratorAidl, ComposeValidPrimitives) {
442     if (!(capabilities & IVibrator::CAP_COMPOSE_EFFECTS)) {
443         GTEST_SKIP() << "CAP_COMPOSE_EFFECTS not supported";
444     }
445 
446     std::vector<CompositePrimitive> supported;
447     int32_t maxDelay, maxSize;
448 
449     ASSERT_TRUE(vibrator->getSupportedPrimitives(&supported).isOk());
450     EXPECT_EQ(Status::EX_NONE, vibrator->getCompositionDelayMax(&maxDelay).exceptionCode());
451     EXPECT_EQ(Status::EX_NONE, vibrator->getCompositionSizeMax(&maxSize).exceptionCode());
452 
453     std::vector<CompositeEffect> composite;
454 
455     for (int i = 0; i < supported.size(); i++) {
456         auto primitive = supported[i];
457         float t = static_cast<float>(i + 1) / supported.size();
458         CompositeEffect effect;
459 
460         effect.delayMs = maxDelay * t;
461         effect.primitive = primitive;
462         effect.scale = t;
463 
464         if (composite.size() == maxSize) {
465             break;
466         }
467     }
468 
469     if (composite.size() != 0) {
470         EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
471         EXPECT_TRUE(vibrator->off().isOk());
472     }
473 }
474 
TEST_P(VibratorAidl,ComposeUnsupportedPrimitives)475 TEST_P(VibratorAidl, ComposeUnsupportedPrimitives) {
476     if (!(capabilities & IVibrator::CAP_COMPOSE_EFFECTS)) {
477         GTEST_SKIP() << "CAP_COMPOSE_EFFECTS not supported";
478     }
479 
480     auto unsupported = kInvalidPrimitives;
481     std::vector<CompositePrimitive> supported;
482 
483     ASSERT_TRUE(vibrator->getSupportedPrimitives(&supported).isOk());
484 
485     for (auto primitive : kCompositePrimitives) {
486         bool isPrimitiveSupported =
487                 std::find(supported.begin(), supported.end(), primitive) != supported.end();
488 
489         if (!isPrimitiveSupported) {
490             unsupported.push_back(primitive);
491         }
492     }
493 
494     for (auto primitive : unsupported) {
495         std::vector<CompositeEffect> composite(1);
496 
497         for (auto& effect : composite) {
498             effect.delayMs = 0;
499             effect.primitive = primitive;
500             effect.scale = 1.0f;
501         }
502         Status status = vibrator->compose(composite, nullptr);
503         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
504     }
505 }
506 
TEST_P(VibratorAidl,ComposeScaleBoundary)507 TEST_P(VibratorAidl, ComposeScaleBoundary) {
508     if (!(capabilities & IVibrator::CAP_COMPOSE_EFFECTS)) {
509         GTEST_SKIP() << "CAP_COMPOSE_EFFECTS not supported";
510     }
511 
512     std::vector<CompositeEffect> composite(1);
513     CompositeEffect& effect = composite[0];
514 
515     effect.delayMs = 0;
516     effect.primitive = CompositePrimitive::CLICK;
517 
518     effect.scale = std::nextafter(0.0f, -1.0f);
519     EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->compose(composite, nullptr).exceptionCode());
520 
521     effect.scale = 0.0f;
522     EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
523     EXPECT_TRUE(vibrator->off().isOk());
524 
525     effect.scale = 1.0f;
526     EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
527     EXPECT_TRUE(vibrator->off().isOk());
528 
529     effect.scale = std::nextafter(1.0f, 2.0f);
530     EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->compose(composite, nullptr).exceptionCode());
531 }
532 
TEST_P(VibratorAidl,ComposeDelayBoundary)533 TEST_P(VibratorAidl, ComposeDelayBoundary) {
534     if (!(capabilities & IVibrator::CAP_COMPOSE_EFFECTS)) {
535         GTEST_SKIP() << "CAP_COMPOSE_EFFECTS not supported";
536     }
537 
538     int32_t maxDelay;
539 
540     EXPECT_EQ(Status::EX_NONE, vibrator->getCompositionDelayMax(&maxDelay).exceptionCode());
541 
542     std::vector<CompositeEffect> composite(1);
543     CompositeEffect& effect = composite[0];
544 
545     effect.primitive = CompositePrimitive::CLICK;
546     effect.scale = 1.0f;
547 
548     effect.delayMs = 0;
549     EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
550     EXPECT_TRUE(vibrator->off().isOk());
551 
552     effect.delayMs = 1;
553     EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
554     EXPECT_TRUE(vibrator->off().isOk());
555 
556     effect.delayMs = maxDelay;
557     EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
558     EXPECT_TRUE(vibrator->off().isOk());
559 
560     effect.delayMs = maxDelay + 1;
561     EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->compose(composite, nullptr).exceptionCode());
562 }
563 
TEST_P(VibratorAidl,ComposeSizeBoundary)564 TEST_P(VibratorAidl, ComposeSizeBoundary) {
565     if (!(capabilities & IVibrator::CAP_COMPOSE_EFFECTS)) {
566         GTEST_SKIP() << "CAP_COMPOSE_EFFECTS not supported";
567     }
568 
569     int32_t maxSize;
570 
571     EXPECT_EQ(Status::EX_NONE, vibrator->getCompositionSizeMax(&maxSize).exceptionCode());
572 
573     std::vector<CompositeEffect> composite(maxSize);
574     CompositeEffect effect;
575 
576     effect.delayMs = 1;
577     effect.primitive = CompositePrimitive::CLICK;
578     effect.scale = 1.0f;
579 
580     std::fill(composite.begin(), composite.end(), effect);
581     EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, nullptr).exceptionCode());
582     EXPECT_TRUE(vibrator->off().isOk());
583 
584     composite.emplace_back(effect);
585     EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT, vibrator->compose(composite, nullptr).exceptionCode());
586 }
587 
TEST_P(VibratorAidl,ComposeCallback)588 TEST_P(VibratorAidl, ComposeCallback) {
589     if (!(capabilities & IVibrator::CAP_COMPOSE_EFFECTS)) {
590         GTEST_SKIP() << "CAP_COMPOSE_EFFECTS not supported";
591     }
592 
593     std::vector<CompositePrimitive> supported;
594 
595     ASSERT_TRUE(vibrator->getSupportedPrimitives(&supported).isOk());
596 
597     for (auto primitive : supported) {
598         if (primitive == CompositePrimitive::NOOP) {
599             continue;
600         }
601 
602         std::promise<void> completionPromise;
603         std::future<void> completionFuture{completionPromise.get_future()};
604         sp<CompletionCallback> callback =
605                 new CompletionCallback([&completionPromise] { completionPromise.set_value(); });
606         CompositeEffect effect;
607         std::vector<CompositeEffect> composite;
608         int32_t durationMs;
609         std::chrono::milliseconds duration;
610         std::chrono::time_point<high_resolution_clock> start, end;
611         std::chrono::milliseconds elapsed;
612 
613         effect.delayMs = 0;
614         effect.primitive = primitive;
615         effect.scale = 1.0f;
616         composite.emplace_back(effect);
617 
618         EXPECT_EQ(Status::EX_NONE,
619                   vibrator->getPrimitiveDuration(primitive, &durationMs).exceptionCode())
620                 << toString(primitive);
621         duration = std::chrono::milliseconds(durationMs);
622 
623         start = high_resolution_clock::now();
624         EXPECT_EQ(Status::EX_NONE, vibrator->compose(composite, callback).exceptionCode())
625                 << toString(primitive);
626 
627         EXPECT_EQ(completionFuture.wait_for(duration + VIBRATION_CALLBACK_TIMEOUT),
628                   std::future_status::ready)
629                 << toString(primitive);
630         end = high_resolution_clock::now();
631 
632         elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
633         EXPECT_GE(elapsed.count(), duration.count()) << toString(primitive);
634 
635         EXPECT_TRUE(vibrator->off().isOk());
636     }
637 }
638 
TEST_P(VibratorAidl,AlwaysOn)639 TEST_P(VibratorAidl, AlwaysOn) {
640     if (capabilities & IVibrator::CAP_ALWAYS_ON_CONTROL) {
641         std::vector<Effect> supported;
642         ASSERT_TRUE(vibrator->getSupportedAlwaysOnEffects(&supported).isOk());
643 
644         for (Effect effect : kEffects) {
645             bool isEffectSupported =
646                 std::find(supported.begin(), supported.end(), effect) != supported.end();
647 
648             for (EffectStrength strength : kEffectStrengths) {
649                 Status status = vibrator->alwaysOnEnable(0, effect, strength);
650 
651                 if (isEffectSupported) {
652                     EXPECT_EQ(Status::EX_NONE, status.exceptionCode())
653                         << toString(effect) << " " << toString(strength);
654                 } else {
655                     EXPECT_TRUE(isUnknownOrUnsupported(status))
656                             << status << " " << toString(effect) << " " << toString(strength);
657                 }
658             }
659         }
660 
661         EXPECT_EQ(Status::EX_NONE, vibrator->alwaysOnDisable(0).exceptionCode());
662     }
663 }
664 
TEST_P(VibratorAidl,GetResonantFrequency)665 TEST_P(VibratorAidl, GetResonantFrequency) {
666     getResonantFrequencyHz(vibrator, capabilities);
667 }
668 
TEST_P(VibratorAidl,GetQFactor)669 TEST_P(VibratorAidl, GetQFactor) {
670     float qFactor;
671     Status status = vibrator->getQFactor(&qFactor);
672     if (capabilities & IVibrator::CAP_GET_Q_FACTOR) {
673         ASSERT_GT(qFactor, 0);
674         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
675     } else {
676         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
677     }
678 }
679 
TEST_P(VibratorAidl,GetFrequencyResolution)680 TEST_P(VibratorAidl, GetFrequencyResolution) {
681     getFrequencyResolutionHz(vibrator, capabilities);
682 }
683 
TEST_P(VibratorAidl,GetFrequencyMinimum)684 TEST_P(VibratorAidl, GetFrequencyMinimum) {
685     getFrequencyMinimumHz(vibrator, capabilities);
686 }
687 
TEST_P(VibratorAidl,GetBandwidthAmplitudeMap)688 TEST_P(VibratorAidl, GetBandwidthAmplitudeMap) {
689     std::vector<float> bandwidthAmplitudeMap;
690     Status status = vibrator->getBandwidthAmplitudeMap(&bandwidthAmplitudeMap);
691     if (capabilities & IVibrator::CAP_FREQUENCY_CONTROL) {
692         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
693         ASSERT_FALSE(bandwidthAmplitudeMap.empty());
694 
695         int minMapSize = (getResonantFrequencyHz(vibrator, capabilities) -
696                           getFrequencyMinimumHz(vibrator, capabilities)) /
697                          getFrequencyResolutionHz(vibrator, capabilities);
698         ASSERT_GT(bandwidthAmplitudeMap.size(), minMapSize);
699 
700         for (float e : bandwidthAmplitudeMap) {
701             ASSERT_GE(e, 0.0);
702             ASSERT_LE(e, 1.0);
703         }
704     } else {
705         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
706     }
707 }
708 
TEST_P(VibratorAidl,GetPwlePrimitiveDurationMax)709 TEST_P(VibratorAidl, GetPwlePrimitiveDurationMax) {
710     int32_t durationMs;
711     Status status = vibrator->getPwlePrimitiveDurationMax(&durationMs);
712     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
713         ASSERT_NE(durationMs, 0);
714         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
715     } else {
716         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
717     }
718 }
719 
TEST_P(VibratorAidl,GetPwleCompositionSizeMax)720 TEST_P(VibratorAidl, GetPwleCompositionSizeMax) {
721     int32_t maxSize;
722     Status status = vibrator->getPwleCompositionSizeMax(&maxSize);
723     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
724         ASSERT_NE(maxSize, 0);
725         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
726     } else {
727         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
728     }
729 }
730 
TEST_P(VibratorAidl,GetSupportedBraking)731 TEST_P(VibratorAidl, GetSupportedBraking) {
732     std::vector<Braking> supported;
733     Status status = vibrator->getSupportedBraking(&supported);
734     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
735         bool isDefaultNoneSupported =
736             std::find(supported.begin(), supported.end(), Braking::NONE) != supported.end();
737         ASSERT_TRUE(isDefaultNoneSupported);
738         EXPECT_EQ(status.exceptionCode(), Status::EX_NONE);
739     } else {
740         EXPECT_TRUE(isUnknownOrUnsupported(status)) << status;
741     }
742 }
743 
TEST_P(VibratorAidl,ComposeValidPwle)744 TEST_P(VibratorAidl, ComposeValidPwle) {
745     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
746         ActivePwle firstActive = composeValidActivePwle(vibrator, capabilities);
747 
748         std::vector<Braking> supported;
749         ASSERT_TRUE(vibrator->getSupportedBraking(&supported).isOk());
750         bool isClabSupported =
751             std::find(supported.begin(), supported.end(), Braking::CLAB) != supported.end();
752         BrakingPwle firstBraking;
753         firstBraking.braking = isClabSupported ? Braking::CLAB : Braking::NONE;
754         firstBraking.duration = 100;
755 
756         ActivePwle secondActive = composeValidActivePwle(vibrator, capabilities);
757         if (capabilities & IVibrator::CAP_FREQUENCY_CONTROL) {
758             float minFrequencyHz = getFrequencyMinimumHz(vibrator, capabilities);
759             float maxFrequencyHz = getFrequencyMaximumHz(vibrator, capabilities);
760             float freqResolutionHz = getFrequencyResolutionHz(vibrator, capabilities);
761             secondActive.startFrequency = minFrequencyHz + (freqResolutionHz / 2.0f);
762             secondActive.endFrequency = maxFrequencyHz - (freqResolutionHz / 3.0f);
763         }
764         BrakingPwle secondBraking;
765         secondBraking.braking = Braking::NONE;
766         secondBraking.duration = 10;
767 
768         auto pwleQueue =
769             std::vector<PrimitivePwle>{firstActive, firstBraking, secondActive, secondBraking};
770 
771         EXPECT_EQ(Status::EX_NONE, vibrator->composePwle(pwleQueue, nullptr).exceptionCode());
772         EXPECT_TRUE(vibrator->off().isOk());
773     }
774 }
775 
TEST_P(VibratorAidl,ComposeValidPwleWithCallback)776 TEST_P(VibratorAidl, ComposeValidPwleWithCallback) {
777     if (!((capabilities & IVibrator::CAP_ON_CALLBACK) &&
778           (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS)))
779         return;
780 
781     std::promise<void> completionPromise;
782     std::future<void> completionFuture{completionPromise.get_future()};
783     sp<CompletionCallback> callback =
784         new CompletionCallback([&completionPromise] { completionPromise.set_value(); });
785     int32_t segmentDurationMaxMs;
786     vibrator->getPwlePrimitiveDurationMax(&segmentDurationMaxMs);
787     uint32_t durationMs = segmentDurationMaxMs * 2 + 100;  // Sum of 2 active and 1 braking below
788     auto timeout = std::chrono::milliseconds(durationMs) + VIBRATION_CALLBACK_TIMEOUT;
789 
790     ActivePwle active = composeValidActivePwle(vibrator, capabilities);
791 
792     std::vector<Braking> supported;
793     ASSERT_TRUE(vibrator->getSupportedBraking(&supported).isOk());
794     bool isClabSupported =
795         std::find(supported.begin(), supported.end(), Braking::CLAB) != supported.end();
796     BrakingPwle braking;
797     braking.braking = isClabSupported ? Braking::CLAB : Braking::NONE;
798     braking.duration = 100;
799 
800     auto pwleQueue = std::vector<PrimitivePwle>{active, braking, active};
801 
802     EXPECT_TRUE(vibrator->composePwle(pwleQueue, callback).isOk());
803     EXPECT_EQ(completionFuture.wait_for(timeout), std::future_status::ready);
804     EXPECT_TRUE(vibrator->off().isOk());
805 }
806 
TEST_P(VibratorAidl,ComposePwleSegmentBoundary)807 TEST_P(VibratorAidl, ComposePwleSegmentBoundary) {
808     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
809         std::vector<PrimitivePwle> pwleQueue;
810         // test empty queue
811         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
812                   vibrator->composePwle(pwleQueue, nullptr).exceptionCode());
813         EXPECT_TRUE(vibrator->off().isOk());
814 
815         ActivePwle active = composeValidActivePwle(vibrator, capabilities);
816 
817         PrimitivePwle pwle;
818         pwle = active;
819         int segmentCountMax;
820         vibrator->getPwleCompositionSizeMax(&segmentCountMax);
821 
822         // Create PWLE queue with more segments than allowed
823         for (int i = 0; i < segmentCountMax + 10; i++) {
824             pwleQueue.emplace_back(std::move(pwle));
825         }
826 
827         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
828                   vibrator->composePwle(pwleQueue, nullptr).exceptionCode());
829         EXPECT_TRUE(vibrator->off().isOk());
830     }
831 }
832 
TEST_P(VibratorAidl,ComposePwleAmplitudeParameterBoundary)833 TEST_P(VibratorAidl, ComposePwleAmplitudeParameterBoundary) {
834     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
835         ActivePwle active = composeValidActivePwle(vibrator, capabilities);
836         active.startAmplitude = getAmplitudeMax() + 1.0;  // Amplitude greater than allowed
837         active.endAmplitude = getAmplitudeMax() + 1.0;    // Amplitude greater than allowed
838 
839         auto pwleQueueGreater = std::vector<PrimitivePwle>{active};
840 
841         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
842                   vibrator->composePwle(pwleQueueGreater, nullptr).exceptionCode());
843         EXPECT_TRUE(vibrator->off().isOk());
844 
845         active.startAmplitude = getAmplitudeMin() - 1.0;  // Amplitude less than allowed
846         active.endAmplitude = getAmplitudeMin() - 1.0;    // Amplitude less than allowed
847 
848         auto pwleQueueLess = std::vector<PrimitivePwle>{active};
849 
850         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
851                   vibrator->composePwle(pwleQueueLess, nullptr).exceptionCode());
852         EXPECT_TRUE(vibrator->off().isOk());
853     }
854 }
855 
TEST_P(VibratorAidl,ComposePwleFrequencyParameterBoundary)856 TEST_P(VibratorAidl, ComposePwleFrequencyParameterBoundary) {
857     if ((capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) &&
858         (capabilities & IVibrator::CAP_FREQUENCY_CONTROL)) {
859         float freqMinimumHz = getFrequencyMinimumHz(vibrator, capabilities);
860         float freqMaximumHz = getFrequencyMaximumHz(vibrator, capabilities);
861         float freqResolutionHz = getFrequencyResolutionHz(vibrator, capabilities);
862 
863         ActivePwle active = composeValidActivePwle(vibrator, capabilities);
864         active.startFrequency =
865             freqMaximumHz + freqResolutionHz;                    // Frequency greater than allowed
866         active.endFrequency = freqMaximumHz + freqResolutionHz;  // Frequency greater than allowed
867 
868         auto pwleQueueGreater = std::vector<PrimitivePwle>{active};
869 
870         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
871                   vibrator->composePwle(pwleQueueGreater, nullptr).exceptionCode());
872         EXPECT_TRUE(vibrator->off().isOk());
873 
874         active.startFrequency = freqMinimumHz - freqResolutionHz;  // Frequency less than allowed
875         active.endFrequency = freqMinimumHz - freqResolutionHz;    // Frequency less than allowed
876 
877         auto pwleQueueLess = std::vector<PrimitivePwle>{active};
878 
879         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
880                   vibrator->composePwle(pwleQueueLess, nullptr).exceptionCode());
881         EXPECT_TRUE(vibrator->off().isOk());
882     }
883 }
884 
TEST_P(VibratorAidl,ComposePwleSegmentDurationBoundary)885 TEST_P(VibratorAidl, ComposePwleSegmentDurationBoundary) {
886     if (capabilities & IVibrator::CAP_COMPOSE_PWLE_EFFECTS) {
887         ActivePwle active = composeValidActivePwle(vibrator, capabilities);
888 
889         int32_t segmentDurationMaxMs;
890         vibrator->getPwlePrimitiveDurationMax(&segmentDurationMaxMs);
891         active.duration = segmentDurationMaxMs + 10;  // Segment duration greater than allowed
892 
893         auto pwleQueue = std::vector<PrimitivePwle>{active};
894 
895         EXPECT_EQ(Status::EX_ILLEGAL_ARGUMENT,
896                   vibrator->composePwle(pwleQueue, nullptr).exceptionCode());
897         EXPECT_TRUE(vibrator->off().isOk());
898     }
899 }
900 
GenerateVibratorMapping()901 std::vector<std::tuple<int32_t, int32_t>> GenerateVibratorMapping() {
902     std::vector<std::tuple<int32_t, int32_t>> tuples;
903     auto managerAidlNames = android::getAidlHalInstanceNames(IVibratorManager::descriptor);
904     std::vector<int32_t> vibratorIds;
905 
906     for (int i = 0; i < managerAidlNames.size(); i++) {
907         auto managerName = String16(managerAidlNames[i].c_str());
908         auto vibratorManager = android::waitForDeclaredService<IVibratorManager>(managerName);
909         if (vibratorManager->getVibratorIds(&vibratorIds).isOk()) {
910             for (auto &vibratorId : vibratorIds) {
911                 tuples.push_back(std::make_tuple(i, vibratorId));
912             }
913         }
914     }
915 
916     auto vibratorAidlNames = android::getAidlHalInstanceNames(IVibrator::descriptor);
917     for (int i = 0; i < vibratorAidlNames.size(); i++) {
918         tuples.push_back(std::make_tuple(-1, i));
919     }
920 
921     return tuples;
922 }
923 
PrintGeneratedTest(const testing::TestParamInfo<VibratorAidl::ParamType> & info)924 std::string PrintGeneratedTest(const testing::TestParamInfo<VibratorAidl::ParamType> &info) {
925     const auto &[managerIdx, vibratorId] = info.param;
926     if (managerIdx < 0) {
927         return std::string("TOP_LEVEL_VIBRATOR_") + std::to_string(vibratorId);
928     }
929     return std::string("MANAGER_") + std::to_string(managerIdx) + "_VIBRATOR_ID_" +
930            std::to_string(vibratorId);
931 }
932 
933 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(VibratorAidl);
934 INSTANTIATE_TEST_SUITE_P(Vibrator, VibratorAidl, testing::ValuesIn(GenerateVibratorMapping()),
935                          PrintGeneratedTest);
936 
main(int argc,char ** argv)937 int main(int argc, char **argv) {
938     ::testing::InitGoogleTest(&argc, argv);
939     ProcessState::self()->setThreadPoolMaxThreadCount(1);
940     ProcessState::self()->startThreadPool();
941     return RUN_ALL_TESTS();
942 }
943