Compare commits

...
Author SHA1 Message Date
J. Nick Koston 8690450d97 Merge branch 'interval-direct-callback' into interval-period-uint32 2026-11-04 18:35:42 -06:00
J. Nick Koston 3ea0067b8d Merge branch 'interval-tests' into interval-direct-callback 2026-11-04 18:35:41 -06:00
J. Nick Koston 7d8b9c31b2 Merge branch 'on-boot-direct-callback' into interval-tests 2026-11-04 18:35:40 -06:00
J. Nick Koston d9d8518171 Merge remote-tracking branch 'origin/dev' into on-boot-direct-callback
# Conflicts:
#	esphome/cpp_generator.py
#	tests/unit_tests/test_cpp_generator.py
2026-11-04 18:34:31 -06:00
J. Nick Koston cd4933652e Merge interval-direct-callback 2026-11-02 09:58:33 -06:00
J. Nick Koston 76c51140b1 Merge interval-tests 2026-11-02 09:55:13 -06:00
J. Nick Koston e6f6c0f09b Merge on-boot-direct-callback 2026-11-02 09:46:22 -06:00
J. Nick Koston 7815874624 Merge dev 2026-11-02 09:46:07 -06:00
J. Nick Koston d9082378c5 Update the interval codegen tests for intervals with a startup delay 2026-11-02 09:34:59 -06:00
J. Nick Koston 95f7423424 Merge dev 2026-11-02 09:33:12 -06:00
J. Nick Koston fef7a15521 Merge on-boot-direct-callback 2026-11-02 09:33:06 -06:00
J. Nick Koston 0b6fc2c3c5 Merge remote-tracking branch 'upstream/dev' into on-boot-direct-callback
# Conflicts:
#	tests/component_tests/automation/test_core_automations.py
2026-10-31 07:09:54 -10:00
J. Nick Koston 352383fa15 Keep UINT32_MAX out of range, since it means never run, and check the rejection cause 2026-10-30 22:16:39 -10:00
J. Nick Koston ea6daacd26 [interval] Reject an interval or startup delay that does not fit uint32_t milliseconds 2026-10-30 22:12:00 -10:00
J. Nick Koston 8bda76cc75 Cut the interval startup delay to 32 bits as the setter did 2026-10-30 22:05:30 -10:00
J. Nick Koston 008da6dceb Share the interval startup delay and decide the hand-set id path in one place 2026-10-30 22:00:06 -10:00
J. Nick Koston 163f6fff55 Merge branch 'interval-tests' into interval-direct-callback
# Conflicts:
#	tests/component_tests/automation/test_core_automations.py
2026-10-30 21:54:03 -10:00
J. Nick Koston 15810c176c Include application.h for HasLoopOverride and check that resume runs the interval again 2026-10-30 21:52:58 -10:00
J. Nick Koston 436baa9375 Merge remote-tracking branch 'origin/on-boot-direct-callback' into interval-tests 2026-10-30 21:50:33 -10:00
J. Nick Koston 4705fbb703 Merge remote-tracking branch 'origin/on-boot-tests' into on-boot-direct-callback
# Conflicts:
#	tests/component_tests/automation/test_core_automations.py
2026-10-30 21:46:06 -10:00
J. Nick Koston b382723e9d [interval] Call the generated function from a small PollingComponent
An interval without a hand-set id now builds IntervalCallback<fn> (or
DelayedIntervalCallback<fn, delay>), whose update() calls a generated
function. When every action is inline that function runs them, so the
Trigger, Automation and action objects go away. build_component_automation
takes the id key and extra template arguments for this.
2026-10-30 21:43:54 -10:00
J. Nick Koston ce70abbbb4 Pin that the delayed boot step runs after setup and find automations by trigger 2026-10-30 21:42:15 -10:00
J. Nick Koston 6b5ae000d6 Give the named interval a startup delay 2026-10-30 21:41:24 -10:00
J. Nick Koston 2cfd2a8f51 [interval] Add tests for interval code generation
Pin the IntervalTrigger construction, update interval, startup delay,
registration order and source, setup priority override, and that an
interval runs repeatedly, waits for its startup delay and can be
suspended by id.
2026-10-30 21:35:07 -10:00
J. Nick Koston 77574a50eb Share static_function's declare and define steps and the priority bit cast 2026-10-30 21:34:12 -10:00
J. Nick Koston c52beb6d5e Fold the priority to a constant on every toolchain and share one loop
GCC 10 does not inline the bit_cast fallback at -Os and IDF builds memcpy
as a call, so read the bits with __builtin_memcpy.
2026-10-30 21:25:32 -10:00
J. Nick Koston dde3aaf50e Register the component before its actions are built
Building the actions can wait for ids declared later, so registering after
them moved the block behind other components of the same priority. The
function is now named after the component and declared first; when an
action is not inline it triggers the Automation, so every block without a
hand-set trigger_id uses the small component.
2026-10-30 21:21:50 -10:00
J. Nick Koston 6f7af22b41 Merge branch 'on-boot-tests' into on-boot-direct-callback 2026-10-30 21:20:48 -10:00
J. Nick Koston de0bf34e84 Pin where on_boot registers when its actions wait for other ids 2026-10-30 21:20:45 -10:00
J. Nick Koston 7bd7547983 [core] Run on_boot from a direct setup callback when every action is inline
An on_boot, on_shutdown or on_loop block whose actions are all inline now
builds one small component that calls the generated function from setup(),
on_shutdown() or loop(), instead of a Trigger, an Automation and action
objects. The setup priority is a template argument, so it takes no RAM.
Blocks with a delay, a wait or a trigger_id set by hand keep the Trigger.
2026-10-30 21:16:27 -10:00
J. Nick Koston aae52f2265 [core] Add tests for on_boot code generation and ordering
Pin the code generated today for on_boot, on_shutdown and on_loop
(priorities, registration order, the Trigger kept for a delay or a
trigger_id set by hand) and add an integration test that on_boot blocks
run once in priority order.
2026-10-30 21:05:09 -10:00
20 changed files with 792 additions and 74 deletions

