Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions custom_components/battery_notes/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from typing import cast

from homeassistant.components.binary_sensor import (
Expand Down Expand Up @@ -71,6 +71,13 @@
_LOGGER = logging.getLogger(__name__)


def _ensure_utc(dt_val: datetime) -> datetime:
"""Ensure a datetime is timezone-aware (UTC). Fixes naive datetimes from old storage."""
if dt_val.tzinfo is None:
return dt_val.replace(tzinfo=UTC)
return dt_val


@dataclass
class BatteryNotesDomainConfig:
"""Class for sharing config data within the BatteryNotes integration."""
Expand Down Expand Up @@ -683,7 +690,8 @@ def last_replaced(self) -> datetime | None:
)

if entry and LAST_REPLACED in entry and entry[LAST_REPLACED] is not None:
return datetime.fromisoformat(str(entry[LAST_REPLACED]))
dt_val = datetime.fromisoformat(str(entry[LAST_REPLACED]))
return _ensure_utc(dt_val)
return None

@last_replaced.setter
Expand All @@ -692,7 +700,9 @@ def last_replaced(self, value: datetime):
if not hasattr(self.config_entry, "runtime_data"):
return

entry = {LAST_REPLACED: value}
entry = {
LAST_REPLACED: _ensure_utc(value) if isinstance(value, datetime) else value
}

if self.source_entity_id:
self.async_update_entity_config(entity_id=self.source_entity_id, data=entry)
Expand All @@ -716,7 +726,8 @@ def last_reported(self) -> datetime | None:
)

if entry and LAST_REPORTED in entry and entry[LAST_REPORTED] is not None:
return datetime.fromisoformat(str(entry[LAST_REPORTED]))
dt_val = datetime.fromisoformat(str(entry[LAST_REPORTED]))
return _ensure_utc(dt_val)

return None

Expand All @@ -727,7 +738,9 @@ def last_reported(self, value: datetime):
if not hasattr(self.config_entry, "runtime_data"):
return

entry = {LAST_REPORTED: value}
entry = {
LAST_REPORTED: _ensure_utc(value) if isinstance(value, datetime) else value
}

if self.source_entity_id:
self.async_update_entity_config(entity_id=self.source_entity_id, data=entry)
Expand Down
Loading