Skip to content

Instantly share code, notes, and snippets.

@aviraldg
Created March 16, 2026 23:50
Show Gist options
  • Select an option

  • Save aviraldg/058f0c207327ff6939c8c16016de40fd to your computer and use it in GitHub Desktop.

Select an option

Save aviraldg/058f0c207327ff6939c8c16016de40fd to your computer and use it in GitHub Desktop.
Label based configuration for button entity actions in Home Assistant.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment