Skip to content

Commit

Permalink
Changed return format of StationBoard-Requests - Fixes #6
Browse files Browse the repository at this point in the history
Created new type
  • Loading branch information
leona-ya committed Jul 31, 2020
1 parent d360ca5 commit 69923c0
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 27 deletions.
18 changes: 11 additions & 7 deletions pyhafas/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from pyhafas.types.station_board_request import StationBoardRequestType
from pyhafas.profile import ProfileInterface
from pyhafas.types.fptf import Journey, Leg, Station
from pyhafas.types.fptf import Journey, Leg, Station, StationBoardLeg


class HafasClient:
Expand Down Expand Up @@ -31,17 +31,19 @@ def departures(
max_journeys: Optional[int] = None, # Deprecated, will be removed in 0.2.0
max_trips: int = -1,
duration: int = -1,
products: Dict[str, bool] = {}) -> List[Leg]:
products: Dict[str, bool] = {}) -> List[StationBoardLeg]:
"""
Returns departing trips at the specified station
To get detailed information on the trip use the `trip` method with the id
:param station: FPTF `Station` object or ID of station
:param date: Date and Time when to search
:param max_journeys: (optional, deprecated, will be removed in 0.2.0) Use `max_trips` instead - Maximum number of trips to be returned. Default is "whatever HaFAS wants"
:param max_trips: (optional) Maximum number of trips to be returned. Default is "whatever HaFAS wants"
:param duration: (optional) Minutes after `date` in which is search is made. Default is "whatever HaFAS wants"
:param products: (optional) Dict of product name(s) and whether it should be enabled or not. Modifies the default products specified in the profile.
:return: List of FPTF `Leg` objects with departing trips
:return: List of FPTF `StationBoardLeg` objects with departing trips
"""
if not isinstance(station, Station):
station = Station(id=station)
Expand All @@ -59,7 +61,7 @@ def departures(
)
res = self.profile.request(body)

return self.profile.parse_station_board_request(res)
return self.profile.parse_station_board_request(res, "d")

def arrivals(
self,
Expand All @@ -68,17 +70,19 @@ def arrivals(
max_journeys: Optional[int] = None, # Deprecated, will be removed in 0.2.0
max_trips: int = -1,
duration: int = -1,
products: Dict[str, bool] = {}) -> List[Leg]:
products: Dict[str, bool] = {}) -> List[StationBoardLeg]:
"""
Returns arriving trips at the specified station
To get detailed information on the trip use the `trip` method with the id
:param station: FPTF `Station` object or ID of station
:param date: Date and Time when to search
:param max_journeys: (optional, deprecated, will be removed in 0.2.0) Use `max_trips` instead - Maximum number of trips to be returned. Default is "whatever HaFAS wants"
:param max_trips: (optional) Maximum number of trips to be returned. Default is "whatever HaFAS wants"
:param duration: (optional) Minutes after `date` in which is search is made. Default is "whatever HaFAS wants"
:param products: (optional) Dict of product name(s) and whether it should be enabled or not. Modifies the default products specified in the profile.
:return: List of FPTF `Leg` objects with arriving trips
:return: List of FPTF `StationBoardLeg` objects with arriving trips
"""
if not isinstance(station, Station):
station = Station(id=station)
Expand All @@ -96,7 +100,7 @@ def arrivals(
)
res = self.profile.request(body)

return self.profile.parse_station_board_request(res)
return self.profile.parse_station_board_request(res, "a")

