Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

publictransport for Kotlin

A Kotlin client for public transport APIs. It uses a shared model for stops, departures and trips that covers several server types, so an application can query any supported network the same way. It supports servers that speak EFA (used by many German transport associations), MOTIS (the routing engine behind Transitous), TRIAS 1.2, OJP 1.0, HAFAS mgate (the interface behind many operators’ apps) and OpenTripPlanner 2 with its Transmodel API.

The package wraps the Rust library of the same name. The Rust code builds the requests and parses the answers, and OkHttp sends them from suspend functions. It runs on the JVM from Java 11.

The package is on Maven Central, for macOS and Linux (with glibc, so not Alpine) on x86-64 and ARM and for Windows on x86-64. An Android library is planned.

dependencies {
    implementation("io.github.kiliankoe:publictransport:0.1.2")
}
import publictransport.BundledNetwork
import publictransport.Client
import publictransport.LocationKind

val client = Client("my-app/1.0 (+https://example.org)")
val network = BundledNetwork.VVO_EFA.network()

val stops = client.locations(network, "Hauptbahnhof", kinds = listOf(LocationKind.STOP))
val (from, to) = stops

for (departure in client.departures(network, from, limit = 10)) {
    // The time on the clocks at the stop, where its time zone is known.
    val time = departure.stop.localTime(departure.scheduledTime)
    println("${time?.toLocalTime() ?: "?"} ${departure.line.name} ${departure.direction ?: ""}")
}

val found = client.trips(network, from, to, limit = 5)
// The same arguments again, with the reference to the trips after these.
val more = client.trips(network, from, to, limit = 5, page = found.later)

The examples have a short program for each kind of request.

BundledNetwork names the networks that ship with the package, and network() gives one. Registry.bundled() holds them all, for a list to choose from: get("vvo-efa") finds one by its ID as text, and covering(Coordinate(...)) lists the networks for a position, each with the tier of its coverage there. A Network can also be written by hand, as Network(id = ..., name = ..., endpoint = ..., protocol = Protocol.EFA, timezone = "Europe/Berlin"), and networkFromJson(id, json) reads further ones from entries in the format of transport-apis.

The model types are data classes with val properties, so copy makes a changed one: network.copy(headers = network.headers + Header("X-Api-Key", key)).

departures takes a Location from a search, a departure or a trip, or the ID of a stop as a String. trips takes two locations, or two Place values for other ends: asPlace() makes one from a location or a Coordinate, as in client.trips(network, stop.asPlace(), Coordinate(51.04, 13.73).asPlace()), and Place.Id names a stop by its ID on the network that is asked. A location that another network returned works as well: for a trip always if it has a coordinate, for departures where the asked network can name the stop, which EFA, TRIAS and OJP can for stops with a global ID. Each call also takes a query of the Rust library (LocationQuery, DeparturesQuery, TripsQuery) in place of the plain values.

Times are java.time.Instant values. Location.localTime(time) gives one as the clocks at that location show it, an OffsetDateTime with the offset that holds there at that time, or null where no time zone is known for it. An EFA network needs its timezone to send a query time. A TRIAS or OJP network needs a requestorRef, which public servers document, e.g. OpenService. A HAFAS network needs hafas = HafasOptions(...) and its timezone; the bundled ones have both.

trips returns a Trips value: the list is in trips, and earlier and later are references for more. Pass one as page with the same other arguments to continue the search. An answer from an OpenTripPlanner server can be empty at night and still have a later reference to follow.

Failures that the server or the query cause are thrown as subclasses of PublicTransportException, such as PublicTransportException.NotFound or PublicTransportException.RateLimited; its message is a sentence in English. Failures of the HTTP exchange are thrown as OkHttp throws them, as an IOException. An answer above 16 MB is a ResponseTooLargeException, which is an IOException too. A cancelled coroutine cancels its request. The client does not follow redirects: a moved server is PublicTransportException.Moved. It does not retry, limit its request rate or cache.

One client serves every network, so create one and keep it. It can be built on an OkHttpClient of your own, Client(userAgent, httpClient), for example to use a proxy or an interceptor. The client uses its connections and settings, except that it never follows a redirect and never sends a request again.

Some networks need more than their entry holds. Entur asks every client for its name in the header ET-Client-Name (company-application) and limits clients without it: add it to the headers of the bundled network with copy, as above.

An application with its own HTTP stack can skip the client: Network.locationsRequest(query) returns the request to send, and Network.parseLocations(response) reads the answer. Departures and trips have the same pair.

Known limitations

The model classes are generated by UniFFI, which shows in a few places.

  • The value of a Place or a TripTime case is named v1, as in Place.Id("de:14612:28").v1.
  • toString() of a model value is the debug text of the Rust library, with Rust’s names for the fields. It leaves out the values of headers, which can be credentials.
  • The package publictransport also has the helpers of the generated code, such as FfiConverterString. They are no part of the API.
  • The documentation of the model types comes from the Rust code, so it links and names things as Rust does: [`Location::local_time`] is Location.localTime, None is null, and Error is PublicTransportException.
  • A Registry is AutoCloseable, because it lives in the Rust library. Closing it is optional: its memory is freed when the object is collected.
  • The Rust library is loaded with JNA. From Java 24 on, the JVM prints a warning about that unless it is started with --enable-native-access=ALL-UNNAMED.

Examples

The repository has these as programs to run, in examples.

Search for places by name

// Searches for places by name on the EFA server of VVO, the transport
// association of Dresden.

import publictransport.BundledNetwork
import publictransport.Client
import java.util.Locale

