Compare commits

..

No commits in common. "dev" and "v0.4.0-rc.1" have entirely different histories.

33 changed files with 480 additions and 759 deletions

View File

@ -11,11 +11,11 @@ on:
jobs: jobs:
test: test:
runs-on: ubuntu-latest-de runs-on: ubuntu-latest
container: catthehacker/ubuntu:act-latest container: catthehacker/ubuntu:act-latest
strategy: strategy:
matrix: matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] python-version: ["3.8", "3.9", "3.10", "3.11"]
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3

1
.gitignore vendored
View File

@ -154,7 +154,6 @@ cython_debug/
# Custom # Custom
.mise.toml
.vscode/ .vscode/
.venv_linux/ .venv_linux/
.venv_windows/ .venv_windows/

View File

@ -10,7 +10,7 @@ maintainers = [{ name = "Profitroll", email = "profitroll@end-play.xyz" }]
description = "Small module that makes your journey with RMV REST API somehow easier." description = "Small module that makes your journey with RMV REST API somehow easier."
readme = "README.md" readme = "README.md"
requires-python = ">=3.8" requires-python = ">=3.8"
license = { text = "MIT" } license = { text = "GPL3" }
classifiers = [ classifiers = [
"Development Status :: 3 - Alpha", "Development Status :: 3 - Alpha",
"Intended Audience :: Developers", "Intended Audience :: Developers",
@ -21,7 +21,6 @@ classifiers = [
"Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities", "Topic :: Utilities",
] ]
@ -39,14 +38,12 @@ dependencies = { file = "requirements/_.txt" }
[tool.setuptools.dynamic.optional-dependencies] [tool.setuptools.dynamic.optional-dependencies]
dev = { file = "requirements/dev.txt" } dev = { file = "requirements/dev.txt" }
dist = { file = "requirements/dist.txt" }
speed = { file = "requirements/speed.txt" }
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
where = ["src"] where = ["src"]
[tool.black] [tool.black]
target-version = ['py38', 'py39', 'py310', 'py311', 'py312'] target-version = ['py38', 'py39', 'py310', 'py311']
line-length = 94 line-length = 94
[tool.isort] [tool.isort]

View File

@ -1,3 +1,3 @@
requests~=2.32.3 requests~=2.31.0
xmltodict~=0.14.0 xmltodict~=0.13.0
isodate~=0.7.0 isodate~=0.6.1

View File

@ -1,12 +1,12 @@
black~=24.8.0 black==23.11.0
isort==5.13.2 build==1.0.3
mypy~=1.13.0 isort==5.12.0
pylint==3.2.7,<3.3.0 mypy==1.7.0
pytest-cov~=6.0.0 pylint==3.0.2
pytest~=8.3.2 pytest-asyncio==0.22.0
tox==4.23.2 pytest-cov==4.1.0
types-ujson~=5.10.0.20240515 pytest==7.4.3
tox==4.11.3
# Disabled async libraries for now twine==4.0.2
# types-aiofiles~=24.1.0.20240626 types-aiofiles==23.2.0.0
# pytest-asyncio~=0.24.0 types-ujson==5.8.0.1

View File

@ -1,2 +0,0 @@
build==1.2.2.post1
twine~=5.1.1

View File

@ -1 +0,0 @@
ujson~=5.10.0

View File

@ -21,7 +21,7 @@ trip = client.trip_find(origin_id=origin.id, dest_id=destination.id)
""" """
__name__ = "pyrmv" __name__ = "pyrmv"
__version__ = "0.4.0" __version__ = "0.4.0-rc.1"
__license__ = "MIT License" __license__ = "MIT License"
__author__ = "Profitroll" __author__ = "Profitroll"

View File

@ -3,7 +3,6 @@ from .gis import Gis
from .journey import Journey from .journey import Journey
from .leg import Leg from .leg import Leg
from .message import Channel, Message, Url from .message import Channel, Message, Url
from .platform_type import PlatformType
from .stop import Stop, StopTrip from .stop import Stop, StopTrip
from .ticket import Ticket from .ticket import Ticket
from .trip import Trip from .trip import Trip

View File

@ -1,57 +1,41 @@
from datetime import datetime from datetime import datetime
from typing import Any, List, Mapping, Union from typing import Any, Mapping
from ..classes.journey import Journey from pyrmv.classes.message import Message
from ..classes.message import Message from pyrmv.utility import ref_upgrade
from ..classes.stop import Stop
from ..utility import ref_upgrade
class LineArrival: class LineArrival:
def __init__( def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True):
self,
data: Mapping[str, Any],
retrieve_stops: bool = False,
retrieve_journey: bool = False,
client: Union["pyrmv.Client", None] = None,
):
if (retrieve_stops or retrieve_journey) and client is None:
raise KeyError(
"Stops/journey retrieval requested but client argument was not provided."
)
# Upgrade is temporarily used due to RMV API mismatch # Upgrade is temporarily used due to RMV API mismatch
# self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) # self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"])
self.journey: Union[Journey, None] = ( self.journey = client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"]))
client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"]))
if retrieve_journey
else None
)
self.status: str = data["JourneyStatus"] self.status = data["JourneyStatus"]
self.messages: List[Message] = [] self.messages = []
self.name: str = data["name"] self.name = data["name"]
self.type: str = data["type"] self.type = data["type"]
self.stop_name: str = data["stop"] self.stop_name = data["stop"]
self.stop_id: str = data["stopid"] self.stop_id = data["stopid"]
self.stop_id_ext: Union[str, None] = data.get("stopExtId") self.stop_id_ext = data["stopExtId"]
self.stop: Union[Stop, None] = ( self.stop = client.stop_by_id(self.stop_id) if retrieve_stops else None
client.stop_by_id(self.stop_id) if retrieve_stops else None self.stop = client.stop_by_id(self.stop_id)
) self.time = datetime.strptime(data["time"], "%H:%M:%S")
self.time: datetime = datetime.strptime( self.date = datetime.strptime(data["date"], "%Y-%m-%d")
f"{data['date']} {data['time']}", "%Y-%m-%d %H:%M:%S" self.reachable = data["reachable"]
) self.origin = data["origin"]
self.time_real: datetime = ( self.origin = data["origin"]
datetime.strptime(f"{data['rtDate']} {data['rtTime']}", "%Y-%m-%d %H:%M:%S")
if data.get("rtTime") and data.get("rtDate")
else None
)
self.reachable: bool = data["reachable"]
self.origin: Union[str, None] = data.get("origin")
if "Messages" in data: if "Messages" in data:
self.messages.extend(Message(message) for message in data["Messages"]["Message"]) self.messages.extend(Message(message) for message in data["Messages"]["Message"])
if ("rtTime" in data) and ("rtDate" in data):
self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S")
self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d")
else:
self.time_real_time = None
self.date_real_time = None
def __str__(self) -> str: def __str__(self) -> str:
return ( return (
f"{self.name} coming from {self.origin} at {self.time.time()} {self.date.date()}" f"{self.name} coming from {self.origin} at {self.time.time()} {self.date.date()}"
@ -59,51 +43,35 @@ class LineArrival:
class LineDeparture: class LineDeparture:
def __init__( def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True):
self,
data: Mapping[str, Any],
retrieve_stops: bool = False,
retrieve_journey: bool = False,
client: Union["pyrmv.Client", None] = None,
):
if (retrieve_stops or retrieve_journey) and client is None:
raise KeyError(
"Stops/journey retrieval requested but client argument was not provided."
)
# Upgrade is temporarily used due to RMV API mismatch # Upgrade is temporarily used due to RMV API mismatch
# self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"]) # self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"])
self.journey: Union[Journey, None] = ( self.journey = client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"]))
client.journey_detail(ref_upgrade(data["JourneyDetailRef"]["ref"]))
if retrieve_journey
else None
)
self.status: str = data["JourneyStatus"] self.status = data["JourneyStatus"]
self.messages: List[Message] = [] self.messages = []
self.name: str = data["name"] self.name = data["name"]
self.type: str = data["type"] self.type = data["type"]
self.stop_name: str = data["stop"] self.stop_name = data["stop"]
self.stop_id: str = data["stopid"] self.stop_id = data["stopid"]
self.stop_id_ext: Union[str, None] = data.get("stopExtId") self.stop_id_ext = data["stopExtId"]
self.stop: Union[Stop, None] = ( self.stop = client.stop_by_id(self.stop_id) if retrieve_stops else None
client.stop_by_id(self.stop_id) if retrieve_stops else None self.time = datetime.strptime(data["time"], "%H:%M:%S")
) self.date = datetime.strptime(data["date"], "%Y-%m-%d")
self.time: datetime = datetime.strptime( self.reachable = data["reachable"]
f"{data['date']} {data['time']}", "%Y-%m-%d %H:%M:%S" self.direction = data["direction"]
) self.direction_flag = data["directionFlag"]
self.time_real: datetime = (
datetime.strptime(f"{data['rtDate']} {data['rtTime']}", "%Y-%m-%d %H:%M:%S")
if data.get("rtTime") and data.get("rtDate")
else None
)
self.reachable: bool = data["reachable"]
self.direction: Union[str, None] = data.get("direction")
self.direction_flag: Union[str, None] = data.get("directionFlag")
if "Messages" in data: if "Messages" in data:
self.messages.extend(Message(message) for message in data["Messages"]["Message"]) self.messages.extend(Message(message) for message in data["Messages"]["Message"])
if ("rtTime" in data) and ("rtDate" in data):
self.time_real_time = datetime.strptime(data["rtTime"], "%H:%M:%S")
self.date_real_time = datetime.strptime(data["rtDate"], "%Y-%m-%d")
else:
self.time_real_time = None
self.date_real_time = None
def __str__(self) -> str: def __str__(self) -> str:
return ( return (
f"{self.name} heading {self.direction} at {self.time.time()} {self.date.date()}" f"{self.name} heading {self.direction} at {self.time.time()} {self.date.date()}"
@ -111,70 +79,28 @@ class LineDeparture:
class BoardArrival(list): class BoardArrival(list):
def __init__( def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True):
self,
data: Mapping[str, Any],
retrieve_stops: bool = False,
retrieve_journey: bool = False,
client: Union["pyrmv.Client", None] = None,
):
"""Arrival board representation
### Args:
* data (`Mapping[str, Any]`): Dictionary from RMV to be parsed.
* retrieve_stops (`bool`, *optional*): Retrieve `Stop` objects for each line of the board. Defaults to `False`.
* retrieve_journey (`bool`, *optional*): Retrieve `Journey` object for each line of the board. Defaults to `False`.
* client (`Union[Client, None]`, *optional*): Client to be used if `retrieve_stops` or `retrieve_journey` are set to `True`. Defaults to `None`.
"""
super().__init__([]) super().__init__([])
if "Arrival" not in data: if "Arrival" not in data:
return return
for line in data["Arrival"]: for line in data["Arrival"]:
self.append( self.append(LineArrival(line, client, retrieve_stops=retrieve_stops))
LineArrival(
line,
retrieve_stops=retrieve_stops,
retrieve_journey=retrieve_journey,
client=client,
)
)
def __str__(self) -> str: def __str__(self) -> str:
return "Arrival board\n" + "\n".join([str(line) for line in self]) return "Arrival board\n" + "\n".join([str(line) for line in self])
class BoardDeparture(list): class BoardDeparture(list):
def __init__( def __init__(self, data: Mapping[str, Any], client, retrieve_stops: bool = True):
self,
data: Mapping[str, Any],
retrieve_stops: bool = False,
retrieve_journey: bool = False,
client: Union["pyrmv.Client", None] = None,
):
"""Departure board representation
### Args:
* data (`Mapping[str, Any]`): Dictionary from RMV to be parsed.
* retrieve_stops (`bool`, *optional*): Retrieve `Stop` objects for each line of the board. Defaults to `False`.
* retrieve_journey (`bool`, *optional*): Retrieve `Journey` object for each line of the board. Defaults to `False`.
* client (`Union[Client, None]`, *optional*): Client to be used if `retrieve_stops` or `retrieve_journey` are set to `True`. Defaults to `None`.
"""
super().__init__([]) super().__init__([])
if "Departure" not in data: if "Departure" not in data:
return return
for line in data["Departure"]: for line in data["Departure"]:
self.append( self.append(LineDeparture(line, client, retrieve_stops=retrieve_stops))
LineDeparture(
line,
retrieve_stops=retrieve_stops,
retrieve_journey=retrieve_journey,
client=client,
)
)
def __str__(self) -> str: def __str__(self) -> str:
return "Departure board\n" + "\n".join([str(line) for line in self]) return "Departure board\n" + "\n".join([str(line) for line in self])

View File

@ -1,7 +1,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import List, OrderedDict, Union from typing import List, OrderedDict, Union
from ..classes import ( from pyrmv.classes import (
BoardArrival, BoardArrival,
BoardDeparture, BoardDeparture,
Journey, Journey,
@ -10,27 +10,16 @@ from ..classes import (
StopTrip, StopTrip,
Trip, Trip,
) )
from ..enums import ( from pyrmv.enums import *
AffectedJourneyMode, from pyrmv.raw import board_arrival as raw_board_arrival
AffectedJourneyStopMode, from pyrmv.raw import board_departure as raw_board_departure
BoardArrivalType, from pyrmv.raw import him_search as raw_him_search
BoardDepartureType, from pyrmv.raw import journey_detail as raw_journey_detail
FilterMode, from pyrmv.raw import stop_by_coords as raw_stop_by_coords
Language, from pyrmv.raw import stop_by_name as raw_stop_by_name
LocationType, from pyrmv.raw import trip_find as raw_trip_find
RealTimeMode, from pyrmv.raw import trip_recon as raw_trip_recon
SearchMode, from pyrmv.utility import find_exception
SelectionMode,
)
from ..raw import board_arrival as raw_board_arrival
from ..raw import board_departure as raw_board_departure
from ..raw import him_search as raw_him_search
from ..raw import journey_detail as raw_journey_detail
from ..raw import stop_by_coords as raw_stop_by_coords
from ..raw import stop_by_name as raw_stop_by_name
from ..raw import trip_find as raw_trip_find
from ..raw import trip_recon as raw_trip_recon
from ..utility import find_exception
try: try:
from typing import Literal from typing import Literal
@ -71,7 +60,7 @@ class Client:
board_departure = client.board_departure("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5) board_departure = client.board_departure("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5)
# Search for HIM messages for S9 # Search for HIM messages for S9
messages = client.him_search(time_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"]) messages = client.him_search(date_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"])
# Get detailed journey of Bus 101 # Get detailed journey of Bus 101
journey = client.journey_detail("2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#", real_time_mode=pyrmv.enums.RealTimeMode.FULL) journey = client.journey_detail("2|#VN#1#ST#1664906549#PI#0#ZI#12709#TA#0#DA#61022#1S#3008007#1T#1248#LS#3008043#LT#1323#PU#80#RT#1#CA#1aE#ZE#101#ZB#Bus 101 #PC#6#FR#3008007#FT#1248#TO#3008043#TT#1323#", real_time_mode=pyrmv.enums.RealTimeMode.FULL)
@ -88,14 +77,15 @@ class Client:
""" """
def __init__(self, access_id: str) -> None: def __init__(self, access_id: str) -> None:
self.access_id: str = access_id self.access_id = access_id
def board_arrival( def board_arrival(
self, self,
id: Union[str, None] = None, id: Union[str, None] = None,
id_ext: Union[str, None] = None, id_ext: Union[str, None] = None,
direction: Union[str, Stop, StopTrip, None] = None, direction: Union[str, Stop, StopTrip, None] = None,
time: Union[datetime, None] = None, date: Union[str, datetime, None] = None,
time: Union[str, datetime, None] = None,
duration: Union[int, timedelta] = 60, duration: Union[int, timedelta] = 60,
journeys_max: int = -1, journeys_max: int = -1,
operators: Union[str, list, None] = None, operators: Union[str, list, None] = None,
@ -108,7 +98,6 @@ class Client:
BoardArrivalType.ARR_STATION, BoardArrivalType.ARR_STATION,
] = BoardArrivalType.ARR, ] = BoardArrivalType.ARR,
retrieve_stops: bool = True, retrieve_stops: bool = True,
retrieve_journey: bool = True,
) -> BoardArrival: ) -> BoardArrival:
"""Method returns a board with arriving transport. """Method returns a board with arriving transport.
@ -118,15 +107,15 @@ class Client:
* id (`str`, **optional**): Specifies the station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * id (`str`, **optional**): Specifies the station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
* id_ext (`str`, **optional**): Deprecated. Please use `id` as it supports external IDs. Specifies the external station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * id_ext (`str`, **optional**): Deprecated. Please use `id` as it supports external IDs. Specifies the external station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
* direction (`Union[str, Stop, StopTrip]`, **optional**): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey or the Stop object itself. Defaults to `None`. * direction (`Union[str, Stop, StopTrip]`, **optional**): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey or the Stop object itself. Defaults to `None`.
* time (`datetime`, **optional**): Sets the start time for which the departures shall be retrieved. Represented as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD or as a datetime object. By default the current server date is used. Defaults to `None`.
* time (`Union[str, datetime]`, **optional**): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature or as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`.
* duration (`Union[int, timedelta]`, **optional**): Set the interval size in minutes. Can also be provided as a timedelta. Defaults to `60`. * duration (`Union[int, timedelta]`, **optional**): Set the interval size in minutes. Can also be provided as a timedelta. Defaults to `60`.
* journeys_max (`int`, **optional**): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to `-1`. * journeys_max (`int`, **optional**): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to `-1`.
* operators (`Union[str, list]`, **optional**): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma or provide a list. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to `None`. * operators (`Union[str, list]`, **optional**): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma or provide a list. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to `None`.
* lines (`Union[str, list]`, **optional**): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma or provide a list. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to `None`. * lines (`Union[str, list]`, **optional**): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma or provide a list. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to `None`.
* passlist (`bool`, **optional**): Include a list of all passed waystops. Defaults to `False`. * passlist (`bool`, **optional**): Include a list of all passed waystops. Defaults to `False`.
* board_type (`Union[BoardArrivalType.ARR, BoardArrivalType.ARR_EQUIVS, BoardArrivalType.ARR_MAST, BoardArrivalType.ARR_STATION]`, *optional*): Set the station arrival board type to be used. Defaults to `BoardArrivalType.ARR`. * board_type (`Union[BoardArrivalType.ARR, BoardArrivalType.ARR_EQUIVS, BoardArrivalType.ARR_MAST, BoardArrivalType.ARR_STATION]`, optional): Set the station arrival board type to be used. Defaults to `BoardArrivalType.ARR`.
* retrieve_stops (`bool`, **optional**): Whether the stops should be retrieved as a `Stop` objects. Using `False` will drastically increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`. * retrieve_stops (`bool`, **optional**): Whether the stops should be retrieved as a `Stop` objects. Using `False` will drastically increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`.
* retrieve_journey (`bool`, **optional**): Whether the journey should be retrieved as a `Journey` object. Using `False` will increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`.
### Returns: ### Returns:
* BoardArrival: Instance of `BoardArrival` object. * BoardArrival: Instance of `BoardArrival` object.
@ -140,7 +129,7 @@ class Client:
id=id, id=id,
extId=id_ext, extId=id_ext,
direction=direction, # type: ignore direction=direction, # type: ignore
date=time, date=date,
time=time, time=time,
duration=duration, duration=duration,
maxJourneys=journeys_max, maxJourneys=journeys_max,
@ -150,21 +139,17 @@ class Client:
boardType=board_type.code, boardType=board_type.code,
) )
find_exception(board_raw.copy()) find_exception(board_raw)
return BoardArrival( return BoardArrival(board_raw, self, retrieve_stops=retrieve_stops)
board_raw,
retrieve_stops=retrieve_stops,
retrieve_journey=retrieve_journey,
client=self,
)
def board_departure( def board_departure(
self, self,
id: Union[str, None] = None, id: Union[str, None] = None,
id_ext: Union[str, None] = None, id_ext: Union[str, None] = None,
direction: Union[str, Stop, StopTrip, None] = None, direction: Union[str, Stop, StopTrip, None] = None,
time: Union[datetime, None] = None, date: Union[str, datetime, None] = None,
time: Union[str, datetime, None] = None,
duration: Union[int, timedelta] = 60, duration: Union[int, timedelta] = 60,
journeys_max: int = -1, journeys_max: int = -1,
operators: Union[str, list, None] = None, operators: Union[str, list, None] = None,
@ -177,7 +162,6 @@ class Client:
BoardDepartureType.DEP_STATION, BoardDepartureType.DEP_STATION,
] = BoardDepartureType.DEP, ] = BoardDepartureType.DEP,
retrieve_stops: bool = True, retrieve_stops: bool = True,
retrieve_journey: bool = True,
) -> BoardDeparture: ) -> BoardDeparture:
"""Method returns a board with departing transport. """Method returns a board with departing transport.
@ -187,15 +171,15 @@ class Client:
* id (`str`, **optional**): Specifies the station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * id (`str`, **optional**): Specifies the station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
* id_ext (`str`, **optional**): Deprecated. Please use `id` as it supports external IDs. Specifies the external station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * id_ext (`str`, **optional**): Deprecated. Please use `id` as it supports external IDs. Specifies the external station/stop ID. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
* direction (`Union[str, Stop, StopTrip]`, **optional**): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey or the Stop object itself. Defaults to `None`. * direction (`Union[str, Stop, StopTrip]`, **optional**): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey or the Stop object itself. Defaults to `None`.
* time (`datetime`, **optional**): Sets the start time for which the departures shall be retrieved. Represented as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD or as a datetime object. By default the current server date is used. Defaults to `None`.
* time (`Union[str, datetime]`, **optional**): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature or as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`.
* duration (`Union[int, timedelta]`, **optional**): Set the interval size in minutes. Can also be provided as a timedelta. Defaults to `60`. * duration (`Union[int, timedelta]`, **optional**): Set the interval size in minutes. Can also be provided as a timedelta. Defaults to `60`.
* journeys_max (`int`, **optional**): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to `-1`. * journeys_max (`int`, **optional**): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to `-1`.
* operators (`Union[str, list]`, **optional**): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma or provide a list. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to `None`. * operators (`Union[str, list]`, **optional**): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma or provide a list. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to `None`.
* lines (`Union[str, list]`, **optional**): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma or provide a list. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to `None`. * lines (`Union[str, list]`, **optional**): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma or provide a list. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to `None`.
* passlist (`bool`, **optional**): Include a list of all passed waystops. Defaults to `False`. * passlist (`bool`, **optional**): Include a list of all passed waystops. Defaults to `False`.
* board_type (`Union[BoardDepartureType.DEP, BoardDepartureType.DEP_EQUIVS, BoardDepartureType.DEP_MAST, BoardDepartureType.DEP_STATION]`, *optional*): Set the station departure board type to be used. Defaults to `BoardDepartureType.DEP`. * board_type (`Union[BoardDepartureType.DEP, BoardDepartureType.DEP_EQUIVS, BoardDepartureType.DEP_MAST, BoardDepartureType.DEP_STATION]`, optional): Set the station departure board type to be used. Defaults to `BoardDepartureType.DEP`.
* retrieve_stops (`bool`, **optional**): Whether the stops should be retrieved as a `Stop` objects. Using `False` will drastically increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`. * retrieve_stops (`bool`, **optional**): Whether the stops should be retrieved as a `Stop` objects. Using `False` will drastically increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`.
* retrieve_journey (`bool`, **optional**): Whether the journey should be retrieved as a `Journey` object. Using `False` will increase processing speed and decrease number of requests made (good for low access_key rate limit). Defaults to `True`.
### Returns: ### Returns:
* BoardDeparture: Instance of `BoardDeparture` object. * BoardDeparture: Instance of `BoardDeparture` object.
@ -209,7 +193,7 @@ class Client:
id=id, id=id,
extId=id_ext, extId=id_ext,
direction=direction, # type: ignore direction=direction, # type: ignore
date=time, date=date,
time=time, time=time,
duration=duration, duration=duration,
maxJourneys=journeys_max, maxJourneys=journeys_max,
@ -219,19 +203,16 @@ class Client:
boardType=board_type.code, boardType=board_type.code,
) )
find_exception(board_raw.copy()) find_exception(board_raw)
return BoardDeparture( return BoardDeparture(board_raw, self, retrieve_stops=retrieve_stops)
board_raw,
retrieve_stops=retrieve_stops,
retrieve_journey=retrieve_journey,
client=self,
)
def him_search( def him_search(
self, self,
time_begin: Union[datetime, None] = None, date_begin: Union[str, datetime, None] = None,
time_end: Union[datetime, None] = None, date_end: Union[str, datetime, None] = None,
time_begin: Union[str, datetime, None] = None,
time_end: Union[str, datetime, None] = None,
weekdays: Union[str, OrderedDict[str, bool], None] = None, weekdays: Union[str, OrderedDict[str, bool], None] = None,
ids: Union[list, None] = None, ids: Union[list, None] = None,
operators: Union[list, None] = None, operators: Union[list, None] = None,
@ -268,26 +249,28 @@ class Client:
More detailed request is available as `raw.him_search()`, however returns `dict` instead of `List[Message]`. More detailed request is available as `raw.him_search()`, however returns `dict` instead of `List[Message]`.
### Args: ### Args:
* time_begin (`datetime`, *optional*): Sets the event period start time. Represented as a datetime object. Defaults to `None`. * date_begin (`Union[str, datetime]`, optional): Sets the event period start date. Defaults to `None`.
* time_end (`datetime`, *optional*): Sets the event period end time. Represented as a datetime object. Defaults to `None`. * date_end (`Union[str, datetime]`, optional): Sets the event period end date. Defaults to `None`.
* weekdays (`Union[str, OrderedDict[str, bool]]`, *optional*): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to `None`. * time_begin (`Union[str, datetime]`, optional): Sets the event period start time. Defaults to `None`.
* ids (`list`, *optional*): List of HIM message IDs as a list or separated by comma. Defaults to `None`. * time_end (`Union[str, datetime]`, optional): Sets the event period end time. Defaults to `None`.
* operators (`list`, *optional*): List of operators as a list or separated by comma. Defaults to `None`. * weekdays (`Union[str, OrderedDict[str, bool]]`, optional): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to `None`.
* categories (`list`, *optional*): List of train categories as a list or separated by comma. Defaults to `None`. * ids (`list`, optional): List of HIM message IDs as a list or separated by comma. Defaults to `None`.
* channels (`list`, *optional*): List of channels as a list or separated by comma. Defaults to `None`. * operators (`list`, optional): List of operators as a list or separated by comma. Defaults to `None`.
* companies (`list`, *optional*): List of companies as a list or separated by comma. Defaults to `None`. * categories (`list`, optional): List of train categories as a list or separated by comma. Defaults to `None`.
* lines (`list`, *optional*): Only HIM messages for the given line are part of the result. To filter multiple lines, provide them as a list or separate the codes by comma. Defaults to `None`. * channels (`list`, optional): List of channels as a list or separated by comma. Defaults to `None`.
* line_ids (`list`, *optional*): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, provide them as a list or separate the line IDs by comma. Defaults to `None`. * companies (`list`, optional): List of companies as a list or separated by comma. Defaults to `None`.
* stations (`Union[list, List[Stop]]`, *optional*): List of (external) station ids or a list of `Stop` objects to be filtered for as a list or separated by comma. Defaults to `None`. * lines (`list`, optional): Only HIM messages for the given line are part of the result. To filter multiple lines, provide them as a list or separate the codes by comma. Defaults to `None`.
* station_from (`Union[str, Stop]`, *optional*): Filter messages by line segment starting at this station given as (external) station id or as a `Stop` object. Defaults to `None`. * line_ids (`list`, optional): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, provide them as a list or separate the line IDs by comma. Defaults to `None`.
* station_to (`Union[str, Stop]`, *optional*): Filter messages by line segment travelling in direction of this station given as (external) station id or as a `Stop` object. Defaults to `None`. * stations (`Union[list, List[Stop]]`, optional): List of (external) station ids or a list of `Stop` objects to be filtered for as a list or separated by comma. Defaults to `None`.
* both_ways (`bool`, *optional*): If enabled, messages in both directions - from 'station_from' to 'station_to' as well as from 'station_to' to 'station_from' are returned. Defaults to `None`. * station_from (`Union[str, Stop]`, optional): Filter messages by line segment starting at this station given as (external) station id or as a `Stop` object. Defaults to `None`.
* train_names (`list`, *optional*): List of train name to be filtered for seperated by comma. Defaults to `None`. * station_to (`Union[str, Stop]`, optional): Filter messages by line segment travelling in direction of this station given as (external) station id or as a `Stop` object. Defaults to `None`.
* search_mode (`Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH]`, *optional*): HIM search mode. `SearchMode.NOMATCH` iterate over all HIM messages available. `SearchMode.MATCH` iterate over all trips to find HIM messages. `SearchMode.TFMATCH` uses filters defined `metas` parameter. Defaults to `None`. * both_ways (`bool`, optional): If enabled, messages in both directions - from 'station_from' to 'station_to' as well as from 'station_to' to 'station_from' are returned. Defaults to `None`.
* affected_journey_mode (`Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF]`, *optional*): Define how to return affected journeys `AffectedJourneyMode.OFF`: do not return affected journeys. `AffectedJourneyMode.ALL`: return affected journeys. Defaults to `None`. * train_names (`list`, optional): List of train name to be filtered for seperated by comma. Defaults to `None`.
* affected_journey_stop_mode (`Literal[AffectedJourneyStopMode.ALL, AffectedJourneyStopMode.IMP, AffectedJourneyStopMode.OFF]`, *optional*): Define how to return stops of affected journeys. `AffectedJourneyStopMode.IMP`: return important stops of affected journeys. `AffectedJourneyStopMode.OFF`: do not return stops of affected journeys. `AffectedJourneyStopMode.ALL`: return all affected stops of affected journeys. Defaults to `None`. * search_mode (`Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH]`, optional): HIM search mode. `SearchMode.NOMATCH` iterate over all HIM messages available. `SearchMode.MATCH` iterate over all trips to find HIM messages. `SearchMode.TFMATCH` uses filters defined `metas` parameter. Defaults to `None`.
* priority_min (`int`, *optional*): Filter for HIM messages having at least this priority. Defaults to `None`. * affected_journey_mode (`Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF]`, optional): Define how to return affected journeys `AffectedJourneyMode.OFF`: do not return affected journeys. `AffectedJourneyMode.ALL`: return affected journeys. Defaults to `None`.
* priority_max (`int`, *optional*): Filter for HIM messages having this priority as maximum. Defaults to `None`. * affected_journey_stop_mode (`Literal[AffectedJourneyStopMode.ALL, AffectedJourneyStopMode.IMP, AffectedJourneyStopMode.OFF]`, optional): Define how to return stops of affected journeys. `AffectedJourneyStopMode.IMP`: return important stops of affected journeys. `AffectedJourneyStopMode.OFF`: do not return stops of affected journeys. `AffectedJourneyStopMode.ALL`: return all affected stops of affected journeys. Defaults to `None`.
* priority_min (`int`, optional): Filter for HIM messages having at least this priority. Defaults to `None`.
* priority_max (`int`, optional): Filter for HIM messages having this priority as maximum. Defaults to `None`.
### Returns: ### Returns:
* List[Message]: List of `Message` objects. Empty list if none found. * List[Message]: List of `Message` objects. Empty list if none found.
@ -319,8 +302,8 @@ class Client:
messages = [] messages = []
messages_raw = raw_him_search( messages_raw = raw_him_search(
accessId=self.access_id, accessId=self.access_id,
dateB=time_begin, dateB=date_begin,
dateE=time_end, dateE=date_end,
timeB=time_begin, timeB=time_begin,
timeE=time_end, timeE=time_end,
weekdays=weekdays, weekdays=weekdays,
@ -343,7 +326,7 @@ class Client:
minprio=priority_min, minprio=priority_min,
) )
find_exception(messages_raw.copy()) find_exception(messages_raw)
if "Message" in messages_raw: if "Message" in messages_raw:
messages.extend(Message(message) for message in messages_raw["Message"]) messages.extend(Message(message) for message in messages_raw["Message"])
@ -402,7 +385,7 @@ class Client:
toIdx=to_index, toIdx=to_index,
) )
find_exception(journey_raw.copy()) find_exception(journey_raw)
return Journey(journey_raw) return Journey(journey_raw)
@ -411,30 +394,18 @@ class Client:
coords_lat: Union[str, float], coords_lat: Union[str, float],
coords_lon: Union[str, float], coords_lon: Union[str, float],
lang: Literal[ lang: Literal[
Language.AR,
Language.CA,
Language.DA,
Language.DE, Language.DE,
Language.EL, Language.DA,
Language.EN, Language.EN,
Language.ES, Language.ES,
Language.FI,
Language.FR, Language.FR,
Language.HI,
Language.HR,
Language.HU, Language.HU,
Language.IT, Language.IT,
Language.NL, Language.NL,
Language.NO, Language.NO,
Language.PL, Language.PL,
Language.RU,
Language.SK,
Language.SL,
Language.SV, Language.SV,
Language.TL,
Language.TR, Language.TR,
Language.UR,
Language.ZH,
] = Language.EN, ] = Language.EN,
radius: Union[int, float] = 1000, radius: Union[int, float] = 1000,
max_number: int = 10, max_number: int = 10,
@ -457,7 +428,7 @@ class Client:
### Args: ### Args:
* coords_lat (`Union[str, float]`): Latitude of centre coordinate. * coords_lat (`Union[str, float]`): Latitude of centre coordinate.
* coords_lon (`Union[str, float]`): Longitude of centre coordinate. * coords_lon (`Union[str, float]`): Longitude of centre coordinate.
* lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`.
* radius (`Union[int, float]`, **optional**): Search radius in meter around the given coordinate if any. Defaults to `1000`. * radius (`Union[int, float]`, **optional**): Search radius in meter around the given coordinate if any. Defaults to `1000`.
* max_number (`int`, **optional**): Maximum number of returned stops. Defaults to `10`. * max_number (`int`, **optional**): Maximum number of returned stops. Defaults to `10`.
* stop_type (`Literal[LocationType.S, LocationType.P, LocationType.SP, LocationType.SE, LocationType.SPE]`, **optional**): Type filter for location types. Defaults to `LocationType.S`. * stop_type (`Literal[LocationType.S, LocationType.P, LocationType.SP, LocationType.SE, LocationType.SPE]`, **optional**): Type filter for location types. Defaults to `LocationType.S`.
@ -481,7 +452,7 @@ class Client:
locationSelectionMode=selection_mode, # type: ignore locationSelectionMode=selection_mode, # type: ignore
) )
find_exception(stops_raw.copy()) find_exception(stops_raw)
if "stopLocationOrCoordLocation" in stops_raw: if "stopLocationOrCoordLocation" in stops_raw:
for stop in stops_raw["stopLocationOrCoordLocation"]: for stop in stops_raw["stopLocationOrCoordLocation"]:
@ -496,37 +467,25 @@ class Client:
self, self,
query: str, query: str,
lang: Literal[ lang: Literal[
Language.AR,
Language.CA,
Language.DA,
Language.DE, Language.DE,
Language.EL, Language.DA,
Language.EN, Language.EN,
Language.ES, Language.ES,
Language.FI,
Language.FR, Language.FR,
Language.HI,
Language.HR,
Language.HU, Language.HU,
Language.IT, Language.IT,
Language.NL, Language.NL,
Language.NO, Language.NO,
Language.PL, Language.PL,
Language.RU,
Language.SK,
Language.SL,
Language.SV, Language.SV,
Language.TL,
Language.TR, Language.TR,
Language.UR,
Language.ZH,
] = Language.EN, ] = Language.EN,
) -> Union[Stop, None]: ) -> Union[Stop, None]:
"""Method can be used to get Stop object whilst only having id available. """Method can be used to get Stop object whilst only having id available.
### Args: ### Args:
* query (`str`): Search for that token. * query (`str`): Search for that token.
* lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`.
### Returns: ### Returns:
* Union[Stop, None]: Instance of `Stop` object or `None` if not found. * Union[Stop, None]: Instance of `Stop` object or `None` if not found.
@ -536,7 +495,7 @@ class Client:
accessId=self.access_id, inputString=query, lang=lang.code, maxNo=1 accessId=self.access_id, inputString=query, lang=lang.code, maxNo=1
) )
find_exception(stops_raw.copy()) find_exception(stops_raw)
if len(stops_raw["stopLocationOrCoordLocation"]) <= 0: if len(stops_raw["stopLocationOrCoordLocation"]) <= 0:
return None return None
@ -554,30 +513,18 @@ class Client:
self, self,
query: str, query: str,
lang: Literal[ lang: Literal[
Language.AR,
Language.CA,
Language.DA,
Language.DE, Language.DE,
Language.EL, Language.DA,
Language.EN, Language.EN,
Language.ES, Language.ES,
Language.FI,
Language.FR, Language.FR,
Language.HI,
Language.HR,
Language.HU, Language.HU,
Language.IT, Language.IT,
Language.NL, Language.NL,
Language.NO, Language.NO,
Language.PL, Language.PL,
Language.RU,
Language.SK,
Language.SL,
Language.SV, Language.SV,
Language.TL,
Language.TR, Language.TR,
Language.UR,
Language.ZH,
] = Language.EN, ] = Language.EN,
max_number: int = 10, max_number: int = 10,
stop_type: Literal[ stop_type: Literal[
@ -609,7 +556,7 @@ class Client:
### Args: ### Args:
* query (`str`): Search for that token. * query (`str`): Search for that token.
* lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`.
* max_number (`int`, **optional**): Maximum number of returned stops. In range 1-1000. Defaults to `10`. * max_number (`int`, **optional**): Maximum number of returned stops. In range 1-1000. Defaults to `10`.
* stop_type (`Literal[LocationType.A, LocationType.ALL, LocationType.AP, LocationType.P, LocationType.S, LocationType.SA, LocationType.SP]`, **optional**): Type filter for location types. Defaults to `LocationType.ALL`. * stop_type (`Literal[LocationType.A, LocationType.ALL, LocationType.AP, LocationType.P, LocationType.S, LocationType.SA, LocationType.SP]`, **optional**): Type filter for location types. Defaults to `LocationType.ALL`.
* selection_mode (`Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N]`, **optional**): Selection mode for locations. `SelectionMode.SLCT_N`: Not selectable, `SelectionMode.SLCT_A`: Selectable. Defaults to `None`. * selection_mode (`Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N]`, **optional**): Selection mode for locations. `SelectionMode.SLCT_N`: Not selectable, `SelectionMode.SLCT_A`: Selectable. Defaults to `None`.
@ -642,7 +589,7 @@ class Client:
filterMode=filter_mode.code, filterMode=filter_mode.code,
) )
find_exception(stops_raw.copy()) find_exception(stops_raw)
if "stopLocationOrCoordLocation" in stops_raw: if "stopLocationOrCoordLocation" in stops_raw:
for stop in stops_raw["stopLocationOrCoordLocation"]: for stop in stops_raw["stopLocationOrCoordLocation"]:
@ -656,30 +603,18 @@ class Client:
def trip_find( def trip_find(
self, self,
lang: Literal[ lang: Literal[
Language.AR,
Language.CA,
Language.DA,
Language.DE, Language.DE,
Language.EL, Language.DA,
Language.EN, Language.EN,
Language.ES, Language.ES,
Language.FI,
Language.FR, Language.FR,
Language.HI,
Language.HR,
Language.HU, Language.HU,
Language.IT, Language.IT,
Language.NL, Language.NL,
Language.NO, Language.NO,
Language.PL, Language.PL,
Language.RU,
Language.SK,
Language.SL,
Language.SV, Language.SV,
Language.TL,
Language.TR, Language.TR,
Language.UR,
Language.ZH,
] = Language.EN, ] = Language.EN,
origin_id: Union[str, None] = None, origin_id: Union[str, None] = None,
origin_id_ext: Union[str, None] = None, origin_id_ext: Union[str, None] = None,
@ -702,7 +637,8 @@ class Client:
change_time_max: Union[int, None] = None, change_time_max: Union[int, None] = None,
change_time_add: Union[int, None] = None, change_time_add: Union[int, None] = None,
change_max: Union[int, None] = None, change_max: Union[int, None] = None,
time: Union[datetime, None] = None, date: Union[str, datetime, None] = None,
time: Union[str, datetime, None] = None,
search_arrival: bool = False, search_arrival: bool = False,
trips_after_time: Union[int, None] = None, trips_after_time: Union[int, None] = None,
trips_before_time: Union[int, None] = None, trips_before_time: Union[int, None] = None,
@ -738,7 +674,7 @@ class Client:
More detailed request is available as `raw.trip_find()`, however returns `dict` instead of `List[Trip]`. More detailed request is available as `raw.trip_find()`, however returns `dict` instead of `List[Trip]`.
### Args: ### Args:
* lang (`Literal[Language.AR, Language.CA, Language.DA, Language.DE, Language.EL, Language.EN, Language.ES, Language.FI, Language.FR, Language.HI, Language.HR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.RU, Language.SK, Language.SL, Language.SV, Language.TL, Language.TR, Language.UR, Language.ZH]`, **optional**): The language of response. Defaults to `Language.EN`. * lang (`Literal[Language.DE, Language.DA, Language.EN, Language.ES, Language.FR, Language.HU, Language.IT, Language.NL, Language.NO, Language.PL, Language.SV, Language.TR]`, **optional**): The language of response. Defaults to `Language.EN`.
* origin_id (`str`, **optional**): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * origin_id (`str`, **optional**): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
* origin_id_ext (`str`, **optional**): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * origin_id_ext (`str`, **optional**): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
* origin_coord_lat (`Union[str, float]`, **optional**): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`. * origin_coord_lat (`Union[str, float]`, **optional**): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
@ -753,14 +689,15 @@ class Client:
* via_id (`str`, **optional**): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stop_by_name() or stop_by_coords(). If `via` is used, `via_id` and `via_wait_time ` are having no effect. Defaults to `None`. * via_id (`str`, **optional**): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stop_by_name() or stop_by_coords(). If `via` is used, `via_id` and `via_wait_time ` are having no effect. Defaults to `None`.
* via_gis (`str`, **optional**): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to `None`. * via_gis (`str`, **optional**): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to `None`.
* via_wait_time (`int`, **optional**): Defines the waiting time spent at via station in minutes. If `via` is used, `via_id` and `via_wait_time` are having no effect. Defaults to 0. * via_wait_time (`int`, **optional**): Defines the waiting time spent at via station in minutes. If `via` is used, `via_id` and `via_wait_time` are having no effect. Defaults to 0.
* avoid (`str`, **optional**): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), *optional* but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to `None`. * avoid (`str`, **optional**): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), optional but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to `None`.
* avoid_id (`str`, **optional**): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). If `avoid` is used, `avoid_id` has no effect. Defaults to `None`. * avoid_id (`str`, **optional**): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). If `avoid` is used, `avoid_id` has no effect. Defaults to `None`.
* change_time_percent (`int`, **optional**): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to `100`. * change_time_percent (`int`, **optional**): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to `100`.
* change_time_min (`int`, **optional**): Minimum change time at stop in minutes. Defaults to `None`. * change_time_min (`int`, **optional**): Minimum change time at stop in minutes. Defaults to `None`.
* change_time_max (`int`, **optional**): Maximum change time at stop in minutes. Defaults to `None`. * change_time_max (`int`, **optional**): Maximum change time at stop in minutes. Defaults to `None`.
* change_time_add (`int`, **optional**): This amount of minutes is added to the change time at each stop. Defaults to `None`. * change_time_add (`int`, **optional**): This amount of minutes is added to the change time at each stop. Defaults to `None`.
* change_max (`int`, **optional**): Maximum number of changes. In range 0-11. Defaults to `None`. * change_max (`int`, **optional**): Maximum number of changes. In range 0-11. Defaults to `None`.
* time (`datetime`, **optional**): Sets the start time for which the departures shall be retrieved. Represented as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`. * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD` or as a datetime object. By default the current server date is used. Defaults to `None`.
* time (`Union[str, datetime]`, **optional**): Sets the start time for which the departures shall be retrieved. Represented in the format `hh:mm[:ss]` in 24h nomenclature or as a datetime object. Seconds will be ignored for requests. By default the current server time is used. Defaults to `None`.
* search_arrival (`bool`, **optional**): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to `False`. * search_arrival (`bool`, **optional**): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to `False`.
* trips_after_time (`int`, **optional**): Minimum number of trips after the search time. Sum of `trips_after_time` and `trips_before_time` has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to `None`. * trips_after_time (`int`, **optional**): Minimum number of trips after the search time. Sum of `trips_after_time` and `trips_before_time` has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to `None`.
* trips_before_time (`int`, **optional**): Minimum number of trips before the search time. Sum of `trips_after_time` and `trips_before_time` has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to `None`. * trips_before_time (`int`, **optional**): Minimum number of trips before the search time. Sum of `trips_after_time` and `trips_before_time` has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to `None`.
@ -811,7 +748,7 @@ class Client:
maxChangeTime=change_time_max, maxChangeTime=change_time_max,
addChangeTime=change_time_add, addChangeTime=change_time_add,
maxChange=change_max, maxChange=change_max,
date=time, date=date,
time=time, time=time,
searchForArrival=search_arrival, searchForArrival=search_arrival,
numF=trips_after_time, numF=trips_after_time,
@ -833,7 +770,7 @@ class Client:
withFreq=frequency, withFreq=frequency,
) )
find_exception(trips_raw.copy()) find_exception(trips_raw)
if "Trip" in trips_raw: if "Trip" in trips_raw:
trips.extend(Trip(trip) for trip in trips_raw["Trip"]) trips.extend(Trip(trip) for trip in trips_raw["Trip"])
@ -843,7 +780,7 @@ class Client:
def trip_recon( def trip_recon(
self, self,
context: Union[str, Trip], context: Union[str, Trip],
date: Union[datetime, None] = None, date: Union[str, datetime, None] = None,
match_real_time: Union[bool, None] = None, match_real_time: Union[bool, None] = None,
enable_replacements: Union[bool, None] = None, enable_replacements: Union[bool, None] = None,
arrival_dev_lower: Union[int, None] = None, arrival_dev_lower: Union[int, None] = None,
@ -873,7 +810,7 @@ class Client:
### Args: ### Args:
* context (`Union[str, Journey]`): Specifies the reconstruction context. * context (`Union[str, Journey]`): Specifies the reconstruction context.
* date (`datetime`, **optional**): Sets the start date for which the departures shall be retrieved. Represented as a datetime object. This parameter will force the service to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, exception SvcNoResultError will be raised. Defaults to `None`. * date (`Union[str, datetime]`, **optional**): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD` or as a datetime object. This parameter will force the service to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, exception SvcNoResultError will be raised. Defaults to `None`.
* match_real_time (`bool`, **optional**): Whether the realtime type that journeys are based on be considered. Defaults to `None`. * match_real_time (`bool`, **optional**): Whether the realtime type that journeys are based on be considered. Defaults to `None`.
* enable_replacements (`bool`, **optional**): If set to `True` replaces cancelled journeys with their replacement journeys if possible. Defaults to `None`. * enable_replacements (`bool`, **optional**): If set to `True` replaces cancelled journeys with their replacement journeys if possible. Defaults to `None`.
* arrival_dev_lower (`int`, **optional**): Lower deviation in minutes within interval `[0, 720]` indicating "how much earlier than original arrival". Defaults to `None`. * arrival_dev_lower (`int`, **optional**): Lower deviation in minutes within interval `[0, 720]` indicating "how much earlier than original arrival". Defaults to `None`.
@ -913,7 +850,7 @@ class Client:
trafficMessages=messages, trafficMessages=messages,
) )
find_exception(trips_raw.copy()) find_exception(trips_raw)
if "Trip" in trips_raw: if "Trip" in trips_raw:
trips.extend(Trip(trip) for trip in trips_raw["Trip"]) trips.extend(Trip(trip) for trip in trips_raw["Trip"])

