1
1
"""Battery Type library for battery_notes."""
2
2
from __future__ import annotations
3
3
4
+ from typing import Any , cast
5
+
4
6
import json
5
7
import logging
6
8
import os
7
9
from typing import NamedTuple
8
10
9
- import aiofiles .os
10
-
11
11
from homeassistant .core import HomeAssistant
12
12
13
13
from .const import (
@@ -31,9 +31,14 @@ def __init__(self, hass: HomeAssistant) -> None:
31
31
"""Init."""
32
32
self .hass = hass
33
33
34
- async def initialize (self ):
34
+ async def load_libraries (self ):
35
35
"""Load the user and default libraries."""
36
36
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
+
37
42
# User Library
38
43
if (
39
44
DOMAIN_CONFIG in self .hass .data [DOMAIN ]
@@ -48,12 +53,10 @@ async def initialize(self):
48
53
_LOGGER .debug ("Using user library file at %s" , json_user_path )
49
54
50
55
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" ]))
57
60
58
61
except FileNotFoundError :
59
62
_LOGGER .error (
@@ -69,12 +72,9 @@ async def initialize(self):
69
72
_LOGGER .debug ("Using library file at %s" , json_default_path )
70
73
71
74
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" ]))
78
78
79
79
except FileNotFoundError :
80
80
_LOGGER .error (
@@ -93,7 +93,7 @@ async def factory(hass: HomeAssistant) -> Library:
93
93
return hass .data [DOMAIN ][DATA_LIBRARY ] # type: ignore
94
94
95
95
library = Library (hass )
96
- await library .initialize ()
96
+ await library .load_libraries ()
97
97
hass .data [DOMAIN ][DATA_LIBRARY ] = library
98
98
return library
99
99
0 commit comments