Home Assistant Unofficial Reference 2024.12.1
instance_id.py
Go to the documentation of this file.
1 """Helper to create a unique instance ID."""
2 
3 from __future__ import annotations
4 
5 import logging
6 import uuid
7 
8 from homeassistant.core import HomeAssistant
9 
10 from . import singleton, storage
11 
12 DATA_KEY = "core.uuid"
13 DATA_VERSION = 1
14 
15 LEGACY_UUID_FILE = ".uuid"
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
20 @singleton.singleton(DATA_KEY)
21 async def async_get(hass: HomeAssistant) -> str:
22  """Get unique ID for the hass instance."""
23  store = storage.Store[dict[str, str]](hass, DATA_VERSION, DATA_KEY, True)
24 
25  data: dict[str, str] | None = None
26  try:
27  data = await storage.async_migrator(
28  hass,
29  hass.config.path(LEGACY_UUID_FILE),
30  store,
31  )
32  except Exception:
33  _LOGGER.exception(
34  (
35  "Could not read hass instance ID from '%s' or '%s', a new instance ID "
36  "will be generated"
37  ),
38  DATA_KEY,
39  LEGACY_UUID_FILE,
40  )
41 
42  if data is not None:
43  return data["uuid"]
44 
45  data = {"uuid": uuid.uuid4().hex}
46 
47  await store.async_save(data)
48 
49  return data["uuid"]
str async_get(HomeAssistant hass)
Definition: instance_id.py:21