xref: /aosp_15_r20/frameworks/native/services/vibratorservice/include/vibratorservice/VibratorHalWrapper.h (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright (C) 2020 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 #ifndef ANDROID_OS_VIBRATORHALWRAPPER_H
18 #define ANDROID_OS_VIBRATORHALWRAPPER_H
19 
20 #include <aidl/android/hardware/vibrator/BnVibratorCallback.h>
21 #include <aidl/android/hardware/vibrator/IVibrator.h>
22 
23 #include <android-base/thread_annotations.h>
24 #include <android/binder_manager.h>
25 #include <android/hardware/vibrator/1.3/IVibrator.h>
26 #include <binder/IServiceManager.h>
27 
28 #include <vibratorservice/VibratorCallbackScheduler.h>
29 
30 namespace android {
31 
32 namespace vibrator {
33 
34 // -------------------------------------------------------------------------------------------------
35 
36 // Base class to represent a generic result of a call to the Vibrator HAL wrapper.
37 class BaseHalResult {
38 public:
isOk()39     bool isOk() const { return mStatus == SUCCESS; }
isFailed()40     bool isFailed() const { return mStatus == FAILED; }
isUnsupported()41     bool isUnsupported() const { return mStatus == UNSUPPORTED; }
shouldRetry()42     bool shouldRetry() const { return isFailed() && mDeadObject; }
errorMessage()43     const char* errorMessage() const { return mErrorMessage.c_str(); }
44 
45 protected:
46     enum Status { SUCCESS, UNSUPPORTED, FAILED };
47     Status mStatus;
48     std::string mErrorMessage;
49     bool mDeadObject;
50 
51     explicit BaseHalResult(Status status, const char* errorMessage = "", bool deadObject = false)
mStatus(status)52           : mStatus(status), mErrorMessage(errorMessage), mDeadObject(deadObject) {}
53     virtual ~BaseHalResult() = default;
54 };
55 
56 // Result of a call to the Vibrator HAL wrapper, holding data if successful.
57 template <typename T>
58 class HalResult : public BaseHalResult {
59 public:
ok(T value)60     static HalResult<T> ok(T value) { return HalResult(value); }
unsupported()61     static HalResult<T> unsupported() { return HalResult(Status::UNSUPPORTED); }
failed(const char * msg)62     static HalResult<T> failed(const char* msg) { return HalResult(Status::FAILED, msg); }
transactionFailed(const char * msg)63     static HalResult<T> transactionFailed(const char* msg) {
64         return HalResult(Status::FAILED, msg, /* deadObject= */ true);
65     }
66 
67     // This will throw std::bad_optional_access if this result is not ok.
value()68     const T& value() const { return mValue.value(); }
valueOr(T && defaultValue)69     const T valueOr(T&& defaultValue) const { return mValue.value_or(defaultValue); }
70 
71 private:
72     std::optional<T> mValue;
73 
HalResult(T value)74     explicit HalResult(T value)
75           : BaseHalResult(Status::SUCCESS), mValue(std::make_optional(value)) {}
76     explicit HalResult(Status status, const char* errorMessage = "", bool deadObject = false)
BaseHalResult(status,errorMessage,deadObject)77           : BaseHalResult(status, errorMessage, deadObject), mValue() {}
78 };
79 
80 // Empty result of a call to the Vibrator HAL wrapper.
81 template <>
82 class HalResult<void> : public BaseHalResult {
83 public:
ok()84     static HalResult<void> ok() { return HalResult(Status::SUCCESS); }
unsupported()85     static HalResult<void> unsupported() { return HalResult(Status::UNSUPPORTED); }
failed(const char * msg)86     static HalResult<void> failed(const char* msg) { return HalResult(Status::FAILED, msg); }
transactionFailed(const char * msg)87     static HalResult<void> transactionFailed(const char* msg) {
88         return HalResult(Status::FAILED, msg, /* deadObject= */ true);
89     }
90 
91 private:
92     explicit HalResult(Status status, const char* errorMessage = "", bool deadObject = false)
BaseHalResult(status,errorMessage,deadObject)93           : BaseHalResult(status, errorMessage, deadObject) {}
94 };
95 
96 // -------------------------------------------------------------------------------------------------
97 
98 // Factory functions that convert failed HIDL/AIDL results into HalResult instances.
99 // Implementation of static template functions needs to be in this header file for the linker.
100 class HalResultFactory {
101 public:
102     template <typename T>
fromStatus(ndk::ScopedAStatus && status,T data)103     static HalResult<T> fromStatus(ndk::ScopedAStatus&& status, T data) {
104         return status.isOk() ? HalResult<T>::ok(std::move(data))
105                              : fromFailedStatus<T>(std::move(status));
106     }
107 
108     template <typename T>
fromStatus(hardware::vibrator::V1_0::Status && status,T data)109     static HalResult<T> fromStatus(hardware::vibrator::V1_0::Status&& status, T data) {
110         return (status == hardware::vibrator::V1_0::Status::OK)
111                 ? HalResult<T>::ok(std::move(data))
112                 : fromFailedStatus<T>(std::move(status));
113     }
114 
115     template <typename T, typename R>
fromReturn(hardware::Return<R> && ret,T data)116     static HalResult<T> fromReturn(hardware::Return<R>&& ret, T data) {
117         return ret.isOk() ? HalResult<T>::ok(std::move(data))
118                           : fromFailedReturn<T, R>(std::move(ret));
119     }
120 
121     template <typename T, typename R>
fromReturn(hardware::Return<R> && ret,hardware::vibrator::V1_0::Status status,T data)122     static HalResult<T> fromReturn(hardware::Return<R>&& ret,
123                                    hardware::vibrator::V1_0::Status status, T data) {
124         return ret.isOk() ? fromStatus<T>(std::move(status), std::move(data))
125                           : fromFailedReturn<T, R>(std::move(ret));
126     }
127 
fromStatus(status_t status)128     static HalResult<void> fromStatus(status_t status) {
129         return (status == android::OK) ? HalResult<void>::ok()
130                                        : fromFailedStatus<void>(std::move(status));
131     }
132 
fromStatus(ndk::ScopedAStatus && status)133     static HalResult<void> fromStatus(ndk::ScopedAStatus&& status) {
134         return status.isOk() ? HalResult<void>::ok() : fromFailedStatus<void>(std::move(status));
135     }
136 
fromStatus(hardware::vibrator::V1_0::Status && status)137     static HalResult<void> fromStatus(hardware::vibrator::V1_0::Status&& status) {
138         return (status == hardware::vibrator::V1_0::Status::OK)
139                 ? HalResult<void>::ok()
140                 : fromFailedStatus<void>(std::move(status));
141     }
142 
143     template <typename R>
fromReturn(hardware::Return<R> && ret)144     static HalResult<void> fromReturn(hardware::Return<R>&& ret) {
145         return ret.isOk() ? HalResult<void>::ok() : fromFailedReturn<void, R>(std::move(ret));
146     }
147 
148 private:
149     template <typename T>
fromFailedStatus(status_t status)150     static HalResult<T> fromFailedStatus(status_t status) {
151         auto msg = "status_t = " + statusToString(status);
152         return (status == android::DEAD_OBJECT) ? HalResult<T>::transactionFailed(msg.c_str())
153                                                 : HalResult<T>::failed(msg.c_str());
154     }
155 
156     template <typename T>
fromFailedStatus(ndk::ScopedAStatus && status)157     static HalResult<T> fromFailedStatus(ndk::ScopedAStatus&& status) {
158         if (status.getExceptionCode() == EX_UNSUPPORTED_OPERATION ||
159             status.getStatus() == STATUS_UNKNOWN_TRANSACTION) {
160             // STATUS_UNKNOWN_TRANSACTION means the HAL implementation is an older version, so this
161             // is the same as the operation being unsupported by this HAL. Should not retry.
162             return HalResult<T>::unsupported();
163         }
164         if (status.getExceptionCode() == EX_TRANSACTION_FAILED) {
165             return HalResult<T>::transactionFailed(status.getMessage());
166         }
167         return HalResult<T>::failed(status.getMessage());
168     }
169 
170     template <typename T>
fromFailedStatus(hardware::vibrator::V1_0::Status && status)171     static HalResult<T> fromFailedStatus(hardware::vibrator::V1_0::Status&& status) {
172         switch (status) {
173             case hardware::vibrator::V1_0::Status::UNSUPPORTED_OPERATION:
174                 return HalResult<T>::unsupported();
175             default:
176                 auto msg = "android::hardware::vibrator::V1_0::Status = " + toString(status);
177                 return HalResult<T>::failed(msg.c_str());
178         }
179     }
180 
181     template <typename T, typename R>
fromFailedReturn(hardware::Return<R> && ret)182     static HalResult<T> fromFailedReturn(hardware::Return<R>&& ret) {
183         return ret.isDeadObject() ? HalResult<T>::transactionFailed(ret.description().c_str())
184                                   : HalResult<T>::failed(ret.description().c_str());
185     }
186 };
187 
188 // -------------------------------------------------------------------------------------------------
189 
190 class HalCallbackWrapper : public aidl::android::hardware::vibrator::BnVibratorCallback {
191 public:
HalCallbackWrapper(std::function<void ()> completionCallback)192     HalCallbackWrapper(std::function<void()> completionCallback)
193           : mCompletionCallback(completionCallback) {}
194 
onComplete()195     ndk::ScopedAStatus onComplete() override {
196         mCompletionCallback();
197         return ndk::ScopedAStatus::ok();
198     }
199 
200 private:
201     const std::function<void()> mCompletionCallback;
202 };
203 
204 // -------------------------------------------------------------------------------------------------
205 
206 // Vibrator HAL capabilities.
207 enum class Capabilities : int32_t {
208     NONE = 0,
209     ON_CALLBACK = aidl::android::hardware::vibrator::IVibrator::CAP_ON_CALLBACK,
210     PERFORM_CALLBACK = aidl::android::hardware::vibrator::IVibrator::CAP_PERFORM_CALLBACK,
211     AMPLITUDE_CONTROL = aidl::android::hardware::vibrator::IVibrator::CAP_AMPLITUDE_CONTROL,
212     EXTERNAL_CONTROL = aidl::android::hardware::vibrator::IVibrator::CAP_EXTERNAL_CONTROL,
213     EXTERNAL_AMPLITUDE_CONTROL =
214             aidl::android::hardware::vibrator::IVibrator::CAP_EXTERNAL_AMPLITUDE_CONTROL,
215     COMPOSE_EFFECTS = aidl::android::hardware::vibrator::IVibrator::CAP_COMPOSE_EFFECTS,
216     COMPOSE_PWLE_EFFECTS = aidl::android::hardware::vibrator::IVibrator::CAP_COMPOSE_PWLE_EFFECTS,
217     ALWAYS_ON_CONTROL = aidl::android::hardware::vibrator::IVibrator::CAP_ALWAYS_ON_CONTROL,
218 };
219 
220 inline Capabilities operator|(Capabilities lhs, Capabilities rhs) {
221     using underlying = typename std::underlying_type<Capabilities>::type;
222     return static_cast<Capabilities>(static_cast<underlying>(lhs) | static_cast<underlying>(rhs));
223 }
224 
225 inline Capabilities& operator|=(Capabilities& lhs, Capabilities rhs) {
226     return lhs = lhs | rhs;
227 }
228 
229 inline Capabilities operator&(Capabilities lhs, Capabilities rhs) {
230     using underlying = typename std::underlying_type<Capabilities>::type;
231     return static_cast<Capabilities>(static_cast<underlying>(lhs) & static_cast<underlying>(rhs));
232 }
233 
234 inline Capabilities& operator&=(Capabilities& lhs, Capabilities rhs) {
235     return lhs = lhs & rhs;
236 }
237 
238 // -------------------------------------------------------------------------------------------------
239 
240 class Info {
241 public:
242     using Effect = aidl::android::hardware::vibrator::Effect;
243     using EffectStrength = aidl::android::hardware::vibrator::EffectStrength;
244     using CompositePrimitive = aidl::android::hardware::vibrator::CompositePrimitive;
245     using Braking = aidl::android::hardware::vibrator::Braking;
246     using FrequencyAccelerationMapEntry =
247             aidl::android::hardware::vibrator::FrequencyAccelerationMapEntry;
248 
249     const HalResult<Capabilities> capabilities;
250     const HalResult<std::vector<Effect>> supportedEffects;
251     const HalResult<std::vector<Braking>> supportedBraking;
252     const HalResult<std::vector<CompositePrimitive>> supportedPrimitives;
253     const HalResult<std::vector<std::chrono::milliseconds>> primitiveDurations;
254     const HalResult<std::chrono::milliseconds> primitiveDelayMax;
255     const HalResult<std::chrono::milliseconds> pwlePrimitiveDurationMax;
256     const HalResult<int32_t> compositionSizeMax;
257     const HalResult<int32_t> pwleSizeMax;
258     const HalResult<float> minFrequency;
259     const HalResult<float> resonantFrequency;
260     const HalResult<float> frequencyResolution;
261     const HalResult<float> qFactor;
262     const HalResult<std::vector<float>> maxAmplitudes;
263     const HalResult<int32_t> maxEnvelopeEffectSize;
264     const HalResult<std::chrono::milliseconds> minEnvelopeEffectControlPointDuration;
265     const HalResult<std::chrono::milliseconds> maxEnvelopeEffectControlPointDuration;
266     const HalResult<std::vector<FrequencyAccelerationMapEntry>> frequencyToOutputAccelerationMap;
267 
logFailures()268     void logFailures() const {
269         logFailure<Capabilities>(capabilities, "getCapabilities");
270         logFailure<std::vector<Effect>>(supportedEffects, "getSupportedEffects");
271         logFailure<std::vector<Braking>>(supportedBraking, "getSupportedBraking");
272         logFailure<std::vector<CompositePrimitive>>(supportedPrimitives, "getSupportedPrimitives");
273         logFailure<std::vector<std::chrono::milliseconds>>(primitiveDurations,
274                                                            "getPrimitiveDuration");
275         logFailure<std::chrono::milliseconds>(primitiveDelayMax, "getPrimitiveDelayMax");
276         logFailure<std::chrono::milliseconds>(pwlePrimitiveDurationMax,
277                                               "getPwlePrimitiveDurationMax");
278         logFailure<int32_t>(compositionSizeMax, "getCompositionSizeMax");
279         logFailure<int32_t>(pwleSizeMax, "getPwleSizeMax");
280         logFailure<float>(minFrequency, "getMinFrequency");
281         logFailure<float>(resonantFrequency, "getResonantFrequency");
282         logFailure<float>(frequencyResolution, "getFrequencyResolution");
283         logFailure<float>(qFactor, "getQFactor");
284         logFailure<std::vector<float>>(maxAmplitudes, "getMaxAmplitudes");
285         logFailure<int32_t>(maxEnvelopeEffectSize, "getMaxEnvelopeEffectSize");
286         logFailure<std::chrono::milliseconds>(minEnvelopeEffectControlPointDuration,
287                                               "getMinEnvelopeEffectControlPointDuration");
288         logFailure<std::chrono::milliseconds>(maxEnvelopeEffectControlPointDuration,
289                                               "getMaxEnvelopeEffectControlPointDuration");
290         logFailure<
291                 std::vector<FrequencyAccelerationMapEntry>>(frequencyToOutputAccelerationMap,
292                                                             "getfrequencyToOutputAccelerationMap");
293     }
294 
shouldRetry()295     bool shouldRetry() const {
296         return capabilities.shouldRetry() || supportedEffects.shouldRetry() ||
297                 supportedBraking.shouldRetry() || supportedPrimitives.shouldRetry() ||
298                 primitiveDurations.shouldRetry() || primitiveDelayMax.shouldRetry() ||
299                 pwlePrimitiveDurationMax.shouldRetry() || compositionSizeMax.shouldRetry() ||
300                 pwleSizeMax.shouldRetry() || minFrequency.shouldRetry() ||
301                 resonantFrequency.shouldRetry() || frequencyResolution.shouldRetry() ||
302                 qFactor.shouldRetry() || maxAmplitudes.shouldRetry() ||
303                 maxEnvelopeEffectSize.shouldRetry() ||
304                 minEnvelopeEffectControlPointDuration.shouldRetry() ||
305                 maxEnvelopeEffectControlPointDuration.shouldRetry() ||
306                 frequencyToOutputAccelerationMap.shouldRetry();
307     }
308 
309 private:
310     template <typename T>
logFailure(HalResult<T> result,const char * functionName)311     void logFailure(HalResult<T> result, const char* functionName) const {
312         if (result.isFailed()) {
313             ALOGE("Vibrator HAL %s failed: %s", functionName, result.errorMessage());
314         }
315     }
316 };
317 
318 class InfoCache {
319 public:
get()320     Info get() {
321         return {mCapabilities,
322                 mSupportedEffects,
323                 mSupportedBraking,
324                 mSupportedPrimitives,
325                 mPrimitiveDurations,
326                 mPrimitiveDelayMax,
327                 mPwlePrimitiveDurationMax,
328                 mCompositionSizeMax,
329                 mPwleSizeMax,
330                 mMinFrequency,
331                 mResonantFrequency,
332                 mFrequencyResolution,
333                 mQFactor,
334                 mMaxAmplitudes,
335                 mMaxEnvelopeEffectSize,
336                 mMinEnvelopeEffectControlPointDuration,
337                 mMaxEnvelopeEffectControlPointDuration,
338                 mFrequencyToOutputAccelerationMap};
339     }
340 
341 private:
342     // Create a transaction failed results as default so we can retry on the first time we get them.
343     static const constexpr char* MSG = "never loaded";
344     HalResult<Capabilities> mCapabilities = HalResult<Capabilities>::transactionFailed(MSG);
345     HalResult<std::vector<Info::Effect>> mSupportedEffects =
346             HalResult<std::vector<Info::Effect>>::transactionFailed(MSG);
347     HalResult<std::vector<Info::Braking>> mSupportedBraking =
348             HalResult<std::vector<Info::Braking>>::transactionFailed(MSG);
349     HalResult<std::vector<Info::CompositePrimitive>> mSupportedPrimitives =
350             HalResult<std::vector<Info::CompositePrimitive>>::transactionFailed(MSG);
351     HalResult<std::vector<std::chrono::milliseconds>> mPrimitiveDurations =
352             HalResult<std::vector<std::chrono::milliseconds>>::transactionFailed(MSG);
353     HalResult<std::chrono::milliseconds> mPrimitiveDelayMax =
354             HalResult<std::chrono::milliseconds>::transactionFailed(MSG);
355     HalResult<std::chrono::milliseconds> mPwlePrimitiveDurationMax =
356             HalResult<std::chrono::milliseconds>::transactionFailed(MSG);
357     HalResult<int32_t> mCompositionSizeMax = HalResult<int>::transactionFailed(MSG);
358     HalResult<int32_t> mPwleSizeMax = HalResult<int>::transactionFailed(MSG);
359     HalResult<float> mMinFrequency = HalResult<float>::transactionFailed(MSG);
360     HalResult<float> mResonantFrequency = HalResult<float>::transactionFailed(MSG);
361     HalResult<float> mFrequencyResolution = HalResult<float>::transactionFailed(MSG);
362     HalResult<float> mQFactor = HalResult<float>::transactionFailed(MSG);
363     HalResult<std::vector<float>> mMaxAmplitudes =
364             HalResult<std::vector<float>>::transactionFailed(MSG);
365     HalResult<int32_t> mMaxEnvelopeEffectSize = HalResult<int>::transactionFailed(MSG);
366     HalResult<std::chrono::milliseconds> mMinEnvelopeEffectControlPointDuration =
367             HalResult<std::chrono::milliseconds>::transactionFailed(MSG);
368     HalResult<std::chrono::milliseconds> mMaxEnvelopeEffectControlPointDuration =
369             HalResult<std::chrono::milliseconds>::transactionFailed(MSG);
370     HalResult<std::vector<Info::FrequencyAccelerationMapEntry>> mFrequencyToOutputAccelerationMap =
371             HalResult<std::vector<Info::FrequencyAccelerationMapEntry>>::transactionFailed(MSG);
372 
373     friend class HalWrapper;
374 };
375 
376 // Wrapper for Vibrator HAL handlers.
377 class HalWrapper {
378 public:
379     using Effect = aidl::android::hardware::vibrator::Effect;
380     using EffectStrength = aidl::android::hardware::vibrator::EffectStrength;
381     using VendorEffect = aidl::android::hardware::vibrator::VendorEffect;
382     using CompositePrimitive = aidl::android::hardware::vibrator::CompositePrimitive;
383     using CompositeEffect = aidl::android::hardware::vibrator::CompositeEffect;
384     using Braking = aidl::android::hardware::vibrator::Braking;
385     using PrimitivePwle = aidl::android::hardware::vibrator::PrimitivePwle;
386     using CompositePwleV2 = aidl::android::hardware::vibrator::CompositePwleV2;
387     using FrequencyAccelerationMapEntry =
388             aidl::android::hardware::vibrator::FrequencyAccelerationMapEntry;
389 
HalWrapper(std::shared_ptr<CallbackScheduler> scheduler)390     explicit HalWrapper(std::shared_ptr<CallbackScheduler> scheduler)
391           : mCallbackScheduler(std::move(scheduler)) {}
392     virtual ~HalWrapper() = default;
393 
394     /* reloads wrapped HAL service instance without waiting. This can be used to reconnect when the
395      * service restarts, to rapidly retry after a failure.
396      */
397     virtual void tryReconnect() = 0;
398 
399     Info getInfo();
400 
401     virtual HalResult<void> ping() = 0;
402     virtual HalResult<void> on(std::chrono::milliseconds timeout,
403                                const std::function<void()>& completionCallback) = 0;
404     virtual HalResult<void> off() = 0;
405 
406     virtual HalResult<void> setAmplitude(float amplitude) = 0;
407     virtual HalResult<void> setExternalControl(bool enabled) = 0;
408 
409     virtual HalResult<void> alwaysOnEnable(int32_t id, Effect effect, EffectStrength strength) = 0;
410     virtual HalResult<void> alwaysOnDisable(int32_t id) = 0;
411 
412     virtual HalResult<std::chrono::milliseconds> performEffect(
413             Effect effect, EffectStrength strength,
414             const std::function<void()>& completionCallback) = 0;
415 
416     virtual HalResult<void> performVendorEffect(const VendorEffect& effect,
417                                                 const std::function<void()>& completionCallback);
418 
419     virtual HalResult<std::chrono::milliseconds> performComposedEffect(
420             const std::vector<CompositeEffect>& primitives,
421             const std::function<void()>& completionCallback);
422 
423     virtual HalResult<void> performPwleEffect(const std::vector<PrimitivePwle>& primitives,
424                                               const std::function<void()>& completionCallback);
425 
426     virtual HalResult<void> composePwleV2(const CompositePwleV2& composite,
427                                           const std::function<void()>& completionCallback);
428 
429 protected:
430     // Shared pointer to allow CallbackScheduler to outlive this wrapper.
431     const std::shared_ptr<CallbackScheduler> mCallbackScheduler;
432 
433     // Load and cache vibrator info, returning cached result is present.
434     HalResult<Capabilities> getCapabilities();
435     HalResult<std::vector<std::chrono::milliseconds>> getPrimitiveDurations();
436 
437     // Request vibrator info to HAL skipping cache.
438     virtual HalResult<Capabilities> getCapabilitiesInternal() = 0;
439     virtual HalResult<std::vector<Effect>> getSupportedEffectsInternal();
440     virtual HalResult<std::vector<Braking>> getSupportedBrakingInternal();
441     virtual HalResult<std::vector<CompositePrimitive>> getSupportedPrimitivesInternal();
442     virtual HalResult<std::vector<std::chrono::milliseconds>> getPrimitiveDurationsInternal(
443             const std::vector<CompositePrimitive>& supportedPrimitives);
444     virtual HalResult<std::chrono::milliseconds> getPrimitiveDelayMaxInternal();
445     virtual HalResult<std::chrono::milliseconds> getPrimitiveDurationMaxInternal();
446     virtual HalResult<int32_t> getCompositionSizeMaxInternal();
447     virtual HalResult<int32_t> getPwleSizeMaxInternal();
448     virtual HalResult<float> getMinFrequencyInternal();
449     virtual HalResult<float> getResonantFrequencyInternal();
450     virtual HalResult<float> getFrequencyResolutionInternal();
451     virtual HalResult<float> getQFactorInternal();
452     virtual HalResult<std::vector<float>> getMaxAmplitudesInternal();
453     virtual HalResult<int32_t> getMaxEnvelopeEffectSizeInternal();
454     virtual HalResult<std::chrono::milliseconds> getMinEnvelopeEffectControlPointDurationInternal();
455     virtual HalResult<std::chrono::milliseconds> getMaxEnvelopeEffectControlPointDurationInternal();
456     virtual HalResult<std::vector<FrequencyAccelerationMapEntry>>
457     getFrequencyToOutputAccelerationMapInternal();
458 
459 private:
460     std::mutex mInfoMutex;
461     InfoCache mInfoCache GUARDED_BY(mInfoMutex);
462 };
463 
464 // Wrapper for the AIDL Vibrator HAL.
465 class AidlHalWrapper : public HalWrapper {
466 public:
467     using IVibrator = aidl::android::hardware::vibrator::IVibrator;
468     using reconnect_fn = std::function<HalResult<std::shared_ptr<IVibrator>>()>;
469 
470     AidlHalWrapper(
471             std::shared_ptr<CallbackScheduler> scheduler, std::shared_ptr<IVibrator> handle,
472             reconnect_fn reconnectFn =
473                     []() {
474                         auto serviceName = std::string(IVibrator::descriptor) + "/default";
475                         auto hal = IVibrator::fromBinder(
476                                 ndk::SpAIBinder(AServiceManager_checkService(serviceName.c_str())));
477                         return HalResult<std::shared_ptr<IVibrator>>::ok(std::move(hal));
478                     })
HalWrapper(std::move (scheduler))479           : HalWrapper(std::move(scheduler)),
480             mReconnectFn(reconnectFn),
481             mHandle(std::move(handle)) {}
482     virtual ~AidlHalWrapper() = default;
483 
484     HalResult<void> ping() override final;
485     void tryReconnect() override final;
486 
487     HalResult<void> on(std::chrono::milliseconds timeout,
488                        const std::function<void()>& completionCallback) override final;
489     HalResult<void> off() override final;
490 
491     HalResult<void> setAmplitude(float amplitude) override final;
492     HalResult<void> setExternalControl(bool enabled) override final;
493 
494     HalResult<void> alwaysOnEnable(int32_t id, Effect effect,
495                                    EffectStrength strength) override final;
496     HalResult<void> alwaysOnDisable(int32_t id) override final;
497 
498     HalResult<std::chrono::milliseconds> performEffect(
499             Effect effect, EffectStrength strength,
500             const std::function<void()>& completionCallback) override final;
501 
502     HalResult<void> performVendorEffect(
503             const VendorEffect& effect,
504             const std::function<void()>& completionCallback) override final;
505 
506     HalResult<std::chrono::milliseconds> performComposedEffect(
507             const std::vector<CompositeEffect>& primitives,
508             const std::function<void()>& completionCallback) override final;
509 
510     HalResult<void> performPwleEffect(
511             const std::vector<PrimitivePwle>& primitives,
512             const std::function<void()>& completionCallback) override final;
513 
514     HalResult<void> composePwleV2(const CompositePwleV2& composite,
515                                   const std::function<void()>& completionCallback) override final;
516 
517 protected:
518     HalResult<Capabilities> getCapabilitiesInternal() override final;
519     HalResult<std::vector<Effect>> getSupportedEffectsInternal() override final;
520     HalResult<std::vector<Braking>> getSupportedBrakingInternal() override final;
521     HalResult<std::vector<CompositePrimitive>> getSupportedPrimitivesInternal() override final;
522     HalResult<std::vector<std::chrono::milliseconds>> getPrimitiveDurationsInternal(
523             const std::vector<CompositePrimitive>& supportedPrimitives) override final;
524     HalResult<std::chrono::milliseconds> getPrimitiveDelayMaxInternal() override final;
525     HalResult<std::chrono::milliseconds> getPrimitiveDurationMaxInternal() override final;
526     HalResult<int32_t> getCompositionSizeMaxInternal() override final;
527     HalResult<int32_t> getPwleSizeMaxInternal() override final;
528     HalResult<float> getMinFrequencyInternal() override final;
529     HalResult<float> getResonantFrequencyInternal() override final;
530     HalResult<float> getFrequencyResolutionInternal() override final;
531     HalResult<float> getQFactorInternal() override final;
532     HalResult<std::vector<float>> getMaxAmplitudesInternal() override final;
533     HalResult<int32_t> getMaxEnvelopeEffectSizeInternal() override final;
534     HalResult<std::chrono::milliseconds> getMinEnvelopeEffectControlPointDurationInternal()
535             override final;
536     HalResult<std::chrono::milliseconds> getMaxEnvelopeEffectControlPointDurationInternal()
537             override final;
538 
539     HalResult<std::vector<FrequencyAccelerationMapEntry>>
540     getFrequencyToOutputAccelerationMapInternal() override final;
541 
542 private:
543     const reconnect_fn mReconnectFn;
544     std::mutex mHandleMutex;
545     std::shared_ptr<IVibrator> mHandle GUARDED_BY(mHandleMutex);
546 
547     std::shared_ptr<IVibrator> getHal();
548 };
549 
550 // Wrapper for the HDIL Vibrator HALs.
551 template <typename I>
552 class HidlHalWrapper : public HalWrapper {
553 public:
HidlHalWrapper(std::shared_ptr<CallbackScheduler> scheduler,sp<I> handle)554     HidlHalWrapper(std::shared_ptr<CallbackScheduler> scheduler, sp<I> handle)
555           : HalWrapper(std::move(scheduler)), mHandle(std::move(handle)) {}
556     virtual ~HidlHalWrapper() = default;
557 
558     HalResult<void> ping() override final;
559     void tryReconnect() override final;
560 
561     HalResult<void> on(std::chrono::milliseconds timeout,
562                        const std::function<void()>& completionCallback) override final;
563     HalResult<void> off() override final;
564 
565     HalResult<void> setAmplitude(float amplitude) override final;
566     virtual HalResult<void> setExternalControl(bool enabled) override;
567 
568     HalResult<void> alwaysOnEnable(int32_t id, HalWrapper::Effect effect,
569                                    HalWrapper::EffectStrength strength) override final;
570     HalResult<void> alwaysOnDisable(int32_t id) override final;
571 
572 protected:
573     std::mutex mHandleMutex;
574     sp<I> mHandle GUARDED_BY(mHandleMutex);
575 
576     virtual HalResult<Capabilities> getCapabilitiesInternal() override;
577 
578     template <class T>
579     using perform_fn =
580             hardware::Return<void> (I::*)(T, hardware::vibrator::V1_0::EffectStrength,
581                                           hardware::vibrator::V1_0::IVibrator::perform_cb);
582 
583     template <class T>
584     HalResult<std::chrono::milliseconds> performInternal(
585             perform_fn<T> performFn, sp<I> handle, T effect, HalWrapper::EffectStrength strength,
586             const std::function<void()>& completionCallback);
587 
588     sp<I> getHal();
589 };
590 
591 // Wrapper for the HDIL Vibrator HAL v1.0.
592 class HidlHalWrapperV1_0 : public HidlHalWrapper<hardware::vibrator::V1_0::IVibrator> {
593 public:
HidlHalWrapperV1_0(std::shared_ptr<CallbackScheduler> scheduler,sp<hardware::vibrator::V1_0::IVibrator> handle)594     HidlHalWrapperV1_0(std::shared_ptr<CallbackScheduler> scheduler,
595                        sp<hardware::vibrator::V1_0::IVibrator> handle)
596           : HidlHalWrapper<hardware::vibrator::V1_0::IVibrator>(std::move(scheduler),
597                                                                 std::move(handle)) {}
598     virtual ~HidlHalWrapperV1_0() = default;
599 
600     HalResult<std::chrono::milliseconds> performEffect(
601             HalWrapper::Effect effect, HalWrapper::EffectStrength strength,
602             const std::function<void()>& completionCallback) override final;
603 };
604 
605 // Wrapper for the HDIL Vibrator HAL v1.1.
606 class HidlHalWrapperV1_1 : public HidlHalWrapper<hardware::vibrator::V1_1::IVibrator> {
607 public:
HidlHalWrapperV1_1(std::shared_ptr<CallbackScheduler> scheduler,sp<hardware::vibrator::V1_1::IVibrator> handle)608     HidlHalWrapperV1_1(std::shared_ptr<CallbackScheduler> scheduler,
609                        sp<hardware::vibrator::V1_1::IVibrator> handle)
610           : HidlHalWrapper<hardware::vibrator::V1_1::IVibrator>(std::move(scheduler),
611                                                                 std::move(handle)) {}
612     virtual ~HidlHalWrapperV1_1() = default;
613 
614     HalResult<std::chrono::milliseconds> performEffect(
615             HalWrapper::Effect effect, HalWrapper::EffectStrength strength,
616             const std::function<void()>& completionCallback) override final;
617 };
618 
619 // Wrapper for the HDIL Vibrator HAL v1.2.
620 class HidlHalWrapperV1_2 : public HidlHalWrapper<hardware::vibrator::V1_2::IVibrator> {
621 public:
HidlHalWrapperV1_2(std::shared_ptr<CallbackScheduler> scheduler,sp<hardware::vibrator::V1_2::IVibrator> handle)622     HidlHalWrapperV1_2(std::shared_ptr<CallbackScheduler> scheduler,
623                        sp<hardware::vibrator::V1_2::IVibrator> handle)
624           : HidlHalWrapper<hardware::vibrator::V1_2::IVibrator>(std::move(scheduler),
625                                                                 std::move(handle)) {}
626     virtual ~HidlHalWrapperV1_2() = default;
627 
628     HalResult<std::chrono::milliseconds> performEffect(
629             HalWrapper::Effect effect, HalWrapper::EffectStrength strength,
630             const std::function<void()>& completionCallback) override final;
631 };
632 
633 // Wrapper for the HDIL Vibrator HAL v1.3.
634 class HidlHalWrapperV1_3 : public HidlHalWrapper<hardware::vibrator::V1_3::IVibrator> {
635 public:
HidlHalWrapperV1_3(std::shared_ptr<CallbackScheduler> scheduler,sp<hardware::vibrator::V1_3::IVibrator> handle)636     HidlHalWrapperV1_3(std::shared_ptr<CallbackScheduler> scheduler,
637                        sp<hardware::vibrator::V1_3::IVibrator> handle)
638           : HidlHalWrapper<hardware::vibrator::V1_3::IVibrator>(std::move(scheduler),
639                                                                 std::move(handle)) {}
640     virtual ~HidlHalWrapperV1_3() = default;
641 
642     HalResult<void> setExternalControl(bool enabled) override final;
643 
644     HalResult<std::chrono::milliseconds> performEffect(
645             HalWrapper::Effect effect, HalWrapper::EffectStrength strength,
646             const std::function<void()>& completionCallback) override final;
647 
648 protected:
649     HalResult<Capabilities> getCapabilitiesInternal() override final;
650 };
651 
652 // -------------------------------------------------------------------------------------------------
653 
654 }; // namespace vibrator
655 
656 }; // namespace android
657 
658 #endif // ANDROID_OS_VIBRATORHALWRAPPER_H
659