Skip to content

Commit

Permalink
Only consider timestamps larger than 1 as a valid timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
golles committed Feb 24, 2024
1 parent ba50793 commit 15c6b13
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
2 changes: 1 addition & 1 deletion custom_components/knmi/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"description": coordinator.get_value(["liveweer", 0, "ltekst"]),
"code": coordinator.get_value(["liveweer", 0, "wrschklr"]),
"next_code": coordinator.get_value(["liveweer", 0, "wrsch_gc"]),
"timestamp": coordinator.get_value_datetime(["liveweer", 0, "wrsch_gts"]),
"timestamp": coordinator.get_value_datetime(["liveweer", 0, "wrsch_gts"], "-"),
},
),
KnmiSensorDescription(
Expand Down
11 changes: 8 additions & 3 deletions custom_components/knmi/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ def get_value(self, path: list[int | str], default=None) -> Any:
_LOGGER.warning("Can't find a value for %s in the API response", path)
return default

def get_value_datetime(self, path: list[int | str], default=None) -> datetime:
def get_value_datetime(
self, path: list[int | str], default=None
) -> datetime | None:
"""
Get a datetime value from the data by a given path.
When the value is absent, the default (None) will be returned and an error will be logged.
Expand All @@ -83,8 +85,11 @@ def get_value_datetime(self, path: list[int | str], default=None) -> datetime:

# Timestamp.
if isinstance(value, int):
_LOGGER.debug("convert %s to datetime (from timestamp)", value)
return datetime.fromtimestamp(value, tz=timezone)
if value > 0:
_LOGGER.debug("convert %s to datetime (from timestamp)", value)
return datetime.fromtimestamp(value, tz=timezone)

return default

# Time.
if re.match(r"^\d{2}:\d{2}$", value):
Expand Down
6 changes: 5 additions & 1 deletion tests/test_coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async def test_get_value_datetime(hass: HomeAssistant, mocked_data, caplog):

coordinator: KnmiDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]

# Timestamp
# Timestamp.
assert (
str(coordinator.get_value_datetime(["liveweer", 0, "timestamp"]))
== "2024-02-14 22:08:03+01:00"
Expand All @@ -84,6 +84,10 @@ async def test_get_value_datetime(hass: HomeAssistant, mocked_data, caplog):
== "2024-02-14 23:00:00+01:00"
)

# Timestamp, 0 or lower value.
coordinator.data["liveweer"][0]["wrsch_gts"] = 0
assert coordinator.get_value_datetime(["liveweer", 0, "wrsch_gts"]) is None

# Time.
assert (
str(coordinator.get_value_datetime(["liveweer", 0, "sup"]))
Expand Down

0 comments on commit 15c6b13

Please sign in to comment.