[core] Add Component::status_comm_result (#20863)

This commit is contained in:
J. Nick Koston
2026-10-17 16:31:17 -10:00
committed by GitHub
parent ee117886b9
commit 1307faef06
3 changed files with 44 additions and 0 deletions
+9
View File
@@ -290,6 +290,15 @@ void Component::status_set_warning(const LogString *message) {
ESP_LOGW(TAG, "%s set Warning flag: %s", LOG_STR_ARG(this->get_component_log_str()),
message ? LOG_STR_ARG(message) : LOG_STR_LITERAL("unspecified"));
}
bool Component::status_comm_result(bool ok) { return this->status_comm_result(ok, LOG_STR(ESP_LOG_MSG_COMM_FAIL)); }
bool Component::status_comm_result(bool ok, const LogString *message) {
if (ok) {
this->status_clear_warning();
} else {
this->status_set_warning(message);
}
return ok;
}
void Component::status_set_error() { this->status_set_error((const LogString *) nullptr); }
void Component::status_set_error(const LogString *message) {
if (this->set_error_flag_(message) && message != nullptr) {
+5
View File
@@ -285,6 +285,11 @@ class Component {
void status_set_warning(const char *message);
void status_set_warning(const LogString *message);
/// Clears the warning when `ok`, else sets it with `message` (default "Communication failed"); returns `ok`.
/// Replaces the `if (!read()) { status_set_warning(...); return; } status_clear_warning();` pattern.
bool status_comm_result(bool ok);
bool status_comm_result(bool ok, const LogString *message);
void status_set_error(); // Set error flag without message
void status_set_error(const LogString *message);
@@ -0,0 +1,30 @@
#include <gtest/gtest.h>
#include "esphome/core/component.h"
#include "esphome/core/log.h"
namespace esphome {
TEST(StatusCommResult, FailureSetsWarningAndSuccessClearsIt) {
Component component;
EXPECT_FALSE(component.status_comm_result(false));
EXPECT_TRUE(component.status_has_warning());
EXPECT_TRUE(component.status_comm_result(true));
EXPECT_FALSE(component.status_has_warning());
}
TEST(StatusCommResult, CustomMessageOverload) {
Component component;
EXPECT_FALSE(component.status_comm_result(false, LOG_STR("Bad CRC")));
EXPECT_TRUE(component.status_has_warning());
EXPECT_TRUE(component.status_comm_result(true, LOG_STR("Bad CRC")));
EXPECT_FALSE(component.status_has_warning());
}
TEST(StatusCommResult, SuccessWithoutWarningStaysClear) {
Component component;
EXPECT_TRUE(component.status_comm_result(true));
EXPECT_FALSE(component.status_has_warning());
}
} // namespace esphome