View File

@ -1,14 +1,13 @@
from datetime import timedelta from typing import Any, Mapping
from typing import Any, Mapping, Union
from isodate import Duration, parse_duration from isodate import parse_duration
class Gis: class Gis:
"""Gis object.""" """Gis object."""
def __init__(self, ref: str, route: Mapping[str, Any]): def __init__(self, ref: str, route: Mapping[str, Any]):
self.ref: str = ref self.ref = ref
self.dist: Union[int, None] = route.get("dist") self.dist = route["dist"]
self.duration: Union[Duration, timedelta] = parse_duration(route["durS"]) self.duration = parse_duration(route["durS"])
self.geo: Union[int, None] = route.get("dirGeo") self.geo = route["dirGeo"]

View File

@ -1,32 +1,24 @@
from typing import Any, List, Mapping, Union from typing import Any, Mapping
from ..classes.message import Message from pyrmv.classes.message import Message
from ..classes.stop import Stop from pyrmv.classes.stop import Stop
from ..utility import ref_upgrade from pyrmv.utility import ref_upgrade
class Journey: class Journey:
"""Journey object.""" """Journey object."""
def __init__(self, data: Mapping[str, Any]): def __init__(self, data: Mapping[str, Any]):
self.stops: List[Stop] = [] self.stops = []
# Upgrade is temporarily used due to RMV API mismatch # Upgrade is temporarily used due to RMV API mismatch
# self.ref = data["ref"] # self.ref = data["ref"]
self.ref: str = ref_upgrade(data["ref"]) self.ref = ref_upgrade(data["ref"])
self.direction: Union[str, None] = ( self.direction = data["Directions"]["Direction"][0]["value"]
data["Directions"]["Direction"][0].get("value") self.direction_flag = data["Directions"]["Direction"][0]["flag"]
if data["Directions"]["Direction"]
else None
)
self.direction_flag: Union[str, None] = (
data["Directions"]["Direction"][0].get("flag")
if data["Directions"]["Direction"]
else None
)
self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"]) self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"])
self.messages: List[Message] = [] self.messages = []
if "Messages" in data: if "Messages" in data:
self.messages.extend(Message(message) for message in data["Messages"]["Message"]) self.messages.extend(Message(message) for message in data["Messages"]["Message"])

