python-rapidbus 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_rapidbus-0.1.0/PKG-INFO +41 -0
- python_rapidbus-0.1.0/README.md +14 -0
- python_rapidbus-0.1.0/pyproject.toml +50 -0
- python_rapidbus-0.1.0/setup.cfg +4 -0
- python_rapidbus-0.1.0/src/python_rapidbus.egg-info/PKG-INFO +41 -0
- python_rapidbus-0.1.0/src/python_rapidbus.egg-info/SOURCES.txt +14 -0
- python_rapidbus-0.1.0/src/python_rapidbus.egg-info/dependency_links.txt +1 -0
- python_rapidbus-0.1.0/src/python_rapidbus.egg-info/requires.txt +6 -0
- python_rapidbus-0.1.0/src/python_rapidbus.egg-info/top_level.txt +1 -0
- python_rapidbus-0.1.0/src/rapidbus/__init__.py +48 -0
- python_rapidbus-0.1.0/src/rapidbus/client.py +75 -0
- python_rapidbus-0.1.0/src/rapidbus/const.py +19 -0
- python_rapidbus-0.1.0/src/rapidbus/decoder.py +146 -0
- python_rapidbus-0.1.0/src/rapidbus/exceptions.py +14 -0
- python_rapidbus-0.1.0/src/rapidbus/static.py +89 -0
- python_rapidbus-0.1.0/tests/test_rapidbus.py +43 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-rapidbus
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous Python client and dependency-free GTFS-Realtime decoder for Malaysian Prasarana bus transit
|
|
5
|
+
Author: Zubir Jamal
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zubirjamal/python-rapidbus
|
|
8
|
+
Project-URL: Repository, https://github.com/zubirjamal/python-rapidbus
|
|
9
|
+
Project-URL: Issues, https://github.com/zubirjamal/python-rapidbus/issues
|
|
10
|
+
Keywords: rapidbus,prasarana,gtfs,gtfs-realtime,malaysia,rapidkl,mrt-feeder,home-assistant
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Home Automation
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
|
|
26
|
+
Requires-Dist: aresponses>=3.0.0; extra == "test"
|
|
27
|
+
|
|
28
|
+
# python-rapidbus
|
|
29
|
+
|
|
30
|
+
Asynchronous Python client and dependency-free GTFS-Realtime decoder for Malaysian Prasarana bus transit (RapidKL, MRT Feeder, Rapid Penang, Rapid Kuantan).
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install python-rapidbus
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Features
|
|
39
|
+
- Dependency-free GTFS-Realtime Protobuf decoder (no heavy external `protobuf` / C-extension conflicts).
|
|
40
|
+
- Fetches and parses live vehicle positions from official Malaysian open data (`api.data.gov.my`).
|
|
41
|
+
- GTFS static package parser for route shapes, stops, headsigns, and ETA calculations.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# python-rapidbus
|
|
2
|
+
|
|
3
|
+
Asynchronous Python client and dependency-free GTFS-Realtime decoder for Malaysian Prasarana bus transit (RapidKL, MRT Feeder, Rapid Penang, Rapid Kuantan).
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install python-rapidbus
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
- Dependency-free GTFS-Realtime Protobuf decoder (no heavy external `protobuf` / C-extension conflicts).
|
|
13
|
+
- Fetches and parses live vehicle positions from official Malaysian open data (`api.data.gov.my`).
|
|
14
|
+
- GTFS static package parser for route shapes, stops, headsigns, and ETA calculations.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "python-rapidbus"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Asynchronous Python client and dependency-free GTFS-Realtime decoder for Malaysian Prasarana bus transit"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "Zubir Jamal" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["rapidbus", "prasarana", "gtfs", "gtfs-realtime", "malaysia", "rapidkl", "mrt-feeder", "home-assistant"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"License :: OSI Approved :: MIT License",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Topic :: Home Automation",
|
|
24
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
25
|
+
"Intended Audience :: Developers",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"aiohttp>=3.9.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.optional-dependencies]
|
|
32
|
+
test = [
|
|
33
|
+
"pytest>=8.0.0",
|
|
34
|
+
"pytest-asyncio>=0.23.0",
|
|
35
|
+
"aresponses>=3.0.0",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/zubirjamal/python-rapidbus"
|
|
40
|
+
Repository = "https://github.com/zubirjamal/python-rapidbus"
|
|
41
|
+
Issues = "https://github.com/zubirjamal/python-rapidbus/issues"
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
asyncio_mode = "auto"
|
|
48
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
49
|
+
pythonpath = ["src"]
|
|
50
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-rapidbus
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Asynchronous Python client and dependency-free GTFS-Realtime decoder for Malaysian Prasarana bus transit
|
|
5
|
+
Author: Zubir Jamal
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/zubirjamal/python-rapidbus
|
|
8
|
+
Project-URL: Repository, https://github.com/zubirjamal/python-rapidbus
|
|
9
|
+
Project-URL: Issues, https://github.com/zubirjamal/python-rapidbus/issues
|
|
10
|
+
Keywords: rapidbus,prasarana,gtfs,gtfs-realtime,malaysia,rapidkl,mrt-feeder,home-assistant
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Topic :: Home Automation
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
Requires-Dist: aiohttp>=3.9.0
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=8.0.0; extra == "test"
|
|
25
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "test"
|
|
26
|
+
Requires-Dist: aresponses>=3.0.0; extra == "test"
|
|
27
|
+
|
|
28
|
+
# python-rapidbus
|
|
29
|
+
|
|
30
|
+
Asynchronous Python client and dependency-free GTFS-Realtime decoder for Malaysian Prasarana bus transit (RapidKL, MRT Feeder, Rapid Penang, Rapid Kuantan).
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install python-rapidbus
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Features
|
|
39
|
+
- Dependency-free GTFS-Realtime Protobuf decoder (no heavy external `protobuf` / C-extension conflicts).
|
|
40
|
+
- Fetches and parses live vehicle positions from official Malaysian open data (`api.data.gov.my`).
|
|
41
|
+
- GTFS static package parser for route shapes, stops, headsigns, and ETA calculations.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/python_rapidbus.egg-info/PKG-INFO
|
|
4
|
+
src/python_rapidbus.egg-info/SOURCES.txt
|
|
5
|
+
src/python_rapidbus.egg-info/dependency_links.txt
|
|
6
|
+
src/python_rapidbus.egg-info/requires.txt
|
|
7
|
+
src/python_rapidbus.egg-info/top_level.txt
|
|
8
|
+
src/rapidbus/__init__.py
|
|
9
|
+
src/rapidbus/client.py
|
|
10
|
+
src/rapidbus/const.py
|
|
11
|
+
src/rapidbus/decoder.py
|
|
12
|
+
src/rapidbus/exceptions.py
|
|
13
|
+
src/rapidbus/static.py
|
|
14
|
+
tests/test_rapidbus.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rapidbus
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""RapidBus transit library."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .client import RapidBusClient
|
|
5
|
+
from .const import (
|
|
6
|
+
CATEGORIES,
|
|
7
|
+
DEFAULT_CATEGORY,
|
|
8
|
+
EARTH_R,
|
|
9
|
+
FEED_TZ,
|
|
10
|
+
REQUEST_TIMEOUT,
|
|
11
|
+
RT_URL_TEMPLATE,
|
|
12
|
+
STATIC_URL_TEMPLATE,
|
|
13
|
+
)
|
|
14
|
+
from .decoder import Vehicle, decode_feed, parse_vehicle_position
|
|
15
|
+
from .exceptions import (
|
|
16
|
+
RapidBusConnectionError,
|
|
17
|
+
RapidBusDecodeError,
|
|
18
|
+
RapidBusError,
|
|
19
|
+
)
|
|
20
|
+
from .static import (
|
|
21
|
+
Route,
|
|
22
|
+
Shape,
|
|
23
|
+
Stop,
|
|
24
|
+
bearing,
|
|
25
|
+
haversine,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"CATEGORIES",
|
|
30
|
+
"DEFAULT_CATEGORY",
|
|
31
|
+
"EARTH_R",
|
|
32
|
+
"FEED_TZ",
|
|
33
|
+
"REQUEST_TIMEOUT",
|
|
34
|
+
"RT_URL_TEMPLATE",
|
|
35
|
+
"STATIC_URL_TEMPLATE",
|
|
36
|
+
"RapidBusClient",
|
|
37
|
+
"RapidBusConnectionError",
|
|
38
|
+
"RapidBusDecodeError",
|
|
39
|
+
"RapidBusError",
|
|
40
|
+
"Route",
|
|
41
|
+
"Shape",
|
|
42
|
+
"Stop",
|
|
43
|
+
"Vehicle",
|
|
44
|
+
"bearing",
|
|
45
|
+
"decode_feed",
|
|
46
|
+
"haversine",
|
|
47
|
+
"parse_vehicle_position",
|
|
48
|
+
]
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Client for Prasarana Rapid Bus realtime and static feeds."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import aiohttp
|
|
8
|
+
|
|
9
|
+
from .const import (
|
|
10
|
+
CATEGORIES,
|
|
11
|
+
DEFAULT_CATEGORY,
|
|
12
|
+
REQUEST_TIMEOUT,
|
|
13
|
+
RT_URL_TEMPLATE,
|
|
14
|
+
STATIC_URL_TEMPLATE,
|
|
15
|
+
)
|
|
16
|
+
from .decoder import Vehicle, decode_feed
|
|
17
|
+
from .exceptions import RapidBusConnectionError, RapidBusError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class RapidBusClient:
|
|
21
|
+
"""Asynchronous client for Prasarana GTFS-Realtime feeds."""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
session: aiohttp.ClientSession | None = None,
|
|
26
|
+
category: str = DEFAULT_CATEGORY,
|
|
27
|
+
timeout: int = REQUEST_TIMEOUT,
|
|
28
|
+
) -> None:
|
|
29
|
+
"""Initialize RapidBusClient."""
|
|
30
|
+
self._session = session
|
|
31
|
+
self.category = category
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
|
|
34
|
+
async def _get_session(self) -> aiohttp.ClientSession:
|
|
35
|
+
if self._session is None or self._session.closed:
|
|
36
|
+
self._session = aiohttp.ClientSession()
|
|
37
|
+
return self._session
|
|
38
|
+
|
|
39
|
+
async def async_get_vehicles(self, category: str | None = None) -> list[Vehicle]:
|
|
40
|
+
"""Fetch and decode all current vehicle positions for a category."""
|
|
41
|
+
cat = category or self.category
|
|
42
|
+
url = RT_URL_TEMPLATE.format(category=cat)
|
|
43
|
+
session = await self._get_session()
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
async with asyncio.timeout(self.timeout):
|
|
47
|
+
async with session.get(url) as resp:
|
|
48
|
+
if resp.status != 200:
|
|
49
|
+
raise RapidBusConnectionError(
|
|
50
|
+
f"HTTP {resp.status} from {url}"
|
|
51
|
+
)
|
|
52
|
+
raw_bytes = await resp.read()
|
|
53
|
+
except (aiohttp.ClientError, TimeoutError) as err:
|
|
54
|
+
raise RapidBusConnectionError(f"Error fetching GTFS-RT feed: {err}") from err
|
|
55
|
+
|
|
56
|
+
return decode_feed(raw_bytes)
|
|
57
|
+
|
|
58
|
+
async def async_get_static_zip(self, category: str | None = None) -> bytes:
|
|
59
|
+
"""Download GTFS static zip archive for a transit category."""
|
|
60
|
+
cat = category or self.category
|
|
61
|
+
url = STATIC_URL_TEMPLATE.format(category=cat)
|
|
62
|
+
session = await self._get_session()
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
async with asyncio.timeout(self.timeout * 2):
|
|
66
|
+
async with session.get(url) as resp:
|
|
67
|
+
if resp.status != 200:
|
|
68
|
+
raise RapidBusConnectionError(
|
|
69
|
+
f"HTTP {resp.status} from {url}"
|
|
70
|
+
)
|
|
71
|
+
return await resp.read()
|
|
72
|
+
except (aiohttp.ClientError, TimeoutError) as err:
|
|
73
|
+
raise RapidBusConnectionError(
|
|
74
|
+
f"Error fetching GTFS static zip: {err}"
|
|
75
|
+
) from err
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Constants for Rapid Bus transit client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Final
|
|
5
|
+
|
|
6
|
+
RT_URL_TEMPLATE: Final = "https://api.data.gov.my/gtfs-realtime/vehicle-position/prasarana/?category={category}"
|
|
7
|
+
STATIC_URL_TEMPLATE: Final = "https://api.data.gov.my/gtfs-static/prasarana?category={category}"
|
|
8
|
+
|
|
9
|
+
CATEGORIES: Final = {
|
|
10
|
+
"rapid-bus-kl": "RapidKL Bus (Klang Valley)",
|
|
11
|
+
"rapid-bus-mrtfeeder": "MRT Feeder Bus",
|
|
12
|
+
"rapid-bus-kuantan": "Rapid Kuantan",
|
|
13
|
+
"rapid-bus-penang": "Rapid Penang",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
DEFAULT_CATEGORY: Final = "rapid-bus-kl"
|
|
17
|
+
FEED_TZ: Final = "Asia/Kuala_Lumpur"
|
|
18
|
+
REQUEST_TIMEOUT: Final = 30
|
|
19
|
+
EARTH_R: Final = 6371.0088
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Decoder for GTFS-Realtime VehiclePosition protobuf streams without external dependencies."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import struct
|
|
6
|
+
from typing import Generator
|
|
7
|
+
|
|
8
|
+
from .exceptions import RapidBusDecodeError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Vehicle:
|
|
13
|
+
"""A bus decoded from GTFS-Realtime stream."""
|
|
14
|
+
|
|
15
|
+
vehicle_id: str
|
|
16
|
+
plate: str
|
|
17
|
+
route_id: str
|
|
18
|
+
trip_id: str
|
|
19
|
+
latitude: float
|
|
20
|
+
longitude: float
|
|
21
|
+
bearing: float | None
|
|
22
|
+
speed: float | None
|
|
23
|
+
timestamp: int
|
|
24
|
+
|
|
25
|
+
def to_dict(self) -> dict:
|
|
26
|
+
return {
|
|
27
|
+
"vehicle_id": self.vehicle_id,
|
|
28
|
+
"plate": self.plate,
|
|
29
|
+
"route_id": self.route_id,
|
|
30
|
+
"trip_id": self.trip_id,
|
|
31
|
+
"latitude": self.latitude,
|
|
32
|
+
"longitude": self.longitude,
|
|
33
|
+
"bearing": self.bearing,
|
|
34
|
+
"speed": self.speed,
|
|
35
|
+
"timestamp": self.timestamp,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _varint(buf: bytes, i: int) -> tuple[int, int]:
|
|
40
|
+
shift = result = 0
|
|
41
|
+
n = len(buf)
|
|
42
|
+
while True:
|
|
43
|
+
if i >= n:
|
|
44
|
+
raise RapidBusDecodeError("Truncated varint in protobuf stream")
|
|
45
|
+
b = buf[i]
|
|
46
|
+
i += 1
|
|
47
|
+
result |= (b & 0x7F) << shift
|
|
48
|
+
if not b & 0x80:
|
|
49
|
+
return result, i
|
|
50
|
+
shift += 7
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _fields(buf: bytes) -> Generator[tuple[int, int, bytes | int], None, None]:
|
|
54
|
+
"""Yield (field_number, wire_type, value) for a protobuf message."""
|
|
55
|
+
i, n = 0, len(buf)
|
|
56
|
+
while i < n:
|
|
57
|
+
key, i = _varint(buf, i)
|
|
58
|
+
fnum, wtype = key >> 3, key & 7
|
|
59
|
+
if wtype == 0:
|
|
60
|
+
val, i = _varint(buf, i)
|
|
61
|
+
elif wtype == 1:
|
|
62
|
+
val, i = buf[i : i + 8], i + 8
|
|
63
|
+
elif wtype == 2:
|
|
64
|
+
ln, i = _varint(buf, i)
|
|
65
|
+
val, i = buf[i : i + ln], i + ln
|
|
66
|
+
elif wtype == 5:
|
|
67
|
+
val, i = buf[i : i + 4], i + 4
|
|
68
|
+
else:
|
|
69
|
+
raise RapidBusDecodeError(f"Unsupported protobuf wire type {wtype}")
|
|
70
|
+
yield fnum, wtype, val
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _f32(v: bytes) -> float:
|
|
74
|
+
return struct.unpack("<f", v)[0]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _str(v: bytes) -> str:
|
|
78
|
+
return v.decode("utf-8", "replace")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def parse_vehicle_position(buf: bytes) -> Vehicle | None:
|
|
82
|
+
"""Parse one VehiclePosition message."""
|
|
83
|
+
trip_id = route_id = vid = plate = label = ""
|
|
84
|
+
lat = lon = None
|
|
85
|
+
bearing = speed = None
|
|
86
|
+
ts = 0
|
|
87
|
+
for f, w, v in _fields(buf):
|
|
88
|
+
if f == 1 and w == 2: # TripDescriptor
|
|
89
|
+
for tf, tw, tv in _fields(v):
|
|
90
|
+
if tf == 1 and tw == 2:
|
|
91
|
+
trip_id = _str(tv)
|
|
92
|
+
elif tf == 5 and tw == 2:
|
|
93
|
+
route_id = _str(tv)
|
|
94
|
+
elif f == 2 and w == 2: # Position
|
|
95
|
+
for pf, pw, pv in _fields(v):
|
|
96
|
+
if pw != 5:
|
|
97
|
+
continue
|
|
98
|
+
if pf == 1:
|
|
99
|
+
lat = _f32(pv)
|
|
100
|
+
elif pf == 2:
|
|
101
|
+
lon = _f32(pv)
|
|
102
|
+
elif pf == 3:
|
|
103
|
+
bearing = _f32(pv)
|
|
104
|
+
elif pf == 5:
|
|
105
|
+
speed = _f32(pv)
|
|
106
|
+
elif f == 5 and w == 0:
|
|
107
|
+
ts = v
|
|
108
|
+
elif f == 8 and w == 2: # VehicleDescriptor
|
|
109
|
+
for df, dw, dv in _fields(v):
|
|
110
|
+
if dw != 2:
|
|
111
|
+
continue
|
|
112
|
+
if df == 1:
|
|
113
|
+
vid = _str(dv)
|
|
114
|
+
elif df == 2:
|
|
115
|
+
label = _str(dv)
|
|
116
|
+
elif df == 3:
|
|
117
|
+
plate = _str(dv)
|
|
118
|
+
|
|
119
|
+
if lat is None or lon is None:
|
|
120
|
+
return None
|
|
121
|
+
# License plate may appear in license_plate (3), label (2) or id (1)
|
|
122
|
+
plate = plate or label or vid
|
|
123
|
+
return Vehicle(
|
|
124
|
+
vehicle_id=vid or plate or trip_id,
|
|
125
|
+
plate=plate,
|
|
126
|
+
route_id=route_id,
|
|
127
|
+
trip_id=trip_id,
|
|
128
|
+
latitude=lat,
|
|
129
|
+
longitude=lon,
|
|
130
|
+
bearing=bearing,
|
|
131
|
+
speed=speed,
|
|
132
|
+
timestamp=ts,
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def decode_feed(buf: bytes) -> list[Vehicle]:
|
|
137
|
+
"""Decode a FeedMessage payload into a list of Vehicles."""
|
|
138
|
+
vehicles: list[Vehicle] = []
|
|
139
|
+
for f, w, v in _fields(buf):
|
|
140
|
+
if f == 2 and w == 2: # FeedEntity
|
|
141
|
+
for ef, ew, ev in _fields(v):
|
|
142
|
+
if ef == 4 and ew == 2: # vehicle: VehiclePosition
|
|
143
|
+
v_obj = parse_vehicle_position(ev)
|
|
144
|
+
if v_obj is not None:
|
|
145
|
+
vehicles.append(v_obj)
|
|
146
|
+
return vehicles
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Exceptions for Rapid Bus client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class RapidBusError(Exception):
|
|
6
|
+
"""Base error for rapid bus operations."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class RapidBusConnectionError(RapidBusError):
|
|
10
|
+
"""Network connection or timeout error."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RapidBusDecodeError(RapidBusError):
|
|
14
|
+
"""Error decoding GTFS or Protobuf binary feed."""
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""GTFS Static models and along-route estimation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import csv
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
import io
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
import zipfile
|
|
10
|
+
|
|
11
|
+
from .const import EARTH_R
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
15
|
+
"""Distance in km between two GPS points."""
|
|
16
|
+
p1, p2 = math.radians(lat1), math.radians(lat2)
|
|
17
|
+
dp, dl = p2 - p1, math.radians(lon2 - lon1)
|
|
18
|
+
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
|
|
19
|
+
return 2 * EARTH_R * math.asin(math.sqrt(a))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
|
23
|
+
"""Bearing in degrees between two GPS points."""
|
|
24
|
+
p1, p2 = math.radians(lat1), math.radians(lat2)
|
|
25
|
+
dl = math.radians(lon2 - lon1)
|
|
26
|
+
x = math.sin(dl) * math.cos(p2)
|
|
27
|
+
y = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
|
|
28
|
+
return (math.degrees(math.atan2(x, y)) + 360) % 360
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Route:
|
|
33
|
+
"""A public transit route."""
|
|
34
|
+
|
|
35
|
+
key: str
|
|
36
|
+
route_ids: set[str]
|
|
37
|
+
short_name: str
|
|
38
|
+
long_name: str
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def label(self) -> str:
|
|
42
|
+
if self.long_name and self.long_name != self.short_name:
|
|
43
|
+
return f"{self.short_name} - {self.long_name}"
|
|
44
|
+
return self.short_name
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Stop:
|
|
49
|
+
"""A transit stop."""
|
|
50
|
+
|
|
51
|
+
stop_id: str
|
|
52
|
+
name: str
|
|
53
|
+
lat: float
|
|
54
|
+
lon: float
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def short_name(self) -> str:
|
|
58
|
+
return re.sub(r"^[A-Z]{1,4}\d{2,}[A-Z]?\s+", "", self.name).title()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class Shape:
|
|
63
|
+
"""A route pattern with cumulative distance in km."""
|
|
64
|
+
|
|
65
|
+
shape_id: str
|
|
66
|
+
headsign: str
|
|
67
|
+
points: list[tuple[float, float]]
|
|
68
|
+
cum: list[float]
|
|
69
|
+
avg_kmh: float = 18.0
|
|
70
|
+
stops: list[tuple[str, float]] = field(default_factory=list)
|
|
71
|
+
|
|
72
|
+
def project(self, lat: float, lon: float) -> tuple[float, float, float]:
|
|
73
|
+
"""Return (offset_km, along_km, segment_heading) of nearest point."""
|
|
74
|
+
best = (1e9, 0.0, 0.0)
|
|
75
|
+
kx = math.cos(math.radians(lat)) * 111.32
|
|
76
|
+
ky = 110.574
|
|
77
|
+
for i in range(len(self.points) - 1):
|
|
78
|
+
(a_lat, a_lon), (b_lat, b_lon) = self.points[i], self.points[i + 1]
|
|
79
|
+
ax, ay = (a_lon - lon) * kx, (a_lat - lat) * ky
|
|
80
|
+
bx, by = (b_lon - lon) * kx, (b_lat - lat) * ky
|
|
81
|
+
dx, dy = bx - ax, by - ay
|
|
82
|
+
seg2 = dx * dx + dy * dy
|
|
83
|
+
t = 0.0 if seg2 == 0 else max(0.0, min(1.0, -(ax * dx + ay * dy) / seg2))
|
|
84
|
+
px, py = ax + t * dx, ay + t * dy
|
|
85
|
+
d = math.hypot(px, py)
|
|
86
|
+
if d < best[0]:
|
|
87
|
+
seg_len = self.cum[i + 1] - self.cum[i]
|
|
88
|
+
best = (d, self.cum[i] + t * seg_len, bearing(a_lat, a_lon, b_lat, b_lon))
|
|
89
|
+
return best
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Tests for python-rapidbus decoder and static helpers."""
|
|
2
|
+
import struct
|
|
3
|
+
import pytest
|
|
4
|
+
from rapidbus import (
|
|
5
|
+
Vehicle,
|
|
6
|
+
parse_vehicle_position,
|
|
7
|
+
decode_feed,
|
|
8
|
+
haversine,
|
|
9
|
+
bearing,
|
|
10
|
+
Route,
|
|
11
|
+
Stop,
|
|
12
|
+
Shape,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
def test_haversine_and_bearing():
|
|
16
|
+
# KL Sentral (3.134, 101.686) to Pasar Seni (3.142, 101.696)
|
|
17
|
+
dist = haversine(3.134, 101.686, 3.142, 101.696)
|
|
18
|
+
assert 1.0 < dist < 2.0
|
|
19
|
+
b = bearing(3.134, 101.686, 3.142, 101.696)
|
|
20
|
+
assert 0 <= b <= 360
|
|
21
|
+
|
|
22
|
+
def test_decode_vehicle_position():
|
|
23
|
+
# Mocking binary varint / float protobuf sequence
|
|
24
|
+
# Position: field 2 (wire 2), latitude=3.14, longitude=101.69
|
|
25
|
+
lat_bytes = struct.pack("<f", 3.14)
|
|
26
|
+
lon_bytes = struct.pack("<f", 101.69)
|
|
27
|
+
# field 1 (lat) tag = (1 << 3) | 5 = 13 (0x0d)
|
|
28
|
+
# field 2 (lon) tag = (2 << 3) | 5 = 21 (0x15)
|
|
29
|
+
pos_sub = bytes([0x0d]) + lat_bytes + bytes([0x15]) + lon_bytes
|
|
30
|
+
# field 2 tag in VehiclePosition = (2 << 3) | 2 = 18 (0x12)
|
|
31
|
+
vp_msg = bytes([0x12, len(pos_sub)]) + pos_sub
|
|
32
|
+
|
|
33
|
+
v = parse_vehicle_position(vp_msg)
|
|
34
|
+
assert v is not None
|
|
35
|
+
assert round(v.latitude, 2) == 3.14
|
|
36
|
+
assert round(v.longitude, 2) == 101.69
|
|
37
|
+
|
|
38
|
+
def test_route_and_stop():
|
|
39
|
+
r = Route(key="770", route_ids={"770"}, short_name="770", long_name="Subang Jaya - Pasar Seni")
|
|
40
|
+
assert r.label == "770 - Subang Jaya - Pasar Seni"
|
|
41
|
+
|
|
42
|
+
s = Stop(stop_id="KL1079", name="KL1079 KL SENTRAL", lat=3.134, lon=101.686)
|
|
43
|
+
assert s.short_name == "Kl Sentral"
|