Skip to content

Commit

Permalink
Use async_add_executor_job (#1710)
Browse files Browse the repository at this point in the history
* Use async_add_executor_job

* Lint
  • Loading branch information
andrew-codechimp authored Jun 1, 2024
1 parent 83609e3 commit 7b7f8ad
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 23 deletions.
32 changes: 16 additions & 16 deletions custom_components/battery_notes/library.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Battery Type library for battery_notes."""
from __future__ import annotations

from typing import Any, cast

import json
import logging
import os
from typing import NamedTuple

import aiofiles.os

from homeassistant.core import HomeAssistant

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

async def initialize(self):
async def load_libraries(self):
"""Load the user and default libraries."""

def _load_library_json(library_file: str) -> dict[str, Any]:
"""Load library json file."""
with open(library_file, encoding="utf-8") as file:
return cast(dict[str, Any], json.load(file))

# User Library
if (
DOMAIN_CONFIG in self.hass.data[DOMAIN]
Expand All @@ -48,12 +53,10 @@ async def initialize(self):
_LOGGER.debug("Using user library file at %s", json_user_path)

try:
async with aiofiles.open(json_user_path, mode="r", encoding="utf-8") as user_file:
content = await user_file.read()
user_json_data = json.loads(content)
self._devices = user_json_data["devices"]
_LOGGER.debug("Loaded %s user devices", len(user_json_data["devices"]))
await user_file.close()
user_json_data = await self.hass.async_add_executor_job(_load_library_json, json_user_path)

self._devices = user_json_data["devices"]
_LOGGER.debug("Loaded %s user devices", len(user_json_data["devices"]))

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

try:
async with aiofiles.open(json_default_path, mode="r", encoding="utf-8") as default_file:
content = await default_file.read()
default_json_data = json.loads(content)
self._devices.extend(default_json_data["devices"])
_LOGGER.debug("Loaded %s default devices", len(default_json_data["devices"]))
await default_file.close()
default_json_data = await self.hass.async_add_executor_job(_load_library_json, json_default_path)
self._devices.extend(default_json_data["devices"])
_LOGGER.debug("Loaded %s default devices", len(default_json_data["devices"]))

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

library = Library(hass)
await library.initialize()
await library.load_libraries()
hass.data[DOMAIN][DATA_LIBRARY] = library
return library

Expand Down
18 changes: 11 additions & 7 deletions custom_components/battery_notes/library_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@

from __future__ import annotations

from typing import Any
import logging
import asyncio
import socket
import json
import os
from datetime import datetime, timedelta

import aiohttp
import aiofiles.os
import asyncio
import async_timeout

from homeassistant.exceptions import ConfigEntryNotReady

from homeassistant.core import callback
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_track_utc_time_change

Expand Down Expand Up @@ -45,7 +45,7 @@ class LibraryUpdaterClientCommunicationError(LibraryUpdaterClientError):
class LibraryUpdater:
"""Library updater."""

def __init__(self, hass):
def __init__(self, hass: HomeAssistant):
"""Initialize the library updater."""
self.hass = hass
self._client = LibraryUpdaterClient(session=async_get_clientsession(hass))
Expand Down Expand Up @@ -78,6 +78,12 @@ async def timer_update(self, time):
async def get_library_updates(self, time):
# pylint: disable=unused-argument
"""Make a call to GitHub to get the latest library.json."""

def _update_library_json(library_file: str, content: str) -> dict[str, Any]:
with open(library_file, mode="w", encoding="utf-8") as file:
file.write(content)
file.close()

try:
_LOGGER.debug("Getting library updates")

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

async with aiofiles.open(json_path, mode="w", encoding="utf-8") as library_file:
await library_file.write(content)
await library_file.close()
await self.hass.async_add_executor_job(_update_library_json, json_path, content)

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

Expand Down

0 comments on commit 7b7f8ad

Please sign in to comment.