Repository navigation
thermal_monitor: Add thermal monitor binary #55
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
jimblacklercorp
merged 6 commits into
android-graphics:main
from
jimblacklercorp:add-thermal-monitor
Nov 6, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
205cac3
thermal_monitor: Add thermal monitor binary
jimblacklercorp 235b7fe
thermal_monitor: Address review feedback on PR #55
jimblacklercorp 69c5994
thermal_monitor: Write counters with the Perfetto SDK instead of atrace
jimblacklercorp 8a034d3
thermal_monitor: Use AThermalStatus instead of a mirror enum
jimblacklercorp f70f55b
thermal_monitor: Address second round of review feedback on PR #55
jimblacklercorp 61dff0c
Merge branch 'main' into add-thermal-monitor
jimblacklercorp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| # Copyright (C) 2026 Google Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| # The sampling policy has no Android dependencies, so it is also built on the host for the unit tests. | ||
| add_library(thermal_collector STATIC thermal_collector.cpp thermal_collector.h) | ||
| target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) | ||
| if(NOT ANDROID) | ||
| # Stands in for the NDK's <android/thermal.h> so that the collector builds off-device. | ||
| target_include_directories(thermal_collector PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/host_stubs) | ||
| endif() | ||
|
|
||
| if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) | ||
| set_property(TARGET thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") | ||
| endif() | ||
|
|
||
| if(ANDROID) | ||
| # The Perfetto SDK that the layers use. Built as its own library so that the availability checks | ||
| # below only apply to main.cpp. | ||
| set(PERFETTO_SDK_DIR ${PROJECT_SOURCE_DIR}/layersvt/perfetto) | ||
| add_library(thermal_monitor_perfetto STATIC ${PERFETTO_SDK_DIR}/perfetto.cc) | ||
| target_include_directories(thermal_monitor_perfetto PUBLIC ${PROJECT_SOURCE_DIR}/layersvt) | ||
| target_compile_options(thermal_monitor_perfetto PRIVATE -Wno-deprecated-declarations) | ||
| target_link_libraries(thermal_monitor_perfetto PUBLIC log) | ||
|
|
||
| add_executable(thermal_monitor main.cpp) | ||
| target_link_libraries(thermal_monitor PRIVATE thermal_collector thermal_monitor_perfetto android log) | ||
| # AThermal_getThermalHeadroomThresholds() is API 35, above ANDROID_PLATFORM, so it is weakly | ||
| # linked and guarded by __builtin_available. | ||
| target_compile_definitions(thermal_monitor PRIVATE __ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) | ||
| target_compile_options(thermal_monitor PRIVATE -Werror=unguarded-availability) | ||
| install(TARGETS thermal_monitor DESTINATION ${CMAKE_INSTALL_BINDIR}) | ||
| endif() | ||
|
|
||
| if(BUILD_TESTS AND NOT ANDROID) | ||
| add_subdirectory(test) | ||
| endif() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| /* Copyright (C) 2026 Google Inc. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| // Host-only stand-in for the NDK's <android/thermal.h>, so that ThermalCollector, which only needs | ||
| // the AThermalStatus type, can be built and unit tested off-device. Only on the include path for | ||
| // non-Android builds; Android builds use the real NDK header. The values are part of the NDK ABI. | ||
|
|
||
| #pragma once | ||
|
|
||
| enum AThermalStatus { | ||
| ATHERMAL_STATUS_ERROR = -1, | ||
| ATHERMAL_STATUS_NONE = 0, | ||
| ATHERMAL_STATUS_LIGHT = 1, | ||
| ATHERMAL_STATUS_MODERATE = 2, | ||
| ATHERMAL_STATUS_SEVERE = 3, | ||
| ATHERMAL_STATUS_CRITICAL = 4, | ||
| ATHERMAL_STATUS_EMERGENCY = 5, | ||
| ATHERMAL_STATUS_SHUTDOWN = 6, | ||
| }; | ||
| typedef enum AThermalStatus AThermalStatus; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| /* Copyright (C) 2026 Google Inc. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| #include "thermal_collector.h" | ||
|
|
||
| #include <android/log.h> | ||
| #include <android/thermal.h> | ||
| #include <poll.h> | ||
|
|
||
| #include <algorithm> | ||
| #include <charconv> | ||
| #include <cmath> | ||
| #include <csignal> | ||
| #include <cstdlib> | ||
| #include <cstring> | ||
| #include <map> | ||
| #include <optional> | ||
| #include <string_view> | ||
|
|
||
| #include "perfetto/perfetto.h" | ||
|
|
||
| PERFETTO_DEFINE_CATEGORIES( | ||
| perfetto::Category(apa::thermal::ThermalConstants::kTrackEventCategory).SetDescription("Framework thermal status and headroom")); | ||
|
|
||
| PERFETTO_TRACK_EVENT_STATIC_STORAGE(); | ||
|
|
||
| namespace apa::thermal { | ||
| namespace { | ||
|
|
||
| constexpr const char* kLogTag = "ThermalMonitor"; | ||
|
|
||
| // Queries the Android framework's thermal state via the NDK AThermal API in libandroid.so. | ||
| // The binary targets API 31 (see scripts/android.py), which covers everything except | ||
| // AThermal_getThermalHeadroomThresholds() (API 35). That symbol is weakly linked | ||
| // (__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__) and guarded by __builtin_available. | ||
| class NdkThermalSource final : public ThermalSource { | ||
| public: | ||
| NdkThermalSource() : manager_(AThermal_acquireManager()) {} | ||
|
|
||
| ~NdkThermalSource() override { | ||
| if (manager_ != nullptr) { | ||
| AThermal_releaseManager(manager_); | ||
| } | ||
| } | ||
|
|
||
| NdkThermalSource(const NdkThermalSource&) = delete; | ||
| NdkThermalSource& operator=(const NdkThermalSource&) = delete; | ||
|
|
||
| [[nodiscard]] bool IsValid() const { return manager_ != nullptr; } | ||
|
|
||
| std::optional<AThermalStatus> CurrentThermalStatus() override { | ||
| const AThermalStatus status = AThermal_getCurrentThermalStatus(manager_); | ||
| if (status < ATHERMAL_STATUS_NONE || status > ATHERMAL_STATUS_SHUTDOWN) { | ||
| return std::nullopt; | ||
| } | ||
| return status; | ||
| } | ||
|
|
||
| std::optional<float> ThermalHeadroom(int forecast_seconds) override { | ||
| const float headroom = AThermal_getThermalHeadroom(manager_, forecast_seconds); | ||
| if (std::isnan(headroom)) { | ||
| return std::nullopt; | ||
| } | ||
| return headroom; | ||
| } | ||
|
|
||
| std::map<AThermalStatus, float> ThermalHeadroomThresholds() override { | ||
| std::map<AThermalStatus, float> result; | ||
| // AThermal_getThermalHeadroomThresholds() was added in Android 15 (API 35). Older versions | ||
| // cannot report thresholds, so they get an empty map. | ||
| if (__builtin_available(android 35, *)) { | ||
| const AThermalHeadroomThreshold* thresholds = nullptr; | ||
| size_t size = 0; | ||
| if (AThermal_getThermalHeadroomThresholds(manager_, &thresholds, &size) != 0 || thresholds == nullptr) { | ||
| return result; | ||
| } | ||
| for (size_t i = 0; i < size; ++i) { | ||
| const AThermalStatus status = thresholds[i].thermalStatus; | ||
| if (status >= ATHERMAL_STATUS_NONE && status <= ATHERMAL_STATUS_SHUTDOWN) { | ||
| result[status] = thresholds[i].headroom; | ||
| } | ||
| } | ||
| // The NDK allocates the array and documents that the client array-deletes it. | ||
| delete[] thresholds; | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| private: | ||
| AThermalManager* manager_ = nullptr; | ||
| }; | ||
|
|
||
| // Emits the headroom thresholds at the start of every tracing session that enables the category. | ||
| // The thresholds never change, so emitting them once per session is enough, and the monitor can be | ||
| // started before tracing is. | ||
| class ThresholdSessionObserver final : public perfetto::TrackEventSessionObserver { | ||
| public: | ||
| explicit ThresholdSessionObserver(const ThermalCollector& collector) : collector_(collector) { | ||
| perfetto::TrackEvent::AddSessionObserver(this); | ||
| } | ||
|
|
||
| ~ThresholdSessionObserver() override { perfetto::TrackEvent::RemoveSessionObserver(this); } | ||
|
|
||
| ThresholdSessionObserver(const ThresholdSessionObserver&) = delete; | ||
| ThresholdSessionObserver& operator=(const ThresholdSessionObserver&) = delete; | ||
|
|
||
| void OnStart(const perfetto::DataSourceBase::StartArgs&) override { collector_.EmitThresholds(); } | ||
|
|
||
| private: | ||
| const ThermalCollector& collector_; | ||
| }; | ||
|
|
||
| void EmitCounter(const char* name, double value) { | ||
| // The names are ThermalConstants string literals, so they outlive the track. | ||
| TRACE_COUNTER(ThermalConstants::kTrackEventCategory, perfetto::CounterTrack(perfetto::StaticString{name}), value); | ||
| } | ||
|
|
||
| volatile std::sig_atomic_t g_stop_requested = 0; | ||
|
|
||
| void HandleStopSignal(int /*signum*/) { g_stop_requested = 1; } | ||
|
|
||
| std::optional<int> ParseInt(std::string_view str) { | ||
| int value = 0; | ||
| const char* begin = str.data(); | ||
| const char* end = begin + str.size(); | ||
| const auto [ptr, ec] = std::from_chars(begin, end, value); | ||
| if (ec != std::errc() || ptr != end) { | ||
| return std::nullopt; | ||
| } | ||
| return value; | ||
| } | ||
|
|
||
| struct Options { | ||
| int poll_interval_ms = ThermalConstants::kDefaultPollIntervalMs; | ||
| int forecast_seconds = ThermalConstants::kDefaultForecastSeconds; | ||
| }; | ||
|
|
||
| // Reads the value that follows argv[*i] into *out, logging an error and exiting when it is missing | ||
| // or malformed. | ||
| void ParseIntOption(int argc, char** argv, int* i, int* out) { | ||
| const char* flag = argv[*i]; | ||
| if (*i + 1 >= argc) { | ||
| __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Missing value for %s", flag); | ||
| std::exit(1); | ||
| } | ||
| const char* value = argv[++*i]; | ||
| if (const std::optional<int> parsed = ParseInt(value); parsed.has_value()) { | ||
| *out = *parsed; | ||
| return; | ||
| } | ||
| __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Invalid value '%s' for %s", value, flag); | ||
| std::exit(1); | ||
| } | ||
|
|
||
| Options ParseOptions(int argc, char** argv) { | ||
| Options options; | ||
| for (int i = 1; i < argc; ++i) { | ||
| if (std::strcmp(argv[i], "--poll-interval-ms") == 0) { | ||
| ParseIntOption(argc, argv, &i, &options.poll_interval_ms); | ||
| } else if (std::strcmp(argv[i], "--forecast-seconds") == 0) { | ||
| ParseIntOption(argc, argv, &i, &options.forecast_seconds); | ||
| } else { | ||
| __android_log_print(ANDROID_LOG_ERROR, kLogTag, "Unknown argument '%s'", argv[i]); | ||
| std::exit(1); | ||
| } | ||
| } | ||
| options.poll_interval_ms = std::max(options.poll_interval_ms, ThermalConstants::kMinPollIntervalMs); | ||
| options.forecast_seconds = std::clamp(options.forecast_seconds, 0, ThermalConstants::kMaxForecastSeconds); | ||
| return options; | ||
| } | ||
|
|
||
| } // namespace | ||
| } // namespace apa::thermal | ||
|
|
||
| int main(int argc, char** argv) { | ||
| using namespace apa::thermal; | ||
|
|
||
| struct sigaction sa = {}; | ||
| sa.sa_handler = HandleStopSignal; | ||
| sigemptyset(&sa.sa_mask); | ||
| sigaction(SIGTERM, &sa, nullptr); | ||
| sigaction(SIGINT, &sa, nullptr); | ||
|
|
||
| const Options options = ParseOptions(argc, argv); | ||
|
|
||
| NdkThermalSource source; | ||
| if (!source.IsValid()) { | ||
| __android_log_print(ANDROID_LOG_WARN, kLogTag, "AThermalManager is unavailable on this device"); | ||
| return 0; | ||
| } | ||
|
|
||
| perfetto::TracingInitArgs args; | ||
| args.backends = perfetto::kSystemBackend; | ||
| perfetto::Tracing::Initialize(args); | ||
| perfetto::TrackEvent::Register(); | ||
|
|
||
| ThermalCollector collector(source, EmitCounter, options.forecast_seconds); | ||
| ThresholdSessionObserver observer(collector); | ||
| // OnStart() only reports sessions that start after the observer is added. | ||
| collector.EmitThresholds(); | ||
|
jimblacklercorp marked this conversation as resolved.
Resolved
|
||
|
|
||
| while (!g_stop_requested) { | ||
| collector.Sample(); | ||
| if (g_stop_requested) { | ||
| break; | ||
| } | ||
| poll(nullptr, 0, options.poll_interval_ms); | ||
| } | ||
|
|
||
| // Commits the last samples to the tracing service before the process exits. | ||
| perfetto::TrackEvent::Flush(); | ||
| return 0; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| # Copyright (C) 2026 Google Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| add_executable(test_thermal_collector test_thermal_collector.cpp) | ||
|
emrekultursay marked this conversation as resolved.
Resolved
|
||
| target_link_libraries(test_thermal_collector PRIVATE thermal_collector GTest::gtest GTest::gtest_main) | ||
| add_test(NAME test_thermal_collector COMMAND test_thermal_collector) | ||
| set_target_properties(test_thermal_collector PROPERTIES FOLDER "thermal_monitor/Test") | ||
|
|
||
| if(WIN32 AND (QT_TARGET_TYPE STREQUAL STATIC_LIBRARY)) | ||
| set_property(TARGET test_thermal_collector PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>") | ||
| endif() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.