|
import homeassistant.helpers.entity_registry as er |
|
import homeassistant.helpers.label_registry as lr |
|
|
|
@event_trigger("state_changed", "entity_id.startswith('event.')") |
|
def matter_button_toggle_handler(entity_id=None, new_state=None, old_state=None, **kwargs): |
|
# Safely extract the state value |
|
new_s = new_state.state if hasattr(new_state, "state") else (new_state.get("state") if isinstance(new_state, dict) else None) |
|
old_s = old_state.state if hasattr(old_state, "state") else (old_state.get("state") if isinstance(old_state, dict) else None) |
|
|
|
# Ignore pure attribute updates |
|
if not new_s or new_s == old_s: |
|
return |
|
|
|
# Fetch the entity registry |
|
entity_reg = er.async_get(hass) |
|
entity_entry = entity_reg.async_get(entity_id) |
|
|
|
if not entity_entry: |
|
return |
|
|
|
# Fetch the label registry to resolve label IDs to raw names |
|
label_reg = lr.async_get(hass) |
|
|
|
# Process all label IDs attached to this button |
|
for label_id in entity_entry.labels: |
|
# CORRECTED: Access the label entry from the labels dictionary |
|
label_entry = label_reg.labels.get(label_id) |
|
|
|
# Skip if the label somehow doesn't exist in the registry |
|
if not label_entry: |
|
continue |
|
|
|
label_name = label_entry.name |
|
|
|
# Check the raw name for your prefix |
|
if label_name.startswith("toggle:"): |
|
# Extract the exact target entity ID string |
|
target_entity = label_name.split(":", 1)[1].strip() |
|
|
|
log.info(f"Button {entity_id} pressed. Toggling raw entity {target_entity}") |
|
|
|
# Fire the toggle service |
|
service.call("homeassistant", "toggle", entity_id=target_entity) |