Skip to content

Commit

Permalink
Rewrite timetable data handling
Browse files Browse the repository at this point in the history
  • Loading branch information
warrior25 committed Jan 26, 2023
1 parent 8b791a0 commit 25871b7
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 139 deletions.
9 changes: 5 additions & 4 deletions custom_components/nysse/const.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
DOMAIN = "nysse"

DEFAULT_NAME = "Nysse"
DEFAULT_ICON = "mdi:bus"
PLATFORM_NAME = "Nysse"
CONF_STOPS = "stops"

CONF_LINE = "line"
CONF_STATION = "station"
CONF_PLATFORM = "platform"
CONF_MAX = "max"
DEFAULT_MAX = 3
DEFAULT_ICON = "mdi:bus-clock"
TRAM_LINES = ["1","3"]

WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

NYSSE_STOP_URL = "https://data.itsfactory.fi/journeys/api/1/stop-monitoring?stops={0}"
NYSSE_STOP_POINTS_URL = "http:https://data.itsfactory.fi/journeys/api/1/stop-points/"
Expand Down
50 changes: 29 additions & 21 deletions custom_components/nysse/nysse_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
from dateutil import parser
import pytz
import logging

LOCAL = pytz.timezone("Europe/Helsinki")
from .const import TRAM_LINES

_LOGGER = logging.getLogger(__name__)
LOCAL_TZ = pytz.timezone("Europe/Helsinki")

class NysseData:
def __init__(self):
Expand All @@ -23,7 +23,7 @@ def populate(self, departures, journeys, station_id, stops, max_items):
departures2 = []
self._station_id = station_id
self._stops = stops
self._last_update = datetime.now().astimezone(LOCAL)
self._last_update = datetime.now().astimezone(LOCAL_TZ)

if self._station_id in departures["body"]:
departures2 = departures["body"][self._station_id]
Expand All @@ -32,21 +32,31 @@ def populate(self, departures, journeys, station_id, stops, max_items):
self._json_data = departures2[:max_items]

# Append static timetable data if not enough realtime data
if len(self._json_data) < max_items:
for i in range(len(self._json_data), max_items):
if len(journeys) > i:
self._json_data.append(journeys[i])
weekday_int = datetime.today().weekday()
i = len(self._json_data)

while len(self._json_data) < max_items:
if len(journeys[weekday_int]) <= i:
i = 0
if (weekday_int < 6):
weekday_int += 1
else:
weekday_int = 0
if weekday_int == datetime.today().weekday():
_LOGGER.warning("%s: Not enough timetable data was found. Try decreasing the number of requested departures", station_id)
break
else:
self._json_data.append(journeys[weekday_int][i])
i += 1

def remove_stale_data(self):
"""Remove old or unavailable departures."""
stale_data = []
for item in self._json_data:
if self.get_departure_time(item, True) == "unavailable":
_LOGGER.info("Removing unavailable departures")
self._json_data.remove(item)

elif (self.get_departure_time(item, False)) < datetime.now().astimezone(LOCAL):
_LOGGER.info("Removing stale departures")
self._json_data.remove(item)
if (self.get_departure_time(item) == "unavailable") or ((self.get_departure_time(item)) < datetime.now().astimezone(LOCAL_TZ)):
stale_data.append(item)
for item in stale_data:
self._json_data.remove(item)

def get_state(self):
"""Get next departure time as the sensor state."""
Expand Down Expand Up @@ -82,25 +92,23 @@ def is_realtime(self, item):
return False
return True

def get_departure_time(self, item, stringify):
def get_departure_time(self, item, stringify = False):
"""Get departure time from json data"""
if "expectedArrivalTime" in item["call"]:
parsed = parser.parse(item["call"]["expectedArrivalTime"])
if stringify:
return parsed.strftime("%H:%M")
else:
return parsed
return parsed
if "aimedArrivalTime" in item["call"]:
parsed = parser.parse(item["call"]["aimedArrivalTime"]).strftime("%H:%M")
if stringify:
return parsed.strftime("%H:%M")
else:
return parsed
return parsed
else:
return "unavailable"

def get_line_icon(self, line_no):
if line_no in ("1", "3"):
if line_no in (TRAM_LINES):
return "mdi:tram"
return "mdi:bus"

Expand All @@ -121,7 +129,7 @@ def time_to_station(self, entry):
if time != "unavailable":
# Convert departure time to UTC
naive = parser.parse(self.get_departure_time(entry, True)).replace(tzinfo=None)
local_dt = LOCAL.localize(naive, is_dst=None)
local_dt = LOCAL_TZ.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
next_departure_time = (utc_dt - datetime.now().astimezone(pytz.utc)).seconds
return int(next_departure_time / 60)
Expand Down
Loading

0 comments on commit 25871b7

Please sign in to comment.