# An automatic Bus Planner

# An automatic bus planner

## Context

Okay, so I got sick and tired of my buses being delayed or planning to take one at a time to either see they've been delayed, or they came 5min earlier and I have to wait for the next one... An hour later.

## So what?

I know there are live data on where/when the buses will arrive at the station. But it requires the app, and there's no way to setup notifications like "bus will be there in 15min, pack up". But I did find the IDFM open data API. It was kinda hard to find, but [here it is](https://prim.iledefrance-mobilites.fr/en/apis/idfm-ivtr-requete_unitaire)!

But for that, you need to specify the stop and route IDs, which there isn't an easy way to get...

### Getting IDs for the actual request

CSV it is!

- [For the stop zone](https://prim.iledefrance-mobilites.fr/en/jeux-de-donnees/zones-d-arrets)
- [For the line ID](https://data.iledefrance-mobilites.fr/explore/dataset/referentiel-des-lignes/information/)

According to [this documentation](https://prim.iledefrance-mobilites.fr/en/aide-et-contact/documentation/prise-en-main-des-api/prise-en-main-des-api-prochains-passages/identification-des-objets), a LineRef is `STIF:Line::CXXXXX:` with CXXXXX the [line identifier](https://data.iledefrance-mobilites.fr/explore/dataset/referentiel-des-lignes/information/).
And as for the stop ref: `STIF:StopPoint:Q:XXXXX:` with XXXXX the stop identifier or `STIF:StopArea:SP:XXXXX:` with XXXXX the [stop zone identifier](https://prim.iledefrance-mobilites.fr/en/jeux-de-donnees/zones-d-arrets).

## Practical example:

We can now see the two values we want. Let's assume I want the next arrivals at "La Défense (Grande Arche)" on the T2 line.

T2 line is `C01390`, and the "La Défense (Grande Arche)" stop is `462395`.

Our data is then:

| MonitoringRef | LineRef |
| --- | --- |
| `STIF:StopArea:SP:462395:` | `STIF:Line::C01390:` |

### The request

Now, we can craft our request:

```sh
vim sncf_prim_token  # put your API key from the PRIM website in this file
curl -L "https://prim.iledefrance-mobilites.fr/marketplace/stop-monitoring?MonitoringRef=STIF:StopArea:SP:462395:&LineRef=STIF:Line::C01390:" -H "apiKey: $(cat sncf_prim_token)"
```

And here we got the data!

And now, for some ***Fancy Magic\~***

```python
from datetime import datetime, timezone
import sys

try:
    import humanize
except ImportError:
    humanize = None
import requests

try:
    from rich.console import Console

    console = Console()
    print = console.print
except ImportError:
    pass


def get_times_from_json(data: dict, destination: str = ""):
    times = []
    buses = data['Siri']['ServiceDelivery']['StopMonitoringDelivery'][-1]
    buses = buses['MonitoredStopVisit']

    buses_filtered = [
        bus for bus in buses if destination.lower() in
        bus['MonitoredVehicleJourney']['DestinationName'][0]['value'].lower()
    ]

    def bustime(bus: dict):
        bus = bus['MonitoredVehicleJourney']
        bus = bus['MonitoredCall']
        bus = bus['ExpectedArrivalTime']
        return bus

    for bus in buses_filtered:
        times.append(bustime(bus))

    return times


def get_times_from_stopline(stopArea: str, lineID: str, dest: str = ""):
    apiKey = open('sncf_prim_token', 'r').read().strip()
    monitoringRef = f"STIF:StopArea:SP:{stopArea}:"
    lineRef = f"STIF:Line::{lineID}:"
    baseUrl = "https://prim.iledefrance-mobilites.fr"
    endpoint = "/marketplace/stop-monitoring"
    arguments = f"?MonitoringRef={monitoringRef}&LineRef={lineRef}"
    fullUrl = f"{baseUrl}{endpoint}{arguments}"
    headers = {
        "apiKey": apiKey
    }
    req = requests.get(fullUrl, headers=headers)
    times = get_times_from_json(req.json(), dest)
    return times


def main():
    if sys.argv[1:]:
        stopID = sys.argv[1].upper()
    else:
        stopID = input("Stop ID: ").upper()
    if sys.argv[2:]:
        lineID = sys.argv[2].upper()
    else:
        lineID = input("Line ID: ").upper()
    if sys.argv[3:]:
        dest = ' '.join(sys.argv[3:]).lower()
    else:
        dest = input("Direction filter: ").lower()
    times = get_times_from_stopline(stopID, lineID, dest)
    print()
    curtime = datetime.now(timezone.utc)
    for time in times:
        dt = datetime.fromisoformat(time)
        time_abs = dt.strftime("%H:%M:%S")
        time_full = f"{time_abs}"
        if humanize:
            time_rel = humanize.naturaltime(curtime - dt)
            time_rel = time_rel.replace(' from now', '')
            time_rel = f"in {time_rel}"
            time_full = f"{time_abs} - {time_rel}"
        print(time_full)
    # print(times)


if __name__ == "__main__":
    main()
```

Which renders as:
![Final Render](img/2026-02-02_12-56.png)
(the relative time requires the "[humanize](https://pypi.org/project/humanize/)" python module)
