The State Machine
TheStateMachine class manages all entity states in Home Assistant:
homeassistant/core.py:2058
State Objects
State Structure
TheState object contains complete entity information:
homeassistant/core.py:1718
State vs Attributes
- State: The primary status (on/off, open/closed, numeric value)
- Attributes: Additional context (brightness, color, temperature)
Reading State
Get Single State
homeassistant/core.py:2142
Check State Value
homeassistant/core.py:2151
Get All States
homeassistant/core.py:2124
Get Entity IDs
homeassistant/core.py:2081
Setting State
Basic State Update
homeassistant/core.py:2247
State Update with Context
Context tracks what triggered the state change:homeassistant/core.py:1213
Force Update
Force a state change event even if state hasn’t changed:homeassistant/core.py:2247
State Change Events
EVENT_STATE_CHANGED
Fired when state or attributes change:homeassistant/core.py:137
EVENT_STATE_REPORTED
Fired when state is updated but unchanged:homeassistant/core.py:147
State Reservations
Reserve Entity ID
Reserve an entity ID before creating the entity:homeassistant/core.py:2222
Check Availability
homeassistant/core.py:2239
Removing State
Remove Entity State
EVENT_STATE_CHANGED with new_state=None.
Reference: homeassistant/core.py:2169
State Persistence
Internal State Format
States are internally compressed for efficiency:homeassistant/core.py:1708
Advanced State Patterns
State Validation
homeassistant/core.py:200
Entity ID Validation
homeassistant/core.py:192, homeassistant/core.py:171
Tracking Multiple Entities
homeassistant/helpers/event.py:309
State Attribute Updates
Update only attributes without changing state:State Machine Indexes
The state machine maintains indexes for performance:Domain Index
homeassistant/core.py:2016
Best Practices
1. Use Async Methods
Always use async methods in the event loop:2. Check for None
Always handle missing states:3. Use Appropriate Tracking
Use helpers instead of manual event listening:4. Minimize State Updates
Only update when necessary:5. Use Context
Provide context for state changes:Performance Considerations
- State reads are fast - Direct dictionary lookup
- State writes fire events - Consider batch updates
- Domain filtering is optimized - Uses internal index
- Attributes are immutable - Uses ReadOnlyDict for safety