Skip to content

Commit

Permalink
Code simplification and improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
warrior25 committed Aug 22, 2023
1 parent 9f6e26c commit f4fa3e7
Show file tree
Hide file tree
Showing 4 changed files with 203 additions and 212 deletions.
14 changes: 7 additions & 7 deletions custom_components/Nysse/fetch_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .network import request
from .network import get
from .const import NYSSE_STOP_POINTS_URL, NYSSE_LINES_URL
import logging
import json
Expand All @@ -13,7 +13,7 @@ async def fetch_stop_points(has_id):
else:
stations = []
try:
result = await request(NYSSE_STOP_POINTS_URL)
result = await get(NYSSE_STOP_POINTS_URL)
if not result:
_LOGGER.error("Could not fetch stop points")
return
Expand All @@ -33,8 +33,8 @@ async def fetch_stop_points(has_id):
stations = sorted(stations, key=lambda item: item["label"])
return stations

except OSError:
_LOGGER.error("Unknown exception. Check your internet connection")
except OSError as err:
_LOGGER.error("Failed to fetch stops: %s", err)
return


Expand All @@ -43,7 +43,7 @@ async def fetch_lines(stop):
lines = []
try:
lines_url = NYSSE_LINES_URL.format(stop)
result = await request(lines_url)
result = await get(lines_url)
if not result:
_LOGGER.error("Could not fetch lines points")
return
Expand All @@ -52,6 +52,6 @@ async def fetch_lines(stop):
lines.append(line["name"])
return lines

except OSError:
_LOGGER.error("Unknown exception. Check your internet connection")
except OSError as err:
_LOGGER.error("Failed to fetch lines: %s", err)
return
26 changes: 14 additions & 12 deletions custom_components/Nysse/network.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import logging
import aiohttp
import async_timeout

REQUEST_TIMEOUT = 30
_LOGGER = logging.getLogger(__name__)

async def fetch(session, url):
try:
with async_timeout.timeout(15):

async def get(url):
timeout = aiohttp.ClientTimeout(total=REQUEST_TIMEOUT)
async with aiohttp.ClientSession(timeout=timeout) as session:
try:
async with session.get(
url, headers={"Accept": "application/json"}
) as response:
return await response.text()
except:
pass


async def request(url):
async with aiohttp.ClientSession() as session:
return await fetch(session, url)
if response.status == 200:
return await response.text()
_LOGGER.error("GET %s: %s", url, response.status)
return
except aiohttp.ClientConnectorError as err:
_LOGGER.error("Connection error: %s", err)
42 changes: 21 additions & 21 deletions custom_components/Nysse/nysse_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,20 @@ def __init__(self):
self._station_id = ""
self._stops = []

def populate(self, departures, journeys, station_id, stops, max_items):
def populate(
self,
departures,
journeys,
station_id,
stops,
max_items,
update_time,
):
"""Collect sensor data to corresponding variables."""
departures2 = []
self._station_id = station_id
self._stops = stops
self._last_update = datetime.now().astimezone(LOCAL_TZ)
self._last_update = update_time

if self._station_id in departures["body"]:
departures2 = departures["body"][self._station_id]
Expand All @@ -33,25 +41,17 @@ 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
weekday_int = datetime.today().weekday()
i = 0

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])
if i < len(journeys):
self._json_data.append(journeys[i])
i += 1
else:
_LOGGER.warning(
"%s: Not enough timetable data was found. Try decreasing the number of requested departures",
station_id,
)
break

def get_state(self):
"""Get next departure time as the sensor state."""
Expand All @@ -68,7 +68,7 @@ def get_departures(self):
"destination": self.get_destination_name(item),
"line": item["lineRef"],
"departure": self.get_departure_time(item, True),
"time_to_station": self.time_to_station(item),
"time_to_station": self.time_to_station(item, self._last_update),
"icon": self.get_line_icon(item["lineRef"]),
"realtime": self.is_realtime(item),
}
Expand Down Expand Up @@ -128,11 +128,11 @@ def get_destination_name(self, entry):
return self._stops[entry["destinationShortName"]]
return "unavailable"

def time_to_station(self, entry, seconds=False):
def time_to_station(self, entry, current_time, seconds=False):
"""Get time until departure in minutes"""
time = self.get_departure_time(entry, False)
if time != "unavailable":
next_departure_time = (time - datetime.now().astimezone(LOCAL_TZ)).seconds
next_departure_time = (time - current_time).seconds

if seconds:
return next_departure_time
Expand Down
Loading

0 comments on commit f4fa3e7

Please sign in to comment.