-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
/
core.py
2853 lines (2375 loc) · 95.9 KB
/
core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Core components of Home Assistant.
Home Assistant is a Home Automation framework for observing the state
of entities and react to changes.
"""
from __future__ import annotations
import asyncio
from collections import UserDict, defaultdict
from collections.abc import (
Callable,
Collection,
Coroutine,
Iterable,
KeysView,
Mapping,
ValuesView,
)
import concurrent.futures
from dataclasses import dataclass
import datetime
import enum
import functools
import inspect
import logging
import re
import threading
import time
from time import monotonic
from typing import (
TYPE_CHECKING,
Any,
Final,
Generic,
NotRequired,
Self,
TypedDict,
cast,
overload,
)
from propcache import cached_property, under_cached_property
from typing_extensions import TypeVar
import voluptuous as vol
from . import util
from .const import (
ATTR_DOMAIN,
ATTR_FRIENDLY_NAME,
ATTR_SERVICE,
ATTR_SERVICE_DATA,
COMPRESSED_STATE_ATTRIBUTES,
COMPRESSED_STATE_CONTEXT,
COMPRESSED_STATE_LAST_CHANGED,
COMPRESSED_STATE_LAST_UPDATED,
COMPRESSED_STATE_STATE,
EVENT_CALL_SERVICE,
EVENT_CORE_CONFIG_UPDATE,
EVENT_HOMEASSISTANT_CLOSE,
EVENT_HOMEASSISTANT_FINAL_WRITE,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STARTED,
EVENT_HOMEASSISTANT_STOP,
EVENT_LOGGING_CHANGED,
EVENT_SERVICE_REGISTERED,
EVENT_SERVICE_REMOVED,
EVENT_STATE_CHANGED,
EVENT_STATE_REPORTED,
MATCH_ALL,
MAX_EXPECTED_ENTITY_IDS,
MAX_LENGTH_EVENT_EVENT_TYPE,
MAX_LENGTH_STATE_STATE,
__version__,
)
from .exceptions import (
HomeAssistantError,
InvalidEntityFormatError,
InvalidStateError,
MaxLengthExceeded,
ServiceNotFound,
ServiceValidationError,
Unauthorized,
)
from .helpers.deprecation import (
DeferredDeprecatedAlias,
EnumWithDeprecatedMembers,
all_with_deprecated_constants,
check_if_deprecated_constant,
dir_with_deprecated_constants,
)
from .helpers.json import json_bytes, json_fragment
from .helpers.typing import VolSchemaType
from .util import dt as dt_util
from .util.async_ import (
cancelling,
create_eager_task,
get_scheduled_timer_handles,
run_callback_threadsafe,
shutdown_run_callback_threadsafe,
)
from .util.event_type import EventType
from .util.executor import InterruptibleThreadPoolExecutor
from .util.hass_dict import HassDict
from .util.json import JsonObjectType
from .util.read_only_dict import ReadOnlyDict
from .util.timeout import TimeoutManager
from .util.ulid import ulid_at_time, ulid_now
# Typing imports that create a circular dependency
if TYPE_CHECKING:
from .auth import AuthManager
from .components.http import HomeAssistantHTTP
from .config_entries import ConfigEntries
from .helpers.entity import StateInfo
STOPPING_STAGE_SHUTDOWN_TIMEOUT = 20
STOP_STAGE_SHUTDOWN_TIMEOUT = 100
FINAL_WRITE_STAGE_SHUTDOWN_TIMEOUT = 60
CLOSE_STAGE_SHUTDOWN_TIMEOUT = 30
_SENTINEL = object()
_DataT = TypeVar("_DataT", bound=Mapping[str, Any], default=Mapping[str, Any])
type CALLBACK_TYPE = Callable[[], None]
DOMAIN = "homeassistant"
# How long to wait to log tasks that are blocking
BLOCK_LOG_TIMEOUT = 60
type ServiceResponse = JsonObjectType | None
type EntityServiceResponse = dict[str, ServiceResponse]
class ConfigSource(
enum.StrEnum,
metaclass=EnumWithDeprecatedMembers,
deprecated={
"DEFAULT": ("core_config.ConfigSource.DEFAULT", "2025.11.0"),
"DISCOVERED": ("core_config.ConfigSource.DISCOVERED", "2025.11.0"),
"STORAGE": ("core_config.ConfigSource.STORAGE", "2025.11.0"),
"YAML": ("core_config.ConfigSource.YAML", "2025.11.0"),
},
):
"""Source of core configuration."""
DEFAULT = "default"
DISCOVERED = "discovered"
STORAGE = "storage"
YAML = "yaml"
class EventStateEventData(TypedDict):
"""Base class for EVENT_STATE_CHANGED and EVENT_STATE_REPORTED data."""
entity_id: str
new_state: State | None
class EventStateChangedData(EventStateEventData):
"""EVENT_STATE_CHANGED data.
A state changed event is fired when on state write the state is changed.
"""
old_state: State | None
class EventStateReportedData(EventStateEventData):
"""EVENT_STATE_REPORTED data.
A state reported event is fired when on state write the state is unchanged.
"""
old_last_reported: datetime.datetime
def _deprecated_core_config() -> Any:
# pylint: disable-next=import-outside-toplevel
from . import core_config
return core_config.Config
# The Config class was moved to core_config in Home Assistant 2024.11
_DEPRECATED_Config = DeferredDeprecatedAlias(
_deprecated_core_config, "homeassistant.core_config.Config", "2025.11"
)
# How long to wait until things that run on startup have to finish.
TIMEOUT_EVENT_START = 15
EVENTS_EXCLUDED_FROM_MATCH_ALL = {
EVENT_HOMEASSISTANT_CLOSE,
EVENT_STATE_REPORTED,
}
_LOGGER = logging.getLogger(__name__)
@functools.lru_cache(MAX_EXPECTED_ENTITY_IDS)
def split_entity_id(entity_id: str) -> tuple[str, str]:
"""Split a state entity ID into domain and object ID."""
domain, _, object_id = entity_id.partition(".")
if not domain or not object_id:
raise ValueError(f"Invalid entity ID {entity_id}")
return domain, object_id
_OBJECT_ID = r"(?!_)[\da-z_]+(?<!_)"
_DOMAIN = r"(?!.+__)" + _OBJECT_ID
VALID_DOMAIN = re.compile(r"^" + _DOMAIN + r"$")
VALID_ENTITY_ID = re.compile(r"^" + _DOMAIN + r"\." + _OBJECT_ID + r"$")
@functools.lru_cache(64)
def valid_domain(domain: str) -> bool:
"""Test if a domain a valid format."""
return VALID_DOMAIN.match(domain) is not None
@functools.lru_cache(512)
def valid_entity_id(entity_id: str) -> bool:
"""Test if an entity ID is a valid format.
Format: <domain>.<entity> where both are slugs.
"""
return VALID_ENTITY_ID.match(entity_id) is not None
def validate_state(state: str) -> str:
"""Validate a state, raise if it not valid."""
if len(state) > MAX_LENGTH_STATE_STATE:
raise InvalidStateError(
f"Invalid state with length {len(state)}. "
"State max length is 255 characters."
)
return state
def callback[_CallableT: Callable[..., Any]](func: _CallableT) -> _CallableT:
"""Annotation to mark method as safe to call from within the event loop."""
setattr(func, "_hass_callback", True)
return func
def is_callback(func: Callable[..., Any]) -> bool:
"""Check if function is safe to be called in the event loop."""
return getattr(func, "_hass_callback", False) is True
def is_callback_check_partial(target: Callable[..., Any]) -> bool:
"""Check if function is safe to be called in the event loop.
This version of is_callback will also check if the target is a partial
and walk the chain of partials to find the original function.
"""
check_target = target
while isinstance(check_target, functools.partial):
check_target = check_target.func
return is_callback(check_target)
class _Hass(threading.local):
"""Container which makes a HomeAssistant instance available to the event loop."""
hass: HomeAssistant | None = None
_hass = _Hass()
@callback
def async_get_hass() -> HomeAssistant:
"""Return the HomeAssistant instance.
Raises HomeAssistantError when called from the wrong thread.
This should be used where it's very cumbersome or downright impossible to pass
hass to the code which needs it.
"""
if not (hass := async_get_hass_or_none()):
raise HomeAssistantError("async_get_hass called from the wrong thread")
return hass
def async_get_hass_or_none() -> HomeAssistant | None:
"""Return the HomeAssistant instance or None.
Returns None when called from the wrong thread.
"""
return _hass.hass
class ReleaseChannel(enum.StrEnum):
BETA = "beta"
DEV = "dev"
NIGHTLY = "nightly"
STABLE = "stable"
@callback
def get_release_channel() -> ReleaseChannel:
"""Find release channel based on version number."""
version = __version__
if "dev0" in version:
return ReleaseChannel.DEV
if "dev" in version:
return ReleaseChannel.NIGHTLY
if "b" in version:
return ReleaseChannel.BETA
return ReleaseChannel.STABLE
@enum.unique
class HassJobType(enum.Enum):
"""Represent a job type."""
Coroutinefunction = 1
Callback = 2
Executor = 3
class HassJob[**_P, _R_co]:
"""Represent a job to be run later.
We check the callable type in advance
so we can avoid checking it every time
we run the job.
"""
__slots__ = ("target", "name", "_cancel_on_shutdown", "_cache")
def __init__(
self,
target: Callable[_P, _R_co],
name: str | None = None,
*,
cancel_on_shutdown: bool | None = None,
job_type: HassJobType | None = None,
) -> None:
"""Create a job object."""
self.target: Final = target
self.name = name
self._cancel_on_shutdown = cancel_on_shutdown
self._cache: dict[str, Any] = {}
if job_type:
# Pre-set the cached_property so we
# avoid the function call
self._cache["job_type"] = job_type
@under_cached_property
def job_type(self) -> HassJobType:
"""Return the job type."""
return get_hassjob_callable_job_type(self.target)
@property
def cancel_on_shutdown(self) -> bool | None:
"""Return if the job should be cancelled on shutdown."""
return self._cancel_on_shutdown
def __repr__(self) -> str:
"""Return the job."""
return f"<Job {self.name} {self.job_type} {self.target}>"
@dataclass(frozen=True)
class HassJobWithArgs:
"""Container for a HassJob and arguments."""
job: HassJob[..., Coroutine[Any, Any, Any] | Any]
args: Iterable[Any]
def get_hassjob_callable_job_type(target: Callable[..., Any]) -> HassJobType:
"""Determine the job type from the callable."""
# Check for partials to properly determine if coroutine function
check_target = target
while isinstance(check_target, functools.partial):
check_target = check_target.func
if asyncio.iscoroutinefunction(check_target):
return HassJobType.Coroutinefunction
if is_callback(check_target):
return HassJobType.Callback
if asyncio.iscoroutine(check_target):
raise ValueError("Coroutine not allowed to be passed to HassJob")
return HassJobType.Executor
class CoreState(enum.Enum):
"""Represent the current state of Home Assistant."""
not_running = "NOT_RUNNING"
starting = "STARTING"
running = "RUNNING"
stopping = "STOPPING"
final_write = "FINAL_WRITE"
stopped = "STOPPED"
def __str__(self) -> str:
"""Return the event."""
return self.value
class HomeAssistant:
"""Root object of the Home Assistant home automation."""
auth: AuthManager
http: HomeAssistantHTTP = None # type: ignore[assignment]
config_entries: ConfigEntries = None # type: ignore[assignment]
def __new__(cls, config_dir: str) -> Self:
"""Set the _hass thread local data."""
hass = super().__new__(cls)
_hass.hass = hass
return hass
def __repr__(self) -> str:
"""Return the representation."""
return f"<HomeAssistant {self.state}>"
def __init__(self, config_dir: str) -> None:
"""Initialize new Home Assistant object."""
# pylint: disable-next=import-outside-toplevel
from . import loader
# pylint: disable-next=import-outside-toplevel
from .core_config import Config
# This is a dictionary that any component can store any data on.
self.data = HassDict()
self.loop = asyncio.get_running_loop()
self._tasks: set[asyncio.Future[Any]] = set()
self._background_tasks: set[asyncio.Future[Any]] = set()
self.bus = EventBus(self)
self.services = ServiceRegistry(self)
self.states = StateMachine(self.bus, self.loop)
self.config = Config(self, config_dir)
self.config.async_initialize()
self.components = loader.Components(self)
self.helpers = loader.Helpers(self)
self.state: CoreState = CoreState.not_running
self.exit_code: int = 0
# If not None, use to signal end-of-loop
self._stopped: asyncio.Event | None = None
# Timeout handler for Core/Helper namespace
self.timeout: TimeoutManager = TimeoutManager()
self._stop_future: concurrent.futures.Future[None] | None = None
self._shutdown_jobs: list[HassJobWithArgs] = []
self.import_executor = InterruptibleThreadPoolExecutor(
max_workers=1, thread_name_prefix="ImportExecutor"
)
self.loop_thread_id = getattr(self.loop, "_thread_id")
def verify_event_loop_thread(self, what: str) -> None:
"""Report and raise if we are not running in the event loop thread."""
if self.loop_thread_id != threading.get_ident():
# frame is a circular import, so we import it here
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report_non_thread_safe_operation(what)
@property
def _active_tasks(self) -> set[asyncio.Future[Any]]:
"""Return all active tasks.
This property is used in bootstrap to log all active tasks
so we can identify what is blocking startup.
This property is marked as private to avoid accidental use
as it is not guaranteed to be present in future versions.
"""
return self._tasks
@cached_property
def is_running(self) -> bool:
"""Return if Home Assistant is running."""
return self.state in (CoreState.starting, CoreState.running)
@cached_property
def is_stopping(self) -> bool:
"""Return if Home Assistant is stopping."""
return self.state in (CoreState.stopping, CoreState.final_write)
def set_state(self, state: CoreState) -> None:
"""Set the current state."""
self.state = state
for prop in ("is_running", "is_stopping"):
self.__dict__.pop(prop, None)
def start(self) -> int:
"""Start Home Assistant.
Note: This function is only used for testing.
For regular use, use "await hass.run()".
"""
# Register the async start
_future = asyncio.run_coroutine_threadsafe(self.async_start(), self.loop)
# Run forever
# Block until stopped
_LOGGER.info("Starting Home Assistant core loop")
self.loop.run_forever()
# The future is never retrieved but we still hold a reference to it
# to prevent the task from being garbage collected prematurely.
del _future
return self.exit_code
async def async_run(self, *, attach_signals: bool = True) -> int:
"""Home Assistant main entry point.
Start Home Assistant and block until stopped.
This method is a coroutine.
"""
if self.state is not CoreState.not_running:
raise RuntimeError("Home Assistant is already running")
# _async_stop will set this instead of stopping the loop
self._stopped = asyncio.Event()
await self.async_start()
if attach_signals:
# pylint: disable-next=import-outside-toplevel
from .helpers.signal import async_register_signal_handling
async_register_signal_handling(self)
await self._stopped.wait()
return self.exit_code
async def async_start(self) -> None:
"""Finalize startup from inside the event loop.
This method is a coroutine.
"""
_LOGGER.info("Starting Home Assistant")
self.set_state(CoreState.starting)
self.bus.async_fire_internal(EVENT_CORE_CONFIG_UPDATE)
self.bus.async_fire_internal(EVENT_HOMEASSISTANT_START)
if not self._tasks:
pending: set[asyncio.Future[Any]] | None = None
else:
_done, pending = await asyncio.wait(
self._tasks, timeout=TIMEOUT_EVENT_START
)
if pending:
_LOGGER.warning(
(
"Something is blocking Home Assistant from wrapping up the start up"
" phase. We're going to continue anyway. Please report the"
" following info at"
" https://github.com/home-assistant/core/issues: %s"
" The system is waiting for tasks: %s"
),
", ".join(self.config.components),
self._tasks,
)
# Allow automations to set up the start triggers before changing state
await asyncio.sleep(0)
if self.state is not CoreState.starting:
_LOGGER.warning(
"Home Assistant startup has been interrupted. "
"Its state may be inconsistent"
)
return
self.set_state(CoreState.running)
self.bus.async_fire_internal(EVENT_CORE_CONFIG_UPDATE)
self.bus.async_fire_internal(EVENT_HOMEASSISTANT_STARTED)
def add_job[*_Ts](
self, target: Callable[[*_Ts], Any] | Coroutine[Any, Any, Any], *args: *_Ts
) -> None:
"""Add a job to be executed by the event loop or by an executor.
If the job is either a coroutine or decorated with @callback, it will be
run by the event loop, if not it will be run by an executor.
target: target to call.
args: parameters for method to call.
"""
if target is None:
raise ValueError("Don't call add_job with None")
if asyncio.iscoroutine(target):
self.loop.call_soon_threadsafe(
functools.partial(self.async_create_task, target, eager_start=True)
)
return
self.loop.call_soon_threadsafe(
functools.partial(self._async_add_hass_job, HassJob(target), *args)
)
@overload
@callback
def async_add_job[_R, *_Ts](
self,
target: Callable[[*_Ts], Coroutine[Any, Any, _R]],
*args: *_Ts,
eager_start: bool = False,
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_add_job[_R, *_Ts](
self,
target: Callable[[*_Ts], Coroutine[Any, Any, _R] | _R],
*args: *_Ts,
eager_start: bool = False,
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_add_job[_R](
self,
target: Coroutine[Any, Any, _R],
*args: Any,
eager_start: bool = False,
) -> asyncio.Future[_R] | None: ...
@callback
def async_add_job[_R, *_Ts](
self,
target: Callable[[*_Ts], Coroutine[Any, Any, _R] | _R]
| Coroutine[Any, Any, _R],
*args: *_Ts,
eager_start: bool = False,
) -> asyncio.Future[_R] | None:
"""Add a job to be executed by the event loop or by an executor.
If the job is either a coroutine or decorated with @callback, it will be
run by the event loop, if not it will be run by an executor.
This method must be run in the event loop.
target: target to call.
args: parameters for method to call.
"""
# late import to avoid circular imports
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report_usage(
"calls `async_add_job`, which should be reviewed against "
"https://developers.home-assistant.io/blog/2024/03/13/deprecate_add_run_job"
" for replacement options",
core_behavior=frame.ReportBehavior.LOG,
breaks_in_ha_version="2025.4",
)
if target is None:
raise ValueError("Don't call async_add_job with None")
if asyncio.iscoroutine(target):
return self.async_create_task(target, eager_start=eager_start)
return self._async_add_hass_job(HassJob(target), *args)
@overload
@callback
def async_add_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R]],
*args: Any,
eager_start: bool = False,
background: bool = False,
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_add_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
eager_start: bool = False,
background: bool = False,
) -> asyncio.Future[_R] | None: ...
@callback
def async_add_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
eager_start: bool = False,
background: bool = False,
) -> asyncio.Future[_R] | None:
"""Add a HassJob from within the event loop.
If eager_start is True, coroutine functions will be scheduled eagerly.
If background is True, the task will created as a background task.
This method must be run in the event loop.
hassjob: HassJob to call.
args: parameters for method to call.
"""
# late import to avoid circular imports
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report_usage(
"calls `async_add_hass_job`, which should be reviewed against "
"https://developers.home-assistant.io/blog/2024/04/07/deprecate_add_hass_job"
" for replacement options",
core_behavior=frame.ReportBehavior.LOG,
breaks_in_ha_version="2025.5",
)
return self._async_add_hass_job(hassjob, *args, background=background)
@overload
@callback
def _async_add_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R]],
*args: Any,
background: bool = False,
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def _async_add_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
background: bool = False,
) -> asyncio.Future[_R] | None: ...
@callback
def _async_add_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
background: bool = False,
) -> asyncio.Future[_R] | None:
"""Add a HassJob from within the event loop.
If eager_start is True, coroutine functions will be scheduled eagerly.
If background is True, the task will created as a background task.
This method must be run in the event loop.
hassjob: HassJob to call.
args: parameters for method to call.
"""
task: asyncio.Future[_R]
# This code path is performance sensitive and uses
# if TYPE_CHECKING to avoid the overhead of constructing
# the type used for the cast. For history see:
# https://github.com/home-assistant/core/pull/71960
if hassjob.job_type is HassJobType.Coroutinefunction:
if TYPE_CHECKING:
hassjob = cast(HassJob[..., Coroutine[Any, Any, _R]], hassjob)
task = create_eager_task(
hassjob.target(*args), name=hassjob.name, loop=self.loop
)
if task.done():
return task
elif hassjob.job_type is HassJobType.Callback:
if TYPE_CHECKING:
hassjob = cast(HassJob[..., _R], hassjob)
self.loop.call_soon(hassjob.target, *args)
return None
else:
if TYPE_CHECKING:
hassjob = cast(HassJob[..., _R], hassjob)
task = self.loop.run_in_executor(None, hassjob.target, *args)
task_bucket = self._background_tasks if background else self._tasks
task_bucket.add(task)
task.add_done_callback(task_bucket.remove)
return task
def create_task(
self, target: Coroutine[Any, Any, Any], name: str | None = None
) -> None:
"""Add task to the executor pool.
target: target to call.
"""
self.loop.call_soon_threadsafe(
functools.partial(
self.async_create_task_internal, target, name, eager_start=True
)
)
@callback
def async_create_task[_R](
self,
target: Coroutine[Any, Any, _R],
name: str | None = None,
eager_start: bool = True,
) -> asyncio.Task[_R]:
"""Create a task from within the event loop.
This method must be run in the event loop. If you are using this in your
integration, use the create task methods on the config entry instead.
target: target to call.
"""
if self.loop_thread_id != threading.get_ident():
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report_non_thread_safe_operation("hass.async_create_task")
return self.async_create_task_internal(target, name, eager_start)
@callback
def async_create_task_internal[_R](
self,
target: Coroutine[Any, Any, _R],
name: str | None = None,
eager_start: bool = True,
) -> asyncio.Task[_R]:
"""Create a task from within the event loop, internal use only.
This method is intended to only be used by core internally
and should not be considered a stable API. We will make
breaking changes to this function in the future and it
should not be used in integrations.
This method must be run in the event loop. If you are using this in your
integration, use the create task methods on the config entry instead.
target: target to call.
"""
if eager_start:
task = create_eager_task(target, name=name, loop=self.loop)
if task.done():
return task
else:
# Use loop.create_task
# to avoid the extra function call in asyncio.create_task.
task = self.loop.create_task(target, name=name)
self._tasks.add(task)
task.add_done_callback(self._tasks.remove)
return task
@callback
def async_create_background_task[_R](
self, target: Coroutine[Any, Any, _R], name: str, eager_start: bool = True
) -> asyncio.Task[_R]:
"""Create a task from within the event loop.
This type of task is for background tasks that usually run for
the lifetime of Home Assistant or an integration's setup.
A background task is different from a normal task:
- Will not block startup
- Will be automatically cancelled on shutdown
- Calls to async_block_till_done will not wait for completion
If you are using this in your integration, use the create task
methods on the config entry instead.
This method must be run in the event loop.
"""
if eager_start:
task = create_eager_task(target, name=name, loop=self.loop)
if task.done():
return task
else:
# Use loop.create_task
# to avoid the extra function call in asyncio.create_task.
task = self.loop.create_task(target, name=name)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.remove)
return task
@callback
def async_add_executor_job[*_Ts, _T](
self, target: Callable[[*_Ts], _T], *args: *_Ts
) -> asyncio.Future[_T]:
"""Add an executor job from within the event loop."""
task = self.loop.run_in_executor(None, target, *args)
tracked = asyncio.current_task() in self._tasks
task_bucket = self._tasks if tracked else self._background_tasks
task_bucket.add(task)
task.add_done_callback(task_bucket.remove)
return task
@callback
def async_add_import_executor_job[*_Ts, _T](
self, target: Callable[[*_Ts], _T], *args: *_Ts
) -> asyncio.Future[_T]:
"""Add an import executor job from within the event loop.
The future returned from this method must be awaited in the event loop.
"""
return self.loop.run_in_executor(self.import_executor, target, *args)
@overload
@callback
def async_run_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R]],
*args: Any,
background: bool = False,
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_run_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
background: bool = False,
) -> asyncio.Future[_R] | None: ...
@callback
def async_run_hass_job[_R](
self,
hassjob: HassJob[..., Coroutine[Any, Any, _R] | _R],
*args: Any,
background: bool = False,
) -> asyncio.Future[_R] | None:
"""Run a HassJob from within the event loop.
This method must be run in the event loop.
If background is True, the task will created as a background task.
hassjob: HassJob
args: parameters for method to call.
"""
# This code path is performance sensitive and uses
# if TYPE_CHECKING to avoid the overhead of constructing
# the type used for the cast. For history see:
# https://github.com/home-assistant/core/pull/71960
if hassjob.job_type is HassJobType.Callback:
if TYPE_CHECKING:
hassjob = cast(HassJob[..., _R], hassjob)
hassjob.target(*args)
return None
return self._async_add_hass_job(hassjob, *args, background=background)
@overload
@callback
def async_run_job[_R, *_Ts](
self, target: Callable[[*_Ts], Coroutine[Any, Any, _R]], *args: *_Ts
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_run_job[_R, *_Ts](
self, target: Callable[[*_Ts], Coroutine[Any, Any, _R] | _R], *args: *_Ts
) -> asyncio.Future[_R] | None: ...
@overload
@callback
def async_run_job[_R](
self, target: Coroutine[Any, Any, _R], *args: Any
) -> asyncio.Future[_R] | None: ...
@callback
def async_run_job[_R, *_Ts](
self,
target: Callable[[*_Ts], Coroutine[Any, Any, _R] | _R]
| Coroutine[Any, Any, _R],
*args: *_Ts,
) -> asyncio.Future[_R] | None:
"""Run a job from within the event loop.
This method must be run in the event loop.
target: target to call.
args: parameters for method to call.
"""
# late import to avoid circular imports
from .helpers import frame # pylint: disable=import-outside-toplevel
frame.report_usage(
"calls `async_run_job`, which should be reviewed against "
"https://developers.home-assistant.io/blog/2024/03/13/deprecate_add_run_job"
" for replacement options",
core_behavior=frame.ReportBehavior.LOG,
breaks_in_ha_version="2025.4",
)
if asyncio.iscoroutine(target):
return self.async_create_task(target, eager_start=True)
return self.async_run_hass_job(HassJob(target), *args)
def block_till_done(self, wait_background_tasks: bool = False) -> None:
"""Block until all pending work is done."""
asyncio.run_coroutine_threadsafe(
self.async_block_till_done(wait_background_tasks=wait_background_tasks),
self.loop,
).result()
async def async_block_till_done(self, wait_background_tasks: bool = False) -> None: