Skip to content

Commit

Permalink
Handle no first or next trip.
Browse files Browse the repository at this point in the history
  • Loading branch information
Martreides committed Mar 1, 2025
1 parent d5eb950 commit 2316fec
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions homeassistant/components/nederlandse_spoorwegen/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def native_value(self):
@property
def extra_state_attributes(self):
"""Return the state attributes."""
if not self._trips:
if not self._trips or self._first_trip is None:
return None

if self._first_trip.trip_parts:
Expand Down Expand Up @@ -212,6 +212,8 @@ def extra_state_attributes(self):
attributes["next"] = self._next_trip.departure_time_planned.strftime(
"%H:%M:%S"
)
else:
attributes["next"] = None

return attributes

Expand Down Expand Up @@ -263,18 +265,26 @@ def update(self) -> None:
> datetime.now().replace(tzinfo=dt_util.get_default_time_zone())
]

sorted_times = sorted(filtered_times, key=lambda x: x[1])
self._first_trip = self._trips[sorted_times[0][0]]
self._state = sorted_times[0][1].strftime("%H:%M:%S")
if len(filtered_times) > 0:
sorted_times = sorted(filtered_times, key=lambda x: x[1])
self._first_trip = self._trips[sorted_times[0][0]]
self._state = sorted_times[0][1].strftime("%H:%M:%S")
else:
self._first_trip = None
self._state = None

# Filter again to remove trains that leave at the exact same time.
filtered_times = [
(i, time)
for i, time in enumerate(all_times)
if time > sorted_times[0][1]
]
sorted_times = sorted(filtered_times, key=lambda x: x[1])
self._next_trip = self._trips[sorted_times[0][0]]

if len(filtered_times) > 0:
sorted_times = sorted(filtered_times, key=lambda x: x[1])
self._next_trip = self._trips[sorted_times[0][0]]
else:
self._next_trip = None

except (
requests.exceptions.ConnectionError,
Expand Down

0 comments on commit 2316fec

Please sign in to comment.