View File

@ -1,30 +1,29 @@
from datetime import timedelta from typing import Any, Mapping
from typing import Any, List, Mapping, Union
from isodate import Duration, parse_duration from isodate import parse_duration
from ..classes.gis import Gis from pyrmv.classes.gis import Gis
from ..classes.message import Message from pyrmv.classes.message import Message
from ..classes.stop import StopTrip from pyrmv.classes.stop import StopTrip
class Leg: class Leg:
"""Trip leg object.""" """Trip leg object."""
def __init__(self, data: Mapping[str, Any]): def __init__(self, data: Mapping[str, Any]):
self.origin: StopTrip = StopTrip(data["Origin"]) self.origin = StopTrip(data["Origin"])
self.destination: StopTrip = StopTrip(data["Destination"]) self.destination = StopTrip(data["Destination"])
self.gis = ( self.gis = (
None if "GisRef" not in data else Gis(data["GisRef"]["ref"], data["GisRoute"]) None if "GisRef" not in data else Gis(data["GisRef"]["ref"], data["GisRoute"])
) )
self.messages: List[Message] = [] self.messages = []
self.index: Union[int, None] = data.get("idx") self.index = data["idx"]
self.name: str = data["name"] self.name = data["name"]
self.type: Union[str, None] = data.get("type") self.type = data["type"]
self.direction: Union[str, None] = data.get("direction") self.direction = data.get("direction")
self.number: Union[str, None] = data.get("number") self.number = data.get("number")
self.duration: Union[Duration, timedelta] = parse_duration(data["duration"]) self.duration = parse_duration(data["duration"])
self.distance: Union[int, None] = data.get("dist") self.distance = data.get("dist")
if "Messages" in data: if "Messages" in data:
self.messages.extend(Message(message) for message in data["Messages"]["Message"]) self.messages.extend(Message(message) for message in data["Messages"]["Message"])

