EventBus Overview
TheEventBus manages event distribution across the entire system:
homeassistant/core.py
The EventBus uses a dictionary to map event types to listener lists, enabling O(1) lookup for event dispatch. The
MATCH_ALL special key allows listeners to receive all events.Core Event Types
Home Assistant defines several core event types inhomeassistant/const.py:
homeassistant/const.py
Event Type Categories
Lifecycle Events
Events marking major transitions in Home Assistant’s lifecycle
State Events
Events fired when entity states change or are reported
Service Events
Events related to service registration and execution
Configuration Events
Events signaling configuration changes
Event Structure
Every event is represented by theEvent class:
homeassistant/core.py
Event Components
- event_type: String or typed identifier for the event
- data: Dictionary containing event-specific information
- origin: Whether the event originated locally or remotely
- time_fired_timestamp: Unix timestamp when the event was fired
- context: Context tracking the chain of events
Firing Events
Internal Events
For performance-critical internal events, useasync_fire_internal:
homeassistant/core.py
Public Events
For regular event firing, use the public API:1
Event Type Validated
The event type length is validated (max 64 characters).
2
Event Created
An Event object is created with the provided data and context.
3
Listeners Retrieved
All listeners for this event type and MATCH_ALL listeners are retrieved.
4
Filters Applied
Event filters are evaluated to determine which listeners should receive the event.
5
Jobs Executed
Each matching listener’s job is executed asynchronously.
Listening for Events
Basic Listener
Register a listener for a specific event type:Event Filters
Filters allow you to selectively receive events:Event filters must be decorated with
@callback and should execute quickly. Slow filters will block event processing for all listeners.Listen Once
For one-time event handling:State Change Events
State changes trigger the most common events in Home Assistant:homeassistant/core.py
Listening for State Changes
Optimized State Tracking
For better performance when tracking specific entities, use the event helpers:async_track_state_change_event uses an optimized index that routes events directly to listeners interested in specific entities, avoiding the need to process all state change events.Match All Listeners
Listen to every event (use sparingly for debugging/monitoring):Event Context
Every event includes a context tracking its origin:homeassistant/core.py
Using Context
Event Origin
Events can originate locally or from remote systems:homeassistant/core.py
Performance Considerations
Best Practices
- Always unregister listeners when your component unloads
- Use typed event data with TypedDict for type safety
- Handle None states in state change events (entity added/removed)
- Propagate context to maintain audit trails
- Avoid blocking operations in event listeners