Compare commits
108 Commits
d949778ac5
...
v0.4.0-rc.
Author | SHA1 | Date | |
---|---|---|---|
eb9a043c34
|
|||
819bd5ff40 | |||
c2e1fc54c1 | |||
29ebb4627d | |||
6b6299cd0a | |||
|
e91846edee | ||
|
9b6b2d6416 | ||
|
f8b13ccedf | ||
|
b47bc51365 | ||
|
f39da9b803 | ||
|
1b863c55f1 | ||
|
80a788933d | ||
|
3599a034dc | ||
|
e09e8f29fb | ||
|
d23d9a005d | ||
9c9489aee1 | |||
07925d15eb | |||
a13027614e | |||
ece22489ad | |||
94472ba945 | |||
76774fc9cb | |||
551babedb7 | |||
ed44947277 | |||
cd973b2000 | |||
036a3174f8 | |||
201fcba766 | |||
b15da7964c | |||
ea828bc966 | |||
3461d82b34 | |||
0d9ea775a6 | |||
5613bf7e3f | |||
2a83b34631 | |||
7e0d381523 | |||
a5022011ed | |||
23527c85f3 | |||
3f738f453b | |||
1a82665932 | |||
84feae2d2f | |||
9da83c878e | |||
c08deb9ff2 | |||
fe9d345002 | |||
f06c9ca33e | |||
4fd566f7c4 | |||
170b472ca4 | |||
d49196ff26 | |||
ebb21aea8c | |||
|
6d447a64c5 | ||
eee76fdff9 | |||
781b202b32 | |||
7e4cde8762 | |||
5c013dd38f | |||
3a23c058c3 | |||
4136bbcddb | |||
366497d8fb | |||
651d709e66 | |||
93240ffcca | |||
65349e14b2 | |||
62cd9feb55 | |||
08dafb6459 | |||
8e9347f526 | |||
04261e9f3c | |||
6809e3ae9c | |||
fe3e839abb | |||
b069b82cc5 | |||
70aa206cba | |||
71597ac658 | |||
93779b62a6 | |||
0719eaacbc | |||
83af5b33da | |||
9c93275e59 | |||
7d5454a5df | |||
013326d32a | |||
|
67699352da | ||
|
1c68772ed4 | ||
|
e5a608ff14 | ||
|
8cad137834 | ||
|
9cce5f338f | ||
|
6b8c173ea8 | ||
6c9a90d455 | |||
37727e38bf | |||
5e4ca07877 | |||
cf642fc00f | |||
|
c7b0649b50 | ||
|
cc6324cc88 | ||
|
52aea964b1 | ||
|
7b0f2c31ed | ||
|
947e6361f6 | ||
|
a868c997ac | ||
|
9641a4dab8 | ||
|
428442d1cb | ||
|
0bbda88433 | ||
|
deb49e174b | ||
|
8cb28e9030 | ||
|
8bf1a6fee3 | ||
|
660c9644f9 | ||
|
1770695067 | ||
|
0a374236b4 | ||
|
f8e7fae9e3 | ||
|
74107ceb1b | ||
|
ab02e13825 | ||
|
45a59ff6f6 | ||
|
977ac2d559 | ||
|
da21f3ad77 | ||
590eca20d8 | |||
0805f1becf | |||
e1e3f40643 | |||
a093d1b5d7 | |||
2851c5083f |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -156,9 +156,10 @@ cython_debug/
|
||||
# Custom
|
||||
.pypirc
|
||||
tests
|
||||
test.*
|
||||
test_all.py
|
||||
test.bat
|
||||
test_key.json
|
||||
build.*
|
||||
cleanup.*
|
||||
publish.*
|
||||
publish-release.*
|
||||
.vscode
|
17
.renovaterc
Normal file
17
.renovaterc
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:base"
|
||||
],
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": [
|
||||
"minor",
|
||||
"patch",
|
||||
"pin",
|
||||
"digest"
|
||||
],
|
||||
"automerge": true
|
||||
}
|
||||
]
|
||||
}
|
56
README.md
56
README.md
@@ -2,56 +2,62 @@
|
||||
|
||||
Small module that makes your journey with RMV REST API somehow easier. Based fully on official RMV API reference and HAFAS documentation.
|
||||
|
||||
# Requirements
|
||||
## Requirements
|
||||
|
||||
* RMV API key (Get it [here](https://opendata.rmv.de/site/start.html))
|
||||
* Python3 (Tested versions are 3.7.9 and 3.9.13)
|
||||
* git (Only for installation from source)
|
||||
|
||||
# Installation
|
||||
## Installation
|
||||
|
||||
If you have everything listed in [requirements](#requirements), then let's begin.
|
||||
|
||||
### Variant 1:
|
||||
### Variant 1
|
||||
|
||||
1. `python -m pip install pyrmv`
|
||||
|
||||
### Variant 2:
|
||||
### Variant 2
|
||||
|
||||
1. `git clone https://git.end-play.xyz/profitroll/PythonRMV.git`
|
||||
2. `cd PythonRMV`
|
||||
3. `python setup.py install`
|
||||
|
||||
# Frequently Asked Questions
|
||||
## Usage
|
||||
|
||||
- [Why are there raw versions and formatted ones?](#why-are-there-raw-versions-and-formatted-ones)
|
||||
- [Some methods work slightly different](#some-methods-work-slightly-different)
|
||||
- [Documentation is not perfectly clear](#documentation-is-not-perfectly-clear)
|
||||
```py
|
||||
import pyrmv
|
||||
|
||||
## Why are there raw versions and formatted ones?
|
||||
# Define a Client with API key
|
||||
client = pyrmv.Client("AcessId")
|
||||
|
||||
# Get origin's and destination's location
|
||||
origin = client.stop_by_name("Frankfurt Hauptbahnhof", max_number=3)[0]
|
||||
destination = client.stop_by_coords(50.099613, 8.685449, max_number=3)[0]
|
||||
|
||||
# Find a trip by locations got
|
||||
trip = client.trip_find(origin_id=origin.id, dest_id=destination.id)
|
||||
```
|
||||
|
||||
## Frequently Asked Questions
|
||||
|
||||
* [Why are there raw versions and formatted ones?](#why-are-there-raw-versions-and-formatted-ones)
|
||||
* [Some methods work slightly different](#some-methods-work-slightly-different)
|
||||
|
||||
### Why are there raw versions and formatted ones?
|
||||
|
||||
For the purposes of my projects I don't really need all the stuff RMV gives (even though it's not much).
|
||||
I only need some specific things. However I do understand that in some cases other users may find
|
||||
those methods quite useful so I implemented them as well.
|
||||
|
||||
|
||||
## Some methods work slightly different
|
||||
### Some methods work slightly different
|
||||
|
||||
Can be. Not all function arguments written may work perfectly because I simply did not test each and
|
||||
every request. Some of arguments may be irrelevant in my use-case and the others are used quite rare at all.
|
||||
Just [make an issue](https://git.end-play.xyz/profitroll/PythonRMV/issues/new) and I'll implement it correct when I'll have some free time.
|
||||
|
||||
## Documentation is not perfectly clear
|
||||
## To-Do
|
||||
|
||||
Of course docs cannot be perfect as a python docstring, especially if sometimes I don't
|
||||
know how things should correctly work. That's why you get HAFAS API docs in addition to your
|
||||
RMV API key. Just use my functions together with those docs, if you want to build something
|
||||
really sophisticated. However I'm not sure whether RMV supports that many HAFAS features publicly.
|
||||
### General
|
||||
|
||||
# To-Do
|
||||
- [ ] arrivalBoard (board_arrival)
|
||||
- [ ] departureBoard (board_departure)
|
||||
- [x] himsearch (him_search)
|
||||
- [ ] journeyDetail (journey_detail)
|
||||
- [x] location.nearbystops (stop_by_coords)
|
||||
- [x] location.name (stop_by_name)
|
||||
- [x] trip (trip_find)
|
||||
- [ ] recon (trip_recon)
|
||||
* [ ] Docs in Wiki
|
||||
* [ ] Tickets
|
||||
|
@@ -3,38 +3,28 @@
|
||||
|
||||
Small module that makes your journey with RMV REST API somehow easier. Based fully on official RMV API reference and HAFAS documentation.
|
||||
|
||||
## Frequently Asked Questions
|
||||
## Usage
|
||||
|
||||
- [Why are there raw versions and formatted ones?](#why-are-there-raw-versions-and-formatted-ones)
|
||||
- [Some methods work slightly different](#some-methods-work-slightly-different)
|
||||
- [Documentation is not perfectly clear](#documentation-is-not-perfectly-clear)
|
||||
```py
|
||||
import pyrmv
|
||||
|
||||
### Why are there raw versions and formatted ones?
|
||||
# Define a Client with API key
|
||||
client = pyrmv.Client("AcessId")
|
||||
|
||||
For the purposes of my projects I don't really need all the stuff RMV gives (even though it's not much).
|
||||
I only need some specific things. However I do understand that in some cases other users may find
|
||||
those methods quite useful so I implemented them as well.
|
||||
# Get origin's and destination's location
|
||||
origin = client.stop_by_name("Frankfurt Hauptbahnhof", max_number=3)[0]
|
||||
destination = client.stop_by_coords(50.099613, 8.685449, max_number=3)[0]
|
||||
|
||||
|
||||
### Some methods work slightly different
|
||||
|
||||
Can be. Not all function arguments written may work perfectly because I simply did not test each and
|
||||
every request. Some of arguments may be irrelevant in my use-case and the others are used quite rare at all.
|
||||
Just [make an issue](https://git.end-play.xyz/profitroll/PythonRMV/issues/new) and I'll implement it correct when I'll have some free time.
|
||||
|
||||
### Documentation is not perfectly clear
|
||||
|
||||
Of course docs cannot be perfect as a python docstring, especially if sometimes I don't
|
||||
know how things should correctly work. That's why you get HAFAS API docs in addition to your
|
||||
RMV API key. Just use my functions together with those docs, if you want to build something
|
||||
really sophisticated. However I'm not sure whether RMV supports that many HAFAS features publicly.
|
||||
# Find a trip by locations got
|
||||
trip = client.trip_find(origin_id=origin.id, dest_id=destination.id)
|
||||
```
|
||||
"""
|
||||
|
||||
__name__ = "pyrmv"
|
||||
__version__ = "0.1.8"
|
||||
__version__ = "0.3.5"
|
||||
__license__ = "MIT License"
|
||||
__author__ = "Profitroll"
|
||||
|
||||
from . import raw
|
||||
from .methods import *
|
||||
from .errors import *
|
||||
from . import const, enums, errors, raw, utility
|
||||
from .classes import *
|
||||
from .classes.Client import Client
|
||||
|
94
pyrmv/classes/Board.py
Normal file
94
pyrmv/classes/Board.py
Normal file
@@ -0,0 +1,94 @@
|
||||
from datetime import datetime
|
||||
from pyrmv.classes.Message import Message
|
||||
|
||||
class LineArrival():
|
||||
|
||||
def __init__(self, data, client, retrieve_stops: bool = True):
|
||||
self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"])
|
||||
self.status = data["JourneyStatus"]
|
||||
self.messages = []
|
||||
if "Messages" in data:
|
||||
self.messages.extend(
|
||||
Message(message) for message in data["Messages"]["Message"]
|
||||
)
|
||||
self.name = data["name"]
|
||||
self.type = data["type"]
|
||||
self.stop_name = data["stop"]
|
||||
self.stop_id = data["stopid"]
|
||||
self.stop_id_ext = data["stopExtId"]
|
||||
if retrieve_stops:
|
||||
self.stop = client.stop_by_id(self.stop_id)
|
||||
else:
|
||||
self.stop = None
|
||||
self.stop = client.stop_by_id(self.stop_id)
|
||||
self.time = datetime.strptime(data["time"], "%H:%M:%S")
|
||||
self.date = datetime.strptime(data["date"], "%Y-%m-%d")
|
||||
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")
|
||||
self.reachable = data["reachable"]
|
||||
self.origin = data["origin"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.name} coming from {self.origin} at {self.time.time()} {self.date.date()}"
|
||||
|
||||
class LineDeparture():
|
||||
|
||||
def __init__(self, data, client, retrieve_stops: bool = True):
|
||||
self.journey = client.journey_detail(data["JourneyDetailRef"]["ref"])
|
||||
self.status = data["JourneyStatus"]
|
||||
self.messages = []
|
||||
if "Messages" in data:
|
||||
self.messages.extend(
|
||||
Message(message) for message in data["Messages"]["Message"]
|
||||
)
|
||||
self.name = data["name"]
|
||||
self.type = data["type"]
|
||||
self.stop_name = data["stop"]
|
||||
self.stop_id = data["stopid"]
|
||||
self.stop_id_ext = data["stopExtId"]
|
||||
if retrieve_stops:
|
||||
self.stop = client.stop_by_id(self.stop_id)
|
||||
else:
|
||||
self.stop = None
|
||||
self.time = datetime.strptime(data["time"], "%H:%M:%S")
|
||||
self.date = datetime.strptime(data["date"], "%Y-%m-%d")
|
||||
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")
|
||||
self.reachable = data["reachable"]
|
||||
self.direction = data["direction"]
|
||||
self.direction_flag = data["directionFlag"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.name} heading {self.direction} at {self.time.time()} {self.date.date()}"
|
||||
|
||||
class BoardArrival(list):
|
||||
|
||||
def __init__(self, data: dict, client, retrieve_stops: bool = True):
|
||||
super().__init__([])
|
||||
if "Arrival" not in data:
|
||||
return
|
||||
for line in data["Arrival"]:
|
||||
self.append(LineArrival(line, client, retrieve_stops=retrieve_stops))
|
||||
|
||||
def __str__(self) -> str:
|
||||
lines = []
|
||||
for line in self:
|
||||
lines.append(str(line))
|
||||
return "Arrival board\n" + "\n".join(lines)
|
||||
|
||||
class BoardDeparture(list):
|
||||
|
||||
def __init__(self, data: dict, client, retrieve_stops: bool = True):
|
||||
super().__init__([])
|
||||
if "Departure" not in data:
|
||||
return
|
||||
for line in data["Departure"]:
|
||||
self.append(LineDeparture(line, client, retrieve_stops=retrieve_stops))
|
||||
|
||||
def __str__(self) -> str:
|
||||
lines = []
|
||||
for line in self:
|
||||
lines.append(str(line))
|
||||
return "Departure board\n" + "\n".join(lines)
|
781
pyrmv/classes/Client.py
Normal file
781
pyrmv/classes/Client.py
Normal file
@@ -0,0 +1,781 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, OrderedDict, Union
|
||||
from pyrmv.classes import *
|
||||
from pyrmv.enums import *
|
||||
from pyrmv.raw import board_arrival as raw_board_arrival
|
||||
from pyrmv.raw.board_departure import board_departure as raw_board_departure
|
||||
from pyrmv.raw.journey_detail import journey_detail as raw_journey_detail
|
||||
from pyrmv.raw.stop_by_name import stop_by_name as raw_stop_by_name
|
||||
from pyrmv.raw.stop_by_coords import stop_by_coords as raw_stop_by_coords
|
||||
from pyrmv.raw.trip_find import trip_find as raw_trip_find
|
||||
from pyrmv.raw.trip_recon import trip_recon as raw_trip_recon
|
||||
from pyrmv.raw.him_search import him_search as raw_him_search
|
||||
from pyrmv.utility.find_exception import find_exception
|
||||
|
||||
try:
|
||||
from typing import Literal
|
||||
except ImportError:
|
||||
from typing_extensions import Literal
|
||||
|
||||
class Client():
|
||||
"""The main class in the whole module. Is used to use all non-raw methods.
|
||||
|
||||
More detailed docs for each method can be found by using IDE's docstring
|
||||
highlighting system or in project's wiki ([can be found here](https://git.end-play.xyz/profitroll/PythonRMV/wiki))
|
||||
|
||||
### Args:
|
||||
* access_id (`str`): Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
|
||||
|
||||
### Methods:
|
||||
* board_arrival -> BoardArrival
|
||||
* board_departure -> BoardDeparture
|
||||
* him_search -> List[Message]
|
||||
* journey_detail -> Journey
|
||||
* stop_by_coords -> List[Stop]
|
||||
* stop_by_id -> Union[Stop, None]
|
||||
* stop_by_name -> List[Stop]
|
||||
* trip_find -> List[Trip]
|
||||
* trip_recon -> List[Trip]
|
||||
|
||||
### Examples:
|
||||
```py
|
||||
import pyrmv
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# Create client object with you API key
|
||||
client = pyrmv.Client("YourAccessId")
|
||||
|
||||
# Get arrival and departure boards for station "Frankfurt (Main) Taunusanlage"
|
||||
board_arrival = client.board_arrival("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
|
||||
messages = client.him_search(date_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"])
|
||||
|
||||
# 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)
|
||||
|
||||
# Look for stops using all possible methods
|
||||
stop_by_coords client.stop_by_coords(50.131140, 8.733362, radius=300, max_number=3)
|
||||
stop_by_id = client.stop_by_id("A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@X=8764456@Y=50105181@U=80@L=3002510@")
|
||||
stop_by_name = client.stop_by_name("Groß Karben", max_number=3)
|
||||
|
||||
# Find a trip and reconstruct it
|
||||
trip = client.trip_find(origin_coord_lat="50.084659", origin_coord_lon="8.785948", destination_coord_lat=50.1233048, destination_coord_lon=8.6129742, messages=True)[0]
|
||||
trip_recon = client.trip_recon(trip)[0]
|
||||
```
|
||||
"""
|
||||
|
||||
def __init__(self, access_id: str) -> None:
|
||||
self.access_id = access_id
|
||||
|
||||
def board_arrival(self,
|
||||
id: Union[str, None] = None,
|
||||
id_ext: Union[str, None] = None,
|
||||
direction: Union[str, Stop, StopTrip, None] = None,
|
||||
date: Union[str, datetime, None] = None,
|
||||
time: Union[str, datetime, None] = None,
|
||||
duration: Union[int, timedelta] = 60,
|
||||
journeys_max: int = -1,
|
||||
operators: Union[str, list, None] = None,
|
||||
lines: Union[str, list, None] = None,
|
||||
passlist: bool = False,
|
||||
board_type: Literal[BoardArrivalType.ARR, BoardArrivalType.ARR_EQUIVS, BoardArrivalType.ARR_MAST, BoardArrivalType.ARR_STATION] = BoardArrivalType.ARR,
|
||||
retrieve_stops: bool = True
|
||||
) -> BoardArrival:
|
||||
"""Method returns a board with arriving transport.
|
||||
|
||||
More detailed request is available as `raw.board_arrival()`, however returns `dict` instead of `Board`.
|
||||
|
||||
### Args:
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
|
||||
### Returns:
|
||||
* BoardArrival: Instance of `BoardArrival` object.
|
||||
"""
|
||||
|
||||
if (isinstance(direction, Stop) or isinstance(direction, StopTrip)):
|
||||
direction = direction.id
|
||||
|
||||
board_raw = raw_board_arrival(
|
||||
accessId=self.access_id,
|
||||
id=id,
|
||||
extId=id_ext,
|
||||
direction=direction, # type: ignore
|
||||
date=date,
|
||||
time=time,
|
||||
duration=duration,
|
||||
maxJourneys=journeys_max,
|
||||
operators=operators,
|
||||
lines=lines,
|
||||
passlist=passlist,
|
||||
boardType=board_type.code
|
||||
)
|
||||
|
||||
find_exception(board_raw)
|
||||
|
||||
return BoardArrival(board_raw, self, retrieve_stops=retrieve_stops)
|
||||
|
||||
def board_departure(self,
|
||||
id: Union[str, None] = None,
|
||||
id_ext: Union[str, None] = None,
|
||||
direction: Union[str, Stop, StopTrip, None] = None,
|
||||
date: Union[str, datetime, None] = None,
|
||||
time: Union[str, datetime, None] = None,
|
||||
duration: Union[int, timedelta] = 60,
|
||||
journeys_max: int = -1,
|
||||
operators: Union[str, list, None] = None,
|
||||
lines: Union[str, list, None] = None,
|
||||
passlist: bool = False,
|
||||
board_type: Literal[BoardDepartureType.DEP, BoardDepartureType.DEP_EQUIVS, BoardDepartureType.DEP_MAST, BoardDepartureType.DEP_STATION] = BoardDepartureType.DEP,
|
||||
retrieve_stops: bool = True
|
||||
) -> BoardDeparture:
|
||||
"""Method returns a board with departing transport.
|
||||
|
||||
More detailed request is available as `raw.board_departure()`, however returns `dict` instead of `Board`.
|
||||
|
||||
### Args:
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
|
||||
### Returns:
|
||||
* BoardDeparture: Instance of `BoardDeparture` object.
|
||||
"""
|
||||
|
||||
if (isinstance(direction, Stop) or isinstance(direction, StopTrip)):
|
||||
direction = direction.id
|
||||
|
||||
board_raw = raw_board_departure(
|
||||
accessId=self.access_id,
|
||||
id=id,
|
||||
extId=id_ext,
|
||||
direction=direction, # type: ignore
|
||||
date=date,
|
||||
time=time,
|
||||
duration=duration,
|
||||
maxJourneys=journeys_max,
|
||||
operators=operators,
|
||||
lines=lines,
|
||||
passlist=passlist,
|
||||
boardType=board_type.code
|
||||
)
|
||||
|
||||
find_exception(board_raw)
|
||||
|
||||
return BoardDeparture(board_raw, self, retrieve_stops=retrieve_stops)
|
||||
|
||||
def him_search(self,
|
||||
date_begin: Union[str, 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,
|
||||
ids: Union[list, None] = None,
|
||||
operators: Union[list, None] = None,
|
||||
categories: Union[list, None] = None,
|
||||
channels: Union[list, None] = None,
|
||||
companies: Union[list, None] = None,
|
||||
lines: Union[list, None] = None,
|
||||
line_ids: Union[list, None] = None,
|
||||
stations: Union[list, List[Stop], None] = None,
|
||||
station_from: Union[str, Stop, None] = None,
|
||||
station_to: Union[str, Stop, None] = None,
|
||||
both_ways: Union[bool, None] = None,
|
||||
train_names: Union[list, None] = None,
|
||||
search_mode: Union[Literal[SearchMode.MATCH, SearchMode.NOMATCH, SearchMode.TFMATCH], None] = None,
|
||||
affected_journey_mode: Union[Literal[AffectedJourneyMode.ALL, AffectedJourneyMode.OFF], None] = None,
|
||||
affected_journey_stop_mode: Union[Literal[AffectedJourneyStopMode.ALL, AffectedJourneyStopMode.IMP, AffectedJourneyStopMode.OFF], None] = None,
|
||||
priority_min: Union[int, None] = None,
|
||||
priority_max: Union[int, None] = None
|
||||
) -> List[Message]:
|
||||
"""The him_search method will deliver a list of HIM messages if matched by the given criteria as
|
||||
well as affected products if any.
|
||||
|
||||
More detailed request is available as `raw.him_search()`, however returns `dict` instead of `List[Message]`.
|
||||
|
||||
### Args:
|
||||
* date_begin (`Union[str, datetime]`, optional): Sets the event period start date. Defaults to `None`.
|
||||
* date_end (`Union[str, datetime]`, optional): Sets the event period end date. Defaults to `None`.
|
||||
* time_begin (`Union[str, datetime]`, optional): Sets the event period start time. Defaults to `None`.
|
||||
* time_end (`Union[str, datetime]`, optional): Sets the event period end time. 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`.
|
||||
* ids (`list`, optional): List of HIM message IDs 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`.
|
||||
* categories (`list`, optional): List of train categories 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`.
|
||||
* companies (`list`, optional): List of companies 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* train_names (`list`, optional): List of train name to be filtered for seperated by comma. 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`.
|
||||
* 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`.
|
||||
* 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:
|
||||
* List[Message]: List of `Message` objects. Empty list if none found.
|
||||
"""
|
||||
|
||||
if isinstance(station_from, Stop):
|
||||
station_from = station_from.ext_id
|
||||
|
||||
if isinstance(station_to, Stop):
|
||||
station_to = station_to.ext_id
|
||||
|
||||
if stations != None:
|
||||
new_stations = []
|
||||
for stop in stations:
|
||||
if isinstance(stop, Stop):
|
||||
new_stations.append(stop.ext_id)
|
||||
else:
|
||||
new_stations.append(stop)
|
||||
stations = new_stations
|
||||
|
||||
if search_mode == None:
|
||||
search_mode = None
|
||||
else:
|
||||
search_mode = search_mode.code
|
||||
|
||||
if affected_journey_mode == None:
|
||||
affected_journey_mode = None
|
||||
else:
|
||||
affected_journey_mode = affected_journey_mode.code
|
||||
|
||||
if affected_journey_stop_mode == None:
|
||||
affected_journey_stop_mode = None
|
||||
else:
|
||||
affected_journey_stop_mode = affected_journey_stop_mode.code
|
||||
|
||||
messages = []
|
||||
messages_raw = raw_him_search(
|
||||
accessId=self.access_id,
|
||||
dateB=date_begin,
|
||||
dateE=date_end,
|
||||
timeB=time_begin,
|
||||
timeE=time_end,
|
||||
weekdays=weekdays,
|
||||
himIds=ids,
|
||||
operators=operators,
|
||||
categories=categories,
|
||||
channels=channels,
|
||||
companies=companies,
|
||||
lines=lines,
|
||||
lineids=line_ids,
|
||||
stations=stations,
|
||||
fromstation=station_from, # type: ignore
|
||||
tostation=station_to, # type: ignore
|
||||
bothways=both_ways,
|
||||
trainnames=train_names,
|
||||
searchmode=search_mode, # type: ignore
|
||||
affectedJourneyMode=affected_journey_mode, # type: ignore
|
||||
affectedJourneyStopMode=affected_journey_stop_mode, # type: ignore
|
||||
maxprio=priority_max,
|
||||
minprio=priority_min
|
||||
)
|
||||
|
||||
find_exception(messages_raw)
|
||||
|
||||
if "Message" in messages_raw:
|
||||
for message in messages_raw["Message"]:
|
||||
messages.append(Message(message))
|
||||
|
||||
return messages
|
||||
|
||||
def journey_detail(self,
|
||||
id: str,
|
||||
date: Union[str, datetime, None] = None,
|
||||
real_time_mode: Union[Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT], None] = None,
|
||||
from_id: Union[str, None] = None,
|
||||
from_index: Union[int, None] = None,
|
||||
to_id: Union[str, None] = None,
|
||||
to_index: Union[int, None] = None
|
||||
) -> Journey:
|
||||
"""The journey_detail method will deliver information about the complete route of a vehicle. The journey
|
||||
identifier is part of a trip or `board_departure()` response. It contains a list of all stops/stations of this journey
|
||||
including all departure and arrival times (with real-time data if available) and additional information like
|
||||
specific attributes about facilities and other texts.
|
||||
|
||||
More detailed request is available as `raw.journey_detail()`, however returns `dict` instead of `Journey`.
|
||||
|
||||
### Args:
|
||||
* id (`str`): Specifies the internal journey id of the journey shall be retrieved. Maximum length 512.
|
||||
* date (`Union[str, datetime]`, **optional**): Day of operation. Represented in the format `YYYY-MM-DD` or as a datetime object. By default the current server date is used. Defaults to `None`.
|
||||
* real_time_mode (`Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT]`, **optional**): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to `None`.
|
||||
* from_id (`str`, **optional**): Specifies the station/stop ID the partial itinerary shall start from. Defaults to `None`.
|
||||
* from_index (`int`, **optional**): Specifies the station/stop index the partial itinerary shall start from. Defaults to `None`.
|
||||
* to_id (`str`, **optional**): Specifies the station/stop ID the partial itinerary shall end at. Defaults to `None`.
|
||||
* to_index (`int`, **optional**): Specifies the station/stop index the partial itinerary shall end at. Defaults to `None`.
|
||||
|
||||
### Returns:
|
||||
* Journey: Instance of `Journey` object.
|
||||
"""
|
||||
|
||||
if real_time_mode == None:
|
||||
real_time_mode = None
|
||||
else:
|
||||
real_time_mode = real_time_mode.code
|
||||
|
||||
journey_raw = raw_journey_detail(
|
||||
accessId=self.access_id,
|
||||
id=id,
|
||||
date=date,
|
||||
rtMode=real_time_mode, # type: ignore
|
||||
fromId=from_id,
|
||||
fromIdx=from_index,
|
||||
toId=to_id,
|
||||
toIdx=to_index
|
||||
)
|
||||
|
||||
find_exception(journey_raw)
|
||||
|
||||
return Journey(journey_raw)
|
||||
|
||||
def stop_by_coords(self,
|
||||
coords_lat: Union[str, float],
|
||||
coords_lon: Union[str, float],
|
||||
|
||||
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] = Language.EN,
|
||||
radius: Union[int, float] = 1000,
|
||||
max_number: int = 10,
|
||||
stop_type: Literal[LocationType.S, LocationType.P, LocationType.SP, LocationType.SE, LocationType.SPE] = LocationType.S,
|
||||
selection_mode: Union[Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N], None] = None,
|
||||
) -> List[Stop]:
|
||||
"""Method returns a list of stops around a given center coordinate.
|
||||
The returned results are ordered by their distance to the center coordinate.
|
||||
|
||||
More detailed request is available as `raw.stop_by_coords()`, however returns `dict` instead of `List[Stop]`.
|
||||
|
||||
### Args:
|
||||
* coords_lat (`Union[str, float]`): Latitude of centre coordinate.
|
||||
* coords_lon (`Union[str, float]`): Longitude of centre coordinate.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
|
||||
### Returns:
|
||||
* List[Stop]: List of `Stop` objects. Empty list if none found.
|
||||
"""
|
||||
|
||||
if selection_mode == None:
|
||||
selection_mode = None
|
||||
else:
|
||||
selection_mode = selection_mode.code
|
||||
|
||||
stops = []
|
||||
stops_raw = raw_stop_by_coords(
|
||||
accessId=self.access_id,
|
||||
originCoordLat=coords_lat,
|
||||
originCoordLong=coords_lon,
|
||||
lang=lang.code,
|
||||
radius=radius,
|
||||
maxNo=max_number,
|
||||
stopType=stop_type.code,
|
||||
locationSelectionMode=selection_mode # type: ignore
|
||||
)
|
||||
|
||||
find_exception(stops_raw)
|
||||
|
||||
if "stopLocationOrCoordLocation" in stops_raw:
|
||||
for stop in stops_raw["stopLocationOrCoordLocation"]:
|
||||
if "StopLocation" in stop:
|
||||
stops.append(Stop(stop["StopLocation"]))
|
||||
elif "CoordLocation" in stop:
|
||||
stops.append(Stop(stop["CoordLocation"]))
|
||||
|
||||
return stops
|
||||
|
||||
def stop_by_id(self,
|
||||
query: str,
|
||||
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] = Language.EN,
|
||||
) -> Union[Stop, None]:
|
||||
"""Method can be used to get Stop object whilst only having id available.
|
||||
|
||||
### Args:
|
||||
* query (`str`): Search for that token.
|
||||
* 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:
|
||||
* Union[Stop, None]: Instance of `Stop` object or `None` if not found.
|
||||
"""
|
||||
|
||||
stops_raw = raw_stop_by_name(
|
||||
accessId=self.access_id,
|
||||
inputString=query,
|
||||
lang=lang.code,
|
||||
maxNo=1
|
||||
)
|
||||
|
||||
find_exception(stops_raw)
|
||||
|
||||
if len(stops_raw["stopLocationOrCoordLocation"]) > 0:
|
||||
stop = stops_raw["stopLocationOrCoordLocation"][0]
|
||||
|
||||
if "StopLocation" in stop:
|
||||
return Stop(stop["StopLocation"])
|
||||
elif "CoordLocation" in stop:
|
||||
return Stop(stop["CoordLocation"])
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
|
||||
def stop_by_name(self,
|
||||
query: str,
|
||||
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] = Language.EN,
|
||||
max_number: int = 10,
|
||||
stop_type: Literal[LocationType.A, LocationType.ALL, LocationType.AP, LocationType.P, LocationType.S, LocationType.SA, LocationType.SP] = LocationType.ALL,
|
||||
selection_mode: Union[Literal[SelectionMode.SLCT_A, SelectionMode.SLCT_N], None] = None,
|
||||
coord_lat: Union[str, float, None] = None,
|
||||
coord_lon: Union[str, float, None] = None,
|
||||
radius: Union[int, float] = 1000,
|
||||
refine_id: Union[str, None] = None,
|
||||
stations: Union[str, list, None] = None,
|
||||
filter_mode: Literal[FilterMode.DIST_PERI, FilterMode.EXCL_PERI, FilterMode.SLCT_PERI] = FilterMode.DIST_PERI
|
||||
) -> List[Stop]:
|
||||
"""Method can be used to perform a pattern matching of a user input and to retrieve a list
|
||||
of possible matches in the journey planner database. Possible matches might be stops/stations,
|
||||
points of interest and addresses.
|
||||
|
||||
More detailed request is available as `raw.stop_by_name()`, however returns `dict` instead of `List[Stop]`.
|
||||
|
||||
### Args:
|
||||
* query (`str`): Search for that token.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* coord_lat (`Union[str, float]`, **optional**): Latitude of centre coordinate. Defaults to `None`.
|
||||
* coord_lon (`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`.
|
||||
* refine_id (`str`, **optional**): In case of an refinable location, this value takes the ID of the refinable one of a previous result. Defaults to `None`.
|
||||
* stations (`Union[str, list]`, **optional**): Filter for stations. Matches if the given value is prefix of any station in the itinerary. As a list or as a string separated by comma. Defaults to `None`.
|
||||
* filter_mode (`Literal[FilterMode.DIST_PERI, FilterMode.EXCL_PERI, FilterMode.SLCT_PERI]`, **optional**): Filter modes for nearby searches. Defaults to `FilterMode.DIST_PERI`.
|
||||
|
||||
### Returns:
|
||||
* List[Stop]: List of `Stop` objects. Empty list if none found.
|
||||
"""
|
||||
|
||||
if selection_mode == None:
|
||||
selection_mode = None
|
||||
else:
|
||||
selection_mode = selection_mode.code
|
||||
|
||||
stops = []
|
||||
stops_raw = raw_stop_by_name(
|
||||
accessId=self.access_id,
|
||||
inputString=query,
|
||||
lang=lang.code,
|
||||
maxNo=max_number,
|
||||
stopType=stop_type.code,
|
||||
locationSelectionMode=selection_mode, # type: ignore
|
||||
coordLat=coord_lat,
|
||||
coordLong=coord_lon,
|
||||
radius=radius,
|
||||
refineId=refine_id,
|
||||
stations=stations,
|
||||
filterMode=filter_mode.code
|
||||
)
|
||||
|
||||
find_exception(stops_raw)
|
||||
|
||||
if "stopLocationOrCoordLocation" in stops_raw:
|
||||
for stop in stops_raw["stopLocationOrCoordLocation"]:
|
||||
if "StopLocation" in stop:
|
||||
stops.append(Stop(stop["StopLocation"]))
|
||||
elif "CoordLocation" in stop:
|
||||
stops.append(Stop(stop["CoordLocation"]))
|
||||
|
||||
return stops
|
||||
|
||||
def trip_find(self,
|
||||
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] = Language.EN,
|
||||
|
||||
origin_id: Union[str, None] = None,
|
||||
origin_id_ext: Union[str, None] = None,
|
||||
origin_coord_lat: Union[str, float, None] = None,
|
||||
origin_coord_lon: Union[str, float, None] = None,
|
||||
origin_coord_name: Union[str, None] = None,
|
||||
|
||||
destination_id: Union[str, None] = None,
|
||||
destination_id_ext: Union[str, None] = None,
|
||||
destination_coord_lat: Union[str, float, None] = None,
|
||||
destination_coord_lon: Union[str, float, None] = None,
|
||||
destination_coord_name: Union[str, None] = None,
|
||||
|
||||
via: Union[str, None] = None,
|
||||
via_id: Union[str, None] = None,
|
||||
via_gis: Union[str, None] = None,
|
||||
via_wait_time: int = 0,
|
||||
|
||||
avoid: Union[str, None] = None,
|
||||
avoid_id: Union[str, None] = None,
|
||||
|
||||
change_time_percent: int = 100,
|
||||
change_time_min: Union[int, None] = None,
|
||||
change_time_max: Union[int, None] = None,
|
||||
change_time_add: Union[int, None] = None,
|
||||
change_max: Union[int, None] = None,
|
||||
|
||||
date: Union[str, datetime, None] = None,
|
||||
time: Union[str, datetime, None] = None,
|
||||
|
||||
search_arrival: bool = False,
|
||||
|
||||
trips_after_time: Union[int, None] = None,
|
||||
trips_before_time: Union[int, None] = None,
|
||||
|
||||
context: Union[str, None] = None,
|
||||
|
||||
passlist: bool = False,
|
||||
operators: Union[str, list, None] = None,
|
||||
|
||||
lines: Union[str, list, None] = None,
|
||||
lineids: Union[str, list, None] = None,
|
||||
|
||||
iv_include: bool = False,
|
||||
iv_only: bool = False,
|
||||
|
||||
bike_carriage: bool = False,
|
||||
|
||||
passing_points: bool = False,
|
||||
|
||||
real_time_mode: Union[Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT], None] = None,
|
||||
|
||||
include_earlier: bool = False,
|
||||
ict_alternatives: bool = False,
|
||||
tariff: Union[bool, None] = None,
|
||||
messages: bool = False,
|
||||
frequency: bool = True
|
||||
) -> List[Trip]:
|
||||
"""The trip service calculates a trip from a specified origin to a specified destination. These might be
|
||||
stop/station IDs or coordinates based on addresses and points of interest validated by the location service or
|
||||
coordinates freely defined by the client.
|
||||
|
||||
More detailed request is available as `raw.trip_find()`, however returns `dict` instead of `List[Trip]`.
|
||||
|
||||
### Args:
|
||||
* 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_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_lon (`Union[str, float]`, **optional**): Longitude 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_name (`str`, **optional**): Name of the trip's origin if coordinate cannot be resolved to an address or poi. Defaults to `None`.
|
||||
* destination_id (`str`, **optional**): Specifies the station/stop ID of the destination for the trip. Such ID can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
|
||||
* destination_id_ext (`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 stop_by_name() or stop_by_coords(). Defaults to `None`.
|
||||
* destination_coord_lat (`Union[str, float]`, **optional**): Latitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
|
||||
* destination_coord_lon (`Union[str, float]`, **optional**): Longitude of station/stop coordinate of the trip's destination. The coordinate can be retrieved from stop_by_name() or stop_by_coords(). Defaults to `None`.
|
||||
* destination_coord_name (`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_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_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_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_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_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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* passlist (`bool`, **optional**): Enables/disables the return of the passlist for each leg of the trip. Defaults to `False`.
|
||||
* 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`.
|
||||
* 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`.
|
||||
* iv_include (`bool`, **optional**): Enables/disables search for individual transport routes. Defaults to `False`.
|
||||
* iv_only (`bool`, **optional**): Enables/disables search for individual transport routes only. Defaults to `False`.
|
||||
* bike_carriage (`bool`, **optional**): Enables/disables search for trips explicit allowing bike carriage. This will only work in combination with `change_max=0` as those trips are always meant to be direct connections. Defaults to `False`.
|
||||
* passing_points (`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`.
|
||||
* real_time_mode (`Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT]`, **optional**): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to `None`.
|
||||
* include_earlier (`bool`, **optional**): Disables search optimization in relation of duration. Defaults to `False`.
|
||||
* ict_alternatives (`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`.
|
||||
* messages (`bool`, **optional**): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to `False`.
|
||||
* frequency (`bool`, **optional**): Enables/disables the calculation of frequency information. Defaults to `True`.
|
||||
|
||||
### Returns:
|
||||
* List[Trip]: List of `Trip` objects. Empty list if none found.
|
||||
"""
|
||||
|
||||
if real_time_mode == None:
|
||||
real_time_mode = None
|
||||
else:
|
||||
real_time_mode = real_time_mode.code
|
||||
|
||||
trips = []
|
||||
trips_raw = raw_trip_find(
|
||||
|
||||
accessId=self.access_id,
|
||||
lang=lang.code,
|
||||
|
||||
originId=origin_id,
|
||||
originExtId=origin_id_ext,
|
||||
originCoordLat=origin_coord_lat,
|
||||
originCoordLong=origin_coord_lon,
|
||||
originCoordName=origin_coord_name,
|
||||
|
||||
destId=destination_id,
|
||||
destExtId=destination_id_ext,
|
||||
destCoordLat=destination_coord_lat,
|
||||
destCoordLong=destination_coord_lon,
|
||||
destCoordName=destination_coord_name,
|
||||
|
||||
via=via,
|
||||
viaId=via_id,
|
||||
viaGis=via_gis,
|
||||
viaWaitTime=via_wait_time,
|
||||
|
||||
avoid=avoid,
|
||||
avoidId=avoid_id,
|
||||
|
||||
changeTimePercent=change_time_percent,
|
||||
minChangeTime=change_time_min,
|
||||
maxChangeTime=change_time_max,
|
||||
addChangeTime=change_time_add,
|
||||
maxChange=change_max,
|
||||
|
||||
date=date,
|
||||
time=time,
|
||||
|
||||
searchForArrival=search_arrival,
|
||||
|
||||
numF=trips_after_time,
|
||||
numB=trips_before_time,
|
||||
|
||||
context=context,
|
||||
|
||||
passlist=passlist,
|
||||
operators=operators,
|
||||
|
||||
lines=lines,
|
||||
lineids=lineids,
|
||||
|
||||
includeIv=iv_include,
|
||||
ivOnly=iv_only,
|
||||
|
||||
bikeCarriage=bike_carriage,
|
||||
|
||||
showPassingPoints=passing_points,
|
||||
|
||||
rtMode=real_time_mode, # type: ignore
|
||||
|
||||
includeEarlier=include_earlier,
|
||||
withICTAlternatives=ict_alternatives,
|
||||
tariff=tariff,
|
||||
trafficMessages=messages,
|
||||
withFreq=frequency
|
||||
)
|
||||
|
||||
find_exception(trips_raw)
|
||||
|
||||
if "Trip" in trips_raw:
|
||||
for trip in trips_raw["Trip"]:
|
||||
trips.append(Trip(trip))
|
||||
|
||||
return trips
|
||||
|
||||
def trip_recon(self,
|
||||
context: Union[str, Trip],
|
||||
date: Union[str, datetime, None] = None,
|
||||
match_real_time: Union[bool, None] = None,
|
||||
enable_replacements: Union[bool, None] = None,
|
||||
arrival_dev_lower: Union[int, None] = None,
|
||||
arrival_dev_upper: Union[int, None] = None,
|
||||
departure_dev_lower: Union[int, None] = None,
|
||||
departure_dev_upper: Union[int, None] = None,
|
||||
passlist: bool = False,
|
||||
passing_points: bool = False,
|
||||
real_time_mode: Union[Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT], None] = None,
|
||||
tariff: Union[bool, None] = None,
|
||||
messages: bool = False
|
||||
) -> List[Trip]:
|
||||
"""Reconstructing a trip can be achieved using the reconstruction context provided by any trip result in the
|
||||
`ctx_recon` attribute of `Trip` object. The result will be a true copy of the original trip search result given
|
||||
that the underlying data did not change.
|
||||
|
||||
More detailed request is available as `raw.trip_recon()`, however returns `dict` instead of `List[Trip]`.
|
||||
|
||||
### Args:
|
||||
* context (`Union[str, Journey]`): Specifies the reconstruction context.
|
||||
* 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`.
|
||||
* 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_upper (`int`, **optional**): Upper deviation in minutes within interval `[0, 720]` indicating "how much later than original arrival". Defaults to `None`.
|
||||
* departure_dev_lower (`int`, **optional**): Lower deviation in minutes within interval `[0, 720]` indicating "how much earlier than original departure". Defaults to `None`.
|
||||
* departure_dev_upper (`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 `None`.
|
||||
* passing_points (`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`.
|
||||
* real_time_mode (`Literal[RealTimeMode.FULL, RealTimeMode.INFOS, RealTimeMode.OFF, RealTimeMode.REALTIME, RealTimeMode.SERVER_DEFAULT]`, **optional**): Set the realtime mode to be used. Read more about this in HAFAS ReST Documentation. Defaults to `None`.
|
||||
* tariff (`bool`, **optional**): Enables/disables the output of tariff data. The default is configurable via provisioning. Defaults to `None`.
|
||||
* messages (`bool`, **optional**): Enables/disables the output of traffic messages. The default is configurable via provisioning. Defaults to `False`.
|
||||
|
||||
### Returns:
|
||||
* List[Trip]: List of `Trip` objects. Empty list if none found.
|
||||
"""
|
||||
|
||||
if real_time_mode == None:
|
||||
real_time_mode = None
|
||||
else:
|
||||
real_time_mode = real_time_mode.code
|
||||
|
||||
if isinstance(context, Trip):
|
||||
context = context.ctx_recon
|
||||
|
||||
trips = []
|
||||
trips_raw = raw_trip_recon(
|
||||
accessId=self.access_id,
|
||||
ctx=context, # type: ignore
|
||||
date=date,
|
||||
matchRtType=match_real_time,
|
||||
enableReplacements=enable_replacements,
|
||||
arrL=arrival_dev_lower,
|
||||
arrU=arrival_dev_upper,
|
||||
depL=departure_dev_lower,
|
||||
depU=departure_dev_upper,
|
||||
passlist=passlist,
|
||||
showPassingPoints=passing_points,
|
||||
rtMode=real_time_mode, # type: ignore
|
||||
tariff=tariff,
|
||||
trafficMessages=messages,
|
||||
)
|
||||
|
||||
find_exception(trips_raw)
|
||||
|
||||
if "Trip" in trips_raw:
|
||||
for trip in trips_raw["Trip"]:
|
||||
trips.append(Trip(trip))
|
||||
|
||||
return trips
|
11
pyrmv/classes/Gis.py
Normal file
11
pyrmv/classes/Gis.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from isodate import parse_duration
|
||||
|
||||
class Gis():
|
||||
"""Gis object."""
|
||||
|
||||
def __init__(self, ref: str, route: dict):
|
||||
|
||||
self.ref = ref
|
||||
self.dist = route["dist"]
|
||||
self.duration = parse_duration(route["durS"])
|
||||
self.geo = route["dirGeo"]
|
22
pyrmv/classes/Journey.py
Normal file
22
pyrmv/classes/Journey.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from pyrmv.classes.Stop import Stop
|
||||
from pyrmv.classes.Message import Message
|
||||
|
||||
class Journey():
|
||||
"""Journey object."""
|
||||
|
||||
def __init__(self, data: dict):
|
||||
self.stops = []
|
||||
self.ref = data["ref"]
|
||||
self.direction = data["Directions"]["Direction"][0]["value"]
|
||||
self.direction_flag = data["Directions"]["Direction"][0]["flag"]
|
||||
self.messages = []
|
||||
|
||||
self.stops.extend(Stop(stop) for stop in data["Stops"]["Stop"])
|
||||
|
||||
if "Messages" in data:
|
||||
self.messages.extend(
|
||||
Message(message) for message in data["Messages"]["Message"]
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Journey with total of {len(self.stops)} stops and {len(self.messages)} messages heading {self.direction} ({self.direction_flag})"
|
43
pyrmv/classes/Leg.py
Normal file
43
pyrmv/classes/Leg.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from pyrmv.classes.Gis import Gis
|
||||
from pyrmv.classes.Message import Message
|
||||
from pyrmv.classes.Stop import StopTrip
|
||||
from isodate import parse_duration
|
||||
|
||||
class Leg():
|
||||
"""Trip leg object."""
|
||||
|
||||
def __init__(self, data: dict):
|
||||
|
||||
self.origin = StopTrip(data["Origin"])
|
||||
self.destination = StopTrip(data["Destination"])
|
||||
|
||||
if "GisRef" in data:
|
||||
self.gis = Gis(data["GisRef"]["ref"], data["GisRoute"])
|
||||
else:
|
||||
self.gis = None
|
||||
|
||||
self.index = data["idx"]
|
||||
self.name = data["name"]
|
||||
self.type = data["type"]
|
||||
|
||||
if "direction" in data:
|
||||
self.direction = data["direction"]
|
||||
else:
|
||||
self.direction = None
|
||||
|
||||
self.messages = []
|
||||
if "Messages" in data:
|
||||
for message in data["Messages"]["Message"]:
|
||||
self.messages.append(Message(message))
|
||||
|
||||
if "number" in data:
|
||||
self.number = data["number"]
|
||||
else:
|
||||
self.number = None
|
||||
|
||||
self.duration = parse_duration(data["duration"])
|
||||
|
||||
if "dist" in data:
|
||||
self.distance = data["dist"]
|
||||
else:
|
||||
self.distance = None
|
84
pyrmv/classes/Message.py
Normal file
84
pyrmv/classes/Message.py
Normal file
@@ -0,0 +1,84 @@
|
||||
from pyrmv.classes.Stop import Stop
|
||||
from datetime import datetime
|
||||
from isodate import parse_duration
|
||||
|
||||
class Url():
|
||||
"""Traffic message channel url object."""
|
||||
|
||||
def __init__(self, data: dict) -> None:
|
||||
self.name = data["name"]
|
||||
self.url = data["url"]
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.name}: {self.url}"
|
||||
|
||||
class Channel():
|
||||
"""Traffic message channel object."""
|
||||
|
||||
def __init__(self, data: dict) -> None:
|
||||
self.name = data["name"]
|
||||
url = []
|
||||
for link in url:
|
||||
url.append(Url(link))
|
||||
self.url = url
|
||||
self.time_start = datetime.strptime(data["validFromTime"], "%H:%M:%S")
|
||||
self.date_start = datetime.strptime(data["validFromDate"], "%Y-%m-%d")
|
||||
self.time_end = datetime.strptime(data["validToTime"], "%H:%M:%S")
|
||||
self.date_end = datetime.strptime(data["validToDate"], "%Y-%m-%d")
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{self.name}: from {self.time_start} {self.date_start} until {self.time_end} {self.date_end}"
|
||||
|
||||
|
||||
class Message():
|
||||
"""Traffic message object."""
|
||||
|
||||
def __init__(self, data: dict) -> None:
|
||||
|
||||
self.affected_stops = []
|
||||
if "affectedStops" in data:
|
||||
for stop in data["affectedStops"]["StopLocation"]:
|
||||
self.affected_stops.append(Stop(stop))
|
||||
|
||||
if "validFromStop" in data:
|
||||
self.valid_from_stop = Stop(data["validFromStop"])
|
||||
else:
|
||||
self.valid_from_stop = None
|
||||
|
||||
if "validToStop" in data:
|
||||
self.valid_to_stop = Stop(data["validToStop"])
|
||||
else:
|
||||
self.valid_to_stop = None
|
||||
|
||||
self.channels = []
|
||||
for channel in data["channel"]:
|
||||
self.channels.append(Channel(channel))
|
||||
|
||||
self.id = data["id"]
|
||||
self.active = data["act"]
|
||||
self.head = data["head"]
|
||||
self.lead = data["lead"]
|
||||
self.text = data["text"]
|
||||
self.company = data["company"]
|
||||
self.category = data["category"]
|
||||
self.priority = None if "priority" not in data else data["priority"]
|
||||
self.products = data["products"]
|
||||
self.icon = data["icon"]
|
||||
self.time_start = datetime.strptime(data["sTime"], "%H:%M:%S")
|
||||
self.date_start = datetime.strptime(data["sDate"], "%Y-%m-%d")
|
||||
self.time_end = datetime.strptime(data["eTime"], "%H:%M:%S")
|
||||
self.date_end = datetime.strptime(data["eDate"], "%Y-%m-%d")
|
||||
self.date_start_alt = data["altStart"]
|
||||
self.date_end_alt = data["altEnd"]
|
||||
self.time_modified = datetime.strptime(data["modTime"], "%H:%M:%S")
|
||||
self.date_modified = datetime.strptime(data["modDate"], "%Y-%m-%d")
|
||||
self.daily_start = datetime.strptime(data["dailyStartingAt"], "%H:%M:%S")
|
||||
self.daily_duration = parse_duration(data["dailyDuration"])
|
||||
|
||||
if "baseType" in data:
|
||||
self.base_type = data["baseType"]
|
||||
else:
|
||||
self.base_type = None
|
||||
|
||||
def __str__(self) -> str:
|
||||
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}"
|
54
pyrmv/classes/Stop.py
Normal file
54
pyrmv/classes/Stop.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class Stop():
|
||||
"""Stop object."""
|
||||
|
||||
def __init__(self, data: dict):
|
||||
|
||||
self.name = data["name"]
|
||||
self.id = data["id"]
|
||||
|
||||
if "extId" in data:
|
||||
self.ext_id = data["extId"]
|
||||
else:
|
||||
self.ext_id = None
|
||||
|
||||
if "description" in data:
|
||||
self.description = data["description"]
|
||||
else:
|
||||
self.description = None
|
||||
|
||||
self.lon = data["lon"]
|
||||
self.lat = data["lat"]
|
||||
|
||||
if "routeIdx" in data:
|
||||
self.route_index = data["routeIdx"]
|
||||
else:
|
||||
self.route_index = None
|
||||
|
||||
if "arrTrack" in data:
|
||||
self.track_arrival = data["arrTrack"]
|
||||
else:
|
||||
self.track_arrival = None
|
||||
|
||||
if "depTrack" in data:
|
||||
self.track_departure = data["depTrack"]
|
||||
else:
|
||||
self.track_departure = None
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Stop {self.name} at {self.lon}, {self.lat}"
|
||||
|
||||
class StopTrip(Stop):
|
||||
"""Trip stop object. It's like a Stop object, but with a date and time."""
|
||||
|
||||
def __init__(self, data: dict):
|
||||
|
||||
self.type = data["type"]
|
||||
self.date = datetime.strptime(data["date"], "%Y-%m-%d")
|
||||
self.time = datetime.strptime(data["time"], "%H:%M:%S")
|
||||
super().__init__(data)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"Stop {self.name} at {self.lon}, {self.lat} at {self.time.time()} {self.date.date()}"
|
52
pyrmv/classes/Ticket.py
Normal file
52
pyrmv/classes/Ticket.py
Normal file
@@ -0,0 +1,52 @@
|
||||
class Ticket():
|
||||
"""
|
||||
{
|
||||
"externalContent": {
|
||||
"content": "eyJSTVZUaWNrZXQiOnsiVGV4dExvbmciOiJFaW56ZWxmYWhydCBLaW5kZXIiLCJUZXh0TWlkZGxlIjoiRWluemVsZmFocnQgS2luZGVyIiwiVGV4dFNob3J0IjoiRWluemVsZmFocnQgS2luZGVyIiwiUmVtYXJrIjoiUmVnZWxwcmVpcyIsIlZhbGlkRnJvbSI6IjI0LjA5LjIwMjIiLCJUYXJpZmZMZXZlbFByaW50IjoiNDAiLCJUYXJpZmZMZXZlbEludGVybiI6IjYwIiwiUHJpY2UiOiI0NDUiLCJUWkNvZGVTdGFydFJlcSI6IjUyMzMiLCJUWkNvZGVTdGFydFJlcyI6IjUyMzMiLCJUWk5hbWVTdGFydCI6IlNjaG1pdHRlbiBLaXJjaGUiLCJWaWFJZCI6IjAiLCJWaWFUZXh0IjoiS8O2bmlnc3RlaW4vSG9oZW1hcmsiLCJUWkNvZGVEZXN0UmVxIjoiNTAwMSIsIlRaQ29kZURlc3RSZXMiOiI1MDAxIiwiVFpOYW1lRGVzdCI6IkZyYW5rZnVydCAoTWFpbikgSGF1cHR3YWNoZSIsIlR5cGVLZXkiOiIzMzAwIiwiU3VidmVudGlvbiI6IjAiLCJUYXJpZmZWZXJzaW9uIjoiNDEiLCJLYXJ0ZW50eXAiOiJLVFlQLUVpbnplbGZhaHJrYXJ0ZSIsIkthcnRlbnR5cEFuemVpZ2VuYW1lIjoiRWluemVsZmFocnQiLCJLQVByb2R1a3RudW1tZXIiOiIxMDE4NiIsIktBSW5mb1RleHQiOiIiLCJWZXJhbnR3b3J0bGljaGVyIjoiUk1WIiwiVmVyYnVlbmRlIjoiUk1WIiwiRXhwb3J0QXR0cmlidXRlIjoiQVRUUi1WVFJCLUVpbnplbHByZWlzPUtpbmR8QVRUUi1WVFJCLXJlcGxTb3J0ZW49MjIwMCAyNTAwIDI4MDAgMzgwMHxBVFRSLUtUWVAtYmlsbGlnVHI9MSIsIkZyZWlnYWJlSWQiOiIyMDczMCIsIkZyZWlnYWJlIjoiMjY0NSwgMzY3MCwgNTAwMSwgNTAwMiwgNTAwMywgNTAwNCwgNTAwNSwgNTAwNiwgNTAxMSwgNTAxMywgNTAxNSwgNTAyMSwgNTAyMiwgNTAyMywgNTAzMSwgNTA0MSwgNTA0MiwgNTA0NiwgNTA1OSwgNTEwMCwgNTIzMywgNjIzOSwgNjYyNiwgNjYzNiwgNjYzNywgNjYzOSwgNjY0OCwgNjY0OSwgNjY1MCwgNjY1NSwgNjY2MCwgNjY2NCwgNjY5MSIsIkZyZWlnYWJlT3ZlcnZpZXciOiJCYWQgSG9tYnVyZyB2LmQuSMO2aGU7QmFkIFNvZGVuIGEuVHMuO0VzY2hib3JuO0ZyaWVkcmljaHNkb3JmO0dsYXNow7x0dGVuIn19",
|
||||
"contentType": "LIB_TARIFF"
|
||||
},
|
||||
"name": "Einzelfahrkarte Regelpreis",
|
||||
"desc": "Kinder",
|
||||
"price": 445,
|
||||
"cur": "EUR",
|
||||
"shpCtx": "{\"RMVTicket\":{\"TextLong\":\"Einzelfahrt Kinder\",\"TextMiddle\":\"Einzelfahrt Kinder\",\"TextShort\":\"Einzelfahrt Kinder\",\"Remark\":\"Regelpreis\",\"ValidFrom\":\"24.09.2022\",\"TariffLevelPrint\":\"40\",\"TariffLevelIntern\":\"60\",\"Price\":\"445\",\"TZCodeStartReq\":\"5233\",\"TZCodeStartRes\":\"5233\",\"TZNameStart\":\"Schmitten Kirche\",\"ViaId\":\"0\",\"ViaText\":\"Königstein/Hohemark\",\"TZCodeDestReq\":\"5001\",\"TZCodeDestRes\":\"5001\",\"TZNameDest\":\"Frankfurt (Main) Hauptwache\",\"TypeKey\":\"3300\",\"Subvention\":\"0\",\"TariffVersion\":\"41\",\"Kartentyp\":\"KTYP-Einzelfahrkarte\",\"KartentypAnzeigename\":\"Einzelfahrt\",\"KAProduktnummer\":\"10186\",\"KAInfoText\":\"\",\"Verantwortlicher\":\"RMV\",\"Verbuende\":\"RMV\",\"ExportAttribute\":\"ATTR-VTRB-Einzelpreis=Kind|ATTR-VTRB-replSorten=2200 2500 2800 3800|ATTR-KTYP-billigTr=1\",\"FreigabeId\":\"20730\",\"Freigabe\":\"2645, 3670, 5001, 5002, 5003, 5004, 5005, 5006, 5011, 5013, 5015, 5021, 5022, 5023, 5031, 5041, 5042, 5046, 5059, 5100, 5233, 6239, 6626, 6636, 6637, 6639, 6648, 6649, 6650, 6655, 6660, 6664, 6691\",\"FreigabeOverview\":\"Bad Homburg v.d.Höhe;Bad Soden a.Ts.;Eschborn;Friedrichsdorf;Glashütten\"}}"
|
||||
}
|
||||
###############################################
|
||||
"shpctx": {
|
||||
"RMVTicket":
|
||||
{
|
||||
"TextLong": "Einzelfahrt Kinder",
|
||||
"TextMiddle": "Einzelfahrt Kinder",
|
||||
"TextShort": "Einzelfahrt Kinder",
|
||||
"Remark": "Regelpreis",
|
||||
"ValidFrom": "24.09.2022",
|
||||
"TariffLevelPrint": "40",
|
||||
"TariffLevelIntern": "60",
|
||||
"Price": "445",
|
||||
"TZCodeStartReq": "5233",
|
||||
"TZCodeStartRes": "5233",
|
||||
"TZNameStart": "Schmitten Kirche",
|
||||
"ViaId": "0",
|
||||
"ViaText": "Königstein/Hohemark",
|
||||
"TZCodeDestReq": "5001",
|
||||
"TZCodeDestRes": "5001",
|
||||
"TZNameDest": "Frankfurt (Main) Hauptwache",
|
||||
"TypeKey": "3300",
|
||||
"Subvention": "0",
|
||||
"TariffVersion": "41",
|
||||
"Kartentyp": "KTYP-Einzelfahrkarte",
|
||||
"KartentypAnzeigename": "Einzelfahrt",
|
||||
"KAProduktnummer": "10186",
|
||||
"KAInfoText": "",
|
||||
"Verantwortlicher": "RMV",
|
||||
"Verbuende": "RMV",
|
||||
"ExportAttribute": "ATTR-VTRB-Einzelpreis=Kind|ATTR-VTRB-replSorten=2200 2500 2800 3800|ATTR-KTYP-billigTr=1",
|
||||
"FreigabeId": "20730",
|
||||
"Freigabe":"2645, 3670, 5001, 5002, 5003, 5004, 5005, 5006, 5011, 5013, 5015, 5021, 5022, 5023, 5031, 5041, 5042, 5046, 5059, 5100, 5233, 6239, 6626, 6636, 6637, 6639, 6648, 6649, 6650, 6655, 6660, 6664, 6691",
|
||||
"FreigabeOverview": "Bad Homburg v.d.Höhe;Bad Soden a.Ts.;Eschborn;Friedrichsdorf;Glashütten"
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
pass
|
37
pyrmv/classes/Trip.py
Normal file
37
pyrmv/classes/Trip.py
Normal file
@@ -0,0 +1,37 @@
|
||||
from pyrmv.classes.Leg import Leg
|
||||
from pyrmv.classes.Stop import StopTrip
|
||||
from isodate import parse_duration
|
||||
|
||||
class Trip():
|
||||
"""Trip object."""
|
||||
|
||||
def __init__(self, data: dict):
|
||||
|
||||
self.raw_data = data
|
||||
self.origin = StopTrip(data["Origin"])
|
||||
self.destination = StopTrip(data["Destination"])
|
||||
|
||||
self.legs = []
|
||||
for leg in data["LegList"]["Leg"]:
|
||||
self.legs.append(Leg(leg))
|
||||
|
||||
self.calculation = data["calculation"]
|
||||
self.index = data["idx"]
|
||||
self.id = data["tripId"]
|
||||
self.ctx_recon = data["ctxRecon"]
|
||||
self.duration = parse_duration(data["duration"])
|
||||
|
||||
if "rtDuration" in data:
|
||||
self.real_time_duration = parse_duration(data["rtDuration"])
|
||||
else:
|
||||
self.real_time_duration = None
|
||||
|
||||
self.checksum = data["checksum"]
|
||||
|
||||
if "transferCount" in data:
|
||||
self.transfer_count = data["transferCount"]
|
||||
else:
|
||||
self.transfer_count = 0
|
||||
|
||||
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"
|
9
pyrmv/classes/__init__.py
Normal file
9
pyrmv/classes/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from .Board import BoardArrival, BoardDeparture, LineArrival, LineDeparture
|
||||
from .Gis import Gis
|
||||
from .Journey import Journey
|
||||
from .Leg import Leg
|
||||
from .Message import Message, Channel, Url
|
||||
from .Stop import Stop, StopTrip
|
||||
from .Ticket import Ticket
|
||||
from .Trip import Trip
|
||||
from .Client import Client
|
20
pyrmv/const/product.py
Normal file
20
pyrmv/const/product.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from typing import Dict
|
||||
|
||||
# Constant is taken from source of PyRMVtransport:
|
||||
# https://github.com/cgtobi/PyRMVtransport/blob/development/RMVtransport/const.py
|
||||
PRODUCTS: Dict[str, int] = {
|
||||
"ice": 1,
|
||||
"ic": 2,
|
||||
"ec": 2,
|
||||
"r": 4,
|
||||
"rb": 4,
|
||||
"re": 4,
|
||||
"sbahn": 8,
|
||||
"ubahn": 16,
|
||||
"tram": 32,
|
||||
"bus": 64,
|
||||
"bus2": 128,
|
||||
"ferry": 256,
|
||||
"taxi": 512,
|
||||
"bahn": 1024,
|
||||
}
|
10
pyrmv/enums/__init__.py
Normal file
10
pyrmv/enums/__init__.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from .product import Product
|
||||
from .rt_mode import RealTimeMode
|
||||
from .lang import Language
|
||||
from .location_type import LocationType
|
||||
from .selection_mode import SelectionMode
|
||||
from .search_mode import SearchMode
|
||||
from .filter_mode import FilterMode
|
||||
from .board_type import BoardArrivalType, BoardDepartureType
|
||||
from .aff_journey_mode import AffectedJourneyMode
|
||||
from .aff_journey_stop_mode import AffectedJourneyStopMode
|
11
pyrmv/enums/aff_journey_mode.py
Normal file
11
pyrmv/enums/aff_journey_mode.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class AffectedJourneyMode(AutoName):
|
||||
"""Enumeration used to declare types of HIM search modes."""
|
||||
|
||||
ALL = auto()
|
||||
"Return affected journeys."
|
||||
|
||||
OFF = auto()
|
||||
"Do not return affected journeys."
|
14
pyrmv/enums/aff_journey_stop_mode.py
Normal file
14
pyrmv/enums/aff_journey_stop_mode.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class AffectedJourneyStopMode(AutoName):
|
||||
"""Enumeration used to declare types of affected journey stops return modes."""
|
||||
|
||||
ALL = auto()
|
||||
"Return all affected stops of affected journeys."
|
||||
|
||||
IMP = auto()
|
||||
"Return important stops of affected journeys."
|
||||
|
||||
OFF = auto()
|
||||
"Do not return stops of affected journeys."
|
19
pyrmv/enums/auto_name.py
Normal file
19
pyrmv/enums/auto_name.py
Normal file
@@ -0,0 +1,19 @@
|
||||
# Class is taken from source code of Pyrogram:
|
||||
# https://github.com/pyrogram/pyrogram/blob/master/pyrogram/enums/auto_name.py
|
||||
|
||||
from enum import Enum
|
||||
from pyrmv.const.product import PRODUCTS
|
||||
|
||||
class AutoName(Enum):
|
||||
def __init__(self, code) -> None:
|
||||
self.code = code
|
||||
|
||||
def _generate_next_value_(self, *args):
|
||||
return self.lower()
|
||||
|
||||
def __repr__(self):
|
||||
return f"pyrmv.enums.{self}"
|
||||
|
||||
class AutoNameProduct(AutoName):
|
||||
def __init__(self, code) -> None:
|
||||
self.code = PRODUCTS[code]
|
44
pyrmv/enums/board_type.py
Normal file
44
pyrmv/enums/board_type.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class BoardArrivalType(AutoName):
|
||||
"""Enumeration used to declare types of arrival board.
|
||||
|
||||
* 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
|
||||
"""
|
||||
|
||||
ARR = auto()
|
||||
"Arrival board as configured in HAFAS"
|
||||
|
||||
ARR_EQUIVS = auto()
|
||||
"Arrival board with all journeys at any masts and equivalent stops"
|
||||
|
||||
ARR_MAST = auto()
|
||||
"Arrival board at mast"
|
||||
|
||||
ARR_STATION = auto()
|
||||
"Arrival board with all journeys at any masts of the requested station"
|
||||
|
||||
class BoardDepartureType(AutoName):
|
||||
"""Enumeration used to declare types of departure board.
|
||||
|
||||
* 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
|
||||
"""
|
||||
|
||||
DEP = auto()
|
||||
"Departure board as configured in HAFAS"
|
||||
|
||||
DEP_EQUIVS = auto()
|
||||
"Departure board with all journeys at any masts and equivalent stops"
|
||||
|
||||
DEP_MAST = auto()
|
||||
"Departure board at mast"
|
||||
|
||||
DEP_STATION = auto()
|
||||
"Departure board with all journeys at any masts of the requested station"
|
19
pyrmv/enums/filter_mode.py
Normal file
19
pyrmv/enums/filter_mode.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class FilterMode(AutoName):
|
||||
"""Enumeration used to declare filters for nearby searches.
|
||||
|
||||
* DIST_PERI - Accentuate matches. Matches in the radius are first
|
||||
* EXCL_PERI - Returns matches inside the radius only
|
||||
* SLCT_PERI - Matches in the radius are excluded. Returns matches outside the radius only
|
||||
"""
|
||||
|
||||
DIST_PERI = auto()
|
||||
"Accentuate matches. Matches in the radius are first."
|
||||
|
||||
EXCL_PERI = auto()
|
||||
"Returns matches inside the radius only."
|
||||
|
||||
SLCT_PERI = auto()
|
||||
"Matches in the radius are excluded. Returns matches outside the radius only."
|
41
pyrmv/enums/lang.py
Normal file
41
pyrmv/enums/lang.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class Language(AutoName):
|
||||
"""Enumeration used to declare locales as ISO-3166 codes (but only available in HAFAS ones)."""
|
||||
|
||||
DE = auto()
|
||||
"German"
|
||||
|
||||
DA = auto()
|
||||
"Danish"
|
||||
|
||||
EN = auto()
|
||||
"English"
|
||||
|
||||
ES = auto()
|
||||
"Spanish"
|
||||
|
||||
FR = auto()
|
||||
"French"
|
||||
|
||||
HU = auto()
|
||||
"Hungarian"
|
||||
|
||||
IT = auto()
|
||||
"Italian"
|
||||
|
||||
NL = auto()
|
||||
"Dutch"
|
||||
|
||||
NO = auto()
|
||||
"Norwegian"
|
||||
|
||||
PL = auto()
|
||||
"Polish"
|
||||
|
||||
SV = auto()
|
||||
"Swedish"
|
||||
|
||||
TR = auto()
|
||||
"Turkish"
|
47
pyrmv/enums/location_type.py
Normal file
47
pyrmv/enums/location_type.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class LocationType(AutoName):
|
||||
"""Enumeration used to declare types of location filter.
|
||||
|
||||
* S - Search for station/stops only
|
||||
* A - Search for addresses only
|
||||
* P - Search for POIs only
|
||||
* AP - Search for addresses and POIs
|
||||
* SA - Search for station/stops and addresses
|
||||
* SE - Search for stations/stops and entrypoints
|
||||
* SP - Search for stations/stops and POIs
|
||||
* ALL - Search in all existing location pools
|
||||
* SPE - Search for stations/stops, POIs and entrypoints
|
||||
|
||||
Note that not all location types may be available for a certain methods.
|
||||
Make sure that selected type is supported by method by looking up
|
||||
its acceptable types in argument description.
|
||||
"""
|
||||
|
||||
S = auto()
|
||||
"Search for station/stops only"
|
||||
|
||||
A = auto()
|
||||
"Search for addresses only"
|
||||
|
||||
P = auto()
|
||||
"Search for POIs only"
|
||||
|
||||
AP = auto()
|
||||
"Search for addresses and POIs"
|
||||
|
||||
SA = auto()
|
||||
"Search for station/stops and addresses"
|
||||
|
||||
SE = auto()
|
||||
"Search for stations/stops and entrypoints"
|
||||
|
||||
SP = auto()
|
||||
"Search for stations/stops and POIs"
|
||||
|
||||
ALL = auto()
|
||||
"Search in all existing location pools"
|
||||
|
||||
SPE = auto()
|
||||
"Search for stations/stops, POIs and entrypoints"
|
47
pyrmv/enums/product.py
Normal file
47
pyrmv/enums/product.py
Normal file
@@ -0,0 +1,47 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoNameProduct
|
||||
|
||||
class Product(AutoNameProduct):
|
||||
"""Enumeration used to declare types of transport."""
|
||||
|
||||
ICE = auto()
|
||||
"The Intercity Express (commonly known as ICE) is a system of high-speed trains predominantly running in Germany."
|
||||
|
||||
IC = auto()
|
||||
"InterCity (commonly abbreviated IC on timetables and tickets) is the classification applied to certain long-distance passenger train services in Europe. Such trains (in contrast to regional, local, or commuter trains) generally call at major stations only."
|
||||
|
||||
EC = auto()
|
||||
"EuroCity, abbreviated as EC, is a cross-border train category within the European inter-city rail network. In contrast to trains allocated to the lower-level \"IC\" (InterCity) category, EC trains are international services that meet 20 criteria covering comfort, speed, food service, and cleanliness."
|
||||
|
||||
R = auto()
|
||||
"Regional rail, also known as local trains and stopping trains, are passenger rail services that operate between towns and cities. These trains operate with more stops over shorter distances than inter-city rail, but fewer stops and faster service than commuter rail."
|
||||
|
||||
RB = auto()
|
||||
"The Regionalbahn (lit. Regional train; abbreviated RB) is a type of local passenger train (stopping train) in Germany. It is similar to the Regionalzug (R) and Regio (R) train categories in neighboring Austria and Switzerland, respectively."
|
||||
|
||||
RE = auto()
|
||||
"In Germany, Luxembourg and Austria, the Regional-Express (RE, or in Austria: REX) is a type of regional train. It is similar to a semi-fast train, with average speed at about 70-90 km/h (top speed often 160 km/h) as it calls at fewer stations than Regionalbahn or S-Bahn trains, but stops more often than InterCity services."
|
||||
|
||||
SBAHN = auto()
|
||||
"The S-Bahn is the name of hybrid urban-suburban rail systems serving a metropolitan region in German-speaking countries. Some of the larger S-Bahn systems provide service similar to rapid transit systems, while smaller ones often resemble commuter or even regional rail. The term derives from Schnellbahn, Stadtbahn or Stadtschnellbahn."
|
||||
|
||||
UBAHN = auto()
|
||||
"A U-Bahn (short for subway, underground express train or metropolitan) is a usually underground, rail-bound means of transport for urban public transport (ÖPNV, city transport)."
|
||||
|
||||
TRAM = auto()
|
||||
"A tram (also known as a streetcar or trolley in North America) is a rail vehicle that travels on tramway tracks on public urban streets; some include segments on segregated right-of-way."
|
||||
|
||||
BUS = auto()
|
||||
"A bus (contracted from omnibus, with variants multibus, motorbus, autobus, etc.) is a road vehicle that carries significantly more passengers than an average car or van."
|
||||
|
||||
BUS2 = auto()
|
||||
"Also a bus, but now idea why it exists anyway."
|
||||
|
||||
FERRY = auto()
|
||||
"A ferry is a ship used to carry passengers, and sometimes vehicles and cargo, across a body of water."
|
||||
|
||||
TAXI = auto()
|
||||
"A taxi, also known as a taxicab or simply a cab, is a type of vehicle for hire with a driver, used by a single passenger or small group of passengers, often for a non-shared ride."
|
||||
|
||||
BAHN = auto()
|
||||
"Rail transport (also known as train transport) is a means of transport that transfers passengers and goods on wheeled vehicles running on rails, which are located on tracks. In contrast to road transport, where the vehicles run on a prepared flat surface, rail vehicles (rolling stock) are directionally guided by the tracks on which they run."
|
20
pyrmv/enums/rt_mode.py
Normal file
20
pyrmv/enums/rt_mode.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class RealTimeMode(AutoName):
|
||||
"""Enumeration used to declare types of real-time traffic."""
|
||||
|
||||
FULL = auto()
|
||||
"Combined search on planned and real-time data This search consists of two steps: i. Search on scheduled data ii. If the result of step (i) contains a non-feasible connection, a search on real-time data is performed and all results are combined"
|
||||
|
||||
INFOS = auto()
|
||||
"Search on planned data, use real-time information for display only: Connections are computed on the basis of planned data. Delays and feasibility of the connections are integrated into the result. Note that additional trains (supplied via realtime feed) will not be part of the resulting connections."
|
||||
|
||||
OFF = auto()
|
||||
"Search on planned data, ignore real-time information completely: Connections are computed on the basis of planned data. No real-time information is shown."
|
||||
|
||||
REALTIME = auto()
|
||||
"Search on real-time data: Connections are computed on the basis of real-time data, using planned schedule only whenever no real-time data is available. All connections computed are feasible with respect to the currently known real-time situation. Additional trains (supplied via real-time feed) will be found if these are part of a fast, comfortable, or direct connection (or economic connection, if economic search is activated)."
|
||||
|
||||
SERVER_DEFAULT = auto()
|
||||
"One of the other real-times modes used by default for RMV."
|
14
pyrmv/enums/search_mode.py
Normal file
14
pyrmv/enums/search_mode.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class SearchMode(AutoName):
|
||||
"""Enumeration used to declare types of HIM search modes."""
|
||||
|
||||
MATCH = auto()
|
||||
"Iterate over all trips to find HIM messages."
|
||||
|
||||
NOMATCH = auto()
|
||||
"Iterate over all HIM messages available."
|
||||
|
||||
TFMATCH = auto()
|
||||
"Uses filters defined `metas` parameter."
|
15
pyrmv/enums/selection_mode.py
Normal file
15
pyrmv/enums/selection_mode.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from enum import auto
|
||||
from .auto_name import AutoName
|
||||
|
||||
class SelectionMode(AutoName):
|
||||
"""Enumeration used to declare location selection modes.
|
||||
|
||||
* SLCT_A - Selectable
|
||||
* SLCT_N - Not selectable
|
||||
"""
|
||||
|
||||
SLCT_A = auto()
|
||||
"Selectable"
|
||||
|
||||
SLCT_N = auto()
|
||||
"Not selectable"
|
55
pyrmv/errors/api_errors.py
Normal file
55
pyrmv/errors/api_errors.py
Normal file
@@ -0,0 +1,55 @@
|
||||
class ApiAuthError(Exception):
|
||||
"""
|
||||
Access denied for accessId provided.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class ApiQuotaError(Exception):
|
||||
"""
|
||||
Quota exceeded for accessId provided.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class ApiTooManyRequests(Exception):
|
||||
"""
|
||||
Too many requests.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class ApiParamError(Exception):
|
||||
"""Exception raised for errors in the input arguments.
|
||||
|
||||
### Attributes:
|
||||
* errorCode: Client error code from HAFAS ReST Request Errors.
|
||||
* errorText: Description of an error occurred.
|
||||
"""
|
||||
|
||||
def __init__(self, errorCode: str, errorText: str):
|
||||
self.errorCode = errorCode
|
||||
self.errorText = errorText
|
||||
super().__init__(self.errorText)
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.errorCode} -> {self.errorText}'
|
||||
|
||||
class ApiFormatError(Exception):
|
||||
"""
|
||||
Response format not supported.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
29
pyrmv/errors/int_errors.py
Normal file
29
pyrmv/errors/int_errors.py
Normal file
@@ -0,0 +1,29 @@
|
||||
class IntError(Exception):
|
||||
"""
|
||||
Internal RMV server error.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class IntGatewayError(Exception):
|
||||
"""
|
||||
Communication error with RMV backend systems.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class IntTimeoutError(Exception):
|
||||
"""
|
||||
Timeout during service processing.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
9
pyrmv/errors/not_ready.py
Normal file
9
pyrmv/errors/not_ready.py
Normal file
@@ -0,0 +1,9 @@
|
||||
class NotReadyYetError(Exception):
|
||||
"""
|
||||
This method is not finished yet.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
13
pyrmv/errors/ps_errors.py
Normal file
13
pyrmv/errors/ps_errors.py
Normal file
@@ -0,0 +1,13 @@
|
||||
class PsIncorrectParamError(Exception):
|
||||
"""
|
||||
An invalid parameter combination was requested, i.e. the
|
||||
defined range of stable segments encompassed all public
|
||||
transport sections or it was attempted to search
|
||||
forward/backward from the end/beginning of the
|
||||
connection.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
49
pyrmv/errors/sot_errors.py
Normal file
49
pyrmv/errors/sot_errors.py
Normal file
@@ -0,0 +1,49 @@
|
||||
class SotAlreadyArrivedError(Exception):
|
||||
"""
|
||||
Trip already arrived.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SotNotStartedError(Exception):
|
||||
"""
|
||||
Trip not started.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SotCancelledError(Exception):
|
||||
"""
|
||||
Trip cancelled.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SotAllTrainsFilteredError(Exception):
|
||||
"""
|
||||
All trips filtered.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SotStayOnTripError(Exception):
|
||||
"""
|
||||
No change. Stay on trip.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
145
pyrmv/errors/svc_errors.py
Normal file
145
pyrmv/errors/svc_errors.py
Normal file
@@ -0,0 +1,145 @@
|
||||
class SvcParamError(Exception):
|
||||
"""Exception raised for errors in the input arguments.
|
||||
|
||||
### Attributes:
|
||||
* errorCode: Client error code from HAFAS ReST Request Errors.
|
||||
* errorText: Description of an error occurred.
|
||||
"""
|
||||
|
||||
def __init__(self, errorCode: str, errorText: str):
|
||||
self.errorCode = errorCode
|
||||
self.errorText = errorText
|
||||
super().__init__(self.errorText)
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.errorCode} -> {self.errorText}'
|
||||
|
||||
class SvcLocationError(Exception):
|
||||
"""
|
||||
Location missing or invalid.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcLocationArrivalError(Exception):
|
||||
"""
|
||||
Arrival location missing or invalid.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcLocationDepartureError(Exception):
|
||||
"""
|
||||
Departure location missing or invalid.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcLocationViaError(Exception):
|
||||
"""
|
||||
Unknown change stop.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcLocationEqualError(Exception):
|
||||
"""
|
||||
Origin/destination or vias are equal.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcLocationNearError(Exception):
|
||||
"""
|
||||
Origin and destination are too close.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcDatetimeError(Exception):
|
||||
"""
|
||||
Date/time are missing or invalid.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcDatetimePeriodError(Exception):
|
||||
"""
|
||||
Date/time are not in timetable or allowed period.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcProductError(Exception):
|
||||
"""
|
||||
Product field missing or invalid.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcContextError(Exception):
|
||||
"""
|
||||
Context is invalid.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcNoResultError(Exception):
|
||||
"""
|
||||
No result found.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcSearchError(Exception):
|
||||
"""
|
||||
Unsuccessful search.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
||||
|
||||
class SvcNoMatchError(Exception):
|
||||
"""
|
||||
No match found.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__(self.__doc__)
|
||||
|
||||
def __str__(self):
|
||||
return self.__doc__
|
15
pyrmv/errors/unknown_error.py
Normal file
15
pyrmv/errors/unknown_error.py
Normal file
@@ -0,0 +1,15 @@
|
||||
class UnknownError(Exception):
|
||||
"""Exception raised but error is not known.
|
||||
|
||||
### Attributes:
|
||||
* errorCode: Client error code from HAFAS ReST Request Errors.
|
||||
* errorText: Description of an error occurred.
|
||||
"""
|
||||
|
||||
def __init__(self, errorCode: str, errorText: str):
|
||||
self.errorCode = errorCode
|
||||
self.errorText = errorText
|
||||
super().__init__(self.errorText)
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.errorCode} -> {self.errorText}'
|
@@ -1,5 +1,6 @@
|
||||
from requests import get
|
||||
from typing import List, Union
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Union
|
||||
from xmltodict import parse as xmlparse
|
||||
|
||||
try:
|
||||
@@ -9,8 +10,53 @@ except ImportError:
|
||||
|
||||
# 2.25. Arrival Board (arrivalBoard)
|
||||
def board_arrival(accessId: str,
|
||||
json: bool = True
|
||||
json: bool = True,
|
||||
id: Union[str, None] = None,
|
||||
extId: Union[str, None] = None,
|
||||
direction: Union[str, None] = None,
|
||||
date: Union[str, datetime, None] = None,
|
||||
time: Union[str, datetime, None] = None,
|
||||
duration: Union[int, timedelta] = 60,
|
||||
maxJourneys: int = -1,
|
||||
products: Union[int, None] = None,
|
||||
operators: Union[str, list, None] = None,
|
||||
lines: Union[str, list, None] = None,
|
||||
filterEquiv: bool = True,
|
||||
attributes: Union[str, list, None] = None,
|
||||
platforms: Union[str, list, None] = None,
|
||||
passlist: bool = False,
|
||||
boardType: Literal["ARR", "ARR_EQUIVS", "ARR_MAST", "ARR_STATION"] = "ARR"
|
||||
) -> dict:
|
||||
"""The arrival board can be retrieved by a call to the arrivalBoard service. This method will return the next
|
||||
arrivals from a given point in time within a duration covered time span. The default duration size is 60 minutes.
|
||||
|
||||
Note: The result list always contains all arrivals running the the last minute found even if the requested
|
||||
maximum was overrun.
|
||||
|
||||
Read more about this in section 2.25. "Arrival Board (arrivalBoard)" of HAFAS ReST Documentation.
|
||||
|
||||
### Args:
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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:
|
||||
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
|
||||
"""
|
||||
|
||||
if json:
|
||||
headers = {"Accept": "application/json"}
|
||||
@@ -20,7 +66,28 @@ def board_arrival(accessId: str,
|
||||
payload = {}
|
||||
|
||||
for var, val in locals().items():
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
if str(var) == "date":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%Y-%m-%d")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "time":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%H:%M")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "duration":
|
||||
if val != None:
|
||||
if isinstance(val, timedelta):
|
||||
payload[str(var)] = val.minutes # type: ignore
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "boardType":
|
||||
if val != None:
|
||||
payload["type"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
@@ -1,5 +1,6 @@
|
||||
from requests import get
|
||||
from typing import List, Union
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Union
|
||||
from xmltodict import parse as xmlparse
|
||||
|
||||
try:
|
||||
@@ -9,8 +10,54 @@ except ImportError:
|
||||
|
||||
# 2.24. Departure Board (departureBoard)
|
||||
def board_departure(accessId: str,
|
||||
json: bool = True
|
||||
json: bool = True,
|
||||
id: Union[str, None] = None,
|
||||
extId: Union[str, None] = None,
|
||||
direction: Union[str, None] = None,
|
||||
date: Union[str, datetime, None] = None,
|
||||
time: Union[str, datetime, None] = None,
|
||||
duration: Union[int, timedelta] = 60,
|
||||
maxJourneys: int = -1,
|
||||
products: Union[int, None] = None,
|
||||
operators: Union[str, list, None] = None,
|
||||
lines: Union[str, list, None] = None,
|
||||
filterEquiv: bool = True,
|
||||
attributes: Union[str, list, None] = None,
|
||||
platforms: Union[str, list, None] = None,
|
||||
passlist: bool = False,
|
||||
boardType: Literal["DEP", "DEP_EQUIVS", "DEP_MAST", "DEP_STATION"] = "DEP"
|
||||
) -> dict:
|
||||
"""The separture board can be retrieved by a call to the departureBoard service. This method will return the
|
||||
next departures (or less if not existing) from a given point in time within a duration covered time span. The
|
||||
default duration size is 60 minutes.
|
||||
|
||||
Note: The result list always contains all departures running the the last minute found even if the requested
|
||||
maximum was overrun.
|
||||
|
||||
Read more about this in section 2.24. "Departure Board (departureBoard)" of HAFAS ReST Documentation.
|
||||
|
||||
### Args:
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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:
|
||||
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
|
||||
"""
|
||||
|
||||
if json:
|
||||
headers = {"Accept": "application/json"}
|
||||
@@ -20,7 +67,28 @@ def board_departure(accessId: str,
|
||||
payload = {}
|
||||
|
||||
for var, val in locals().items():
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
if str(var) == "date":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%Y-%m-%d")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "time":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%H:%M")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "duration":
|
||||
if val != None:
|
||||
if isinstance(val, timedelta):
|
||||
payload[str(var)] = val.minutes # type: ignore
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "boardType":
|
||||
if val != None:
|
||||
payload["type"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
@@ -1,8 +1,10 @@
|
||||
from requests import get
|
||||
from typing import Dict, Union
|
||||
from typing import OrderedDict, Union
|
||||
from xmltodict import parse as xmlparse
|
||||
from datetime import datetime
|
||||
|
||||
from pyrmv.utility.weekdays_bitmask import weekdays_bitmask
|
||||
|
||||
try:
|
||||
from typing import Literal
|
||||
except ImportError:
|
||||
@@ -11,38 +13,38 @@ except ImportError:
|
||||
# 2.37. HIM Search (himsearch)
|
||||
def him_search(accessId: str,
|
||||
json: bool = True,
|
||||
dateB: Union[str, datetime] = None,
|
||||
dateE: Union[str, datetime] = None,
|
||||
timeB: Union[str, datetime] = None,
|
||||
timeE: Union[str, datetime] = None,
|
||||
weekdays: Dict[str, bool] = None,
|
||||
himIds: Union[str, list] = None,
|
||||
dateB: Union[str, datetime, None] = None,
|
||||
dateE: Union[str, datetime, None] = None,
|
||||
timeB: Union[str, datetime, None] = None,
|
||||
timeE: Union[str, datetime, None] = None,
|
||||
weekdays: Union[str, OrderedDict[str, bool], None] = None,
|
||||
himIds: Union[str, list, None] = None,
|
||||
hierarchicalView: bool = False,
|
||||
operators: Union[str, list] = None,
|
||||
categories: Union[str, list] = None,
|
||||
channels: Union[str, list] = None,
|
||||
companies: Union[str, list] = None,
|
||||
lines: Union[str, list] = None,
|
||||
lineids: Union[str, list] = None,
|
||||
stations: Union[str, list] = None,
|
||||
fromstation: str = None,
|
||||
tostation: str = None,
|
||||
bothways: bool = None,
|
||||
trainnames: Union[str, list] = None,
|
||||
metas: Union[str, list] = None,
|
||||
himcategory: str = None,
|
||||
himtags: Union[str, list] = None,
|
||||
regions: Union[str, list] = None,
|
||||
himtext: Union[str, list] = None,
|
||||
himtexttags: Union[str, list] = None,
|
||||
additionalfields: Union[str, list] = None,
|
||||
operators: Union[str, list, None] = None,
|
||||
categories: Union[str, list, None] = None,
|
||||
channels: Union[str, list, None] = None,
|
||||
companies: Union[str, list, None] = None,
|
||||
lines: Union[str, list, None] = None,
|
||||
lineids: Union[str, list, None] = None,
|
||||
stations: Union[str, list, None] = None,
|
||||
fromstation: Union[str, None] = None,
|
||||
tostation: Union[str, None] = None,
|
||||
bothways: Union[bool, None] = None,
|
||||
trainnames: Union[str, list, None] = None,
|
||||
metas: Union[str, list, None] = None,
|
||||
himcategory: Union[str, None] = None,
|
||||
himtags: Union[str, list, None] = None,
|
||||
regions: Union[str, list, None] = None,
|
||||
himtext: Union[str, list, None] = None,
|
||||
himtexttags: Union[str, list, None] = None,
|
||||
additionalfields: Union[str, list, dict, None] = None,
|
||||
poly: bool = False,
|
||||
searchmode: Literal["MATCH", "NOMATCH", "TFMATCH"] = None,
|
||||
affectedJourneyMode: Literal["ALL", "OFF"] = None,
|
||||
affectedJourneyStopMode: Literal["ALL", "IMP", "OFF"] = None,
|
||||
orderBy: Union[str, list] = None,
|
||||
minprio: Union[str, int] = None,
|
||||
maxprio: Union[str, int] = None
|
||||
searchmode: Union[Literal["MATCH", "NOMATCH", "TFMATCH"], None] = None,
|
||||
affectedJourneyMode: Union[Literal["ALL", "OFF"], None] = None,
|
||||
affectedJourneyStopMode: Union[Literal["ALL", "IMP", "OFF"], None] = None,
|
||||
orderBy: Union[str, list, None] = None,
|
||||
minprio: Union[str, int, None] = None,
|
||||
maxprio: Union[str, int, None] = None
|
||||
) -> dict:
|
||||
"""The himSearch will return a list of HIM messages if matched by the given criteria as well as affected
|
||||
products if any.
|
||||
@@ -50,40 +52,40 @@ def him_search(accessId: str,
|
||||
Read more about this in section 2.37. "HIM Search (himsearch)" of HAFAS ReST Documentation.
|
||||
|
||||
### Args:
|
||||
* accessId (str): _description_
|
||||
* json (bool, optional): _description_. Defaults to True.
|
||||
* dateB (Union[str, datetime], optional): _description_. Defaults to None.
|
||||
* dateE (Union[str, datetime], optional): _description_. Defaults to None.
|
||||
* timeB (Union[str, datetime], optional): _description_. Defaults to None.
|
||||
* timeE (Union[str, datetime], optional): _description_. Defaults to None.
|
||||
* weekdays (Dict[str, bool], optional): _description_. Defaults to None.
|
||||
* himIds (Union[str, list], optional): _description_. Defaults to None.
|
||||
* hierarchicalView (bool, optional): _description_. Defaults to False.
|
||||
* operators (Union[str, list], optional): _description_. Defaults to None.
|
||||
* categories (Union[str, list], optional): _description_. Defaults to None.
|
||||
* channels (Union[str, list], optional): _description_. Defaults to None.
|
||||
* companies (Union[str, list], optional): _description_. Defaults to None.
|
||||
* lines (Union[str, list], optional): _description_. Defaults to None.
|
||||
* lineids (Union[str, list], optional): _description_. Defaults to None.
|
||||
* stations (Union[str, list], optional): _description_. Defaults to None.
|
||||
* fromstation (str, optional): _description_. Defaults to None.
|
||||
* tostation (str, optional): _description_. Defaults to None.
|
||||
* bothways (bool, optional): _description_. Defaults to None.
|
||||
* trainnames (Union[str, list], optional): _description_. Defaults to None.
|
||||
* metas (Union[str, list], optional): _description_. Defaults to None.
|
||||
* himcategory (str, optional): _description_. Defaults to None.
|
||||
* himtags (Union[str, list], optional): _description_. Defaults to None.
|
||||
* regions (Union[str, list], optional): _description_. Defaults to None.
|
||||
* himtext (Union[str, list], optional): _description_. Defaults to None.
|
||||
* himtexttags (Union[str, list], optional): _description_. Defaults to None.
|
||||
* additionalfields (Union[str, list], optional): _description_. Defaults to None.
|
||||
* poly (bool, optional): _description_. Defaults to False.
|
||||
* searchmode (Literal["MATCH", "NOMATCH", "TFMATCH"], optional): _description_. Defaults to None.
|
||||
* affectedJourneyMode (Literal["ALL", "OFF"], optional): _description_. Defaults to None.
|
||||
* affectedJourneyStopMode (Literal["ALL", "IMP", "OFF"], optional): _description_. Defaults to None.
|
||||
* orderBy (Union[str, list], optional): _description_. Defaults to None.
|
||||
* minprio (Union[str, int], optional): _description_. Defaults to None.
|
||||
* maxprio (Union[str, int], optional): _description_. Defaults to None.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
|
||||
### Returns:
|
||||
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
|
||||
@@ -109,6 +111,21 @@ def him_search(accessId: str,
|
||||
payload[str(var)] = val.strftime("%H:%M")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "weekdays":
|
||||
if val != None:
|
||||
if isinstance(val, OrderedDict):
|
||||
payload[str(var)] = weekdays_bitmask(val)
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "searchmode":
|
||||
if val != None:
|
||||
payload["searchmode"] = val.upper()
|
||||
elif str(var) == "affectedJourneyMode":
|
||||
if val != None:
|
||||
payload["affectedJourneyMode"] = val.upper()
|
||||
elif str(var) == "affectedJourneyStopMode":
|
||||
if val != None:
|
||||
payload["affectedJourneyStopMode"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
@@ -1,5 +1,6 @@
|
||||
from datetime import datetime
|
||||
from requests import get
|
||||
from typing import List, Union
|
||||
from typing import Union
|
||||
from xmltodict import parse as xmlparse
|
||||
|
||||
try:
|
||||
@@ -9,8 +10,44 @@ except ImportError:
|
||||
|
||||
# 2.26. Journey Detail (journeyDetail)
|
||||
def journey_detail(accessId: str,
|
||||
json: bool = True
|
||||
id: str,
|
||||
json: bool = True,
|
||||
date: Union[str, datetime, None] = None,
|
||||
poly: bool = False,
|
||||
polyEnc: Literal["DLT", "GPA", "N"] = "N",
|
||||
showPassingPoints: bool = False,
|
||||
rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None,
|
||||
fromId: Union[str, None] = None,
|
||||
fromIdx: Union[int, None] = None,
|
||||
toId: Union[str, None] = None,
|
||||
toIdx: Union[int, None] = None,
|
||||
baim: bool = False
|
||||
) -> dict:
|
||||
"""The journey_detail method will deliver information about the complete route of a vehicle. The journey
|
||||
identifier is part of a trip or departureBoard response. It contains a list of all stops/stations of this journey
|
||||
including all departure and arrival times (with real-time data if available) and additional information like
|
||||
specific attributes about facilities and other texts.
|
||||
|
||||
Read more about this in section 2.26. "Journey Detail (journeyDetail)" of HAFAS ReST Documentation.
|
||||
|
||||
### Args:
|
||||
* 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.
|
||||
* 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.
|
||||
* 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".
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* baim (bool, optional): Enables/disables BAIM search and response. Defaults to False.
|
||||
|
||||
### Returns:
|
||||
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
|
||||
"""
|
||||
|
||||
if json:
|
||||
headers = {"Accept": "application/json"}
|
||||
@@ -20,7 +57,10 @@ def journey_detail(accessId: str,
|
||||
payload = {}
|
||||
|
||||
for var, val in locals().items():
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
if str(var) == "rtMode":
|
||||
if val != None:
|
||||
payload["rtMode"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
@@ -16,11 +16,11 @@ def stop_by_coords(accessId: str,
|
||||
radius: Union[int, float] = 1000,
|
||||
maxNo: int = 10,
|
||||
stopType: Literal["S", "P", "SP", "SE", "SPE"] = "S",
|
||||
locationSelectionMode: Literal["SLCT_N", "SLCT_A"] = None,
|
||||
products: int = None,
|
||||
meta: str = None,
|
||||
sattributes: Union[str, list] = None,
|
||||
sinfotexts: Union[str, list] = None
|
||||
locationSelectionMode: Union[Literal["SLCT_N", "SLCT_A"], None] = None,
|
||||
products: Union[int, None] = None,
|
||||
meta: Union[str, None] = None,
|
||||
sattributes: Union[str, list, None] = None,
|
||||
sinfotexts: Union[str, list, None] = None
|
||||
) -> dict:
|
||||
"""The location.nearbystops service returns a list of stops around a given center coordinate (within a
|
||||
radius of 1000m). The returned results are ordered by their distance to the center coordinate.
|
||||
@@ -32,7 +32,7 @@ def stop_by_coords(accessId: str,
|
||||
* originCoordLat (Union[str, float]): Latitude 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".
|
||||
* 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. 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.
|
||||
* 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".
|
||||
@@ -54,7 +54,13 @@ def stop_by_coords(accessId: str,
|
||||
payload = {}
|
||||
|
||||
for var, val in locals().items():
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
if str(var) == "stopType":
|
||||
if val != None:
|
||||
payload["type"] = val.upper()
|
||||
elif str(var) == "locationSelectionMode":
|
||||
if val != None:
|
||||
payload["locationSelectionMode"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload", "raw_response"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
@@ -14,15 +14,15 @@ def stop_by_name(accessId: str,
|
||||
json: bool = True,
|
||||
maxNo: int = 10,
|
||||
stopType: Literal["A", "ALL", "AP", "P", "S", "SA", "SP"] = "ALL",
|
||||
locationSelectionMode: Literal["SLCT_N", "SLCT_A"] = None,
|
||||
products: int = None,
|
||||
coordLat: Union[str, float] = None,
|
||||
coordLong: Union[str, float] = None,
|
||||
locationSelectionMode: Union[Literal["SLCT_N", "SLCT_A"], None] = None,
|
||||
products: Union[int, None] = None,
|
||||
coordLat: Union[str, float, None] = None,
|
||||
coordLong: Union[str, float, None] = None,
|
||||
radius: Union[int, float] = 1000,
|
||||
refineId: str = None,
|
||||
meta: str = None,
|
||||
stations: Union[str, list] = None,
|
||||
sattributes: Union[str, list] = None,
|
||||
refineId: Union[str, None] = None,
|
||||
meta: Union[str, None] = None,
|
||||
stations: Union[str, list, None] = None,
|
||||
sattributes: Union[str, list, None] = None,
|
||||
filterMode: Literal["DIST_PERI", "EXCL_PERI", "SLCT_PERI"] = "DIST_PERI"
|
||||
) -> dict:
|
||||
"""The location.name service can be used to perform a pattern matching of a user input and to retrieve a list
|
||||
@@ -39,7 +39,7 @@ def stop_by_name(accessId: str,
|
||||
* 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.
|
||||
* 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. 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.
|
||||
* 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.
|
||||
@@ -68,7 +68,13 @@ def stop_by_name(accessId: str,
|
||||
if str(var) == "inputString":
|
||||
if val != None:
|
||||
payload["input"] = val
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
elif str(var) == "stopType":
|
||||
if val != None:
|
||||
payload["type"] = val.upper()
|
||||
elif str(var) == "filterMode":
|
||||
if val != None:
|
||||
payload["filterMode"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload", "raw_response", "stopType"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
@@ -1,3 +1,4 @@
|
||||
from datetime import datetime
|
||||
from requests import get
|
||||
from typing import List, Union
|
||||
from xmltodict import parse as xmlparse
|
||||
@@ -12,87 +13,87 @@ def trip_find(accessId: str,
|
||||
lang: Literal["de", "da", "en", "es", "fr", "hu", "it", "nl", "no", "pl", "sv", "tr"] = "en",
|
||||
json: bool = True,
|
||||
|
||||
originId: str = None,
|
||||
originExtId: str = None,
|
||||
originCoordLat: Union[str, float] = None,
|
||||
originCoordLong: Union[str, float] = None,
|
||||
originCoordName: str = None,
|
||||
originId: Union[str, None] = None,
|
||||
originExtId: Union[str, None] = None,
|
||||
originCoordLat: Union[str, float, None] = None,
|
||||
originCoordLong: Union[str, float, None] = None,
|
||||
originCoordName: Union[str, None] = None,
|
||||
|
||||
destId: str = None,
|
||||
destExtId: str = None,
|
||||
destCoordLat: Union[str, float] = None,
|
||||
destCoordLong: Union[str, float] = None,
|
||||
destCoordName: str = None,
|
||||
destId: Union[str, None] = None,
|
||||
destExtId: Union[str, None] = None,
|
||||
destCoordLat: Union[str, float, None] = None,
|
||||
destCoordLong: Union[str, float, None] = None,
|
||||
destCoordName: Union[str, None] = None,
|
||||
|
||||
via: str = None,
|
||||
viaId: str = None,
|
||||
via: Union[str, None] = None,
|
||||
viaId: Union[str, None] = None,
|
||||
viaWaitTime: int = 0,
|
||||
|
||||
avoid: str = None,
|
||||
avoidId: str = None,
|
||||
avoid: Union[str, None] = None,
|
||||
avoidId: Union[str, None] = None,
|
||||
|
||||
viaGis: str = None,
|
||||
viaGis: Union[str, None] = None,
|
||||
|
||||
changeTimePercent: int = 100,
|
||||
minChangeTime: int = None,
|
||||
maxChangeTime: int = None,
|
||||
addChangeTime: int = None,
|
||||
maxChange: int = None,
|
||||
minChangeTime: Union[int, None] = None,
|
||||
maxChangeTime: Union[int, None] = None,
|
||||
addChangeTime: Union[int, None] = None,
|
||||
maxChange: Union[int, None] = None,
|
||||
|
||||
date: str = None,
|
||||
time: str = None,
|
||||
date: Union[str, datetime, None] = None,
|
||||
time: Union[str, datetime, None] = None,
|
||||
|
||||
searchForArrival: bool = False,
|
||||
|
||||
numF: int = None,
|
||||
numB: int = None,
|
||||
numF: Union[int, None] = None,
|
||||
numB: Union[int, None] = None,
|
||||
|
||||
context: str = None,
|
||||
context: Union[str, None] = None,
|
||||
|
||||
poly: bool = False,
|
||||
polyEnc: Literal["DLT", "GPA", "N"] = "N",
|
||||
|
||||
passlist: bool = False,
|
||||
products: str = None,
|
||||
operators: Union[str, list] = None,
|
||||
products: Union[int, None] = None,
|
||||
operators: Union[str, list, None] = None,
|
||||
|
||||
attributes: Union[str, list] = None,
|
||||
sattributes: Union[str, list] = None,
|
||||
fattributes: Union[str, list] = None,
|
||||
lines: Union[str, list] = None,
|
||||
lineids: Union[str, list] = None,
|
||||
attributes: Union[str, list, None] = None,
|
||||
sattributes: Union[str, list, None] = None,
|
||||
fattributes: Union[str, list, None] = None,
|
||||
lines: Union[str, list, None] = None,
|
||||
lineids: Union[str, list, None] = None,
|
||||
|
||||
avoidPaths: List[Literal["SW", "EA", "ES", "RA", "CB"]] = None,
|
||||
avoidPaths: Union[List[Literal["SW", "EA", "ES", "RA", "CB"]], None] = None,
|
||||
|
||||
originWalk: Union[str, list] = None,
|
||||
originBike: Union[str, list] = None,
|
||||
originCar: Union[str, list] = None,
|
||||
originTaxi: Union[str, list] = None,
|
||||
originPark: Union[str, list] = None,
|
||||
originMeta: Union[str, list] = None,
|
||||
originWalk: Union[str, list, None] = None,
|
||||
originBike: Union[str, list, None] = None,
|
||||
originCar: Union[str, list, None] = None,
|
||||
originTaxi: Union[str, list, None] = None,
|
||||
originPark: Union[str, list, None] = None,
|
||||
originMeta: Union[str, list, None] = None,
|
||||
|
||||
destWalk: Union[str, list] = None,
|
||||
destBike: Union[str, list] = None,
|
||||
destCar: Union[str, list] = None,
|
||||
destTaxi: Union[str, list] = None,
|
||||
destPark: Union[str, list] = None,
|
||||
destMeta: Union[str, list] = None,
|
||||
destWalk: Union[str, list, None] = None,
|
||||
destBike: Union[str, list, None] = None,
|
||||
destCar: Union[str, list, None] = None,
|
||||
destTaxi: Union[str, list, None] = None,
|
||||
destPark: Union[str, list, None] = None,
|
||||
destMeta: Union[str, list, None] = None,
|
||||
|
||||
totalWalk: Union[str, list] = None,
|
||||
totalBike: Union[str, list] = None,
|
||||
totalCar: Union[str, list] = None,
|
||||
totalTaxi: Union[str, list] = None,
|
||||
totalMeta: Union[str, list] = None,
|
||||
totalWalk: Union[str, list, None] = None,
|
||||
totalBike: Union[str, list, None] = None,
|
||||
totalCar: Union[str, list, None] = None,
|
||||
totalTaxi: Union[str, list, None] = None,
|
||||
totalMeta: Union[str, list, None] = None,
|
||||
|
||||
gisProducts: str = None,
|
||||
gisProducts: Union[str, None] = None,
|
||||
|
||||
includeIv: bool = False,
|
||||
ivOnly: bool = False,
|
||||
|
||||
mobilityProfile: str = None,
|
||||
mobilityProfile: Union[str, None] = None,
|
||||
|
||||
bikeCarriage: bool = False,
|
||||
bikeCarriageType: Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"] = None,
|
||||
bikeCarriageType: Union[Literal["SINGLEBIKES", "SMALLGROUPS", "LARGEGROUPS"], None] = None,
|
||||
|
||||
sleepingCar: bool = False,
|
||||
couchetteCoach: bool = False,
|
||||
@@ -101,24 +102,24 @@ def trip_find(accessId: str,
|
||||
|
||||
eco: bool = False,
|
||||
ecoCmp: bool = False,
|
||||
ecoParams: str = None,
|
||||
ecoParams: Union[str, None] = None,
|
||||
|
||||
rtMode: Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"] = None,
|
||||
rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None,
|
||||
|
||||
unsharp: bool = False,
|
||||
trainFilter: str = None,
|
||||
trainFilter: Union[str, None] = None,
|
||||
economic: bool = False,
|
||||
groupFilter: str = None,
|
||||
groupFilter: Union[str, None] = None,
|
||||
|
||||
blockingList: str = None,
|
||||
blockedEdges: str = None,
|
||||
blockingList: Union[str, None] = None,
|
||||
blockedEdges: Union[str, None] = None,
|
||||
|
||||
trainComposition: bool = False,
|
||||
includeEarlier: bool = False,
|
||||
withICTAlternatives: bool = False,
|
||||
tariff: bool = None,
|
||||
tariff: Union[bool, None] = None,
|
||||
trafficMessages: bool = False,
|
||||
travellerProfileData: str = None,
|
||||
travellerProfileData: Union[str, None] = None,
|
||||
withFreq: bool = True
|
||||
) -> dict:
|
||||
"""The trip service calculates a trip from a specified origin to a specified destination. These might be
|
||||
@@ -152,8 +153,8 @@ def trip_find(accessId: str,
|
||||
* 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.
|
||||
* maxChange (int, optional): Maximum number of changes. In range 0-11. Defaults to None.
|
||||
* date (str, 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 (str, 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
@@ -169,22 +170,22 @@ def trip_find(accessId: str,
|
||||
* 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.
|
||||
* 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. 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. 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. 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. 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. 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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. 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. 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. 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. 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. 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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. 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. 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. 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. 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* includeIv (bool, optional): Enables/disables search for individual transport routes. Defaults to False.
|
||||
@@ -226,7 +227,22 @@ def trip_find(accessId: str,
|
||||
payload = {}
|
||||
|
||||
for var, val in locals().items():
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
if str(var) == "date":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%Y-%m-%d")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "time":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%H:%M")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) == "rtMode":
|
||||
if val != None:
|
||||
payload["rtMode"] = val.upper()
|
||||
elif str(var) not in ["json", "headers", "payload"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
@@ -1,5 +1,6 @@
|
||||
from datetime import datetime
|
||||
from requests import get
|
||||
from typing import List, Union
|
||||
from typing import Union
|
||||
from xmltodict import parse as xmlparse
|
||||
|
||||
try:
|
||||
@@ -9,8 +10,77 @@ except ImportError:
|
||||
|
||||
# 2.17. Reconstruction (recon)
|
||||
def trip_recon(accessId: str,
|
||||
json: bool = True
|
||||
ctx: str,
|
||||
json: bool = True,
|
||||
poly: bool = False,
|
||||
polyEnc: Literal["DLT", "GPA", "N"] = "N",
|
||||
date: Union[str, datetime, None] = None,
|
||||
useCombinedComparison: Union[bool, None] = None,
|
||||
acceptGaps: Union[bool, None] = None,
|
||||
allowDummySections: Union[bool, None] = None,
|
||||
flagAllNonReachable: Union[bool, None] = None,
|
||||
matchCatStrict: Union[bool, None] = None,
|
||||
matchIdNonBlank: Union[bool, None] = None,
|
||||
matchIdStrict: Union[bool, None] = None,
|
||||
matchNumStrict: Union[bool, None] = None,
|
||||
matchRtType: Union[bool, None] = None,
|
||||
enableRtFullSearch: Union[bool, None] = None,
|
||||
enableReplacements: Union[bool, None] = None,
|
||||
arrL: Union[int, None] = None,
|
||||
arrU: Union[int, None] = None,
|
||||
depL: Union[int, None] = None,
|
||||
depU: Union[int, None] = None,
|
||||
passlist: bool = False,
|
||||
showPassingPoints: bool = False,
|
||||
rtMode: Union[Literal["FULL", "INFOS", "OFF", "REALTIME", "SERVER_DEFAULT"], None] = None,
|
||||
eco: bool = False,
|
||||
ecoCmp: bool = False,
|
||||
ecoParams: Union[str, None] = None,
|
||||
tariff: Union[bool, None] = None,
|
||||
trafficMessages: Union[bool, None] = None,
|
||||
travellerProfileData: Union[str, None] = None
|
||||
) -> dict:
|
||||
"""Reconstructing a trip can be achieved using the reconstruction context provided by any trip result in the
|
||||
ctxRecon attribute of Trip element. The result will be a true copy of the original trip search result given
|
||||
that the underlying data did not change.
|
||||
|
||||
Read more about this in section 2.17. "Reconstruction (recon)" of HAFAS ReST Documentation.
|
||||
|
||||
### Args:
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* 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.
|
||||
* eco (bool, optional): Enables/disables eco value calculation. 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.
|
||||
* 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.
|
||||
* travellerProfileData (str, optional): Traveller profile data. Structure depends on set up. Defaults to None.
|
||||
|
||||
### Returns:
|
||||
* dict: Output from RMV. Dict will contain "errorCode" and "errorText" if exception occurs.
|
||||
"""
|
||||
|
||||
if json:
|
||||
headers = {"Accept": "application/json"}
|
||||
@@ -20,7 +90,13 @@ def trip_recon(accessId: str,
|
||||
payload = {}
|
||||
|
||||
for var, val in locals().items():
|
||||
if str(var) not in ["json", "headers", "payload"]:
|
||||
if str(var) == "date":
|
||||
if val != None:
|
||||
if isinstance(val, datetime):
|
||||
payload[str(var)] = val.strftime("%Y-%m-%d")
|
||||
else:
|
||||
payload[str(var)] = val
|
||||
elif str(var) not in ["json", "headers", "payload"]:
|
||||
if val != None:
|
||||
payload[str(var)] = val
|
||||
|
||||
|
0
pyrmv/utility/__init__.py
Normal file
0
pyrmv/utility/__init__.py
Normal file
102
pyrmv/utility/find_exception.py
Normal file
102
pyrmv/utility/find_exception.py
Normal file
@@ -0,0 +1,102 @@
|
||||
from pyrmv.errors.api_errors import ApiAuthError, ApiFormatError, ApiParamError, ApiQuotaError, ApiTooManyRequests
|
||||
from pyrmv.errors.int_errors import IntError, IntGatewayError, IntTimeoutError
|
||||
from pyrmv.errors.ps_errors import PsIncorrectParamError
|
||||
from pyrmv.errors.sot_errors import SotAllTrainsFilteredError, SotAlreadyArrivedError, SotCancelledError, SotNotStartedError, SotStayOnTripError
|
||||
from pyrmv.errors.svc_errors import SvcContextError, SvcDatetimeError, SvcDatetimePeriodError, SvcLocationArrivalError, SvcLocationDepartureError, SvcLocationEqualError, SvcLocationError, SvcLocationNearError, SvcLocationViaError, SvcNoMatchError, SvcNoResultError, SvcProductError, SvcSearchError
|
||||
from pyrmv.errors.unknown_error import UnknownError
|
||||
|
||||
def find_exception(data: dict):
|
||||
"""Scan returned dict for errorCode from RMV.
|
||||
Raises different exceptions if errorCode is not None.
|
||||
|
||||
### Args:
|
||||
* data (dict): Response from RMV as a dict.
|
||||
|
||||
### Raises:
|
||||
* Any: Formatted as "errorCode -> errorText" if ApiParamError and UnknownError or as a single massage for others.
|
||||
"""
|
||||
if "errorCode" in data:
|
||||
|
||||
if data["errorCode"] == "API_AUTH":
|
||||
raise ApiAuthError()
|
||||
|
||||
elif data["errorCode"] == "API_QUOTA":
|
||||
raise ApiQuotaError()
|
||||
|
||||
elif data["errorCode"] == "API_TOO_MANY_REQUESTS":
|
||||
raise ApiTooManyRequests()
|
||||
|
||||
elif data["errorCode"] == "API_PARAM":
|
||||
raise ApiParamError(errorCode=data["errorCode"], errorText=data["errorText"])
|
||||
|
||||
elif data["errorCode"] == "API_FORMAT":
|
||||
raise ApiFormatError()
|
||||
|
||||
elif data["errorCode"] == "SVC_LOC":
|
||||
raise SvcLocationError()
|
||||
|
||||
elif data["errorCode"] == "SVC_LOC_ARR":
|
||||
raise SvcLocationArrivalError()
|
||||
|
||||
elif data["errorCode"] == "SVC_LOC_DEP":
|
||||
raise SvcLocationDepartureError()
|
||||
|
||||
elif data["errorCode"] == "SVC_LOC_VIA":
|
||||
raise SvcLocationViaError()
|
||||
|
||||
elif data["errorCode"] == "SVC_LOC_EQUAL":
|
||||
raise SvcLocationEqualError()
|
||||
|
||||
elif data["errorCode"] == "SVC_LOC_NEAR":
|
||||
raise SvcLocationNearError()
|
||||
|
||||
elif data["errorCode"] == "SVC_DATATIME":
|
||||
raise SvcDatetimeError()
|
||||
|
||||
elif data["errorCode"] == "SVC_DATATIME_PERIOD":
|
||||
raise SvcDatetimePeriodError()
|
||||
|
||||
elif data["errorCode"] == "SVC_PROD":
|
||||
raise SvcProductError()
|
||||
|
||||
elif data["errorCode"] == "SVC_CTX":
|
||||
raise SvcContextError()
|
||||
|
||||
elif data["errorCode"] == "SVC_NO_RESULT":
|
||||
raise SvcNoResultError()
|
||||
|
||||
elif data["errorCode"] == "SVC_FAILED_SEARCH":
|
||||
raise SvcSearchError()
|
||||
|
||||
elif data["errorCode"] == "SVC_NO_MATCH":
|
||||
raise SvcNoMatchError()
|
||||
|
||||
elif data["errorCode"] == "INT_ERR":
|
||||
raise IntError()
|
||||
|
||||
elif data["errorCode"] == "INT_GATEWAY":
|
||||
raise IntGatewayError()
|
||||
|
||||
elif data["errorCode"] == "INT_TIMEOUT":
|
||||
raise IntTimeoutError()
|
||||
|
||||
elif data["errorCode"] == "SOT_AT_DEST":
|
||||
raise SotAlreadyArrivedError()
|
||||
|
||||
elif data["errorCode"] == "SOT_BEFORE_START":
|
||||
raise SotNotStartedError()
|
||||
|
||||
elif data["errorCode"] == "SOT_CANCELLED":
|
||||
raise SotCancelledError()
|
||||
|
||||
elif data["errorCode"] == "SOT_ALL_TRAINS_FILTERED":
|
||||
raise SotAllTrainsFilteredError()
|
||||
|
||||
elif data["errorCode"] == "SOT_STAY_IN_CURRENT_CONNECTION":
|
||||
raise SotStayOnTripError()
|
||||
|
||||
elif data["errorCode"] == "PARTIALSEARCH_INCORRECT_PARAM":
|
||||
raise PsIncorrectParamError()
|
||||
|
||||
else:
|
||||
raise UnknownError(errorCode=data["errorCode"], errorText=data["errorText"])
|
21
pyrmv/utility/weekdays_bitmask.py
Normal file
21
pyrmv/utility/weekdays_bitmask.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from typing import OrderedDict
|
||||
|
||||
|
||||
def weekdays_bitmask(data: OrderedDict[str, bool]) -> str:
|
||||
"""Convert ordered dict with weekdays to a bitmask.
|
||||
|
||||
### Args:
|
||||
* data (OrderedDict[str, bool]): OrderedDict formatted as follows: OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)
|
||||
|
||||
### Returns:
|
||||
* str: _description_
|
||||
"""
|
||||
output = ""
|
||||
if len(data) != 7:
|
||||
raise ValueError("OrderedDict must be formatted as follows: OrderedDict(Monday=bool, Tuesday=bool, Wednesday=bool, Thursday=bool, Friday=bool, Saturday=bool, Sunday=bool)")
|
||||
for day in data:
|
||||
if data[day]:
|
||||
output += "1"
|
||||
else:
|
||||
output += "0"
|
||||
return output
|
@@ -1,2 +1,3 @@
|
||||
requests
|
||||
xmltodict
|
||||
requests~=2.31.0
|
||||
xmltodict~=0.13.0
|
||||
isodate~=0.6.1
|
22
setup.py
22
setup.py
@@ -2,10 +2,10 @@ from setuptools import setup
|
||||
|
||||
setup(
|
||||
name="pyrmv",
|
||||
version="0.1.8",
|
||||
version="0.3.5",
|
||||
author="Profitroll",
|
||||
description="Small module that makes your journey with RMV REST API somehow easier.",
|
||||
long_description="Small module that makes your journey with RMV REST API somehow easier. Based fully on official RMV API reference and HAFAS documentation.\n\n# Frequently Asked Questions\n\n- [Why are there raw versions and formatted ones?](#why-are-there-raw-versions-and-formatted-ones)\n- [Some methods work slightly different](#some-methods-work-slightly-different)\n- [Documentation is not perfectly clear](#documentation-is-not-perfectly-clear)\n\n## Why are there raw versions and formatted ones?\n\nFor the purposes of my projects I don't really need all the stuff RMV gives (even though it's not much).\nI only need some specific things. However I do understand that in some cases other users may find\nthose methods quite useful so I implemented them as well.\n\n\n## Some methods work slightly different\n\nCan be. Not all function arguments written may work perfectly because I simply did not test each and\nevery request. Some of arguments may be irrelevant in my use-case and the others are used quite rare at all.\nJust [make an issue](https://git.end-play.xyz/profitroll/PythonRMV/issues/new) and I'll implement it correct when I'll have some free time.\n\n## Documentation is not perfectly clear\n\nOf course docs cannot be perfect as a python docstring, especially if sometimes I don't\nknow how things should correctly work. That's why you get HAFAS API docs in addition to your\nRMV API key. Just use my functions together with those docs, if you want to build something\nreally sophisticated. However I'm not sure whether RMV supports that many HAFAS features publicly.\n\n# To-Do\n- [ ] arrivalBoard (boardArrival) \n- [ ] departureBoard (boardArrival) \n- [x] himsearch (himSearch) \n- [ ] journeyDetail \n- [x] location.nearbystops (stopByCoords) \n- [x] location.name (stopByName) \n- [ ] recon \n- [x] trip (findRoute)",
|
||||
long_description="Small module that makes your journey with RMV REST API somehow easier. Based fully on official RMV API reference and HAFAS documentation.\n\n## Requirements\n\n* RMV API key (Get it [here](https://opendata.rmv.de/site/start.html))\n* Python3 (Tested versions are 3.7.9 and 3.9.13)\n* git (Only for installation from source)\n\n## Installation\n\nIf you have everything listed in [requirements](#requirements), then let's begin.\n\n### Variant 1\n\n1. `python -m pip install pyrmv`\n\n### Variant 2\n\n1. `git clone https://git.end-play.xyz/profitroll/PythonRMV.git`\n2. `cd PythonRMV`\n3. `python setup.py install`\n\n## Usage\n\n```py\nimport pyrmv\n\n# Define a Client with API key\nclient = pyrmv.Client(\"AcessId\")\n\n# Get origin's and destination's location\norigin = client.stop_by_name(\"Frankfurt Hauptbahnhof\", max_number=3)[0]\ndestination = client.stop_by_coords(50.099613, 8.685449, max_number=3)[0]\n\n# Find a trip by locations got\ntrip = client.trip_find(origin_id=origin.id, dest_id=destination.id)\n```\n\n## Frequently Asked Questions\n\n* [Why are there raw versions and formatted ones?](#why-are-there-raw-versions-and-formatted-ones)\n* [Some methods work slightly different](#some-methods-work-slightly-different)\n\n### Why are there raw versions and formatted ones?\n\nFor the purposes of my projects I don't really need all the stuff RMV gives (even though it's not much).\nI only need some specific things. However I do understand that in some cases other users may find\nthose methods quite useful so I implemented them as well.\n\n### Some methods work slightly different\n\nCan be. Not all function arguments written may work perfectly because I simply did not test each and\nevery request. Some of arguments may be irrelevant in my use-case and the others are used quite rare at all.\nJust [make an issue](https://git.end-play.xyz/profitroll/PythonRMV/issues/new) and I'll implement it correct when I'll have some free time.\n\n## To-Do\n\n### General\n\n* [ ] Docs in Wiki\n* [ ] Tickets",
|
||||
long_description_content_type="text/markdown",
|
||||
author_email="profitroll@end-play.xyz",
|
||||
url="https://git.end-play.xyz/profitroll/PythonRMV",
|
||||
@@ -16,19 +16,21 @@ setup(
|
||||
},
|
||||
packages=[
|
||||
"pyrmv",
|
||||
"pyrmv.raw"
|
||||
],
|
||||
install_requires=[
|
||||
"requests",
|
||||
"xmltodict"
|
||||
"pyrmv.raw",
|
||||
"pyrmv.const",
|
||||
"pyrmv.enums",
|
||||
"pyrmv.errors",
|
||||
"pyrmv.utility",
|
||||
"pyrmv.classes",
|
||||
],
|
||||
install_requires=["requests", "xmltodict", "isodate"],
|
||||
classifiers=[
|
||||
"Development Status :: 1 - Planning",
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
"Topic :: Utilities"
|
||||
]
|
||||
"Topic :: Utilities",
|
||||
],
|
||||
)
|
82
test.py
Normal file
82
test.py
Normal file
@@ -0,0 +1,82 @@
|
||||
from datetime import datetime, timedelta
|
||||
from os import makedirs
|
||||
from typing import Any
|
||||
from ujson import loads, dumps, JSONDecodeError
|
||||
from test_colors import *
|
||||
|
||||
import pyrmv
|
||||
|
||||
try:
|
||||
with open("test_key.json", mode="r", encoding="utf-8") as file:
|
||||
key = loads(file.read())["key"]
|
||||
file.close()
|
||||
except FileNotFoundError:
|
||||
key = input("File 'test_key.json' does not exist. Enter your RMV API key to continue: ").strip()
|
||||
key_save = input("To skip entering your key every time I can save your apikey here. Should I do that? (Y/n) > ").strip().lower()
|
||||
if key_save == "y":
|
||||
try:
|
||||
with open("test_key.json", mode="w", encoding="utf-8") as file:
|
||||
file.write(dumps({"key": key}))
|
||||
file.close()
|
||||
except Exception as exp:
|
||||
print(f"Could not save 'test_key.json' with your apikey due to {exp}", flush=True)
|
||||
else:
|
||||
print("To skip entering your key every time create file 'test_key.json' with your apikey as a value for 'key' dict key.", flush=True)
|
||||
|
||||
|
||||
def test(name: str, data: Any, raw: bool = False) -> None:
|
||||
|
||||
makedirs("tests", exist_ok=True)
|
||||
|
||||
if isinstance(data, dict):
|
||||
if "errorCode" in data:
|
||||
print(f"{BBLACK}[{BRED}ER{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}did not go well. ErrorCode is {BRED}{data['errorCode']}{RESET}. Check {CYAN}tests/{name}.json {RESET}for more information.", flush=True)
|
||||
else:
|
||||
print(f"{BBLACK}[{BGREEN}OK{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}seems to be alright.", flush=True)
|
||||
|
||||
if raw:
|
||||
|
||||
try:
|
||||
with open(f"tests/{name}.json", "w", encoding="utf-8") as file:
|
||||
file.write(dumps(data, indent=4, ensure_ascii=False))
|
||||
file.close()
|
||||
except JSONDecodeError:
|
||||
print(f"{BBLACK}[{BRED}ER{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}did not go well. ErrorCode is {BRED}{data['errorCode']}{RESET}. Check {CYAN}tests/{name}.json {RESET}for more information.", flush=True)
|
||||
|
||||
else:
|
||||
|
||||
with open(f"tests/{name}.txt", "w", encoding="utf-8") as file:
|
||||
if isinstance(data, list):
|
||||
list_2 = []
|
||||
for item in data:
|
||||
list_2.append(str(item)+"\n")
|
||||
file.writelines(list_2)
|
||||
else:
|
||||
file.write(str(data))
|
||||
file.close()
|
||||
|
||||
if data in ["", "\n"]:
|
||||
print(f"{BBLACK}[{BRED}ER{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}did not go well. ErrorCode is {BRED}{data['errorCode']}{RESET}. Check {CYAN}tests/{name}.txt {RESET}for more information.", flush=True) # type: ignore
|
||||
else:
|
||||
print(f"{BBLACK}[{BGREEN}OK{BBLACK}] {RESET}Test of {YELLOW}{name} {RESET}is not empty, so might be fine. Check {CYAN}tests/{name}.txt {RESET}for more information.", flush=True)
|
||||
|
||||
client = pyrmv.Client(key)
|
||||
|
||||
test("raw_board_arrival", pyrmv.raw.board_arrival(key, id="A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@X=8783648@Y=50083822@U=80@L=3008012@", maxJourneys=5), raw=True)
|
||||
test("raw_board_departure", pyrmv.raw.board_departure(key, id="A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@X=8783648@Y=50083822@U=80@L=3008012@", maxJourneys=5), raw=True)
|
||||
test("raw_him_search", pyrmv.raw.him_search(key, dateE=datetime.now()+timedelta(days=10), timeE=datetime.now()+timedelta(days=10), minprio=2, trainnames=["S9"]), raw=True)
|
||||
test("raw_journey_detail", pyrmv.raw.journey_detail(key, id="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#"), raw=True)
|
||||
test("raw_stop_by_name", pyrmv.raw.stop_by_name(key, "Groß Karben", maxNo=3), raw=True)
|
||||
test("raw_stop_by_coords", pyrmv.raw.stop_by_coords(key, 50.131140, 8.733362, radius=300, maxNo=3), raw=True)
|
||||
test("raw_trip_find", pyrmv.raw.trip_find(key, originCoordLat="50.084659", originCoordLong="8.785948", destCoordLat=50.1233048, destCoordLong=8.6129742, trafficMessages=True, numF=3), raw=True)
|
||||
test("raw_trip_recon", pyrmv.raw.trip_recon(key, ctx="¶HKI¶G@F$A=2@O=50.084659, 8.785948@X=8785948@Y=50084659@u=0@a=128@$A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@L=3008012@a=128@$202210061243$202210061247$$$1$$$$$$§T$A=1@O=Offenbach (Main)-Tempelsee Wilhelm-Schramm-Straße@L=3008012@a=128@$A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@L=3002510@a=128@$202210061247$202210061300$Bus 101 $$1$$$$$$§W$A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@L=3002510@a=128@$A=1@O=Offenbach (Main)-Zentrum Marktplatz@L=3011265@a=128@$202210061300$202210061304$$$1$$$$$$§T$A=1@O=Offenbach (Main)-Zentrum Marktplatz@L=3011265@a=128@$A=1@O=Frankfurt (Main) Taunusanlage@L=3000011@a=128@$202210061306$202210061319$ S2$$1$$$$$$§T$A=1@O=Frankfurt (Main) Taunusanlage@L=3000011@a=128@$A=1@O=Frankfurt (Main) Rödelheim Bahnhof@L=3001217@a=128@$202210061322$202210061333$ S5$$1$$$$$$§G@F$A=1@O=Frankfurt (Main) Rödelheim Bahnhof@L=3001217@a=128@$A=2@O=50.123304, 8.612974@X=8612974@Y=50123304@u=0@a=128@$202210061333$202210061344$$$1$$$$$$¶GP¶ft@0@2000@120@1@100@1@@0@@@@@false@0@-1@0@-1@-1@$f@$f@$f@$f@$f@$§bt@0@2000@120@1@100@1@@0@@@@@false@0@-1@0@-1@-1@$f@$f@$f@$f@$f@$§tt@0@2000@120@1@100@1@@0@@@@@false@0@-1@0@-1@-1@$f@$f@$f@$f@$f@$§¶KRCC¶#VE#1#"), raw=True)
|
||||
|
||||
test("board_arrival", client.board_arrival("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5))
|
||||
test("board_departure", client.board_departure("A=1@O=Frankfurt (Main) Taunusanlage@X=8668765@Y=50113478@U=80@L=3000011@", journeys_max=5, retrieve_stops=False))
|
||||
test("him_search", client.him_search(date_end=datetime.now()+timedelta(days=10), priority_min=2, train_names=["S9"]))
|
||||
test("journey_detail", 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))
|
||||
test("stop_by_coords", client.stop_by_coords(50.131140, 8.733362, radius=300, max_number=3))
|
||||
test("stop_by_id", client.stop_by_id("A=1@O=Offenbach (Main)-Zentrum Marktplatz/Frankf. Straße@X=8764456@Y=50105181@U=80@L=3002510@"))
|
||||
test("stop_by_name", client.stop_by_name("Groß Karben", max_number=3))
|
||||
test("trip_find", client.trip_find(origin_coord_lat="50.084659", origin_coord_lon="8.785948", destination_coord_lat=50.1233048, destination_coord_lon=8.6129742, messages=True))
|
||||
test("trip_recon", client.trip_recon( client.trip_find(origin_coord_lat="50.084659", origin_coord_lon="8.785948", destination_coord_lat=50.1233048, destination_coord_lon=8.6129742, messages=True, trips_after_time=1)[0] ))
|
19
test_colors.py
Normal file
19
test_colors.py
Normal file
@@ -0,0 +1,19 @@
|
||||
RESET = '\u001b[0m'
|
||||
BLACK = '\u001b[30m'
|
||||
RED = '\u001b[31m'
|
||||
GREEN = '\u001b[32m'
|
||||
YELLOW = '\u001b[33m'
|
||||
BLUE = '\u001b[34m'
|
||||
MAGENTA = '\u001b[35m'
|
||||
CYAN = '\u001b[36m'
|
||||
WHITE = '\u001b[37m'
|
||||
BBLACK = '\u001b[30;1m'
|
||||
BRED = '\u001b[31;1m'
|
||||
BGREEN = '\u001b[32;1m'
|
||||
BYELLOW = '\u001b[33;1m'
|
||||
BBLUE = '\u001b[34;1m'
|
||||
BMAGENTA = '\u001b[35;1m'
|
||||
BCYAN = '\u001b[36;1m'
|
||||
BWHITE = '\u001b[37;1m'
|
||||
ULINE = '\u001b[4m'
|
||||
REVERSE = '\u001b[7m'
|
30
wiki/Client.md
Normal file
30
wiki/Client.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# PythonRMV Client
|
||||
You are now viewing the main class of the module, its heart. The main Client class, all available normal methods can be found here.
|
||||
|
||||
This page is about the Client class, which exposes high-level methods for an easy access to the API.
|
||||
|
||||
```py
|
||||
from pyrmv import Client
|
||||
|
||||
client = Client("SampleAPIKey")
|
||||
|
||||
print(client.stop_by_id("A=1@O=Offenbach (Main)-Zentrum Marktplatz\/Frankf. Straße@X=8764456@Y=50105181@U=80@L=3002510@"))
|
||||
```
|
||||
|
||||
# Details
|
||||
|
||||
## `class pyrmv.Client`
|
||||
|
||||
### Parameters
|
||||
* access_key (`str`) – Access ID for identifying the requesting client. Get your key on [RMV website](https://opendata.rmv.de/site/start.html).
|
||||
|
||||
### Methods:
|
||||
* [board_arrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_arrival) -> `BoardArrival`
|
||||
* [board_departure](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_departure) -> `BoardDeparture`
|
||||
* [him_search](https://git.end-play.xyz/profitroll/PythonRMV/wiki/him_search) -> `List[Message]`
|
||||
* [journey_detail](https://git.end-play.xyz/profitroll/PythonRMV/wiki/journey_detail) -> `Journey`
|
||||
* [stop_by_coords](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_coords) -> `List[Stop]`
|
||||
* [stop_by_id](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_id) -> `Union[Stop, None]`
|
||||
* [stop_by_name](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_name) -> `List[Stop]`
|
||||
* [trip_find](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_find) -> `List[Trip]`
|
||||
* [trip_recon](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_recon) -> `List[Trip]`
|
5
wiki/Home.md
Normal file
5
wiki/Home.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# PythonRMV
|
||||
|
||||
Welcome to the project's Wiki.
|
||||
|
||||
Conceptional there are two different types of methods. Normal and raw ones. Raw methods are only beautiful variant of HTTP requests, nothing except for that actually. Normal ones are meant to be used as objects. You can still provide strings here and there, but basic concept is focused on objects usage.
|
15
wiki/_Sidebar.md
Normal file
15
wiki/_Sidebar.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## [Home](https://git.end-play.xyz/profitroll/PythonRMV/wiki)
|
||||
|
||||
### Classes
|
||||
* [Client](https://git.end-play.xyz/profitroll/PythonRMV/wiki/Client)
|
||||
|
||||
### Methods
|
||||
* [board_arrival](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_arrival)
|
||||
* [board_departure](https://git.end-play.xyz/profitroll/PythonRMV/wiki/board_departure)
|
||||
* [him_search](https://git.end-play.xyz/profitroll/PythonRMV/wiki/him_search)
|
||||
* [journey_detail](https://git.end-play.xyz/profitroll/PythonRMV/wiki/journey_detail)
|
||||
* [stop_by_coords](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_coords)
|
||||
* [stop_by_id](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_id)
|
||||
* [stop_by_name](https://git.end-play.xyz/profitroll/PythonRMV/wiki/stop_by_name)
|
||||
* [trip_find](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_find)
|
||||
* [trip_recon](https://git.end-play.xyz/profitroll/PythonRMV/wiki/trip_recon)
|
Reference in New Issue
Block a user