View File

@ -1,17 +1,17 @@
from datetime import datetime, timedelta from datetime import datetime
from typing import Any, List, Mapping, Union from typing import Any, Mapping
from isodate import Duration, parse_duration from isodate import parse_duration
from ..classes.stop import Stop from pyrmv.classes.stop import Stop
class Url: class Url:
"""Traffic message channel url object.""" """Traffic message channel url object."""
def __init__(self, data: Mapping[str, Any]) -> None: def __init__(self, data: Mapping[str, Any]) -> None:
self.name: str = data["name"] self.name = data["name"]
self.url: str = data["url"] self.url = data["url"]
def __str__(self) -> str: def __str__(self) -> str:
return f"{self.name}: {self.url}" return f"{self.name}: {self.url}"
@ -21,84 +21,51 @@ class Channel:
"""Traffic message channel object.""" """Traffic message channel object."""
def __init__(self, data: Mapping[str, Any]) -> None: def __init__(self, data: Mapping[str, Any]) -> None:
self.name: str = data["name"] self.name = data["name"]
url = [] url = []
url.extend(Url(link) for link in url) url.extend(Url(link) for link in url)
self.url: List[Url] = url self.url = url
self.time_start: Union[datetime, None] = ( self.time_start = datetime.strptime(data["validFromTime"], "%H:%M:%S")
None self.date_start = datetime.strptime(data["validFromDate"], "%Y-%m-%d")
if "validFromDate" not in data self.time_end = datetime.strptime(data["validToTime"], "%H:%M:%S")
else datetime.strptime( self.date_end = datetime.strptime(data["validToDate"], "%Y-%m-%d")
f"{data['validFromDate']} {data['validFromTime']}", "%Y-%m-%d %H:%M:%S"
)
)
self.time_end: Union[datetime, None] = (
None
if "validToDate" not in data
else datetime.strptime(
f"{data['validToDate']} {data['validToTime']}", "%Y-%m-%d %H:%M:%S"
)
)
def __str__(self) -> str: def __str__(self) -> str:
return f"{self.name}: from {self.time_start} until {self.time_end}" return f"{self.name}: from {self.time_start} {self.date_start} until {self.time_end} {self.date_end}"
class Message: class Message:
"""Traffic message object.""" """Traffic message object."""
def __init__(self, data: Mapping[str, Any]) -> None: def __init__(self, data: Mapping[str, Any]) -> None:
self.affected_stops: List[Stop] = [] self.affected_stops = []
self.valid_from_stop: Union[Stop, None] = ( self.valid_from_stop = (
None if "validFromStop" not in data else Stop(data["validFromStop"]) None if "validFromStop" not in data else Stop(data["validFromStop"])
) )
self.valid_to_stop: Union[Stop, None] = ( self.valid_to_stop = None if "validToStop" not in data else Stop(data["validToStop"])
None if "validToStop" not in data else Stop(data["validToStop"]) self.channels = []
)
self.channels: Union[Channel, None] = []
self.channels.extend(Channel(channel) for channel in data["channel"]) self.channels.extend(Channel(channel) for channel in data["channel"])
self.id: str = data["id"] self.id = data["id"]
self.active: bool = data["act"] self.active = data["act"]
self.head: str = "" if "head" not in data else data["head"] self.head = data["head"]
self.lead: str = "" if "lead" not in data else data["lead"] self.lead = data["lead"]
self.text: str = "" if "text" not in data else data["text"] self.text = data["text"]
self.company: Union[str, None] = data.get("company") self.company = data["company"]
self.category: Union[str, None] = data.get("category") self.category = data["category"]
self.priority: Union[int, None] = data.get("priority") self.priority = None if "priority" not in data else data["priority"]
self.products: int = data["products"] self.products = data["products"]
self.icon: Mapping[str, Any] = data["icon"] self.icon = data["icon"]
self.time_start: Union[datetime, None] = ( self.time_start = datetime.strptime(data["sTime"], "%H:%M:%S")
None self.date_start = datetime.strptime(data["sDate"], "%Y-%m-%d")
if "validFromDate" not in data or "validFromTime" not in data self.time_end = datetime.strptime(data["eTime"], "%H:%M:%S")
else datetime.strptime( self.date_end = datetime.strptime(data["eDate"], "%Y-%m-%d")
f"{data['validFromDate']} {data['validFromTime']}", "%Y-%m-%d %H:%M:%S" self.date_start_alt = data["altStart"]
) self.date_end_alt = data["altEnd"]
) self.time_modified = datetime.strptime(data["modTime"], "%H:%M:%S")
self.time_end: Union[datetime, None] = ( self.date_modified = datetime.strptime(data["modDate"], "%Y-%m-%d")
None self.daily_start = datetime.strptime(data["dailyStartingAt"], "%H:%M:%S")
if "validToDate" not in data or "validToTime" not in data self.daily_duration = parse_duration(data["dailyDuration"])
else datetime.strptime( self.base_type = data["baseType"] if "baseType" in data else None
f"{data['validToDate']} {data['validToTime']}", "%Y-%m-%d %H:%M:%S"
)
)
self.date_start_alt: str = data["altStart"]
self.date_end_alt: str = data["altEnd"]
self.time_modified: Union[datetime, None] = (
None
if "modDate" not in data or "modTime" not in data
else datetime.strptime(
f"{data['modDate']} {data['modTime']}", "%Y-%m-%d %H:%M:%S"
)
)
self.daily_start: Union[datetime, None] = (
None
if "dailyStartingAt" not in data
else datetime.strptime(data["dailyStartingAt"], "%H:%M:%S")
)
self.daily_duration: Union[Duration, timedelta] = parse_duration(
data["dailyDuration"]
)
self.base_type: Union[str, None] = data.get("baseType")
if "affectedStops" in data: if "affectedStops" in data:
self.affected_stops.extend( self.affected_stops.extend(
@ -106,4 +73,4 @@ class Message:
) )
def __str__(self) -> str: def __str__(self) -> str:
return f"{self.base_type} message with priority {self.products} valid from {self.time_start} until {self.time_end}: {self.head} - {self.lead}" return f"{self.base_type} message with priority {self.products} valid from {self.time_start.time()} {self.date_start.date()} until {self.time_end.time()} {self.date_end.date()}: {self.head} - {self.lead}"

