Skip to content

Commit 7b7f8ad

Browse files
Use async_add_executor_job (#1710)
* Use async_add_executor_job * Lint
1 parent 83609e3 commit 7b7f8ad

File tree

2 files changed

+27
-23
lines changed

2 files changed

+27
-23
lines changed

custom_components/battery_notes/library.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
"""Battery Type library for battery_notes."""
22
from __future__ import annotations
33

4+
from typing import Any, cast
5+
46
import json
57
import logging
68
import os
79
from typing import NamedTuple
810

9-
import aiofiles.os
10-
1111
from homeassistant.core import HomeAssistant
1212

1313
from .const import (
@@ -31,9 +31,14 @@ def __init__(self, hass: HomeAssistant) -> None:
3131
"""Init."""
3232
self.hass = hass
3333

34-
async def initialize(self):
34+
async def load_libraries(self):
3535
"""Load the user and default libraries."""
3636

37+
def _load_library_json(library_file: str) -> dict[str, Any]:
38+
"""Load library json file."""
39+
with open(library_file, encoding="utf-8") as file:
40+
return cast(dict[str, Any], json.load(file))
41+
3742
# User Library
3843
if (
3944
DOMAIN_CONFIG in self.hass.data[DOMAIN]
@@ -48,12 +53,10 @@ async def initialize(self):
4853
_LOGGER.debug("Using user library file at %s", json_user_path)
4954

5055
try:
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)
54-
self._devices = user_json_data["devices"]
55-
_LOGGER.debug("Loaded %s user devices", len(user_json_data["devices"]))
56-
await user_file.close()
56+
user_json_data = await self.hass.async_add_executor_job(_load_library_json, json_user_path)
57+
58+
self._devices = user_json_data["devices"]
59+
_LOGGER.debug("Loaded %s user devices", len(user_json_data["devices"]))
5760

5861
except FileNotFoundError:
5962
_LOGGER.error(
@@ -69,12 +72,9 @@ async def initialize(self):
6972
_LOGGER.debug("Using library file at %s", json_default_path)
7073

7174
try:
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)
75-
self._devices.extend(default_json_data["devices"])
76-
_LOGGER.debug("Loaded %s default devices", len(default_json_data["devices"]))
77-
await default_file.close()
75+
default_json_data = await self.hass.async_add_executor_job(_load_library_json, json_default_path)
76+
self._devices.extend(default_json_data["devices"])
77+
_LOGGER.debug("Loaded %s default devices", len(default_json_data["devices"]))
7878

7979
except FileNotFoundError:
8080
_LOGGER.error(
@@ -93,7 +93,7 @@ async def factory(hass: HomeAssistant) -> Library:
9393
return hass.data[DOMAIN][DATA_LIBRARY] # type: ignore
9494

9595
library = Library(hass)
96-
await library.initialize()
96+
await library.load_libraries()
9797
hass.data[DOMAIN][DATA_LIBRARY] = library
9898
return library
9999

custom_components/battery_notes/library_updater.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,20 @@
22

33
from __future__ import annotations
44

5+
from typing import Any
56
import logging
6-
import asyncio
77
import socket
88
import json
99
import os
1010
from datetime import datetime, timedelta
1111

1212
import aiohttp
13-
import aiofiles.os
13+
import asyncio
1414
import async_timeout
1515

1616
from homeassistant.exceptions import ConfigEntryNotReady
1717

18-
from homeassistant.core import callback
18+
from homeassistant.core import HomeAssistant, callback
1919
from homeassistant.helpers.aiohttp_client import async_get_clientsession
2020
from homeassistant.helpers.event import async_track_utc_time_change
2121

@@ -45,7 +45,7 @@ class LibraryUpdaterClientCommunicationError(LibraryUpdaterClientError):
4545
class LibraryUpdater:
4646
"""Library updater."""
4747

48-
def __init__(self, hass):
48+
def __init__(self, hass: HomeAssistant):
4949
"""Initialize the library updater."""
5050
self.hass = hass
5151
self._client = LibraryUpdaterClient(session=async_get_clientsession(hass))
@@ -78,6 +78,12 @@ async def timer_update(self, time):
7878
async def get_library_updates(self, time):
7979
# pylint: disable=unused-argument
8080
"""Make a call to GitHub to get the latest library.json."""
81+
82+
def _update_library_json(library_file: str, content: str) -> dict[str, Any]:
83+
with open(library_file, mode="w", encoding="utf-8") as file:
84+
file.write(content)
85+
file.close()
86+
8187
try:
8288
_LOGGER.debug("Getting library updates")
8389

@@ -89,9 +95,7 @@ async def get_library_updates(self, time):
8995
"library.json",
9096
)
9197

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()
98+
await self.hass.async_add_executor_job(_update_library_json, json_path, content)
9599

96100
self.hass.data[DOMAIN][DATA_LIBRARY_LAST_UPDATE] = datetime.now()
97101

0 commit comments

Comments
 (0)