No files matched your search

+60 -2
View File
@@ -5,6 +5,7 @@ import logging
import math
import re
import string
import struct
from typing import Any
import esphome.codegen as cg
@@ -1950,14 +1951,21 @@ def _is_direct(plan: list[MockObj | list[_InlineAction]], config: ConfigType) ->
)
def _direct_statements(
plan: list[MockObj | list[_InlineAction]], config: ConfigType
) -> list[str] | None:
if not _is_direct(plan, config):
return None
return [line for line in _run_statements(plan[0]) if line != _STOP_CHECK]
def _direct_function(
plan: list[MockObj | list[_InlineAction]],
args: TemplateArgsType,
config: ConfigType,
) -> MockObj | None:
if not _is_direct(plan, config):
if (statements := _direct_statements(plan, config)) is None:
return None
statements = [line for line in _run_statements(plan[0]) if line != _STOP_CHECK]
return apply_static_function(
plan[0][0].id_, cg.void, _apply_params(args), statements
)
@@ -1980,6 +1988,56 @@ async def build_automation(
return await new_automation(args, config, trigger)
async def build_component_automation(
config: ConfigType,
component_class: MockObjClass,
priority: float | None = None,
*,
id_key: str = CONF_TRIGGER_ID,
template_args: Sequence[SafeExpType] = (),
trigger_class: MockObjClass | None = None,
trigger_args: Sequence[SafeExpType] = (),
) -> MockObj:
"""Create and register the Component that runs a no-argument automation.
That is ``component_class<function[, priority bits], *template_args>``, whose function runs
the actions directly when they are all inline, else triggers their Automation. An id under
``id_key`` set by hand keeps its Trigger, or ``trigger_class`` if given, built with
``priority`` if given and ``trigger_args`` instead of ``template_args``.
"""
trigger_id: ID = config[id_key]
if trigger_id.is_manual:
if trigger_class is not None:
trigger_id.type = trigger_class
var = cg.new_Pvariable(
trigger_id, *([] if priority is None else [priority]), *trigger_args
)
await cg.register_component(var, config)
await build_automation(var, [], config)
return var
# Declared and registered before the actions are built, which can wait for other ids
name = f"esphome__{trigger_id.id}__fn"
define = cg.declare_static_function(name, cg.void, [])
id_ = trigger_id.copy()
id_.type = component_class
bits = [] if priority is None else [_float_bits(priority)]
var = cg.new_Pvariable(
id_, cg.TemplateArguments(cg.RawExpression(name), *bits, *template_args)
)
await cg.register_component(var, config)
plan = await _build_automation_plan([], config)
if (body := _direct_statements(plan, config)) is None:
body = [f"{parent_ref(_automation_from_plan(plan, [], config))}->trigger();"]
define(body)
return var
def _float_bits(value: float) -> cg.RawExpression:
"""``value`` as a C++ float's bit pattern, for a template argument."""
(bits,) = struct.unpack("<I", struct.pack("<f", value))
return cg.RawExpression(f"0x{bits:08X}u")
async def build_trigger_callback(
args: TemplateArgsType,
config: ConfigType,
+1
View File
@@ -31,6 +31,7 @@ from esphome.cpp_generator import ( # noqa: F401
add_global,
add_library,
add_platformio_option,
declare_static_function,
extern_progmem_array,
get_variable,
get_variable_with_full_id,
+32 -10
View File
@@ -11,15 +11,30 @@ IntervalTrigger = interval_ns.class_(
"IntervalTrigger", automation.Trigger.template(), cg.PollingComponent
)
DelayedIntervalTrigger = interval_ns.class_("DelayedIntervalTrigger", IntervalTrigger)
IntervalCallback = interval_ns.class_("IntervalCallback", cg.PollingComponent)
DelayedIntervalCallback = interval_ns.class_(
"DelayedIntervalCallback", IntervalCallback
)
# Held as uint32_t milliseconds, where UINT32_MAX is SCHEDULER_DONT_RUN (never run)
_MAX_PERIOD_MS = 2**32 - 2
def _uint32_milliseconds() -> cv.All:
"""Built per key, so the language schema keeps the time period type."""
return cv.All(
cv.positive_time_period_milliseconds,
cv.Range(max=cv.TimePeriod(milliseconds=_MAX_PERIOD_MS)),
)
CONFIG_SCHEMA = automation.validate_automation(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(IntervalTrigger),
cv.Optional(
CONF_STARTUP_DELAY, default="0s"
): cv.positive_time_period_milliseconds,
cv.Required(CONF_INTERVAL): cv.positive_time_period_milliseconds,
cv.Optional(CONF_STARTUP_DELAY, default="0s"): _uint32_milliseconds(),
cv.Required(CONF_INTERVAL): _uint32_milliseconds(),
}
).extend(cv.COMPONENT_SCHEMA)
)
@@ -28,11 +43,18 @@ CONFIG_SCHEMA = automation.validate_automation(
async def to_code(config: list[ConfigType]) -> None:
for conf in config:
if startup_delay := conf[CONF_STARTUP_DELAY].total_milliseconds:
conf[CONF_ID].type = DelayedIntervalTrigger
var = cg.new_Pvariable(conf[CONF_ID], startup_delay)
component_class, template_args = DelayedIntervalCallback, [startup_delay]
trigger_class = DelayedIntervalTrigger
else:
var = cg.new_Pvariable(conf[CONF_ID])
await cg.register_component(var, conf)
await automation.build_automation(var, [], conf)
component_class, template_args = IntervalCallback, []
trigger_class = None
var = await automation.build_component_automation(
conf,
component_class,
id_key=CONF_ID,
template_args=template_args,
# A hand-set id keeps a trigger, which takes the delay as a constructor argument
trigger_class=trigger_class,
trigger_args=template_args,
)
cg.add(var.set_update_interval(conf[CONF_INTERVAL]))
+11 -5
View File
@@ -6,7 +6,16 @@
namespace esphome::interval {
class IntervalTrigger : public Trigger<>, public PollingComponent {
/// Base of the interval components; holds the first update back for a startup delay.
class IntervalBase : public PollingComponent {
protected:
void start_after_delay_(uint32_t startup_delay) {
this->stop_poller();
this->set_timeout(startup_delay, [this] { this->start_poller(); });
}
};
class IntervalTrigger : public Trigger<>, public IntervalBase {
public:
void update() override { this->trigger(); }
};
@@ -16,10 +25,7 @@ class DelayedIntervalTrigger final : public IntervalTrigger {
public:
explicit DelayedIntervalTrigger(uint32_t startup_delay) : startup_delay_(startup_delay) {}
void setup() override {
this->stop_poller();
this->set_timeout(this->startup_delay_, [this] { this->start_poller(); });
}
void setup() override { this->start_after_delay_(this->startup_delay_); }
protected:
const uint32_t startup_delay_;
@@ -0,0 +1,19 @@
#pragma once
#include "interval.h"
namespace esphome::interval {
/// Calls Fn from update(), for an interval without a hand-set id.
template<void (*Fn)()> class IntervalCallback : public IntervalBase {
public:
void update() override { Fn(); }
};
/// An IntervalCallback whose first run waits STARTUP_DELAY ms; only used when the delay is not zero.
template<void (*Fn)(), uint32_t STARTUP_DELAY> class DelayedIntervalCallback final : public IntervalCallback<Fn> {
public:
void setup() override { this->start_after_delay_(STARTUP_DELAY); }
};
} // namespace esphome::interval
+30
View File
@@ -171,6 +171,36 @@ class LoopTrigger : public Trigger<>, public Component {
float get_setup_priority() const override { return setup_priority::DATA; }
};
/// The float whose bit pattern is BITS. Folds to a constant; GCC 10's bit_cast fallback is not
/// inlined at -Os, and IDF builds memcpy as a call.
template<uint32_t BITS> ESPHOME_ALWAYS_INLINE inline float float_from_bits() {
const uint32_t bits = BITS;
float value;
__builtin_memcpy(&value, &bits, sizeof(value));
return value;
}
/// Calls Fn from setup(), for on_boot. PRIORITY_BITS is the setup priority's float bit pattern,
/// since GCC 10 (ESP8266) has no float template parameters.
template<void (*Fn)(), uint32_t PRIORITY_BITS> class StartupCallback final : public Component {
public:
void setup() override { Fn(); }
float get_setup_priority() const override { return float_from_bits<PRIORITY_BITS>(); }
};
/// Calls Fn from on_shutdown(), for on_shutdown.
template<void (*Fn)(), uint32_t PRIORITY_BITS> class ShutdownCallback final : public Component {
public:
void on_shutdown() override { Fn(); }
float get_setup_priority() const override { return float_from_bits<PRIORITY_BITS>(); }
};
/// Calls Fn from loop(), for on_loop.
template<void (*Fn)()> class LoopCallback final : public Component {
public:
void loop() override { Fn(); }
};
#ifdef ESPHOME_PROJECT_NAME
class ProjectUpdateTrigger : public Trigger<std::string>, public Component {
public:
+12 -14
View File
@@ -124,6 +124,9 @@ ShutdownTrigger = cg.esphome_ns.class_(
LoopTrigger = cg.esphome_ns.class_(
"LoopTrigger", cg.Component, automation.Trigger.template()
)
StartupCallback = cg.esphome_ns.class_("StartupCallback", cg.Component)
ShutdownCallback = cg.esphome_ns.class_("ShutdownCallback", cg.Component)
LoopCallback = cg.esphome_ns.class_("LoopCallback", cg.Component)
ProjectUpdateTrigger = cg.esphome_ns.class_(
"ProjectUpdateTrigger", cg.Component, automation.Trigger.template(cg.std_string)
)
@@ -785,20 +788,15 @@ async def _add_environment_variables(env_vars: dict[str, str]) -> None:
@coroutine_with_priority(CoroPriority.AUTOMATION)
async def _add_automations(config):
for conf in config.get(CONF_ON_BOOT, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf.get(CONF_PRIORITY))
await cg.register_component(trigger, conf)
await automation.build_automation(trigger, [], conf)
for conf in config.get(CONF_ON_SHUTDOWN, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], conf.get(CONF_PRIORITY))
await cg.register_component(trigger, conf)
await automation.build_automation(trigger, [], conf)
for conf in config.get(CONF_ON_LOOP, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID])
await cg.register_component(trigger, conf)
await automation.build_automation(trigger, [], conf)
for key, component_class in (
(CONF_ON_BOOT, StartupCallback),
(CONF_ON_SHUTDOWN, ShutdownCallback),
(CONF_ON_LOOP, LoopCallback),
):
for conf in config.get(key, []):
await automation.build_component_automation(
conf, component_class, conf.get(CONF_PRIORITY)
)
# Datetime component has special subtypes that need additional defines
+24 -9
View File
@@ -789,14 +789,13 @@ def new_Pvariable(id_: ID, *args: SafeExpType) -> "MockObj":
return Pvariable(id_, rhs)
def static_function(
def declare_static_function(
name: str,
return_type: SafeExpType,
parameters: TemplateArgsType,
body: list[str | Statement],
) -> RawExpression:
"""Emit ``static <return_type> <name>(parameters) { body }`` at global scope and return an
expression naming it, for use as a template argument or a function pointer.
) -> Callable[[list[str | Statement]], RawExpression]:
"""Declare ``static <return_type> <name>(parameters)`` now and return the function that
emits its body, for a caller that names the function before the body is known.
The declaration goes with the other globals, so a template argument can name the function
at once; the body goes after the user includes, where every id and everything those
@@ -806,10 +805,26 @@ def static_function(
f"static {safe_exp(return_type)} {name}({ParameterListExpression(*parameters)})"
)
add_global(RawStatement(f"{signature};"))
add_global_after_includes(
RawStatement(f"{signature} {{\n{indent(chr(10).join(map(str, body)))}\n}}")
)
return RawExpression(name)
def define(body: list[str | Statement]) -> RawExpression:
add_global_after_includes(
RawStatement(f"{signature} {{\n{indent(chr(10).join(map(str, body)))}\n}}")
)
return RawExpression(name)
return define
def static_function(
name: str,
return_type: SafeExpType,
parameters: TemplateArgsType,
body: list[str | Statement],
) -> RawExpression:
"""Emit ``static <return_type> <name>(parameters) { body }`` at global scope and return an
expression naming it, for use as a template argument or a function pointer.
"""
return declare_static_function(name, return_type, parameters)(body)
def add(expression: Expression | Statement, prepend: bool = False):
@@ -6,6 +6,8 @@ import re
import pytest
from tests.component_tests.helpers import constructed, function_body
CONFIG = "core_automations.yaml"
@@ -17,12 +19,6 @@ def main_cpp(
return generate_main(component_config_path(CONFIG))
def _constructed(main_cpp: str, var: str) -> str:
match = re.search(rf"new\({var}\) ([^;]+);", main_cpp)
assert match is not None, var
return match.group(1)
def _automation_of(main_cpp: str, trigger: str) -> str:
"""The Automation built on ``trigger``, found by its trigger rather than an id counter."""
match = re.search(rf"new\((\w+)\) Automation<>\({trigger}\);", main_cpp)
@@ -30,14 +26,6 @@ def _automation_of(main_cpp: str, trigger: str) -> str:
return match.group(1)
def _has_delay(main_cpp: str, trigger: str) -> bool:
automation = _automation_of(main_cpp, trigger)
return (
re.search(rf"{automation}->add_action\(delayaction_id\w*\);", main_cpp)
is not None
)
def _registered(main_cpp: str) -> list[str]:
return re.findall(r"App\.register_component_\((\w+), \d+\);", main_cpp)
@@ -56,40 +44,79 @@ def test_core_automations_registration_order(main_cpp: str) -> None:
]
def _delayed_automation(main_cpp: str, function: str) -> str:
"""The Automation that ``function`` triggers, checked to hold a delay; found through the
function rather than an id counter."""
match = re.fullmatch(
r"\n ::(\w+)->trigger\(\);", function_body(main_cpp, function)
)
assert match is not None, function
automation = match.group(1)
assert f"new({automation}) Automation<>();" in main_cpp
assert re.search(rf"{automation}->add_action\(delayaction_id\w*\);", main_cpp)
return automation
def test_on_boot_inline_priorities(main_cpp: str) -> None:
"""All-inline on_boot blocks keep their configured priority, default 600."""
assert _constructed(main_cpp, "startuptrigger_id") == "StartupTrigger(800.0f)"
assert _constructed(main_cpp, "startuptrigger_id_2") == "StartupTrigger(600.0f)"
_automation_of(main_cpp, "startuptrigger_id")
_automation_of(main_cpp, "startuptrigger_id_2")
"""All-inline on_boot blocks call one function from setup() at their priority, default 600.
The priority is the float's bit pattern: 0x44480000 is 800.0f, 0x44160000 is 600.0f.
"""
assert constructed(main_cpp, "startuptrigger_id") == (
"StartupCallback<esphome__startuptrigger_id__fn, 0x44480000u>()"
)
assert constructed(main_cpp, "startuptrigger_id_2") == (
"StartupCallback<esphome__startuptrigger_id_2__fn, 0x44160000u>()"
)
assert "Automation<>(startuptrigger_id" not in main_cpp
# Both actions of the first block run in the one function, with no stop checks
body = function_body(main_cpp, "esphome__startuptrigger_id__fn")
assert "boot high" in body
assert "boot high lambda" in body
assert "esphome__running" not in body
assert "Automation" not in body
assert "boot default" in function_body(main_cpp, "esphome__startuptrigger_id_2__fn")
def test_on_boot_delay_keeps_trigger(main_cpp: str) -> None:
"""A delay needs the Trigger and its Automation of separate actions."""
assert _constructed(main_cpp, "startuptrigger_id_3") == "StartupTrigger(-100.0f)"
assert _has_delay(main_cpp, "startuptrigger_id_3")
def test_on_boot_delay_triggers_automation(main_cpp: str) -> None:
"""A delay keeps the Automation of separate actions, which the function triggers."""
assert constructed(main_cpp, "startuptrigger_id_3") == (
"StartupCallback<esphome__startuptrigger_id_3__fn, 0xC2C80000u>()"
)
_delayed_automation(main_cpp, "esphome__startuptrigger_id_3__fn")
def test_on_boot_manual_trigger_id_keeps_trigger(main_cpp: str) -> None:
"""A trigger_id set by hand can be used from lambdas, so the Trigger stays."""
assert _constructed(main_cpp, "manual_boot") == "StartupTrigger(250.5f)"
assert constructed(main_cpp, "manual_boot") == "StartupTrigger(250.5f)"
_automation_of(main_cpp, "manual_boot")
def test_on_shutdown_priorities(main_cpp: str) -> None:
"""on_shutdown blocks keep their priority; a delay keeps the Trigger."""
assert _constructed(main_cpp, "shutdowntrigger_id") == "ShutdownTrigger(700.0f)"
_automation_of(main_cpp, "shutdowntrigger_id")
assert _constructed(main_cpp, "shutdowntrigger_id_2") == "ShutdownTrigger(600.0f)"
assert _has_delay(main_cpp, "shutdowntrigger_id_2")
"""on_shutdown calls its function at its priority; a delay keeps the Automation."""
assert constructed(main_cpp, "shutdowntrigger_id") == (
"ShutdownCallback<esphome__shutdowntrigger_id__fn, 0x442F0000u>()"
)
assert "shutdown inline" in function_body(
main_cpp, "esphome__shutdowntrigger_id__fn"
)
assert constructed(main_cpp, "shutdowntrigger_id_2") == (
"ShutdownCallback<esphome__shutdowntrigger_id_2__fn, 0x44160000u>()"
)
_delayed_automation(main_cpp, "esphome__shutdowntrigger_id_2__fn")
def test_on_loop(main_cpp: str) -> None:
"""on_loop blocks are looping components; a delay keeps the Trigger."""
assert _constructed(main_cpp, "looptrigger_id") == "LoopTrigger()"
_automation_of(main_cpp, "looptrigger_id")
assert _constructed(main_cpp, "looptrigger_id_2") == "LoopTrigger()"
assert _has_delay(main_cpp, "looptrigger_id_2")
"""on_loop calls its function each loop; a delay keeps the Automation."""
assert constructed(main_cpp, "looptrigger_id") == (
"LoopCallback<esphome__looptrigger_id__fn>()"
)
assert "loop inline" in function_body(main_cpp, "esphome__looptrigger_id__fn")
assert "HasLoopOverride<LoopCallback<esphome__looptrigger_id__fn>>" in main_cpp
assert constructed(main_cpp, "looptrigger_id_2") == (
"LoopCallback<esphome__looptrigger_id_2__fn>()"
)
_delayed_automation(main_cpp, "esphome__looptrigger_id_2__fn")
def test_on_boot_registered_before_its_actions_are_built(
+14
View File
@@ -40,3 +40,17 @@ def get_define_value(name: str) -> str | None:
if define.name == name:
return str(define.value)
return None
def constructed(main_cpp: str, var: str) -> str:
"""The expression placement-new builds ``var`` with, e.g. ``Foo<bar>()``."""
match = re.search(rf"new\({var}\) ([^;]+);", main_cpp)
assert match is not None, var
return match.group(1)
def function_body(main_cpp: str, name: str) -> str:
"""The body of the generated ``static void name()``."""
match = re.search(rf"static void {name}\(\) \{{(.*?)\n\}}\n", main_cpp, re.DOTALL)
assert match is not None, name
return match.group(1)
@@ -0,0 +1,42 @@
esphome:
name: test
esp32:
board: nodemcu-32s
logger:
interval:
- interval: 1s
then:
- logger.log: inline tick
- lambda: ESP_LOGD("test", "inline lambda");
- interval: 2s
startup_delay: 5s
then:
- logger.log: delayed start tick
- interval: 3s
then:
- logger.log: before delay
- delay: 10ms
- logger.log: after delay
- id: named_interval
interval: 4s
startup_delay: 3s
then:
- logger.log: named tick
- interval: 5s
setup_priority: 250
then:
# The script is declared later, so building this action waits for it
- script.execute: later_script
script:
- id: later_script
then:
- logger.log: script ran
sensor:
- platform: template
id: some_sensor
lambda: return 1.0;
@@ -0,0 +1,13 @@
esphome:
name: test
esp32:
board: esp32dev
logger:
interval:
- interval: 1s
startup_delay: 50d
then:
- logger.log: long delay
@@ -0,0 +1,144 @@
"""Tests for the code generated for interval blocks."""
from collections.abc import Callable
from pathlib import Path
import re
import pytest
from tests.component_tests.helpers import constructed, function_body
CONFIG = "interval_codegen.yaml"
@pytest.fixture
def main_cpp(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> str:
return generate_main(component_config_path(CONFIG))
def _callback(var: str, startup_delay: int = 0) -> str:
if startup_delay:
return (
f"interval::DelayedIntervalCallback<esphome__{var}__fn, {startup_delay}>()"
)
return f"interval::IntervalCallback<esphome__{var}__fn>()"
def _registered(main_cpp: str) -> list[tuple[str, str]]:
return re.findall(r"App\.register_component_\((\w+), (\d+)\);", main_cpp)
def test_interval_registration_order_and_source(main_cpp: str) -> None:
"""Each interval is one component, registered in config order under the interval source."""
registered = _registered(main_cpp)
assert [var for var, _ in registered[-6:]] == [
"interval_intervaltrigger_id",
"interval_intervaltrigger_id_2",
"interval_intervaltrigger_id_3",
"named_interval",
"interval_intervaltrigger_id_4",
"some_sensor",
]
source = re.search(r'COMP_SRC_TABLE_STR_(\d+)\[\] PROGMEM = "interval";', main_cpp)
assert source is not None
assert {index for _, index in registered[-6:-1]} == {str(int(source.group(1)) + 1)}
def test_interval_update_interval_and_startup_delay(main_cpp: str) -> None:
"""Every interval gets its update interval; a non-zero startup delay is built in.
It is a template argument, or the DelayedIntervalTrigger constructor's for a hand-set id.
"""
for var, interval in (
("interval_intervaltrigger_id", 1000),
("interval_intervaltrigger_id_2", 2000),
("interval_intervaltrigger_id_3", 3000),
("named_interval", 4000),
("interval_intervaltrigger_id_4", 5000),
):
assert f"{var}->set_update_interval({interval});" in main_cpp
assert constructed(main_cpp, "interval_intervaltrigger_id_2") == _callback(
"interval_intervaltrigger_id_2", 5000
)
assert (
constructed(main_cpp, "named_interval")
== "interval::DelayedIntervalTrigger(3000)"
)
assert "set_startup_delay" not in main_cpp
def test_interval_setup_priority_override(main_cpp: str) -> None:
"""A setup_priority set on an interval is applied before it is registered."""
assert (
"interval_intervaltrigger_id_4->set_setup_priority(250.0f);\n"
"App.register_component_(interval_intervaltrigger_id_4, " in main_cpp
)
assert main_cpp.count("set_setup_priority") == 1
def test_interval_inline_actions(main_cpp: str) -> None:
"""All-inline intervals call one function from update(), with no Automation."""
assert constructed(main_cpp, "interval_intervaltrigger_id") == _callback(
"interval_intervaltrigger_id"
)
assert "Automation<>(interval_intervaltrigger_id" not in main_cpp
# Both actions run in the one function, with no stop checks
body = function_body(main_cpp, "esphome__interval_intervaltrigger_id__fn")
assert "inline tick" in body
assert "inline lambda" in body
assert "esphome__running" not in body
assert "Automation" not in body
assert "delayed start tick" in function_body(
main_cpp, "esphome__interval_intervaltrigger_id_2__fn"
)
def test_interval_delay_triggers_automation(main_cpp: str) -> None:
"""A delay keeps the Automation of separate actions, which the function triggers."""
assert constructed(main_cpp, "interval_intervaltrigger_id_3") == _callback(
"interval_intervaltrigger_id_3"
)
assert "new(automation_id_3) Automation<>();" in main_cpp
assert "automation_id_3->add_action(delayaction_id);" in main_cpp
assert function_body(main_cpp, "esphome__interval_intervaltrigger_id_3__fn") == (
"\n ::automation_id_3->trigger();"
)
def test_interval_manual_id_keeps_trigger(main_cpp: str) -> None:
"""An id set by hand can be used from lambdas and component actions as its trigger."""
assert (
constructed(main_cpp, "named_interval")
== "interval::DelayedIntervalTrigger(3000)"
)
assert (
"static interval::DelayedIntervalTrigger *const named_interval = " in main_cpp
)
assert "new(automation_id_4) Automation<>(named_interval);" in main_cpp
def test_interval_registered_before_its_actions_are_built(main_cpp: str) -> None:
"""An interval waiting for a later id keeps its place and still gets its interval."""
assert constructed(main_cpp, "interval_intervaltrigger_id_4") == _callback(
"interval_intervaltrigger_id_4"
)
registered = main_cpp.index("App.register_component_(interval_intervaltrigger_id_4")
assert registered < main_cpp.index("new(later_script)")
assert "::later_script->execute();" in function_body(
main_cpp, "esphome__interval_intervaltrigger_id_4__fn"
)
assert main_cpp.index(
"interval_intervaltrigger_id_4->set_update_interval(5000);"
) > main_cpp.index("new(later_script)")
def test_interval_looping_count(main_cpp: str) -> None:
"""Intervals do not loop; the looping component count names each class."""
assert (
"(1 * HasLoopOverride<interval::IntervalCallback<"
"esphome__interval_intervaltrigger_id__fn>>::value)" in main_cpp
)
assert "(1 * HasLoopOverride<interval::DelayedIntervalTrigger>::value)" in main_cpp
@@ -0,0 +1,35 @@
"""Tests for the interval config validation."""
from collections.abc import Callable
from pathlib import Path
import pytest
from esphome.components.interval import _MAX_PERIOD_MS, _uint32_milliseconds
from esphome.config import read_config
import esphome.config_validation as cv
from esphome.core import CORE
@pytest.mark.parametrize(
("value", "milliseconds"),
[("0s", 0), ("1s", 1000), (f"{_MAX_PERIOD_MS}ms", _MAX_PERIOD_MS)],
)
def test_period_up_to_the_max_is_accepted(value: str, milliseconds: int) -> None:
assert _uint32_milliseconds()(value).total_milliseconds == milliseconds
def test_period_past_the_max_is_rejected() -> None:
"""UINT32_MAX would mean never run; past it the value would be cut down on the device."""
with pytest.raises(cv.Invalid):
_uint32_milliseconds()(f"{_MAX_PERIOD_MS + 1}ms")
def test_config_with_startup_delay_past_the_max_is_invalid(
component_config_path: Callable[[str], Path],
capsys: pytest.CaptureFixture[str],
) -> None:
CORE.config_path = component_config_path("interval_long_delay.yaml")
assert read_config({}) is None
# Rejected for the bound (only startup_delay exceeds it), not an unrelated fixture error
assert f"value must be at most {_MAX_PERIOD_MS}ms." in capsys.readouterr().out
@@ -0,0 +1,62 @@
#include <gtest/gtest.h>
#include "esphome/core/base_automation.h"
namespace esphome::core::testing {
namespace {
int calls = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
void count_call() { calls++; }
// Bit patterns of 800.0f, -100.0f and 250.5f, as the code generator writes them
constexpr uint32_t PRIORITY_800 = 0x44480000;
constexpr uint32_t PRIORITY_MINUS_100 = 0xC2C80000;
constexpr uint32_t PRIORITY_250_5 = 0x437A8000;
} // namespace
TEST(CoreAutomationCallbacks, StartupCallbackRunsFromSetupAtItsPriority) {
calls = 0;
StartupCallback<count_call, PRIORITY_800> high;
StartupCallback<count_call, PRIORITY_MINUS_100> late;
StartupCallback<count_call, PRIORITY_250_5> fractional;
EXPECT_EQ(high.get_setup_priority(), 800.0f);
EXPECT_EQ(late.get_setup_priority(), -100.0f);
EXPECT_EQ(fractional.get_setup_priority(), 250.5f);
high.loop();
high.on_shutdown();
EXPECT_EQ(calls, 0);
high.setup();
EXPECT_EQ(calls, 1);
}
TEST(CoreAutomationCallbacks, ShutdownCallbackRunsFromOnShutdownAtItsPriority) {
calls = 0;
ShutdownCallback<count_call, PRIORITY_MINUS_100> shutdown;
EXPECT_EQ(shutdown.get_setup_priority(), -100.0f);
shutdown.setup();
shutdown.loop();
EXPECT_EQ(calls, 0);
shutdown.on_shutdown();
EXPECT_EQ(calls, 1);
}
TEST(CoreAutomationCallbacks, LoopCallbackRunsEachLoopAtDataPriority) {
calls = 0;
LoopCallback<count_call> looping;
EXPECT_EQ(looping.get_setup_priority(), setup_priority::DATA);
EXPECT_TRUE(HasLoopOverride<LoopCallback<count_call>>::value);
EXPECT_FALSE((HasLoopOverride<StartupCallback<count_call, PRIORITY_800>>::value));
looping.setup();
EXPECT_EQ(calls, 0);
looping.loop();
looping.loop();
EXPECT_EQ(calls, 2);
}
} // namespace esphome::core::testing
@@ -0,0 +1,44 @@
#include <gtest/gtest.h>
#include <type_traits>
#include "esphome/components/interval/interval_callback.h"
#include "esphome/core/application.h"
namespace esphome::interval::testing {
namespace {
int calls = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
void count_call() { calls++; }
} // namespace
TEST(IntervalCallback, UpdateCallsFnAtDataPriority) {
calls = 0;
IntervalCallback<count_call> interval;
EXPECT_EQ(interval.get_setup_priority(), setup_priority::DATA);
EXPECT_FALSE(HasLoopOverride<IntervalCallback<count_call>>::value);
interval.set_update_interval(1000);
EXPECT_EQ(interval.get_update_interval(), 1000u);
interval.setup();
EXPECT_EQ(calls, 0);
interval.update();
interval.update();
EXPECT_EQ(calls, 2);
}
TEST(IntervalCallback, DelayedIntervalCallbackIsAnIntervalCallback) {
// Only the delayed class overrides setup(), so a zero delay keeps Component::setup()
EXPECT_TRUE((std::is_base_of_v<IntervalCallback<count_call>, DelayedIntervalCallback<count_call, 5000>>) );
EXPECT_FALSE((HasLoopOverride<DelayedIntervalCallback<count_call, 5000>>::value));
calls = 0;
DelayedIntervalCallback<count_call, 5000> delayed;
EXPECT_EQ(delayed.get_setup_priority(), setup_priority::DATA);
delayed.update();
EXPECT_EQ(calls, 1);
}
} // namespace esphome::interval::testing
@@ -0,0 +1,34 @@
#include <gtest/gtest.h>
#include "esphome/components/interval/interval.h"
#include "esphome/core/application.h"
namespace esphome::interval::testing {
class CountAction : public Action<> {
public:
explicit CountAction(int *count) : count_(count) {}
void play() override { (*this->count_)++; }
protected:
int *count_;
};
TEST(IntervalTrigger, UpdateRunsTheAutomationAtDataPriority) {
IntervalTrigger trigger;
Automation<> automation{&trigger};
int count = 0;
CountAction action{&count};
automation.add_action(&action);
EXPECT_EQ(trigger.get_setup_priority(), setup_priority::DATA);
EXPECT_FALSE(HasLoopOverride<IntervalTrigger>::value);
trigger.set_update_interval(1000);
EXPECT_EQ(trigger.get_update_interval(), 1000u);
trigger.update();
trigger.update();
EXPECT_EQ(count, 2);
}
} // namespace esphome::interval::testing
@@ -0,0 +1,81 @@
esphome:
name: interval-runs
host:
api:
logger:
level: DEBUG
globals:
- id: inline_count
type: int
initial_value: "0"
- id: action_count
type: int
initial_value: "0"
- id: startup_count
type: int
initial_value: "0"
- id: named_count
type: int
initial_value: "0"
- id: phase
type: int
initial_value: "0"
interval:
# All actions inline
- interval: 50ms
then:
- lambda: id(inline_count) += 1;
- lambda: |-
if (id(inline_count) == 1) {
ESP_LOGI("test", "INLINE first uptime=%u", (unsigned) millis());
} else if (id(inline_count) == 20) {
ESP_LOGI("test", "INLINE ran 20 times");
}
# A delay between the actions
- interval: 100ms
then:
- lambda: |-
id(action_count) += 1;
ESP_LOGI("test", "ACTION start %d", id(action_count));
- delay: 20ms
- lambda: ESP_LOGI("test", "ACTION end %d", id(action_count));
# First run waits for the startup delay
- interval: 50ms
startup_delay: 1000ms
then:
- lambda: |-
if (++id(startup_count) == 1) {
ESP_LOGI("test", "STARTUP first uptime=%u inline_count=%d", (unsigned) millis(), id(inline_count));
}
# Reachable by id for component.suspend and component.resume
- id: named_interval
interval: 50ms
then:
- lambda: id(named_count) += 1;
# Suspends named_interval, resumes it a run later, then checks it ran again
- interval: 500ms
startup_delay: 500ms
then:
- lambda: id(phase) += 1;
- if:
condition:
lambda: return id(phase) == 1;
then:
- component.suspend: named_interval
- lambda: |-
ESP_LOGI("test", "SUSPENDED named_count=%d update_interval=%u", id(named_count),
(unsigned) id(named_interval)->get_update_interval());
- if:
condition:
lambda: return id(phase) == 2;
then:
- lambda: ESP_LOGI("test", "STILL SUSPENDED named_count=%d", id(named_count));
- component.resume: named_interval
- if:
condition:
lambda: return id(phase) == 3;
then:
- lambda: ESP_LOGI("test", "RESUMED named_count=%d", id(named_count));
+58
View File
@@ -0,0 +1,58 @@
"""Integration test that intervals run repeatedly, honour their startup delay and can be suspended."""
from __future__ import annotations
import re
import pytest
from .log_utils import LineWaiter
from .types import RunCompiledFunction
INLINE_FIRST = re.compile(r"INLINE first uptime=(\d+)")
STARTUP_FIRST = re.compile(r"STARTUP first uptime=(\d+) inline_count=(\d+)")
SUSPENDED = re.compile(r"SUSPENDED named_count=(\d+) update_interval=(\d+)")
STILL_SUSPENDED = re.compile(r"STILL SUSPENDED named_count=(\d+)")
RESUMED = re.compile(r"RESUMED named_count=(\d+)")
ACTION = re.compile(r"ACTION (start|end) (\d+)")
@pytest.mark.asyncio
async def test_interval_runs(
yaml_config: str,
run_compiled: RunCompiledFunction,
) -> None:
"""Inline and delayed actions repeat; the startup delay and component.suspend hold runs back."""
waiter = LineWaiter()
inline_future = waiter.expect(INLINE_FIRST)
startup_future = waiter.expect(STARTUP_FIRST)
suspended_future = waiter.expect(SUSPENDED)
still_future = waiter.expect(STILL_SUSPENDED)
resumed_future = waiter.expect(RESUMED)
async with run_compiled(yaml_config, line_callback=waiter.callback):
inline = await waiter.wait(inline_future)
startup = await waiter.wait(startup_future)
suspended = await waiter.wait(suspended_future)
still = await waiter.wait(still_future)
resumed = await waiter.wait(resumed_future)
await waiter.wait_for_each("INLINE ran 20 times", "ACTION end 3")
# The startup delay held the first run back while the inline interval kept running
assert int(startup.group(1)) - int(inline.group(1)) >= 800
assert int(startup.group(2)) >= 10
# Suspended by id: no run in the 500 ms until the next check
assert int(suspended.group(2)) == 50
assert int(still.group(1)) == int(suspended.group(1))
# Resumed by id: it ran again in the 500 ms after
assert int(resumed.group(1)) >= int(still.group(1)) + 5
# Each run of the delayed actions finished before the next started
actions = [m.groups() for line in waiter.lines if (m := ACTION.search(line))]
assert actions[:6] == [
("start", "1"),
("end", "1"),
("start", "2"),
("end", "2"),
("start", "3"),
("end", "3"),
]
+15
View File
@@ -986,6 +986,21 @@ def test_static_function_declares_early_and_defines_after_includes() -> None:
]
def test_declare_static_function_defines_the_body_later() -> None:
"""The declaration is emitted at once; the body only when define() is called."""
define = cg.declare_static_function("esphome__act__fn", ct.void, [])
assert [str(st) for st in CORE.global_statements] == [
"static void esphome__act__fn();"
]
assert CORE.global_statements_after_includes == []
fn = define(["first();", "second();"])
assert str(fn) == "esphome__act__fn"
assert [str(st) for st in CORE.global_statements_after_includes] == [
"static void esphome__act__fn() {\n first();\n second();\n}"
]
def test_static_function_accepts_statements() -> None:
call = cg.MockObj("foo")(cg.MockObj("x") >> 2)
cg.static_function(