Skip to content

Commit 6ad5771

Browse files
Fix blocking file io (#1704)
1 parent 8c2cfc8 commit 6ad5771

File tree

4 files changed

+29
-17
lines changed

4 files changed

+29
-17
lines changed

custom_components/battery_notes/config_flow.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ async def async_step_device(
174174

175175
model_info = ModelInfo(device_entry.manufacturer, device_entry.model, device_entry.hw_version)
176176

177-
library = Library.factory(self.hass)
177+
library = await Library.factory(self.hass)
178178

179179
# Set defaults if not found in library
180180
self.data[CONF_BATTERY_QUANTITY] = 1
@@ -248,7 +248,7 @@ async def async_step_entity(
248248

249249
model_info = ModelInfo(device_entry.manufacturer, device_entry.model, device_entry.hw_version)
250250

251-
library = Library.factory(self.hass)
251+
library = await Library.factory(self.hass)
252252

253253
device_battery_details = await library.get_device_battery_details(
254254
model_info

custom_components/battery_notes/discovery.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ async def start_discovery(self) -> None:
8383
_LOGGER.debug("Start auto discovering devices")
8484
device_registry = dr.async_get(self.hass)
8585

86-
library = Library.factory(self.hass)
86+
library = await Library.factory(self.hass)
8787

8888
if library.loaded():
8989
for device_entry in list(device_registry.devices.values()):

custom_components/battery_notes/library.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import os
77
from typing import NamedTuple
88

9+
import aiofiles.os
10+
911
from homeassistant.core import HomeAssistant
1012

1113
from .const import (
@@ -27,25 +29,31 @@ class Library: # pylint: disable=too-few-public-methods
2729

2830
def __init__(self, hass: HomeAssistant) -> None:
2931
"""Init."""
32+
self.hass = hass
33+
34+
async def initialize(self):
35+
"""Load the user and default libraries."""
3036

3137
# User Library
3238
if (
33-
DOMAIN_CONFIG in hass.data[DOMAIN]
34-
and CONF_USER_LIBRARY in hass.data[DOMAIN][DOMAIN_CONFIG]
39+
DOMAIN_CONFIG in self.hass.data[DOMAIN]
40+
and CONF_USER_LIBRARY in self.hass.data[DOMAIN][DOMAIN_CONFIG]
3541
):
36-
user_library_filename = hass.data[DOMAIN][DOMAIN_CONFIG].get(CONF_USER_LIBRARY)
37-
if user_library_filename != "":
42+
user_library_filename = self.hass.data[DOMAIN][DOMAIN_CONFIG].get(CONF_USER_LIBRARY)
43+
if user_library_filename != "":
3844
json_user_path = os.path.join(
3945
BUILT_IN_DATA_DIRECTORY,
4046
user_library_filename,
4147
)
4248
_LOGGER.debug("Using user library file at %s", json_user_path)
4349

4450
try:
45-
with open(json_user_path, encoding="utf-8") as user_file:
46-
user_json_data = json.load(user_file)
51+
async with aiofiles.open(json_user_path, mode="r", encoding="utf-8") as user_file:
52+
content = await user_file.read()
53+
user_json_data = json.loads(content)
4754
self._devices = user_json_data["devices"]
48-
user_file.close()
55+
_LOGGER.debug("Loaded %s user devices", len(user_json_data["devices"]))
56+
await user_file.close()
4957

5058
except FileNotFoundError:
5159
_LOGGER.error(
@@ -61,10 +69,12 @@ def __init__(self, hass: HomeAssistant) -> None:
6169
_LOGGER.debug("Using library file at %s", json_default_path)
6270

6371
try:
64-
with open(json_default_path, encoding="utf-8") as default_file:
65-
default_json_data = json.load(default_file)
72+
async with aiofiles.open(json_default_path, mode="r", encoding="utf-8") as default_file:
73+
content = await default_file.read()
74+
default_json_data = json.loads(content)
6675
self._devices.extend(default_json_data["devices"])
67-
default_file.close()
76+
_LOGGER.debug("Loaded %s default devices", len(default_json_data["devices"]))
77+
await default_file.close()
6878

6979
except FileNotFoundError:
7080
_LOGGER.error(
@@ -73,7 +83,7 @@ def __init__(self, hass: HomeAssistant) -> None:
7383
)
7484

7585
@staticmethod
76-
def factory(hass: HomeAssistant) -> Library:
86+
async def factory(hass: HomeAssistant) -> Library:
7787
"""Return the library or create."""
7888

7989
if DOMAIN not in hass.data:
@@ -83,6 +93,7 @@ def factory(hass: HomeAssistant) -> Library:
8393
return hass.data[DOMAIN][DATA_LIBRARY] # type: ignore
8494

8595
library = Library(hass)
96+
await library.initialize()
8697
hass.data[DOMAIN][DATA_LIBRARY] = library
8798
return library
8899

custom_components/battery_notes/library_updater.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from datetime import datetime, timedelta
1111

1212
import aiohttp
13+
import aiofiles.os
1314
import async_timeout
1415

1516
from homeassistant.exceptions import ConfigEntryNotReady
@@ -88,9 +89,9 @@ async def get_library_updates(self, time):
8889
"library.json",
8990
)
9091

91-
with open(json_path, "w", encoding="utf-8") as file:
92-
file.write(content)
93-
file.close()
92+
async with aiofiles.open(json_path, mode="w", encoding="utf-8") as library_file:
93+
await library_file.write(content)
94+
await library_file.close()
9495

9596
self.hass.data[DOMAIN][DATA_LIBRARY_LAST_UPDATE] = datetime.now()
9697

0 commit comments

Comments
 (0)