Skip to content

Commit 26025f8

Browse files
WIP
1 parent b341e23 commit 26025f8

File tree

9 files changed

+55
-80
lines changed

9 files changed

+55
-80
lines changed

custom_components/battery_notes/__init__.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,13 @@
4040
DEFAULT_SCHEMA_URL,
4141
DOMAIN,
4242
MIN_HA_VERSION,
43-
MY_KEY,
4443
PLATFORMS,
4544
)
4645
from .coordinator import (
46+
MY_KEY,
4747
BatteryNotesConfigEntry,
4848
BatteryNotesCoordinator,
49+
BatteryNotesData,
4950
BatteryNotesDomainConfig,
5051
)
5152
from .discovery import DiscoveryManager
@@ -104,9 +105,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
104105
_LOGGER.critical(msg)
105106
return False
106107

107-
library_updater = LibraryUpdater(hass)
108-
await library_updater.copy_schema()
109-
await library_updater.get_library_updates(dt_util.utcnow())
108+
store = await async_get_registry(hass)
110109

111110
domain_config = BatteryNotesDomainConfig(
112111
enable_autodiscovery=config.get(DOMAIN, {}).get(CONF_ENABLE_AUTODISCOVERY, True),
@@ -122,12 +121,16 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
122121
),
123122
library_url=config.get(DOMAIN, {}).get(CONF_LIBRARY_URL, DEFAULT_LIBRARY_URL),
124123
schema_url=config.get(DOMAIN, {}).get(CONF_SCHEMA_URL, DEFAULT_SCHEMA_URL),
125-
library_updater=library_updater,
126124
user_library=config.get(DOMAIN, {}).get(CONF_USER_LIBRARY, ""),
125+
store=store,
127126
)
128127

129128
hass.data[MY_KEY] = domain_config
130129

130+
library_updater = LibraryUpdater(hass)
131+
await library_updater.copy_schema()
132+
await library_updater.get_library_updates(dt_util.utcnow())
133+
131134
if domain_config.enable_autodiscovery:
132135
discovery_manager = DiscoveryManager(hass, domain_config)
133136
await discovery_manager.start_discovery()
@@ -143,9 +146,14 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
143146
async def async_setup_entry(hass: HomeAssistant, config_entry: BatteryNotesConfigEntry) -> bool:
144147
"""Set up a config entry."""
145148

146-
config_entry.runtime_data.domain_config = hass.data[MY_KEY]
147-
config_entry.runtime_data.store = await async_get_registry(hass, config_entry)
148-
config_entry.runtime_data.coordinator = BatteryNotesCoordinator(hass, config_entry)
149+
data = hass.data[MY_KEY]
150+
config_entry.runtime_data = BatteryNotesData(
151+
domain_config=data,
152+
store=data.store,
153+
)
154+
155+
coordinator = BatteryNotesCoordinator(hass, config_entry)
156+
config_entry.runtime_data.coordinator = coordinator
149157

150158
await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS)
151159

custom_components/battery_notes/binary_sensor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@
7272
ATTR_BATTERY_TYPE_AND_QUANTITY,
7373
CONF_SOURCE_ENTITY_ID,
7474
DOMAIN,
75-
MY_KEY,
7675
)
7776
from .coordinator import (
77+
MY_KEY,
7878
BatteryNotesConfigEntry,
7979
BatteryNotesCoordinator,
8080
)

