1 /*
2  * Copyright (c) 2023 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 
16 #include "power_vibrator.h"
17 
18 #include <string>
19 #include "power_log.h"
20 #ifdef POWER_VIBRATOR_MODE_ENABLE
21 #include "vibrator_agent.h"
22 #endif
23 #include "vibrator_source_parser.h"
24 
25 namespace OHOS {
26 namespace PowerMgr {
27 namespace {
28 #ifdef POWER_VIBRATOR_MODE_ENABLE
29 const int32_t VIBRATOR_SUCCESS = 0;
30 #endif
31 }
32 std::mutex PowerVibrator::mutex_;
33 std::shared_ptr<PowerVibrator> PowerVibrator::instance_ = nullptr;
34 
LoadConfig(const std::string & etcPath,const std::string & vendorPath,const std::string & systemPath)35 void PowerVibrator::LoadConfig(
36     const std::string& etcPath, const std::string& vendorPath, const std::string& systemPath)
37 {
38     std::shared_ptr<VibratorSourceParser> parser = std::make_shared<VibratorSourceParser>();
39     std::vector<VibratorSource> sources = parser->ParseSources(etcPath, vendorPath, systemPath);
40     std::lock_guard<std::mutex> lock(sourcesMutex_);
41     for (auto source : sources) {
42         sourceList_.emplace_back(source);
43     }
44 }
45 
StartVibrator(const std::string & scene)46 void PowerVibrator::StartVibrator(const std::string& scene)
47 {
48 #ifdef POWER_VIBRATOR_MODE_ENABLE
49     VibratorSource source;
50     for (VibratorSource& src : sourceList_) {
51         if (src.GetScene() == scene) {
52             source = src;
53             break;
54         }
55     }
56     if (!source.IsEnable() || source.GetType() == "") {
57         POWER_HILOGI(COMP_UTILS, "%{public}s do not need vibrator", scene.c_str());
58         return;
59     }
60     int32_t ret = Sensors::StartVibrator(source.GetType().c_str());
61     if (ret != VIBRATOR_SUCCESS) {
62         POWER_HILOGE(COMP_UTILS, "%{public}s vibrator failed", scene.c_str());
63         return;
64     }
65 #else
66     return;
67 #endif
68 }
69 
GetInstance()70 std::shared_ptr<PowerVibrator> PowerVibrator::GetInstance()
71 {
72     std::lock_guard<std::mutex> lock(mutex_);
73     if (instance_ != nullptr) {
74         return instance_;
75     }
76     instance_ = std::make_shared<PowerVibrator>();
77     return instance_;
78 }
79 } // namespace PowerMgr
80 } // namespace OHOS
81