Skip to content

Commit

Permalink
Updated file handling to async
Browse files Browse the repository at this point in the history
  • Loading branch information
kgn3400 committed May 17, 2024
1 parent cb2b3e5 commit 1fd1684
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 21 deletions.
17 changes: 7 additions & 10 deletions custom_components/message_log/component_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers.storage import STORAGE_DIR
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import (
CONF_MARKDOWN_MESSAGE_LIST_COUNT,
CONF_ORDER_BY_MESSAGE_LEVEL,
CONF_REMOVE_MESSAGE_AFTER_HOURS,
CONF_SCROLL_THROUGH_LAST_MESSAGES_COUNT,
DOMAIN,
)
from .message_log_settings import (
MessageItem,
Expand Down Expand Up @@ -44,7 +42,6 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
self.settings: MessageLogSettings = MessageLogSettings(
self.entry.options.get(CONF_ORDER_BY_MESSAGE_LEVEL, True)
)
self.settings.read_settings(hass.config.path(STORAGE_DIR, DOMAIN))

# ------------------------------------------------------------------
async def async_relative_time(self, date_time: datetime) -> str:
Expand Down Expand Up @@ -85,7 +82,7 @@ async def async_remove_messages_service(self, call: ServiceCall) -> None:
self.settings.message_list.clear()

self.settings.set_highest_message_level()
self.settings.write_settings()
await self.settings.async_write_settings()
await self.coordinator.async_refresh()

# ------------------------------------------------------------------
Expand Down Expand Up @@ -113,7 +110,7 @@ async def async_add_message_service(self, call: ServiceCall) -> None:

self.settings.message_list.insert(0, MessageItem(**tmp_dict))
self.settings.set_highest_message_level()
self.settings.write_settings()
await self.settings.async_write_settings()
await self.coordinator.async_refresh()

# ------------------------------------------------------------------
Expand All @@ -132,7 +129,7 @@ async def async_messagelist_orderby_service(self, call: ServiceCall) -> None:
if len(self.settings.message_list) > 1:
self.scroll_message_pos = -1

self.settings.write_settings()
await self.settings.async_write_settings()
await self.coordinator.async_refresh()

# ------------------------------------------------------------------
Expand All @@ -148,19 +145,19 @@ async def async_messagelist_show_service(self, call: ServiceCall) -> None:
call.data.get("show", "ALL").upper()
]

self.settings.write_settings()
await self.settings.async_write_settings()
await self.coordinator.async_refresh()

# ------------------------------------------------------------------
async def async_update(self) -> None:
"""Message log Update."""

self.remove_outdated()
await self.async_remove_outdated()
self.update_scroll_message_pos()
await self.async_update_markdown()

# ------------------------------------------------------------------
def remove_outdated(self) -> None:
async def async_remove_outdated(self) -> None:
"""Remove outdated."""
save_settings: bool = False

Expand All @@ -171,7 +168,7 @@ def remove_outdated(self) -> None:

if save_settings:
self.settings.set_highest_message_level()
self.settings.write_settings()
await self.settings.async_write_settings()

# ------------------------------------------------------------------
async def async_update_markdown(self) -> None:
Expand Down
5 changes: 3 additions & 2 deletions custom_components/message_log/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@
"homekit": {},
"iot_class": "cloud_push",
"requirements": [
"jsonpickle"
"jsonpickle",
"aiofiles"
],
"single_config_entry": true,
"ssdp": [],
"version": "1.0.14",
"version": "1.0.15",
"zeroconf": []
}
7 changes: 7 additions & 0 deletions custom_components/message_log/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from homeassistant.core import Event, HomeAssistant
from homeassistant.helpers import start
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.storage import STORAGE_DIR
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .component_api import ComponentApi
Expand All @@ -35,6 +36,10 @@ async def async_setup_entry(
coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
component_api: ComponentApi = hass.data[DOMAIN][entry.entry_id]["component_api"]

await component_api.settings.async_read_settings(
hass.config.path(STORAGE_DIR, DOMAIN)
)

sensors = []

sensors.append(MessageLastSensor(hass, coordinator, entry, component_api))
Expand Down Expand Up @@ -111,6 +116,8 @@ def extra_state_attributes(self) -> dict:
if self.component_api.markdown_message_settings:
attr["markdown_settings"] = self.component_api.markdown_message_settings

# attr["message_list"] = self.component_api.settings.message_list

return attr

# ------------------------------------------------------
Expand Down
22 changes: 13 additions & 9 deletions custom_components/message_log/settings_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from os import mkdir, path, remove, sep

import aiofiles
import jsonpickle


Expand Down Expand Up @@ -34,16 +35,18 @@ def set_settings_file_name(self, settings_file: str = "") -> None:
self.settings_file___ = settings_file

# ------------------------------------------------------------------
def read_settings(self, settings_file: str = "") -> None:
async def async_read_settings(self, settings_file: str = "") -> None:
"""read_settings."""
if hasattr(self, "__dict__") is False:
return

self.set_settings_file_name(settings_file)

try:
with open(self.settings_file___, encoding="UTF-8") as settingsfile:
tmp_obj = jsonpickle.decode(settingsfile.read())
async with aiofiles.open(
self.settings_file___, encoding="UTF-8"
) as settingsfile:
tmp_obj = jsonpickle.decode(await settingsfile.read())

if hasattr(tmp_obj, "__dict__") is False:
return
Expand Down Expand Up @@ -85,7 +88,7 @@ def remove_hidden_attrib(obj) -> None:
return tmp_dict

# ------------------------------------------------------------------
def write_settings(
async def async_write_settings(
self, unpicklable: bool = True, write_hidden_attributes: bool = False
) -> None:
"""Write settings."""
Expand All @@ -96,9 +99,11 @@ def write_settings(
self.write_hidden_attributes___ = write_hidden_attributes
jsonpickle.set_encoder_options("json", ensure_ascii=False)

with open(self.settings_file___, "w", encoding="UTF-8") as settingsfile:
settingsfile.write(
jsonpickle.encode(self, unpicklable=unpicklable, indent=4) # type: ignore
async with aiofiles.open(
self.settings_file___, "w", encoding="UTF-8"
) as settingsfile:
await settingsfile.write(
jsonpickle.encode(self, unpicklable=unpicklable, indent=4)
)

# ------------------------------------------------------------------
Expand All @@ -113,5 +118,4 @@ def delete_settings(self, settings_file: str = "") -> bool:
except FileNotFoundError:
return False
return True
else:
return False
return False

0 comments on commit 1fd1684

Please sign in to comment.