1 /*
2 * Copyright (c) 2022-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 "thermal_hdf_utils.h"
17
18 #include <securec.h>
19
20 #include "file_ex.h"
21 #include "hdf_base.h"
22 #include "string_ex.h"
23 #include "thermal_log.h"
24
25 namespace OHOS {
26 namespace HDI {
27 namespace Thermal {
28 namespace V1_1 {
29 namespace {
30 constexpr int32_t INVALID_NUM = -100000;
31 }
32
ReadNodeToInt(const std::string & path)33 int32_t ThermalHdfUtils::ReadNodeToInt(const std::string& path)
34 {
35 std::string content;
36 if (!ReadNode(path, content)) {
37 THERMAL_HILOGW(COMP_HDI, "get node failed");
38 return INVALID_NUM;
39 }
40 int32_t value = INVALID_NUM;
41 StrToInt(content, value);
42 return value;
43 }
44
ReadNode(const std::string & path,std::string & out)45 bool ThermalHdfUtils::ReadNode(const std::string& path, std::string& out)
46 {
47 bool ret = LoadStringFromFile(path, out);
48 TrimStr(out);
49 return ret;
50 }
51
WriteNode(const std::string & path,std::string & data)52 int32_t ThermalHdfUtils::WriteNode(const std::string& path, std::string& data)
53 {
54 FILE* fp;
55 int32_t ret = HDF_FAILURE;
56 if ((fp = fopen(path.c_str(), "r")) == nullptr) {
57 THERMAL_HILOGI(COMP_HDI, "open file failed");
58 return ret;
59 }
60
61 if (fwrite(data.c_str(), sizeof(data.c_str()), 1, fp) == 0) {
62 THERMAL_HILOGW(COMP_HDI, "write node failed");
63 } else {
64 ret = HDF_SUCCESS;
65 }
66
67 if (fclose(fp) != 0) {
68 THERMAL_HILOGW(COMP_HDI, "close file stream failed");
69 }
70 return ret;
71 }
72
TrimStr(std::string & str)73 void ThermalHdfUtils::TrimStr(std::string& str)
74 {
75 if (str.empty()) {
76 return;
77 }
78 str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
79 str.erase(std::remove(str.begin(), str.end(), '\r'), str.end());
80 }
81 } // V1_1
82 } // Thermal
83 } // HDI
84 } // OHOS
85