1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "core/common/vibrator/vibrator_utils.h"
16 #include <vector>
17 
18 #include "vibrator_agent.h"
19 
20 using namespace OHOS::Sensors;
21 
22 namespace OHOS::Ace::NG {
23 namespace {
24     static std::vector<const char*> effectIdNames = {
25         VIBRATOR_TYPE_SLIDE,
26         VIBRATOR_TYPE_SLIDE_LIGHT,
27         VIBRATOR_TYPE_CHARGING,
28         VIBRATOR_TYPE_CLOCK_TIMER
29     };
30 
31     const char* VIBRATOR_TYPE_INVALID = "vibrator.type.invalid";
GetVibratorType(const std::string & vibratorType)32     const char* GetVibratorType(const std::string& vibratorType)
33     {
34         if (vibratorType == "longPress.light") {
35             return VIBRATOR_TYPE_LONG_PRESS_LIGHT;
36         } else if (vibratorType == "slide") {
37             return VIBRATOR_TYPE_SLIDE;
38         } else if (vibratorType == "slide.light") {
39             return VIBRATOR_TYPE_SLIDE_LIGHT;
40         }
41         return VIBRATOR_TYPE_INVALID;
42     }
43 };
44 
45 const char* VibratorUtils::supportedEffectId = nullptr;
46 
GetFirstSupportedId()47 const char* VibratorUtils::GetFirstSupportedId()
48 {
49     bool state = false;
50     for (auto item : effectIdNames) {
51         Sensors::IsSupportEffect(item, &state);
52         if (state) {
53             return item;
54         }
55     }
56     return nullptr;
57 }
58 
StartVibraFeedback()59 void VibratorUtils::StartVibraFeedback()
60 {
61 #ifdef INDEXER_SUPPORT_VIBRATOR
62     if (supportedEffectId == nullptr) {
63         supportedEffectId = VibratorUtils::GetFirstSupportedId();
64     }
65     if (supportedEffectId != nullptr) {
66         Sensors::StartVibrator(supportedEffectId);
67     }
68 #endif
69 }
70 
StartVibraFeedback(const std::string & vibratorType)71 void VibratorUtils::StartVibraFeedback(const std::string& vibratorType)
72 {
73     const char* realVibratorType = GetVibratorType(vibratorType);
74     if (strcmp(realVibratorType, VIBRATOR_TYPE_INVALID) == 0) {
75         return;
76     }
77     bool state = false;
78     Sensors::IsSupportEffect(realVibratorType, &state);
79     if (state) {
80         Sensors::StartVibrator(realVibratorType);
81     }
82 }
83 } // namespace OHOS::Ace::NG