Skip to content

Commit

Permalink
Merge pull request #123 from HASwitchPlate/open_file_executor_job
Browse files Browse the repository at this point in the history
Move file open() to executor job
  • Loading branch information
fvanroie authored Jun 11, 2024
2 parents 246fb06 + 24f071c commit 801e5f6
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions custom_components/openhasp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,15 +344,15 @@ def __init__(self, hass, config, entry):

self._subscriptions = []

with open(
pathlib.Path(__file__).parent.joinpath("pages_schema.json"), "r"
) as schema_file:
self.json_schema = json.load(schema_file)

self._attr_unique_id = entry.data[CONF_HWID]
self._attr_name = entry.data[CONF_NAME]
self._attr_icon = "mdi:gesture-tap-box"

def _read_file(self, path):
"""Executor helper to read file."""
with open(path, "r") as src_file:
return src_file.read()

@property
def state(self):
"""Return the state of the component."""
Expand All @@ -377,6 +377,9 @@ async def async_added_to_hass(self):
"""Run when entity about to be added."""
await super().async_added_to_hass()

schema_file_contents = await self.hass.async_add_executor_job(self._read_file, pathlib.Path(__file__).parent.joinpath("pages_schema.json"))
self.json_schema = json.loads(schema_file_contents)

state = await self.async_get_last_state()
if state and state.state not in [STATE_UNAVAILABLE, STATE_UNKNOWN, None]:
self._page = int(state.state)
Expand Down Expand Up @@ -650,17 +653,17 @@ async def send_lines(lines):
)

try:
with open(path, "r") as pages_file:
if path.endswith(".json"):
json_data = json.load(pages_file)
jsonschema.validate(instance=json_data, schema=self.json_schema)
lines = []
for item in json_data:
if isinstance(item, dict):
lines.append(json.dumps(item) + "\n")
await send_lines(lines)
else:
await send_lines(pages_file)
pages_file = await self.hass.async_add_executor_job(self._read_file, path)
if path.endswith(".json"):
json_data = json.load(pages_file)
jsonschema.validate(instance=json_data, schema=self.json_schema)
lines = []
for item in json_data:
if isinstance(item, dict):
lines.append(json.dumps(item) + "\n")
await send_lines(lines)
else:
await send_lines(pages_file)
await self.refresh()

except (IndexError, FileNotFoundError, IsADirectoryError, UnboundLocalError):
Expand Down

0 comments on commit 801e5f6

Please sign in to comment.