11"""Battery Type library for battery_notes."""
22from __future__ import annotations
33
4+ from typing import Any , cast
5+
46import json
57import logging
68import os
79from typing import NamedTuple
810
9- import aiofiles .os
10-
1111from homeassistant .core import HomeAssistant
1212
1313from .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
0 commit comments