custom_components/battery_notes/config_flow.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -162,15 +162,9 @@ async def async_step_device(
162162

163163
device_id = user_input[CONF_DEVICE_ID]
164164

165-
if (
166-
DOMAIN in self.hass.data
167-
and DATA_LIBRARY_UPDATER in self.hass.data[DOMAIN]
168-
):
169-
library_updater: LibraryUpdater = self.hass.data[DOMAIN][
170-
DATA_LIBRARY_UPDATER
171-
]
172-
if await library_updater.time_to_update_library(1):
173-
await library_updater.get_library_updates(dt_util.utcnow())
165+
library_updater = LibraryUpdater(self.hass)
166+
if await library_updater.time_to_update_library(1):
167+
await library_updater.get_library_updates(dt_util.utcnow())
174168

175169
device_registry = dr.async_get(self.hass)
176170
device_entry = device_registry.async_get(device_id)

custom_components/battery_notes/const.py

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
11
"""Constants for battery_notes."""
22

33
import json
4-
from dataclasses import dataclass
5-
from datetime import datetime
64
from logging import Logger, getLogger
75
from pathlib import Path
86
from typing import Final
97

108
import voluptuous as vol
119
from homeassistant.const import Platform
1210
from homeassistant.helpers import config_validation as cv
13-
from homeassistant.util.hass_dict import HassKey
14-
15-
from .library_updater import LibraryUpdater
1611

1712
LOGGER: Logger = getLogger(__package__)
1813

@@ -117,21 +112,3 @@
117112
Platform.SENSOR,
118113
Platform.BINARY_SENSOR,
119114
]
120-
121-
@dataclass
122-
class BatteryNotesDomainConfig:
123-
"""Class for sharing config data within the BatteryNotes integration."""
124-
enable_autodiscovery: bool = True
125-
show_all_devices: bool = False
126-
enable_replaced: bool = True
127-
hide_battery: bool = False
128-
round_battery: bool = False
129-
default_battery_low_threshold: int = DEFAULT_BATTERY_LOW_THRESHOLD
130-
battery_increased_threshod: int = DEFAULT_BATTERY_INCREASE_THRESHOLD
131-
library_url: str = DEFAULT_LIBRARY_URL
132-
schema_url: str = DEFAULT_SCHEMA_URL
133-
library_updater: LibraryUpdater | None
134-
library_last_update: datetime | None = None
135-
user_library: str = ""
136-
137-
MY_KEY: HassKey[BatteryNotesDomainConfig] = HassKey(DOMAIN)

custom_components/battery_notes/coordinator.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from homeassistant.helpers.entity_registry import RegistryEntry
2626
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
2727
from homeassistant.util import dt as dt_util
28+
from homeassistant.util.hass_dict import HassKey
2829

2930
from .common import validate_is_float
3031
from .const import (
@@ -57,14 +58,30 @@
5758
LAST_REPLACED,
5859
LAST_REPORTED,
5960
LAST_REPORTED_LEVEL,
60-
BatteryNotesDomainConfig,
6161
)
6262
from .filters import LowOutlierFilter
63-
from .library_updater import LibraryUpdater
6463
from .store import BatteryNotesStorage
6564

6665
_LOGGER = logging.getLogger(__name__)
6766

67+
@dataclass
68+
class BatteryNotesDomainConfig:
69+
"""Class for sharing config data within the BatteryNotes integration."""
70+
enable_autodiscovery: bool = True
71+
show_all_devices: bool = False
72+
enable_replaced: bool = True
73+
hide_battery: bool = False
74+
round_battery: bool = False
75+
default_battery_low_threshold: int = DEFAULT_BATTERY_LOW_THRESHOLD
76+
battery_increased_threshod: int = DEFAULT_BATTERY_INCREASE_THRESHOLD
77+
library_url: str = DEFAULT_LIBRARY_URL
78+
schema_url: str = DEFAULT_SCHEMA_URL
79+
library_last_update: datetime | None = None
80+
user_library: str = ""
81+
store: BatteryNotesStorage | None = None
82+
83+
MY_KEY: HassKey[BatteryNotesDomainConfig] = HassKey(DOMAIN)
84+
6885
type BatteryNotesConfigEntry = ConfigEntry[BatteryNotesData]
6986

7087
@dataclass
@@ -73,7 +90,7 @@ class BatteryNotesData:
7390

7491
domain_config: BatteryNotesDomainConfig
7592
store: BatteryNotesStorage
76-
coordinator: BatteryNotesCoordinator
93+
coordinator: BatteryNotesCoordinator | None = None
7794

7895

7996
class BatteryNotesCoordinator(DataUpdateCoordinator[None]):

custom_components/battery_notes/discovery.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ async def start_discovery(self) -> None:
8787
_LOGGER.debug("Start auto discovering devices")
8888
device_registry = dr.async_get(self.hass)
8989

