Compare commits

..
12 changed files with 235 additions and 197 deletions

No files matched your search

+18 -8
View File
@@ -1,5 +1,7 @@
#include "i2c.h"
#include <span>
#include "esphome/core/defines.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
@@ -9,17 +11,25 @@ namespace esphome::i2c {
ESPHOME_LOG_TAG(TAG, "i2c");
// Addresses 0x08 to 0x77; the others are reserved
static constexpr uint8_t SCAN_FIRST_ADDRESS = 0x08;
static constexpr uint8_t SCAN_END_ADDRESS = 0x78;
static constexpr uint8_t SCAN_RESULT_ERROR = 0x80;
void I2CBus::i2c_scan_() {
for (uint8_t address = 8; address != 120; address++) {
auto err = write_readv(address, nullptr, 0, nullptr, 0);
uint8_t results[SCAN_END_ADDRESS - SCAN_FIRST_ADDRESS];
size_t count = 0;
for (uint8_t address = SCAN_FIRST_ADDRESS; address != SCAN_END_ADDRESS; address++) {
auto err = this->write_readv(address, nullptr, 0, nullptr, 0);
if (err == ERROR_OK) {
scan_results_.emplace_back(address, true);
results[count++] = address;
} else if (err == ERROR_UNKNOWN) {
scan_results_.emplace_back(address, false);
results[count++] = address | SCAN_RESULT_ERROR;
}
// it takes 16sec to scan on nrf52. It prevents board reset.
arch_feed_wdt();
}
this->scan_results_.set(results, count);
}
void I2CBus::dump_scan_results_() {
@@ -30,11 +40,11 @@ void I2CBus::dump_scan_results_() {
ESP_LOGCONFIG(TAG, "Found no devices");
return;
}
for (const auto &s : this->scan_results_) {
if (s.second) {
ESP_LOGCONFIG(TAG, "Found device at address 0x%02X", s.first);
for (uint8_t result : std::span<const uint8_t>(this->scan_results_)) {
if (result & SCAN_RESULT_ERROR) {
ESP_LOGE(TAG, "Unknown error at address 0x%02X", result & ~SCAN_RESULT_ERROR);
} else {
ESP_LOGE(TAG, "Unknown error at address 0x%02X", s.first);
ESP_LOGCONFIG(TAG, "Found device at address 0x%02X", result);
}
}
}
+4 -6
View File
@@ -1,8 +1,6 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <utility>
#include <vector>
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
@@ -64,13 +62,13 @@ class I2CBus {
#endif
protected:
/// @brief Scans the I2C bus for devices. Devices presence is kept in an array of std::pair
/// that contains the address and the corresponding bool presence flag.
/// @brief Scans the I2C bus and keeps each address that answered (ERROR_OK) or returned ERROR_UNKNOWN
void i2c_scan_();
/// @brief Logs the scan results at config level, if the bus was scanned
void dump_scan_results_();
std::vector<std::pair<uint8_t, bool>> scan_results_; ///< array containing scan results
bool scan_{false}; ///< Should we scan ? Can be set in the yaml
/// One byte per kept address, bit 7 set for ERROR_UNKNOWN; inline for up to 4 devices
SmallInlineBuffer<4> scan_results_;
bool scan_{false}; ///< Should we scan ? Can be set in the yaml
};
class InternalI2CBus : public I2CBus {
+66 -33
View File
@@ -11,12 +11,13 @@ from esphome.const import (
CONF_ON_ERROR,
CONF_OTA,
CONF_PLATFORM,
CONF_TRIGGER_ID,
PlatformFramework,
)
from esphome.core import CORE, coroutine_with_priority
from esphome.coroutine import CoroPriority
from esphome.cpp_generator import MockObj
from esphome.types import ConfigType, TemplateArgsType
from esphome.types import ConfigType
OTA_STATE_LISTENER_KEY = "ota_state_listener"
@@ -44,25 +45,14 @@ CONF_ON_PROGRESS = "on_progress"
ota_ns = cg.esphome_ns.namespace("ota")
OTAComponent = ota_ns.class_("OTAComponent", cg.Component)
OTAState = ota_ns.enum("OTAState")
_request_state_callback_slot = cg.slot_counter("OTA_STATE_CALLBACK_COUNT")
# Callback parameters, shared by every key and every OTA component
_STATE_CALLBACK_PARAMS: TemplateArgsType = [
(OTAState, "state"),
(cg.float_, "progress"),
(cg.uint8, "error"),
(OTAComponent.operator("ptr"), "component"),
]
# conf key: (automation args, forwarded expressions, state filter)
_STATE_AUTOMATIONS: dict[str, tuple[TemplateArgsType, list[str], MockObj | None]] = {
CONF_ON_STATE_CHANGE: ([(OTAState, "state")], ["state"], None),
CONF_ON_ABORT: ([], [], ota_ns.OTA_ABORT),
CONF_ON_BEGIN: ([], [], ota_ns.OTA_STARTED),
CONF_ON_PROGRESS: ([(cg.float_, "x")], ["progress"], ota_ns.OTA_IN_PROGRESS),
CONF_ON_END: ([], [], ota_ns.OTA_COMPLETED),
CONF_ON_ERROR: ([(cg.uint8, "x")], ["error"], ota_ns.OTA_ERROR),
}
OTAAbortTrigger = ota_ns.class_("OTAAbortTrigger", automation.Trigger.template())
OTAEndTrigger = ota_ns.class_("OTAEndTrigger", automation.Trigger.template())
OTAErrorTrigger = ota_ns.class_("OTAErrorTrigger", automation.Trigger.template())
OTAProgressTrigger = ota_ns.class_("OTAProgressTrigger", automation.Trigger.template())
OTAStartTrigger = ota_ns.class_("OTAStartTrigger", automation.Trigger.template())
OTAStateChangeTrigger = ota_ns.class_(
"OTAStateChangeTrigger", automation.Trigger.template()
)
def _ota_final_validate(config: ConfigType) -> None:
@@ -75,7 +65,38 @@ def _ota_final_validate(config: ConfigType) -> None:
FINAL_VALIDATE_SCHEMA = _ota_final_validate
BASE_OTA_SCHEMA = cv.Schema(
{cv.Optional(key): automation.validate_automation({}) for key in _STATE_AUTOMATIONS}
{
cv.Optional(CONF_ON_STATE_CHANGE): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAStateChangeTrigger),
}
),
cv.Optional(CONF_ON_ABORT): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAAbortTrigger),
}
),
cv.Optional(CONF_ON_BEGIN): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAStartTrigger),
}
),
cv.Optional(CONF_ON_END): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAEndTrigger),
}
),
cv.Optional(CONF_ON_ERROR): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAErrorTrigger),
}
),
cv.Optional(CONF_ON_PROGRESS): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OTAProgressTrigger),
}
),
}
)
@@ -91,18 +112,30 @@ async def to_code(config: ConfigType) -> None:
async def ota_to_code(var: MockObj, config: ConfigType) -> None:
await cg.past_safe_mode()
use_state_callback = False
for key, (args, forward, state) in _STATE_AUTOMATIONS.items():
# Checked per callback, as each trigger did, so one that marks it failed stops the rest
when = "component == {parent} && !component->is_failed()"
if state is not None:
when += f" && state == {state}"
for conf in config.get(key, []):
_request_state_callback_slot()
callback = await automation.build_trigger_callback(
args, conf, _STATE_CALLBACK_PARAMS, forward, when, var
)
cg.add(MockObj(f"{OTAComponent}::add_state_callback")(callback))
use_state_callback = True
for conf in config.get(CONF_ON_STATE_CHANGE, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [(OTAState, "state")], conf)
use_state_callback = True
for conf in config.get(CONF_ON_ABORT, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
use_state_callback = True
for conf in config.get(CONF_ON_BEGIN, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
use_state_callback = True
for conf in config.get(CONF_ON_PROGRESS, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [(float, "x")], conf)
use_state_callback = True
for conf in config.get(CONF_ON_END, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
use_state_callback = True
for conf in config.get(CONF_ON_ERROR, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [(cg.uint8, "x")], conf)
use_state_callback = True
if use_state_callback:
request_ota_state_listeners()
+70
View File
@@ -0,0 +1,70 @@
#pragma once
#ifdef USE_OTA_STATE_LISTENER
#include "ota_backend.h"
#include "esphome/core/automation.h"
namespace esphome::ota {
class OTAStateChangeTrigger final : public Trigger<OTAState>, public OTAStateListener {
public:
explicit OTAStateChangeTrigger(OTAComponent *parent) : parent_(parent) { parent->add_state_listener(this); }
void on_ota_state(OTAState state, float progress, uint8_t error) override {
if (!this->parent_->is_failed()) {
this->trigger(state);
}
}
protected:
OTAComponent *parent_;
};
template<OTAState State> class OTAStateTrigger final : public Trigger<>, public OTAStateListener {
public:
explicit OTAStateTrigger(OTAComponent *parent) : parent_(parent) { parent->add_state_listener(this); }
void on_ota_state(OTAState state, float progress, uint8_t error) override {
if (state == State && !this->parent_->is_failed()) {
this->trigger();
}
}
protected:
OTAComponent *parent_;
};
using OTAStartTrigger = OTAStateTrigger<OTA_STARTED>;
using OTAEndTrigger = OTAStateTrigger<OTA_COMPLETED>;
using OTAAbortTrigger = OTAStateTrigger<OTA_ABORT>;
class OTAProgressTrigger final : public Trigger<float>, public OTAStateListener {
public:
explicit OTAProgressTrigger(OTAComponent *parent) : parent_(parent) { parent->add_state_listener(this); }
void on_ota_state(OTAState state, float progress, uint8_t error) override {
if (state == OTA_IN_PROGRESS && !this->parent_->is_failed()) {
this->trigger(progress);
}
}
protected:
OTAComponent *parent_;
};
class OTAErrorTrigger final : public Trigger<uint8_t>, public OTAStateListener {
public:
explicit OTAErrorTrigger(OTAComponent *parent) : parent_(parent) { parent->add_state_listener(this); }
void on_ota_state(OTAState state, float progress, uint8_t error) override {
if (state == OTA_ERROR && !this->parent_->is_failed()) {
this->trigger(error);
}
}
protected:
OTAComponent *parent_;
};
} // namespace esphome::ota
#endif
-9
View File
@@ -89,12 +89,6 @@ void UpdateLock::release() {
void UpdateLock::force_release() { update_lock_clear(); }
#ifdef USE_OTA_STATE_LISTENER
#ifdef OTA_STATE_CALLBACK_COUNT
// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
StaticCallbackManager<OTA_STATE_CALLBACK_COUNT, void(OTAState, float, uint8_t, OTAComponent *)>
OTAComponent::state_callbacks;
#endif
OTAGlobalCallback *global_ota_callback{nullptr}; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
OTAGlobalCallback *get_global_ota_callback() {
@@ -118,9 +112,6 @@ void OTAComponent::notify_state_deferred_(OTAState state, float progress, uint8_
}
void OTAComponent::notify_state_(OTAState state, float progress, uint8_t error) {
#ifdef OTA_STATE_CALLBACK_COUNT
state_callbacks.call(state, progress, error, this);
#endif
for (auto *listener : this->state_listeners_) {
listener->on_ota_state(state, progress, error);
}
-10
View File
@@ -160,12 +160,6 @@ class OTAComponent : public Component {
#ifdef USE_OTA_STATE_LISTENER
public:
void add_state_listener(OTAStateListener *listener) { this->state_listeners_.push_back(listener); }
#ifdef OTA_STATE_CALLBACK_COUNT
/// For the generated on_* automations: codegen sizes the list, so other code should use add_state_listener().
/// One list serves every OTA component and runs before the listeners; each callback checks component and
/// is_failed() itself.
template<typename F> static void add_state_callback(F &&callback) { state_callbacks.add(std::forward<F>(callback)); }
#endif
protected:
void notify_state_(OTAState state, float progress, uint8_t error);
@@ -178,10 +172,6 @@ class OTAComponent : public Component {
void notify_state_deferred_(OTAState state, float progress, uint8_t error);
std::vector<OTAStateListener *> state_listeners_;
#ifdef OTA_STATE_CALLBACK_COUNT
static StaticCallbackManager<OTA_STATE_CALLBACK_COUNT, void(OTAState, float, uint8_t, OTAComponent *)>
state_callbacks; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#endif
#endif
};
-1
View File
@@ -321,7 +321,6 @@
#define USE_NEXTION_WAVEFORM
#define USE_NUMBER
#define USE_OTA_STATE_LISTENER
#define OTA_STATE_CALLBACK_COUNT 2
#define USE_OUTPUT
#define USE_OUTPUT_FLOAT_POWER_SCALING
#define PACKET_INTERFACE_ADDRESSING_PORT_COUNT 2
@@ -159,5 +159,5 @@ def test_safe_mode_keeps_the_ble_trigger(
"App.register_component_(adafruit_ble_otacomponent_id",
):
assert main_cpp.index(registration) < guard
for automation in ("->add_passkey_callback(", "OTAComponent::add_state_callback("):
for automation in ("->add_passkey_callback(", "new(ota_otastarttrigger_id)"):
assert main_cpp.index(automation) > guard
@@ -41,26 +41,9 @@ def test_ota_automations_generated(generate_main: Callable[[str], str]) -> None:
assert "USE_OTA_STATE_LISTENER" in _defines()
def test_ota_automations_are_callbacks(generate_main: Callable[[str], str]) -> None:
"""Each automation is one callback on the list every OTA component shares,
filtered on its component and state; the list is sized for all of them."""
main_cpp = generate_main(AUTOMATIONS_YAML)
assert main_cpp.count("ota::OTAComponent::add_state_callback(") == 10
assert main_cpp.count("component == ::ota_native") == 7
assert main_cpp.count("component == ::ota_web") == 2
assert main_cpp.count("component == ::ota_http") == 1
assert main_cpp.count("!component->is_failed()") == 10
assert "Trigger" not in main_cpp
assert "__fn(progress);" in main_cpp
assert "__fn(error);" in main_cpp
assert "__fn(state);" in main_cpp
counts = {d.name: str(d.value) for d in CORE.defines}
assert counts["OTA_STATE_CALLBACK_COUNT"] == "10"
def test_ota_without_automations_skips_state_listener(
generate_main: Callable[[str], str],
) -> None:
"""Without automations or listeners the state notifications compile out."""
generate_main(PLAIN_YAML)
assert not {"USE_OTA_STATE_LISTENER", "OTA_STATE_CALLBACK_COUNT"} & _defines()
assert "USE_OTA_STATE_LISTENER" not in _defines()
+75
View File
@@ -0,0 +1,75 @@
#include <gtest/gtest.h>
#include <set>
#include <span>
#include <vector>
#include "esphome/components/i2c/i2c.h"
namespace esphome::i2c::testing {
class ScanBus : public I2CBus {
public:
ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
size_t read_count) override {
this->probed.push_back(address);
if (this->errors.contains(address))
return ERROR_UNKNOWN;
return this->present.contains(address) ? ERROR_OK : ERROR_NOT_ACKNOWLEDGED;
}
void scan() { this->i2c_scan_(); }
std::vector<uint8_t> results() const {
std::span<const uint8_t> span = this->scan_results_;
return {span.begin(), span.end()};
}
std::set<uint8_t> present;
std::set<uint8_t> errors;
std::vector<uint8_t> probed;
};
TEST(I2CScan, ProbesTheUnreservedAddresses) {
ScanBus bus;
bus.scan();
ASSERT_EQ(bus.probed.size(), 112u);
EXPECT_EQ(bus.probed.front(), 0x08);
EXPECT_EQ(bus.probed.back(), 0x77);
EXPECT_TRUE(bus.results().empty());
}
TEST(I2CScan, KeepsFoundAddressesInOrder) {
ScanBus bus;
bus.present = {0x48, 0x10, 0x76, 0x3C};
bus.scan();
EXPECT_EQ(bus.results(), (std::vector<uint8_t>{0x10, 0x3C, 0x48, 0x76}));
}
TEST(I2CScan, MarksUnknownErrorsInBitSeven) {
ScanBus bus;
bus.present = {0x20, 0x77};
bus.errors = {0x08, 0x40};
bus.scan();
EXPECT_EQ(bus.results(), (std::vector<uint8_t>{0x88, 0x20, 0xC0, 0x77}));
}
TEST(I2CScan, StuckBusKeepsAllAddresses) {
ScanBus bus;
for (uint8_t address = 0x08; address < 0x78; address++)
bus.present.insert(address);
bus.scan();
ASSERT_EQ(bus.probed.size(), 112u);
EXPECT_EQ(bus.results(), bus.probed);
}
TEST(I2CScan, RescanReplacesTheResults) {
ScanBus bus;
bus.present = {0x10, 0x20, 0x30, 0x40, 0x50};
bus.scan();
EXPECT_EQ(bus.results(), (std::vector<uint8_t>{0x10, 0x20, 0x30, 0x40, 0x50}));
bus.present = {0x60};
bus.scan();
EXPECT_EQ(bus.results(), (std::vector<uint8_t>{0x60}));
}
} // namespace esphome::i2c::testing
-12
View File
@@ -1,12 +0,0 @@
import esphome.codegen as cg
from esphome.types import ConfigType
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# The real to_code requests these from ota_to_code when on_* automations are configured
async def to_code_testing(config: ConfigType) -> None:
cg.add_define("USE_OTA_STATE_LISTENER")
cg.add_define("OTA_STATE_CALLBACK_COUNT", 5)
manifest.to_code = to_code_testing
@@ -1,99 +0,0 @@
#include <gtest/gtest.h>
#include <vector>
#include "esphome/components/ota/ota_backend.h"
namespace esphome::ota::testing {
struct Event {
char source;
OTAState state;
float progress;
uint8_t error;
};
static std::vector<Event> events; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
class RecordingListener : public OTAStateListener {
public:
void on_ota_state(OTAState state, float progress, uint8_t error) override {
events.push_back({'l', state, progress, error});
}
};
class TestOTAComponent : public OTAComponent {
public:
using OTAComponent::notify_state_;
void fail() { this->mark_failed(); }
};
// The callback list is shared by every OTA component and cannot be cleared, so the
// callbacks are registered once, each filtering on its component like the generated ones.
static TestOTAComponent first_ota; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
static TestOTAComponent second_ota; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
static TestOTAComponent failed_ota; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
static RecordingListener listener; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
class OTAStateCallback : public ::testing::Test {
protected:
static void SetUpTestSuite() {
OTAComponent::add_state_callback([](OTAState state, float progress, uint8_t error, OTAComponent *component) {
if (component == &first_ota)
events.push_back({'a', state, progress, error});
});
OTAComponent::add_state_callback([](OTAState state, float progress, uint8_t error, OTAComponent *component) {
if (component == &first_ota)
events.push_back({'b', state, progress, error});
});
OTAComponent::add_state_callback([](OTAState state, float progress, uint8_t error, OTAComponent *component) {
if (component == &second_ota)
events.push_back({'s', state, progress, error});
});
// Like the generated callbacks: the first marks the component failed, the second checks it first
OTAComponent::add_state_callback([](OTAState state, float progress, uint8_t error, OTAComponent *component) {
if (component == &failed_ota && !component->is_failed()) {
events.push_back({'f', state, progress, error});
failed_ota.fail();
}
});
OTAComponent::add_state_callback([](OTAState state, float progress, uint8_t error, OTAComponent *component) {
if (component == &failed_ota && !component->is_failed())
events.push_back({'g', state, progress, error});
});
first_ota.add_state_listener(&listener);
failed_ota.add_state_listener(&listener);
}
void SetUp() override { events.clear(); }
};
TEST_F(OTAStateCallback, ForwardsStateProgressAndError) {
second_ota.notify_state_(OTA_IN_PROGRESS, 42.5f, 0);
second_ota.notify_state_(OTA_ERROR, 0.0f, OTA_RESPONSE_ERROR_UPDATE_END);
ASSERT_EQ(events.size(), 2U);
EXPECT_EQ(events[0].source, 's');
EXPECT_EQ(events[0].state, OTA_IN_PROGRESS);
EXPECT_FLOAT_EQ(events[0].progress, 42.5f);
EXPECT_EQ(events[1].state, OTA_ERROR);
EXPECT_EQ(events[1].error, OTA_RESPONSE_ERROR_UPDATE_END);
}
TEST_F(OTAStateCallback, EveryCallbackRunsBeforeTheListeners) {
first_ota.notify_state_(OTA_STARTED, 0.0f, 0);
ASSERT_EQ(events.size(), 3U);
EXPECT_EQ(events[0].source, 'a');
EXPECT_EQ(events[1].source, 'b');
EXPECT_EQ(events[2].source, 'l');
}
TEST_F(OTAStateCallback, MarkingFailedStopsLaterCallbacksButListenersStillRun) {
failed_ota.notify_state_(OTA_STARTED, 0.0f, 0);
ASSERT_EQ(events.size(), 2U);
EXPECT_EQ(events[0].source, 'f');
EXPECT_EQ(events[1].source, 'l');
failed_ota.notify_state_(OTA_STARTED, 0.0f, 0);
ASSERT_EQ(events.size(), 3U);
EXPECT_EQ(events[2].source, 'l');
}
} // namespace esphome::ota::testing