mirror of
https://github.com/esphome/esphome.git
synced 2026-09-11 23:37:34 +00:00
[core] Merge set_name + set_entity_strings into configure_entity
Every entity generated two codegen calls:
entity->set_name("Name", hash);
entity->set_entity_strings(packed);
Merge these into a single configure_entity(name, hash, packed) call
to reduce generated code size. For a config with 50+ entities this
eliminates 50+ function calls from the generated setup() function.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
96793a99ce
commit
42fa6ef818
@@ -45,6 +45,11 @@ void EntityBase::set_name(const char *name, uint32_t object_id_hash) {
|
||||
}
|
||||
}
|
||||
|
||||
void EntityBase::configure_entity(const char *name, uint32_t object_id_hash, uint32_t entity_strings_packed) {
|
||||
this->set_name(name, object_id_hash);
|
||||
this->set_entity_strings(entity_strings_packed);
|
||||
}
|
||||
|
||||
// Weak default lookup functions — overridden by generated code in main.cpp
|
||||
__attribute__((weak)) const char *entity_device_class_lookup(uint8_t) { return ""; }
|
||||
__attribute__((weak)) const char *entity_uom_lookup(uint8_t) { return ""; }
|
||||
|
||||
@@ -52,6 +52,9 @@ class EntityBase {
|
||||
/// Use hash=0 for dynamic names that need runtime calculation
|
||||
void set_name(const char *name, uint32_t object_id_hash);
|
||||
|
||||
/// Combined entity setup from codegen: set name, object_id hash, and entity string indices.
|
||||
void configure_entity(const char *name, uint32_t object_id_hash, uint32_t entity_strings_packed);
|
||||
|
||||
// Get whether this Entity has its own name or it should use the device friendly_name.
|
||||
bool has_own_name() const { return this->flags_.has_own_name; }
|
||||
|
||||
|
||||
@@ -30,8 +30,10 @@ DOMAIN = "entity_string_pool"
|
||||
_KEY_DC_IDX = "_entity_dc_idx"
|
||||
_KEY_UOM_IDX = "_entity_uom_idx"
|
||||
_KEY_ICON_IDX = "_entity_icon_idx"
|
||||
_KEY_ENTITY_NAME = "_entity_name"
|
||||
_KEY_OBJECT_ID_HASH = "_entity_object_id_hash"
|
||||
|
||||
# Bit layout for set_entity_strings(packed) — must match C++ setter in entity_base.h:
|
||||
# Bit layout for entity_strings_packed in configure_entity() — must match C++ in entity_base.h:
|
||||
# [23..16] icon (8 bits) | [15..8] UoM (8 bits) | [7..0] device_class (8 bits)
|
||||
_DC_SHIFT = 0
|
||||
_UOM_SHIFT = 8
|
||||
@@ -180,17 +182,18 @@ def setup_unit_of_measurement(config: ConfigType) -> None:
|
||||
|
||||
|
||||
def finalize_entity_strings(var: MockObj, config: ConfigType) -> None:
|
||||
"""Emit a single set_entity_strings() call with all packed indices.
|
||||
"""Emit a single configure_entity() call with name, hash, and packed string indices.
|
||||
|
||||
Call this at the end of each component's setup function, after
|
||||
setup_entity() and any register_device_class/register_unit_of_measurement calls.
|
||||
"""
|
||||
entity_name = config[_KEY_ENTITY_NAME]
|
||||
object_id_hash = config[_KEY_OBJECT_ID_HASH]
|
||||
dc_idx = config.get(_KEY_DC_IDX, 0)
|
||||
uom_idx = config.get(_KEY_UOM_IDX, 0)
|
||||
icon_idx = config.get(_KEY_ICON_IDX, 0)
|
||||
packed = (dc_idx << _DC_SHIFT) | (uom_idx << _UOM_SHIFT) | (icon_idx << _ICON_SHIFT)
|
||||
if packed != 0:
|
||||
add(var.set_entity_strings(packed))
|
||||
add(var.configure_entity(entity_name, object_id_hash, packed))
|
||||
|
||||
|
||||
def get_base_entity_object_id(
|
||||
@@ -292,13 +295,15 @@ async def _setup_entity_impl(var: MockObj, config: ConfigType, platform: str) ->
|
||||
device: MockObj = await get_variable(device_id_obj)
|
||||
add(var.set_device(device))
|
||||
|
||||
# Set the entity name with pre-computed object_id hash
|
||||
# Pre-compute entity name and object_id hash for configure_entity()
|
||||
# which is emitted later by finalize_entity_strings().
|
||||
# For named entities: pre-compute hash from entity name
|
||||
# For empty-name entities: pass 0, C++ calculates hash at runtime from
|
||||
# device name, friendly_name, or app name (bug-for-bug compatibility)
|
||||
entity_name = config[CONF_NAME]
|
||||
object_id_hash = fnv1_hash_object_id(entity_name) if entity_name else 0
|
||||
add(var.set_name(entity_name, object_id_hash))
|
||||
config[_KEY_ENTITY_NAME] = entity_name
|
||||
config[_KEY_OBJECT_ID_HASH] = object_id_hash
|
||||
# Only set disabled_by_default if True (default is False)
|
||||
if config[CONF_DISABLED_BY_DEFAULT]:
|
||||
add(var.set_disabled_by_default(True))
|
||||
|
||||
@@ -30,9 +30,11 @@ from esphome.helpers import sanitize, snake_case
|
||||
|
||||
from .common import load_config_from_fixture
|
||||
|
||||
# Pre-compiled regex pattern for extracting names from set_name calls
|
||||
# Matches: .set_name("name", hash) or .set_name("name")
|
||||
SET_NAME_PATTERN = re.compile(r'\.set_name\(["\']([^"\']*)["\']')
|
||||
# Pre-compiled regex pattern for extracting names from configure_entity/set_name calls
|
||||
# Matches: .configure_entity("name", ...) or .set_name("name", ...)
|
||||
ENTITY_NAME_PATTERN = re.compile(
|
||||
r'\.(?:configure_entity|set_name)\(["\']([^"\']*)["\']'
|
||||
)
|
||||
|
||||
FIXTURES_DIR = Path(__file__).parent.parent / "fixtures" / "core" / "entity_helpers"
|
||||
|
||||
@@ -274,15 +276,23 @@ def setup_test_environment() -> Generator[list[str], None, None]:
|
||||
entity_helpers.add = original_add
|
||||
|
||||
|
||||
def extract_object_id_from_expressions(expressions: list[str]) -> str | None:
|
||||
"""Extract the object ID that would be computed from set_name calls.
|
||||
def extract_object_id_from_config(config: dict[str, Any]) -> str | None:
|
||||
"""Extract the object ID from config keys set by _setup_entity_impl."""
|
||||
name = config.get("_entity_name")
|
||||
if name is None:
|
||||
return None
|
||||
if name:
|
||||
return sanitize(snake_case(name))
|
||||
# Empty name - fall back to friendly_name or device name
|
||||
if CORE.friendly_name:
|
||||
return sanitize(snake_case(CORE.friendly_name))
|
||||
return sanitize(snake_case(CORE.name)) if CORE.name else None
|
||||
|
||||
Since object_id is now computed from the name (via snake_case + sanitize),
|
||||
we extract the name from set_name() calls and compute the expected object_id.
|
||||
For empty names, we fall back to CORE.friendly_name or CORE.name.
|
||||
"""
|
||||
|
||||
def extract_object_id_from_expressions(expressions: list[str]) -> str | None:
|
||||
"""Extract the object ID from configure_entity() calls in generated expressions."""
|
||||
for expr in expressions:
|
||||
if match := SET_NAME_PATTERN.search(expr):
|
||||
if match := ENTITY_NAME_PATTERN.search(expr):
|
||||
name = match.group(1)
|
||||
if name:
|
||||
return sanitize(snake_case(name))
|
||||
@@ -297,7 +307,7 @@ def extract_object_id_from_expressions(expressions: list[str]) -> str | None:
|
||||
async def test_setup_entity_no_duplicates(setup_test_environment: list[str]) -> None:
|
||||
"""Test setup_entity with unique names."""
|
||||
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
# Create mock entities
|
||||
var1 = MockObj("sensor1")
|
||||
@@ -310,13 +320,10 @@ async def test_setup_entity_no_duplicates(setup_test_environment: list[str]) ->
|
||||
}
|
||||
await _setup_entity_impl(var1, config1, "sensor")
|
||||
|
||||
# Get object ID from first entity
|
||||
object_id1 = extract_object_id_from_expressions(added_expressions)
|
||||
# Get object ID from first entity (stored in config, emitted later by finalize)
|
||||
object_id1 = extract_object_id_from_config(config1)
|
||||
assert object_id1 == "temperature"
|
||||
|
||||
# Clear for next entity
|
||||
added_expressions.clear()
|
||||
|
||||
# Set up second entity with different name
|
||||
config2 = {
|
||||
CONF_NAME: "Humidity",
|
||||
@@ -325,7 +332,7 @@ async def test_setup_entity_no_duplicates(setup_test_environment: list[str]) ->
|
||||
await _setup_entity_impl(var2, config2, "sensor")
|
||||
|
||||
# Get object ID from second entity
|
||||
object_id2 = extract_object_id_from_expressions(added_expressions)
|
||||
object_id2 = extract_object_id_from_config(config2)
|
||||
assert object_id2 == "humidity"
|
||||
|
||||
|
||||
@@ -335,7 +342,7 @@ async def test_setup_entity_different_platforms(
|
||||
) -> None:
|
||||
"""Test that same name on different platforms doesn't conflict."""
|
||||
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
# Create mock entities
|
||||
sensor = MockObj("sensor1")
|
||||
@@ -354,15 +361,11 @@ async def test_setup_entity_different_platforms(
|
||||
(text_sensor, "text_sensor"),
|
||||
]
|
||||
|
||||
object_ids: list[str] = []
|
||||
for var, platform in platforms:
|
||||
added_expressions.clear()
|
||||
await _setup_entity_impl(var, config, platform)
|
||||
object_id = extract_object_id_from_expressions(added_expressions)
|
||||
object_ids.append(object_id)
|
||||
|
||||
# All should get base object ID without suffix
|
||||
assert all(obj_id == "status" for obj_id in object_ids)
|
||||
# All should get the same object ID (name stored in config, not platform-specific)
|
||||
assert extract_object_id_from_config(config) == "status"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -387,7 +390,7 @@ async def test_setup_entity_with_devices(
|
||||
setup_test_environment: list[str], mock_get_variable: dict[ID, MockObj]
|
||||
) -> None:
|
||||
"""Test that same name on different devices doesn't conflict."""
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
# Create mock devices
|
||||
device1_id = ID("device1", type="Device")
|
||||
@@ -416,23 +419,19 @@ async def test_setup_entity_with_devices(
|
||||
}
|
||||
|
||||
# Get object IDs
|
||||
object_ids: list[str] = []
|
||||
for var, config in [(sensor1, config1), (sensor2, config2)]:
|
||||
added_expressions.clear()
|
||||
await _setup_entity_impl(var, config, "sensor")
|
||||
object_id = extract_object_id_from_expressions(added_expressions)
|
||||
object_ids.append(object_id)
|
||||
|
||||
# Both should get base object ID without suffix (different devices)
|
||||
assert object_ids[0] == "temperature"
|
||||
assert object_ids[1] == "temperature"
|
||||
assert extract_object_id_from_config(config1) == "temperature"
|
||||
assert extract_object_id_from_config(config2) == "temperature"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_setup_entity_empty_name(setup_test_environment: list[str]) -> None:
|
||||
"""Test setup_entity with empty entity name."""
|
||||
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
var = MockObj("sensor1")
|
||||
|
||||
@@ -443,7 +442,7 @@ async def test_setup_entity_empty_name(setup_test_environment: list[str]) -> Non
|
||||
|
||||
await _setup_entity_impl(var, config, "sensor")
|
||||
|
||||
object_id = extract_object_id_from_expressions(added_expressions)
|
||||
object_id = extract_object_id_from_config(config)
|
||||
# Should use friendly name
|
||||
assert object_id == "test_device"
|
||||
|
||||
@@ -454,7 +453,7 @@ async def test_setup_entity_special_characters(
|
||||
) -> None:
|
||||
"""Test setup_entity with names containing special characters."""
|
||||
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
var = MockObj("sensor1")
|
||||
|
||||
@@ -464,7 +463,7 @@ async def test_setup_entity_special_characters(
|
||||
}
|
||||
|
||||
await _setup_entity_impl(var, config, "sensor")
|
||||
object_id = extract_object_id_from_expressions(added_expressions)
|
||||
object_id = extract_object_id_from_config(config)
|
||||
|
||||
# Special characters should be sanitized
|
||||
assert object_id == "temperature_sensor_"
|
||||
@@ -798,10 +797,9 @@ async def test_setup_entity_empty_name_with_device(
|
||||
# Check that set_device was called
|
||||
assert any("sensor1.set_device" in expr for expr in added_expressions)
|
||||
|
||||
# For empty-name entities, Python passes 0 - C++ calculates hash at runtime
|
||||
assert any('set_name("", 0)' in expr for expr in added_expressions), (
|
||||
f"Expected set_name with hash 0, got {added_expressions}"
|
||||
)
|
||||
# For empty-name entities, Python stores hash 0 - C++ calculates hash at runtime
|
||||
assert config.get("_entity_name") == ""
|
||||
assert config.get("_entity_object_id_hash") == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -813,7 +811,7 @@ async def test_setup_entity_empty_name_with_mac_suffix(
|
||||
For empty-name entities, Python passes 0 and C++ calculates the hash
|
||||
at runtime from friendly_name (bug-for-bug compatibility).
|
||||
"""
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
# Set up CORE.config with name_add_mac_suffix enabled
|
||||
CORE.config = {"name_add_mac_suffix": True}
|
||||
@@ -829,10 +827,9 @@ async def test_setup_entity_empty_name_with_mac_suffix(
|
||||
|
||||
await _setup_entity_impl(var, config, "sensor")
|
||||
|
||||
# For empty-name entities, Python passes 0 - C++ calculates hash at runtime
|
||||
assert any('set_name("", 0)' in expr for expr in added_expressions), (
|
||||
f"Expected set_name with hash 0, got {added_expressions}"
|
||||
)
|
||||
# For empty-name entities, Python stores hash 0 - C++ calculates hash at runtime
|
||||
assert config.get("_entity_name") == ""
|
||||
assert config.get("_entity_object_id_hash") == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -845,7 +842,7 @@ async def test_setup_entity_empty_name_with_mac_suffix_no_friendly_name(
|
||||
at runtime. In this case C++ will hash the empty friendly_name
|
||||
(bug-for-bug compatibility).
|
||||
"""
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
# Set up CORE.config with name_add_mac_suffix enabled
|
||||
CORE.config = {"name_add_mac_suffix": True}
|
||||
@@ -861,10 +858,9 @@ async def test_setup_entity_empty_name_with_mac_suffix_no_friendly_name(
|
||||
|
||||
await _setup_entity_impl(var, config, "sensor")
|
||||
|
||||
# For empty-name entities, Python passes 0 - C++ calculates hash at runtime
|
||||
assert any('set_name("", 0)' in expr for expr in added_expressions), (
|
||||
f"Expected set_name with hash 0, got {added_expressions}"
|
||||
)
|
||||
# For empty-name entities, Python stores hash 0 - C++ calculates hash at runtime
|
||||
assert config.get("_entity_name") == ""
|
||||
assert config.get("_entity_object_id_hash") == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -876,7 +872,7 @@ async def test_setup_entity_empty_name_no_mac_suffix_no_friendly_name(
|
||||
For empty-name entities, Python passes 0 and C++ calculates the hash
|
||||
at runtime from the device name.
|
||||
"""
|
||||
added_expressions = setup_test_environment
|
||||
setup_test_environment # noqa: F841 - fixture initializes CORE state
|
||||
|
||||
# No MAC suffix (either not set or False)
|
||||
CORE.config = {}
|
||||
@@ -894,10 +890,9 @@ async def test_setup_entity_empty_name_no_mac_suffix_no_friendly_name(
|
||||
|
||||
await _setup_entity_impl(var, config, "sensor")
|
||||
|
||||
# For empty-name entities, Python passes 0 - C++ calculates hash at runtime
|
||||
assert any('set_name("", 0)' in expr for expr in added_expressions), (
|
||||
f"Expected set_name with hash 0, got {added_expressions}"
|
||||
)
|
||||
# For empty-name entities, Python stores hash 0 - C++ calculates hash at runtime
|
||||
assert config.get("_entity_name") == ""
|
||||
assert config.get("_entity_object_id_hash") == 0
|
||||
|
||||
|
||||
def test_register_string_overflow() -> None:
|
||||
@@ -942,7 +937,7 @@ async def test_setup_entity_direct_call(setup_test_environment: list[str]) -> No
|
||||
# Direct call mode: await setup_entity(var, config, "camera")
|
||||
await setup_entity(var, config, "camera")
|
||||
|
||||
# Should have called set_name
|
||||
# Should have emitted configure_entity
|
||||
object_id = extract_object_id_from_expressions(added_expressions)
|
||||
assert object_id == "my_camera"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user