suspend fun main() {
    // Servers want to know who asks: name your application and a way to reach you.
    val client = Client("publictransport-example (+https://github.com/kiliankoe/publictransport)")
    val network = BundledNetwork.VVO_EFA.network()

    // Every kind of place. `kinds = listOf(LocationKind.STOP)` asks for stops only.
    val locations = client.locations(network, "Dresden Zwinger")

    // The best match comes first.
    for (location in locations.take(5)) {
        val position =
            location.coordinate?.let { " at %.4f, %.4f".format(Locale.ROOT, it.latitude, it.longitude) } ?: ""
        println("${location.kind}: ${location.name} (${location.id})$position")
    }
}

List the next departures at a stop

// Lists the next departures at a stop on the HAFAS server of VBB, the
// transport association of Berlin and Brandenburg.

import publictransport.BundledNetwork
import publictransport.Client
import publictransport.LocationKind
import java.time.Duration
import java.time.format.DateTimeFormatter

private val clock = DateTimeFormatter.ofPattern("HH:mm")

suspend fun main() {
    // Servers want to know who asks: name your application and a way to reach you.
    val client = Client("publictransport-example (+https://github.com/kiliankoe/publictransport)")
    val network = BundledNetwork.VBB_HAFAS.network()

    val stop = client.locations(network, "S+U Alexanderplatz", kinds = listOf(LocationKind.STOP)).first()

    println("Departures at ${stop.name}:")
    // From now on. `time =` asks for another time.
    for (departure in client.departures(network, stop, limit = 10)) {
        // Times are `Instant` values, and a location gives the time on the
        // clocks there, where the server names its time zone.
        val time = departure.stop.localTime(departure.scheduledTime)?.format(clock) ?: "??:??"
        // Only departures with real-time data have a delay.
        val delay =
            departure.realtimeTime?.let { "%+d".format(Duration.between(departure.scheduledTime, it).toMinutes()) }
        println(
            "  $time ${(delay ?: "").padStart(3)} ${departure.line.name.padEnd(5)} ${departure.direction ?: "?"}" +
                if (departure.cancelled) " (cancelled)" else "",
        )
    }
}

Plan trips, and ask for later ones

// Plans trips between two stops on the OTP server of Entur, the journey
// planner for Norway, and asks for the trips after the first ones.

import publictransport.BundledNetwork
import publictransport.Client
import publictransport.Header
import publictransport.LegEnd
import publictransport.LegKind
import publictransport.LocationKind
import publictransport.Trip
import java.time.format.DateTimeFormatter

private val clock = DateTimeFormatter.ofPattern("HH:mm")

// The expected time of day at the stop: the real-time one if there is one.
// Times are `Instant` values, and a location gives the time on the clocks
// there, where the server names its time zone.
private fun localTime(end: LegEnd): String = end.stop.localTime(end.expectedTime)?.format(clock) ?: "??:??"

private fun printTrip(trip: Trip) {
    val departure = trip.departure ?: return
    val arrival = trip.arrival ?: return
    println("  ${localTime(departure)} to ${localTime(arrival)}, ${trip.transfers} change(s)")
    for (leg in trip.legs) {
        val how =
            when (val kind = leg.kind) {
                is LegKind.Transit -> "${kind.line.name} to ${kind.direction ?: "?"}"
                is LegKind.Walk -> "walk"
                else -> "other"
            }
        println(
            "    ${localTime(leg.departure)} ${leg.departure.stop.name}" +
                " -> ${localTime(leg.arrival)} ${leg.arrival.stop.name}: $how",
        )
    }
}

suspend fun main() {
    // Servers want to know who asks: name your application and a way to reach you.
    val client = Client("publictransport-example (+https://github.com/kiliankoe/publictransport)")
    val entur = BundledNetwork.ENTUR.network()
    // Entur asks every client for its name, as `company-application`.
    val network = entur.copy(headers = entur.headers + Header("ET-Client-Name", "publictransport-example"))

    val origin = client.locations(network, "Oslo S", kinds = listOf(LocationKind.STOP)).first()
    val destination = client.locations(network, "Lillehammer stasjon", kinds = listOf(LocationKind.STOP)).first()

    // Leaving now. `departAt =` and `arriveBy =` ask for another time.
    // An end can also be a coordinate, with `asPlace()` on both ends, or the
    // ID of a stop as a `Place.Id`.
    val found = client.trips(network, origin, destination, limit = 3)
    println("Trips from ${origin.name} to ${destination.name}:")
    found.trips.forEach(::printTrip)

    // The same arguments again, with the reference to the trips after these.
    found.later?.let { later ->
        println("Later trips:")
        val more = client.trips(network, origin, destination, limit = 3, page = later)
        more.trips.forEach(::printTrip)
    }
}

Find the bundled networks for a position

// Lists the bundled networks that cover a position. This sends no request:
// the networks and their areas ship with the package.

import publictransport.Coordinate
import publictransport.Registry

fun main() {
    val registry = Registry.bundled()
    println("${registry.networks().size} networks are bundled.")

    val duesseldorf = Coordinate(latitude = 51.2198, longitude = 6.7943)
    // The best coverage comes first: real-time data, then complete timetables,
    // then any data.
    println("At Düsseldorf Hauptbahnhof:")
    for (covering in registry.covering(duesseldorf)) {
        val network = covering.network
        println("  ${covering.tier}: ${network.name} (${network.id}, ${network.protocol})")
    }

    // A network by its ID, as an application would store it.
    registry.get("vrr-efa")?.let { network ->
        println("vrr-efa is ${network.name} at ${network.endpoint}")
    }
}