1 /*
2 * Copyright (C) 2018 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 #include <algorithm>
18 #include <string_view>
19
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24 #include "thermal_files.h"
25
26 namespace android {
27 namespace hardware {
28 namespace thermal {
29 namespace V2_0 {
30 namespace implementation {
31
getThermalFilePath(std::string_view thermal_name) const32 std::string ThermalFiles::getThermalFilePath(std::string_view thermal_name) const {
33 auto sensor_itr = thermal_name_to_path_map_.find(thermal_name.data());
34 if (sensor_itr == thermal_name_to_path_map_.end()) {
35 return "";
36 }
37 return sensor_itr->second;
38 }
39
addThermalFile(std::string_view thermal_name,std::string_view path)40 bool ThermalFiles::addThermalFile(std::string_view thermal_name, std::string_view path) {
41 return thermal_name_to_path_map_.emplace(thermal_name, path).second;
42 }
43
readThermalFile(std::string_view thermal_name,std::string * data) const44 bool ThermalFiles::readThermalFile(std::string_view thermal_name, std::string *data) const {
45 std::string sensor_reading;
46 std::string file_path = getThermalFilePath(std::string_view(thermal_name));
47 *data = "";
48 if (file_path.empty()) {
49 PLOG(WARNING) << "Failed to find " << thermal_name << "'s path";
50 return false;
51 }
52
53 if (!::android::base::ReadFileToString(file_path, &sensor_reading)) {
54 PLOG(WARNING) << "Failed to read sensor: " << thermal_name;
55 return false;
56 }
57
58 // Strip the newline.
59 *data = ::android::base::Trim(sensor_reading);
60 return true;
61 }
62
writeCdevFile(std::string_view cdev_name,std::string_view data)63 bool ThermalFiles::writeCdevFile(std::string_view cdev_name, std::string_view data) {
64 std::string file_path =
65 getThermalFilePath(android::base::StringPrintf("%s_%s", cdev_name.data(), "w"));
66
67 if (!android::base::WriteStringToFile(data.data(), file_path)) {
68 PLOG(WARNING) << "Failed to write cdev: " << cdev_name << " to " << data.data();
69 return false;
70 }
71
72 return true;
73 }
74
75 } // namespace implementation
76 } // namespace V2_0
77 } // namespace thermal
78 } // namespace hardware
79 } // namespace android
80