Skip to content

Commit

Permalink
fix: blocking call for timezone fetching, references #171
Browse files Browse the repository at this point in the history
  • Loading branch information
geertmeersman committed Jun 21, 2024
1 parent f969763 commit d78bc87
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 5 additions & 0 deletions custom_components/robonect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.storage import STORAGE_DIR, Store
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
import pytz

from .const import (
CONF_ATTRS_UNITS,
Expand Down Expand Up @@ -58,6 +59,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
for platform in PLATFORMS:
hass.data[DOMAIN][entry.entry_id].setdefault(platform, set())

# Cache the timezone during setup
timezone = await hass.async_add_executor_job(pytz.timezone, hass.config.time_zone)
hass.data[DOMAIN]["timezone"] = timezone

if entry.data[CONF_MQTT_ENABLED] is True:
if not await mqtt.async_wait_for_mqtt_client(hass):
_LOGGER.error("MQTT integration is not available")
Expand Down
17 changes: 15 additions & 2 deletions custom_components/robonect/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,20 @@
from jsonpath import jsonpath
import pytz

from .const import ATTR_STATE_UNITS, WEEKDAYS_HEX
from .const import ATTR_STATE_UNITS, DOMAIN, WEEKDAYS_HEX

_LOGGER = logging.getLogger(__name__)

_cached_timezone = None


def get_cached_timezone(hass):
"""Get the cached timezone."""
global _cached_timezone
if _cached_timezone is None:
_cached_timezone = pytz.timezone(hass.config.time_zone)
return _cached_timezone


def str_to_float(input, entity=None) -> float:
"""Transform float to string."""
Expand Down Expand Up @@ -120,7 +130,10 @@ def unix_to_datetime(epoch_timestamp, hass=None):
datetime_utc = datetime.datetime.fromtimestamp(int(epoch_timestamp), pytz.UTC)

# Convert UTC datetime to the desired timezone
timezone = pytz.timezone(hass.config.time_zone)
timezone = hass.data[DOMAIN].get("timezone")
if timezone is None:
timezone = pytz.UTC # Fallback in case timezone isn't cached properly

datetime_with_timezone = datetime_utc.astimezone(timezone)

# Subtract 2 hours from the timestamp
Expand Down

0 comments on commit d78bc87

Please sign in to comment.