View File

@ -1,17 +0,0 @@
from typing import Any, Mapping, Union
from ..enums.platform_type_type import PlatformTypeType
class PlatformType:
"""Platform information."""
def __init__(self, data: Mapping[str, Any]):
self.type: PlatformTypeType = (
PlatformTypeType.U if "type" not in data else PlatformTypeType(data.get("type"))
)
self.text: Union[str, None] = data.get("text")
self.hidden: bool = bool(data.get("hidden"))
self.lon: float = data["lon"]
self.lat: float = data["lat"]
self.alt: int = data["alt"]

View File

@ -1,20 +1,19 @@
from datetime import datetime from datetime import datetime
from typing import Union
class Stop: class Stop:
"""Stop object.""" """Stop object."""
def __init__(self, data: dict): def __init__(self, data: dict):
self.name: str = data["name"] self.name = data["name"]
self.id: str = data["id"] self.id = data["id"]
self.ext_id: Union[str, None] = data.get("extId") self.ext_id = data.get("extId")
self.description: Union[str, None] = data.get("description") self.description = data.get("description")
self.lon: float = data["lon"] self.lon = data["lon"]
self.lat: float = data["lat"] self.lat = data["lat"]
self.route_index: Union[int, None] = data.get("routeIdx") self.route_index = data.get("routeIdx")
self.track_arrival: Union[str, None] = data.get("arrTrack") self.track_arrival = data.get("arrTrack")
self.track_departure: Union[str, None] = data.get("depTrack") self.track_departure = data.get("depTrack")
def __str__(self) -> str: def __str__(self) -> str:
return f"Stop {self.name} at {self.lon}, {self.lat}" return f"Stop {self.name} at {self.lon}, {self.lat}"
@ -24,11 +23,10 @@ class StopTrip(Stop):
"""Trip stop object. It's like a Stop object, but with a date and time.""" """Trip stop object. It's like a Stop object, but with a date and time."""
def __init__(self, data: dict): def __init__(self, data: dict):
self.type: str = data["type"] self.type = data["type"]
self.time: datetime = datetime.strptime( self.date = datetime.strptime(data["date"], "%Y-%m-%d")
f"{data['date']} {data['time']}", "%Y-%m-%d %H:%M:%S" self.time = datetime.strptime(data["time"], "%H:%M:%S")
)
super().__init__(data) super().__init__(data)
def __str__(self) -> str: def __str__(self) -> str:
return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()}" return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()} {self.date.date()}"

View File

@ -1,32 +1,28 @@
from datetime import timedelta from isodate import parse_duration
from typing import List, Union
from isodate import Duration, parse_duration from pyrmv.classes.leg import Leg
from pyrmv.classes.stop import StopTrip
from ..classes.leg import Leg
from ..classes.stop import StopTrip
class Trip: class Trip:
"""Trip object.""" """Trip object."""
def __init__(self, data: dict): def __init__(self, data: dict):
self.origin: StopTrip = StopTrip(data["Origin"]) self.raw_data = data
self.destination: StopTrip = StopTrip(data["Destination"]) self.origin = StopTrip(data["Origin"])
self.legs: List[Leg] = [] self.destination = StopTrip(data["Destination"])
self.legs = []
self.legs.extend(Leg(leg) for leg in data["LegList"]["Leg"]) self.legs.extend(Leg(leg) for leg in data["LegList"]["Leg"])
self.calculation: str = data["calculation"] self.calculation = data["calculation"]
self.index: int = data["idx"] self.index = data["idx"]
self.id: str = data["tripId"] self.id = data["tripId"]
self.ctx_recon: str = data["ctxRecon"] self.ctx_recon = data["ctxRecon"]
self.duration: Union[Duration, timedelta, None] = ( self.duration = parse_duration(data["duration"])
None if "duration" not in data else parse_duration(data["duration"]) self.real_time_duration = (
)
self.real_time_duration: Union[Duration, timedelta, None] = (
None if "rtDuration" not in data else parse_duration(data["rtDuration"]) None if "rtDuration" not in data else parse_duration(data["rtDuration"])
) )
self.checksum: str = data["checksum"] self.checksum = data["checksum"]
self.transfer_count: int = data.get("transferCount", 0) self.transfer_count = data.get("transferCount", 0)
def __str__(self) -> str: def __str__(self) -> str:
return f"Trip from {self.origin.name} to {self.destination.name} lasting {self.duration} ({self.real_time_duration}) with {len(self.legs)} legs and {self.transfer_count} transfers" return f"Trip from {self.origin.name} to {self.destination.name} lasting {self.duration} ({self.real_time_duration}) with {len(self.legs)} legs and {self.transfer_count} transfers"

View File

@ -4,7 +4,6 @@ from .board_type import BoardArrivalType, BoardDepartureType
from .filter_mode import FilterMode from .filter_mode import FilterMode
from .lang import Language from .lang import Language
from .location_type import LocationType from .location_type import LocationType
from .platform_type_type import PlatformTypeType
from .product import Product from .product import Product
from .rt_mode import RealTimeMode from .rt_mode import RealTimeMode
from .search_mode import SearchMode from .search_mode import SearchMode

View File

@ -3,7 +3,7 @@
from enum import Enum from enum import Enum
from ..const import PRODUCTS from pyrmv.const import PRODUCTS
class AutoName(Enum): class AutoName(Enum):

View File

@ -1,51 +0,0 @@
from enum import Enum, auto
class PlatformTypeType(Enum):
"""Enumeration used to declare types of platform type.
* U - Undefined
* PL - Platform/track at train station
* ST - Stop at bus or tram station
* GA - Terminal/Gate at airport
* PI - Pier if ship or ferry
* SL - Slot/parking space if bike or car
* FL - Floor in buildings or at footpath
* CI - Check-in/entrance
* CO - Check-out/exit
* X - No explicit type
* H - Hide platform information
"""
U = auto()
"Undefined"
PL = auto()
"Platform/track at train station"
ST = auto()
"Stop at bus or tram station"
GA = auto()
"Terminal/Gate at airport"
PI = auto()
"Pier if ship or ferry"
SL = auto()
"Slot/parking space if bike or car"
FL = auto()
"Floor in buildings or at footpath"
CI = auto()
"Check-in/entrance"
CO = auto()
"Check-out/exit"
X = auto()
"No explicit type"
H = auto()
"Hide platform information"

View File

@ -1,7 +1,3 @@
import contextlib
import requests
from .board_arrival import board_arrival from .board_arrival import board_arrival
from .board_departure import board_departure from .board_departure import board_departure
from .him_search import him_search from .him_search import him_search
@ -10,8 +6,3 @@ from .stop_by_coords import stop_by_coords
from .stop_by_name import stop_by_name from .stop_by_name import stop_by_name
from .trip_find import trip_find from .trip_find import trip_find
from .trip_recon import trip_recon from .trip_recon import trip_recon
with contextlib.suppress(ImportError):
import ujson
requests.models.complexjson = ujson

View File

