1 /*
2  * Copyright (C) 2021 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 #pragma once
17 
18 #include <aidl/android/hardware/vibrator/BnVibrator.h>
19 #include <android-base/unique_fd.h>
20 #include <linux/input.h>
21 #include <tinyalsa/asoundlib.h>
22 
23 #include <array>
24 #include <fstream>
25 #include <future>
26 
27 namespace aidl {
28 namespace android {
29 namespace hardware {
30 namespace vibrator {
31 
32 class Vibrator : public BnVibrator {
33   public:
34     // APIs for interfacing with the GPIO pin.
35     class HwGPIO {
36       public:
37         virtual ~HwGPIO() = default;
38         // Get the GPIO pin num and address shift information
39         virtual bool getGPIO() = 0;
40         // Init the GPIO function
41         virtual bool initGPIO() = 0;
42         // Trigger the GPIO pin to synchronize both vibrators's play
43         virtual bool setGPIOOutput(bool value) = 0;
44         // Emit diagnostic information to the given file.
45         virtual void debug(int fd) = 0;
46     };
47 
48     // APIs for interfacing with the kernel driver.
49     class HwApi {
50       public:
51         virtual ~HwApi() = default;
52         // Stores the LRA resonant frequency to be used for PWLE playback
53         // and click compensation.
54         virtual bool setF0(std::string value) = 0;
55         // Stores the frequency offset for long vibrations.
56         virtual bool setF0Offset(uint32_t value) = 0;
57         // Stores the LRA series resistance to be used for click
58         // compensation.
59         virtual bool setRedc(std::string value) = 0;
60         // Stores the LRA Q factor to be used for Q-dependent waveform
61         // selection.
62         virtual bool setQ(std::string value) = 0;
63         // Reports the number of effect waveforms loaded in firmware.
64         virtual bool getEffectCount(uint32_t *value) = 0;
65         // Checks whether braking time bank is supported.
66         virtual bool hasEffectBrakingTimeBank() = 0;
67         // Specifies the bank of the effect for querying braking time.
68         // 0: RAM bank, 2: OWT bank
69         virtual bool setEffectBrakingTimeBank(uint32_t value) = 0;
70         // Specifies the index of an effect whose braking time is to be read.
71         virtual bool setEffectBrakingTimeIndex(uint32_t value) = 0;
72         // Gets the braking time duration of SVC effects (returns 0 if not SVC).
73         virtual bool getEffectBrakingTimeMs(uint32_t *value) = 0;
74         // Blocks until timeout or vibrator reaches desired state
75         // (2 = ASP enabled, 1 = haptic enabled, 0 = disabled).
76         virtual bool pollVibeState(uint32_t value, int32_t timeoutMs = -1) = 0;
77         // Reports whether getOwtFreeSpace() is supported.
78         virtual bool hasOwtFreeSpace() = 0;
79         // Reports the available OWT bytes.
80         virtual bool getOwtFreeSpace(uint32_t *value) = 0;
81         // Enables/Disables F0 compensation enable status
82         virtual bool setF0CompEnable(bool value) = 0;
83         // Enables/Disables Redc compensation enable status
84         virtual bool setRedcCompEnable(bool value) = 0;
85         // Stores the minumun delay time between playback and stop effects.
86         virtual bool setMinOnOffInterval(uint32_t value) = 0;
87         // Indicates the number of 0.125-dB steps of attenuation to apply to
88         // waveforms triggered in response to vibration calls from the
89         // Android vibrator HAL.
90         virtual bool setFFGain(int fd, uint16_t value) = 0;
91         // Create/modify custom effects for all physical waveforms.
92         virtual bool setFFEffect(int fd, struct ff_effect *effect, uint16_t timeoutMs) = 0;
93         // Activates/deactivates the effect index after setFFGain() and setFFEffect().
94         virtual bool setFFPlay(int fd, int8_t index, bool value) = 0;
95         // Get the Alsa device for the audio coupled haptics effect
96         virtual bool getHapticAlsaDevice(int *card, int *device) = 0;
97         // Set haptics PCM amplifier before triggering audio haptics feature
98         virtual bool setHapticPcmAmp(struct pcm **haptic_pcm, bool enable, int card,
99                                      int device) = 0;
100         // Set OWT waveform for compose or compose PWLE request
101         virtual bool uploadOwtEffect(int fd, const uint8_t *owtData, const uint32_t numBytes,
102                                      struct ff_effect *effect, uint32_t *outEffectIndex,
103                                      int *status) = 0;
104         // Erase OWT waveform
105         virtual bool eraseOwtEffect(int fd, int8_t effectIndex, std::vector<ff_effect> *effect) = 0;
106         // Emit diagnostic information to the given file.
107         virtual void debug(int fd) = 0;
108     };
109 
110     // APIs for obtaining calibration/configuration data from persistent memory.
111     class HwCal {
112       public:
113         virtual ~HwCal() = default;
114         // Obtain the calibration version
115         virtual bool getVersion(uint32_t *value) = 0;
116         // Obtains the LRA resonant frequency to be used for PWLE playback
117         // and click compensation.
118         virtual bool getF0(std::string *value) = 0;
119         // Obtains the offset for actuator that will adjust configured F0 to target
120         // frequency for dual actuators
121         virtual bool getF0SyncOffset(uint32_t *value) = 0;
122         // Obtains the LRA series resistance to be used for click
123         // compensation.
124         virtual bool getRedc(std::string *value) = 0;
125         // Obtains the LRA Q factor to be used for Q-dependent waveform
126         // selection.
127         virtual bool getQ(std::string *value) = 0;
128         // Obtains frequency shift for long vibrations.
129         virtual bool getLongFrequencyShift(int32_t *value) = 0;
130         // Obtains the v0/v1(min/max) voltage levels to be applied for
131         // tick/click/long in units of 1%.
132         virtual bool getTickVolLevels(std::array<uint32_t, 2> *value) = 0;
133         virtual bool getClickVolLevels(std::array<uint32_t, 2> *value) = 0;
134         virtual bool getLongVolLevels(std::array<uint32_t, 2> *value) = 0;
135         // Checks if the chirp feature is enabled.
136         virtual bool isChirpEnabled() = 0;
137         // Obtains the supported primitive effects.
138         virtual bool getSupportedPrimitives(uint32_t *value) = 0;
139         // Checks if the f0 compensation feature needs to be enabled.
140         virtual bool isF0CompEnabled() = 0;
141         // Checks if the redc compensation feature needs to be enabled.
142         virtual bool isRedcCompEnabled() = 0;
143         // Emit diagnostic information to the given file.
144         virtual void debug(int fd) = 0;
145     };
146 
147   public:
148     Vibrator(std::unique_ptr<HwApi> hwApiDefault, std::unique_ptr<HwCal> hwCalDefault,
149              std::unique_ptr<HwApi> hwApiDual, std::unique_ptr<HwCal> hwCalDual,
150              std::unique_ptr<HwGPIO> hwgpio);
151 
152     // BnVibrator APIs
153     ndk::ScopedAStatus getCapabilities(int32_t *_aidl_return) override;
154     ndk::ScopedAStatus off() override;
155     ndk::ScopedAStatus on(int32_t timeoutMs,
156                           const std::shared_ptr<IVibratorCallback> &callback) override;
157     ndk::ScopedAStatus perform(Effect effect, EffectStrength strength,
158                                const std::shared_ptr<IVibratorCallback> &callback,
159                                int32_t *_aidl_return) override;
160     ndk::ScopedAStatus getSupportedEffects(std::vector<Effect> *_aidl_return) override;
161     ndk::ScopedAStatus setAmplitude(float amplitude) override;
162     ndk::ScopedAStatus setExternalControl(bool enabled) override;
163     ndk::ScopedAStatus getCompositionDelayMax(int32_t *maxDelayMs);
164     ndk::ScopedAStatus getCompositionSizeMax(int32_t *maxSize);
165     ndk::ScopedAStatus getSupportedPrimitives(std::vector<CompositePrimitive> *supported) override;
166     ndk::ScopedAStatus getPrimitiveDuration(CompositePrimitive primitive,
167                                             int32_t *durationMs) override;
168     ndk::ScopedAStatus compose(const std::vector<CompositeEffect> &composite,
169                                const std::shared_ptr<IVibratorCallback> &callback) override;
170     ndk::ScopedAStatus getSupportedAlwaysOnEffects(std::vector<Effect> *_aidl_return) override;
171     ndk::ScopedAStatus alwaysOnEnable(int32_t id, Effect effect, EffectStrength strength) override;
172     ndk::ScopedAStatus alwaysOnDisable(int32_t id) override;
173     ndk::ScopedAStatus getResonantFrequency(float *resonantFreqHz) override;
174     ndk::ScopedAStatus getQFactor(float *qFactor) override;
175     ndk::ScopedAStatus getFrequencyResolution(float *freqResolutionHz) override;
176     ndk::ScopedAStatus getFrequencyMinimum(float *freqMinimumHz) override;
177     ndk::ScopedAStatus getBandwidthAmplitudeMap(std::vector<float> *_aidl_return) override;
178     ndk::ScopedAStatus getPwlePrimitiveDurationMax(int32_t *durationMs) override;
179     ndk::ScopedAStatus getPwleCompositionSizeMax(int32_t *maxSize) override;
180     ndk::ScopedAStatus getSupportedBraking(std::vector<Braking> *supported) override;
181     ndk::ScopedAStatus composePwle(const std::vector<PrimitivePwle> &composite,
182                                    const std::shared_ptr<IVibratorCallback> &callback) override;
183 
184     // BnCInterface APIs
185     binder_status_t dump(int fd, const char **args, uint32_t numArgs) override;
186 
187     static constexpr uint32_t MIN_ON_OFF_INTERVAL_US = 8500;  // SVC initialization time
188 
189   private:
190     ndk::ScopedAStatus on(uint32_t timeoutMs, uint32_t effectIndex, const class DspMemChunk *ch,
191                           const std::shared_ptr<IVibratorCallback> &callback);
192     // set 'amplitude' based on an arbitrary scale determined by 'maximum'
193     ndk::ScopedAStatus setEffectAmplitude(float amplitude, float maximum);
194     ndk::ScopedAStatus setGlobalAmplitude(bool set);
195     // 'simple' effects are those precompiled and loaded into the controller
196     ndk::ScopedAStatus getSimpleDetails(Effect effect, EffectStrength strength,
197                                         uint32_t *outEffectIndex, uint32_t *outTimeMs,
198                                         uint32_t *outVolLevel);
199     // 'compound' effects are those composed by stringing multiple 'simple' effects
200     ndk::ScopedAStatus getCompoundDetails(Effect effect, EffectStrength strength,
201                                           uint32_t *outTimeMs, class DspMemChunk *outCh);
202     ndk::ScopedAStatus getPrimitiveDetails(CompositePrimitive primitive, uint32_t *outEffectIndex);
203     ndk::ScopedAStatus performEffect(Effect effect, EffectStrength strength,
204                                      const std::shared_ptr<IVibratorCallback> &callback,
205                                      int32_t *outTimeMs);
206     ndk::ScopedAStatus performEffect(uint32_t effectIndex, uint32_t volLevel,
207                                      const class DspMemChunk *ch,
208                                      const std::shared_ptr<IVibratorCallback> &callback);
209     ndk::ScopedAStatus setPwle(const std::string &pwleQueue);
210     bool isUnderExternalControl();
211     void waitForComplete(std::shared_ptr<IVibratorCallback> &&callback);
212     uint32_t intensityToVolLevel(float intensity, uint32_t effectIndex);
213     bool findHapticAlsaDevice(int *card, int *device);
214     bool hasHapticAlsaDevice();
215     bool enableHapticPcmAmp(struct pcm **haptic_pcm, bool enable, int card, int device);
216 
217     std::unique_ptr<HwApi> mHwApiDef;
218     std::unique_ptr<HwCal> mHwCalDef;
219     std::unique_ptr<HwApi> mHwApiDual;
220     std::unique_ptr<HwCal> mHwCalDual;
221     std::unique_ptr<HwGPIO> mHwGPIO;
222     uint32_t mF0Offset;
223     uint32_t mF0OffsetDual;
224     std::array<uint32_t, 2> mTickEffectVol;
225     std::array<uint32_t, 2> mClickEffectVol;
226     std::array<uint32_t, 2> mLongEffectVol;
227     std::vector<ff_effect> mFfEffects;
228     std::vector<ff_effect> mFfEffectsDual;
229     std::vector<uint32_t> mEffectDurations;
230     std::vector<uint32_t> mEffectBrakingDurations;
231     std::vector<std::vector<int16_t>> mEffectCustomData;
232     std::vector<std::vector<int16_t>> mEffectCustomDataDual;
233     std::future<void> mAsyncHandle;
234     ::android::base::unique_fd mInputFd;
235     ::android::base::unique_fd mInputFdDual;
236     int8_t mActiveId{-1};
237     struct pcm *mHapticPcm;
238     int mCard;
239     int mDevice;
240     bool mHasHapticAlsaDevice{false};
241     bool mIsUnderExternalControl;
242     float mLongEffectScale{1.0};
243     bool mIsChirpEnabled;
244     uint32_t mSupportedPrimitivesBits = 0x0;
245     float mRedc{0.0f};
246     float mResonantFrequency{0.0f};
247     std::vector<CompositePrimitive> mSupportedPrimitives;
248     std::vector<uint32_t> mPrimitiveMaxScale;
249     std::vector<uint32_t> mPrimitiveMinScale;
250     bool mConfigHapticAlsaDeviceDone{false};
251     bool mGPIOStatus;
252     bool mIsDual{false};
253 };
254 
255 }  // namespace vibrator
256 }  // namespace hardware
257 }  // namespace android
258 }  // namespace aidl
259