90-
library = await Library.factory(self.hass)
90+
library = Library(self.hass)
91+
await library.load_libraries()
9192

9293
if library.loaded():
9394
for device_entry in list(device_registry.devices.values()):

custom_components/battery_notes/library.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
from .const import (
1414
DATA_LIBRARY,
1515
DOMAIN,
16-
MY_KEY,
1716
)
17+
from .coordinator import MY_KEY
1818

1919
_LOGGER = logging.getLogger(__name__)
2020

@@ -105,15 +105,13 @@ def _load_library_json(library_file: str) -> dict[str, Any]:
105105
async def factory(hass: HomeAssistant) -> Library:
106106
"""Return the library or create."""
107107

108-
if DOMAIN not in hass.data:
109-
hass.data[DOMAIN] = {}
110-
111-
if DATA_LIBRARY in hass.data[DOMAIN]:
112-
return hass.data[DOMAIN][DATA_LIBRARY] # type: ignore
108+
domain_config = hass.data[MY_KEY]
109+
if domain_config.library:
110+
return domain_config.library
113111

114112
library = Library(hass)
115113
await library.load_libraries()
116-
hass.data[DOMAIN][DATA_LIBRARY] = library
114+
domain_config.library = library
117115
return library
118116

119117
async def get_device_battery_details(

custom_components/battery_notes/library_updater.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,7 @@
1818
from homeassistant.helpers.event import async_track_utc_time_change
1919
from homeassistant.helpers.storage import STORAGE_DIR
2020

21-
from .const import (
22-
MY_KEY,
23-
)
21+
from .coordinator import MY_KEY
2422
from .discovery import DiscoveryManager
2523

2624
_LOGGER = logging.getLogger(__name__)

custom_components/battery_notes/sensor.py

Lines changed: 7 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,9 @@
7171
CONF_SOURCE_ENTITY_ID,
7272
DOMAIN,
7373
LAST_REPLACED,
74-
MY_KEY,
7574
PLATFORMS,
7675
)
77-
from .coordinator import BatteryNotesConfigEntry, BatteryNotesCoordinator
76+
from .coordinator import MY_KEY, BatteryNotesConfigEntry, BatteryNotesCoordinator
7877
from .entity import (
7978
BatteryNotesEntityDescription,
8079
)
@@ -781,38 +780,21 @@ async def async_added_to_hass(self) -> None:
781780

782781
def _set_native_value(self, log_on_error=True):
783782
# pylint: disable=unused-argument
784-
if self._source_entity_id:
785-
entry = self.coordinator.store.async_get_entity(self._source_entity_id)
786-
else:
787-
entry = self.coordinator.store.async_get_device(self._device_id)
788783

789-
if entry:
790-
if LAST_REPLACED in entry and entry[LAST_REPLACED] is not None:
791-
last_replaced_date = datetime.fromisoformat(
792-
str(entry[LAST_REPLACED]) + "+00:00"
793-
)
794-
self._native_value = last_replaced_date
784+
if last_replaced := self.coordinator.last_replaced:
785+
self._native_value = last_replaced
795786

796-
return True
787+
return True
797788
return False
798789

799790
@callback
800791
def _handle_coordinator_update(self) -> None:
801792
"""Handle updated data from the coordinator."""
802793

803-
if self.coordinator.source_entity_id:
804-
entry = self.coordinator.store.async_get_entity(self._source_entity_id)
805-
else:
806-
entry = self.coordinator.store.async_get_device(self._device_id)
807-
808-
if entry:
809-
if LAST_REPLACED in entry and entry[LAST_REPLACED] is not None:
810-
last_replaced_date = datetime.fromisoformat(
811-
str(entry[LAST_REPLACED]) + "+00:00"
812-
)
813-
self._native_value = last_replaced_date
794+
if last_replaced := self.coordinator.last_replaced:
795+
self._native_value = last_replaced
814796

815-
self.async_write_ha_state()
797+
self.async_write_ha_state()
816798

817799
@property
818800
def native_value(self) -> datetime | None:

0 commit comments

Comments
 (0)