mirror of
https://github.com/esphome/esphome.git
synced 2026-10-27 00:12:11 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a4e7f4c680 | ||
|
|
557ed04f7f | ||
|
|
c04cdea1a0 | ||
|
|
46d8c3ec02 |
No files matched your search
@@ -443,7 +443,8 @@ file does, and it is the authority when they disagree. The most useful starting
|
||||
- **Hub forwarding entities need no C++ class:** a button, switch, number or select that only calls its hub
|
||||
uses `button.ApplyButton` (`switch.ApplySwitch`, `number.ApplyNumber`, `select.ApplySelect`) in its schema
|
||||
and `apply=` on the `sub_*` call. The body is a call on the hub with `entity` and `state`, `value` or
|
||||
`index`/`option` in scope; on a switch, number or select `publish="before"` or `"after"` publishes the state.
|
||||
`index`/`option` in scope; on a switch, number or select `publish="before"` or `"after"` publishes the state,
|
||||
and `publish="on_success"` publishes only when the hub call returns true (a write the device can refuse).
|
||||
`publish="momentary"` is only for legacy action switches (restart, factory reset): it publishes off and runs
|
||||
the body only when turned on. Never use it for a new entity; an action is a button.
|
||||
```python
|
||||
|
||||
@@ -5,7 +5,7 @@ from importlib import import_module
|
||||
from importlib.util import find_spec
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
from typing import Any, Literal, get_args
|
||||
|
||||
from esphome.automation import apply_static_function, parent_ref
|
||||
import esphome.codegen as cg
|
||||
@@ -503,7 +503,8 @@ async def _setup_entity_impl(var: MockObj, config: ConfigType, platform: str) ->
|
||||
config[_KEY_ICON_IDX] = icon_idx
|
||||
|
||||
|
||||
ApplyPublish = Literal["before", "after", "momentary"] | None
|
||||
ApplyPublishMode = Literal["before", "after", "momentary", "on_success"]
|
||||
ApplyPublish = ApplyPublishMode | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -577,7 +578,8 @@ class SubEntities:
|
||||
|
||||
With ``apply`` the entity is the domain's ``Apply*`` class and its control runs
|
||||
``parent->apply``, or ``apply`` as a namespaced free statement when no parent is bound, with
|
||||
``publish`` ("before"/"after") placing the domain's publish. ``publish="momentary"`` instead
|
||||
``publish`` ("before"/"after") placing the domain's publish; ``"on_success"`` publishes only when
|
||||
``apply`` returns true. ``publish="momentary"`` instead
|
||||
acknowledges first (a switch publishes off) and runs ``apply`` only when turned on. It is only for
|
||||
legacy action switches; a new action entity is a button.
|
||||
"""
|
||||
@@ -600,10 +602,8 @@ class SubEntities:
|
||||
)
|
||||
if publish is not None and (apply is None or self.apply_entity.publish is None):
|
||||
raise ValueError(f"{entity_id}: publish= needs apply= on a stateful domain")
|
||||
if publish not in (None, "before", "after", "momentary"):
|
||||
raise ValueError(
|
||||
f'{entity_id}: publish= must be "before", "after" or "momentary"'
|
||||
)
|
||||
if publish is not None and publish not in (modes := get_args(ApplyPublishMode)):
|
||||
raise ValueError(f"{entity_id}: publish= must be one of {', '.join(modes)}")
|
||||
if publish == "momentary" and self.apply_entity.momentary is None:
|
||||
raise ValueError(f'{entity_id}: publish="momentary" is not supported here')
|
||||
|
||||
@@ -626,11 +626,21 @@ class SubEntities:
|
||||
if isinstance(parent, ID):
|
||||
parent = await get_variable(parent)
|
||||
apply_entity = self.apply_entity
|
||||
call = f"{apply};" if parent is None else f"{parent_ref(parent)}->{apply};"
|
||||
expr = apply if parent is None else f"{parent_ref(parent)}->{apply}"
|
||||
call = f"{expr};"
|
||||
if publish == "before":
|
||||
body = [apply_entity.publish, call]
|
||||
elif publish == "after":
|
||||
body = [call, apply_entity.publish]
|
||||
elif publish == "on_success":
|
||||
# An esp_err_t or int would convert to bool silently and flip the meaning
|
||||
body = [
|
||||
(
|
||||
f"static_assert(std::is_same_v<decltype({expr}), bool>, "
|
||||
'"publish=\\"on_success\\" needs a hub call that returns bool");'
|
||||
),
|
||||
f"if ({expr}) {{ {apply_entity.publish} }}",
|
||||
]
|
||||
elif publish == "momentary":
|
||||
acknowledge, condition = apply_entity.momentary
|
||||
body = [acknowledge, f"if ({condition}) {{ {call} }}"]
|
||||
|
||||
@@ -1711,6 +1711,16 @@ _SELECT_APPLY = entity_helpers.ApplyEntity(
|
||||
"after",
|
||||
"::hub->set_mode(index, options_);\nentity->publish_state(index);",
|
||||
),
|
||||
(
|
||||
"set_mode(option)",
|
||||
"on_success",
|
||||
(
|
||||
"const char *option = entity->option_at(index);\n"
|
||||
"static_assert(std::is_same_v<decltype(::hub->set_mode(option)), bool>, "
|
||||
'"publish=\\"on_success\\" needs a hub call that returns bool");\n'
|
||||
"if (::hub->set_mode(option)) { entity->publish_state(index); }"
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_sub_entities_apply_locals(
|
||||
@@ -1883,6 +1893,43 @@ async def test_sub_entities_apply_momentary(
|
||||
assert apply_functions[0][2] == body
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("parent", "apply", "body"),
|
||||
[
|
||||
(
|
||||
_HUB,
|
||||
"write_level(state)",
|
||||
(
|
||||
"static_assert(std::is_same_v<decltype(::hub->write_level(state)), bool>, "
|
||||
'"publish=\\"on_success\\" needs a hub call that returns bool");\n'
|
||||
"if (::hub->write_level(state)) { entity->publish_state(state); }"
|
||||
),
|
||||
),
|
||||
(
|
||||
None,
|
||||
"chip::write_level(state)",
|
||||
(
|
||||
"static_assert(std::is_same_v<decltype(chip::write_level(state)), bool>, "
|
||||
'"publish=\\"on_success\\" needs a hub call that returns bool");\n'
|
||||
"if (chip::write_level(state)) { entity->publish_state(state); }"
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_sub_entities_apply_on_success(
|
||||
setup_test_environment: list[str],
|
||||
apply_functions: list[tuple[str, str, str]],
|
||||
parent: MockObj | None,
|
||||
apply: str,
|
||||
body: str,
|
||||
) -> None:
|
||||
"""publish="on_success" publishes only when the hub call returns true."""
|
||||
sub = _apply_sub([], {"k": _apply_conf("k_sw")}, parent=parent)
|
||||
await sub("k", None, apply=apply, publish="on_success")
|
||||
assert apply_functions[0][2] == body
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sub_entities_apply_without_parent_needs_namespaced_call(
|
||||
setup_test_environment: list[str],
|
||||
|
||||
Reference in new issue
Block a user