2022-09-27 17:56:00 +00:00
|
|
|
"""Support for esphome domain data."""
|
2024-03-08 13:15:26 +00:00
|
|
|
|
2022-09-27 17:56:00 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
from dataclasses import dataclass, field
|
2024-06-25 11:10:09 +00:00
|
|
|
from functools import cache
|
|
|
|
from typing import Self
|
2022-12-12 03:50:18 +00:00
|
|
|
|
2023-12-14 17:21:31 +00:00
|
|
|
from bleak_esphome.backend.cache import ESPHomeBluetoothCache
|
|
|
|
|
2022-09-27 17:56:00 +00:00
|
|
|
from homeassistant.core import HomeAssistant
|
|
|
|
from homeassistant.helpers.json import JSONEncoder
|
|
|
|
|
2023-01-18 16:59:55 +00:00
|
|
|
from .const import DOMAIN
|
2024-06-25 11:10:09 +00:00
|
|
|
from .entry_data import ESPHomeConfigEntry, ESPHomeStorage, RuntimeEntryData
|
2022-09-27 17:56:00 +00:00
|
|
|
|
|
|
|
STORAGE_VERSION = 1
|
2022-09-28 18:06:30 +00:00
|
|
|
|
2022-09-27 17:56:00 +00:00
|
|
|
|
2023-07-21 20:41:50 +00:00
|
|
|
@dataclass(slots=True)
|
2022-09-27 17:56:00 +00:00
|
|
|
class DomainData:
|
|
|
|
"""Define a class that stores global esphome data in hass.data[DOMAIN]."""
|
|
|
|
|
2023-06-26 02:31:31 +00:00
|
|
|
_stores: dict[str, ESPHomeStorage] = field(default_factory=dict)
|
2023-07-21 20:41:50 +00:00
|
|
|
bluetooth_cache: ESPHomeBluetoothCache = field(
|
|
|
|
default_factory=ESPHomeBluetoothCache
|
2022-12-12 03:50:18 +00:00
|
|
|
)
|
2022-09-27 17:56:00 +00:00
|
|
|
|
2024-06-25 11:10:09 +00:00
|
|
|
def get_entry_data(self, entry: ESPHomeConfigEntry) -> RuntimeEntryData:
|
2022-09-27 17:56:00 +00:00
|
|
|
"""Return the runtime entry data associated with this config entry.
|
|
|
|
|
|
|
|
Raises KeyError if the entry isn't loaded yet.
|
|
|
|
"""
|
2024-06-25 11:10:09 +00:00
|
|
|
return entry.runtime_data
|
2022-09-27 17:56:00 +00:00
|
|
|
|
2023-06-26 02:31:31 +00:00
|
|
|
def get_or_create_store(
|
2024-06-25 11:10:09 +00:00
|
|
|
self, hass: HomeAssistant, entry: ESPHomeConfigEntry
|
2023-06-26 02:31:31 +00:00
|
|
|
) -> ESPHomeStorage:
|
2022-09-27 17:56:00 +00:00
|
|
|
"""Get or create a Store instance for the given config entry."""
|
|
|
|
return self._stores.setdefault(
|
|
|
|
entry.entry_id,
|
2023-06-26 02:31:31 +00:00
|
|
|
ESPHomeStorage(
|
2022-09-27 17:56:00 +00:00
|
|
|
hass, STORAGE_VERSION, f"esphome.{entry.entry_id}", encoder=JSONEncoder
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
@classmethod
|
2024-06-25 11:10:09 +00:00
|
|
|
@cache
|
2023-02-07 04:29:47 +00:00
|
|
|
def get(cls, hass: HomeAssistant) -> Self:
|
2022-09-27 17:56:00 +00:00
|
|
|
"""Get the global DomainData instance stored in hass.data."""
|
|
|
|
ret = hass.data[DOMAIN] = cls()
|
|
|
|
return ret
|