@ -40,22 +40,22 @@ def board_arrival(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True.
* id (str, *optional*): Access ID for identifying the requesting client. Defaults to None. * id (str, optional): Access ID for identifying the requesting client. Defaults to None.
* extId (str, *optional*): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None. * extId (str, optional): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None.
* direction (str, *optional*): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None. * direction (str, optional): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None.
* date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None. * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None.
* time (Union[str, datetime], *optional*): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. * time (Union[str, datetime], optional): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None.
* duration (int, *optional*): Set the interval size in minutes. Defaults to 60. * duration (int, optional): Set the interval size in minutes. Defaults to 60.
* maxJourneys (int, *optional*): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1. * maxJourneys (int, optional): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1.
* products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None.
* operators (Union[str, list], *optional*): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None. * operators (Union[str, list], optional): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None.
* lines (Union[str, list], *optional*): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * lines (Union[str, list], optional): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* filterEquiv (bool, *optional*): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True. * filterEquiv (bool, optional): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True.
* attributes (Union[str, list], *optional*): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None. * attributes (Union[str, list], optional): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None.
* platforms (Union[str, list], *optional*): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None. * platforms (Union[str, list], optional): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None.
* passlist (bool, *optional*): Include a list of all passed waystops. Defaults to False. * passlist (bool, optional): Include a list of all passed waystops. Defaults to False.
* boardType (Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"], *optional*): Set the station arrival board type to be used. ARR: Arrival board as configured in HAFAS; ARR_EQUIVS: Arrival board with all journeys at any masts and equivalent stops; ARR_MAST: Arrival board at mast; ARR_STATION: Arrival board with all journeys at any masts of the requested station. Defaults to "ARR". * boardType (Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"], optional): Set the station arrival board type to be used. ARR: Arrival board as configured in HAFAS; ARR_EQUIVS: Arrival board with all journeys at any masts and equivalent stops; ARR_MAST: Arrival board at mast; ARR_STATION: Arrival board with all journeys at any masts of the requested station. Defaults to "ARR".
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -64,7 +64,7 @@ def board_arrival(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "date": if str(var) == "date":
if val != None: if val != None:
if isinstance(val, datetime): if isinstance(val, datetime):

View File

@ -41,22 +41,22 @@ def board_departure(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True.
* id (str, *optional*): Access ID for identifying the requesting client. Defaults to None. * id (str, optional): Access ID for identifying the requesting client. Defaults to None.
* extId (str, *optional*): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None. * extId (str, optional): Deprecated. Please use id as it supports external IDs. Specifies the external station/stop ID for which the arrivals shall be retrieved. Required if id is not present. Such ID can be retrieved from the `stop_by_name` or `stop_by_coords`. Defaults to None.
* direction (str, *optional*): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None. * direction (str, optional): If only vehicles departing or arriving from a certain direction shall be returned, specify the direction by giving the station/stop ID of the last stop on the journey. Defaults to None.
* date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None. * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format YYYY-MM-DD. By default the current server date is used. Defaults to None.
* time (Union[str, datetime], *optional*): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. * time (Union[str, datetime], optional): Sets the start time for which the departures shall be retrieved. Represented in the format hh:mm[:ss] in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None.
* duration (int, *optional*): Set the interval size in minutes. Defaults to 60. * duration (int, optional): Set the interval size in minutes. Defaults to 60.
* maxJourneys (int, *optional*): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1. * maxJourneys (int, optional): Maximum number of journeys to be returned. If no value is defined or -1, all departing/arriving services within the duration sized period are returned. Defaults to -1.
* products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None.
* operators (Union[str, list], *optional*): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None. * operators (Union[str, list], optional): Only journeys provided by the given operators are part of the result. To filter multiple operators, separate the codes by comma. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=[A,B]`. Defaults to None.
* lines (Union[str, list], *optional*): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * lines (Union[str, list], optional): Only journeys running the given line are part of the result. To filter multiple lines, provide a list or separate the codes by comma. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* filterEquiv (bool, *optional*): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True. * filterEquiv (bool, optional): Use `boardType` instead. Enables/disables the filtering of equivalent marked stops. Defaults to True.
* attributes (Union[str, list], *optional*): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None. * attributes (Union[str, list], optional): Filter boards by one or more attribute codes of a journey. Multiple attribute as a list or as a string separated by comma. If the attribute should not be part of the result, negate it by putting ! in front of it. Defaults to None.
* platforms (Union[str, list], *optional*): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None. * platforms (Union[str, list], optional): Filter boards by platform. Multiple platforms provided as a list or as a string separated by comma. Defaults to None.
* passlist (bool, *optional*): Include a list of all passed waystops. Defaults to False. * passlist (bool, optional): Include a list of all passed waystops. Defaults to False.
* boardType (Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"], *optional*): Set the station departure board type to be used. DEP: Departure board as configured in HAFAS; DEP_EQUIVS: Departure board with all journeys at any masts and equivalent stops; DEP_MAST: Departure board at mast; DEP_STATION: Departure board with all journeys at any masts of the requested station. Defaults to "DEP". * boardType (Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"], optional): Set the station departure board type to be used. DEP: Departure board as configured in HAFAS; DEP_EQUIVS: Departure board with all journeys at any masts and equivalent stops; DEP_MAST: Departure board at mast; DEP_STATION: Departure board with all journeys at any masts of the requested station. Defaults to "DEP".
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -65,7 +65,7 @@ def board_departure(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "date": if str(var) == "date":
if val != None: if val != None:
if isinstance(val, datetime): if isinstance(val, datetime):

View File

@ -4,7 +4,7 @@ from typing import OrderedDict, Union
from requests import get from requests import get
from xmltodict import parse as xmlparse from xmltodict import parse as xmlparse
from ..utility import weekdays_bitmask from pyrmv.utility import weekdays_bitmask
try: try:
from typing import Literal from typing import Literal
@ -56,39 +56,39 @@ def him_search(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True.
* dateB (Union[str, datetime], *optional*): Sets the event period start date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. * dateB (Union[str, datetime], optional): Sets the event period start date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None.
* dateE (Union[str, datetime], *optional*): Sets the event period end date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. * dateE (Union[str, datetime], optional): Sets the event period end date. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None.
* timeB (Union[str, datetime], *optional*): Sets the event period start time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. * timeB (Union[str, datetime], optional): Sets the event period start time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None.
* timeE (Union[str, datetime], *optional*): Sets the event period end time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. * timeE (Union[str, datetime], optional): Sets the event period end time. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None.
* weekdays (Union[str, OrderedDict[str, bool]], *optional*): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to None. * weekdays (Union[str, OrderedDict[str, bool]], optional): Bitmask or an OrderedDict for validity of HIM messages based on weekdays. OrderedDict must be formatted as follows: `OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)`. Each character of a bitmask represents a weekday starting on monday. Example: Only find HIM Messages valid from monday to friday: `1111100`. Defaults to None.
* himIds (Union[str, list], *optional*): List of HIM message IDs as a list or as a string separated by comma. Defaults to None. * himIds (Union[str, list], optional): List of HIM message IDs as a list or as a string separated by comma. Defaults to None.
* hierarchicalView (bool, *optional*): Return parent messages with childs. Defaults to False. * hierarchicalView (bool, optional): Return parent messages with childs. Defaults to False.
* operators (Union[str, list], *optional*): List of operators as a list or as a string separated by comma. Defaults to None. * operators (Union[str, list], optional): List of operators as a list or as a string separated by comma. Defaults to None.
* categories (Union[str, list], *optional*): List of train categories as a list or as a string separated by comma. Defaults to None. * categories (Union[str, list], optional): List of train categories as a list or as a string separated by comma. Defaults to None.
* channels (Union[str, list], *optional*): List of channels as a list or as a string separated by comma. Defaults to None. * channels (Union[str, list], optional): List of channels as a list or as a string separated by comma. Defaults to None.
* companies (Union[str, list], *optional*): List of companies as a list or as a string separated by comma. Defaults to None. * companies (Union[str, list], optional): List of companies as a list or as a string separated by comma. Defaults to None.
* lines (Union[str, list], *optional*): Only HIM messages for the given line are part of the result. To filter multiple lines, separate the codes by comma. Defaults to None. * lines (Union[str, list], optional): Only HIM messages for the given line are part of the result. To filter multiple lines, separate the codes by comma. Defaults to None.
* lineids (Union[str, list], *optional*): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, separate the line IDs by comma. Defaults to None. * lineids (Union[str, list], optional): Only HIM messages for the given line (identified by its line ID) are part of the result. To filter multiple lines, separate the line IDs by comma. Defaults to None.
* stations (Union[str, list], *optional*): List of (external) station ids to be filtered for as a list or as a string separated by comma. Defaults to None. * stations (Union[str, list], optional): List of (external) station ids to be filtered for as a list or as a string separated by comma. Defaults to None.
* fromstation (str, *optional*): Filter messages by line segment starting at this station given as (external) station id. Defaults to None. * fromstation (str, optional): Filter messages by line segment starting at this station given as (external) station id. Defaults to None.
* tostation (str, *optional*): Filter messages by line segment travelling in direction of this station given as (external) station id. Defaults to None. * tostation (str, optional): Filter messages by line segment travelling in direction of this station given as (external) station id. Defaults to None.
* bothways (bool, *optional*): If enabled, messages in both directions - from 'fromstation' to 'tostation' as well as from 'tostation' to 'fromstation' are returned. Defaults to None. * bothways (bool, optional): If enabled, messages in both directions - from 'fromstation' to 'tostation' as well as from 'tostation' to 'fromstation' are returned. Defaults to None.
* trainnames (Union[str, list], *optional*): List of train name to be filtered for as a list or as a string separated by comma. Defaults to None. * trainnames (Union[str, list], optional): List of train name to be filtered for as a list or as a string separated by comma. Defaults to None.
* metas (Union[str, list], *optional*): List of predefined filters as a list or as a string separated by comma. Defaults to None. * metas (Union[str, list], optional): List of predefined filters as a list or as a string separated by comma. Defaults to None.
* himcategory (str, *optional*): HIM category, e.g. Works and/or Disturbance. Value depends on your HAFAS server data. Defaults to None. * himcategory (str, optional): HIM category, e.g. Works and/or Disturbance. Value depends on your HAFAS server data. Defaults to None.
* himtags (Union[str, list], *optional*): HIM Tags. Value depends on your HAFAS server data. Return HIM messages having these tag(s) only. Multiple values are separated by comma. Note: HIM tags differ from HIM text tags. Defaults to None. * himtags (Union[str, list], optional): HIM Tags. Value depends on your HAFAS server data. Return HIM messages having these tag(s) only. Multiple values are separated by comma. Note: HIM tags differ from HIM text tags. Defaults to None.
* regions (Union[str, list], *optional*): Filter for HIM messages based on regions defined in HAFAS raw data. As a list or as a string separated by comma. Available regions can be retrieved by /datainfo service. Defaults to None. * regions (Union[str, list], optional): Filter for HIM messages based on regions defined in HAFAS raw data. As a list or as a string separated by comma. Available regions can be retrieved by /datainfo service. Defaults to None.
* himtext (Union[str, list], *optional*): Filter for HIM messages containing the given free text message as a list or as a string separated by comma. Defaults to None. * himtext (Union[str, list], optional): Filter for HIM messages containing the given free text message as a list or as a string separated by comma. Defaults to None.
* himtexttags (Union[str, list], *optional*): Return HIM texts having this text tag(s) only. Multiple values are separated by comma. Note: HIM text tags differ from HIM tags. Defaults to None. * himtexttags (Union[str, list], optional): Return HIM texts having this text tag(s) only. Multiple values are separated by comma. Note: HIM text tags differ from HIM tags. Defaults to None.
* additionalfields (Union[str, list, dict], *optional*): List of additional fields and values to be filtered for. Two filter options are available: Filter by key only: `additionalfields=key` or filter by key and value: `additionalfields={key:value}`. Multiple filters are separated by comma like `additionalfields=[keyA,keyB]` or `additionalfields={key:value}`. Defaults to None. * additionalfields (Union[str, list, dict], optional): List of additional fields and values to be filtered for. Two filter options are available: Filter by key only: `additionalfields=key` or filter by key and value: `additionalfields={key:value}`. Multiple filters are separated by comma like `additionalfields=[keyA,keyB]` or `additionalfields={key:value}`. Defaults to None.
* poly (bool, *optional*): Enables/disables returning of geo information for affected edges and regions if available and enabled in the backend. Defaults to False. * poly (bool, optional): Enables/disables returning of geo information for affected edges and regions if available and enabled in the backend. Defaults to False.
* searchmode (Literal["MATCH", "NOMATCH", "TFMATCH"], *optional*): HIM search mode. `"NOMATCH"` iterate over all HIM messages available. `"MATCH"` iterate over all trips to find HIM messages. `"TFMATCH"` uses filters defined `metas` parameter. Defaults to None. * searchmode (Literal["MATCH", "NOMATCH", "TFMATCH"], optional): HIM search mode. `"NOMATCH"` iterate over all HIM messages available. `"MATCH"` iterate over all trips to find HIM messages. `"TFMATCH"` uses filters defined `metas` parameter. Defaults to None.
* affectedJourneyMode (Literal["ALL", "OFF"], *optional*): Define how to return affected journeys `"OFF"`: do not return affected journeys. `"ALL"`: return affected journeys. Defaults to None. * affectedJourneyMode (Literal["ALL", "OFF"], optional): Define how to return affected journeys `"OFF"`: do not return affected journeys. `"ALL"`: return affected journeys. Defaults to None.
* affectedJourneyStopMode (Literal["ALL", "IMP", "OFF"], *optional*): Define how to return stops of affected journeys. `"IMP"`: return important stops of affected journeys. `"OFF"`: do not return stops of affected journeys. `"ALL"`: return all affected stops of affected journeys. Defaults to None. * affectedJourneyStopMode (Literal["ALL", "IMP", "OFF"], optional): Define how to return stops of affected journeys. `"IMP"`: return important stops of affected journeys. `"OFF"`: do not return stops of affected journeys. `"ALL"`: return all affected stops of affected journeys. Defaults to None.
* orderBy (Union[str, list], *optional*): Define the Order the returned messages by fields and directions. Multiple, string comma separated or list entries are supported. Read more about this in HAFAS ReST Documentation. Defaults to None. * orderBy (Union[str, list], optional): Define the Order the returned messages by fields and directions. Multiple, string comma separated or list entries are supported. Read more about this in HAFAS ReST Documentation. Defaults to None.
* minprio (Union[str, int], *optional*): Filter for HIM messages having at least this priority. Defaults to None. * minprio (Union[str, int], optional): Filter for HIM messages having at least this priority. Defaults to None.
* maxprio (Union[str, int], *optional*): Filter for HIM messages having this priority as maximum. Defaults to None. * maxprio (Union[str, int], optional): Filter for HIM messages having this priority as maximum. Defaults to None.
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -97,7 +97,7 @@ def him_search(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) in {"dateB", "dateE"}: if str(var) in {"dateB", "dateE"}:
if val != None: if val != None:
if isinstance(val, datetime): if isinstance(val, datetime):

View File

@ -36,17 +36,17 @@ def journey_detail(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* id (str): Specifies the internal journey id of the journey shall be retrieved. Maximum length 512. * id (str): Specifies the internal journey id of the journey shall be retrieved. Maximum length 512.
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True.
* date (Union[str, datetime], *optional*): Day of operation. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. * date (Union[str, datetime], optional): Day of operation. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None.
* poly (bool, *optional*): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. * poly (bool, optional): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False.
* polyEnc (Literal["DLT", "GPA", "N"], *optional*): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". * polyEnc (Literal["DLT", "GPA", "N"], optional): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N".
* showPassingPoints (bool, *optional*): Enables/disables the return of stops having no alighting and no boarding in its passlist for each leg of the trip. Defaults to False. * showPassingPoints (bool, optional): Enables/disables the return of stops having no alighting and no boarding in its passlist for each leg of the trip. Defaults to False.
* rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], *optional*): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], optional): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None.
* fromId (str, *optional*): Specifies the station/stop ID the partial itinerary shall start from. Defaults to None. * fromId (str, optional): Specifies the station/stop ID the partial itinerary shall start from. Defaults to None.
* fromIdx (str, *optional*): Specifies the station/stop index the partial itinerary shall start from. Defaults to None. * fromIdx (str, optional): Specifies the station/stop index the partial itinerary shall start from. Defaults to None.
* toId (str, *optional*): Specifies the station/stop ID the partial itinerary shall end at. Defaults to None. * toId (str, optional): Specifies the station/stop ID the partial itinerary shall end at. Defaults to None.
* toIdx (str, *optional*): Specifies the station/stop index the partial itinerary shall end at. Defaults to None. * toIdx (str, optional): Specifies the station/stop index the partial itinerary shall end at. Defaults to None.
* baim (bool, *optional*): Enables/disables BAIM search and response. Defaults to False. * baim (bool, optional): Enables/disables BAIM search and response. Defaults to False.
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -55,7 +55,7 @@ def journey_detail(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "rtMode": if str(var) == "rtMode":
if val != None: if val != None:
payload["rtMode"] = val.upper() payload["rtMode"] = val.upper()

View File

@ -36,16 +36,16 @@ def stop_by_coords(
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* originCoordLat (Union[str, float]): Latitude of centre coordinate. * originCoordLat (Union[str, float]): Latitude of centre coordinate.
* originCoordLong (Union[str, float]): Longitude of centre coordinate. * originCoordLong (Union[str, float]): Longitude of centre coordinate.
* lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], *optional*): The language of response. Defaults to "en". * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], optional): The language of response. Defaults to "en".
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True.
* radius (Union[int, float], *optional*): Search radius in meter around the given coordinate if any. Defaults to 1000. * radius (Union[int, float], optional): Search radius in meter around the given coordinate if any. Defaults to 1000.
* maxNo (int, *optional*): Maximum number of returned stops. Defaults to 10. * maxNo (int, optional): Maximum number of returned stops. Defaults to 10.
* stopType (Literal["S", "P", "SP", "SE", "SPE"], *optional*): Type filter for location types. Defaults to "S". * stopType (Literal["S", "P", "SP", "SE", "SPE"], optional): Type filter for location types. Defaults to "S".
* locationSelectionMode (Literal["SLCT_N", "SLCT_A"], *optional*): Selection mode for locations. Defaults to None. * locationSelectionMode (Literal["SLCT_N", "SLCT_A"], optional): Selection mode for locations. Defaults to None.
* products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None.
* meta (str, *optional*): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None. * meta (str, optional): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None.
* sattributes (Union[str, list], *optional*): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None. * sattributes (Union[str, list], optional): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None.
* sinfotexts (Union[str, list], *optional*): Filter locations by one or more station infotext codes and values. Multiple attribute codes are separated by comma the value by pipe |. Defaults to None. * sinfotexts (Union[str, list], optional): Filter locations by one or more station infotext codes and values. Multiple attribute codes are separated by comma the value by pipe |. Defaults to None.
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -54,7 +54,7 @@ def stop_by_coords(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "stopType": if str(var) == "stopType":
if val != None: if val != None:
payload["type"] = val.upper() payload["type"] = val.upper()

View File

@ -43,20 +43,20 @@ def stop_by_name(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* inputString (str): Search for that token. * inputString (str): Search for that token.
* lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], *optional*): The language of response. Defaults to "en". * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], optional): The language of response. Defaults to "en".
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Only matters if raw_response is True. Defaults to True.
* maxNo (int, *optional*): Maximum number of returned stops. In range 1-1000. Defaults to 10. * maxNo (int, optional): Maximum number of returned stops. In range 1-1000. Defaults to 10.
* stopType (Literal["A", "ALL", "AP", "P", "S", "SA", "SP"], *optional*): Type filter for location types. Defaults to "ALL". * stopType (Literal["A", "ALL", "AP", "P", "S", "SA", "SP"], optional): Type filter for location types. Defaults to "ALL".
* locationSelectionMode (str, *optional*): Selection mode for locations. "SLCT_N": Not selectable, "SLCT_A": Selectable. Defaults to None. * locationSelectionMode (str, optional): Selection mode for locations. "SLCT_N": Not selectable, "SLCT_A": Selectable. Defaults to None.
* products (int, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. * products (int, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None.
* coordLat (Union[str, float], *optional*): Latitude of centre coordinate. Defaults to None. * coordLat (Union[str, float], optional): Latitude of centre coordinate. Defaults to None.
* coordLong (Union[str, float], *optional*): Longitude of centre coordinate. Defaults to None. * coordLong (Union[str, float], optional): Longitude of centre coordinate. Defaults to None.
* radius (Union[int, float], *optional*): Search radius in meter around the given coordinate if any. Defaults to 1000. * radius (Union[int, float], optional): Search radius in meter around the given coordinate if any. Defaults to 1000.
* refineId (str, *optional*): In case of an refinable location, this value takes the ID of the refinable one of a previous result. Defaults to None. * refineId (str, optional): In case of an refinable location, this value takes the ID of the refinable one of a previous result. Defaults to None.
* meta (str, *optional*): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None. * meta (str, optional): Filter by a predefined meta filter. If the rules of the predefined filter should not be negated, put ! in front of it. Defaults to None.
* stations (Union[str, list], *optional*): Filter for stations. Matches if the given value is prefix of any station in the itinerary. Multiple values are separated by comma. Defaults to None. * stations (Union[str, list], optional): Filter for stations. Matches if the given value is prefix of any station in the itinerary. Multiple values are separated by comma. Defaults to None.
* sattributes (Union[str, list], *optional*): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None. * sattributes (Union[str, list], optional): Filter locations by one or more attribute codes. Multiple attribute codes are separated by comma. If the attribute should not be part of the be location data, negate it by putting ! in front of it. Defaults to None.
* filterMode (Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"], *optional*): Filter modes for nearby searches. Defaults to "DIST_PERI". * filterMode (Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"], optional): Filter modes for nearby searches. Defaults to "DIST_PERI".
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -65,7 +65,7 @@ def stop_by_name(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "inputString": if str(var) == "inputString":
if val != None: if val != None:
payload["input"] = val payload["input"] = val

View File

@ -109,90 +109,90 @@ def trip_find(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], *optional*): The language of response. Defaults to "en". * lang (Literal["de","da","en","es","fr","hu","it","nl","no","pl","sv","tr"], optional): The language of response. Defaults to "en".
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True.
* originId (str, *optional*): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. * originId (str, optional): Specifies the station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* originExtId (str, *optional*): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. * originExtId (str, optional): Deprecated. Please use originId as it supports external IDs. Specifies the external station/stop ID of the origin for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* originCoordLat (Union[str, float], *optional*): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. * originCoordLat (Union[str, float], optional): Latitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* originCoordLong (Union[str, float], *optional*): Longitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. * originCoordLong (Union[str, float], optional): Longitude of station/stop coordinate of the trip's origin. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* originCoordName (str, *optional*): Name of the trip's origin if coordinate cannot be resolved to an address or poi. Defaults to None. * originCoordName (str, optional): Name of the trip's origin if coordinate cannot be resolved to an address or poi. Defaults to None.
* destId (str, *optional*): Specifies the station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. * destId (str, optional): Specifies the station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* destExtId (str, *optional*): Deprecated. Please use destId as it supports external IDs. Specifies the external station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None. * destExtId (str, optional): Deprecated. Please use destId as it supports external IDs. Specifies the external station/stop ID of the destination for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* destCoordLat (Union[str, float], *optional*): Latitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. * destCoordLat (Union[str, float], optional): Latitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* destCoordLong (Union[str, float], *optional*): Longitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None. * destCoordLong (Union[str, float], optional): Longitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stopByName() or stopByCoords(). Defaults to None.
* destCoordName (str, *optional*): Name of the trip's destination if coordinate cannot be resolved to an address or poi. Defaults to None. * destCoordName (str, optional): Name of the trip's destination if coordinate cannot be resolved to an address or poi. Defaults to None.
* via (str, *optional*): Complex structure to provide multiple via points separated by semicolon. This structure is build like this: `viaId|waittime|viastatus|products|direct|sleepingCar|couchetteCoach|attributes`. Read more about this in HAFAS ReST Documentation. Defaults to None. * via (str, optional): Complex structure to provide multiple via points separated by semicolon. This structure is build like this: `viaId|waittime|viastatus|products|direct|sleepingCar|couchetteCoach|attributes`. Read more about this in HAFAS ReST Documentation. Defaults to None.
* viaId (str, *optional*): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stopByName() or stopByCoords(). If `via` is used, `viaId` and `viaWaitTime ` are having no effect. Defaults to None. * viaId (str, optional): ID of a station/stop used as a via for the trip. Specifying a via station forces the trip search to look for trips which must pass through this station. Such ID can be retrieved from stopByName() or stopByCoords(). If `via` is used, `viaId` and `viaWaitTime ` are having no effect. Defaults to None.
* viaWaitTime (int, *optional*): Defines the waiting time spent at via station in minutes. If `via` is used, `viaId` and `viaWaitTime` are having no effect. Defaults to 0. * viaWaitTime (int, optional): Defines the waiting time spent at via station in minutes. If `via` is used, `viaId` and `viaWaitTime` are having no effect. Defaults to 0.
* avoid (str, *optional*): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), *optional* but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to None. * avoid (str, optional): Complex structure to provide multiple points to be avoided separated by semicolon. This structure is build like this: `avoidId|avoidstatus` avoidId: id, extId or altId of the avoid, mandatory avoidstatus: one of NPAVM (do not run through if this is a meta station), NPAVO (do not run through), NCAVM (do not change if this is a meta station), NCAVO (do not change), optional but defaults to NCAVM Example: Just define three avoids by extId: `avoid="801234;801235;801236"`. Defaults to None.
* avoidId (str, *optional*): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). If `avoid` is used, `avoidId` has no effect. Defaults to None. * avoidId (str, optional): ID of a station/stop to be avoided as transfer stop for the trip. Such ID can be retrieved from stopByName() or stopByCoords(). If `avoid` is used, `avoidId` has no effect. Defaults to None.
* viaGis (str, *optional*): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to None. * viaGis (str, optional): Complex structure to provide multiple GIS via locations separated by semicolon. This structure is build like this: `locationId|locationMode|transportMode|placeType|usageType|mode|durationOfStay`. Read more about this in HAFAS ReST Documentation. Defaults to None.
* changeTimePercent (int, *optional*): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to 100. * changeTimePercent (int, optional): Configures the walking speed when changing from one leg of the journey to the next one. It extends the time required for changes by a specified percentage. A value of 200 doubles the change time as initially calculated by the system. In the response, change time is presented in full minutes. If the calculation based on changeTime-Percent does not result in a full minute, it is rounded using "round half up" method. Defaults to 100.
* minChangeTime (int, *optional*): Minimum change time at stop in minutes. Defaults to None. * minChangeTime (int, optional): Minimum change time at stop in minutes. Defaults to None.
* maxChangeTime (int, *optional*): Maximum change time at stop in minutes. Defaults to None. * maxChangeTime (int, optional): Maximum change time at stop in minutes. Defaults to None.
* addChangeTime (int, *optional*): This amount of minutes is added to the change time at each stop. Defaults to None. * addChangeTime (int, optional): This amount of minutes is added to the change time at each stop. Defaults to None.
* maxChange (int, *optional*): Maximum number of changes. In range 0-11. Defaults to None. * maxChange (int, optional): Maximum number of changes. In range 0-11. Defaults to None.
* date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None. * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. By default the current server date is used. Defaults to None.
* time (Union[str, datetime], *optional*): Sets the start time for which the departures shall be retrieved. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None. * time (Union[str, datetime], optional): Sets the start time for which the departures shall be retrieved. Represented in the format `hh:mm[:ss]` in 24h nomenclature. Seconds will be ignored for requests. By default the current server time is used. Defaults to None.
* searchForArrival (bool, *optional*): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to False. * searchForArrival (bool, optional): If set, the date and time parameters specify the arrival time for the trip search instead of the departure time. Defaults to False.
* numF (int, *optional*): Minimum number of trips after the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to None. * numF (int, optional): Minimum number of trips after the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 1-6. Defaults to None.
* numB (int, *optional*): Minimum number of trips before the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to None. * numB (int, optional): Minimum number of trips before the search time. Sum of numF and numB has to be less or equal 6. Read more about this in HAFAS ReST Documentation. In range 0-6. Defaults to None.
* context (str, *optional*): Defines the starting point for the scroll back or forth operation. Use the scrB value from a previous result to scroll backwards in time and use the scrF value to scroll forth. Defaults to None. * context (str, optional): Defines the starting point for the scroll back or forth operation. Use the scrB value from a previous result to scroll backwards in time and use the scrF value to scroll forth. Defaults to None.
* poly (bool, *optional*): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. * poly (bool, optional): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False.
* polyEnc (Literal["DLT", "GPA", "N"], *optional*): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". * polyEnc (Literal["DLT", "GPA", "N"], optional): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N".
* passlist (bool, *optional*): Enables/disables the return of the passlist for each leg of the trip. Defaults to False. * passlist (bool, optional): Enables/disables the return of the passlist for each leg of the trip. Defaults to False.
* products (str, *optional*): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None. * products (str, optional): Decimal value defining the product classes to be included in the search. It represents a bitmask combining bit number of a product as defined in the HAFAS raw data. Defaults to None.
* operators (Union[str, list], *optional*): Only trips provided by the given operators are part of the result. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=["A","B"]`. Defaults to None. * operators (Union[str, list], optional): Only trips provided by the given operators are part of the result. If the operator should not be part of the be trip, negate it by putting ! in front of it. Example: Filter for operator A and B: `operators=["A","B"]`. Defaults to None.
* attributes (Union[str, list], *optional*): Filter trips by one or more attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * attributes (Union[str, list], optional): Filter trips by one or more attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* sattributes (Union[str, list], *optional*): Filter trips by one or more station attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * sattributes (Union[str, list], optional): Filter trips by one or more station attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* fattributes (Union[str, list], *optional*): Filter trips by one or more footway attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * fattributes (Union[str, list], optional): Filter trips by one or more footway attribute codes of a journey. If the attribute should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* lines (Union[str, list], *optional*): Only journeys running the given line are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * lines (Union[str, list], optional): Only journeys running the given line are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* lineids (Union[str, list], *optional*): Only journeys running the given line (identified by its line ID) are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None. * lineids (Union[str, list], optional): Only journeys running the given line (identified by its line ID) are part of the result. If the line should not be part of the be trip, negate it by putting ! in front of it. Defaults to None.
* avoidPaths (List[Literal["SW", "EA", "ES", "RA", "CB"]], *optional*): Only path not having the given properties will be part of the result. "SW": Stairway; "EA": Elevator; "ES": Escalator; "RA": Ramp; "CB": Convey Belt. Example: Use paths without ramp and stairway: `avoidPaths="SW", "RA"`. Defaults to None. * avoidPaths (List[Literal["SW", "EA", "ES", "RA", "CB"]], optional): Only path not having the given properties will be part of the result. "SW": Stairway; "EA": Elevator; "ES": Escalator; "RA": Ramp; "CB": Convey Belt. Example: Use paths without ramp and stairway: `avoidPaths="SW", "RA"`. Defaults to None.
* originWalk (Union[str, list], *optional*): Enables/disables using footpaths in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * originWalk (Union[str, list], optional): Enables/disables using footpaths in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* originBike (Union[str, list], *optional*): Enables/disables using bike routes in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station or mode change point, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * originBike (Union[str, list], optional): Enables/disables using bike routes in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station or mode change point, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* originCar (Union[str, list], *optional*): Enables/disables using car in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * originCar (Union[str, list], optional): Enables/disables using car in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* originTaxi (Union[str, list], *optional*): Enables/disables using taxi rides in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * originTaxi (Union[str, list], optional): Enables/disables using taxi rides in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* originPark (Union[str, list], *optional*): Enables/disables using Park and Ride in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * originPark (Union[str, list], optional): Enables/disables using Park and Ride in the beginning of a trip when searching from an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* originMeta (Union[str, list], *optional*): Enables using one or more predefined individual transport meta profile at the beginning of a trip. Defaults to None. * originMeta (Union[str, list], optional): Enables using one or more predefined individual transport meta profile at the beginning of a trip. Defaults to None.
* destWalk (Union[str, list], *optional*): Enables/disables using footpaths at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * destWalk (Union[str, list], optional): Enables/disables using footpaths at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* destBike (Union[str, list], *optional*): Enables/disables using bike routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * destBike (Union[str, list], optional): Enables/disables using bike routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* destCar (Union[str, list], *optional*): Enables/disables using car routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * destCar (Union[str, list], optional): Enables/disables using car routes at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* destTaxi (Union[str, list], *optional*): Enables/disables using taxi rides at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * destTaxi (Union[str, list], optional): Enables/disables using taxi rides at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* destPark (Union[str, list], *optional*): Enables/disables using Park and Ride at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * destPark (Union[str, list], optional): Enables/disables using Park and Ride at the end of a trip when searching to an address. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* destMeta (Union[str, list], *optional*): Enables using one or more predefined individual transport meta profile at the end of a trip. Defaults to None. * destMeta (Union[str, list], optional): Enables using one or more predefined individual transport meta profile at the end of a trip. Defaults to None.
* totalWalk (Union[str, list], *optional*): Enables/disables using footpaths for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * totalWalk (Union[str, list], optional): Enables/disables using footpaths for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* totalBike (Union[str, list], *optional*): Enables/disables using bike routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * totalBike (Union[str, list], optional): Enables/disables using bike routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* totalCar (Union[str, list], *optional*): Enables/disables using car routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * totalCar (Union[str, list], optional): Enables/disables using car routes for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* totalTaxi (Union[str, list], *optional*): Enables/disables using taxi rides for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None. * totalTaxi (Union[str, list], optional): Enables/disables using taxi rides for the whole trip. To fine-tune the minimum and/or maximum distance to the next public transport station, provide these values as a list or as a string separated by comma. These values are expressed in meters. Read more about this in HAFAS ReST Documentation. Defaults to None.
* totalMeta (Union[str, list], *optional*): Enables using one or more predefined individual transport meta profile for a trip. Defaults to None. * totalMeta (Union[str, list], optional): Enables using one or more predefined individual transport meta profile for a trip. Defaults to None.
* gisProducts (str, *optional*): Filter on GIS product, e.g. specific sharing provider. Currently, only exclusion of certain providers is available by adding ! in front of the provider meta code. Defaults to None. * gisProducts (str, optional): Filter on GIS product, e.g. specific sharing provider. Currently, only exclusion of certain providers is available by adding ! in front of the provider meta code. Defaults to None.
* includeIv (bool, *optional*): Enables/disables search for individual transport routes. Defaults to False. * includeIv (bool, optional): Enables/disables search for individual transport routes. Defaults to False.
* ivOnly (bool, *optional*): Enables/disables search for individual transport routes only. Defaults to False. * ivOnly (bool, optional): Enables/disables search for individual transport routes only. Defaults to False.
* mobilityProfile (str, *optional*): Use a predefined filter by its name. The filters are defined in the HAFAS installation. If the filter should be negated, put a ! in front of its name. Defaults to None. * mobilityProfile (str, optional): Use a predefined filter by its name. The filters are defined in the HAFAS installation. If the filter should be negated, put a ! in front of its name. Defaults to None.
* bikeCarriage (bool, *optional*): Enables/disables search for trips explicit allowing bike carriage. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. * bikeCarriage (bool, optional): Enables/disables search for trips explicit allowing bike carriage. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False.
* bikeCarriageType (Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], *optional*): Filter for a specific bike carriage type. Defaults to None. * bikeCarriageType (Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], optional): Filter for a specific bike carriage type. Defaults to None.
* sleepingCar (bool, *optional*): Enables/disables search for trips having sleeping car. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. * sleepingCar (bool, optional): Enables/disables search for trips having sleeping car. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False.
* couchetteCoach (bool, *optional*): Enables/disables search for trips having couchette coach. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False. * couchetteCoach (bool, optional): Enables/disables search for trips having couchette coach. This will only work in combination with `maxChange=0` as those trips are always meant to be direct connections. Defaults to False.
* showPassingPoints (bool, *optional*): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist enabled. Defaults to False. * showPassingPoints (bool, optional): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist enabled. Defaults to False.
* baim (bool, *optional*): Enables/disables BAIM search and response. Defaults to False. * baim (bool, optional): Enables/disables BAIM search and response. Defaults to False.
* eco (bool, *optional*): Enables/disables eco value calculation. Defaults to False. * eco (bool, optional): Enables/disables eco value calculation. Defaults to False.
* ecoCmp (bool, *optional*): Enables/disables eco comparison. Defaults to False. * ecoCmp (bool, optional): Enables/disables eco comparison. Defaults to False.
* ecoParams (str, *optional*): Provide additional eco parameters. Defaults to None. * ecoParams (str, optional): Provide additional eco parameters. Defaults to None.
* rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], *optional*): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], optional): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None.
* unsharp (bool, *optional*): Enables/disables unsharp search mode. Read more about this in section 2.12.2.1. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False. * unsharp (bool, optional): Enables/disables unsharp search mode. Read more about this in section 2.12.2.1. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False.
* trainFilter (str, *optional*): Filters a trip search for a certain train. First hit will be taken. Defaults to None. * trainFilter (str, optional): Filters a trip search for a certain train. First hit will be taken. Defaults to None.
* economic (bool, *optional*): Enables/disables economic search mode. Read more about this in section 2.12.2.2. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False. * economic (bool, optional): Enables/disables economic search mode. Read more about this in section 2.12.2.2. "Trip Search (trip)" of HAFAS ReST Documentation. Defaults to False.
* groupFilter (str, *optional*): Use a predefined group filter to query for certain modes. Defaults to None. * groupFilter (str, optional): Use a predefined group filter to query for certain modes. Defaults to None.
* blockingList (str, *optional*): Defines a section of a route of a journey not to be used within the trip search. Each route section is defined by a tuple of the following style: `<train name>|<departure id>|<arrival id>|<departure time>|<arrival time>|<departure date>|<arrival date>` A set of tuples can be separated by semicolon. Defaults to None. * blockingList (str, optional): Defines a section of a route of a journey not to be used within the trip search. Each route section is defined by a tuple of the following style: `<train name>|<departure id>|<arrival id>|<departure time>|<arrival time>|<departure date>|<arrival date>` A set of tuples can be separated by semicolon. Defaults to None.
* blockedEdges (str, *optional*): List of edges within the public transport network that should be excluded from the result. Each edge is defined by a tuple of the following style: `start location ID|end locationID|bidirectional|blockOnlyIfInOutAllowed` A set of tuples can be separated by semicolon. Defaults to None. * blockedEdges (str, optional): List of edges within the public transport network that should be excluded from the result. Each edge is defined by a tuple of the following style: `start location ID|end locationID|bidirectional|blockOnlyIfInOutAllowed` A set of tuples can be separated by semicolon. Defaults to None.
* trainComposition (bool, *optional*): Enables/disables train composition data. Defaults to False. * trainComposition (bool, optional): Enables/disables train composition data. Defaults to False.
* includeEarlier (bool, *optional*): Disables search optimization in relation of duration. Defaults to False. * includeEarlier (bool, optional): Disables search optimization in relation of duration. Defaults to False.
* withICTAlternatives (bool, *optional*): Enables/disables the search for alternatives with individualized change times (ICT). Defaults to False. * withICTAlternatives (bool, optional): Enables/disables the search for alternatives with individualized change times (ICT). Defaults to False.
* tariff (bool, *optional*): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None. * tariff (bool, optional): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None.
* trafficMessages (bool, *optional*): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to False. * trafficMessages (bool, optional): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to False.
* travellerProfileData (str, *optional*): Traveller profile data. Structure depends on set up. Defaults to None. * travellerProfileData (str, optional): Traveller profile data. Structure depends on set up. Defaults to None.
* withFreq (bool, *optional*): Enables/disables the calculation of frequency information. Defaults to True. * withFreq (bool, optional): Enables/disables the calculation of frequency information. Defaults to True.
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -201,7 +201,7 @@ def trip_find(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "date": if str(var) == "date":
if val != None: if val != None:
if isinstance(val, datetime): if isinstance(val, datetime):

View File

@ -51,34 +51,34 @@ def trip_recon(
### Args: ### Args:
* accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html). * accessId (str): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
* ctx (str): Specifies the reconstruction context. * ctx (str): Specifies the reconstruction context.
* json (bool, *optional*): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True. * json (bool, optional): Whether response should be retrieved as JSON. XML is returned if False. Defaults to True.
* poly (bool, *optional*): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False. * poly (bool, optional): Enables/disables the calculation of the polyline for each leg of the trip except any GIS route. Defaults to False.
* polyEnc (Literal["DLT", "GPA", "N"], *optional*): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N". * polyEnc (Literal["DLT", "GPA", "N"], optional): Defines encoding of the returned polyline. Possible values are "N" (no encoding / compression), "DLT" (delta to the previous coordinate), "GPA" (Google encoded polyline format). Defaults to "N".
* date (Union[str, datetime], *optional*): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. This parameter will force the ser-vice to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, the error code SVC_NO_RESULT will be returned. Defaults to None. * date (Union[str, datetime], optional): Sets the start date for which the departures shall be retrieved. Represented in the format `YYYY-MM-DD`. This parameter will force the ser-vice to reconstruct the trip on that specific date. If the trip is not available on that date, because it does not operate, the error code SVC_NO_RESULT will be returned. Defaults to None.
* useCombinedComparison (bool, *optional*): Compare based on combined output name - `False`: Compare parameters (category, line, train number) individually. Defaults to None. * useCombinedComparison (bool, optional): Compare based on combined output name - `False`: Compare parameters (category, line, train number) individually. Defaults to None.
* acceptGaps (bool, *optional*): Accept an incomplete description of the connection (with gaps) i.e. missing walks/transfers. Defaults to None. * acceptGaps (bool, optional): Accept an incomplete description of the connection (with gaps) i.e. missing walks/transfers. Defaults to None.
* allowDummySections (bool, *optional*): Allow a partial reconstruction that will not lead to a reconstruction failure if sections are not reconstructable. Instead, for theses inconstructable sections, dummy sections will be created in the result. Defaults to None. * allowDummySections (bool, optional): Allow a partial reconstruction that will not lead to a reconstruction failure if sections are not reconstructable. Instead, for theses inconstructable sections, dummy sections will be created in the result. Defaults to None.
* flagAllNonReachable (bool, *optional*): Should all non-reachable journeys be flagged (`True`), or only the first one encountered? Defaults to None. * flagAllNonReachable (bool, optional): Should all non-reachable journeys be flagged (`True`), or only the first one encountered? Defaults to None.
* matchCatStrict (bool, *optional*): Should the category (Gattung) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None. * matchCatStrict (bool, optional): Should the category (Gattung) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None.
* matchIdNonBlank (bool, *optional*): Should the train identifier (Zugbezeichner) without whitespace match? Defaults to None. * matchIdNonBlank (bool, optional): Should the train identifier (Zugbezeichner) without whitespace match? Defaults to None.
* matchIdStrict (bool, *optional*): Should the train identifier (Zugbezeichner) match exactly? Defaults to None. * matchIdStrict (bool, optional): Should the train identifier (Zugbezeichner) match exactly? Defaults to None.
* matchNumStrict (bool, *optional*): Should the train number (Zugnummer) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None. * matchNumStrict (bool, optional): Should the train number (Zugnummer) match exactly? Only applicable if `useCombinedComparison` is `False`. Defaults to None.
* matchRtType (bool, *optional*): Should the realtime type that journeys are based on (e.g. SOLL, IST, additional, deviation, ) be considered? Defaults to None. * matchRtType (bool, optional): Should the realtime type that journeys are based on (e.g. SOLL, IST, additional, deviation, ) be considered? Defaults to None.
* enableRtFullSearch (bool, *optional*): By default, the reconstruction request makes one attempt for each journey within the scheduled data. However, the scheduled data may not necessarily reflect basic realtime properties of the journeys therein. In such a case, one may enable a two-step approach which we call "full search", i.e. search for matching journeys in the scheduled data in a first step. If this fails, then search for matching journeys in the realtime data. Defaults to None. * enableRtFullSearch (bool, optional): By default, the reconstruction request makes one attempt for each journey within the scheduled data. However, the scheduled data may not necessarily reflect basic realtime properties of the journeys therein. In such a case, one may enable a two-step approach which we call "full search", i.e. search for matching journeys in the scheduled data in a first step. If this fails, then search for matching journeys in the realtime data. Defaults to None.
* enableReplacements (bool, *optional*): If set to true replaces cancelled journeys with their replacement journeys if possible. Defaults to None. * enableReplacements (bool, optional): If set to true replaces cancelled journeys with their replacement journeys if possible. Defaults to None.
* arrL (int, *optional*): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original arrival". Defaults to None. * arrL (int, optional): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original arrival". Defaults to None.
* arrU (int, *optional*): Upper deviation in minutes within interval [0, 720] indicating "how much later than original arrival". Defaults to None. * arrU (int, optional): Upper deviation in minutes within interval [0, 720] indicating "how much later than original arrival". Defaults to None.
* depL (int, *optional*): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original departure". Defaults to None. * depL (int, optional): Lower deviation in minutes within interval [0, 720] indicating "how much earlier than original departure". Defaults to None.
* depU (int, *optional*): Upper deviation in minutes within interval [0, 720] indicating "how much later than original departure". Defaults to None. * depU (int, optional): Upper deviation in minutes within interval [0, 720] indicating "how much later than original departure". Defaults to None.
* passlist (bool, *optional*): Enables/disables the return of the passlist for each leg of the trip. Defaults to False. * passlist (bool, optional): Enables/disables the return of the passlist for each leg of the trip. Defaults to False.
* showPassingPoints (bool, *optional*): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist parameter enabled. Defaults to False. * showPassingPoints (bool, optional): Enables/disables the return of stops having no alighting and boarding in its passlist for each leg of the trip. Needs passlist parameter enabled. Defaults to False.
* rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], *optional*): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None. * rtMode (Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], optional): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to None.
* eco (bool, *optional*): Enables/disables eco value calculation. Defaults to False. * eco (bool, optional): Enables/disables eco value calculation. Defaults to False.
* ecoCmp (bool, *optional*): Enables/disables eco comparison. Defaults to False. * ecoCmp (bool, optional): Enables/disables eco comparison. Defaults to False.
* ecoParams (str, *optional*): Provide additional eco parameters. Values vary. Defaults to None. * ecoParams (str, optional): Provide additional eco parameters. Values vary. Defaults to None.
* tariff (bool, *optional*): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None. * tariff (bool, optional): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to None.
* trafficMessages (bool, *optional*): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to None. * trafficMessages (bool, optional): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to None.
* travellerProfileData (str, *optional*): Traveller profile data. Structure depends on set up. Defaults to None. * travellerProfileData (str, optional): Traveller profile data. Structure depends on set up. Defaults to None.
### Returns: ### Returns:
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs. * dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
@ -87,7 +87,7 @@ def trip_recon(
payload = {} payload = {}
headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"} headers = {"Accept": "application/json"} if json else {"Accept": "application/xml"}
for var, val in locals().copy().items(): for var, val in locals().items():
if str(var) == "date": if str(var) == "date":
if val != None: if val != None:
if isinstance(val, datetime): if isinstance(val, datetime):

View File

@ -1,4 +1,4 @@
from ..errors import ( from pyrmv.errors import (
ApiAuthError, ApiAuthError,
ApiFormatError, ApiFormatError,
ApiParamError, ApiParamError,
@ -26,7 +26,6 @@ from ..errors import (
SvcNoResultError, SvcNoResultError,
SvcProductError, SvcProductError,
SvcSearchError, SvcSearchError,
SvcParamError,
UnknownError, UnknownError,
) )
@ -87,9 +86,6 @@ def find_exception(data: dict):
elif data["errorCode"] == "SVC_CTX": elif data["errorCode"] == "SVC_CTX":
raise SvcContextError() raise SvcContextError()
elif data["errorCode"] == "SVC_PARAM":
raise SvcParamError(errorCode=data["errorCode"], errorText=data["errorText"])
elif data["errorCode"] == "SVC_NO_RESULT": elif data["errorCode"] == "SVC_NO_RESULT":
raise SvcNoResultError() raise SvcNoResultError()

View File

@ -4,7 +4,8 @@ from typing import List
import pytest import pytest
from pyrmv import Client, enums from pyrmv import Client, enums
from pyrmv.classes import BoardArrival, BoardDeparture, Journey, Message, Stop, Trip from pyrmv.classes import Journey, Message, Stop, Trip
from pyrmv.classes.board import BoardArrival, BoardDeparture
def test_board_arrival(api_client: Client, sample_stop_id: str): def test_board_arrival(api_client: Client, sample_stop_id: str):
@ -20,16 +21,13 @@ def test_board_departure(api_client: Client, sample_stop_id: str):
def test_him_search(api_client: Client): def test_him_search(api_client: Client):
response = api_client.him_search(time_end=datetime.now() + timedelta(days=10)) assert isinstance(
api_client.him_search(date_end=datetime.now() + timedelta(days=10))[0], Message
if len(response) != 0: )
assert isinstance(response[0], Message)
else:
assert isinstance(response, list)
def test_journey_detail(api_client: Client, sample_journey_id: str): def test_journey_detail(api_client: Client, sample_journey_id: str):
assert isinstance( assert (
api_client.journey_detail( api_client.journey_detail(
sample_journey_id, sample_journey_id,
real_time_mode=enums.RealTimeMode.FULL, real_time_mode=enums.RealTimeMode.FULL,

View File

@ -1,6 +1,6 @@
[tox] [tox]
minversion = 3.8.0 minversion = 3.8.0
envlist = py38, py39, py310, py311, py312 envlist = py38, py39, py310, py311
isolated_build = true isolated_build = true
[gh-actions] [gh-actions]
@ -9,7 +9,6 @@ python =
3.9: py39 3.9: py39
3.10: py310 3.10: py310
3.11: py311 3.11: py311
3.12: py312
[testenv] [testenv]
setenv = setenv =
@ -19,6 +18,6 @@ passenv =
deps = deps =
-r{toxinidir}/requirements/_.txt -r{toxinidir}/requirements/_.txt
-r{toxinidir}/requirements/dev.txt -r{toxinidir}/requirements/dev.txt
-r{toxinidir}/requirements/speed.txt
commands = commands =
pytest --basetemp={envtmpdir} --cov=pyrmv --cov-report term-missing pytest --basetemp={envtmpdir} --cov=pyrmv --cov-report term-missing