Skip to content

Commit

Permalink
Rework data fetching and formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
warrior25 committed Aug 25, 2023
1 parent f4fa3e7 commit 240e5a2
Show file tree
Hide file tree
Showing 8 changed files with 225 additions and 212 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.vscode
custom_components/nysse/__pycache__/*
3 changes: 1 addition & 2 deletions custom_components/Nysse/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations
import asyncio

from homeassistant import config_entries, core

from .const import DOMAIN


Expand Down
1 change: 0 additions & 1 deletion custom_components/Nysse/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ async def async_step_init(
errors: dict[str, str] = {}

if user_input is not None:
print(user_input)
self.stations = await fetch_stop_points(True)
for station in self.stations:
if station["value"] == self.config_entry.data[CONF_STATION]:
Expand Down
10 changes: 10 additions & 0 deletions custom_components/Nysse/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@
"Sunday",
]

DEFAULT_TIME_ZONE = "Europe/Helsinki"

JOURNEY = "journey"
DEPARTURE = "departure"
AIMED_ARRIVAL_TIME = "aimedArrivalTime"
AIMED_DEPARTURE_TIME = "aimedDepartureTime"
EXPECTED_ARRIVAL_TIME = "expectedArrivalTime"
EXPECTED_DEPARTURE_TIME = "expectedDepartureTime"


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/"
NYSSE_JOURNEYS_URL = "http:https://data.itsfactory.fi/journeys/api/1/journeys?stopPointId={0}&dayTypes={1}&startIndex={2}"
Expand Down
11 changes: 8 additions & 3 deletions custom_components/Nysse/manifest.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"codeowners": ["@warrior25"],
"codeowners": [
"@warrior25"
],
"config_flow": true,
"dependencies": [],
"documentation": "https://github.com/warrior25/HA-Nysse",
Expand All @@ -8,5 +10,8 @@
"issue_tracker": "https://github.com/warrior25/HA-Nysse/issues",
"name": "Nysse",
"requirements": [],
"version": "0.1"
}
"version": "0.2",
"ssdp": [],
"zeroconf": [],
"homekit": {}
}
77 changes: 20 additions & 57 deletions custom_components/Nysse/nysse_data.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from datetime import datetime
from dateutil import parser
import pytz
import logging
from .const import TRAM_LINES
from .const import (
TRAM_LINES,
)

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


class NysseData:
Expand All @@ -29,16 +29,12 @@ def populate(
update_time,
):
"""Collect sensor data to corresponding variables."""
departures2 = []
self._station_id = station_id
self._stops = stops
self._last_update = update_time

if self._station_id in departures["body"]:
departures2 = departures["body"][self._station_id]

# Store realtime arrival data
self._json_data = departures2[:max_items]
self._json_data = departures[:max_items]

# Append static timetable data if not enough realtime data
i = 0
Expand All @@ -47,7 +43,7 @@ def populate(
self._json_data.append(journeys[i])
i += 1
else:
_LOGGER.warning(
_LOGGER.info(
"%s: Not enough timetable data was found. Try decreasing the number of requested departures",
station_id,
)
Expand All @@ -56,62 +52,35 @@ def populate(
def get_state(self):
"""Get next departure time as the sensor state."""
if len(self._json_data) > 0:
depart_time = self.get_departure_time(self._json_data[0], True)
if depart_time != "unavailable":
return parser.parse(depart_time).strftime("%H:%M")
depart_time = self._json_data[0]["departureTime"].strftime("%H:%M")
return depart_time

def get_departures(self):
"""Format departure data to show in sensor attributes."""
departures = []
for item in self._json_data:
departure = {
"destination": self.get_destination_name(item),
"line": item["lineRef"],
"departure": self.get_departure_time(item, True),
"destination": self._stops[item["destinationCode"]],
"line": item["line"],
"departure": item["departureTime"].strftime("%H:%M"),
"time_to_station": self.time_to_station(item, self._last_update),
"icon": self.get_line_icon(item["lineRef"]),
"realtime": self.is_realtime(item),
"icon": self.get_line_icon(item["line"]),
"realtime": item["realtime"],
}

# Append only valid departures
if departure["time_to_station"] != "unavailable":
departures.append(departure)
else:
_LOGGER.debug("Discarding departure with unavailable time_to_station")
_LOGGER.debug(departure)
_LOGGER.debug(
"Discarding departure with unavailable time_to_station field: %s",
departure,
)

# Sort departures according to their departure times
departures = sorted(departures, key=lambda d: d["time_to_station"])
return departures

def is_realtime(self, item):
"""Check if departure data is from realtime data source"""
if "non-realtime" in item:
return False
return True

def get_departure_time(self, item, stringify=False, time_type="any"):
"""Get departure time from json data"""
if "expectedArrivalTime" in item["call"] and time_type == "any":
parsed = parser.parse(item["call"]["expectedArrivalTime"])
elif "expectedDepartureTime" in item["call"] and time_type == "any":
parsed = parser.parse(item["call"]["expectedDepartureTime"])
elif "aimedArrivalTime" in item["call"] and (
time_type in ("any", "aimedArrival")
):
parsed = parser.parse(item["call"]["aimedArrivalTime"])
elif "aimedDepartureTime" in item["call"] and time_type == "any":
parsed = parser.parse(item["call"]["aimedDepartureTime"])

try:
parsed
except NameError:
return "unavailable"
else:
if stringify:
return parsed.strftime("%H:%M")
return parsed

def get_line_icon(self, line_no):
if line_no in (TRAM_LINES):
return "mdi:tram"
Expand All @@ -123,16 +92,10 @@ def get_station_name(self):
def get_last_update(self):
return self._last_update

def get_destination_name(self, entry):
if "destinationShortName" in entry:
return self._stops[entry["destinationShortName"]]
return "unavailable"

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 - current_time).seconds
def time_to_station(self, item, current_time, seconds=False):
"""Get time until departure"""
if item["departureTime"] != "unavailable":
next_departure_time = (item["departureTime"] - current_time).seconds

if seconds:
return next_departure_time
Expand Down
Loading

0 comments on commit 240e5a2

Please sign in to comment.