1 /*
2 * Copyright (C) 2017 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 "recovery_utils/thermalutil.h"
18
19 #include <dirent.h>
20 #include <stdio.h>
21
22 #include <algorithm>
23 #include <string>
24 #include <vector>
25
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/parseint.h>
29 #include <android-base/strings.h>
30
31 static constexpr auto THERMAL_PREFIX = "/sys/class/thermal/";
32
thermal_filter(const dirent * de)33 static int thermal_filter(const dirent* de) {
34 if (android::base::StartsWith(de->d_name, "thermal_zone")) {
35 return 1;
36 }
37 return 0;
38 }
39
InitThermalPaths()40 static std::vector<std::string> InitThermalPaths() {
41 dirent** namelist;
42 int n = scandir(THERMAL_PREFIX, &namelist, thermal_filter, alphasort);
43 if (n == -1) {
44 PLOG(ERROR) << "Failed to scandir " << THERMAL_PREFIX;
45 return {};
46 }
47 if (n == 0) {
48 LOG(ERROR) << "Failed to find CPU thermal info in " << THERMAL_PREFIX;
49 return {};
50 }
51
52 std::vector<std::string> thermal_paths;
53 while (n--) {
54 thermal_paths.push_back(THERMAL_PREFIX + std::string(namelist[n]->d_name) + "/temp");
55 free(namelist[n]);
56 }
57 free(namelist);
58 return thermal_paths;
59 }
60
GetMaxValueFromThermalZone()61 int GetMaxValueFromThermalZone() {
62 static std::vector<std::string> thermal_paths = InitThermalPaths();
63 int max_temperature = -1;
64 for (const auto& path : thermal_paths) {
65 std::string content;
66 if (!android::base::ReadFileToString(path, &content)) {
67 PLOG(WARNING) << "Failed to read " << path;
68 continue;
69 }
70
71 int temperature;
72 if (!android::base::ParseInt(android::base::Trim(content), &temperature)) {
73 LOG(WARNING) << "Failed to parse integer in " << content;
74 continue;
75 }
76 max_temperature = std::max(temperature, max_temperature);
77 }
78 LOG(INFO) << "current maximum temperature: " << max_temperature;
79 return max_temperature;
80 }
81