def journeys(
self,
Expand Down
49 changes: 33 additions & 16 deletions pyhafas/profile/base/requests/station_board.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import datetime
from typing import Dict, List

from pyhafas.types.station_board_request import StationBoardRequestType
from pyhafas.profile import ProfileInterface
from pyhafas.profile.interfaces.requests.station_board import \
StationBoardRequestInterface
from pyhafas.types.fptf import Leg, Station
from pyhafas.types.fptf import Station, StationBoardLeg
from pyhafas.types.hafas_response import HafasResponse
from pyhafas.types.station_board_request import StationBoardRequestType


class BaseStationBoardRequest(StationBoardRequestInterface):
Expand Down Expand Up @@ -50,25 +50,42 @@ def format_station_board_request(

def parse_station_board_request(
self: ProfileInterface,
data: HafasResponse) -> List[Leg]:
data: HafasResponse,
departure_arrival_prefix: str) -> List[StationBoardLeg]:
"""
Parses the HaFAS data for a station board request
:param data: Formatted HaFAS response
:return: List of journey objects
:param departure_arrival_prefix: Prefix for specifying whether its for arrival or departure (either a for arrival or d for departure)
:return: List of StationBoardLeg objects
"""
legs = []
try:
if not data.res.get('jnyL', False):
return legs
else:
for raw_leg in data.res['jnyL']:
leg = self.parse_leg(
raw_leg,
data.res['common'],
raw_leg['stopL'][0],
raw_leg['stopL'][-1],
self.parse_date(raw_leg['date'])
)
legs.append(leg)
except KeyError:
pass
date = self.parse_date(raw_leg['date'])

try:
platform = raw_leg['stbStop'][departure_arrival_prefix + 'PltfR']['txt'] if raw_leg['stbStop'].get(departure_arrival_prefix + 'PltfR') is not None else raw_leg['stbStop'][departure_arrival_prefix + 'PltfS']['txt']
except KeyError:
platform = raw_leg['stbStop'].get(departure_arrival_prefix + 'PlatfR', raw_leg['stbStop'].get(departure_arrival_prefix + 'PlatfS', None))

return legs
legs.append(StationBoardLeg(
id=raw_leg['jid'],
name=data.common['prodL'][raw_leg['prodX']]['name'],
direction=raw_leg['dirTxt'],
date_time=self.parse_datetime(
raw_leg['stbStop'][departure_arrival_prefix + 'TimeS'],
date
),
station=self.parse_lid_to_station(data.common['locL'][raw_leg['stbStop']['locX']]['lid']),
platform=platform,
delay=self.parse_datetime(
raw_leg['stbStop'][departure_arrival_prefix + 'TimeR'],
date) - self.parse_datetime(
raw_leg['stbStop'][departure_arrival_prefix + 'TimeS'],
date) if raw_leg['stbStop'].get(departure_arrival_prefix + 'TimeR') is not None else None,
cancelled=bool(raw_leg['stbStop'].get(departure_arrival_prefix + 'Cncl', False))
))
return legs
10 changes: 7 additions & 3 deletions pyhafas/profile/interfaces/requests/station_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Dict, List

from pyhafas.types.station_board_request import StationBoardRequestType
from pyhafas.types.fptf import Leg, Station
from pyhafas.types.fptf import Leg, Station, StationBoardLeg
from pyhafas.types.hafas_response import HafasResponse


Expand All @@ -30,11 +30,15 @@ def format_station_board_request(
"""
pass

def parse_station_board_request(self, data: HafasResponse) -> List[Leg]:
def parse_station_board_request(
self,
data: HafasResponse,
departure_arrival_prefix: str) -> List[StationBoardLeg]:
"""
Parses the HaFAS data for a station board request
:param data: Formatted HaFAS response
:return: List of journey objects
:param departure_arrival_prefix: Prefix for specifying whether its for arrival or departure
:return: List of StationBoardLeg objects
"""
pass
62 changes: 61 additions & 1 deletion pyhafas/types/fptf.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ class Leg:
A leg or also named trip is most times part of a journey and defines a journey with only one specific vehicle from A to B.
:ivar id: ID of the Journey
:ivar id: ID of the Leg
:vartype id: str
:ivar origin: FPTF `Station` object of the origin station
:vartype origin: Station
Expand Down Expand Up @@ -251,3 +251,63 @@ def __init__(

def __repr__(self):
return "%s(%r)" % (self.__class__, self.__dict__)


class StationBoardLeg:
"""
`StationBoardLeg` object
Returned at Station Board-Requests. This requests do not have enough information for a FPTF `Leg` object.
With the ID a `trip` request can be made to get detailed information about the trip
:ivar id: ID of the Leg
:vartype id: str
:ivar name: Name of the trip (e.g. ICE 123)
:vartype name: str
:ivar direction: Direction text of the trip (e.g. Berlin Central Station)
:vartype direction: str
:ivar station: FPTF `Station` object of the departing/arriving station
:vartype station: Station
:ivar date_time: Planned Date and Time of the departure/arrival
:vartype date_time: datetime.datetime
:ivar cancelled: Whether the stop or trip cancelled
:vartype cancelled: bool
:ivar delay: Delay at the departure station (maybe `None`)
:vartype delay: Optional[datetime.timedelta]
:ivar platform: Real-time platform at the station (maybe `None`)
:vartype platform: Optional[str]
"""
def __init__(
self,
id: str,
name: str,
direction: str,
station: Station,
date_time: datetime.datetime,
cancelled: bool,
delay: Optional[datetime.timedelta] = None,
platform: Optional[str] = None
):
"""
`StationBoardLeg` object
:param id: ID of the Leg
:param name: Name of the trip (e.g. ICE 123)
:param direction: Direction text of the trip (e.g. Berlin Central Station)
:param station: FPTF `Station` object of the departing/arriving station
:param date_time: Planned Date and Time of the departure/arrival
:param cancelled: Whether the stop or trip cancelled
:param delay: (optional) Delay at the departure station. Defaults to `None`
:param platform: (optional) Real-time platform at the station. Defaults to `None`
"""
self.id: str = id
self.name: str = name
self.direction: str = direction
self.station: Station = station
self.dateTime: datetime.datetime = date_time
self.cancelled: bool = cancelled
self.delay: Optional[datetime.timedelta] = delay
self.platform: Optional[str] = platform

def __repr__(self):
return "%s(%r)" % (self.__class__, self.__dict__)

0 comments on commit 69923c0

Please sign in to comment.