mirror of
https://github.com/esphome/esphome.git
synced 2026-09-17 18:18:43 +00:00
[template] Skip the switch optimistic and assumed state setters when they match the default (#19232)
This commit is contained in:
@@ -72,8 +72,11 @@ async def to_code(config):
|
||||
await automation.build_automation(
|
||||
var.get_turn_on_trigger(), [], config[CONF_TURN_ON_ACTION]
|
||||
)
|
||||
cg.add(var.set_optimistic(config[CONF_OPTIMISTIC]))
|
||||
cg.add(var.set_assumed_state(config[CONF_ASSUMED_STATE]))
|
||||
# optimistic_ and assumed_state_ are false in C++; only emit setters to turn them on.
|
||||
if config[CONF_OPTIMISTIC]:
|
||||
cg.add(var.set_optimistic(True))
|
||||
if config[CONF_ASSUMED_STATE]:
|
||||
cg.add(var.set_assumed_state(True))
|
||||
|
||||
|
||||
@automation.register_action(
|
||||
|
||||
@@ -29,6 +29,7 @@ class TemplateSwitch final : public switch_::Switch, public Component {
|
||||
void write_state(bool state) override;
|
||||
|
||||
TemplateLambda<bool> f_;
|
||||
// Codegen only emits these setters to turn them on
|
||||
bool optimistic_{false};
|
||||
bool assumed_state_{false};
|
||||
Trigger<> turn_on_trigger_;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
|
||||
logger:
|
||||
|
||||
switch:
|
||||
- platform: template
|
||||
id: plain_switch
|
||||
turn_on_action:
|
||||
- logger.log: "on"
|
||||
- platform: template
|
||||
id: enabled_switch
|
||||
optimistic: true
|
||||
assumed_state: true
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Tests for the template switch codegen."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_default_flags_are_not_emitted(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""Only true optimistic and assumed_state are set; false is the C++ initializer."""
|
||||
main_cpp = generate_main(component_config_path("switch_defaults.yaml"))
|
||||
|
||||
assert "plain_switch->set_optimistic(" not in main_cpp
|
||||
assert "plain_switch->set_assumed_state(" not in main_cpp
|
||||
assert "enabled_switch->set_optimistic(true);" in main_cpp
|
||||
assert "enabled_switch->set_assumed_state(true);" in main_cpp
|
||||
Reference in New Issue
Block a user