0
# Core System
1
2
Central Home Assistant runtime providing the foundation for all automation and integration functionality. The core system includes the main HomeAssistant instance, event system, state management, service registry, and fundamental coordination mechanisms.
3
4
## Capabilities
5
6
### HomeAssistant Instance
7
8
The central coordinator that manages all Home Assistant components, services, and state. Acts as the main entry point and context for all Home Assistant operations.
9
10
```python { .api }
11
class HomeAssistant:
12
"""Main Home Assistant instance."""
13
14
def __init__(self, config_dir: str):
15
"""Initialize Home Assistant instance.
16
17
Args:
18
config_dir: Path to configuration directory (required)
19
"""
20
21
async def async_start(self) -> None:
22
"""Start Home Assistant."""
23
24
async def async_stop(self, exit_code: int = 0, *, force: bool = False) -> None:
25
"""Stop Home Assistant.
26
27
Args:
28
exit_code: Exit code for shutdown
29
force: Force stop regardless of current state (used for testing)
30
"""
31
32
async def async_run(self, *, attach_signals: bool = True) -> int:
33
"""Run Home Assistant.
34
35
Args:
36
attach_signals: Whether to attach signal handlers
37
38
Returns:
39
Exit code
40
"""
41
42
def async_create_task(self, target: Coroutine, name: str = None, eager_start: bool = True) -> asyncio.Task:
43
"""Create a task that will be tracked by Home Assistant.
44
45
Args:
46
target: Coroutine to run
47
name: Optional name for the task
48
eager_start: Whether to start the task eagerly
49
50
Returns:
51
Created task
52
"""
53
54
def async_add_job(self, target: Callable | Coroutine, *args, eager_start: bool = False) -> asyncio.Future | None:
55
"""Add job to be executed.
56
57
Args:
58
target: Function or coroutine to execute
59
*args: Arguments for target
60
eager_start: Whether to start the job eagerly
61
62
Returns:
63
Future representing the job result
64
"""
65
66
# Core subsystem properties
67
states: StateMachine
68
services: ServiceRegistry
69
bus: EventBus
70
config: Config
71
data: dict
72
loop: asyncio.AbstractEventLoop
73
74
@property
75
def is_running(self) -> bool:
76
"""Return if Home Assistant is running."""
77
78
@property
79
def is_stopping(self) -> bool:
80
"""Return if Home Assistant is stopping."""
81
82
@property
83
def state(self) -> CoreState:
84
"""Return the current state of Home Assistant."""
85
```
86
87
### Context
88
89
Execution context that tracks the origin and flow of events, state changes, and service calls throughout the system.
90
91
```python { .api }
92
class Context:
93
"""Context of an event, state change, or service call."""
94
95
def __init__(self, user_id: str = None, parent_id: str = None, id: str = None):
96
"""Initialize context.
97
98
Args:
99
user_id: ID of user that initiated the action
100
parent_id: ID of parent context
101
id: Context ID (generated if not provided)
102
"""
103
104
@property
105
def user_id(self) -> str:
106
"""Return user ID."""
107
108
@property
109
def parent_id(self) -> str:
110
"""Return parent context ID."""
111
112
@property
113
def origin(self) -> str:
114
"""Return origin of context."""
115
116
@property
117
def id(self) -> str:
118
"""Return unique context ID."""
119
```
120
121
### Event System
122
123
Core event publication and subscription system enabling real-time communication between Home Assistant components.
124
125
```python { .api }
126
class Event:
127
"""Representation of an event within the event bus."""
128
129
def __init__(self, event_type: str, data: dict = None, origin: EventOrigin = None,
130
time_fired: datetime = None, context: Context = None):
131
"""Initialize event.
132
133
Args:
134
event_type: Type of event
135
data: Event data
136
origin: Origin of event (EventOrigin enum)
137
time_fired: Time event was fired
138
context: Event context
139
"""
140
141
@property
142
def event_type(self) -> str:
143
"""Return event type."""
144
145
@property
146
def data(self) -> dict:
147
"""Return event data."""
148
149
@property
150
def origin(self) -> str:
151
"""Return event origin."""
152
153
@property
154
def time_fired(self) -> datetime:
155
"""Return time event was fired."""
156
157
@property
158
def time_fired_timestamp(self) -> float:
159
"""Return timestamp when event was fired."""
160
161
@property
162
def context(self) -> Context:
163
"""Return event context."""
164
165
class EventBus:
166
"""Event bus for firing and listening to events."""
167
168
def fire(self, event_type: str, event_data: dict = None, origin: str = None,
169
context: Context = None) -> None:
170
"""Fire an event.
171
172
Args:
173
event_type: Type of event to fire
174
event_data: Event data
175
origin: Origin of event
176
context: Event context
177
"""
178
179
async def async_fire(self, event_type: str, event_data: dict = None,
180
origin: str = None, context: Context = None) -> None:
181
"""Fire an event asynchronously.
182
183
Args:
184
event_type: Type of event to fire
185
event_data: Event data
186
origin: Origin of event
187
context: Event context
188
"""
189
190
def listen(self, event_type: str, listener: Callable) -> Callable:
191
"""Listen for events of a specific type.
192
193
Args:
194
event_type: Type of event to listen for
195
listener: Function to call when event occurs
196
197
Returns:
198
Function to remove listener
199
"""
200
201
def async_listen(self, event_type: str, listener: Callable) -> Callable:
202
"""Listen for events asynchronously.
203
204
Args:
205
event_type: Type of event to listen for
206
listener: Async function to call when event occurs
207
208
Returns:
209
Function to remove listener
210
"""
211
212
def listen_once(self, event_type: str, listener: Callable) -> Callable:
213
"""Listen for first event of a specific type.
214
215
Args:
216
event_type: Type of event to listen for
217
listener: Function to call when event occurs
218
219
Returns:
220
Function to remove listener
221
"""
222
```
223
224
### State Management
225
226
Central state machine that tracks and manages the state of all entities in Home Assistant.
227
228
```python { .api }
229
class State:
230
"""Object to represent a state."""
231
232
def __init__(self, entity_id: str, state: str, attributes: dict = None,
233
last_changed: datetime = None, last_updated: datetime = None,
234
context: Context = None):
235
"""Initialize state.
236
237
Args:
238
entity_id: Entity ID
239
state: State value
240
attributes: State attributes
241
last_changed: When state last changed
242
last_updated: When state was last updated
243
context: State context
244
"""
245
246
@property
247
def entity_id(self) -> str:
248
"""Return entity ID."""
249
250
@property
251
def state(self) -> str:
252
"""Return state value."""
253
254
@property
255
def attributes(self) -> dict:
256
"""Return state attributes."""
257
258
@property
259
def last_changed(self) -> datetime:
260
"""Return when state last changed."""
261
262
@property
263
def last_updated(self) -> datetime:
264
"""Return when state was last updated."""
265
266
@property
267
def context(self) -> Context:
268
"""Return state context."""
269
270
@property
271
def domain(self) -> str:
272
"""Return entity domain."""
273
274
@property
275
def object_id(self) -> str:
276
"""Return entity object ID."""
277
278
class StateMachine:
279
"""State machine to track states of entities."""
280
281
def get(self, entity_id: str) -> State:
282
"""Retrieve state of entity.
283
284
Args:
285
entity_id: Entity ID to get state for
286
287
Returns:
288
State object or None if not found
289
"""
290
291
def set(self, entity_id: str, new_state: str, attributes: dict = None,
292
force_update: bool = False, context: Context = None) -> State:
293
"""Set state of an entity.
294
295
Args:
296
entity_id: Entity ID to set state for
297
new_state: New state value
298
attributes: State attributes
299
force_update: Force update even if state unchanged
300
context: State context
301
302
Returns:
303
New state object
304
"""
305
306
async def async_set(self, entity_id: str, new_state: str,
307
attributes: dict = None, force_update: bool = False,
308
context: Context = None) -> State:
309
"""Set state of an entity asynchronously.
310
311
Args:
312
entity_id: Entity ID to set state for
313
new_state: New state value
314
attributes: State attributes
315
force_update: Force update even if state unchanged
316
context: State context
317
318
Returns:
319
New state object
320
"""
321
322
def remove(self, entity_id: str) -> bool:
323
"""Remove state of entity.
324
325
Args:
326
entity_id: Entity ID to remove
327
328
Returns:
329
True if entity was removed
330
"""
331
332
async def async_remove(self, entity_id: str, context: Context = None) -> bool:
333
"""Remove state of entity asynchronously.
334
335
Args:
336
entity_id: Entity ID to remove
337
context: Removal context
338
339
Returns:
340
True if entity was removed
341
"""
342
343
@property
344
def entity_ids(self) -> list[str]:
345
"""Return list of entity IDs."""
346
347
def all(self, domain_filter: str = None) -> list[State]:
348
"""Get all states.
349
350
Args:
351
domain_filter: Optional domain to filter by
352
353
Returns:
354
List of state objects
355
"""
356
```
357
358
### Service Registry
359
360
System for registering, managing, and calling services that perform actions in Home Assistant.
361
362
```python { .api }
363
class ServiceCall:
364
"""Representation of a service call."""
365
366
def __init__(self, domain: str, service: str, data: dict = None,
367
context: Context = None, hass: HomeAssistant = None):
368
"""Initialize service call.
369
370
Args:
371
domain: Service domain
372
service: Service name
373
data: Service data
374
context: Service context
375
hass: Home Assistant instance
376
"""
377
378
@property
379
def domain(self) -> str:
380
"""Return service domain."""
381
382
@property
383
def service(self) -> str:
384
"""Return service name."""
385
386
@property
387
def data(self) -> dict:
388
"""Return service data."""
389
390
@property
391
def context(self) -> Context:
392
"""Return service context."""
393
394
class ServiceRegistry:
395
"""Registry of services."""
396
397
def register(self, domain: str, service: str, service_func: Callable,
398
schema: dict = None) -> None:
399
"""Register a service.
400
401
Args:
402
domain: Service domain
403
service: Service name
404
service_func: Function to call for service
405
schema: Voluptuous schema for service data
406
"""
407
408
async def async_register(self, domain: str, service: str,
409
service_func: Callable, schema: dict = None) -> None:
410
"""Register a service asynchronously.
411
412
Args:
413
domain: Service domain
414
service: Service name
415
service_func: Async function to call for service
416
schema: Voluptuous schema for service data
417
"""
418
419
def call(self, domain: str, service: str, service_data: dict = None,
420
blocking: bool = False, context: Context = None) -> bool:
421
"""Call a service.
422
423
Args:
424
domain: Service domain
425
service: Service name
426
service_data: Service data
427
blocking: Wait for service to complete
428
context: Service context
429
430
Returns:
431
True if service was called successfully
432
"""
433
434
async def async_call(self, domain: str, service: str,
435
service_data: dict = None, blocking: bool = False,
436
context: Context = None) -> bool:
437
"""Call a service asynchronously.
438
439
Args:
440
domain: Service domain
441
service: Service name
442
service_data: Service data
443
blocking: Wait for service to complete
444
context: Service context
445
446
Returns:
447
True if service was called successfully
448
"""
449
450
def has_service(self, domain: str, service: str) -> bool:
451
"""Check if service exists.
452
453
Args:
454
domain: Service domain
455
service: Service name
456
457
Returns:
458
True if service exists
459
"""
460
461
@property
462
def services(self) -> dict:
463
"""Return dictionary of registered services."""
464
```
465
466
### Core Utility Functions
467
468
Essential utility functions for working with the core system.
469
470
```python { .api }
471
def callback(func: Callable) -> Callable:
472
"""Decorator to mark function as safe to call from event loop.
473
474
Args:
475
func: Function to decorate
476
477
Returns:
478
Decorated function
479
"""
480
481
def split_entity_id(entity_id: str) -> tuple[str, str]:
482
"""Split entity ID into domain and object ID.
483
484
Args:
485
entity_id: Entity ID to split
486
487
Returns:
488
Tuple of (domain, object_id)
489
"""
490
491
def valid_entity_id(entity_id: str) -> bool:
492
"""Validate entity ID format.
493
494
Args:
495
entity_id: Entity ID to validate
496
497
Returns:
498
True if valid entity ID format
499
"""
500
501
async def async_get_hass() -> HomeAssistant:
502
"""Get current Home Assistant instance.
503
504
Returns:
505
HomeAssistant instance
506
"""
507
```
508
509
## Types
510
511
```python { .api }
512
from enum import Enum
513
from typing import Any, Callable, Dict, Optional, Union
514
import asyncio
515
516
# Event origin enum
517
class EventOrigin(Enum):
518
"""Origin of an event."""
519
local = "LOCAL"
520
remote = "REMOTE"
521
522
# Core state enum
523
class CoreState(Enum):
524
"""Core state of Home Assistant."""
525
not_running = "NOT_RUNNING"
526
starting = "STARTING"
527
running = "RUNNING"
528
stopping = "STOPPING"
529
final_write = "FINAL_WRITE"
530
531
# Type aliases
532
EventType = str
533
StateType = Union[None, str, int, float, bool]
534
ServiceDataType = Dict[str, Any]
535
ConfigType = Dict[str, Any]
536
CallbackType = Callable[[], None]
537
EventListenerType = Callable[[Event], Union[None, Coroutine]]
538
ServiceHandlerType = Callable[[ServiceCall], Union[None, Coroutine]]
539
```