diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
index 804378b..e13982e 100644
--- a/.github/workflows/android.yml
+++ b/.github/workflows/android.yml
@@ -15,7 +15,9 @@ jobs:
java-version: '17'
cache: gradle
- uses: android-actions/setup-android@v3
+ with:
+ packages: platform-tools
- name: Install Android SDK
run: sdkmanager "platform-tools" "platforms;android-37.0" "build-tools;37.0.0"
- name: Verify, test, lint, and assemble
- run: ./gradlew verifyCompatibility :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:assembleRelease
+ run: ./gradlew --no-daemon verifyCompatibility :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:assembleRelease
diff --git a/.gitignore b/.gitignore
index cfb8ef6..6b352a1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,3 +15,8 @@ gradle/gradle-daemon-jvm.properties
local.properties
app/release
AGENTS.md
+__pycache__/
+*.pyc
+*.pyo
+*.pyd
+
diff --git a/TODO.md b/TODO.md
deleted file mode 100644
index ec2f134..0000000
--- a/TODO.md
+++ /dev/null
@@ -1,142 +0,0 @@
-# BART Runner cleanup and efficiency plan
-
-This is the post-Compose cleanup backlog. The major migration work is complete;
-the remaining work should reduce duplicate computation, remove accidental state,
-and keep the implementation simple.
-
-## Working principles
-
-- Favorites persist only their origin and destination.
-- Fares and other schedule-derived values are transient UI data.
-- Prefer a small cache or shared projection over a new abstraction layer.
-- Keep the existing serialized persistence writers unless batching or coalescing
- is needed.
-- Measure startup and rendering changes before optimizing Compose recomposition.
-- Do not migrate storage technologies merely for modernization.
-
-## Phase 1: remove dead pre-Compose code
-
-- [x] Delete `FavoritesArrayAdapter` and `DepartureArrayAdapter`.
-- [x] Delete `CheckableLinearLayout` and `ScreenTicker`.
-- [x] Delete the obsolete route-selection and alarm dialog fragments.
-- [x] Delete unused XML layouts, menus, and legacy action icons.
-- [x] Remove obsolete styles, colors, dimensions, and strings.
-- [x] Remove `viewBinding` after the XML layer was removed.
-
-## Phase 2: simplify dependencies and activity plumbing
-
-- [x] Remove unused RecyclerView, PhotoView, Material Components, and AppCompat dependencies.
-- [x] Convert Compose activities to `ComponentActivity`.
-- [x] Use `by viewModels()` where it improves readability.
-- [x] Remove duplicate or transitively supplied lifecycle dependencies.
-- [x] Update migration documentation to describe Compose as the production UI.
-
-## Phase 3: lifecycle-aware Compose state
-
-- [x] Add lifecycle-aware collection with `collectAsStateWithLifecycle()`.
-- [x] Move alarm state into repository/ViewModel state.
-- [x] Replace the UI-local clock with the shared `TimeSource`-based ticker.
-- [x] Move user-visible text and content descriptions into resources.
-- [x] Add baseline Compose UI coverage for the home screen, route picker,
- departures, trip actions, alarm picker, and map controls.
-- [ ] Expand interaction coverage for route selection, following a trip, alarm
- cancellation, permission denial, and process restoration.
-
-## Phase 4: make favorite persistence minimal
-
-- [x] Persist favorites as records containing only `origin` and `destination`.
-- [x] Stop serializing fare, fare timestamps, average trip length, and sample
- count as part of favorite state.
-- [x] Remove `updateFare()` from `FavoritesRepository` and `RoutesViewModel`.
-- [x] Remove `fareLastUpdated`, `averageTripLength`, and
- `averageTripSampleCount` from `StationPair` if no remaining callers need them.
-- [x] Load fares as transient derived data from the cached static GTFS data.
-- [x] Existing persisted data is intentionally not supported during this
- zero-user development phase; the next write uses the minimal schema.
-
-## Phase 5: remove duplicate feed and projection work
-
-- [x] Establish a clear base-schedule versus realtime-corrected-schedule
- contract between `Schedule` and `GtfsRealtimeContentHandler`.
-- [x] Ensure each feed snapshot applies realtime corrections only once.
-- [x] Avoid rebuilding a protobuf feed and `GtfsRealtimeFeedIndex` from an
- already-indexed entity list during normal projection.
-- [x] Cache the corrected schedule/feed context per `TransitFeedSnapshot` so
- multiple consumers reuse it.
-- [ ] Consolidate per-favorite projection jobs in `RoutesViewModel` where this
- remains simpler than maintaining one full projection per favorite.
-- [x] Cache immutable GTFS-derived route patterns per line in `BartGtfsNetwork`.
-- [ ] Re-evaluate the explicit startup refresh after measuring first-render
- latency; remove it if shared-feed subscription polling is sufficient.
-
-## Phase 6: keep persistence efficient without adding machinery
-
-- [ ] Keep the single-thread persistence writers for deterministic ordering.
-- [x] Coalesce pending favorite writes when several real favorite changes occur
- in quick succession, especially drag-to-reorder operations.
-- [x] Coalesce followed-trip cache writes when successive realtime updates do
- not materially change durable state.
-- [ ] Keep atomic temporary-file replacement for followed-trip and static-feed
- caches, and improve replacement behavior if the platform permits a safer
- atomic move.
-
-## Phase 7: static-feed cache reliability and derived-data caching
-
-- [x] Make a corrupt or unparsable static cache fall back to a refresh instead
- of failing from the fresh-cache path.
-- [x] Persist normalized static GTFS data in Room/SQLite so process restarts
- load topology from the database and query only active, time-windowed trips.
-- [ ] Avoid holding the static-data lock across network I/O if profiling shows
- contention; do not redesign this preemptively.
-
-## Phase 8: lint, resource, and manifest cleanup
-
-- [x] Remove the stale lint suppression for deleted `train_alarm_dialog.xml`.
-- [x] Remove unused `ACCESS_NETWORK_STATE` and `WAKE_LOCK` permissions.
-- [x] Remove lint-reported unused strings and plurals.
-- [x] Move the map bitmap to an appropriate density-independent resource folder.
-- [x] Keep the adaptive launcher icon in `mipmap-anydpi-v31` with a legacy
- fallback for devices below Android 12.
-- [x] Replace the raster notification icon with a white vector drawable and
- make the cancel-alarm action asset density-independent.
-- [x] Add API annotations around full-screen-intent settings access and remove
- redundant SDK guards made unnecessary by `minSdk`.
-- [x] Fix the remaining low-risk Compose lint hints.
-- [x] Keep debug lint at zero errors; the two remaining resource-layout warnings
- are intentional for the adaptive launcher/resource setup.
-
-## Phase 9: staged dependency and SDK maintenance
-
-- [x] Upgrade the version catalog, including lifecycle, coroutines, AndroidX,
- Compose, OkHttp, Jackson, GTFS-RT, and the AndroidX test libraries.
-- [x] Run unit tests, lint, and debug assembly after the dependency upgrade.
-- [x] Run the release assembly and device smoke tests on the Pixel 10a
- emulator.
-- [x] Re-evaluate compile/target SDK against the installed SDK 37; target SDK
- is now 37.
-- [ ] Remove obsolete resource qualifiers only after confirming the supported
- device range.
-
-## Verification checklist
-
-- [x] `:app:testDebugUnitTest`
-- [x] `:app:assembleDebug`
-- [x] `:app:lintDebug`
-- [x] Instrumentation smoke tests on the connected Pixel 10a emulator.
-- [ ] Manually verify route selection and editing.
-- [ ] Manually verify live departures and trip following.
-- [ ] Manually verify alarm setup, cancellation, exact-alarm denial, and
- notification/full-screen-intent denial.
-- [ ] Manually verify background alarm delivery and notification actions.
-- [ ] Manually verify process-death restoration of favorites and followed trips.
-- [ ] Decide whether connected instrumentation should run periodically in CI;
- keep normal CI fast if emulator startup remains too expensive.
-
-## Explicitly deferred unless evidence changes
-
-- Do not migrate tiny preference values to DataStore solely for modernization.
-- Do not move followed-trip JSON to Proto DataStore unless the current schema or
- file-backed cache becomes a real maintenance problem.
-- Do not replace the serialized executors with application coroutine scopes
- unless it simplifies the code or fixes a measured issue.
-- Do not redesign the Compose ticker unless profiling shows meaningful UI cost.
diff --git a/app/build.gradle b/app/build.gradle
index 587a41b..02dbb69 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -54,7 +54,9 @@ dependencies {
implementation(libs.androidx.compose.foundation)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons)
- implementation('com.google.android.gms:play-services-oss-licenses:17.5.1')
+ implementation(libs.coil.compose)
+ implementation(libs.coil.resvg)
+ implementation(libs.play.services.oss.licenses)
}
android {
@@ -95,8 +97,6 @@ android {
buildTypes {
release {
- // Include native debug symbols
- ndk.debugSymbolLevel = 'FULL'
minifyEnabled = true
shrinkResources = true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
diff --git a/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt b/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt
index 8b15728..7052225 100644
--- a/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt
+++ b/app/src/androidTest/kotlin/in/izyum/bart/ui/BartRunnerUiTest.kt
@@ -20,6 +20,7 @@ import `in`.izyum.bart.activities.RoutesUiState
import `in`.izyum.bart.model.Alert
import `in`.izyum.bart.model.Departure
import `in`.izyum.bart.model.Line
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.Station
import `in`.izyum.bart.model.TimeSource
import `in`.izyum.bart.model.TripLeg
@@ -258,7 +259,7 @@ class BartRunnerUiTest {
BartRunnerTheme {
HomeScreen(
state = RoutesUiState(isLoading = false),
- followedTrip = departureBeforeBoarding(now),
+ followedTrip = Itinerary.fromDeparture(departureBeforeBoarding(now)),
timeSource = TimeSource { now },
onRouteSelected = {},
onAddFavorite = {},
@@ -271,7 +272,7 @@ class BartRunnerUiTest {
}
}
- composeRule.onNodeWithText("Train arrives in 10:30").assertIsDisplayed()
+ composeRule.onNodeWithText("Train arrives in 10:00").assertIsDisplayed()
composeRule.onNodeWithText("Trip in progress").assertDoesNotExist()
}
@@ -282,7 +283,9 @@ class BartRunnerUiTest {
BartRunnerTheme {
HomeScreen(
state = RoutesUiState(isLoading = false),
- followedTrip = transferDeparture(now, connectingArrival = now + 120_000L),
+ followedTrip = Itinerary.fromDeparture(
+ transferDeparture(now, connectingArrival = now + 120_000L),
+ ),
timeSource = TimeSource { now },
onRouteSelected = {},
onAddFavorite = {},
@@ -304,7 +307,7 @@ class BartRunnerUiTest {
setTestContent {
BartRunnerTheme {
TripScreen(
- departure = testDeparture(),
+ departure = Itinerary.fromDeparture(testDeparture()),
route = `in`.izyum.bart.model.StationPair(Station.CAST, Station.MLPT),
alerts = Alert.AlertList(
listOf(Alert(id = "trip-alert", description = "BART test alert")),
@@ -381,7 +384,7 @@ class BartRunnerUiTest {
setTestContent {
BartRunnerTheme {
TripScreen(
- departure = testDeparture(),
+ departure = Itinerary.fromDeparture(testDeparture()),
route = `in`.izyum.bart.model.StationPair(Station.CAST, Station.MLPT),
isFollowingInitially = true,
alarmVisible = false,
@@ -409,7 +412,9 @@ class BartRunnerUiTest {
setTestContent {
BartRunnerTheme {
TripScreen(
- departure = transferDeparture(now, connectingArrival = now + 120_000L),
+ departure = Itinerary.fromDeparture(
+ transferDeparture(now, connectingArrival = now + 120_000L),
+ ),
route = `in`.izyum.bart.model.StationPair(Station.CAST, Station.MLPT),
isFollowingInitially = true,
alarmVisible = false,
@@ -437,7 +442,9 @@ class BartRunnerUiTest {
setTestContent {
BartRunnerTheme {
TripScreen(
- departure = transferDeparture(now, connectingArrival = now - 1_000L),
+ departure = Itinerary.fromDeparture(
+ transferDeparture(now, connectingArrival = now - 1_000L),
+ ),
route = `in`.izyum.bart.model.StationPair(Station.CAST, Station.MLPT),
isFollowingInitially = true,
alarmVisible = false,
@@ -481,8 +488,6 @@ class BartRunnerUiTest {
.setTrainDestination(Station.MLPT)
.setPassengerDestination(Station.MLPT)
.setLine(Line.ORANGE)
- .setTrainDestinationColorHex("#ff8c00")
- .setDirection("instrumented-test")
.setMinEstimate(departureTime - 30_000L)
.setMaxEstimate(departureTime + 30_000L)
.setTripLegs(listOf(TripLeg(
@@ -499,7 +504,6 @@ class BartRunnerUiTest {
.setTrainDestination(Station.MLPT)
.setPassengerDestination(Station.MLPT)
.setLine(Line.ORANGE)
- .setDirection("arrival-test")
.setMinEstimate(departureTime - 30_000L)
.setMaxEstimate(departureTime + 30_000L)
.setTripLegs(listOf(
@@ -523,8 +527,6 @@ class BartRunnerUiTest {
.setTrainDestination(Station.MLPT)
.setPassengerDestination(Station.MLPT)
.setLine(Line.BLUE)
- .setTrainDestinationColorHex("#0099cc")
- .setDirection("transfer-test")
.setMinEstimate(now - 600_000L)
.setMaxEstimate(now - 590_000L)
.setTripLegs(listOf(
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index eba0a2e..4511b6c 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -9,9 +9,13 @@
+
+
+
+
+
+
+
diff --git a/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt b/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt
index a1ad9fc..623140c 100644
--- a/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt
+++ b/app/src/main/kotlin/in/izyum/bart/BartRunnerApplication.kt
@@ -3,6 +3,9 @@ package `in`.izyum.bart
import android.app.Application
import android.app.Activity
import android.os.Bundle
+import coil3.ImageLoader
+import coil3.SingletonImageLoader
+import com.hashsequence.coilresvg.ResvgDecoder
import `in`.izyum.bart.backend.TransitFeedSnapshot
import `in`.izyum.bart.backend.HttpTransitFeedClient
import `in`.izyum.bart.backend.TransitRepository
@@ -11,21 +14,18 @@ import `in`.izyum.bart.data.FollowedTripRepository
import `in`.izyum.bart.model.SystemTimeSource
import `in`.izyum.bart.model.TimeSource
import `in`.izyum.bart.networktasks.GtfsStaticData
-import `in`.izyum.bart.networktasks.EtdStationCache
-import `in`.izyum.bart.networktasks.HttpEtdClient
import `in`.izyum.bart.platform.OfflineStatusController
import `in`.izyum.bart.platform.DeparturePollingAlarm
import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
import java.io.IOException
import java.util.function.Supplier
-class BartRunnerApplication : Application() {
+class BartRunnerApplication : Application(), SingletonImageLoader.Factory {
lateinit var favoritesRepository: FavoritesRepository
lateinit var followedTripRepository: FollowedTripRepository
lateinit var transitRepository: TransitRepository
lateinit var gtfsStaticData: GtfsStaticData
lateinit var offlineStatusController: OfflineStatusController
- lateinit var etdStationCache: EtdStationCache
val timeSource: TimeSource = SystemTimeSource
@@ -42,14 +42,13 @@ class BartRunnerApplication : Application() {
favoritesRepository = FavoritesRepository(this)
followedTripRepository = FollowedTripRepository(this)
gtfsStaticData = GtfsStaticData(this, timeSource)
- etdStationCache = EtdStationCache(HttpEtdClient(), timeSource)
transitRepository = TransitRepository(
HttpTransitFeedClient(),
15_000L,
offlineSnapshotProvider = { TransitFeedSnapshot.empty(timeSource.nowMillis()) },
)
offlineStatusController = OfflineStatusController(this, transitRepository, followedTripRepository) {
- transitRepository.refreshNow()
+ transitRepository.refresh()
}
DeparturePollingAlarm.refresh(this, followedTripRepository)
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
@@ -75,4 +74,11 @@ class BartRunnerApplication : Application() {
})
}
+ override fun newImageLoader(context: coil3.PlatformContext): ImageLoader =
+ ImageLoader.Builder(context)
+ .components {
+ add(ResvgDecoder.Factory())
+ }
+ .build()
+
}
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt
index 5801bc8..da73f7e 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/AboutActivity.kt
@@ -1,11 +1,11 @@
package `in`.izyum.bart.activities
import android.content.Intent
-import android.net.Uri
import android.os.Bundle
import android.os.Build
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
+import androidx.core.net.toUri
import `in`.izyum.bart.BuildConfig
import `in`.izyum.bart.R
import `in`.izyum.bart.ui.AboutScreen
@@ -25,7 +25,7 @@ class AboutActivity : ComponentActivity() {
startActivity(
Intent(
Intent.ACTION_VIEW,
- Uri.parse(getString(R.string.github_url)),
+ getString(R.string.github_url).toUri(),
)
)
},
@@ -33,7 +33,7 @@ class AboutActivity : ComponentActivity() {
startActivity(
Intent(
Intent.ACTION_VIEW,
- Uri.parse(getString(R.string.apache_license_url)),
+ getString(R.string.apache_license_url).toUri(),
)
)
},
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt
index 17b4fdd..eb86159 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/DeparturesViewModel.kt
@@ -3,13 +3,11 @@ package `in`.izyum.bart.activities
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import `in`.izyum.bart.backend.RouteDepartureProjection
-import `in`.izyum.bart.backend.EtdAwareRouteDepartureProjection
import `in`.izyum.bart.backend.TransitRepository
import `in`.izyum.bart.model.Departure
import `in`.izyum.bart.model.StationPair
import `in`.izyum.bart.model.SystemTimeSource
import `in`.izyum.bart.model.TimeSource
-import `in`.izyum.bart.networktasks.EtdStationCache
import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
@@ -58,7 +56,6 @@ class DeparturesViewModel @JvmOverloads constructor(
repository: TransitRepository,
networkSupplier: Supplier,
stationPair: StationPair?,
- etdStationCache: EtdStationCache? = null,
) {
collectionJob?.cancel()
collectionJob = null
@@ -70,33 +67,22 @@ class DeparturesViewModel @JvmOverloads constructor(
collectionJob = viewModelScope.launch {
val baseProjection = RouteDepartureProjection(stationPair, networkSupplier)
- val etdProjection = etdStationCache?.let {
- EtdAwareRouteDepartureProjection(baseProjection, it)
- }
- val projectedState = if (etdProjection != null) {
- repository.projectedStateSuspending(
- etdProjection::project,
- etdProjection::areEquivalent,
- )
- } else {
- repository.projectedState(
- baseProjection::project,
- baseProjection::areEquivalent,
- )
- }
- projectedState
+ repository.projectedState(
+ baseProjection::project,
+ baseProjection::areEquivalent,
+ )
.collectLatest { result ->
result.exceptionOrNull()?.let { exception ->
updateError(asException(exception))
} ?: result.getOrNull()?.let { departures ->
- updateFromFeed(departures.getDepartures())
+ replace(departures.getDepartures())
}
}
}
}
@Synchronized
- fun replace(incoming: List): List {
+ internal fun replace(incoming: List): List {
departures = immutableCopy(Departure.replaceFeed(departures, incoming, timeSource))
_uiState.value = if (departures.isEmpty()) {
State.empty()
@@ -106,23 +92,6 @@ class DeparturesViewModel @JvmOverloads constructor(
return departures
}
- @Synchronized
- fun clear(): List {
- departures = emptyList()
- _uiState.value = State.empty()
- return departures
- }
-
- fun getState(): State = uiState.value
-
- @Synchronized
- fun getDepartures(): List = departures
-
- @Synchronized
- private fun updateFromFeed(incoming: List) {
- replace(incoming)
- }
-
@Synchronized
private fun updateError(exception: Exception) {
_uiState.value = State.error(exception, departures)
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/RouteArguments.kt b/app/src/main/kotlin/in/izyum/bart/activities/RouteArguments.kt
index 3528517..d9e1ca5 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/RouteArguments.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/RouteArguments.kt
@@ -9,7 +9,7 @@ import `in`.izyum.bart.model.StationPair
object RouteArguments {
const val ORIGIN = "routeOrigin"
const val DESTINATION = "routeDestination"
- const val DEPARTURE_IDENTITY = "departureIdentity"
+ const val SELECTION_IDENTITY = "selectionIdentity"
const val SCREEN_MODE = "screenMode"
const val MODE_SCHEDULE = "schedule"
@@ -30,10 +30,10 @@ object RouteArguments {
}
@JvmStatic
- fun putTrip(intent: Intent?, route: StationPair?, identity: String?, mode: String?) {
+ fun putTrip(intent: Intent?, route: StationPair?, selectionIdentity: String?, mode: String?) {
if (intent == null) return
putRoute(intent, route)
- intent.putExtra(DEPARTURE_IDENTITY, identity)
+ intent.putExtra(SELECTION_IDENTITY, selectionIdentity)
intent.putExtra(SCREEN_MODE, mode)
}
@@ -48,8 +48,8 @@ object RouteArguments {
}
@JvmStatic
- fun readDepartureIdentity(intent: Intent?): String? =
- intent?.getStringExtra(DEPARTURE_IDENTITY)
+ fun readSelectionIdentity(intent: Intent?): String? =
+ intent?.getStringExtra(SELECTION_IDENTITY)
@JvmStatic
fun readScreenMode(intent: Intent?): String? = intent?.getStringExtra(SCREEN_MODE)
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt
index 2a39889..27ec823 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/RoutesListActivity.kt
@@ -89,7 +89,7 @@ class RoutesListActivity : ComponentActivity() {
}
}
lifecycleScope.launch(Dispatchers.IO) {
- PerformanceTrace.section("BART startup refresh") {
+ PerformanceTrace.suspendSection("BART startup refresh") {
application.transitRepository.refreshIfStale()
}
}
@@ -110,8 +110,8 @@ class RoutesListActivity : ComponentActivity() {
}
}
val followedTripState by application.followedTripRepository.state.collectAsStateWithLifecycle()
- val followedTrip = if (followedTripState.departure != null) {
- application.followedTripRepository.getFollowedDeparture()
+ val followedTrip = if (followedTripState.itinerary != null) {
+ application.followedTripRepository.getFollowedItinerary()
} else {
null
}
@@ -129,12 +129,12 @@ class RoutesListActivity : ComponentActivity() {
onRemoveFavorite = routesViewModel::removeFavorite,
onMoveFavorite = routesViewModel::moveFavorite,
onInsertFavorite = routesViewModel::insertFavorite,
- onViewTrip = { departure ->
+ onViewTrip = { itinerary ->
startActivity(Intent(this, TripInProgressActivity::class.java).apply {
RouteArguments.putTrip(
this,
- departure.getStationPair(),
- departure.identity,
+ itinerary.getStationPair(),
+ itinerary.selectionIdentity,
RouteArguments.MODE_FOLLOWED,
)
})
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt
index dfe9cc6..6270f9d 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/RoutesViewModel.kt
@@ -5,7 +5,6 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import `in`.izyum.bart.BartRunnerApplication
import `in`.izyum.bart.backend.AlertProjection
-import `in`.izyum.bart.backend.EtdAwareRouteDepartureProjection
import `in`.izyum.bart.backend.RouteDepartureProjection
import `in`.izyum.bart.data.FareDiscountPreferences
import `in`.izyum.bart.data.FavoritesRepository
@@ -155,13 +154,9 @@ class RoutesViewModel(application: Application) : AndroidViewModel(application)
route,
app.bartGtfsNetworkSupplier,
)
- val projection = EtdAwareRouteDepartureProjection(
- baseProjection,
- app.etdStationCache,
- )
- transitRepository.projectedStateSuspending(
- projection::project,
- projection::areEquivalent,
+ transitRepository.projectedState(
+ baseProjection::project,
+ baseProjection::areEquivalent,
).collectLatest { state ->
state.exceptionOrNull()?.let { exception ->
publishError(asException(exception))
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/TripActionsViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/TripActionsViewModel.kt
index 5263dd9..4f72fe7 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/TripActionsViewModel.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/TripActionsViewModel.kt
@@ -3,8 +3,7 @@ package `in`.izyum.bart.activities
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import `in`.izyum.bart.BartRunnerApplication
-import `in`.izyum.bart.model.Departure
-import `in`.izyum.bart.model.Station
+import `in`.izyum.bart.model.Itinerary
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -22,10 +21,10 @@ class TripActionsViewModel(application: Application) :
private val _uiState = MutableStateFlow(readUiState())
val uiState: StateFlow = _uiState.asStateFlow()
- fun getFollowedDeparture(): Departure? = followedTripRepository.getFollowedDeparture()
+ fun getFollowedItinerary(): Itinerary? = followedTripRepository.getFollowedItinerary()
- fun isFollowing(departure: Departure): Boolean =
- followedTripRepository.getFollowedDeparture() == departure
+ fun isFollowing(itinerary: Itinerary): Boolean =
+ followedTripRepository.getFollowedItinerary() == itinerary
fun isAlarmPending(): Boolean = followedTripRepository.getAlarmScheduler()?.isPending == true
@@ -36,18 +35,14 @@ class TripActionsViewModel(application: Application) :
_uiState.value = readUiState()
}
- fun followTrip(departure: Departure, passengerDestination: Station? = null) {
- followedTripRepository.setFollowedDeparture(
- prepareDepartureForFollowing(departure, passengerDestination),
- )
+ fun followTrip(itinerary: Itinerary) {
+ followedTripRepository.setFollowedItinerary(itinerary)
followedTripRepository.startTracking()
}
- fun updateFollowedTrip(departure: Departure) {
- followedTripRepository.getFollowedDeparture()?.let { current ->
- followedTripRepository.setFollowedDeparture(
- prepareDepartureForFollowing(departure, current.passengerDestination),
- )
+ fun updateFollowedTrip(itinerary: Itinerary) {
+ followedTripRepository.getFollowedItinerary()?.let {
+ followedTripRepository.setFollowedItinerary(itinerary)
}
}
@@ -70,11 +65,3 @@ class TripActionsViewModel(application: Application) :
alarmLeadTimeMinutes = getAlarmLeadTimeMinutes(),
)
}
-
-/** Ensures a departure followed from trip details has the destination required by notifications. */
-internal fun prepareDepartureForFollowing(
- departure: Departure,
- passengerDestination: Station? = null,
-): Departure = departure.withPassengerDestination(
- passengerDestination ?: departure.passengerDestination ?: departure.trainDestination,
-)
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt
index 89c9365..1d94ea4 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/TripInProgressActivity.kt
@@ -25,6 +25,7 @@ import `in`.izyum.bart.BartRunnerApplication
import `in`.izyum.bart.data.FareDiscountPreferences
import `in`.izyum.bart.R
import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.Station
import `in`.izyum.bart.model.StationPair
import `in`.izyum.bart.presentation.DepartureTextFormatter
@@ -49,7 +50,6 @@ class TripInProgressActivity : ComponentActivity() {
private val tripActionsViewModel: TripActionsViewModel by viewModels()
private val serviceAlertsViewModel: ServiceAlertsViewModel by viewModels()
private var isFollowing = false
- private var routeDestination: Station? = null
private var tripRoute: StationPair? = null
private var tripFare by mutableStateOf(null)
private var fareEligible = false
@@ -76,7 +76,7 @@ class TripInProgressActivity : ComponentActivity() {
alarmVisible = true
showAlarmWindow()
}
- if (intent.getStringExtra(RouteArguments.DEPARTURE_IDENTITY) != null) {
+ if (intent.getStringExtra(RouteArguments.SELECTION_IDENTITY) != null) {
setIntent(intent)
recreate()
}
@@ -85,26 +85,22 @@ class TripInProgressActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val app = application as BartRunnerApplication
- val followed = tripActionsViewModel.getFollowedDeparture()
+ val followed = tripActionsViewModel.getFollowedItinerary()
var route = RouteArguments.readRoute(intent)
- var identity = RouteArguments.readDepartureIdentity(intent)
+ var selectionIdentity = RouteArguments.readSelectionIdentity(intent)
val screenMode = RouteArguments.readScreenMode(intent)
- if (shouldReturnToRoutes(screenMode, followed)) {
- startActivity(Intent(this, RoutesListActivity::class.java).apply {
- addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
- })
- finish()
+ if (shouldReturnToRoutes(screenMode, followed?.toDeparture())) {
+ returnToRoutes()
return
}
if (route == null && followed != null && (screenMode == null || screenMode == RouteArguments.MODE_FOLLOWED)) {
- identity = followed.identity
+ selectionIdentity = followed.selectionIdentity
route = followed.getStationPair()
}
- if (route == null || identity == null) {
- finish()
+ if (route == null || selectionIdentity == null) {
+ returnToRoutes()
return
}
- routeDestination = route.destination
tripRoute = route
fareEligible = route.destination != null
tripFare = null
@@ -116,33 +112,41 @@ class TripInProgressActivity : ComponentActivity() {
if (alarmVisible) {
showAlarmWindow()
}
- isFollowing = followed != null && identity == followed.identity
+ isFollowing = followed != null && selectionIdentity == followed.selectionIdentity
tripProgressViewModel.setQuery(
route,
- identity,
- app.timeSource,
- initialDeparture = if (isFollowing) followed else null,
+ selectionIdentity,
+ initialItinerary = if (isFollowing) followed else null,
)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
- tripProgressViewModel.departureState.collect { updated ->
- if (updated != null) {
- if (isFollowing) tripActionsViewModel.updateFollowedTrip(updated)
- resolveFare(app, updated.getStationPair())
+ launch {
+ tripProgressViewModel.itineraryState.collect { updated ->
+ if (updated != null) {
+ if (isFollowing) tripActionsViewModel.updateFollowedTrip(updated)
+ resolveFare(app, updated.getStationPair())
+ }
+ }
+ }
+ launch {
+ tripProgressViewModel.resolutionState.collect { state ->
+ if (state == TripResolutionState.NOT_FOUND && !isFinishing) {
+ returnToRoutes()
+ }
}
}
}
}
setContent {
- val departure by tripProgressViewModel.departureState.collectAsStateWithLifecycle()
+ val itinerary by tripProgressViewModel.itineraryState.collectAsStateWithLifecycle()
val tripActionsState by tripActionsViewModel.uiState.collectAsStateWithLifecycle()
val alerts by serviceAlertsViewModel.alerts.collectAsStateWithLifecycle()
val isOffline by app.offlineStatusController.isOffline.collectAsStateWithLifecycle()
BartRunnerTheme {
TripScreen(
- departure = departure,
+ departure = itinerary,
route = tripRoute,
alerts = alerts,
isOffline = isOffline,
@@ -170,6 +174,13 @@ class TripInProgressActivity : ComponentActivity() {
}
}
+ private fun returnToRoutes() {
+ startActivity(Intent(this, RoutesListActivity::class.java).apply {
+ addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
+ })
+ finish()
+ }
+
private fun silenceAlarm() {
alarmVisible = false
NotificationManagerCompat.from(this)
@@ -254,9 +265,9 @@ class TripInProgressActivity : ComponentActivity() {
}
}
- private fun followTrip(departure: Departure) {
+ private fun followTrip(itinerary: Itinerary) {
if (isFollowing) return
- tripActionsViewModel.followTrip(departure, tripRoute?.destination)
+ tripActionsViewModel.followTrip(itinerary)
requestNotificationPermissionIfNeeded()
startAlarmTrackingService()
isFollowing = true
@@ -285,15 +296,12 @@ class TripInProgressActivity : ComponentActivity() {
}
}
- private fun shareArrival(departure: Departure) {
- val destination = departure.getStationPair()?.destination
- ?: routeDestination
- ?: departure.trainDestination
- ?: return
+ private fun shareArrival(itinerary: Itinerary) {
+ val destination = itinerary.destination
val message = getString(
R.string.arrival_message,
destination.getName(),
- DepartureTextFormatter.estimatedArrivalTime(this, departure, false),
+ DepartureTextFormatter.estimatedArrivalTime(this, itinerary),
)
startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt b/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt
index fe694e6..886da78 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/TripProgressViewModel.kt
@@ -8,102 +8,129 @@ import `in`.izyum.bart.backend.RouteDepartureProjection
import `in`.izyum.bart.backend.TransitRepository
import `in`.izyum.bart.backend.TripProgressProjection
import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.StationPair
-import `in`.izyum.bart.model.TimeSource
-import `in`.izyum.bart.model.TripLeg
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.launch
+enum class TripResolutionState {
+ LOADING,
+ READY,
+ NOT_FOUND,
+}
+
/** Owns live trip state from the shared feed until the screen ViewModel clears. */
class TripProgressViewModel(application: Application) :
AndroidViewModel(application) {
- private val _departureState = MutableStateFlow(null)
- val departureState: StateFlow = _departureState.asStateFlow()
+ private val _itineraryState = MutableStateFlow(null)
+ val itineraryState: StateFlow = _itineraryState.asStateFlow()
+
+ private val _resolutionState = MutableStateFlow(TripResolutionState.LOADING)
+ val resolutionState: StateFlow = _resolutionState.asStateFlow()
private var routeCollectionJob: Job? = null
private var tripProgressCollectionJob: Job? = null
- private var departureTimeSource: TimeSource? = null
- private var queryStationPair: StationPair? = null
-
fun setQuery(
stationPair: StationPair,
- departureIdentity: String,
- timeSource: TimeSource,
- initialDeparture: Departure? = null,
+ selectionIdentity: String,
+ initialItinerary: Itinerary? = null,
) {
cancelCollections()
- departureTimeSource = timeSource
- queryStationPair = stationPair
- _departureState.value = initialDeparture
+ _itineraryState.value = initialItinerary
+ _resolutionState.value = if (initialItinerary == null) {
+ TripResolutionState.LOADING
+ } else {
+ TripResolutionState.READY
+ }
val application = getApplication()
val repository: TransitRepository = application.transitRepository
- routeCollectionJob = viewModelScope.launch {
- val projection = RouteDepartureProjection(
- stationPair,
- application.bartGtfsNetworkSupplier,
- )
- repository.projectedState(projection::project, projection::areEquivalent)
- .collectLatest { result ->
- result.getOrNull()?.let { departures ->
- departures.getDepartures()
- .firstOrNull { it.identity == departureIdentity }
- ?.let(::updateFromRealtime)
+ initialItinerary?.let(::startTripProgress)
+ if (initialItinerary == null) {
+ routeCollectionJob = viewModelScope.launch {
+ val projection = RouteDepartureProjection(
+ stationPair,
+ application.bartGtfsNetworkSupplier,
+ )
+ val itinerary = repository
+ .projectedState(projection::project, projection::areEquivalent)
+ .mapNotNull { result -> result.getOrNull() }
+ .map { departures ->
+ departures.getDepartures()
+ .firstOrNull {
+ it.matchesSelectionIdentity(stationPair, selectionIdentity)
+ }
+ ?.let { incoming -> itineraryFromDeparture(incoming, stationPair) }
+ }
+ .first()
+ if (itinerary == null) {
+ _resolutionState.value = TripResolutionState.NOT_FOUND
+ } else {
+ publish(itinerary)
+ _resolutionState.value = TripResolutionState.READY
+ startTripProgress(itinerary)
}
}
}
}
- fun getDeparture(): Departure? = departureState.value
+ fun getItinerary(): Itinerary? = itineraryState.value
- private fun updateFromRealtime(incoming: Departure) {
- val timeSource = departureTimeSource ?: return
- val normalizedIncoming = queryStationPair?.destination?.let {
- incoming.withPassengerDestination(it)
- } ?: incoming
- val current = departureState.value
- val updated = current?.let {
- Departure.merge(it, normalizedIncoming, true, timeSource)
- } ?: normalizedIncoming
- publish(updated)
- startTripProgress(updated)
- }
-
- private fun startTripProgress(departure: Departure) {
+ private fun startTripProgress(itinerary: Itinerary) {
if (tripProgressCollectionJob?.isActive == true
- || departure.tripLegs.isEmpty()
+ || itinerary.legs.isEmpty()
) {
return
}
- val stationPair = departure.getStationPair() ?: return
- val origin = stationPair.origin
- val destination = stationPair.destination ?: return
val application = getApplication()
tripProgressCollectionJob = viewModelScope.launch {
val projection = TripProgressProjection(
- origin,
- destination,
- departure.tripLegs,
+ itinerary.origin,
+ itinerary.destination,
+ itinerary.legs,
application.bartGtfsNetworkSupplier,
)
application.transitRepository
- .projectedState(projection::project)
- .collectLatest { result -> result.getOrNull()?.let(::updateTripLegs) }
+ .projectedState(projection::projectItinerary)
+ .collectLatest { result -> result.getOrNull()?.let(::publish) }
}
}
- private fun updateTripLegs(updatedLegs: List) {
- departureState.value?.let { publish(it.replaceTripLegs(updatedLegs)) }
+ private fun publish(replacement: Itinerary) {
+ _itineraryState.value = replacement
}
- private fun publish(replacement: Departure) {
- _departureState.value = replacement
+ private fun itineraryFromDeparture(
+ departure: Departure,
+ stationPair: StationPair,
+ ): Itinerary? = Itinerary.fromDeparture(
+ if (stationPair.destination != null) {
+ departure.withPassengerDestination(stationPair.destination)
+ } else {
+ departure
+ },
+ )
+
+ private fun Departure.matchesSelectionIdentity(
+ stationPair: StationPair,
+ selectionIdentity: String,
+ ): Boolean {
+ val firstLeg = tripLegs.firstOrNull()
+ if (firstLeg?.tripIdentity?.toString() == selectionIdentity) return true
+
+ val origin = origin ?: return false
+ val destination = stationPair.destination ?: trainDestination ?: return false
+ return selectionIdentity ==
+ "itinerary|${origin.abbreviation}|${destination.abbreviation}|${firstLeg?.departureTime ?: 0L}"
}
private fun cancelCollections() {
diff --git a/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt b/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt
index f2690e7..e163595 100644
--- a/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt
+++ b/app/src/main/kotlin/in/izyum/bart/activities/ViewDeparturesActivity.kt
@@ -13,6 +13,7 @@ import androidx.lifecycle.lifecycleScope
import `in`.izyum.bart.BartRunnerApplication
import `in`.izyum.bart.data.FareDiscountPreferences
import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.StationPair
import `in`.izyum.bart.ui.BartRunnerTheme
import `in`.izyum.bart.ui.DeparturesScreen
@@ -51,7 +52,6 @@ class ViewDeparturesActivity : ComponentActivity() {
app.transitRepository,
app.bartGtfsNetworkSupplier,
stationPair,
- app.etdStationCache,
)
setContent {
val state by departuresViewModel.uiState.collectAsStateWithLifecycle()
@@ -80,8 +80,14 @@ class ViewDeparturesActivity : ComponentActivity() {
private fun openTripSchedule(departure: Departure) {
val prepared = prepareDepartureForTrip(departure)
+ val itinerary = Itinerary.fromDeparture(prepared) ?: return
startActivity(Intent(this, TripInProgressActivity::class.java).apply {
- RouteArguments.putTrip(this, stationPair, prepared.identity, RouteArguments.MODE_SCHEDULE)
+ RouteArguments.putTrip(
+ this,
+ stationPair,
+ itinerary.selectionIdentity,
+ RouteArguments.MODE_SCHEDULE,
+ )
})
}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt b/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt
index d052c29..2cc6004 100644
--- a/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt
+++ b/app/src/main/kotlin/in/izyum/bart/backend/AlertProjection.kt
@@ -1,7 +1,6 @@
package `in`.izyum.bart.backend
import `in`.izyum.bart.model.Alert
-import `in`.izyum.bart.networktasks.GtfsRealtimeFeedIndex
import `in`.izyum.bart.performance.PerformanceTrace
import com.google.transit.realtime.GtfsRealtime
@@ -9,9 +8,8 @@ import com.google.transit.realtime.GtfsRealtime
class AlertProjection {
fun project(snapshot: TransitFeedSnapshot): Alert.AlertList {
return PerformanceTrace.section("BART alert projection") {
- val index: GtfsRealtimeFeedIndex = snapshot.getAlertIndex()
val alerts = mutableListOf()
- for (entity in index.alertEntities) {
+ for (entity in snapshot.getNormalizedAlerts().entities) {
if (!entity.hasAlert()) {
continue
}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/CanonicalRoutingAdapter.kt b/app/src/main/kotlin/in/izyum/bart/backend/CanonicalRoutingAdapter.kt
new file mode 100644
index 0000000..6693a74
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/backend/CanonicalRoutingAdapter.kt
@@ -0,0 +1,99 @@
+package `in`.izyum.bart.backend
+
+import `in`.izyum.bart.model.Line
+import `in`.izyum.bart.model.Route
+import `in`.izyum.bart.model.Station
+import `in`.izyum.bart.routing.RaptorRouter
+import `in`.izyum.bart.routing.TransferPolicy
+import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
+import java.util.LinkedHashMap
+
+/** Converts canonical trips to RAPTOR input and owns canonical journey ranking. */
+class CanonicalRoutingAdapter(
+ private val network: BartGtfsNetwork,
+ private val transferPolicy: TransferPolicy = TransferPolicy(network),
+) {
+ data class Input(
+ val trip: Schedule.Trip,
+ val raptorTrip: RaptorRouter.Trip,
+ )
+
+ fun inputs(schedule: Schedule): List = inputs(schedule.trips)
+
+ fun inputs(trips: List): List = trips.map { trip ->
+ Input(trip, raptorTrip(trip))
+ }
+
+ fun router(inputs: List): RaptorRouter = RaptorRouter(
+ inputs.map { it.raptorTrip },
+ network,
+ transferPolicy,
+ )
+
+ fun bestJourney(
+ router: RaptorRouter,
+ origin: Station,
+ destination: Station,
+ departureTime: Long,
+ ): RaptorRouter.Journey? = router.journeys(origin, destination, departureTime)
+ .minWithOrNull(
+ compareBy { it.arrivalTime }
+ .thenBy { it.transferCount }
+ .thenBy { routeForJourney(it)?.let(transferPolicy::routeScore) ?: Int.MAX_VALUE },
+ )
+
+ fun routeForJourney(journey: RaptorRouter.Journey): Route? {
+ val legs = journey.legs
+ val origin = legs.firstOrNull()?.origin ?: return null
+ val destination = legs.lastOrNull()?.destination ?: return null
+ if (legs.size == 1) {
+ val leg = legs.single()
+ return Route.direct(
+ origin,
+ destination,
+ leg.trip.line,
+ leg.trip.direction,
+ leg.trip.stops.map { it.station },
+ )
+ }
+ val sequences = LinkedHashMap>()
+ legs.forEach { leg ->
+ sequences[leg.trip.line] = leg.trip.stops.map { it.station }
+ }
+ return Route.transfer(
+ origin,
+ destination,
+ legs.map { it.trip.line },
+ legs.dropLast(1).map { it.destination },
+ legs.first().trip.direction,
+ sequences,
+ )
+ }
+
+ fun canonicalTripId(trip: Schedule.Trip): String =
+ "${trip.key.serviceDate}:${trip.key.tripId}"
+
+ private fun raptorTrip(trip: Schedule.Trip): RaptorRouter.Trip {
+ val stops = trip.stops.map { stop ->
+ RaptorRouter.StopTime(
+ station = stop.station,
+ arrivalTime = stop.arrivalTime,
+ departureTime = stop.departureTime,
+ scheduledArrivalTime = stop.scheduledArrivalTime,
+ scheduledDepartureTime = stop.scheduledDepartureTime,
+ arrivalSource = stop.arrivalSource,
+ departureSource = stop.departureSource,
+ platform = stop.platform,
+ )
+ }
+ return RaptorRouter.Trip(
+ id = canonicalTripId(trip),
+ line = trip.line,
+ direction = trip.direction,
+ trainDestination = trip.trainDestination,
+ stops = stops,
+ payload = trip,
+ canceled = trip.canceled,
+ )
+ }
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/CanonicalTransitSnapshot.kt b/app/src/main/kotlin/in/izyum/bart/backend/CanonicalTransitSnapshot.kt
new file mode 100644
index 0000000..b552b95
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/backend/CanonicalTransitSnapshot.kt
@@ -0,0 +1,182 @@
+package `in`.izyum.bart.backend
+
+import `in`.izyum.bart.transit.normalization.AssociationStatus
+import `in`.izyum.bart.transit.normalization.AssociationConfidence
+import `in`.izyum.bart.transit.normalization.NormalizedRealtimeFeed
+import `in`.izyum.bart.transit.normalization.RequiredCounterpartStatus
+import `in`.izyum.bart.transit.normalization.RequiredTransferPair
+import `in`.izyum.bart.transit.normalization.StaticTripIdentity
+import `in`.izyum.bart.transit.normalization.TripAssociation
+import `in`.izyum.bart.transit.normalization.TripAssociator
+import `in`.izyum.bart.model.Line
+import `in`.izyum.bart.model.Station
+import java.util.Collections
+
+enum class PassengerTripAvailability {
+ SCHEDULE_ONLY,
+ REALTIME_OBSERVED,
+ CANCELED_EXPLICIT,
+}
+
+/** One consumer-neutral passenger trip state derived from the canonical feed. */
+data class PassengerTripState(
+ val trip: Schedule.Trip,
+ val availability: PassengerTripAvailability,
+ val association: TripAssociation?,
+ val transferPair: RequiredTransferPair? = null,
+)
+
+/**
+ * The single normalization boundary for all app consumers. Static schedule,
+ * raw realtime facts, identity decisions, and terminal telemetry stay
+ * separate here instead of being reconstructed in each projection. The
+ * returned schedule already includes any unambiguous DMU stop-time merge.
+ */
+class CanonicalTransitSnapshot private constructor(
+ val normalizedFeed: NormalizedRealtimeFeed,
+ val correctedSchedule: Schedule,
+ val associations: List,
+ val passengerTrips: List,
+ val requiredTransferPairs: List,
+) {
+ companion object {
+ @JvmStatic
+ fun create(baseSchedule: Schedule, normalizedFeed: NormalizedRealtimeFeed): CanonicalTransitSnapshot {
+ val staticTrips = baseSchedule.trips
+ .map { StaticTripIdentity(it.key.serviceDate, it.key.tripId) }
+ val associations = TripAssociator.associate(staticTrips, normalizedFeed)
+ val byIdentity = associations.filter { it.status == AssociationStatus.EXACT }
+ .mapNotNull { association -> association.staticIdentity?.let { it to association } }
+ .toMap()
+ val exactCorrected = baseSchedule.applyRealtime(normalizedFeed)
+ val requiredPairs = buildRequiredTransferPairs(exactCorrected, associations)
+ val corrected = exactCorrected.applyDmuTransferPairs(requiredPairs)
+ val transferByIdentity = requiredPairs.mapNotNull { pair ->
+ pair.passengerIdentity?.let { it to pair }
+ }.toMap()
+ val passengerTrips = corrected.trips.map { trip ->
+ val identity = StaticTripIdentity(trip.key.serviceDate, trip.key.tripId)
+ val association = byIdentity[identity]
+ val transferPair = transferByIdentity[identity]
+ val availability = when {
+ association?.observation?.explicitlyCanceled == true ->
+ PassengerTripAvailability.CANCELED_EXPLICIT
+ association != null || transferPair != null ->
+ PassengerTripAvailability.REALTIME_OBSERVED
+ else -> PassengerTripAvailability.SCHEDULE_ONLY
+ }
+ PassengerTripState(trip, availability, association, transferPair)
+ }
+ return CanonicalTransitSnapshot(
+ normalizedFeed,
+ corrected,
+ immutableList(associations),
+ immutableList(passengerTrips),
+ immutableList(requiredPairs),
+ )
+ }
+ }
+}
+
+private fun buildRequiredTransferPairs(
+ schedule: Schedule,
+ associations: List,
+): List {
+ val exactPassengerIds = associations.asSequence()
+ .filter { it.status == AssociationStatus.EXACT }
+ .mapNotNull { it.staticIdentity }
+ .toSet()
+ val exactYellow = associations.filter { association ->
+ association.status == AssociationStatus.EXACT
+ && association.staticIdentity in exactPassengerIds
+ && association.staticIdentity?.let { identity ->
+ schedule.trips.any {
+ StaticTripIdentity(it.key.serviceDate, it.key.tripId) == identity
+ && it.line == Line.YELLOW
+ && !it.canceled
+ }
+ } == true
+ }
+ val usedPassengerIds = mutableSetOf()
+ return associations.asSequence()
+ .filter { it.status == AssociationStatus.OPERATIONAL_TELEMETRY }
+ .sortedBy { it.observation.entityOrder }
+ .map { telemetry ->
+ val observed = telemetry.observation.stops.mapNotNull { stop ->
+ val station = schedule.stationForStopId(stop.stopId) ?: return@mapNotNull null
+ val time = stop.departureTimeMillis ?: stop.arrivalTimeMillis
+ ?: return@mapNotNull null
+ station to (stop to time)
+ }.let { entries ->
+ // Stop sequence is the preferred order for association. If
+ // it is absent, the normalizer's protobuf order is retained.
+ val ordered = if (entries.all { it.second.first.stopSequence != null }) {
+ entries.sortedBy { it.second.first.stopSequence }
+ } else {
+ entries
+ }
+ ordered.associate { entry -> entry.first to entry.second.second }
+ }
+ val firstObserved = observed.entries.firstOrNull()
+ // Keep the complete normalized DMU stop sequence. In particular,
+ // BART may include a PITT prediction in the DMU entity even though
+ // PITT is the electric handoff station. Station classification is
+ // not a reason to discard an observed stop.
+ val compatible = if (observed.isNotEmpty() && firstObserved != null) {
+ schedule.trips.filter { trip ->
+ val identity = StaticTripIdentity(trip.key.serviceDate, trip.key.tripId)
+ trip.key.serviceDate == telemetry.serviceDate
+ && trip.line == Line.YELLOW
+ && !trip.canceled
+ && identity !in usedPassengerIds
+ && trip.stops.map { it.station }.containsAll(TERMINAL_STATIONS)
+ && observed.keys.map { station ->
+ trip.stops.indexOfFirst { it.station == station }
+ }.zipWithNext().all { (before, after) ->
+ before >= 0 && after > before
+ }
+ && trip.stopAt(firstObserved.key)?.scheduledDepartureTime?.let { scheduled ->
+ kotlin.math.abs(scheduled - firstObserved.value) <=
+ OPERATIONAL_TIMING_WINDOW_MILLIS
+ } == true
+ }.singleOrNull()
+ } else {
+ null
+ }
+ val identity = compatible?.let {
+ StaticTripIdentity(it.key.serviceDate, it.key.tripId)
+ }
+ if (identity != null) usedPassengerIds += identity
+ val electric = exactYellow.firstOrNull { it.staticIdentity == identity }
+ RequiredTransferPair(
+ operationalObservation = telemetry.observation,
+ passengerIdentity = identity,
+ electricAssociation = electric,
+ status = if (electric == null) {
+ RequiredCounterpartStatus.REQUIRED_COUNTERPART_NOT_OBSERVED
+ } else {
+ RequiredCounterpartStatus.OBSERVED
+ },
+ confidence = if (identity == null) AssociationConfidence.LOW
+ else if (electric == null) AssociationConfidence.HIGH
+ else AssociationConfidence.HIGH,
+ evidence = when {
+ identity == null ->
+ "No unique same-date Yellow passenger trip matched the DMU stop sequence and five-minute schedule window"
+ electric == null ->
+ "DMU telemetry matched a unique same-date Yellow passenger trip; electric realtime counterpart was not observed"
+ else ->
+ "DMU telemetry linked to the exact electric passenger trip at PITT"
+ },
+ )
+ }.toList()
+}
+
+private fun immutableList(values: Collection): List =
+ Collections.unmodifiableList(ArrayList(values))
+
+private val TERMINAL_STATIONS = setOf(Station.PITT, Station.PCTR, Station.ANTC)
+// The Antioch shuttle normally runs on a 20-minute cadence. A five-minute
+// window leaves room for real delay while preventing one shuttle observation
+// from being projected onto the adjacent scheduled passenger departure.
+private const val OPERATIONAL_TIMING_WINDOW_MILLIS = 5L * 60L * 1000L
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/DepartureProjector.kt b/app/src/main/kotlin/in/izyum/bart/backend/DepartureProjector.kt
new file mode 100644
index 0000000..09150e1
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/backend/DepartureProjector.kt
@@ -0,0 +1,151 @@
+package `in`.izyum.bart.backend
+
+import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Line
+import `in`.izyum.bart.model.PredictionSource
+import `in`.izyum.bart.model.RealTimeDepartures
+import `in`.izyum.bart.model.Route
+import `in`.izyum.bart.model.Station
+import `in`.izyum.bart.model.TripLeg
+import `in`.izyum.bart.model.TripStop
+import `in`.izyum.bart.routing.TransferPolicy
+import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
+
+/** Projects selected journeys from the canonical passenger schedule. */
+class DepartureProjector(
+ private val origin: Station,
+ private val destination: Station?,
+ private val network: BartGtfsNetwork,
+) {
+ private val routing = CanonicalRoutingAdapter(network)
+ private val transferPolicy = TransferPolicy(network)
+
+ fun project(canonical: CanonicalTransitSnapshot): RealTimeDepartures {
+ val trips = canonical.passengerTrips.map { it.trip }
+ val feedTime = canonical.normalizedFeed.provenance.feedTimestampMillis
+ val inputs = routing.inputs(trips)
+ val byTrip = inputs.associateBy { it.trip }
+ val router = routing.router(inputs)
+ val departures = mutableListOf()
+
+ trips.forEach { trip ->
+ val originStop = trip.stopAt(origin) ?: return@forEach
+ if (originStop.departureTime <= 0L
+ || originStop.departureTime < feedTime - DEPARTURE_STALE_TOLERANCE_MILLIS
+ ) return@forEach
+
+ val selected = if (destination != null) {
+ val input = byTrip[trip] ?: return@forEach
+ val journey = routing.bestJourney(router, origin, destination, originStop.departureTime)
+ ?: return@forEach
+ if (journey.legs.firstOrNull()?.trip?.id != input.raptorTrip.id) {
+ return@forEach
+ }
+ val route = routing.routeForJourney(journey) ?: return@forEach
+ val legs = journey.legs.mapIndexed { index, leg ->
+ val selectedTrip = leg.trip.payload as? Schedule.Trip ?: return@forEach
+ tripLeg(route, index, leg.origin, leg.destination, selectedTrip)
+ }
+ if (legs.lastOrNull()?.destination != destination) return@forEach
+ route to legs
+ } else {
+ val route = Route.direct(
+ origin,
+ trip.trainDestination,
+ trip.line,
+ trip.direction,
+ trip.stops.map { it.station },
+ )
+ route to listOf(tripLeg(route, 0, origin, trip.trainDestination, trip))
+ }
+
+ val (route, legs) = selected
+ val line = legs.firstOrNull()?.line ?: trip.line
+ val minutes = maxOf(0L, (originStop.departureTime - feedTime) / 60_000L).toInt()
+ val departure = Departure.builder()
+ .setOrigin(origin)
+ .setTrainDestination(trip.trainDestination)
+ .setLine(line)
+ .setPlatform(originStop.platform)
+ .setCanceled(trip.canceled)
+ .setMinutes(minutes)
+ .setMinEstimate(originStop.departureTime - ESTIMATE_TOLERANCE_MILLIS)
+ .setMaxEstimate(originStop.departureTime + ESTIMATE_TOLERANCE_MILLIS)
+ .setTripLegs(legs)
+ .let { builder ->
+ legs.lastOrNull()?.arrivalTime?.takeIf { it > 0L }?.let { arrival ->
+ builder.setEstimatedTripTime((arrival - originStop.departureTime).toInt())
+ } ?: builder
+ }
+ .build()
+ departures += departure
+ }
+
+ return RealTimeDepartures(
+ origin,
+ destination,
+ feedTime,
+ departures,
+ transfersIncluded = destination != null,
+ )
+ }
+
+ private fun tripLeg(
+ route: Route,
+ legIndex: Int,
+ legOrigin: Station,
+ legDestination: Station,
+ trip: Schedule.Trip,
+ ): TripLeg {
+ val departure = trip.stopAt(legOrigin)
+ val arrival = trip.stopAt(legDestination)
+ val stops = trip.stops
+ .dropWhile { it.station != legOrigin }
+ .takeWhile { it.station != legDestination }
+ .plus(listOfNotNull(arrival))
+ .map { stop ->
+ TripStop(
+ stop.station,
+ stop.arrivalTime,
+ stop.departureTime,
+ stop.scheduledArrivalTime,
+ stop.scheduledDepartureTime,
+ stop.arrivalSource,
+ stop.departureSource,
+ )
+ }
+ return TripLeg(
+ trip.line,
+ legOrigin,
+ legDestination,
+ trip.trainDestination,
+ trip.key.tripId,
+ departure?.departureTime ?: 0L,
+ arrival?.arrivalTime ?: 0L,
+ stops,
+ minimumTransferSecondsAfter(route, legIndex, trip.line),
+ departure?.scheduledDepartureTime ?: 0L,
+ arrival?.scheduledArrivalTime ?: 0L,
+ departure?.departureSource ?: PredictionSource.UNKNOWN,
+ arrival?.arrivalSource ?: PredictionSource.UNKNOWN,
+ departure?.platform,
+ trip.key.serviceDate,
+ trip.canceled,
+ trip.direction,
+ )
+ }
+
+ private fun minimumTransferSecondsAfter(route: Route, index: Int, fromLine: Line): Int {
+ if (index < 0 || index + 1 >= route.lines.size) return 0
+ return transferPolicy.minimumTransferSeconds(
+ route.transferStations.getOrNull(index),
+ fromLine,
+ route.lines[index + 1],
+ )
+ }
+
+ private companion object {
+ const val ESTIMATE_TOLERANCE_MILLIS = 30_000L
+ const val DEPARTURE_STALE_TOLERANCE_MILLIS = 45_000L
+ }
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt b/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt
deleted file mode 100644
index 9655082..0000000
--- a/app/src/main/kotlin/in/izyum/bart/backend/EtdCorroboration.kt
+++ /dev/null
@@ -1,223 +0,0 @@
-package `in`.izyum.bart.backend
-
-import `in`.izyum.bart.model.Departure
-import `in`.izyum.bart.model.Line
-import `in`.izyum.bart.model.PredictionSource
-import `in`.izyum.bart.model.RealTimeDepartures
-import `in`.izyum.bart.model.Station
-import `in`.izyum.bart.model.TripLeg
-import `in`.izyum.bart.networktasks.EtdDeparture
-import `in`.izyum.bart.networktasks.EtdStationCache
-import `in`.izyum.bart.networktasks.EtdLookup
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-
-enum class EtdMatch {
- MATCHED,
- CANCELED,
- ABSENT,
- UNKNOWN,
-}
-
-data class EtdLegDecision(
- val match: EtdMatch,
- val departureTimeMillis: Long? = null,
-)
-
-data class EtdLegKey(
- val tripId: String,
- val origin: Station,
- val destination: Station?,
- val scheduledDepartureTime: Long,
-)
-
-/** Applies ETD only to suspicious missing-trip candidates. */
-object EtdCorroborator {
- const val SUSPICIOUS_WINDOW_MILLIS = 60L * 60L * 1000L
- const val MATCH_TOLERANCE_MILLIS = 8L * 60L * 1000L
-
- fun suspiciousLegs(
- departures: List,
- snapshot: TransitFeedSnapshot,
- ): List {
- val feedIds = snapshot.getTripUpdateIndex().tripUpdatesById.keys
- val feedTime = snapshot.getTripUpdatesTimestampMillis()
- return departures
- .flatMap { it.tripLegs }
- .filter { leg ->
- val tripId = leg.tripId
- tripId != null
- && tripId !in feedIds
- && leg.departureSource == PredictionSource.SCHEDULE
- && leg.origin != null
- && leg.scheduledDepartureTime in
- feedTime..(feedTime + SUSPICIOUS_WINDOW_MILLIS)
- }
- .distinctBy(::key)
- }
-
- fun decideDetailed(
- suspicious: List,
- boards: Map,
- occupiedRealtime: List = emptyList(),
- ): Map {
- val decisions = LinkedHashMap()
- suspicious
- .groupBy { MatchGroup(it.origin, it.line, it.trainDestination) }
- .forEach { (group, legs) ->
- val board = group.station?.let { boards[it]?.board }
- val candidates = board?.departuresFor(group.line, group.destination).orEmpty()
- val used = occupiedSlots(group, candidates, occupiedRealtime)
- legs.sortedBy { it.scheduledDepartureTime }.forEach { leg ->
- val matchIndex = candidates.indices
- .filter { it !in used }
- .minByOrNull {
- kotlin.math.abs(
- candidates[it].departureTimeMillis -
- leg.scheduledDepartureTime
- )
- }
- val match = matchIndex?.let { candidates[it] }
- val decision = if (match != null && kotlin.math.abs(
- match.departureTimeMillis - leg.scheduledDepartureTime
- ) <= MATCH_TOLERANCE_MILLIS
- ) {
- used += matchIndex
- EtdLegDecision(
- if (match.canceled) EtdMatch.CANCELED else EtdMatch.MATCHED,
- match.departureTimeMillis.takeUnless { match.canceled },
- )
- } else {
- if (boardCoversCandidate(board, leg.scheduledDepartureTime)) {
- EtdLegDecision(EtdMatch.ABSENT)
- } else {
- EtdLegDecision(EtdMatch.UNKNOWN)
- }
- }
- decisions[key(leg)] = decision
- }
- }
- return decisions
- }
-
- private fun occupiedSlots(
- group: MatchGroup,
- candidates: List,
- occupiedRealtime: List,
- ): MutableSet {
- val used = mutableSetOf()
- occupiedRealtime
- .filter { realtime ->
- realtime.origin == group.station
- && realtime.line == group.line
- && realtime.trainDestination == group.destination
- && realtime.departureSource == PredictionSource.REALTIME
- }
- .sortedBy { it.departureTime }
- .forEach { realtime ->
- val matchIndex = candidates.indices
- .filter { it !in used }
- .minByOrNull {
- kotlin.math.abs(
- candidates[it].departureTimeMillis - realtime.departureTime
- )
- }
- if (matchIndex != null && kotlin.math.abs(
- candidates[matchIndex].departureTimeMillis - realtime.departureTime
- ) <= MATCH_TOLERANCE_MILLIS
- ) {
- used += matchIndex
- }
- }
- return used
- }
-
- /**
- * A successful station response with no train in the requested direction
- * is meaningful once the response covers the candidate's time. An empty
- * board is treated as a valid no-service response for the normal
- * suspicious window; a failed request never reaches this function because
- * its board is null.
- */
- private fun boardCoversCandidate(
- board: `in`.izyum.bart.networktasks.EtdStationBoard?,
- candidateTimeMillis: Long,
- ): Boolean {
- if (board == null) return false
- val latestStationDeparture = board.departures.maxOfOrNull {
- it.departureTimeMillis
- }
- return latestStationDeparture != null && latestStationDeparture >=
- candidateTimeMillis - MATCH_TOLERANCE_MILLIS ||
- board.departures.isEmpty() && candidateTimeMillis <=
- board.receivedAtMillis + SUSPICIOUS_WINDOW_MILLIS
- }
-
- private data class MatchGroup(
- val station: Station?,
- val line: Line?,
- val destination: Station?,
- )
-
- private fun key(leg: TripLeg): EtdLegKey = EtdLegKey(
- requireNotNull(leg.tripId),
- requireNotNull(leg.origin),
- leg.destination,
- leg.scheduledDepartureTime,
- )
-
-}
-
-/** Adds the asynchronous ETD step after the ordinary projection identifies candidates. */
-class EtdAwareRouteDepartureProjection(
- private val projection: RouteDepartureProjection,
- private val cache: EtdStationCache,
-) {
- suspend fun project(snapshot: TransitFeedSnapshot): RealTimeDepartures {
- val result = projection.projectForEtd(snapshot)
- val suspicious = EtdCorroborator.suspiciousLegs(result.getDepartures(), snapshot)
- if (suspicious.isEmpty()) return projection.project(snapshot)
- val boards = withContext(Dispatchers.IO) {
- cache.getAll(suspicious.mapNotNull { it.origin }.toSet())
- }
- val realtime = result.getDepartures()
- .flatMap { it.tripLegs }
- .filter { it.departureSource == PredictionSource.REALTIME }
- val detailed = EtdCorroborator.decideDetailed(suspicious, boards, realtime)
- val excludedTripIds = detailed
- .filterValues {
- it.match == EtdMatch.ABSENT || it.match == EtdMatch.CANCELED
- }
- .keys
- .map { it.tripId }
- .toSet()
- val departureOverrides = detailed
- .mapNotNull { (key, decision) ->
- if (decision.match == EtdMatch.MATCHED
- && decision.departureTimeMillis != null
- ) {
- (key.tripId to key.origin) to decision.departureTimeMillis
- } else {
- null
- }
- }
- .toMap()
- // Reconcile against the ordinary projection so unrelated schedule
- // candidates remain subject to the realtime cutoff. Only trips that
- // ETD positively matched may bypass that cutoff.
- val forcedScheduleTripIds = departureOverrides.keys
- .map { it.first }
- .toSet()
- return projection.project(
- snapshot,
- excludedTripIds,
- departureOverrides,
- forcedScheduleTripIds,
- )
- }
-
- fun areEquivalent(
- previous: RealTimeDepartures?,
- current: RealTimeDepartures?,
- ): Boolean = projection.areEquivalent(previous, current)
-}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/FollowedItineraryAlarmProjection.kt b/app/src/main/kotlin/in/izyum/bart/backend/FollowedItineraryAlarmProjection.kt
new file mode 100644
index 0000000..68833fb
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/backend/FollowedItineraryAlarmProjection.kt
@@ -0,0 +1,28 @@
+package `in`.izyum.bart.backend
+
+import `in`.izyum.bart.model.Itinerary
+import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
+import java.util.function.Supplier
+
+/**
+ * Refreshes only the followed itinerary leg that controls the departure alarm.
+ * It deliberately does not validate connections or replan future legs.
+ */
+class FollowedItineraryAlarmProjection(
+ private val networkSupplier: Supplier,
+) {
+ constructor(network: BartGtfsNetwork) : this(Supplier { network })
+
+ fun project(snapshot: TransitFeedSnapshot, itinerary: Itinerary): Itinerary {
+ val firstLeg = itinerary.legs.firstOrNull() ?: return itinerary
+ val network = networkSupplier.get()
+ val canonical = snapshot.getCanonicalSnapshot(network)
+ val refreshed = ItineraryRefreshProjector(
+ itinerary.origin,
+ itinerary.destination,
+ network,
+ ).refreshLeg(canonical, firstLeg)
+ if (refreshed == firstLeg) return itinerary
+ return itinerary.replaceLegs(listOf(refreshed) + itinerary.legs.drop(1))
+ }
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/ItineraryRefreshProjector.kt b/app/src/main/kotlin/in/izyum/bart/backend/ItineraryRefreshProjector.kt
new file mode 100644
index 0000000..f6eb452
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/backend/ItineraryRefreshProjector.kt
@@ -0,0 +1,327 @@
+package `in`.izyum.bart.backend
+
+import `in`.izyum.bart.model.Line
+import `in`.izyum.bart.model.Itinerary
+import `in`.izyum.bart.model.PredictionSource
+import `in`.izyum.bart.model.Route
+import `in`.izyum.bart.model.Station
+import `in`.izyum.bart.model.TripLeg
+import `in`.izyum.bart.model.TripStop
+import `in`.izyum.bart.routing.TransferPolicy
+import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
+
+/** Refreshes a selected itinerary and replans its future when it fails. */
+class ItineraryRefreshProjector(
+ private val origin: Station,
+ private val destination: Station,
+ private val network: BartGtfsNetwork,
+) {
+ private val routing = CanonicalRoutingAdapter(network)
+ private val transferPolicy = TransferPolicy(network)
+
+ fun project(canonical: CanonicalTransitSnapshot, itinerary: Itinerary): Itinerary {
+ val refreshed = projectLegs(canonical, itinerary.origin, itinerary.destination, itinerary.legs)
+ return itinerary.replaceLegs(refreshed)
+ }
+
+ /** Refreshes one existing leg without validating or replanning its route. */
+ fun refreshLeg(canonical: CanonicalTransitSnapshot, existing: TripLeg): TripLeg {
+ val trips = canonical.correctedSchedule.trips
+ val byIdentity = trips.associateBy { routing.canonicalTripId(it) }
+ val byId = trips.groupBy { it.key.tripId }
+ val current = existing.canonicalIdentity?.let(byIdentity::get)
+ ?: byId[existing.tripId].orEmpty().singleOrNull()
+ ?: findMatchingTrip(existing, trips)
+ return if (current == null) existing else updateTripLeg(existing, current)
+ }
+
+ /** Compatibility entry point for board/projection regression tests. */
+ fun project(canonical: CanonicalTransitSnapshot, existingLegs: List): List =
+ projectLegs(canonical, origin, destination, existingLegs)
+
+ private fun projectLegs(
+ canonical: CanonicalTransitSnapshot,
+ origin: Station,
+ destination: Station,
+ existingLegs: List,
+ ): List {
+ val trips = canonical.correctedSchedule.trips
+ val byIdentity = trips.associateBy { routing.canonicalTripId(it) }
+ val byId = trips.groupBy { it.key.tripId }
+ val updated = existingLegs.map { existing ->
+ val current = existing.canonicalIdentity?.let(byIdentity::get)
+ ?: byId[existing.tripId].orEmpty().singleOrNull()
+ ?: findMatchingTrip(existing, trips)
+ if (current == null) existing else updateTripLeg(existing, current)
+ }.toMutableList()
+
+ val route = routeForExistingLegs(updated)
+ ?: routeForCanonicalItinerary(trips, updated)
+ if (route == null || itineraryIsFeasible(route, updated, trips)) {
+ return updated
+ }
+
+ // Keep the current itinerary until it is no longer usable. Once a
+ // leg or connection fails, discard the future suffix and let RAPTOR
+ // choose one complete continuation.
+ val preserved = traveledPrefix(
+ updated,
+ canonical.normalizedFeed.provenance.feedTimestampMillis,
+ )
+ val replanOrigin = preserved.lastOrNull()?.destination ?: origin
+ val replanTime = maxOf(
+ canonical.normalizedFeed.provenance.feedTimestampMillis,
+ preserved.lastOrNull()?.arrivalTime ?: 0L,
+ updated.firstOrNull()?.departureTime ?: 0L,
+ )
+ val inputs = routing.inputs(trips)
+ val journey = routing.bestJourney(
+ routing.router(inputs),
+ replanOrigin,
+ destination,
+ replanTime,
+ )
+ val replanned = journey?.let { selected ->
+ val replannedRoute = routing.routeForJourney(selected) ?: return@let emptyList()
+ selected.legs.mapIndexedNotNull { index, leg ->
+ val trip = leg.trip.payload as? Schedule.Trip ?: return@mapIndexedNotNull null
+ tripLeg(replannedRoute, index, leg.origin, leg.destination, trip)
+ }
+ }.orEmpty()
+ return preserved + replanned
+ }
+
+ private fun routeForCanonicalItinerary(
+ trips: List,
+ existingLegs: List,
+ ): Route? {
+ val firstLeg = existingLegs.firstOrNull() ?: return null
+ val departureTime = firstLeg.departureTime.takeIf { it > 0L }
+ ?: firstLeg.scheduledDepartureTime.takeIf { it > 0L }
+ ?: return null
+ val inputs = routing.inputs(trips)
+ val router = routing.router(inputs)
+ val journeys = router.journeys(origin, destination, departureTime)
+ val expectedId = firstLeg.canonicalIdentity ?: firstLeg.tripId
+ val selected = journeys.firstOrNull { it.legs.firstOrNull()?.trip?.id == expectedId }
+ ?: routing.bestJourney(router, origin, destination, departureTime)
+ return selected?.let(routing::routeForJourney)
+ }
+
+ private fun routeForExistingLegs(legs: List): Route? {
+ if (legs.isEmpty()) return null
+ val routeOrigin = legs.first().origin ?: return null
+ val finalDestination = legs.last().destination ?: return null
+ val lines = legs.map { it.line ?: return null }
+ val transferStations = legs.dropLast(1).map { it.destination ?: return null }
+ val sequences = linkedMapOf>()
+ legs.forEach { leg ->
+ val line = leg.line ?: return@forEach
+ sequences.putIfAbsent(
+ line,
+ (listOfNotNull(leg.origin)
+ + leg.stops.mapNotNull { it.station }
+ + listOfNotNull(leg.destination)).distinct(),
+ )
+ }
+ return if (lines.size == 1) {
+ Route.direct(routeOrigin, finalDestination, lines.single(), null, sequences[lines.single()].orEmpty())
+ } else {
+ Route.transfer(routeOrigin, finalDestination, lines, transferStations, null, sequences)
+ }
+ }
+
+ private fun itineraryIsFeasible(
+ route: Route,
+ legs: List,
+ trips: List,
+ ): Boolean {
+ legs.forEachIndexed { index, leg ->
+ if (isCanceled(leg, trips)) return false
+ }
+ for (index in 1 until route.lines.size) {
+ val previous = legs.getOrNull(index - 1) ?: return false
+ val next = legs.getOrNull(index) ?: return false
+ val expectedDestination = if (index < route.transferStations.size) {
+ route.transferStations[index]
+ } else {
+ destination
+ }
+ if (next.line != route.lines[index]
+ || next.origin != previous.destination
+ || next.destination != expectedDestination
+ || !connectionIsFeasible(previous, next)
+ ) return false
+ }
+ return true
+ }
+
+ private fun connectionIsFeasible(previous: TripLeg, next: TripLeg): Boolean {
+ if (previous.arrivalTime <= 0L || next.departureTime <= 0L) return true
+ val station = previous.destination ?: return false
+ return transferPolicy.canMakeTransfer(
+ previous.arrivalTime,
+ next.departureTime,
+ station,
+ previous.line,
+ next.line,
+ when {
+ previous.line == Line.YELLOW -> previous.stops.mapNotNull { it.station }
+ next.line == Line.YELLOW -> next.stops.mapNotNull { it.station }
+ else -> null
+ },
+ )
+ }
+
+ private fun traveledPrefix(legs: List, asOf: Long): List {
+ if (asOf <= 0L) return emptyList()
+ val prefix = mutableListOf()
+ for (leg in legs) {
+ if (leg.arrivalTime > 0L && leg.arrivalTime <= asOf) {
+ prefix += leg
+ continue
+ }
+ val passed = leg.stops.mapIndexedNotNull { index, stop ->
+ if (stop.arrivalTime > 0L && stop.arrivalTime <= asOf) index to stop else null
+ }.lastOrNull() ?: break
+ if (passed.second.station == leg.origin) break
+ prefix += partialLeg(leg, passed.first)
+ break
+ }
+ return prefix
+ }
+
+ private fun partialLeg(leg: TripLeg, lastPassedIndex: Int): TripLeg {
+ val passedStop = leg.stops[lastPassedIndex]
+ return TripLeg(
+ leg.line,
+ leg.origin,
+ passedStop.station,
+ leg.trainDestination,
+ leg.tripId,
+ leg.departureTime,
+ passedStop.arrivalTime,
+ leg.stops.take(lastPassedIndex + 1),
+ 0,
+ leg.scheduledDepartureTime,
+ passedStop.scheduledArrivalTime,
+ leg.departureSource,
+ passedStop.arrivalSource,
+ leg.platform,
+ leg.serviceDate,
+ leg.canceled,
+ leg.direction,
+ )
+ }
+
+ private fun tripLeg(
+ route: Route,
+ index: Int,
+ legOrigin: Station,
+ legDestination: Station,
+ trip: Schedule.Trip,
+ ): TripLeg {
+ val departure = trip.stopAt(legOrigin)
+ val arrival = trip.stopAt(legDestination)
+ return TripLeg(
+ trip.line,
+ legOrigin,
+ legDestination,
+ trip.trainDestination,
+ trip.key.tripId,
+ departure?.departureTime ?: 0L,
+ arrival?.arrivalTime ?: 0L,
+ trip.stops.filterBetween(legOrigin, legDestination).map { stop ->
+ TripStop(
+ stop.station,
+ stop.arrivalTime,
+ stop.departureTime,
+ stop.scheduledArrivalTime,
+ stop.scheduledDepartureTime,
+ stop.arrivalSource,
+ stop.departureSource,
+ )
+ },
+ minimumTransferSecondsAfter(route, index, legDestination, trip.line),
+ departure?.scheduledDepartureTime ?: 0L,
+ arrival?.scheduledArrivalTime ?: 0L,
+ departure?.departureSource ?: PredictionSource.UNKNOWN,
+ arrival?.arrivalSource ?: PredictionSource.UNKNOWN,
+ departure?.platform,
+ trip.key.serviceDate,
+ trip.canceled,
+ trip.direction,
+ )
+ }
+
+ private fun updateTripLeg(existing: TripLeg, trip: Schedule.Trip): TripLeg {
+ val originStop = trip.stopAt(existing.origin)
+ val destinationStop = trip.stopAt(existing.destination)
+ val stops = existing.stops.map { old ->
+ val current = trip.stopAt(old.station) ?: return@map old
+ TripStop(
+ old.station,
+ current.arrivalTime,
+ current.departureTime,
+ current.scheduledArrivalTime.takeIf { it > 0L } ?: old.scheduledArrivalTime,
+ current.scheduledDepartureTime.takeIf { it > 0L } ?: old.scheduledDepartureTime,
+ current.arrivalSource,
+ current.departureSource,
+ )
+ }
+ return TripLeg(
+ trip.line,
+ existing.origin,
+ existing.destination,
+ trip.trainDestination,
+ existing.tripId,
+ originStop?.departureTime ?: existing.departureTime,
+ destinationStop?.arrivalTime ?: existing.arrivalTime,
+ stops,
+ existing.minimumTransferSecondsAfter,
+ existing.scheduledDepartureTime,
+ existing.scheduledArrivalTime,
+ originStop?.departureSource ?: existing.departureSource,
+ destinationStop?.arrivalSource ?: existing.arrivalSource,
+ originStop?.platform ?: existing.platform,
+ trip.key.serviceDate,
+ trip.canceled,
+ trip.direction,
+ )
+ }
+
+ private fun findMatchingTrip(leg: TripLeg, trips: List): Schedule.Trip? =
+ trips.firstOrNull {
+ !it.canceled && it.line == leg.line && it.trainDestination == leg.trainDestination
+ && it.canServe(leg.origin, leg.destination)
+ }
+
+ private fun isCanceled(leg: TripLeg, trips: List): Boolean =
+ trips.any {
+ it.canceled && it.key.tripId == leg.tripId
+ && (leg.serviceDate == null || it.key.serviceDate == leg.serviceDate)
+ }
+
+ private fun minimumTransferSecondsAfter(
+ route: Route,
+ index: Int,
+ transferStation: Station,
+ fromLine: Line,
+ ): Int {
+ if (index + 1 >= route.lines.size) return 0
+ return transferPolicy.minimumTransferSeconds(
+ transferStation,
+ fromLine,
+ route.lines[index + 1],
+ )
+ }
+}
+
+private fun List.filterBetween(
+ origin: Station,
+ destination: Station,
+): List {
+ val start = indexOfFirst { it.station == origin }
+ val end = indexOfFirst { it.station == destination }
+ return if (start < 0 || end <= start) emptyList() else subList(start, end + 1)
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt b/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt
index 4967b95..fe2574e 100644
--- a/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt
+++ b/app/src/main/kotlin/in/izyum/bart/backend/RouteDepartureProjection.kt
@@ -1,176 +1,35 @@
package `in`.izyum.bart.backend
import `in`.izyum.bart.model.RealTimeDepartures
-import `in`.izyum.bart.model.Route
-import `in`.izyum.bart.model.Station
import `in`.izyum.bart.model.StationPair
-import `in`.izyum.bart.networktasks.GtfsRealtimeContentHandler
-import `in`.izyum.bart.networktasks.GtfsRealtimeFeedIndex
import `in`.izyum.bart.performance.PerformanceTrace
import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
-import com.google.transit.realtime.GtfsRealtime
import java.util.function.Supplier
/** Builds departures for one route from the already-downloaded feed. */
-class RouteDepartureProjection private constructor(
+class RouteDepartureProjection(
private val query: StationPair,
- private val ignoreDirection: Boolean,
private val networkSupplier: Supplier,
) {
- constructor(query: StationPair, networkSupplier: Supplier) :
- this(query, false, networkSupplier)
-
constructor(query: StationPair, bartGtfsNetwork: BartGtfsNetwork) :
- this(query, false, Supplier { bartGtfsNetwork })
-
- constructor(
- query: StationPair,
- ignoreDirection: Boolean,
- bartGtfsNetwork: BartGtfsNetwork
- ) : this(query, ignoreDirection, Supplier { bartGtfsNetwork })
+ this(query, Supplier { bartGtfsNetwork })
fun project(snapshot: TransitFeedSnapshot): RealTimeDepartures =
- project(snapshot, emptySet(), emptyMap(), true, emptySet())
+ projectInternal(snapshot)
- /** Projects while excluding trips corroborated as unavailable by ETD. */
- fun project(
+ private fun projectInternal(
snapshot: TransitFeedSnapshot,
- excludedTripIds: Set,
- ): RealTimeDepartures = project(
- snapshot, excludedTripIds, emptyMap(), true, emptySet()
- )
-
- /**
- * Builds the uncut candidate set for ETD reconciliation. Schedule-only
- * candidates covered by realtime are admitted temporarily so ETD can
- * corroborate a real departure that the GTFS-RT feed omitted.
- */
- internal fun projectForEtd(
- snapshot: TransitFeedSnapshot,
- excludedTripIds: Set = emptySet(),
- departureOverrides: Map, Long> = emptyMap(),
- ): RealTimeDepartures = project(
- snapshot,
- excludedTripIds,
- departureOverrides,
- false,
- emptySet(),
- )
-
- /** Projects with operational departure times for ETD-correlated trips. */
- fun project(
- snapshot: TransitFeedSnapshot,
- excludedTripIds: Set,
- departureOverrides: Map, Long>,
- forcedScheduleTripIds: Set = emptySet(),
- ): RealTimeDepartures = project(
- snapshot,
- excludedTripIds,
- departureOverrides,
- true,
- forcedScheduleTripIds,
- )
-
- private fun project(
- snapshot: TransitFeedSnapshot,
- excludedTripIds: Set,
- departureOverrides: Map, Long>,
- suppressScheduleCoveredByRealtime: Boolean,
- forcedScheduleTripIds: Set,
): RealTimeDepartures {
val name = "BART route ${query.origin.abbreviation}-${query.destination?.abbreviation.orEmpty()}"
return PerformanceTrace.section(name) {
val network = networkSupplier.get()
- val feedIndex = snapshot.getTripUpdateIndex()
- val feedTime = snapshot.getTripUpdatesTimestampMillis()
- // A later fallback may add transfer routes whose lines are not present
- // in the first route set. Build one complete time-scoped graph so the
- // fallback cannot accidentally lose its static connecting trains.
- val schedule = snapshot.getCorrectedSchedule(network)
- .applyDepartureOverrides(departureOverrides)
- val routes = schedule.routesFor(query.origin, query.destination)
- projectWithRouting(
- routes,
- network,
- feedIndex,
- feedTime,
- schedule,
- excludedTripIds,
- suppressScheduleCoveredByRealtime,
- forcedScheduleTripIds,
- )
- }
- }
-
- private fun projectWithRouting(
- routes: List,
- network: BartGtfsNetwork,
- feedIndex: GtfsRealtimeFeedIndex,
- feedTime: Long,
- schedule: Schedule,
- excludedTripIds: Set,
- suppressScheduleCoveredByRealtime: Boolean,
- forcedScheduleTripIds: Set,
- ): RealTimeDepartures {
- var result = projectRoutes(
- routes,
- network,
- feedIndex,
- feedTime,
- schedule,
- excludedTripIds,
- suppressScheduleCoveredByRealtime,
- forcedScheduleTripIds,
- )
-
- if (result.getDepartures().isEmpty() && query.destination != null) {
- val lateNightRoutes = if (schedule.isLateNightSfoMillbraeService()) {
- schedule.lateNightSfoMillbraeRoutes(
- query.origin,
- query.destination,
- )
- } else {
- emptyList()
- }
- val transferRoutes = schedule.preferredTransferRoutes(
+ val canonical = snapshot.getCanonicalSnapshot(network)
+ DepartureProjector(
query.origin,
- query.destination
- ) + lateNightRoutes
- val transferResult = projectRoutes(
- routes + transferRoutes,
+ query.destination,
network,
- feedIndex,
- feedTime,
- schedule,
- excludedTripIds,
- suppressScheduleCoveredByRealtime,
- forcedScheduleTripIds,
- )
- if (transferResult.getDepartures().isNotEmpty()) {
- result = transferResult.includeTransferRoutes()
- }
+ ).project(canonical).sortDepartures()
}
- result = result.sortDepartures()
- if (result.getDepartures().isEmpty() && query.destination != null) {
- val doubleTransferRoutes = schedule.doubleTransferRoutes(
- query.origin,
- query.destination
- )
- val doubleTransferResult = projectRoutes(
- routes + doubleTransferRoutes,
- network,
- feedIndex,
- feedTime,
- schedule,
- excludedTripIds,
- suppressScheduleCoveredByRealtime,
- forcedScheduleTripIds,
- )
- if (doubleTransferResult.getDepartures().isNotEmpty()) {
- result = doubleTransferResult.includeDoubleTransferRoutes()
- }
- }
- return result.finalizeDeparturesList()
}
fun areEquivalent(
@@ -180,28 +39,4 @@ class RouteDepartureProjection private constructor(
&& previous.areTransfersIncluded() == current.areTransfersIncluded()
&& previous.getDepartures() == current.getDepartures()
- private fun projectRoutes(
- routes: List,
- network: BartGtfsNetwork,
- feedIndex: GtfsRealtimeFeedIndex,
- feedTime: Long,
- schedule: Schedule,
- excludedTripIds: Set,
- suppressScheduleCoveredByRealtime: Boolean,
- forcedScheduleTripIds: Set,
- ): RealTimeDepartures = GtfsRealtimeContentHandler(
- query.origin,
- query.destination,
- routes,
- ignoreDirection,
- network
- ).getRealTimeDepartures(
- feedIndex,
- feedTime,
- schedule,
- excludedTripIds,
- suppressScheduleCoveredByRealtime,
- forcedScheduleTripIds,
- )
-
}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt b/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt
index 53510b8..774758d 100644
--- a/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt
+++ b/app/src/main/kotlin/in/izyum/bart/backend/Schedule.kt
@@ -2,17 +2,17 @@ package `in`.izyum.bart.backend
import `in`.izyum.bart.model.Line
import `in`.izyum.bart.model.PredictionSource
-import `in`.izyum.bart.model.Route
import `in`.izyum.bart.model.Station
-import `in`.izyum.bart.networktasks.GtfsRealtimeFeedIndex
-import `in`.izyum.bart.routing.TransferPolicy
import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
import `in`.izyum.bart.transit.gtfs.GtfsScheduledTrip
import `in`.izyum.bart.transit.gtfs.GtfsStopTime
+import `in`.izyum.bart.transit.normalization.NormalizedRealtimeFeed
+import `in`.izyum.bart.transit.normalization.RequiredTransferPair
+import `in`.izyum.bart.transit.normalization.StaticTripIdentity
+import `in`.izyum.bart.transit.BartDataPolicy
import com.google.transit.realtime.GtfsRealtime
import java.time.Instant
import java.time.LocalDate
-import java.time.ZoneId
import java.util.Collections
import java.util.LinkedHashMap
@@ -29,8 +29,7 @@ class Schedule private constructor(
private val nominalTravelTimes: Map, Long>,
private val stationResolver: (String?) -> Station?,
) {
- private val transferPolicy = TransferPolicy(network)
- data class TripKey(val serviceDate: LocalDate?, val tripId: String)
+ data class TripKey(val serviceDate: LocalDate, val tripId: String)
data class Stop(
val station: Station,
@@ -53,7 +52,6 @@ class Schedule private constructor(
val trainDestination: Station,
val stops: List,
val canceled: Boolean = false,
- val synthetic: Boolean = false,
) {
fun stopAt(station: Station?): Stop? = stops.firstOrNull { it.station == station }
@@ -70,19 +68,28 @@ class Schedule private constructor(
if (from == null || to == null) null else nominalTravelTimes[from to to]
/** Returns a corrected immutable graph using the supplied realtime feed. */
- fun applyRealtime(feedIndex: GtfsRealtimeFeedIndex): Schedule {
- val updates = feedIndex.tripUpdatesById
- val correctedBaseTrips = trips.filterNot { it.synthetic }.map { trip ->
- val entity = updates[trip.key.tripId]
- if (entity?.hasTripUpdate() == true) {
- correctTrip(trip, entity.tripUpdate)
+ fun applyRealtime(feed: NormalizedRealtimeFeed): Schedule {
+ val updates = feed.projectedTripUpdatesByIdentity
+ val updatesById = feed.projectedTripUpdatesById
+ // Only a static trip with the same ID is eligible to change this graph.
+ // Operational telemetry remains in the normalized feed for its own
+ // projection and cannot fabricate a static passenger identity here.
+ val correctedBaseTrips = trips.map { trip ->
+ val identity = StaticTripIdentity(trip.key.serviceDate, trip.key.tripId)
+ val observation = updates[identity] ?: updatesById[trip.key.tripId]
+ ?.takeIf { fallback ->
+ !fallback.isOperationalTelemetry
+ && fallback.startDate == null
+ && trips.count { it.key.tripId == trip.key.tripId } == 1
+ }
+ if (observation != null) {
+ correctTrip(trip, observation.rawEntity.tripUpdate)
} else {
trip
}
}
- val correctedTrips = applyTerminalRealtime(correctedBaseTrips, feedIndex)
return create(
- correctedTrips,
+ correctedBaseTrips,
nominalTravelTimes,
stationResolver,
network,
@@ -91,42 +98,94 @@ class Schedule private constructor(
}
/**
- * Applies operational departure times without changing the static schedule.
- * ETD has no trip IDs, so callers must first make the station/time
- * association. Once associated, shift predicted times at and after the
- * station so transfer validation uses the observed departure and the
- * scheduled running time remains intact.
+ * Applies canonical DMU observations at every resolved stop to the
+ * electric passenger trip they serve at Pittsburg. The DMU identifier
+ * remains provenance; the electric static identity remains the passenger
+ * identity.
*/
- fun applyDepartureOverrides(
- overrides: Map, Long>,
+ fun applyDmuTransferPairs(
+ pairs: Collection,
): Schedule {
- if (overrides.isEmpty()) return this
+ if (pairs.isEmpty()) return this
+ val timingByIdentity = pairs.mapNotNull { pair ->
+ val identity = pair.passengerIdentity
+ ?: pair.electricAssociation?.staticIdentity
+ ?: return@mapNotNull null
+ val observed = pair.operationalObservation.stops.mapNotNull { stop ->
+ val station = stationResolver(stop.stopId) ?: return@mapNotNull null
+ if (stop.arrivalTimeMillis == null && stop.departureTimeMillis == null) {
+ return@mapNotNull null
+ }
+ station to stop
+ }.toMap()
+ identity to observed
+ }.toMap()
val adjustedTrips = trips.map { trip ->
- val tripId = trip.key.tripId
- val override = trip.stops.mapIndexedNotNull { index, stop ->
- overrides[tripId to stop.station]?.let { index to it }
- }.firstOrNull()
- if (override == null) {
- trip
- } else {
- val (startIndex, departureTime) = override
- val scheduledDeparture = trip.stops[startIndex].scheduledDepartureTime
- val delay = departureTime - scheduledDeparture
- trip.copy(
- stops = immutableList(trip.stops.mapIndexed { index, stop ->
- if (index < startIndex) {
- stop
+ val observed = timingByIdentity[StaticTripIdentity(trip.key.serviceDate, trip.key.tripId)]
+ ?: return@map trip
+ val lastObservedIndex = trip.stops.indexOfLast { it.station in observed }
+ trip.copy(stops = immutableList(trip.stops.mapIndexed { index, stop ->
+ val observedStop = observed[stop.station]
+ val observedArrival = observedStop?.arrivalTimeMillis
+ ?: observedStop?.departureTimeMillis
+ val observedDeparture = observedStop?.departureTimeMillis
+ ?: observedStop?.arrivalTimeMillis
+ when {
+ observedArrival != null || observedDeparture != null -> stop.copy(
+ arrivalTime = observedArrival ?: stop.arrivalTime,
+ departureTime = observedDeparture ?: stop.departureTime,
+ arrivalSource = PredictionSource.REALTIME,
+ departureSource = PredictionSource.REALTIME,
+ )
+ index > lastObservedIndex -> {
+ val previous = trip.stops.take(index).lastOrNull { candidate ->
+ candidate.station in observed
+ }
+ val previousStop = previous?.let { observed[it.station] }
+ val previousTime = previousStop?.departureTimeMillis
+ ?: previousStop?.arrivalTimeMillis
+ if (previous != null && previousTime != null) {
+ val travel = nominalTravelTimeMillis(previous.station, stop.station)
+ if (travel != null && travel > 0L) {
+ val arrival = previousTime + travel
+ val dwell = (stop.scheduledDepartureTime - stop.scheduledArrivalTime)
+ .coerceAtLeast(0L)
+ // The electric update may already have supplied
+ // a realtime PITT time. DMU propagation fills
+ // gaps; it must never downgrade an existing
+ // realtime field to an estimate.
+ stop.copy(
+ arrivalTime = if (stop.arrivalSource == PredictionSource.REALTIME) {
+ stop.arrivalTime
+ } else {
+ arrival
+ },
+ departureTime = if (stop.departureSource == PredictionSource.REALTIME) {
+ stop.departureTime
+ } else {
+ arrival + dwell
+ },
+ arrivalSource = if (stop.arrivalSource == PredictionSource.REALTIME) {
+ PredictionSource.REALTIME
+ } else {
+ PredictionSource.ESTIMATE
+ },
+ departureSource = if (stop.departureSource == PredictionSource.REALTIME) {
+ PredictionSource.REALTIME
+ } else {
+ PredictionSource.ESTIMATE
+ },
+ )
+ } else {
+ stop
+ }
} else {
- stop.copy(
- arrivalTime = shifted(stop.arrivalTime, delay),
- departureTime = shifted(stop.departureTime, delay),
- arrivalSource = PredictionSource.ESTIMATE,
- departureSource = PredictionSource.ESTIMATE,
- )
+ stop
}
- })
- )
- }
+ }
+ else -> stop
+ }
+ }))
}
return create(
adjustedTrips,
@@ -137,131 +196,7 @@ class Schedule private constructor(
)
}
- /** Routes are selected from this corrected schedule, not from static data alone. */
- fun routesFor(origin: Station?, destination: Station?): List {
- if (origin == null || origin == destination) return emptyList()
- if (destination == null) {
- return catalogStationOnlyRoutes(origin)
- .filter(::hasUsableService)
- }
- val direct = catalogDirectRoutes(origin, destination)
- .filter(::hasUsableService)
- val transferAlternatives = preferredTransferRoutes(origin, destination)
- val lateNightSfoMillbrae = if (isLateNightSfoMillbraeService()
- && destination == Station.MLBR
- ) {
- lateNightSfoMillbraeRoutes(origin, destination)
- } else {
- emptyList()
- }
- val normalRoutes = uniqueRoutes(direct + transferAlternatives)
- .sortedWith(routePreference)
- return immutableList(
- lateNightSfoMillbrae + normalRoutes.filterNot { normal ->
- lateNightSfoMillbrae.any { special ->
- special.lines == normal.lines
- && special.transferStations == normal.transferStations
- }
- }
- )
- }
-
- fun preferredTransferRoutes(origin: Station?, destination: Station?): List {
- if (origin == null || destination == null || origin == destination) {
- return emptyList()
- }
- val directTransfers = catalogTransferRoutes(origin, destination, false)
- .sortedWith(routePreference)
- val doubleTransfers = catalogTransferRoutes(origin, destination, true)
- .sortedWith(routePreference)
- val selected = if (doubleTransfers.isNotEmpty()
- && (directTransfers.isEmpty()
- || routeScore(doubleTransfers.first()) < routeScore(directTransfers.first()))
- ) doubleTransfers else directTransfers
- return immutableList(selected.filter(::hasUsableService))
- }
-
- fun doubleTransferRoutes(origin: Station?, destination: Station?): List {
- if (origin == null || destination == null || origin == destination) {
- return emptyList()
- }
- return immutableList(
- catalogTransferRoutes(origin, destination, true)
- .sortedWith(routePreference)
- .filter(::hasUsableService)
- )
- }
-
- fun transferRoutes(origin: Station?, destination: Station?): List {
- if (origin == null || destination == null || origin == destination) {
- return emptyList()
- }
- return immutableList(
- catalogTransferRoutes(origin, destination, false)
- .sortedWith(routePreference)
- .filter(::hasUsableService)
- )
- }
-
- fun lateNightSfoMillbraeRoutes(origin: Station?, destination: Station?): List {
- if (origin == null || destination != Station.MLBR) return emptyList()
- if (origin == Station.SFIA) {
- return listOf(Route.direct(
- origin, destination, Line.YELLOW_LATE_NIGHT, "s",
- listOf(Station.SFIA, Station.MLBR)
- ))
- }
- val pattern = network.routePatternsForLine(Line.YELLOW)
- .filter { pattern ->
- val originIndex = pattern.stations.indexOf(origin)
- val sfoIndex = pattern.stations.indexOf(Station.SFIA)
- originIndex >= 0 && sfoIndex > originIndex
- }
- .maxByOrNull { it.stations.size } ?: return emptyList()
- val route = Route.transfer(
- origin, destination,
- listOf(Line.YELLOW, Line.YELLOW_LATE_NIGHT),
- listOf(Station.SFIA), pattern.direction,
- mapOf(
- Line.YELLOW to pattern.stations,
- Line.YELLOW_LATE_NIGHT to listOf(Station.SFIA, Station.MLBR),
- )
- )
- return if (hasUsableService(route)) listOf(route) else emptyList()
- }
-
- /** Whether the feed represents BART's late-night SFO/Millbrae service. */
- fun isLateNightSfoMillbraeService(): Boolean {
- if (feedTime <= 0L) return false
- val hour = Instant.ofEpochMilli(feedTime).atZone(PACIFIC_ZONE).hour
- return hour >= LATE_NIGHT_START_HOUR || hour < LATE_NIGHT_END_HOUR
- }
-
- private val routePreference = compareBy { routeScore(it) }
-
- private fun hasUsableService(route: Route): Boolean {
- if (route.destination == null) {
- val candidates = trips.filter { it.line == route.directLine }
- return candidates.isEmpty() || candidates.any {
- !it.canceled && it.canServe(route.origin, null)
- }
- }
- for (index in route.lines.indices) {
- val segmentOrigin = if (index == 0) route.origin else route.transferStations[index - 1]
- val segmentDestination = if (index == route.lines.lastIndex) {
- route.destination
- } else {
- route.transferStations[index]
- }
- val candidates = trips.filter { it.line == route.lines[index] }
- if (candidates.isNotEmpty() && !candidates.any {
- !it.canceled && it.canServe(segmentOrigin, segmentDestination)
- }) {
- return false
- }
- }
- return true
- }
+ internal fun stationForStopId(stopId: String?): Station? = stationResolver(stopId)
private fun correctTrip(trip: Trip, update: GtfsRealtime.TripUpdate): Trip {
val realtimeByStation = LinkedHashMap()
@@ -319,226 +254,6 @@ class Schedule private constructor(
return trip.copy(stops = immutableList(correctedStops), canceled = canceled || trip.canceled)
}
- /**
- * BART's Antioch/DMU feed has independent trip IDs. Use it to fill
- * terminal stop times on the corresponding static Yellow passenger trip;
- * it must never create a separate technical passenger departure by itself.
- */
- private fun applyTerminalRealtime(
- trips: List,
- feedIndex: GtfsRealtimeFeedIndex,
- ): List {
- val result = trips.toMutableList()
- val usedTrips = mutableSetOf()
- val terminalEntities = feedIndex.tripUpdateEntities
- .filter(::isTerminalRealtime)
- // A direct Antioch departure is the strongest evidence for the
- // Antioch board. Let it claim the next normal PITT train before a
- // PCTR-only DMU update can consume that same static trip.
- .sortedByDescending { entity ->
- entity.tripUpdate.stopTimeUpdateList.any { stopUpdate ->
- stationResolver(stopUpdate.stopId) == Station.ANTC
- && (terminalEventTime(stopUpdate.departure) != null
- || terminalEventTime(stopUpdate.arrival) != null)
- }
- }
- terminalEntities.forEach { entity ->
- val update = entity.tripUpdate
- val points = update.stopTimeUpdateList.mapNotNull { stopUpdate ->
- val station = stationResolver(stopUpdate.stopId)
- ?.takeIf { it == Station.PCTR || it == Station.ANTC }
- ?: return@mapNotNull null
- station to stopUpdate
- }.toMap()
- if (points.isEmpty()) return@forEach
- val terminalStation = points.keys.firstOrNull { it == Station.PCTR }
- ?: Station.ANTC
- val terminalUpdate = points[terminalStation] ?: return@forEach
- val terminalTime = terminalEventTime(terminalUpdate.departure)
- ?: terminalEventTime(terminalUpdate.arrival) ?: return@forEach
- val platform = platformForStopId(update.stopTimeUpdateList.firstOrNull()?.stopId)
- val direction = when (platform) {
- "1" -> "n"
- "2" -> "s"
- else -> null
- }
- // DMU telemetry has its own 600-series trip IDs and only covers
- // the terminal segment. Prefer joining it to an electric trip
- // whose passenger update supplies a realtime PITT time; the
- // static terminal time can belong to a different train.
- val realtimeElectricMatch = result.indices
- .filter { index ->
- val trip = result[index]
- if (index in usedTrips || !isTerminalCandidate(trip, direction, platform)) {
- return@filter false
- }
- val pitt = trip.stopAt(Station.PITT) ?: return@filter false
- pitt.arrivalSource == PredictionSource.REALTIME ||
- pitt.departureSource == PredictionSource.REALTIME
- }
- .mapNotNull { index ->
- val projected = projectRealtimeTerminalTime(
- result[index], terminalStation, direction
- ) ?: return@mapNotNull null
- index to kotlin.math.abs(projected - terminalTime)
- }
- .filter { (_, delta) -> delta <= TERMINAL_MATCH_MAX_MILLIS }
- .minByOrNull { (_, delta) -> delta }
- ?.first
- val match = realtimeElectricMatch ?: result.indices
- .filter { index ->
- val trip = result[index]
- if (index in usedTrips || !isTerminalCandidate(trip, direction, platform)) {
- return@filter false
- }
- kotlin.math.abs(
- (trip.stopAt(terminalStation)?.arrivalTime ?: 0L) - terminalTime
- ) <= TERMINAL_MATCH_MAX_MILLIS
- }
- .minByOrNull { index ->
- kotlin.math.abs(
- (result[index].stopAt(terminalStation)?.arrivalTime ?: 0L)
- - terminalTime
- )
- }
- ?: return@forEach
- usedTrips += match
- result[match] = mergeTerminalRealtime(result[match], update, points)
- }
- return immutableList(result)
- }
-
- private fun isTerminalCandidate(
- trip: Trip,
- direction: String?,
- platform: String?,
- ): Boolean {
- if (trip.line != Line.YELLOW || trip.canceled
- || direction != null && trip.direction != direction
- || trip.stopAt(Station.PCTR) == null
- || trip.stopAt(Station.ANTC) == null
- ) return false
- val tripPlatform = trip.stopAt(Station.PITT)?.platform
- return platform == null || tripPlatform == null || platform == tripPlatform
- }
-
- private fun isTerminalRealtime(entity: GtfsRealtime.FeedEntity): Boolean {
- if (!entity.hasTripUpdate()) return false
- val trip = entity.tripUpdate.trip
- val routeId = trip.routeId.takeIf { trip.hasRouteId() && it.isNotEmpty() }
- ?: network.routeIdForTrip(trip.tripId)
- if (network.lineForRouteId(routeId) != null) return false
- return entity.tripUpdate.stopTimeUpdateList.any { stopUpdate ->
- stationResolver(stopUpdate.stopId) in setOf(Station.PCTR, Station.ANTC)
- }
- }
-
- private fun mergeTerminalRealtime(
- trip: Trip,
- update: GtfsRealtime.TripUpdate,
- points: Map,
- ): Trip {
- val directStations = points.keys
- var stops = trip.stops.map { stop ->
- val terminalUpdate = points[stop.station] ?: return@map stop
- // DMU trip IDs are not tied to static GTFS. Delay-only events
- // therefore cannot be interpreted against the matched electric
- // trip's schedule; use only absolute event times here.
- val arrival = terminalEventTime(terminalUpdate.arrival)
- val departure = terminalEventTime(terminalUpdate.departure)
- when {
- arrival != null || departure != null -> stop.copy(
- arrivalTime = arrival ?: departure!!,
- departureTime = departure ?: arrival!!,
- arrivalSource = if (arrival != null) PredictionSource.REALTIME
- else PredictionSource.ESTIMATE,
- departureSource = if (departure != null) PredictionSource.REALTIME
- else PredictionSource.ESTIMATE,
- skipped = isSkipped(terminalUpdate),
- )
- isSkipped(terminalUpdate) -> stop.copy(
- arrivalTime = 0L,
- departureTime = 0L,
- arrivalSource = PredictionSource.UNKNOWN,
- departureSource = PredictionSource.UNKNOWN,
- skipped = true,
- )
- else -> stop
- }
- }
- val pctr = stops.first { it.station == Station.PCTR }
- val antc = stops.first { it.station == Station.ANTC }
- if (Station.PCTR in directStations && Station.ANTC !in directStations) {
- val estimatedAntc = if (trip.direction == "n") {
- estimateAfter(pctr, antc)
- } else {
- estimateBefore(pctr, antc)
- }
- if (estimatedAntc != null) {
- stops = stops.map { if (it.station == Station.ANTC) estimatedAntc else it }
- }
- } else if (Station.ANTC in directStations && Station.PCTR !in directStations) {
- val estimatedPctr = if (trip.direction == "n") {
- estimateBefore(antc, pctr)
- } else {
- estimateAfter(antc, pctr)
- }
- if (estimatedPctr != null) {
- stops = stops.map { if (it.station == Station.PCTR) estimatedPctr else it }
- }
- }
- return trip.copy(stops = immutableList(stops))
- }
-
- private fun projectRealtimeTerminalTime(
- trip: Trip,
- terminalStation: Station,
- direction: String?,
- ): Long? {
- val pittIndex = trip.stops.indexOfFirst { it.station == Station.PITT }
- val terminalIndex = trip.stops.indexOfFirst { it.station == terminalStation }
- if (pittIndex < 0 || terminalIndex < 0 || pittIndex == terminalIndex) return null
- val pitt = trip.stops[pittIndex]
- var time = pitt.arrivalTime.takeIf { it > 0L }
- ?: pitt.departureTime.takeIf { it > 0L }
- ?: return null
- if (direction == "n" && terminalIndex > pittIndex) {
- for (index in pittIndex until terminalIndex) {
- time += nominalTravelTimeMillis(
- trip.stops[index].station,
- trip.stops[index + 1].station,
- ) ?: return null
- }
- return time
- }
- if (direction == "s" && terminalIndex < pittIndex) {
- for (index in pittIndex downTo terminalIndex + 1) {
- time -= nominalTravelTimeMillis(
- trip.stops[index - 1].station,
- trip.stops[index].station,
- ) ?: return null
- }
- return time
- }
- return null
- }
-
- private fun estimateBefore(next: Stop, previous: Stop): Stop? {
- val travel = nominalTravelTimeMillis(previous.station, next.station)
- ?: return null
- val nextTime = next.arrivalTime.takeIf { it > 0L } ?: return null
- val arrival = nextTime - travel
- if (arrival <= 0L) return null
- val dwell = (previous.scheduledDepartureTime - previous.scheduledArrivalTime)
- .coerceAtLeast(0L)
- return previous.copy(
- arrivalTime = arrival,
- departureTime = arrival + dwell,
- arrivalSource = PredictionSource.ESTIMATE,
- departureSource = PredictionSource.ESTIMATE,
- )
- }
-
private fun estimateAfter(previous: Stop, current: Stop): Stop? {
val travel = nominalTravelTimeMillis(previous.station, current.station) ?: return null
if (previous.departureTime <= 0L || travel <= 0L) return null
@@ -581,279 +296,15 @@ class Schedule private constructor(
return null
}
- /** Absolute DMU times only; delay-only and malformed epoch values are not usable. */
- private fun terminalEventTime(
- event: GtfsRealtime.TripUpdate.StopTimeEvent?,
- ): Long? = eventTime(event, 0L)?.takeIf { it >= MIN_REALTIME_EVENT_TIME_MILLIS }
-
private fun isSkipped(update: GtfsRealtime.TripUpdate.StopTimeUpdate?): Boolean =
update?.hasScheduleRelationship() == true &&
update.scheduleRelationship ==
GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED
- private fun catalogStationOnlyRoutes(origin: Station): List =
- network.linesForStation(origin).mapNotNull { line ->
- network.routePatternsForLine(line)
- .filter { origin in it.stations }
- .maxByOrNull { it.stations.size }
- ?.let { Route.stationOnly(origin, line, it.stations) }
- }
-
- private fun catalogDirectRoutes(origin: Station, destination: Station): List {
- val routes = mutableListOf()
- for (line in network.linesForStation(origin)) {
- val bestPatterns = LinkedHashMap()
- network.routePatternsForLine(line).forEach { pattern ->
- val direction = pattern.direction
- val originIndex = pattern.stations.indexOf(origin)
- val destinationIndex = pattern.stations.indexOf(destination)
- if (originIndex >= 0 && destinationIndex > originIndex
- && (bestPatterns[direction] == null
- || pattern.stations.size > bestPatterns[direction]!!.stations.size)
- ) {
- bestPatterns[direction] = pattern
- }
- }
- bestPatterns.values.forEach { pattern ->
- val direction = pattern.direction
- routes += Route.direct(
- origin, destination, line, direction, pattern.stations
- )
- }
- }
- return routes
- }
-
- private fun catalogTransferRoutes(
- origin: Station,
- destination: Station,
- onlyDoubleTransfers: Boolean,
- ): List {
- val routes = mutableListOf()
- // The terminal vehicle is an operational feed detail, not a
- // passenger-facing line or transfer.
- val lines = Line.values().filter {
- it != Line.YELLOW_DMU && network.routePatternsForLine(it).isNotEmpty()
- }
- for (first in lines) {
- if (!contains(first, origin)) continue
- for (last in lines) {
- if (first == last || !contains(last, destination)) continue
- commonStations(first, last).forEach { transfer ->
- if (!network.canTransfer(transfer, first, last)
- || onlyDoubleTransfers
- || segment(first, origin, transfer) == null
- || segment(last, transfer, destination) == null
- ) continue
- makeTransferRoute(
- origin, destination, listOf(first, last), listOf(transfer)
- )?.let(routes::add)
- }
- for (middle in lines) {
- if (middle == first || middle == last) continue
- commonStations(first, middle).forEach { firstTransfer ->
- if (!network.canTransfer(firstTransfer, first, middle)
- || segment(first, origin, firstTransfer) == null
- ) return@forEach
- commonStations(middle, last).forEach { secondTransfer ->
- if (!network.canTransfer(secondTransfer, middle, last)
- || firstTransfer == secondTransfer
- || segment(middle, firstTransfer, secondTransfer) == null
- || segment(last, secondTransfer, destination) == null
- ) return@forEach
- makeTransferRoute(
- origin, destination,
- listOf(first, middle, last),
- listOf(firstTransfer, secondTransfer)
- )?.let(routes::add)
- }
- }
- }
- }
- }
- return uniqueRoutes(routes)
- }
-
- private fun makeTransferRoute(
- origin: Station,
- destination: Station,
- lines: List,
- transfers: List,
- ): Route? {
- val sequences = LinkedHashMap>()
- var direction: String? = null
- lines.forEachIndexed { index, line ->
- val segmentOrigin = if (index == 0) origin else transfers[index - 1]
- val segmentDestination = if (index == lines.lastIndex) destination else transfers[index]
- val pattern = segment(line, segmentOrigin, segmentDestination) ?: return null
- sequences[line] = pattern.stations
- if (index == 0) {
- direction = pattern.direction
- }
- }
- val route = Route.transfer(origin, destination, lines, transfers, direction, sequences)
- return if (isValidTransferPath(route)) route else null
- }
-
- private fun contains(line: Line, station: Station): Boolean =
- network.routePatternsForLine(line).any { station in it.stations }
-
- private fun commonStations(first: Line, second: Line): List {
- val result = mutableListOf()
- network.routePatternsForLine(first).forEach { pattern ->
- pattern.stations.forEach { station ->
- if (station !in result && contains(second, station)) result += station
- }
- }
- return result
- }
-
- private fun segment(
- line: Line,
- origin: Station,
- destination: Station,
- ): BartGtfsNetwork.StationPattern? = network.routePatternsForLine(line)
- .filter { pattern ->
- val originIndex = pattern.stations.indexOf(origin)
- val destinationIndex = pattern.stations.indexOf(destination)
- originIndex >= 0 && destinationIndex > originIndex
- }
- .maxByOrNull { it.stations.size }
-
- private fun isValidTransferPath(route: Route): Boolean {
- route.lines.forEachIndexed { index, line ->
- val origin = if (index == 0) route.origin else route.transferStations[index - 1]
- val destination = if (index == route.lines.lastIndex) {
- route.destination
- } else {
- route.transferStations[index]
- }
- val sequence = route.getStationSequence(line)
- val originIndex = sequence.indexOf(origin)
- val destinationIndex = sequence.indexOf(destination)
- if (originIndex < 0 || destinationIndex <= originIndex) return false
- if (index < route.lines.lastIndex && route.destination in sequence) return false
- if (index > 0 && route.origin in sequence) return false
- }
- return true
- }
-
- private fun routeScore(route: Route): Int {
- var score = route.transferStations.size * 100
- val lines = route.lines
- if ((route.origin == Station.DUBL || route.origin == Station.CAST)
- && (route.destination == Station.PITT
- || route.destination == Station.PCTR
- || route.destination == Station.ANTC)
- && lines.size == 3
- && lines[0] == Line.BLUE
- && lines[1] == Line.ORANGE
- && lines[2] == Line.YELLOW
- && route.transferStations.size == 2
- ) score -= 200
- if (isYellowSouthToBlueViaOrange(route)) {
- // This is the preferred Antioch/East Bay pattern even though it
- // adds a transfer: it avoids the split-platform West Oakland
- // connection and uses the Orange line as the BART timetable does.
- score -= 250
- }
- route.transferStations.indices.forEach { index ->
- val station = route.transferStations[index]
- if (transferPolicy.isAvoidedForRouteRanking(route, index)) {
- score += 80
- } else if (transferPolicy.isBusyStation(station)) {
- score += 3
- }
- val preferred = preferredTransferStation(route, lines[index], lines[index + 1], index)
- if (station != preferred) {
- score += if (preferred == Station.LAKE
- && station == Station.BAYF
- ) 4 else 10
- }
- }
- return score
- }
-
- private fun isYellowSouthToBlueViaOrange(route: Route): Boolean {
- if (route.lines != listOf(Line.YELLOW, Line.ORANGE, Line.BLUE)
- || route.transferStations.firstOrNull() != Station.MCAR
- ) return false
- return transferPolicy.yellowTravelIsSouthbound(route) == true
- }
-
- private fun preferredTransferStation(
- route: Route,
- first: Line,
- second: Line,
- transferIndex: Int,
- ): Station? {
- if (isEastBayToSanFranciscoTrunk(first, second)) return Station.BALB
- if (samePair(first, second, Line.BLUE, Line.ORANGE)
- || samePair(first, second, Line.GREEN, Line.BLUE)
- ) {
- val segmentOrigin = if (transferIndex == 0) route.origin
- else route.transferStations[transferIndex - 1]
- val segmentDestination = if (transferIndex + 1 < route.transferStations.size) {
- route.transferStations[transferIndex + 1]
- } else {
- route.destination
- }
- if (segmentOrigin != null && segmentDestination != null
- && segment(first, segmentOrigin, Station.LAKE) != null
- && segment(second, Station.LAKE, segmentDestination) != null
- && network.canTransfer(Station.LAKE, first, second)
- ) return Station.LAKE
- return Station.BAYF
- }
- if (samePair(first, second, Line.ORANGE, Line.YELLOW)) {
- return if (transferPolicy.yellowTravelIsSouthbound(route) == true) {
- Station.MCAR
- } else {
- Station._19TH
- }
- }
- return null
- }
-
- private fun isEastBayToSanFranciscoTrunk(first: Line, second: Line): Boolean {
- val eastBayLine = first == Line.BLUE || first == Line.GREEN
- val sanFranciscoTrunk = second == Line.RED
- || second == Line.YELLOW
- || second == Line.YELLOW_LATE_NIGHT
- val reversedEastBayLine = second == Line.BLUE || second == Line.GREEN
- val reversedSanFranciscoTrunk = first == Line.RED
- || first == Line.YELLOW
- || first == Line.YELLOW_LATE_NIGHT
- return (eastBayLine && sanFranciscoTrunk)
- || (reversedEastBayLine && reversedSanFranciscoTrunk)
- }
-
- private fun samePair(
- left: Line,
- right: Line,
- expectedLeft: Line,
- expectedRight: Line,
- ): Boolean = (left == expectedLeft && right == expectedRight)
- || (left == expectedRight && right == expectedLeft)
-
- private fun uniqueRoutes(routes: List): List {
- val unique = mutableListOf()
- routes.forEach { route ->
- if (unique.none { it.lines == route.lines
- && it.transferStations == route.transferStations }) unique += route
- }
- return unique
- }
-
companion object {
- private val PACIFIC_ZONE = ZoneId.of("America/Los_Angeles")
+ private val PACIFIC_ZONE = BartDataPolicy.PACIFIC_ZONE
private const val LOOK_AHEAD_MILLIS = 2L * 60L * 60L * 1000L
private const val LOOK_BEHIND_MILLIS = 30L * 60L * 1000L
- private const val TERMINAL_MATCH_MAX_MILLIS = 20L * 60L * 1000L
- private const val MIN_REALTIME_EVENT_TIME_MILLIS = 1_000_000_000_000L
- private const val LATE_NIGHT_START_HOUR = 21
- private const val LATE_NIGHT_END_HOUR = 5
-
@JvmStatic
fun fromStatic(
network: BartGtfsNetwork,
@@ -880,9 +331,7 @@ class Schedule private constructor(
}
}
.forEach { scheduledTrip ->
- if (staticTrips.none { it.key.tripId == scheduledTrip.trip.tripId }) {
- toTrip(network, serviceDate, scheduledTrip)?.let(staticTrips::add)
- }
+ toTrip(network, serviceDate, scheduledTrip)?.let(staticTrips::add)
}
}
val nominal = nominalTravelTimes(staticTrips)
@@ -967,11 +416,10 @@ class Schedule private constructor(
network: BartGtfsNetwork,
feedTime: Long,
): Schedule {
- val immutableTrips = immutableList(trips)
return Schedule(
network,
feedTime,
- immutableTrips,
+ immutableList(trips),
immutableMap(nominalTravelTimes),
stationResolver,
)
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt b/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt
index 0250d62..2b93e41 100644
--- a/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt
+++ b/app/src/main/kotlin/in/izyum/bart/backend/TransitFeedSnapshot.kt
@@ -1,7 +1,8 @@
package `in`.izyum.bart.backend
import `in`.izyum.bart.model.Line
-import `in`.izyum.bart.networktasks.GtfsRealtimeFeedIndex
+import `in`.izyum.bart.transit.normalization.NormalizedRealtimeFeed
+import `in`.izyum.bart.transit.normalization.RealtimeFeedNormalizer
import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
import com.google.transit.realtime.GtfsRealtime
import java.util.IdentityHashMap
@@ -13,12 +14,12 @@ class TransitFeedSnapshot(
val receivedAtMillis: Long
) {
@Volatile
- private var tripUpdateIndex: GtfsRealtimeFeedIndex? = null
+ private var normalizedTripUpdates: NormalizedRealtimeFeed? = null
@Volatile
- private var alertIndex: GtfsRealtimeFeedIndex? = null
+ private var normalizedAlerts: NormalizedRealtimeFeed? = null
- private val correctedSchedules = IdentityHashMap()
+ private val canonicalSnapshots = IdentityHashMap()
init {
requireNotNull(tripUpdates) { "tripUpdates" }
@@ -28,37 +29,41 @@ class TransitFeedSnapshot(
fun getTripUpdatesTimestampMillis(): Long =
feedTimestampMillis(tripUpdates, receivedAtMillis)
- /** Builds the trip-update index once and shares it across all projections. */
- fun getTripUpdateIndex(): GtfsRealtimeFeedIndex {
- tripUpdateIndex?.let { return it }
+ /** Builds the lossless trip-update normalization once for all projections. */
+ fun getNormalizedTripUpdates(): NormalizedRealtimeFeed {
+ normalizedTripUpdates?.let { return it }
synchronized(this) {
- tripUpdateIndex?.let { return it }
- return GtfsRealtimeFeedIndex.from(tripUpdates).also {
- tripUpdateIndex = it
- }
+ normalizedTripUpdates?.let { return it }
+ return RealtimeFeedNormalizer.normalize(tripUpdates, receivedAtMillis, "trip_updates")
+ .also {
+ normalizedTripUpdates = it
+ }
}
}
- /** Builds the alert index once and shares it across all projections. */
- fun getAlertIndex(): GtfsRealtimeFeedIndex {
- alertIndex?.let { return it }
+ /** Builds the lossless alert-feed normalization once for all projections. */
+ fun getNormalizedAlerts(): NormalizedRealtimeFeed {
+ normalizedAlerts?.let { return it }
synchronized(this) {
- alertIndex?.let { return it }
- return GtfsRealtimeFeedIndex.from(alerts).also {
- alertIndex = it
+ normalizedAlerts?.let { return it }
+ return RealtimeFeedNormalizer.normalize(alerts, receivedAtMillis, "alerts").also {
+ normalizedAlerts = it
}
}
}
- /** Builds the corrected schedule once for each static network consumer. */
- fun getCorrectedSchedule(network: BartGtfsNetwork): Schedule {
- synchronized(correctedSchedules) {
- return correctedSchedules[network] ?: Schedule.fromStatic(
+ /** Builds one canonical snapshot for each static network consumer. */
+ fun getCanonicalSnapshot(network: BartGtfsNetwork): CanonicalTransitSnapshot {
+ synchronized(canonicalSnapshots) {
+ return canonicalSnapshots[network] ?: CanonicalTransitSnapshot.create(
+ Schedule.fromStatic(
network,
getTripUpdatesTimestampMillis(),
Line.values().toSet(),
- ).applyRealtime(getTripUpdateIndex()).also {
- correctedSchedules[network] = it
+ ),
+ getNormalizedTripUpdates(),
+ ).also {
+ canonicalSnapshots[network] = it
}
}
}
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt b/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt
index 508d210..103a989 100644
--- a/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt
+++ b/app/src/main/kotlin/in/izyum/bart/backend/TransitRepository.kt
@@ -29,10 +29,19 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.runInterruptible
+data class RealtimeFeedState(
+ val lastSuccessReceivedAtMillis: Long? = null,
+ val feedTimestampMillis: Long? = null,
+ val lastError: Exception? = null,
+ val isUsable: Boolean = false,
+)
+
data class TransitFeedState(
val snapshot: TransitFeedSnapshot? = null,
val error: Exception? = null,
val isOffline: Boolean = false,
+ val tripUpdates: RealtimeFeedState = RealtimeFeedState(),
+ val alerts: RealtimeFeedState = RealtimeFeedState(),
)
/** Owns feed polling and exposes one replaying flow for all transit consumers. */
@@ -44,7 +53,18 @@ class TransitRepository(
private val offlineSnapshotProvider: (() -> TransitFeedSnapshot)? = null,
private val backgroundPollingIntervalMillis: StateFlow =
MutableStateFlow(refreshIntervalMillis),
+ private val tripUpdatesStaleAfterMillis: Long = 2 * 60_000L,
+ private val alertsStaleAfterMillis: Long = 10 * 60_000L,
+ private val nowMillisProvider: () -> Long = System::currentTimeMillis,
) : AutoCloseable {
+ init {
+ require(tripUpdatesStaleAfterMillis > 0) {
+ "tripUpdatesStaleAfterMillis must be positive"
+ }
+ require(alertsStaleAfterMillis > 0) {
+ "alertsStaleAfterMillis must be positive"
+ }
+ }
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val lock = Any()
private val appInForeground = MutableStateFlow(false)
@@ -55,6 +75,10 @@ class TransitRepository(
)
private var latestSnapshot: TransitFeedSnapshot? = null
+ private var latestTripUpdates: CachedRealtimeFeed? = null
+ private var latestAlerts: CachedRealtimeFeed? = null
+ private var lastTripUpdatesError: Exception? = null
+ private var lastAlertsError: Exception? = null
private var refreshInProgress = false
private var lastRefreshStartedAtMillis: Long? = null
private var closed = false
@@ -128,6 +152,13 @@ class TransitRepository(
feedState
}
}
+ // buildStateLocked reuses the previous snapshot when a refresh
+ // contains identical feed data. Deduplicate that stable snapshot
+ // before invoking the potentially expensive projection. Keep
+ // null-snapshot states distinct so errors and recovery still flow.
+ .distinctUntilChanged { previous, current ->
+ previous.snapshot != null && previous.snapshot === current.snapshot
+ }
.mapLatest { feedState ->
val snapshot = feedState.snapshot
if (snapshot == null) {
@@ -149,8 +180,23 @@ class TransitRepository(
}
.flowOn(Dispatchers.Default)
- /** Synchronously fetches once. Intended for tests and explicit refresh actions. */
- fun refreshNow() {
+ /** Refreshes once without blocking the caller's thread. */
+ suspend fun refresh() = kotlinx.coroutines.withContext(Dispatchers.IO) {
+ refreshNowBlockingForTests()
+ }
+
+ /** Refreshes immediately when stale, always off the caller's thread. */
+ suspend fun refreshIfStale() = kotlinx.coroutines.withContext(Dispatchers.IO) {
+ refreshIfStaleBlocking()
+ }
+
+ /** Refreshes only trip updates without blocking the caller's thread. */
+ suspend fun refreshTripUpdates() = kotlinx.coroutines.withContext(Dispatchers.IO) {
+ refreshTripUpdatesNow()
+ }
+
+ /** Synchronous refresh helper reserved for JVM tests and background callers. */
+ fun refreshNowBlockingForTests() {
if (!beginRefresh(force = true)) {
return
}
@@ -168,7 +214,6 @@ class TransitRepository(
return
}
- val previousSnapshot = synchronized(lock) { latestSnapshot }
val result = try {
Result.success(feedClient.fetchTripUpdates())
} catch (exception: Exception) {
@@ -179,34 +224,26 @@ class TransitRepository(
synchronized(lock) {
refreshInProgress = false
if (!closed) {
+ val now = nowMillisProvider()
result.fold(
onSuccess = { tripUpdates ->
- val alerts = previousSnapshot?.alerts
- ?: TransitFeedSnapshot.empty(System.currentTimeMillis()).alerts
- val refreshedSnapshot = TransitFeedSnapshot(
+ lastTripUpdatesError = null
+ latestTripUpdates = CachedRealtimeFeed(
tripUpdates,
- alerts,
- System.currentTimeMillis(),
+ now,
+ feedTimestampMillis(tripUpdates, now),
+ null,
)
- if (latestSnapshot == null ||
- !refreshedSnapshot.hasSameFeedData(latestSnapshot)
- ) {
- latestSnapshot = refreshedSnapshot
- stateToPublish = TransitFeedState(snapshot = refreshedSnapshot)
- }
},
onFailure = { exception ->
- stateToPublish = TransitFeedState(
- snapshot = latestSnapshot,
- error = exception as? Exception
- ?: RuntimeException(exception),
- isOffline = true,
- )
+ val error = exception as? Exception ?: RuntimeException(exception)
+ lastTripUpdatesError = error
+ latestTripUpdates = latestTripUpdates?.copy(lastError = error)
},
)
+ stateToPublish = buildStateLocked(now)
}
}
-
stateToPublish?.let {
_state.value = it
feedUpdates.tryEmit(it)
@@ -214,7 +251,7 @@ class TransitRepository(
}
/** Fetches immediately only when the feed has not been fetched recently. */
- fun refreshIfStale() {
+ private fun refreshIfStaleBlocking() {
if (!beginRefresh(force = false)) {
return
}
@@ -251,7 +288,7 @@ class TransitRepository(
if (closed || refreshInProgress) {
return false
}
- val nowMillis = System.currentTimeMillis()
+ val nowMillis = nowMillisProvider()
if (!force && lastRefreshStartedAtMillis?.let {
nowMillis - it < refreshIntervalMillis
} == true
@@ -277,36 +314,38 @@ class TransitRepository(
}
private fun publishFetchResult(fetchResult: TransitFeedFetchResult) {
-
- val refreshErrors = mutableListOf()
var stateToPublish: TransitFeedState? = null
synchronized(lock) {
refreshInProgress = false
if (!closed) {
- fetchResult.tripUpdatesError?.let { addRefreshError(refreshErrors, it) }
- fetchResult.alertsError?.let { addRefreshError(refreshErrors, it) }
-
- val mergedSnapshot = if (refreshErrors.isNotEmpty()) {
- // The Android application supplies a static-only snapshot here so
- // stale realtime corrections are not presented as current data.
- offlineSnapshotProvider?.invoke() ?: mergeSnapshot(fetchResult)
- } else {
- mergeSnapshot(fetchResult)
- }
- if (mergedSnapshot != null &&
- (latestSnapshot == null ||
- !mergedSnapshot.hasSameFeedData(latestSnapshot!!))
- ) {
- latestSnapshot = mergedSnapshot
- stateToPublish = TransitFeedState(snapshot = mergedSnapshot)
+ val now = nowMillisProvider()
+ if (fetchResult.tripUpdates != null) {
+ lastTripUpdatesError = null
+ latestTripUpdates = CachedRealtimeFeed(
+ fetchResult.tripUpdates,
+ now,
+ feedTimestampMillis(fetchResult.tripUpdates, now),
+ null,
+ )
+ } else if (fetchResult.tripUpdatesError != null) {
+ lastTripUpdatesError = fetchResult.tripUpdatesError
+ latestTripUpdates = latestTripUpdates?.copy(
+ lastError = fetchResult.tripUpdatesError,
+ )
}
- if (refreshErrors.isNotEmpty()) {
- stateToPublish = TransitFeedState(
- snapshot = latestSnapshot,
- error = refreshErrors.first(),
- isOffline = true,
+ if (fetchResult.alerts != null) {
+ lastAlertsError = null
+ latestAlerts = CachedRealtimeFeed(
+ fetchResult.alerts,
+ now,
+ feedTimestampMillis(fetchResult.alerts, now),
+ null,
)
+ } else if (fetchResult.alertsError != null) {
+ lastAlertsError = fetchResult.alertsError
+ latestAlerts = latestAlerts?.copy(lastError = fetchResult.alertsError)
}
+ stateToPublish = buildStateLocked(now, fetchResult.getCompleteSnapshot())
}
}
@@ -318,29 +357,68 @@ class TransitRepository(
fun getLatestSnapshot(): TransitFeedSnapshot? = synchronized(lock) { latestSnapshot }
- private fun mergeSnapshot(result: TransitFeedFetchResult): TransitFeedSnapshot? {
- result.getCompleteSnapshot()?.let { return it }
-
- var tripUpdates: GtfsRealtime.FeedMessage? = result.tripUpdates
- var alerts: GtfsRealtime.FeedMessage? = result.alerts
- latestSnapshot?.let { snapshot ->
- if (tripUpdates == null) {
- tripUpdates = snapshot.tripUpdates
- }
- if (alerts == null) {
- alerts = snapshot.alerts
- }
+ private fun buildStateLocked(
+ nowMillis: Long,
+ preferredSnapshot: TransitFeedSnapshot? = null,
+ ): TransitFeedState {
+ val trip = latestTripUpdates?.status(nowMillis, tripUpdatesStaleAfterMillis)
+ ?: RealtimeFeedState(lastError = lastTripUpdatesError)
+ val alerts = latestAlerts?.status(nowMillis, alertsStaleAfterMillis)
+ ?: RealtimeFeedState(lastError = lastAlertsError)
+ val usableTrip = latestTripUpdates?.takeIf {
+ it.isUsable(nowMillis, tripUpdatesStaleAfterMillis)
+ }?.message ?: TransitFeedSnapshot.empty(nowMillis).tripUpdates
+ val usableAlerts = latestAlerts?.takeIf {
+ it.isUsable(nowMillis, alertsStaleAfterMillis)
+ }?.message ?: TransitFeedSnapshot.empty(nowMillis).alerts
+ val hasUsableRealtime = trip.isUsable || alerts.isUsable
+ val errors = listOfNotNull(trip.lastError, alerts.lastError)
+ val mergedSnapshot = preferredSnapshot ?: if (hasUsableRealtime) {
+ TransitFeedSnapshot(usableTrip, usableAlerts, nowMillis)
+ } else {
+ // No retained realtime remains usable. The provider supplies the
+ // static-only projection used by the Android application.
+ offlineSnapshotProvider?.invoke() ?: TransitFeedSnapshot.empty(nowMillis)
}
- if (tripUpdates == null || alerts == null) {
- return null
+ if (latestSnapshot == null || !mergedSnapshot.hasSameFeedData(latestSnapshot)) {
+ latestSnapshot = mergedSnapshot
}
- return TransitFeedSnapshot(tripUpdates, alerts, System.currentTimeMillis())
+ return TransitFeedState(
+ snapshot = latestSnapshot,
+ error = errors.firstOrNull(),
+ // Departure screens depend on trip updates. Fresh alert data must
+ // not make stale or missing departure predictions appear online.
+ isOffline = errors.isNotEmpty() || !trip.isUsable,
+ tripUpdates = trip,
+ alerts = alerts,
+ )
}
- private fun addRefreshError(errors: MutableList, error: Exception) {
- if (!errors.contains(error)) {
- errors.add(error)
- }
+ private fun feedTimestampMillis(
+ feed: GtfsRealtime.FeedMessage,
+ fallbackMillis: Long,
+ ): Long = if (feed.hasHeader() && feed.header.hasTimestamp() && feed.header.timestamp > 0) {
+ feed.header.timestamp * 1000L
+ } else {
+ fallbackMillis
+ }
+
+ private data class CachedRealtimeFeed(
+ val message: GtfsRealtime.FeedMessage,
+ val receivedAtMillis: Long,
+ val feedTimestampMillis: Long,
+ val lastError: Exception?,
+ ) {
+ fun isUsable(nowMillis: Long, staleAfterMillis: Long): Boolean =
+ nowMillis - receivedAtMillis < staleAfterMillis
+
+ fun status(nowMillis: Long, staleAfterMillis: Long): RealtimeFeedState =
+ RealtimeFeedState(
+ lastSuccessReceivedAtMillis = receivedAtMillis,
+ feedTimestampMillis = feedTimestampMillis,
+ lastError = lastError,
+ isUsable = isUsable(nowMillis, staleAfterMillis),
+ )
}
override fun close() {
diff --git a/app/src/main/kotlin/in/izyum/bart/backend/TripProgressProjection.kt b/app/src/main/kotlin/in/izyum/bart/backend/TripProgressProjection.kt
index d82c777..3449221 100644
--- a/app/src/main/kotlin/in/izyum/bart/backend/TripProgressProjection.kt
+++ b/app/src/main/kotlin/in/izyum/bart/backend/TripProgressProjection.kt
@@ -1,8 +1,8 @@
package `in`.izyum.bart.backend
import `in`.izyum.bart.model.TripLeg
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.Station
-import `in`.izyum.bart.networktasks.GtfsRealtimeContentHandler
import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
import java.util.function.Supplier
@@ -16,6 +16,7 @@ class TripProgressProjection(
private val origin = origin
private val destination = destination
private val existingLegs = existingLegs.toList()
+ private var currentItinerary = Itinerary(origin, destination, this.existingLegs)
constructor(
origin: Station,
@@ -25,22 +26,19 @@ class TripProgressProjection(
) : this(origin, destination, existingLegs ?: emptyList(), Supplier { bartGtfsNetwork })
fun project(snapshot: TransitFeedSnapshot): List {
+ return projectItinerary(snapshot).legs
+ }
+
+ fun projectItinerary(snapshot: TransitFeedSnapshot): Itinerary {
val network = networkSupplier.get()
- val schedule = snapshot.getCorrectedSchedule(network)
- val routes = schedule.routesFor(origin, destination)
- val handler = GtfsRealtimeContentHandler(
+ val canonical = snapshot.getCanonicalSnapshot(network)
+ val refreshed = ItineraryRefreshProjector(
origin,
destination,
- routes,
- true,
network
- )
- return handler.updateTripLegs(
- snapshot.getTripUpdateIndex(),
- existingLegs,
- snapshot.getTripUpdatesTimestampMillis(),
- schedule,
- )
+ ).project(canonical, currentItinerary)
+ currentItinerary = refreshed
+ return refreshed
}
}
diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt
index 09ae711..aad84eb 100644
--- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt
+++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRecord.kt
@@ -1,29 +1,23 @@
package `in`.izyum.bart.data
-import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.Line
import `in`.izyum.bart.model.PredictionSource
import `in`.izyum.bart.model.Station
import `in`.izyum.bart.model.TripLeg
import `in`.izyum.bart.model.TripStop
+import java.time.LocalDate
/** Versioned JSON schema for the durable followed-trip state. */
-class FollowedTripRecord constructor() {
+class FollowedTripRecord {
@JvmField var version: Int = CURRENT_VERSION
@JvmField var origin: String? = null
@JvmField var trainDestination: String? = null
@JvmField var passengerDestination: String? = null
@JvmField var line: String? = null
- @JvmField var trainDestinationColorHex: String? = null
- @JvmField var trainDestinationColorText: String? = null
@JvmField var platform: String? = null
- @JvmField var direction: String? = null
- @JvmField var bikeAllowed = false
@JvmField var trainLength: String? = null
- @JvmField var requiresTransfer = false
- @JvmField var transferScheduled = false
@JvmField var canceled = false
- @JvmField var listedInETDs = true
@JvmField var minutes = 0
@JvmField var minEstimate = 0L
@JvmField var maxEstimate = 0L
@@ -31,61 +25,35 @@ class FollowedTripRecord constructor() {
@JvmField var estimatedTripTime = 0
@JvmField var tripLegs: MutableList = mutableListOf()
- fun toDeparture(): Departure {
+ fun toItinerary(): Itinerary {
require(version == CURRENT_VERSION) {
"Unsupported followed trip format version: $version"
}
- val legs = tripLegs.map { it.toTripLeg() }
- return Departure.builder()
- .setOrigin(station(origin))
- .setTrainDestination(station(trainDestination))
- .setPassengerDestination(station(passengerDestination) ?: station(trainDestination))
- .setLine(line?.let(Line::valueOf))
- .setTrainDestinationColorHex(trainDestinationColorHex)
- .setTrainDestinationColorText(trainDestinationColorText)
- .setPlatform(platform)
- .setDirection(direction)
- .setBikeAllowed(bikeAllowed)
- .setTrainLength(trainLength)
- .setRequiresTransfer(requiresTransfer)
- .setTransferScheduled(transferScheduled)
- .setCanceled(canceled)
- .setListedInETDs(listedInETDs)
- .setMinutes(minutes)
- .setMinEstimate(minEstimate)
- .setMaxEstimate(maxEstimate)
- .setArrivalTimeOverride(arrivalTimeOverride)
- .setEstimatedTripTime(estimatedTripTime)
- .setTripLegs(legs)
- .build()
+ val itineraryOrigin = station(origin)
+ ?: throw IllegalArgumentException("Followed trip has no origin")
+ val itineraryDestination = station(passengerDestination ?: trainDestination)
+ ?: throw IllegalArgumentException("Followed trip has no destination")
+ return Itinerary(itineraryOrigin, itineraryDestination, tripLegs.map { it.toTripLeg() })
}
companion object {
- const val CURRENT_VERSION = 1
+ const val CURRENT_VERSION = 2
@JvmStatic
- fun fromDeparture(departure: Departure): FollowedTripRecord =
+ fun fromItinerary(itinerary: Itinerary): FollowedTripRecord =
FollowedTripRecord().apply {
- origin = abbreviation(departure.origin)
- trainDestination = abbreviation(departure.trainDestination)
- passengerDestination = abbreviation(departure.passengerDestination)
- line = departure.line?.name
- trainDestinationColorHex = departure.destinationColorHex
- trainDestinationColorText = departure.destinationColorText
- platform = departure.platform
- direction = departure.direction
- bikeAllowed = departure.bikeAllowed
- trainLength = departure.trainLength
- requiresTransfer = departure.requiresTransfer
- transferScheduled = departure.transferScheduled
- canceled = departure.canceled
- listedInETDs = departure.listedInETDs
- minutes = departure.minutes
- minEstimate = departure.minEstimate
- maxEstimate = departure.maxEstimate
- arrivalTimeOverride = departure.arrivalTimeOverride
- estimatedTripTime = departure.estimatedTripTime
- tripLegs = departure.tripLegs.map(TripLegRecord::fromTripLeg).toMutableList()
+ origin = itinerary.origin.abbreviation
+ trainDestination = itinerary.trainDestination?.abbreviation
+ passengerDestination = itinerary.destination.abbreviation
+ line = itinerary.line?.name
+ platform = itinerary.platform
+ canceled = itinerary.canceled
+ minEstimate = itinerary.getInitialDepartureTime()
+ maxEstimate = itinerary.getInitialDepartureTime()
+ estimatedTripTime = (
+ itinerary.getEstimatedArrivalTime() - itinerary.getInitialDepartureTime()
+ ).coerceAtLeast(0L).toInt()
+ tripLegs = itinerary.legs.map(TripLegRecord::fromTripLeg).toMutableList()
}
private fun abbreviation(station: Station?): String? = station?.abbreviation
@@ -94,7 +62,7 @@ class FollowedTripRecord constructor() {
abbreviation?.let(Station::getByAbbreviation)
}
- class TripLegRecord constructor() {
+ class TripLegRecord {
@JvmField var line: String? = null
@JvmField var origin: String? = null
@JvmField var destination: String? = null
@@ -108,6 +76,9 @@ class FollowedTripRecord constructor() {
@JvmField var departureSource: String? = null
@JvmField var arrivalSource: String? = null
@JvmField var platform: String? = null
+ @JvmField var serviceDate: String? = null
+ @JvmField var canceled = false
+ @JvmField var direction: String? = null
@JvmField var stops: MutableList = mutableListOf()
fun toTripLeg(): TripLeg = TripLeg(
@@ -125,6 +96,9 @@ class FollowedTripRecord constructor() {
predictionSource(departureSource),
predictionSource(arrivalSource),
platform,
+ serviceDate?.let { value -> runCatching { LocalDate.parse(value) }.getOrNull() },
+ canceled,
+ direction,
)
companion object {
@@ -143,12 +117,15 @@ class FollowedTripRecord constructor() {
departureSource = leg.departureSource.name
arrivalSource = leg.arrivalSource.name
platform = leg.platform
+ serviceDate = leg.serviceDate?.toString()
+ canceled = leg.canceled
+ direction = leg.direction
stops = leg.stops.map(TripStopRecord::fromTripStop).toMutableList()
}
}
}
- class TripStopRecord constructor() {
+ class TripStopRecord {
@JvmField var station: String? = null
@JvmField var arrivalTime = 0L
@JvmField var departureTime = 0L
@@ -186,7 +163,5 @@ private fun predictionSource(value: String?): PredictionSource =
value?.let { runCatching { PredictionSource.valueOf(it) }.getOrNull() }
?: PredictionSource.UNKNOWN
-private fun abbreviation(station: Station?): String? = station?.abbreviation
-
private fun station(abbreviation: String?): Station? =
abbreviation?.let(Station::getByAbbreviation)
diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt
index eff1faf..9de9950 100644
--- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt
+++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripRepository.kt
@@ -1,7 +1,8 @@
package `in`.izyum.bart.data
import android.content.Context
-import `in`.izyum.bart.model.Departure
+import android.util.Log
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.SystemTimeSource
import `in`.izyum.bart.model.TimeSource
import `in`.izyum.bart.platform.DepartureAlarmScheduler
@@ -14,12 +15,13 @@ import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
-/** Owns the followed trip, its process-death cache, and its observable state. */
+/** Owns the followed itinerary, its process-death cache, and its observable state. */
class FollowedTripRepository @JvmOverloads constructor(
context: Context,
private val timeSource: TimeSource = SystemTimeSource
) : AutoCloseable {
private companion object {
+ const val TAG = "FollowedTripRepository"
const val STORAGE_FILE_NAME = "followed_trip.json"
}
@@ -28,68 +30,72 @@ class FollowedTripRepository @JvmOverloads constructor(
private val store = FollowedTripStore(storageFile)
private val persistenceExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private val stateLock = Any()
- private var pendingDeparture: Departure? = null
+ private var pendingItinerary: Itinerary? = null
private var hasPendingPersistence = false
private var persistenceWriteQueued = false
- private var followedDeparture: Departure? = restore()
- private var alarmScheduler: DepartureAlarmScheduler? = followedDeparture?.let {
+ private var followedItinerary: Itinerary? = restore()
+ private var alarmScheduler: DepartureAlarmScheduler? = followedItinerary?.let {
DepartureAlarmScheduler(applicationContext, it)
}
- private val _state = MutableStateFlow(toState(followedDeparture))
+ private val _state = MutableStateFlow(toState(followedItinerary))
private val _backgroundPollingNeeded = MutableStateFlow(
alarmScheduler?.isTracking == true,
)
val state: StateFlow = _state.asStateFlow()
val backgroundPollingNeeded: StateFlow = _backgroundPollingNeeded.asStateFlow()
- fun getFollowedDeparture(): Departure? {
- val departure = synchronized(stateLock) { followedDeparture }
- if (departure != null && departure.hasInitialDeparturePassed(timeSource.nowMillis(), pessimistic = true)) {
+ fun getFollowedItinerary(): Itinerary? {
+ val itinerary = synchronized(stateLock) { followedItinerary }
+ if (itinerary != null && itinerary.hasInitialDeparturePassed(timeSource.nowMillis(), pessimistic = true)) {
// A followed train is monitored only until departure. Stop the
// background work as soon as the cached estimate crosses departure,
// even if no realtime refresh is available.
stopTracking()
}
- if (departure != null && departure.hasExpired(timeSource.nowMillis())) {
- clearFollowedDeparture()
+ if (itinerary != null && itinerary.hasExpired(timeSource.nowMillis())) {
+ clearFollowedItinerary()
return null
}
- return departure
+ return itinerary
}
- fun setFollowedDeparture(
- departure: Departure?,
+ fun setFollowedItinerary(
+ itinerary: Itinerary?,
refreshBackgroundWork: Boolean = true,
) {
val previousScheduler: DepartureAlarmScheduler?
val preserveAlarm = synchronized(stateLock) {
- followedDeparture?.let { previous ->
- departure != null && isSameAlarmDeparture(previous, departure)
+ followedItinerary?.let { previous ->
+ itinerary != null && isSameAlarmItinerary(previous, itinerary)
} == true
}
synchronized(stateLock) {
- if (departure == followedDeparture) {
+ if (itinerary == followedItinerary) {
return
}
previousScheduler = alarmScheduler
previousScheduler?.close(preservePending = preserveAlarm)
- followedDeparture = departure
- alarmScheduler = departure?.let {
+ followedItinerary = itinerary
+ alarmScheduler = itinerary?.let {
DepartureAlarmScheduler(applicationContext, it)
}
- _state.value = toState(departure)
+ _state.value = toState(itinerary)
refreshBackgroundPollingStateLocked()
}
- persist(departure)
+ persist(itinerary)
if (refreshBackgroundWork) {
DeparturePollingAlarm.refresh(applicationContext, this)
}
}
+ fun clearFollowedItinerary() {
+ setFollowedItinerary(null)
+ }
+
fun clearFollowedDeparture() {
- setFollowedDeparture(null)
+ clearFollowedItinerary()
}
fun getAlarmScheduler(): DepartureAlarmScheduler? {
@@ -126,21 +132,21 @@ class FollowedTripRepository @JvmOverloads constructor(
}
/** Atomically claims a pending alarm and returns the departure it belongs to. */
- fun handleAlarmTriggered(): Departure? {
- val departure = synchronized(stateLock) {
+ fun handleAlarmTriggered(): Itinerary? {
+ val itinerary = synchronized(stateLock) {
if (alarmScheduler?.isPending != true) {
return@synchronized null
}
alarmScheduler?.notifyAlarmHasBeenHandled()
- followedDeparture
+ followedItinerary
}
refreshBackgroundPollingState()
- return departure
+ return itinerary
}
/** Reads the cached trip without applying expiry or tracking side effects. */
- internal fun peekFollowedDeparture(): Departure? =
- synchronized(stateLock) { followedDeparture }
+ internal fun peekFollowedItinerary(): Itinerary? =
+ synchronized(stateLock) { followedItinerary }
private fun refreshBackgroundPollingStateInternal() {
synchronized(stateLock) { refreshBackgroundPollingStateLocked() }
@@ -156,22 +162,22 @@ class FollowedTripRepository @JvmOverloads constructor(
_backgroundPollingNeeded.value = alarmScheduler?.isTracking == true
}
- internal fun backgroundPollingDelayMillis(departure: Departure?): Long {
+ internal fun backgroundPollingDelayMillis(itinerary: Itinerary?): Long {
val nowMillis = timeSource.nowMillis()
val scheduler = getAlarmScheduler()
- val alarmTime = if (scheduler?.isPending == true && departure != null) {
- DepartureAlarmPolicy.alarmTime(departure, scheduler.leadTimeMinutes)
+ val alarmTime = if (scheduler?.isPending == true && itinerary != null) {
+ DepartureAlarmPolicy.alarmTime(itinerary, scheduler.leadTimeMinutes)
} else {
- departure?.getInitialArrivalTime(pessimistic = true) ?: nowMillis
+ itinerary?.getInitialArrivalTime(pessimistic = true) ?: nowMillis
}
return DepartureAlarmPolicy.nextPollingDelayMillis(alarmTime - nowMillis)
}
- private fun restore(): Departure? = store.load()
+ private fun restore(): Itinerary? = store.loadItinerary()
- private fun persist(departure: Departure?) {
+ private fun persist(itinerary: Itinerary?) {
synchronized(stateLock) {
- pendingDeparture = departure
+ pendingItinerary = itinerary
hasPendingPersistence = true
if (persistenceWriteQueued) {
return
@@ -180,41 +186,56 @@ class FollowedTripRepository @JvmOverloads constructor(
}
persistenceExecutor.execute {
while (true) {
- val nextDeparture = synchronized(stateLock) {
+ val nextItinerary = synchronized(stateLock) {
if (!hasPendingPersistence) {
persistenceWriteQueued = false
return@execute
}
hasPendingPersistence = false
- pendingDeparture
+ pendingItinerary
}
try {
- store.save(nextDeparture)
+ store.saveItinerary(nextItinerary)
} catch (exception: Exception) {
- // Persistence is best effort; the in-memory state remains authoritative.
+ Log.w(TAG, "Could not persist followed trip state", exception)
}
}
}
}
- private fun toState(departure: Departure?): FollowedTripState =
- FollowedTripState(departure)
+ private fun toState(itinerary: Itinerary?): FollowedTripState =
+ FollowedTripState(itinerary)
/**
* Realtime updates can add trip-leg IDs after a trip has been followed. The
* alarm belongs to the train, not to that feed detail, so retain it when the
- * route and nearby departure still identify the same train.
+ * route and nearby departure still identify the same train. A matching
+ * first-leg trip identity is required so adjacent trains cannot inherit
+ * one another's alarm state.
*/
- private fun isSameAlarmDeparture(previous: Departure, next: Departure): Boolean {
- if (previous.identity == next.identity) {
+ private fun isSameAlarmItinerary(previous: Itinerary, next: Itinerary): Boolean {
+ if (previous.selectionIdentity == next.selectionIdentity) {
return true
}
- return previous.origin?.abbreviation == next.origin?.abbreviation
- && previous.trainDestination?.abbreviation == next.trainDestination?.abbreviation
+ val previousFirstLeg = previous.legs.firstOrNull()
+ val nextFirstLeg = next.legs.firstOrNull()
+ if (previousFirstLeg?.tripId != nextFirstLeg?.tripId) {
+ return false
+ }
+ if (previousFirstLeg?.serviceDate != null
+ && nextFirstLeg?.serviceDate != null
+ && previousFirstLeg.serviceDate != nextFirstLeg.serviceDate
+ ) {
+ return false
+ }
+ return previous.origin == next.origin
+ && previous.destination == next.destination
&& previous.line == next.line
&& previous.direction == next.direction
&& previous.platform == next.platform
- && kotlin.math.abs(previous.getMeanEstimate() - next.getMeanEstimate()) <= 5 * 60_000L
+ && kotlin.math.abs(
+ previous.getInitialDepartureTime() - next.getInitialDepartureTime(),
+ ) <= 5 * 60_000L
}
override fun close() {
diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripState.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripState.kt
index 94f5900..38fb794 100644
--- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripState.kt
+++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripState.kt
@@ -1,8 +1,8 @@
package `in`.izyum.bart.data
-import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
-/** Immutable state of the departure currently being followed. */
+/** Immutable state of the itinerary currently being followed. */
data class FollowedTripState(
- val departure: Departure?,
+ val itinerary: Itinerary?,
)
diff --git a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt
index a4e318c..5a9ff14 100644
--- a/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt
+++ b/app/src/main/kotlin/in/izyum/bart/data/FollowedTripStore.kt
@@ -1,9 +1,13 @@
package `in`.izyum.bart.data
-import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import java.io.File
+import java.nio.file.AtomicMoveNotSupportedException
+import java.nio.file.Files
+import java.nio.file.StandardCopyOption.ATOMIC_MOVE
+import java.nio.file.StandardCopyOption.REPLACE_EXISTING
/** Pure file-backed persistence for the disposable followed-trip state. */
class FollowedTripStore @JvmOverloads constructor(
@@ -11,14 +15,11 @@ class FollowedTripStore @JvmOverloads constructor(
private val objectMapper: ObjectMapper = ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false),
) {
- fun load(): Departure? {
- if (!storageFile.exists()) {
- return null
- }
+ fun loadItinerary(): Itinerary? {
+ if (!storageFile.exists()) return null
return try {
storageFile.inputStream().use { input ->
- objectMapper.readValue(input, FollowedTripRecord::class.java)
- .toDeparture()
+ objectMapper.readValue(input, FollowedTripRecord::class.java).toItinerary()
}
} catch (exception: Exception) {
delete()
@@ -26,32 +27,47 @@ class FollowedTripStore @JvmOverloads constructor(
}
}
- fun save(departure: Departure?) {
- if (departure == null) {
+ fun saveItinerary(itinerary: Itinerary?) {
+ if (itinerary == null) {
delete()
return
}
- storageFile.parentFile?.mkdirs()
- val temporaryFile = File(storageFile.parentFile,
- storageFile.name + ".tmp")
+ saveRecord(FollowedTripRecord.fromItinerary(itinerary))
+ }
+
+ private fun saveRecord(record: FollowedTripRecord) {
+ val parent = storageFile.parentFile ?: File(".")
+ parent.mkdirs()
+ val temporaryFile = File(parent, storageFile.name + ".tmp")
try {
temporaryFile.outputStream().use { output ->
- objectMapper.writeValue(output,
- FollowedTripRecord.fromDeparture(departure))
- }
- if (storageFile.exists() && !storageFile.delete()) {
- throw IllegalStateException("Could not replace followed trip state")
- }
- if (!temporaryFile.renameTo(storageFile)) {
- throw IllegalStateException("Could not save followed trip state")
+ objectMapper.writeValue(output, record)
}
+ replaceStorageFile(temporaryFile)
} catch (exception: Exception) {
temporaryFile.delete()
throw exception
}
}
+ private fun replaceStorageFile(temporaryFile: File) {
+ try {
+ Files.move(
+ temporaryFile.toPath(),
+ storageFile.toPath(),
+ REPLACE_EXISTING,
+ ATOMIC_MOVE,
+ )
+ } catch (_: AtomicMoveNotSupportedException) {
+ Files.move(
+ temporaryFile.toPath(),
+ storageFile.toPath(),
+ REPLACE_EXISTING,
+ )
+ }
+ }
+
private fun delete() {
if (storageFile.exists() && !storageFile.delete()) {
throw IllegalStateException("Could not delete followed trip state")
diff --git a/app/src/main/kotlin/in/izyum/bart/model/Departure.kt b/app/src/main/kotlin/in/izyum/bart/model/Departure.kt
index 5b88cfe..f810863 100644
--- a/app/src/main/kotlin/in/izyum/bart/model/Departure.kt
+++ b/app/src/main/kotlin/in/izyum/bart/model/Departure.kt
@@ -9,14 +9,8 @@ data class Departure(
val trainDestination: Station?,
val passengerDestination: Station?,
val line: Line?,
- val destinationColorHex: String?,
- val destinationColorText: String?,
val platform: String?,
- val direction: String?,
- val bikeAllowed: Boolean,
val trainLength: String?,
- val requiresTransfer: Boolean,
- val transferScheduled: Boolean,
val canceled: Boolean,
val minutes: Int,
val minEstimate: Long,
@@ -24,22 +18,19 @@ data class Departure(
val estimatedTripTime: Int,
val beganAsDeparted: Boolean,
val arrivalTimeOverride: Long,
- val listedInETDs: Boolean,
val tripLegs: List,
) : Comparable {
/** Stable identity used to match a departure across feed refreshes. */
val identity: String
get() = buildString {
- append(line).append('|')
- .append(trainDestination?.abbreviation).append('|')
- .append(direction).append('|')
- .append(platform).append('|')
if (tripLegs.isEmpty()) {
- append("no-legs")
+ append("observation|")
+ .append(origin?.abbreviation).append('|')
+ .append(minEstimate)
} else {
tripLegs.forEach {
- append(it.tripId ?: "etd@").append(
+ append(it.canonicalIdentity ?: "etd@").append(
if (it.tripId == null) it.departureTime else ""
).append(';')
}
@@ -57,8 +48,6 @@ data class Departure(
fun hasTransfers(): Boolean = tripLegs.size > 1
- fun isListedInETDs(): Boolean = listedInETDs
-
fun hasAnyArrivalEstimate(): Boolean =
(tripLegs.isNotEmpty() && hasCompleteTripLegs() && tripLegs.last().hasArrivalTime())
|| estimatedTripTime > 0
@@ -92,9 +81,14 @@ data class Departure(
fun getMeanEstimate(min: Long, max: Long): Long = (min + max) / 2L
- /** Latest safe estimate for the train's arrival at the initial station. */
+ /** Lower-bound estimate for the train's arrival at the initial station. */
fun getInitialArrivalTime(pessimistic: Boolean = false): Long {
- val departureEstimate = if (pessimistic) maxEstimate else getMeanEstimate()
+ val firstLeg = tripLegs.firstOrNull()
+ val departureEstimate = when {
+ pessimistic && firstLeg != null -> pessimisticDepartureTime(firstLeg)
+ pessimistic -> minEstimate
+ else -> getMeanEstimate()
+ }
val firstStop = tripLegs.firstOrNull()?.stops?.firstOrNull { it.station == origin }
val actualDwell = if (firstStop != null && firstStop.arrivalTime > 0L && firstStop.departureTime > 0L) {
(firstStop.departureTime - firstStop.arrivalTime).coerceAtLeast(0L)
@@ -107,7 +101,11 @@ data class Departure(
}
fun getInitialDepartureTime(pessimistic: Boolean = false): Long =
- if (pessimistic) maxEstimate else getMeanEstimate()
+ if (pessimistic) {
+ tripLegs.firstOrNull()?.let(::pessimisticDepartureTime) ?: minEstimate
+ } else {
+ getMeanEstimate()
+ }
fun hasInitialDeparturePassed(nowMillis: Long, pessimistic: Boolean = false): Boolean =
getInitialDepartureTime(pessimistic) <= nowMillis
@@ -199,7 +197,7 @@ data class Departure(
override fun toString(): String {
return buildString {
append(trainDestination)
- if (requiresTransfer) append(" (w/ xfer)")
+ if (hasTransfers()) append(" (w/ xfer)")
append(", ")
append("estimate=").append(getMeanEstimate())
}
@@ -231,7 +229,10 @@ data class Departure(
previous.tripLegs
}
- var merged = previous.copy(tripLegs = immutableList(tripLegs))
+ // Identity is stable across platform/terminal changes. Refresh all
+ // display metadata from the incoming projection while preserving
+ // only the deliberate estimate-smoothing policy below.
+ var merged = incoming.copy(tripLegs = immutableList(tripLegs))
if (incoming.hasDeparted(now)
&& previous.origin?.longStationLinger == true
&& previous.minEstimate > 0
@@ -296,14 +297,8 @@ data class Departure(
private var trainDestination: Station? = null
private var passengerDestination: Station? = null
private var line: Line? = null
- private var destinationColorHex: String? = null
- private var destinationColorText: String? = null
private var platform: String? = null
- private var direction: String? = null
- private var bikeAllowed = false
private var trainLength: String? = null
- private var requiresTransfer = false
- private var transferScheduled = false
private var canceled = false
private var minutes = 0
private var minEstimate = 0L
@@ -311,21 +306,14 @@ data class Departure(
private var estimatedTripTime = 0
private var beganAsDeparted = false
private var arrivalTimeOverride = 0L
- private var listedInETDs = true
private var tripLegs: List = emptyList()
fun setOrigin(value: Station?) = apply { origin = value }
fun setTrainDestination(value: Station?) = apply { trainDestination = value }
fun setPassengerDestination(value: Station?) = apply { passengerDestination = value }
fun setLine(value: Line?) = apply { line = value }
- fun setTrainDestinationColorHex(value: String?) = apply { destinationColorHex = value }
- fun setTrainDestinationColorText(value: String?) = apply { destinationColorText = value }
fun setPlatform(value: String?) = apply { platform = value }
- fun setDirection(value: String?) = apply { direction = value }
- fun setBikeAllowed(value: Boolean) = apply { bikeAllowed = value }
fun setTrainLength(value: String?) = apply { trainLength = value }
- fun setRequiresTransfer(value: Boolean) = apply { requiresTransfer = value }
- fun setTransferScheduled(value: Boolean) = apply { transferScheduled = value }
fun setCanceled(value: Boolean) = apply { canceled = value }
fun setMinutes(value: Int) = apply {
minutes = value
@@ -335,7 +323,6 @@ data class Departure(
fun setMaxEstimate(value: Long) = apply { maxEstimate = value }
fun setEstimatedTripTime(value: Int) = apply { estimatedTripTime = value }
fun setArrivalTimeOverride(value: Long) = apply { arrivalTimeOverride = value }
- fun setListedInETDs(value: Boolean) = apply { listedInETDs = value }
fun setTripLegs(value: List?) = apply { tripLegs = value ?: emptyList() }
fun build(): Departure {
@@ -345,14 +332,8 @@ data class Departure(
trainDestination,
passengerDestination,
line,
- destinationColorHex,
- destinationColorText,
platform,
- direction,
- bikeAllowed,
trainLength,
- requiresTransfer,
- transferScheduled,
canceled,
minutes,
minEstimate,
@@ -360,7 +341,6 @@ data class Departure(
estimatedTripTime,
beganAsDeparted,
arrivalTimeOverride,
- listedInETDs,
immutableLegs,
)
return departure.withImmutableTripLegs(immutableLegs)
diff --git a/app/src/main/kotlin/in/izyum/bart/model/Itinerary.kt b/app/src/main/kotlin/in/izyum/bart/model/Itinerary.kt
new file mode 100644
index 0000000..6cd0531
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/model/Itinerary.kt
@@ -0,0 +1,100 @@
+package `in`.izyum.bart.model
+
+/**
+ * The selected passenger journey. Unlike [Departure], this is the state owned
+ * by the trip-progress screen: its legs may be refreshed individually and its
+ * future suffix may be replaced when a connection becomes infeasible.
+ */
+data class Itinerary(
+ val origin: Station,
+ val destination: Station,
+ val legs: List,
+) {
+ val trainDestination: Station?
+ get() = legs.lastOrNull()?.trainDestination ?: legs.lastOrNull()?.destination
+
+ val line: Line?
+ get() = legs.firstOrNull()?.line
+
+ val direction: String?
+ get() = legs.firstOrNull()?.direction
+
+ val platform: String?
+ get() = legs.firstOrNull()?.platform
+
+ val canceled: Boolean
+ get() = legs.any { it.canceled }
+
+ /** Stable anchor used to reopen the selected journey across feed refreshes. */
+ val selectionIdentity: String
+ get() = legs.firstOrNull()?.tripIdentity?.toString()
+ ?: "itinerary|${origin.abbreviation}|${destination.abbreviation}|${legs.firstOrNull()?.departureTime ?: 0L}"
+
+ fun hasTransfers(): Boolean = legs.size > 1
+
+ fun getStationPair(): StationPair = StationPair(origin, destination)
+
+ fun getInitialDepartureTime(pessimistic: Boolean = false): Long {
+ val first = legs.firstOrNull() ?: return 0L
+ return if (pessimistic) pessimisticDepartureTime(first) else first.departureTime
+ }
+
+ fun getInitialArrivalTime(pessimistic: Boolean = false): Long {
+ val first = legs.firstOrNull() ?: return 0L
+ val stop = first.stops.firstOrNull { it.station == origin }
+ val actualDwell = if (stop != null && stop.arrivalTime > 0L && stop.departureTime > 0L) {
+ (stop.departureTime - stop.arrivalTime).coerceAtLeast(0L)
+ } else 0L
+ val scheduledDwell = if (stop != null && stop.scheduledArrivalTime > 0L && stop.scheduledDepartureTime > 0L) {
+ (stop.scheduledDepartureTime - stop.scheduledArrivalTime).coerceAtLeast(0L)
+ } else 0L
+ return (getInitialDepartureTime(pessimistic) - maxOf(actualDwell, scheduledDwell))
+ .coerceAtLeast(0L)
+ }
+
+ fun getEstimatedArrivalTime(): Long = legs.lastOrNull()?.arrivalTime ?: 0L
+
+ fun hasAnyArrivalEstimate(): Boolean = getEstimatedArrivalTime() > 0L
+
+ fun getEstimatedArrivalMinutesLeft(nowMillis: Long): Long {
+ val arrival = getEstimatedArrivalTime()
+ if (arrival <= 0L) return 0L
+ val millisLeft = arrival - nowMillis
+ return if (millisLeft < 0L) -1L else (millisLeft + 29_999L) / 60_000L
+ }
+
+ fun hasInitialDeparturePassed(nowMillis: Long, pessimistic: Boolean = false): Boolean =
+ getInitialDepartureTime(pessimistic) <= nowMillis
+
+ fun hasExpired(nowMillis: Long): Boolean =
+ hasAnyArrivalEstimate() && getEstimatedArrivalTime() + 60_000L < nowMillis
+
+ fun replaceLegs(updatedLegs: List): Itinerary = copy(legs = updatedLegs)
+
+ /** Compatibility adapter for alarms, notifications, and the departure list. */
+ fun toDeparture(): Departure = Departure.builder()
+ .setOrigin(origin)
+ .setTrainDestination(trainDestination)
+ .setPassengerDestination(destination)
+ .setLine(line)
+ .setPlatform(platform)
+ .setCanceled(canceled)
+ .setMinEstimate(getInitialDepartureTime())
+ .setMaxEstimate(getInitialDepartureTime())
+ .setEstimatedTripTime(
+ (getEstimatedArrivalTime() - getInitialDepartureTime()).coerceAtLeast(0L).toInt(),
+ )
+ .setTripLegs(legs)
+ .build()
+
+ companion object {
+ @JvmStatic
+ fun fromDeparture(departure: Departure): Itinerary? {
+ val origin = departure.origin ?: return null
+ val destination = departure.passengerDestination
+ ?: departure.trainDestination
+ ?: return null
+ return Itinerary(origin, destination, departure.tripLegs)
+ }
+ }
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/model/Line.kt b/app/src/main/kotlin/in/izyum/bart/model/Line.kt
index 8ae5541..0a7dc30 100644
--- a/app/src/main/kotlin/in/izyum/bart/model/Line.kt
+++ b/app/src/main/kotlin/in/izyum/bart/model/Line.kt
@@ -9,13 +9,10 @@ enum class Line(
RED,
ORANGE,
YELLOW,
- YELLOW_LATE_NIGHT,
BLUE,
GREEN,
YELLOW_ORANGE_SCHEDULED_TRANSFER(YELLOW, ORANGE),
- PURPLE,
- /** Technical-only identity for BART's separate terminal RT feed. */
- YELLOW_DMU(label = "Yellow shuttle");
+ PURPLE;
fun getDisplayName(): String = label ?: name
diff --git a/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt b/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt
index c9e24a0..6a2e659 100644
--- a/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt
+++ b/app/src/main/kotlin/in/izyum/bart/model/RealTimeDepartures.kt
@@ -1,6 +1,5 @@
package `in`.izyum.bart.model
-import `in`.izyum.bart.backend.Schedule
import java.util.ArrayList
import java.util.Collections
@@ -9,87 +8,23 @@ class RealTimeDepartures internal constructor(
private val origin: Station?,
private val destination: Station?,
private val time: Long,
- routes: List,
- unfilteredDepartures: List,
departures: List,
- private val schedule: Schedule,
private val transfersIncluded: Boolean = false,
) {
- private val routes = immutableList(routes)
- private val unfilteredDepartures = immutableList(unfilteredDepartures)
private val departures = immutableList(departures)
- init {
- requireNotNull(schedule) { "A schedule is required" }
- }
-
fun getDepartures(): List = departures
fun areTransfersIncluded(): Boolean = transfersIncluded
- fun includeTransferRoutes(): RealTimeDepartures = withAdditionalRoutes(
- schedule.preferredTransferRoutes(origin, destination)
- )
-
- fun includeDoubleTransferRoutes(): RealTimeDepartures = withAdditionalRoutes(
- schedule.doubleTransferRoutes(origin, destination)
- )
-
- fun sortDepartures(): RealTimeDepartures = copy(
- departures = departures.sortedBy { it.minutes }
- )
-
- fun finalizeDeparturesList(): RealTimeDepartures {
- if (destination == null) {
- return sortDepartures()
- }
- return sortDepartures()
- }
-
- private fun withAdditionalRoutes(additionalRoutes: List): RealTimeDepartures {
- val nextRoutes = routes + additionalRoutes
- return copy(
- routes = nextRoutes,
- departures = unfilteredDepartures.mapNotNull { departure ->
- findRouteForDeparture(departure, nextRoutes)?.let { route ->
- departure.copy(
- requiresTransfer = route.hasTransfer(),
- transferScheduled = Line.YELLOW_ORANGE_SCHEDULED_TRANSFER == route.directLine,
- )
- }
- },
- transfersIncluded = true,
- )
- }
-
- private fun copy(
- routes: List = this.routes,
- departures: List = this.departures,
- transfersIncluded: Boolean = this.transfersIncluded,
- ): RealTimeDepartures = RealTimeDepartures(
+ fun sortDepartures(): RealTimeDepartures = RealTimeDepartures(
origin,
destination,
time,
- routes,
- unfilteredDepartures,
- departures,
- schedule,
+ departures.sortedBy { it.minutes },
transfersIncluded,
)
- private fun findRouteForDeparture(
- departure: Departure,
- routes: List,
- ): Route? {
- val trainDestination = Station.getByAbbreviation(
- departure.trainDestination?.abbreviation
- )
- val line = departure.line ?: return null
- return routes.firstOrNull { route ->
- route.trainDestinationIsApplicable(trainDestination, line)
- }
- }
-
private fun immutableList(values: Collection): List =
Collections.unmodifiableList(ArrayList(values))
diff --git a/app/src/main/kotlin/in/izyum/bart/model/Route.kt b/app/src/main/kotlin/in/izyum/bart/model/Route.kt
index 096019c..77c2c14 100644
--- a/app/src/main/kotlin/in/izyum/bart/model/Route.kt
+++ b/app/src/main/kotlin/in/izyum/bart/model/Route.kt
@@ -60,8 +60,7 @@ class Route private constructor(
|| viaLine == directLine.transferLine2
}
// Departures are queried at the passenger origin, so only the
- // first line of a multi-leg route can be represented by an ETD
- // returned for this route. The remaining lines are paired later.
+ // first line of a multi-leg route is represented on the board.
if (viaLine != lines.first()) {
return false
}
diff --git a/app/src/main/kotlin/in/izyum/bart/model/TripIdentity.kt b/app/src/main/kotlin/in/izyum/bart/model/TripIdentity.kt
new file mode 100644
index 0000000..2b87cc3
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/model/TripIdentity.kt
@@ -0,0 +1,11 @@
+package `in`.izyum.bart.model
+
+import java.time.LocalDate
+
+/** Stable identity of one published static trip on one service date. */
+data class TripIdentity(
+ val serviceDate: LocalDate,
+ val tripId: String,
+) {
+ override fun toString(): String = "$serviceDate:$tripId"
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/model/TripLeg.kt b/app/src/main/kotlin/in/izyum/bart/model/TripLeg.kt
index 74d5e36..8c68f96 100644
--- a/app/src/main/kotlin/in/izyum/bart/model/TripLeg.kt
+++ b/app/src/main/kotlin/in/izyum/bart/model/TripLeg.kt
@@ -2,6 +2,7 @@ package `in`.izyum.bart.model
import java.util.ArrayList
import java.util.Collections
+import java.time.LocalDate
/** One train in a possibly multi-train itinerary. */
class TripLeg @JvmOverloads constructor(
@@ -19,11 +20,31 @@ class TripLeg @JvmOverloads constructor(
val departureSource: PredictionSource = PredictionSource.UNKNOWN,
val arrivalSource: PredictionSource = PredictionSource.UNKNOWN,
val platform: String? = null,
+ /** Static service date keeps trip IDs stable across midnight refreshes. */
+ val serviceDate: LocalDate? = null,
+ val canceled: Boolean = false,
+ val direction: String? = null,
) {
val stops: List = immutableTripLegList(stops)
+ val canonicalIdentity: String?
+ get() = tripIdentity?.toString() ?: tripId
+
+ val tripIdentity: TripIdentity?
+ get() = tripId?.let { id -> serviceDate?.let { TripIdentity(it, id) } }
+
fun hasArrivalTime(): Boolean = arrivalTime > 0
}
+/** BART's ETD range is generally +/- 30 seconds around the effective time. */
+internal const val DEPARTURE_UNCERTAINTY_MILLIS = 30_000L
+
+/** Lower-bound boarding time used by safety-sensitive countdowns. */
+internal fun pessimisticDepartureTime(leg: TripLeg): Long {
+ val effectiveDeparture = leg.departureTime.takeIf { it > 0L }
+ ?: leg.scheduledDepartureTime
+ return (effectiveDeparture - DEPARTURE_UNCERTAINTY_MILLIS).coerceAtLeast(0L)
+}
+
private fun immutableTripLegList(values: Collection): List =
Collections.unmodifiableList(ArrayList(values))
diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/BartApiConfig.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/BartApiConfig.kt
index 4a0565b..9396ede 100644
--- a/app/src/main/kotlin/in/izyum/bart/networktasks/BartApiConfig.kt
+++ b/app/src/main/kotlin/in/izyum/bart/networktasks/BartApiConfig.kt
@@ -3,7 +3,6 @@ package `in`.izyum.bart.networktasks
/** External BART endpoints and credentials shared by the network clients. */
object BartApiConfig {
const val LEGACY_API_KEY = "MW9S-E7SL-26DU-VV8V"
- const val LEGACY_ETD_URL = "https://api.bart.gov/api/etd.aspx"
const val LEGACY_ELEVATOR_URL = "https://api.bart.gov/api/bsa.aspx"
const val GTFS_RT_TRIP_UPDATES_URL = "https://api.bart.gov/gtfsrt/tripupdate.aspx"
const val GTFS_RT_ALERTS_URL = "https://api.bart.gov/gtfsrt/alerts.aspx"
diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt
deleted file mode 100644
index effc216..0000000
--- a/app/src/main/kotlin/in/izyum/bart/networktasks/EtdClient.kt
+++ /dev/null
@@ -1,144 +0,0 @@
-package `in`.izyum.bart.networktasks
-
-import `in`.izyum.bart.model.Line
-import `in`.izyum.bart.model.Station
-import com.fasterxml.jackson.databind.JsonNode
-import com.fasterxml.jackson.databind.ObjectMapper
-import okhttp3.HttpUrl
-import okhttp3.OkHttpClient
-import okhttp3.Request
-import okhttp3.HttpUrl.Companion.toHttpUrl
-import java.io.IOException
-
-/** One legacy ETD estimate returned by BART's station operations API. */
-data class EtdDeparture(
- val destination: Station?,
- val line: Line?,
- val departureTimeMillis: Long,
- val platform: String?,
- val direction: String?,
- val canceled: Boolean,
-)
-
-/** A normalized legacy ETD board for one station. */
-data class EtdStationBoard(
- val station: Station,
- val receivedAtMillis: Long,
- val departures: List,
-) {
- fun departuresFor(line: Line?, destination: Station?): List =
- departures.filter { departure ->
- normalizeLine(departure.line) == normalizeLine(line)
- && normalizeDestination(departure.destination, departure.line) ==
- normalizeDestination(destination, line)
- }
-
- private fun normalizeLine(line: Line?): Line? = when (line) {
- Line.YELLOW_LATE_NIGHT -> Line.YELLOW
- else -> line
- }
-
- /** BART's ETD board labels the Yellow SFO terminus as MLBR. */
- private fun normalizeDestination(destination: Station?, line: Line?): Station? =
- if (normalizeLine(line) == Line.YELLOW
- && destination in setOf(Station.MLBR, Station.SFIA)
- ) {
- Station.SFIA
- } else {
- destination
- }
-}
-
-interface EtdClient {
- fun fetch(station: Station, receivedAtMillis: Long): EtdStationBoard
-}
-
-/** Downloads the legacy ETD board used by BART's station displays. */
-class HttpEtdClient @JvmOverloads constructor(
- private val client: OkHttpClient = NetworkUtils.makeHttpClient(),
-) : EtdClient {
- override fun fetch(station: Station, receivedAtMillis: Long): EtdStationBoard {
- val request = Request.Builder()
- .url(etdUrl(station))
- .header("Accept", "application/json")
- .build()
- return client.newCall(request).execute().use { response ->
- if (!response.isSuccessful) {
- throw IOException("ETD status returned ${response.code}")
- }
- val body = response.body
- parseBoard(station, receivedAtMillis, body.string())
- }
- }
-
- private fun etdUrl(station: Station): HttpUrl = BartApiConfig.LEGACY_ETD_URL.toHttpUrl()
- .newBuilder()
- .addQueryParameter("cmd", "etd")
- .addQueryParameter("orig", station.abbreviation.lowercase())
- .addQueryParameter("key", BartApiConfig.LEGACY_API_KEY)
- .addQueryParameter("json", "y")
- .build()
-
- companion object {
- private val objectMapper = ObjectMapper()
-
- internal fun parseBoard(
- station: Station,
- receivedAtMillis: Long,
- json: String,
- ): EtdStationBoard {
- val root = objectMapper.readTree(json).path("root")
- val stationNode = asList(root.path("station")).firstOrNull()
- ?: throw IOException("ETD response did not contain a station")
- val departures = asList(stationNode.path("etd")).flatMap { etd ->
- val destination = Station.getByAbbreviation(
- text(etd.path("abbreviation"))
- )
- asList(etd.path("estimate")).mapNotNull { estimate ->
- val minutes = parseMinutes(text(estimate.path("minutes")))
- ?: return@mapNotNull null
- EtdDeparture(
- destination = destination,
- line = lineForColor(
- text(estimate.path("color"))
- ?: text(etd.path("color"))
- ),
- departureTimeMillis = receivedAtMillis + minutes * 60_000L,
- platform = text(estimate.path("platform")),
- direction = text(estimate.path("direction")),
- canceled = text(estimate.path("cancelflag")) == "1",
- )
- }
- }
- return EtdStationBoard(station, receivedAtMillis, departures)
- }
-
- private fun asList(node: JsonNode): List = when {
- node.isArray -> node.toList()
- node.isObject -> listOf(node)
- else -> emptyList()
- }
-
- private fun text(node: JsonNode): String? = when {
- node.isTextual -> node.asText().trim().takeIf(String::isNotEmpty)
- node.isObject && node.path("#cdata-section").isTextual ->
- node.path("#cdata-section").asText().trim().takeIf(String::isNotEmpty)
- else -> null
- }
-
- private fun parseMinutes(value: String?): Long? = when {
- value == null -> null
- value.equals("leaving", ignoreCase = true) -> 0L
- else -> value.toLongOrNull()?.coerceAtLeast(0L)
- }
-
- private fun lineForColor(color: String?): Line? = when (color?.uppercase()) {
- "RED" -> Line.RED
- "ORANGE" -> Line.ORANGE
- "YELLOW" -> Line.YELLOW
- "BLUE" -> Line.BLUE
- "GREEN" -> Line.GREEN
- else -> null
- }
- }
-}
diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/EtdStationCache.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/EtdStationCache.kt
deleted file mode 100644
index 0b8d595..0000000
--- a/app/src/main/kotlin/in/izyum/bart/networktasks/EtdStationCache.kt
+++ /dev/null
@@ -1,70 +0,0 @@
-package `in`.izyum.bart.networktasks
-
-import `in`.izyum.bart.model.Station
-import `in`.izyum.bart.model.SystemTimeSource
-import `in`.izyum.bart.model.TimeSource
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.async
-import kotlinx.coroutines.awaitAll
-import kotlinx.coroutines.coroutineScope
-
-data class EtdLookup(
- val board: EtdStationBoard?,
- val error: Exception? = null,
-)
-
-/** Shares station ETD responses and expires them at the next reported train. */
-class EtdStationCache(
- private val client: EtdClient,
- private val timeSource: TimeSource = SystemTimeSource,
- private val retryMillis: Long = DEFAULT_RETRY_MILLIS,
-) {
- private data class Entry(
- val lookup: EtdLookup,
- val validUntilMillis: Long,
- )
-
- private val lock = Any()
- private val entries = mutableMapOf()
- private val stationLocks = mutableMapOf()
-
- fun get(station: Station): EtdLookup {
- val stationLock = synchronized(lock) {
- stationLocks.getOrPut(station) { Any() }
- }
- synchronized(stationLock) {
- val now = timeSource.nowMillis()
- synchronized(lock) {
- entries[station]
- ?.takeIf { now < it.validUntilMillis }
- ?.let { return it.lookup }
- }
- val lookup = try {
- EtdLookup(client.fetch(station, now))
- } catch (exception: Exception) {
- EtdLookup(null, exception)
- }
- val nextDeparture = lookup.board?.departures
- ?.map { it.departureTimeMillis }
- ?.filter { it > now }
- ?.minOrNull()
- val validUntil = nextDeparture ?: now + retryMillis
- synchronized(lock) {
- entries[station] = Entry(lookup, validUntil)
- }
- return lookup
- }
- }
-
- suspend fun getAll(stations: Set): Map = coroutineScope {
- stations.map { station ->
- async(Dispatchers.IO) { station to get(station) }
- }.awaitAll().toMap()
- }
-
- fun clear() = synchronized(lock) { entries.clear() }
-
- companion object {
- private const val DEFAULT_RETRY_MILLIS = 15_000L
- }
-}
diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt
deleted file mode 100644
index a719bfc..0000000
--- a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeContentHandler.kt
+++ /dev/null
@@ -1,1277 +0,0 @@
-package `in`.izyum.bart.networktasks
-
-import `in`.izyum.bart.model.Departure
-import `in`.izyum.bart.model.Line
-import `in`.izyum.bart.model.PredictionSource
-import `in`.izyum.bart.model.RealTimeDepartures
-import `in`.izyum.bart.model.Route
-import `in`.izyum.bart.model.Station
-import `in`.izyum.bart.model.TripLeg
-import `in`.izyum.bart.model.TripStop
-import `in`.izyum.bart.model.SystemTimeSource
-import `in`.izyum.bart.model.TimeSource
-import `in`.izyum.bart.routing.TransferPolicy
-import `in`.izyum.bart.backend.Schedule
-import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
-import com.google.transit.realtime.GtfsRealtime
-import java.time.DateTimeException
-import java.time.Instant
-import java.time.LocalDate
-import java.time.ZoneId
-import java.time.format.DateTimeFormatter
-
-/** Converts BART's GTFS-RT trip updates into the app's departure model. */
-class GtfsRealtimeContentHandler @JvmOverloads constructor(
- private val origin: Station,
- private val destination: Station?,
- private val routes: List,
- private val ignoreDirection: Boolean,
- private val bartGtfsNetwork: BartGtfsNetwork,
- private val timeSource: TimeSource = SystemTimeSource,
-) {
- private val transferPolicy = TransferPolicy(bartGtfsNetwork)
-
- init {
- requireNotNull(bartGtfsNetwork) { "A validated GTFS network is required" }
- }
-
- fun getRealTimeDepartures(feed: GtfsRealtime.FeedMessage): RealTimeDepartures {
- val feedIndex = GtfsRealtimeFeedIndex.from(feed)
- val feedTime = feedTime(feed)
- return getRealTimeDepartures(
- feedIndex,
- feedTime,
- correctedSchedule(feedIndex, feedTime),
- )
- }
-
- fun getRealTimeDepartures(
- feedIndex: GtfsRealtimeFeedIndex,
- feedTime: Long
- ): RealTimeDepartures = getRealTimeDepartures(
- feedIndex,
- feedTime,
- correctedSchedule(feedIndex, feedTime),
- )
-
- /** Uses a schedule that has already had this feed's realtime corrections applied. */
- fun getRealTimeDepartures(
- feedIndex: GtfsRealtimeFeedIndex,
- feedTime: Long,
- schedule: Schedule,
- excludedTripIds: Set = emptySet(),
- suppressScheduleCoveredByRealtime: Boolean = true,
- forcedScheduleTripIds: Set = emptySet(),
- ): RealTimeDepartures {
- val departures = DepartureCollection()
-
- val trips = parseTrips(
- feedIndex.tripUpdateEntities,
- feedTime,
- schedule,
- suppressScheduleCoveredByRealtime,
- forcedScheduleTripIds,
- )
- .filter { it.tripId !in excludedTripIds }
- trips.forEach { trip -> addTripUpdate(departures, trip, trips, feedTime) }
- return RealTimeDepartures(
- origin,
- destination,
- feedTime,
- routes,
- departures.unfiltered,
- departures.filtered,
- schedule,
- )
- }
-
- /**
- * Replaces the stop estimates for an already-selected itinerary using
- * the latest update for each exact train. A train may no longer include
- * the passenger's origin in the feed after it has departed, so missing
- * passed stops are deliberately retained from the previous snapshot.
- */
- fun updateTripLegs(
- feed: GtfsRealtime.FeedMessage,
- existingLegs: List,
- feedTime: Long
- ): List {
- val feedIndex = GtfsRealtimeFeedIndex.from(feed)
- return updateTripLegs(
- feedIndex,
- existingLegs,
- feedTime,
- correctedSchedule(feedIndex, feedTime),
- )
- }
-
- fun updateTripLegs(
- feedIndex: GtfsRealtimeFeedIndex,
- existingLegs: List,
- feedTime: Long
- ): List = updateTripLegs(
- feedIndex,
- existingLegs,
- feedTime,
- correctedSchedule(feedIndex, feedTime),
- )
-
- /** Uses a schedule that has already had this feed's realtime corrections applied. */
- fun updateTripLegs(
- feedIndex: GtfsRealtimeFeedIndex,
- existingLegs: List,
- feedTime: Long,
- schedule: Schedule
- ): List {
- val trips = parseTrips(
- feedIndex.tripUpdateEntities,
- feedTime,
- schedule,
- true,
- )
- val tripsById = trips
- .filter { !it.tripId.isNullOrEmpty() }
- .associateBy { it.tripId!! }
-
- val updatedLegs = existingLegs.map { existing ->
- val current = tripsById[existing.tripId] ?: findMatchingTrip(existing, trips)
- if (current == null) existing else updateTripLeg(existing, current)
- }.toMutableList()
-
- val route = routes.firstOrNull { matchesExistingLegs(it, updatedLegs) }
- if (route != null) {
- refreshConnectingLegs(route, updatedLegs, trips)
- }
- return updatedLegs
- }
-
- /**
- * Revalidates connections after each leg has been independently refreshed.
- * A delay can invalidate the previously selected next train, so replace it
- * with the first feasible later train or remove the unusable suffix.
- */
- private fun refreshConnectingLegs(
- route: Route,
- legs: MutableList,
- trips: List,
- ) {
- var index = 1
- while (index < route.lines.size) {
- val previous = legs.getOrNull(index - 1) ?: return
- val legOrigin = previous.destination ?: return
- val legDestination = if (index < route.transferStations.size) {
- route.transferStations[index]
- } else {
- destination ?: return
- }
- val existing = legs.getOrNull(index)
- if (existing != null
- && existing.line == route.lines[index]
- && existing.origin == legOrigin
- && existing.destination == legDestination
- && !isCanceled(existing, trips)
- && connectionIsFeasible(previous, existing)
- ) {
- index++
- continue
- }
-
- val connectingTrip = findConnectingTrip(
- route.lines[index],
- legOrigin,
- legDestination,
- previous,
- trips,
- )
- if (connectingTrip != null) {
- val replacement = tripLegFor(
- route, index, legOrigin, legDestination, connectingTrip
- )
- if (existing == null) legs += replacement else legs[index] = replacement
- index++
- continue
- }
-
- if (isUnscheduledTerminalLeg(route.lines[index], legOrigin, legDestination)) {
- val replacement = unscheduledTerminalLeg(
- route.lines[index], legOrigin, legDestination
- )
- if (existing == null) legs += replacement else legs[index] = replacement
- index++
- continue
- }
-
- while (legs.size > index) legs.removeAt(legs.lastIndex)
- return
- }
- }
-
- private fun connectionIsFeasible(previous: TripLeg, next: TripLeg): Boolean =
- previous.arrivalTime <= 0L || next.departureTime <= 0L
- || next.departureTime >= previous.arrivalTime
-
- private fun isCanceled(leg: TripLeg, trips: List): Boolean =
- leg.tripId != null && trips.any { it.tripId == leg.tripId && it.canceled }
-
- private fun matchesExistingLegs(route: Route, legs: List): Boolean {
- if (legs.isEmpty() || legs.size > route.lines.size) {
- return false
- }
- for (index in legs.indices) {
- val leg = legs[index]
- val expectedOrigin = if (index == 0) origin else legs[index - 1].destination
- if (leg.line != route.lines[index] || leg.origin != expectedOrigin) {
- return false
- }
-
- val expectedDestination = if (index < route.transferStations.size) {
- route.transferStations[index]
- } else {
- destination
- }
- if (leg.destination == expectedDestination) {
- continue
- }
-
- // A previously selected itinerary can end partway through a
- // route segment when the next connection was not present in the
- // feed. It is still the same line sequence, so allow the refresh
- // to continue from that actual station.
- if (index != legs.lastIndex || index >= route.transferStations.size
- || !isBeforeOnRoute(route, route.lines[index], leg.destination,
- expectedDestination)
- ) {
- return false
- }
- }
- return true
- }
-
- private fun isBeforeOnRoute(
- route: Route,
- line: Line,
- station: Station?,
- destination: Station?
- ): Boolean {
- val sequence = route.getStationSequence(line)
- val stationIndex = sequence.indexOf(station)
- val destinationIndex = sequence.indexOf(destination)
- return stationIndex >= 0 && destinationIndex >= 0 && stationIndex < destinationIndex
- }
-
- private fun appendConnectingLegs(
- route: Route,
- legs: MutableList,
- trips: List
- ) {
- val tripDestination = destination ?: return
- while (legs.size < route.lines.size) {
- val index = legs.size
- val legOrigin = legs[index - 1].destination ?: return
- val legDestination = if (index < route.transferStations.size) {
- route.transferStations[index]
- } else {
- tripDestination
- }
- val currentTrip = findConnectingTrip(
- route.lines[index],
- legOrigin,
- legDestination,
- legs[index - 1],
- trips
- )
- if (currentTrip == null) {
- if (isUnscheduledTerminalLeg(route.lines[index], legOrigin, legDestination)) {
- legs += unscheduledTerminalLeg(
- route.lines[index], legOrigin, legDestination
- )
- continue
- }
- return
- }
- if (currentTrip.pointAt(legOrigin) == null) return
- legs += tripLegFor(
- route, index, legOrigin, legDestination, currentTrip
- )
- }
- }
-
- private fun tripLegFor(
- route: Route,
- index: Int,
- legOrigin: Station,
- legDestination: Station,
- trip: TripSnapshot,
- ): TripLeg {
- val departure = trip.pointAt(legOrigin)
- val arrival = trip.pointAt(legDestination)
- val stops = trip.pointsBetween(legOrigin, legDestination).map {
- tripStop(it)
- }
- return TripLeg(
- lineForLeg(trip.line, legOrigin, legDestination, trip.trainDestination),
- legOrigin,
- legDestination,
- trip.trainDestination,
- trip.tripId,
- departure?.departureTime ?: 0L,
- arrival?.arrivalTime ?: 0L,
- stops,
- minimumTransferSecondsAfter(route, index, legOrigin, trip.line),
- departure?.scheduledDepartureTime ?: 0L,
- arrival?.scheduledArrivalTime ?: 0L,
- departure?.departureSource ?: PredictionSource.UNKNOWN,
- arrival?.arrivalSource ?: PredictionSource.UNKNOWN,
- departure?.platform,
- )
- }
-
- private fun isUnscheduledTerminalLeg(
- line: Line,
- origin: Station,
- destination: Station
- ): Boolean = line == Line.YELLOW_LATE_NIGHT
- && origin == Station.SFIA
- && destination == Station.MLBR
-
- private fun unscheduledTerminalLeg(
- line: Line,
- origin: Station,
- destination: Station
- ): TripLeg = TripLeg(
- line,
- origin,
- destination,
- destination,
- null,
- 0L,
- 0L,
- emptyList()
- )
-
- private fun parseTrips(
- entities: List,
- feedTime: Long,
- schedule: Schedule,
- suppressScheduleCoveredByRealtime: Boolean,
- forcedScheduleTripIds: Set = emptySet(),
- ): List {
- val scheduledTrips = schedule.trips.map(::snapshotFromSchedule).toMutableList()
- val scheduledIds = scheduledTrips.mapNotNull { it.tripId }.toSet()
- val realtimeTrips = entities.mapNotNull { entity ->
- if (!entity.hasTripUpdate()) null else parseTrip(entity.tripUpdate, feedTime)
- }.toMutableList()
- // The Antioch DMU and the electric train are reported as separate
- // updates. DMU trip IDs are technical 600-series IDs, so they cannot
- // be used as passenger trip identities. Join their terminal points
- // onto the nearest valid electric realtime trip before discarding the
- // DMU-only snapshot. Scheduled electric trips are also corrected in
- // Schedule.applyRealtime; doing this here covers electric updates that
- // are not present in the static schedule snapshot.
- joinDmuRealtimeTrips(realtimeTrips, schedule)
- val realtimeOnly = realtimeTrips.filter { it.tripId !in scheduledIds }
- // Once realtime has reported a departure at this station, the static
- // schedule is not allowed to invent service during the first hour.
- // Beyond that cancellation window, the cutoff follows only the
- // matching branch's latest realtime prediction.
- val latestRealtimeDepartureByBranch = realtimeTrips
- .mapNotNull { trip ->
- val point = trip.pointAt(origin) ?: return@mapNotNull null
- if (point.departureSource != PredictionSource.REALTIME
- || point.departureTime < feedTime
- ) {
- return@mapNotNull null
- }
- coverageKey(trip.line, trip.trainDestination) to point.departureTime
- }
- .groupBy({ it.first }, { it.second })
- .mapValues { (_, times) -> times.maxOrNull()!! }
- val hasForwardRealtimeAtStation = latestRealtimeDepartureByBranch.isNotEmpty()
- val coveredSchedule = if (!suppressScheduleCoveredByRealtime) {
- scheduledTrips
- } else {
- scheduledTrips.filter { trip ->
- if (trip.tripId in forcedScheduleTripIds) {
- true
- } else {
- val originPoint = trip.pointAt(origin)
- if (originPoint == null
- || originPoint.departureSource != PredictionSource.SCHEDULE
- || originPoint.departureTime < feedTime
- ) {
- true
- } else {
- val latest = latestRealtimeDepartureByBranch[
- coverageKey(trip.line, trip.trainDestination)
- ]
- val inCancellationWindow = originPoint.departureTime <=
- feedTime + REALTIME_CANCELLATION_WINDOW_MILLIS
- if (inCancellationWindow) {
- !hasForwardRealtimeAtStation
- } else {
- latest == null ||
- latest <= feedTime + REALTIME_CANCELLATION_WINDOW_MILLIS ||
- originPoint.departureTime > latest
- }
- }
- }
- }
- }
- return coveredSchedule + realtimeOnly.filter {
- it.line != Line.YELLOW_DMU
- }
- }
-
- private fun joinDmuRealtimeTrips(
- realtimeTrips: MutableList,
- schedule: Schedule,
- ) {
- val electricTrips = realtimeTrips.filter { trip ->
- trip.line == Line.YELLOW
- && !trip.canceled
- && !isDmuTripId(trip.tripId)
- && !trip.tripId.isNullOrEmpty()
- }
- val usedElectricTrips = mutableSetOf()
- realtimeTrips.filter { it.line == Line.YELLOW_DMU }.forEach { dmu ->
- val direction = terminalDirection(dmu)
- val terminal = terminalPoint(dmu, direction) ?: return@forEach
- val match = electricTrips
- .filter { candidate ->
- candidate !in usedElectricTrips
- && (direction == null || candidate.direction == null
- || candidate.direction == direction)
- }
- .mapNotNull { candidate ->
- terminalMatchDelta(candidate, terminal.station, terminal.time, direction, schedule)
- ?.let { candidate to it }
- }
- .filter { (_, delta) -> delta <= DMU_MATCH_MAX_MILLIS }
- .minByOrNull { (_, delta) -> delta }
- ?.first
- if (match != null) {
- usedElectricTrips += match
- mergeRealtimeTrip(match, dmu)
- }
- }
- }
-
- private fun terminalDirection(trip: TripSnapshot): String? =
- (trip.platform ?: trip.feedPlatform)?.let {
- when (it) {
- "1" -> "n"
- "2" -> "s"
- else -> null
- }
- }
-
- private fun terminalPoint(
- trip: TripSnapshot,
- direction: String?,
- ): TerminalPoint? {
- val station = when (direction) {
- "n" -> Station.PCTR
- "s" -> Station.ANTC
- else -> null
- }
- val point = station?.let { trip.pointAt(it) }
- ?: trip.pointAt(Station.ANTC)
- ?: trip.pointAt(Station.PCTR)
- ?: return null
- val time = point.departureTime.takeIf { it > 0L }
- ?: point.arrivalTime.takeIf { it > 0L }
- ?: return null
- return TerminalPoint(point.station, time)
- }
-
- private fun terminalMatchDelta(
- candidate: TripSnapshot,
- terminalStation: Station,
- terminalTime: Long,
- direction: String?,
- schedule: Schedule,
- ): Long? {
- val direct = candidate.pointAt(terminalStation)?.let { point ->
- val time = point.departureTime.takeIf { it > 0L }
- ?: point.arrivalTime.takeIf { it > 0L }
- time?.let { kotlin.math.abs(it - terminalTime) }
- }
- if (direct != null) return direct
-
- val pitt = candidate.pointAt(Station.PITT) ?: return null
- val pittTime = pitt.departureTime.takeIf { it > 0L }
- ?: pitt.arrivalTime.takeIf { it > 0L }
- ?: return null
- val travel = travelTimeBetween(Station.PITT, terminalStation, direction, schedule)
- ?: return null
- val projected = if (direction == "n") pittTime - travel else pittTime + travel
- return kotlin.math.abs(projected - terminalTime)
- }
-
- private fun travelTimeBetween(
- from: Station,
- to: Station,
- direction: String?,
- schedule: Schedule,
- ): Long? {
- val pattern = bartGtfsNetwork.routePatternsForLine(Line.YELLOW)
- .firstOrNull { direction == null || it.direction == null || it.direction == direction }
- ?: return null
- val fromIndex = pattern.stations.indexOf(from)
- val toIndex = pattern.stations.indexOf(to)
- if (fromIndex < 0 || toIndex < 0 || fromIndex == toIndex) return null
- val step = if (toIndex > fromIndex) 1 else -1
- var total = 0L
- var index = fromIndex
- while (index != toIndex) {
- val next = index + step
- total += schedule.nominalTravelTimeMillis(
- pattern.stations[index], pattern.stations[next]
- ) ?: return null
- index = next
- }
- return total
- }
-
- private fun isDmuTripId(tripId: String?): Boolean =
- tripId?.toIntOrNull()?.let { it in 600..799 } == true
-
- private data class TerminalPoint(val station: Station, val time: Long)
-
- private fun coverageKey(line: Line, destination: Station?): CoverageKey = CoverageKey(
- when (line) {
- Line.YELLOW_LATE_NIGHT -> Line.YELLOW
- else -> line
- },
- if (line in setOf(Line.YELLOW, Line.YELLOW_LATE_NIGHT)
- && destination in setOf(Station.MLBR, Station.SFIA)
- ) {
- Station.SFIA
- } else {
- destination
- },
- )
-
- private data class CoverageKey(
- val line: Line,
- val destination: Station?,
- )
-
- private fun correctedSchedule(
- feedIndex: GtfsRealtimeFeedIndex,
- feedTime: Long,
- ): Schedule = Schedule.fromStatic(
- bartGtfsNetwork,
- feedTime,
- Line.values().toSet(),
- ).applyRealtime(feedIndex)
-
- private fun snapshotFromSchedule(trip: Schedule.Trip): TripSnapshot {
- val result = TripSnapshot(
- trip.key.tripId,
- trip.line,
- trip.direction,
- )
- result.trainDestination = trip.trainDestination
- result.platform = trip.stopAt(origin)?.platform
- result.feedPlatform = trip.stopAt(Station.PITT)?.platform
- result.canceled = trip.canceled
- trip.stops.forEachIndexed { index, stop ->
- result.points += StopTimePoint(
- stop.station,
- index,
- stop.departureTime,
- stop.arrivalTime,
- stop.scheduledDepartureTime,
- stop.scheduledArrivalTime,
- stop.departureSource,
- stop.arrivalSource,
- stop.platform,
- )
- }
- result.lastOrder = trip.stops.lastIndex
- return result
- }
-
- private fun mergeRealtimeTrip(target: TripSnapshot, realtime: TripSnapshot) {
- target.platform = realtime.platform ?: target.platform
- target.canceled = target.canceled || realtime.canceled
- realtime.points.forEach { realtimePoint ->
- val existing = target.pointAt(realtimePoint.station)
- if (existing == null) {
- target.points += StopTimePoint(
- realtimePoint.station,
- stationOrder(target, realtimePoint.station) ?: realtimePoint.order,
- realtimePoint.departureTime,
- realtimePoint.arrivalTime,
- realtimePoint.scheduledDepartureTime,
- realtimePoint.scheduledArrivalTime,
- realtimePoint.departureSource,
- realtimePoint.arrivalSource,
- realtimePoint.platform,
- )
- } else {
- target.points.remove(existing)
- target.points += StopTimePoint(
- existing.station,
- existing.order,
- realtimePoint.departureTime,
- realtimePoint.arrivalTime,
- existing.scheduledDepartureTime,
- existing.scheduledArrivalTime,
- PredictionSource.REALTIME,
- PredictionSource.REALTIME,
- realtimePoint.platform ?: existing.platform,
- )
- }
- }
- target.points.sortBy { it.order }
- target.lastOrder = target.points.maxOfOrNull { it.order } ?: target.lastOrder
- val realtimeDestination = realtime.trainDestination
- val targetDestination = target.trainDestination
- if (realtimeDestination != null
- && (targetDestination == null
- || (stationOrder(target, realtimeDestination) ?: Int.MIN_VALUE)
- > (stationOrder(target, targetDestination) ?: Int.MIN_VALUE))
- ) {
- target.trainDestination = realtimeDestination
- }
- }
-
- private fun stationOrder(trip: TripSnapshot, station: Station): Int? =
- bartGtfsNetwork.routePatternsForLine(trip.line)
- .filter { trip.direction == null || it.direction == null || it.direction == trip.direction }
- .mapNotNull { pattern -> pattern.stations.indexOf(station).takeIf { it >= 0 } }
- .minOrNull()
-
- private fun findMatchingTrip(leg: TripLeg, trips: List): TripSnapshot? =
- trips.firstOrNull { trip ->
- !trip.canceled
- && trip.line == leg.line
- && trip.trainDestination == leg.trainDestination
- && trip.canServe(leg.origin, leg.destination)
- }
-
- private fun updateTripLeg(existing: TripLeg, trip: TripSnapshot): TripLeg {
- val originPoint = trip.pointAt(existing.origin)
- val destinationPoint = trip.pointAt(existing.destination)
- val departureTime = originPoint?.departureTime ?: existing.departureTime
- val arrivalTime = destinationPoint?.arrivalTime ?: existing.arrivalTime
- val stops = existing.stops.map { existingStop ->
- val stop = trip.pointAt(existingStop.station)
- if (stop == null) {
- existingStop
- } else {
- TripStop(
- existingStop.station,
- stop.arrivalTime,
- stop.departureTime,
- if (stop.scheduledArrivalTime > 0L) stop.scheduledArrivalTime
- else existingStop.scheduledArrivalTime,
- if (stop.scheduledDepartureTime > 0L) stop.scheduledDepartureTime
- else existingStop.scheduledDepartureTime,
- stop.arrivalSource,
- stop.departureSource,
- )
- }
- }
- return TripLeg(
- lineForLeg(
- trip.line,
- existing.origin,
- existing.destination,
- trip.trainDestination,
- ),
- existing.origin,
- existing.destination,
- trip.trainDestination,
- existing.tripId,
- departureTime,
- arrivalTime,
- stops,
- existing.minimumTransferSecondsAfter,
- existing.scheduledDepartureTime,
- existing.scheduledArrivalTime,
- originPoint?.departureSource ?: existing.departureSource,
- destinationPoint?.arrivalSource ?: existing.arrivalSource,
- originPoint?.platform ?: existing.platform,
- )
- }
-
- private fun addTripUpdate(
- departures: DepartureCollection,
- trip: TripSnapshot,
- allTrips: List,
- feedTime: Long,
- ) {
- if (destination != null && !ignoreDirection && !origin.ignoreRoutingDirection
- && !routes.any {
- it.trainDestinationIsApplicable(trip.trainDestination, trip.line)
- }
- ) {
- return
- }
- val originPoint = trip.pointAt(origin)
- if (originPoint == null || originPoint.departureTime <= 0) {
- return
- }
- if (originPoint.departureTime < feedTime - DEPARTURE_STALE_TOLERANCE_MILLIS) {
- return
- }
- val minutes = maxOf(0L, (originPoint.departureTime - feedTime) / 60000L).toInt()
- // A train can match several route alternatives because they share the
- // same first leg. Rank complete timed itineraries after validating
- // transfers, so a preferred station does not hide a much earlier
- // arrival.
- val candidates = routes.asSequence()
- .filter { it.trainDestinationIsApplicable(trip.trainDestination, trip.line) }
- .map { route -> route to buildTripLegs(route, trip, allTrips) }
- .filter { (route, legs) ->
- destination == null || (legs.size == route.lines.size
- && legs.lastOrNull()?.destination == destination)
- }
- .toList()
- val lateNightCandidates = candidates.filter { (route, _) ->
- Line.YELLOW_LATE_NIGHT in route.lines
- }
- if (lateNightCandidates.isNotEmpty()) {
- addSelectedCandidate(
- departures, lateNightCandidates, trip, originPoint, minutes
- )
- return
- }
- val preferredTopologyExists = routes
- .filter { it.trainDestinationIsApplicable(trip.trainDestination, trip.line) }
- .any { route ->
- route.transferStations.indices.none { index ->
- isAvoidedForRouteRanking(route, index)
- }
- }
- val nonAvoidedCandidates = candidates.filter { (route, _) ->
- route.transferStations.indices.none { index ->
- isAvoidedForRouteRanking(route, index)
- }
- }
- val marginSafeNonAvoided = nonAvoidedCandidates.filter { (route, legs) ->
- hasRequiredTransferMargins(route, legs)
- }
- val candidatesToChoose = if (marginSafeNonAvoided.isNotEmpty()) {
- marginSafeNonAvoided
- } else if (preferredTopologyExists) {
- emptyList()
- } else {
- candidates.filter { (route, legs) -> hasRequiredTransferMargins(route, legs) }
- }
- val earliestArrival = candidatesToChoose.mapNotNull { (_, legs) ->
- legs.lastOrNull()?.arrivalTime?.takeIf { it > 0L }
- }.minOrNull()
- candidatesToChoose.firstOrNull { (_, legs) ->
- val arrival = legs.lastOrNull()?.arrivalTime ?: 0L
- earliestArrival == null || arrival <= earliestArrival +
- TransferPolicy.MAX_PREFERRED_ARRIVAL_DELTA_MILLIS
- }
- ?.let { (route, legs) ->
- addSelectedCandidate(
- departures, listOf(route to legs), trip, originPoint, minutes
- )
- }
- }
-
- private fun addSelectedCandidate(
- departures: DepartureCollection,
- candidates: List>>,
- trip: TripSnapshot,
- originPoint: StopTimePoint,
- minutes: Int,
- ) {
- candidates.firstOrNull()?.let { (route, legs) ->
- val line = lineForDeparture(trip, legs)
- val departure = Departure.builder()
- .setOrigin(origin)
- .setTrainDestination(trip.trainDestination)
- .setLine(line)
- .setDirection(trip.direction)
- .setPlatform(trip.platform)
- .setCanceled(trip.canceled)
- .setTrainDestinationColorText(line.name)
- .setTrainDestinationColorHex(colorForLine(line))
- .setMinutes(minutes)
- .setMinEstimate(originPoint.departureTime - ESTIMATE_TOLERANCE_MILLIS)
- .setMaxEstimate(originPoint.departureTime + ESTIMATE_TOLERANCE_MILLIS)
- .setTripLegs(legs)
- .let { builder ->
- if (legs.isNotEmpty() && legs.last().hasArrivalTime()) {
- builder.setEstimatedTripTime(
- (legs.last().arrivalTime - originPoint.departureTime).toInt()
- )
- } else {
- builder
- }
- }
- .build()
- addDeparture(departures, departure, route)
- }
- }
-
- private fun isAvoidedForRouteRanking(route: Route, index: Int): Boolean {
- return transferPolicy.isAvoidedForRouteRanking(route, index)
- }
-
- private fun hasRequiredTransferMargins(
- route: Route,
- legs: List,
- ): Boolean = route.transferStations.indices.all { index ->
- val station = route.transferStations[index]
- if (!transferPolicy.isAvoidedStation(station)) {
- true
- } else {
- val arriving = legs.getOrNull(index)?.arrivalTime ?: 0L
- val departing = legs.getOrNull(index + 1)?.departureTime ?: 0L
- val minimum = legs.getOrNull(index)?.minimumTransferSecondsAfter ?: 0
- transferPolicy.hasExtraMargin(arriving, departing, minimum)
- }
- }
-
- private fun addDeparture(
- collection: DepartureCollection,
- departure: Departure,
- route: Route,
- ) {
- collection.unfiltered += departure
- collection.filtered += departure.copy(
- requiresTransfer = route.hasTransfer(),
- transferScheduled = Line.YELLOW_ORANGE_SCHEDULED_TRANSFER == route.directLine,
- )
- }
-
- private class DepartureCollection {
- val unfiltered = mutableListOf()
- val filtered = mutableListOf()
- }
-
- private fun parseTrip(
- tripUpdate: GtfsRealtime.TripUpdate,
- feedTime: Long
- ): TripSnapshot? {
- if (!tripUpdate.hasTrip()) {
- return null
- }
- val trip = tripUpdate.getTrip()
- var routeId = if (trip.hasRouteId() && trip.getRouteId().isNotEmpty()) {
- trip.getRouteId()
- } else {
- null
- }
- if (routeId.isNullOrEmpty()) {
- routeId = bartGtfsNetwork.routeIdForTrip(trip.getTripId())
- }
- val line = bartGtfsNetwork.lineForRouteId(routeId)
- ?: if (isAntiochShuttleTrip(tripUpdate)) Line.YELLOW_DMU else return null
-
- val result = TripSnapshot(
- tripId = trip.getTripId(),
- line = line,
- direction = bartGtfsNetwork.directionForRouteId(routeId),
- )
- val scheduledStations = bartGtfsNetwork.stationsForTrip(trip.getTripId())
- var updateIndex = 0
- for (update in tripUpdate.getStopTimeUpdateList()) {
- if (isSkipped(update)) {
- updateIndex++
- continue
- }
- val station = bartGtfsNetwork.stationForStopId(update.getStopId())
- if (result.feedPlatform == null) {
- result.feedPlatform = platformForStopId(update.getStopId())
- }
- val departure = departureTime(update)
- val arrival = arrivalTime(update)
- if (station != null && station != Station.SPCL && (departure > 0 || arrival > 0)) {
- val scheduledOrder = scheduledStations.indexOf(station)
- val point = StopTimePoint(
- station = station,
- order = if (scheduledOrder >= 0) {
- scheduledOrder
- } else {
- stopOrder(update, updateIndex)
- },
- departureTime = if (departure > 0) departure else arrival,
- arrivalTime = if (arrival > 0) arrival else departure,
- departureSource = PredictionSource.REALTIME,
- arrivalSource = PredictionSource.REALTIME,
- platform = platformForStopId(update.getStopId()),
- )
- result.points += point
- if (result.trainDestination == null || point.order > result.lastOrder) {
- result.trainDestination = station
- result.lastOrder = point.order
- }
- if (station == origin && result.platform == null) {
- result.platform = platformForStopId(update.getStopId())
- }
- }
- updateIndex++
- }
- if (scheduledStations.isNotEmpty()) {
- for ((index, station) in scheduledStations.withIndex()) {
- if (result.pointAt(station) == null) {
- result.points += StopTimePoint(
- station = station,
- order = index,
- departureTime = 0L,
- arrivalTime = 0L
- )
- }
- }
- result.points.sortBy { it.order }
- result.trainDestination = scheduledStations.last()
- result.lastOrder = scheduledStations.lastIndex
- }
- if (result.trainDestination == null) {
- return null
- }
- if (line == Line.YELLOW_DMU && result.pointAt(Station.PITT) == null) {
- if (result.feedPlatform == "1" && result.pointAt(Station.PCTR) != null) {
- result.trainDestination = Station.ANTC
- } else if (result.feedPlatform == "2"
- && result.pointAt(Station.PCTR) != null
- ) {
- result.trainDestination = Station.PITT
- }
- }
- result.canceled = trip.hasScheduleRelationship() &&
- trip.getScheduleRelationship() ==
- GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED
- if (result.pointAt(origin) == null && result.canceled) {
- // A canceled trip can still be displayed if BART supplies its
- // start time, matching the old ETD behavior.
- val start = scheduledStartTime(trip, feedTime)
- if (start > 0) {
- result.points += StopTimePoint(
- station = origin,
- order = Int.MIN_VALUE,
- departureTime = start,
- arrivalTime = start
- )
- }
- }
- return result
- }
-
- private fun buildTripLegs(
- route: Route,
- firstTrip: TripSnapshot,
- allTrips: List
- ): List {
- // A station-only lookup has no requested passenger destination, but
- // the selected train still gives us the endpoint to display. Treat it
- // as a single-leg trip, just like a lookup made directly to that
- // endpoint.
- val tripDestination = destination ?: firstTrip.trainDestination ?: return emptyList()
- val lines = route.lines
- if (lines.isEmpty()) {
- return emptyList()
- }
- val transfers = route.transferStations
- val result = mutableListOf()
- var currentTrip = firstTrip
- var legOrigin = origin
- for (i in lines.indices) {
- val legDestination = if (i < transfers.size) transfers[i] else tripDestination
- if (i > 0) {
- val arrivingLeg = result[i - 1]
- val connectingTrip = findConnectingTrip(
- lines[i],
- legOrigin,
- legDestination,
- arrivingLeg,
- allTrips
- )
- if (connectingTrip == null) {
- if (isUnscheduledTerminalLeg(lines[i], legOrigin, legDestination)) {
- result += unscheduledTerminalLeg(
- lines[i], legOrigin, legDestination
- )
- legOrigin = legDestination
- continue
- }
- break
- }
- currentTrip = connectingTrip
- }
- val departure = currentTrip.pointAt(legOrigin) ?: break
- val arrival = currentTrip.pointAt(legDestination)
- val stops = currentTrip.pointsBetween(legOrigin, legDestination).map {
- tripStop(it)
- }
- result += TripLeg(
- lineForLeg(
- currentTrip.line,
- legOrigin,
- legDestination,
- currentTrip.trainDestination,
- ),
- legOrigin,
- legDestination,
- currentTrip.trainDestination,
- currentTrip.tripId,
- departure.departureTime,
- arrival?.arrivalTime ?: 0L,
- stops,
- minimumTransferSecondsAfter(route, i, legDestination, currentTrip.line),
- departure.scheduledDepartureTime,
- arrival?.scheduledArrivalTime ?: 0L,
- departure.departureSource,
- arrival?.arrivalSource ?: PredictionSource.UNKNOWN,
- departure.platform,
- )
- legOrigin = legDestination
- }
- return result
- }
-
- private fun findConnectingTrip(
- line: Line,
- origin: Station,
- destination: Station,
- arrivingLeg: TripLeg,
- allTrips: List
- ): TripSnapshot? {
- var best: TripSnapshot? = null
- for (trip in allTrips) {
- if (trip.canceled || trip.line != line || !trip.canServe(origin, destination)) {
- continue
- }
- val departure = trip.pointAt(origin)
- if (departure == null || !transferPolicy.canTransfer(
- arrivingLeg.arrivalTime,
- departure.departureTime,
- origin,
- arrivingLeg.line,
- line,
- )
- ) {
- continue
- }
- val bestDeparture = best?.pointAt(origin)?.departureTime
- if (best == null || departure.departureTime < bestDeparture!!) {
- best = trip
- }
- }
- return best
- }
-
- private fun minimumTransferSecondsAfter(
- route: Route,
- legIndex: Int,
- transferStation: Station,
- fromLine: Line
- ): Int {
- if (legIndex + 1 >= route.lines.size) {
- return 0
- }
- return bartGtfsNetwork.minimumTransferSeconds(
- transferStation, fromLine, route.lines[legIndex + 1]
- ).coerceAtLeast(0)
- }
-
- private class StopTimePoint(
- val station: Station,
- val order: Int,
- val departureTime: Long,
- val arrivalTime: Long,
- val scheduledDepartureTime: Long = 0L,
- val scheduledArrivalTime: Long = 0L,
- val departureSource: PredictionSource = PredictionSource.UNKNOWN,
- val arrivalSource: PredictionSource = PredictionSource.UNKNOWN,
- var platform: String? = null,
- )
-
- private class TripSnapshot(
- val tripId: String?,
- val line: Line,
- val direction: String?
- ) {
- var trainDestination: Station? = null
- var platform: String? = null
- var feedPlatform: String? = null
- var canceled = false
- var lastOrder = Int.MIN_VALUE
- val points = mutableListOf()
-
- fun addPoint(point: StopTimePoint) {
- points.removeAll { it.station == point.station }
- points += point
- lastOrder = maxOf(lastOrder, point.order)
- }
-
- fun pointAt(station: Station?): StopTimePoint? =
- points.firstOrNull { it.station == station }
-
- fun canServe(origin: Station?, destination: Station?): Boolean {
- val start = pointAt(origin)
- val end = pointAt(destination)
- return start != null && end != null && end.order > start.order
- }
-
- fun pointsBetween(origin: Station?, destination: Station?): List {
- val start = pointAt(origin)
- val end = pointAt(destination)
- if (start == null || end == null) {
- return emptyList()
- }
- return points.filter { it.order in start.order..end.order }
- .sortedBy { it.order }
- }
- }
-
- private fun tripStop(point: StopTimePoint): TripStop = TripStop(
- point.station,
- point.arrivalTime,
- point.departureTime,
- point.scheduledArrivalTime,
- point.scheduledDepartureTime,
- point.arrivalSource,
- point.departureSource,
- )
-
- private fun isAntiochShuttleTrip(
- tripUpdate: GtfsRealtime.TripUpdate
- ): Boolean = tripUpdate.getStopTimeUpdateList().any { update ->
- bartGtfsNetwork.stationForStopId(update.getStopId()) == Station.PITT
- || bartGtfsNetwork.stationForStopId(update.getStopId()) == Station.PCTR
- || bartGtfsNetwork.stationForStopId(update.getStopId()) == Station.ANTC
- }
-
- private fun lineForLeg(
- line: Line,
- legOrigin: Station?,
- legDestination: Station?,
- trainDestination: Station?,
- ): Line = if (line == Line.YELLOW && (
- (legOrigin == Station.SFIA && legDestination == Station.MLBR)
- || (destination == null && trainDestination == Station.MLBR)
- || origin == Station.MLBR
- )) {
- Line.YELLOW_LATE_NIGHT
- } else {
- line
- }
-
- private fun lineForDeparture(trip: TripSnapshot, legs: List): Line =
- if (destination == null && trip.line == Line.YELLOW
- && trip.trainDestination == Station.MLBR
- ) {
- Line.YELLOW_LATE_NIGHT
- } else {
- legs.firstOrNull()?.line ?: trip.line
- }
-
- private fun feedTime(feed: GtfsRealtime.FeedMessage): Long =
- if (feed.hasHeader() && feed.getHeader().hasTimestamp()
- && feed.getHeader().getTimestamp() > 0
- ) {
- feed.getHeader().getTimestamp() * 1000L
- } else {
- timeSource.nowMillis()
- }
-
- companion object {
- private const val ESTIMATE_TOLERANCE_MILLIS = 30000L
- private const val DMU_MATCH_MAX_MILLIS = 20L * 60L * 1000L
- private const val REALTIME_CANCELLATION_WINDOW_MILLIS = 60L * 60L * 1000L
- private const val DEPARTURE_STALE_TOLERANCE_MILLIS = 45 * 1000L
- private val PACIFIC_ZONE = ZoneId.of("America/Los_Angeles")
-
- private fun departureTime(update: GtfsRealtime.TripUpdate.StopTimeUpdate): Long {
- if (update.hasDeparture() && update.getDeparture().hasTime()) {
- return update.getDeparture().getTime() * 1000L
- }
- if (update.hasArrival() && update.getArrival().hasTime()) {
- return update.getArrival().getTime() * 1000L
- }
- return 0L
- }
-
- private fun arrivalTime(update: GtfsRealtime.TripUpdate.StopTimeUpdate): Long {
- if (update.hasArrival() && update.getArrival().hasTime()) {
- return update.getArrival().getTime() * 1000L
- }
- if (update.hasDeparture() && update.getDeparture().hasTime()) {
- return update.getDeparture().getTime() * 1000L
- }
- return 0L
- }
-
- private fun scheduledStartTime(
- trip: GtfsRealtime.TripDescriptor,
- feedTime: Long
- ): Long {
- if (!trip.hasStartTime()) {
- return 0L
- }
- val startDate = if (trip.hasStartDate()) {
- trip.getStartDate()
- } else {
- DateTimeFormatter.BASIC_ISO_DATE.format(
- Instant.ofEpochMilli(feedTime).atZone(PACIFIC_ZONE).toLocalDate()
- )
- }
- val timeParts = trip.getStartTime().split(":")
- if (timeParts.size != 3) {
- return 0L
- }
- return try {
- val hour = timeParts[0].toInt()
- val minute = timeParts[1].toInt()
- val second = timeParts[2].toInt()
- val date = LocalDate.parse(startDate, DateTimeFormatter.BASIC_ISO_DATE)
- date.atStartOfDay(PACIFIC_ZONE)
- .plusHours(hour.toLong())
- .plusMinutes(minute.toLong())
- .plusSeconds(second.toLong())
- .toInstant()
- .toEpochMilli()
- } catch (_: NumberFormatException) {
- 0L
- } catch (_: DateTimeException) {
- 0L
- }
- }
-
- private fun isSkipped(update: GtfsRealtime.TripUpdate.StopTimeUpdate): Boolean =
- update.hasScheduleRelationship() &&
- update.getScheduleRelationship() ==
- GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED
-
- private fun stopOrder(
- update: GtfsRealtime.TripUpdate.StopTimeUpdate,
- listIndex: Int
- ): Int {
- // BART currently omits stop_sequence from its GTFS-RT feed. The feed
- // order is still the trip order, so use it when no sequence exists.
- return if (update.hasStopSequence()) update.getStopSequence() else listIndex
- }
-
- private fun platformForStopId(stopId: String?): String? {
- if (stopId == null) {
- return null
- }
- val separator = stopId.lastIndexOf('-')
- return if (separator >= 0 && separator + 1 < stopId.length) {
- stopId.substring(separator + 1)
- } else {
- null
- }
- }
-
- private fun colorForLine(line: Line): String = when (line) {
- Line.RED -> "#ffff0000"
- Line.ORANGE -> "#ffff9933"
- Line.YELLOW, Line.YELLOW_LATE_NIGHT, Line.YELLOW_DMU -> "#ffffff33"
- Line.GREEN -> "#ff339933"
- Line.BLUE -> "#ff0099cc"
- else -> "#ffffffff"
- }
- }
-}
diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeFeedIndex.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeFeedIndex.kt
deleted file mode 100644
index a9f4b6f..0000000
--- a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsRealtimeFeedIndex.kt
+++ /dev/null
@@ -1,109 +0,0 @@
-package `in`.izyum.bart.networktasks
-
-import com.google.transit.realtime.GtfsRealtime
-import java.util.ArrayList
-import java.util.Collections
-import java.util.LinkedHashMap
-
-/** Immutable one-pass index of the entities in a GTFS realtime feed. */
-class GtfsRealtimeFeedIndex private constructor(
- entities: Iterable
-) {
- val tripUpdateEntities: List
- val tripUpdatesById: Map
- val alertEntities: List
- val alertsById: Map
-
- init {
- val tripEntities = mutableListOf()
- val trips = LinkedHashMap()
- val entitiesWithAlerts = mutableListOf()
- val alerts = LinkedHashMap()
- for (entity in entities) {
- if (entity.hasTripUpdate()) {
- tripEntities += entity
- val tripUpdate = entity.tripUpdate
- val trip = if (tripUpdate.hasTrip()) tripUpdate.trip else null
- if (trip != null && trip.hasTripId() && trip.tripId.isNotEmpty()
- && !isDmuTripId(trip.tripId)
- ) {
- val tripId = trip.tripId
- val existing = trips[tripId]
- if (existing == null || shouldReplaceTrip(existing, entity)) {
- trips[tripId] = entity
- }
- }
- }
- if (entity.hasAlert()) {
- entitiesWithAlerts += entity
- if (entity.hasId()) {
- alerts[entity.id] = entity
- }
- }
- }
- tripUpdateEntities = immutableList(tripEntities)
- tripUpdatesById = immutableMap(trips)
- alertEntities = immutableList(entitiesWithAlerts)
- alertsById = immutableMap(alerts)
- }
-
- companion object {
- @JvmStatic
- fun from(feed: GtfsRealtime.FeedMessage?): GtfsRealtimeFeedIndex =
- GtfsRealtimeFeedIndex(requireNotNull(feed) { "feed" }.entityList)
-
- /** Adds fallback entities, replacing explicitly stale live trip updates. */
- @JvmStatic
- fun merge(
- primary: GtfsRealtimeFeedIndex,
- fallback: GtfsRealtimeFeedIndex,
- replaceTripIds: Set = emptySet()
- ): GtfsRealtimeFeedIndex {
- val primaryTripIds = primary.tripUpdatesById.keys
- return GtfsRealtimeFeedIndex(
- primary.tripUpdateEntities.filterNot { entity ->
- tripIdOf(entity) in replaceTripIds
- } + fallback.tripUpdateEntities.filter { entity ->
- val tripId = tripIdOf(entity)
- tripId in replaceTripIds || tripId == null || tripId !in primaryTripIds
- }
- )
- }
-
- private fun tripIdOf(entity: GtfsRealtime.FeedEntity): String? =
- if (entity.hasTripUpdate() && entity.tripUpdate.hasTrip()
- && entity.tripUpdate.trip.hasTripId()
- ) {
- entity.tripUpdate.trip.tripId
- } else {
- null
- }
-
- private fun isDmuTripId(tripId: String): Boolean =
- tripId.toIntOrNull()?.let { it in 600..799 } == true
-
- private fun shouldReplaceTrip(
- existing: GtfsRealtime.FeedEntity,
- candidate: GtfsRealtime.FeedEntity,
- ): Boolean {
- val existingUpdate = existing.tripUpdate
- val candidateUpdate = candidate.tripUpdate
- val existingCanceled = existingUpdate.hasTrip()
- && existingUpdate.trip.hasScheduleRelationship()
- && existingUpdate.trip.scheduleRelationship ==
- GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED
- val candidateCanceled = candidateUpdate.hasTrip()
- && candidateUpdate.trip.hasScheduleRelationship()
- && candidateUpdate.trip.scheduleRelationship ==
- GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED
- if (candidateCanceled != existingCanceled) return candidateCanceled
- return candidateUpdate.stopTimeUpdateCount >= existingUpdate.stopTimeUpdateCount
- }
- }
-}
-
-private fun immutableList(values: Collection): List =
- Collections.unmodifiableList(ArrayList(values))
-
-private fun immutableMap(values: Map): Map =
- Collections.unmodifiableMap(LinkedHashMap(values))
diff --git a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt
index cd0bc57..1c4c73f 100644
--- a/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt
+++ b/app/src/main/kotlin/in/izyum/bart/networktasks/GtfsStaticData.kt
@@ -16,6 +16,7 @@ import `in`.izyum.bart.transit.gtfs.GtfsScheduledTrip
import `in`.izyum.bart.transit.gtfs.GtfsStop
import `in`.izyum.bart.transit.gtfs.GtfsTransfer
import `in`.izyum.bart.transit.gtfs.GtfsTrip
+import `in`.izyum.bart.transit.BartDataPolicy
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.ByteArrayOutputStream
@@ -27,7 +28,6 @@ import java.io.IOException
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.time.LocalDate
-import java.time.ZoneId
import java.util.Collections
import java.util.HashMap
import java.util.Locale
@@ -378,7 +378,7 @@ class GtfsStaticData @JvmOverloads constructor(
private const val PREFS_NAME = "gtfs_static_schedule"
private const val LAST_ATTEMPT = "last_attempt"
private const val LAST_SUCCESS = "last_success"
- private val PACIFIC_ZONE = ZoneId.of("America/Los_Angeles")
+ private val PACIFIC_ZONE = BartDataPolicy.PACIFIC_ZONE
private val CLIENT: OkHttpClient = NetworkUtils.makeHttpClient()
@Throws(IOException::class)
diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmPolicy.kt b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmPolicy.kt
index 9417902..b436b90 100644
--- a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmPolicy.kt
+++ b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmPolicy.kt
@@ -1,6 +1,6 @@
package `in`.izyum.bart.platform
-import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
/** Deterministic alarm decisions shared by Android scheduling and tests. */
object DepartureAlarmPolicy {
@@ -14,20 +14,8 @@ object DepartureAlarmPolicy {
fun alarmTime(arrivalEstimateMillis: Long, leadTimeMinutes: Int): Long =
arrivalEstimateMillis - leadTimeMinutes * 60_000L
- /** Uses the same pessimistic initial-station arrival time shown by the UI. */
- fun alarmTime(departure: Departure, leadTimeMinutes: Int): Long =
- alarmTime(departure.getInitialArrivalTime(pessimistic = true), leadTimeMinutes)
-
- fun secondsUntilAlarm(arrivalEstimateMillis: Long,
- leadTimeMinutes: Int,
- nowMillis: Long): Int =
- ((alarmTime(arrivalEstimateMillis, leadTimeMinutes) - nowMillis) / 1_000L)
- .toInt()
-
- fun secondsUntilAlarm(departure: Departure,
- leadTimeMinutes: Int,
- nowMillis: Long): Int =
- ((alarmTime(departure, leadTimeMinutes) - nowMillis) / 1_000L).toInt()
+ fun alarmTime(itinerary: Itinerary, leadTimeMinutes: Int): Long =
+ alarmTime(itinerary.getInitialArrivalTime(pessimistic = true), leadTimeMinutes)
/**
* Returns the delay before the next background refresh. Refreshes happen
diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt
index 5865c38..d210d15 100644
--- a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt
+++ b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmScheduler.kt
@@ -12,19 +12,16 @@ import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale
import `in`.izyum.bart.activities.RoutesListActivity
-import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.Station
import `in`.izyum.bart.model.SystemTimeSource
import `in`.izyum.bart.model.TimeSource
import `in`.izyum.bart.receivers.AlarmBroadcastReceiver
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
-import kotlinx.coroutines.flow.asStateFlow
/** Owns Android alarm scheduling for one followed departure. */
class DepartureAlarmScheduler @JvmOverloads constructor(
context: Context,
- private val departure: Departure,
+ private val itinerary: Itinerary,
private val timeSource: TimeSource = SystemTimeSource
) :
AutoCloseable {
@@ -35,6 +32,8 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
const val LEAD_TIME_SUFFIX = ".leadTimeMinutes"
const val PENDING_SUFFIX = ".pending"
const val TRACKING_SUFFIX = ".tracking"
+ const val LAST_USED_SUFFIX = ".lastUsedMillis"
+ const val MAX_PERSISTED_ALARM_STATES = 16
}
private val applicationContext = context.applicationContext
@@ -42,51 +41,52 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
.getSystemService(Context.ALARM_SERVICE) as? AlarmManager
private val preferences = applicationContext.getSharedPreferences(
ALARM_PREFS, Context.MODE_PRIVATE)
- private val stateKey = buildStateKey(departure)
- private val _state = MutableStateFlow(
- DepartureAlarmState(
- leadTimeMinutes = preferences.getInt(
- stateKey + LEAD_TIME_SUFFIX, 0),
- pending = preferences.getBoolean(stateKey + PENDING_SUFFIX, false),
- )
- )
- val state: StateFlow = _state.asStateFlow()
-
+ private val stateKey = buildStateKey(itinerary)
+ private var storedLeadTimeMinutes = preferences.getInt(
+ stateKey + LEAD_TIME_SUFFIX, 0)
+ private var pendingAlarm = preferences.getBoolean(
+ stateKey + PENDING_SUFFIX, false)
init {
+ prunePersistedStates()
val nowMillis = timeSource.nowMillis()
if (DepartureAlarmPolicy.shouldRestore(isPending,
- departure.hasInitialDeparturePassed(nowMillis, pessimistic = true),
- departure.hasExpired(nowMillis))) {
- schedule()
+ itinerary.hasInitialDeparturePassed(nowMillis, pessimistic = true),
+ itinerary.hasExpired(nowMillis))) {
+ if (!schedule()) {
+ updateState(leadTimeMinutes, false)
+ }
} else if (isPending) {
cancel()
}
}
val leadTimeMinutes: Int
- get() = _state.value.leadTimeMinutes
+ get() = storedLeadTimeMinutes
val isPending: Boolean
- get() = _state.value.pending
+ get() = pendingAlarm
val isTracking: Boolean
get() = preferences.getBoolean(stateKey + TRACKING_SUFFIX, false)
- val secondsUntilAlarm: Int
- get() = DepartureAlarmPolicy.secondsUntilAlarm(
- departure, leadTimeMinutes, timeSource.nowMillis())
-
fun setUp(leadTimeMinutes: Int) {
require(leadTimeMinutes >= 0) {
"leadTimeMinutes must be non-negative"
}
- updateState(leadTimeMinutes, true)
+ // Keep the requested lead time, but do not expose the alarm as pending
+ // until Android accepts the alarm.
+ updateState(leadTimeMinutes, false)
startTracking()
- schedule()
+ if (schedule()) {
+ updateState(leadTimeMinutes, true)
+ }
}
fun startTracking() {
- preferences.edit { putBoolean(stateKey + TRACKING_SUFFIX, true) }
+ preferences.edit {
+ putBoolean(stateKey + TRACKING_SUFFIX, true)
+ putLong(stateKey + LAST_USED_SUFFIX, timeSource.nowMillis())
+ }
}
fun cancel() {
@@ -96,7 +96,10 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
}
fun stopTracking() {
- preferences.edit { putBoolean(stateKey + TRACKING_SUFFIX, false) }
+ preferences.edit {
+ putBoolean(stateKey + TRACKING_SUFFIX, false)
+ putLong(stateKey + LAST_USED_SUFFIX, timeSource.nowMillis())
+ }
}
fun notifyAlarmHasBeenHandled() {
@@ -106,7 +109,9 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
}
fun rescheduleIfPending() {
- if (isPending) schedule()
+ if (isPending && !schedule()) {
+ updateState(leadTimeMinutes, false)
+ }
}
/**
@@ -140,21 +145,22 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
}
private fun alarmClockTime(): Long = DepartureAlarmPolicy.alarmTime(
- departure, leadTimeMinutes)
+ itinerary, leadTimeMinutes)
- private fun schedule() {
+ private fun schedule(): Boolean {
val manager = alarmManager
if (manager == null) {
Log.w(TAG,
"No alarm manager available, so alarm will not be scheduled")
- return
+ return false
}
val alarmTime = alarmClockTime()
val intent = alarmIntent()
if (!ExactAlarmPermission.isGranted(applicationContext)) {
Log.w(TAG, "Exact alarm permission is unavailable")
- return
+ manager.cancel(intent)
+ return false
}
try {
manager.setAlarmClock(
@@ -163,6 +169,8 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
)
} catch (exception: SecurityException) {
Log.w(TAG, "Could not schedule departure alarm", exception)
+ manager.cancel(intent)
+ return false
}
val alarmText = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)
@@ -170,13 +178,36 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
.withZone(ZoneId.systemDefault())
.format(Instant.ofEpochMilli(alarmTime))
Log.v(TAG, "Scheduling alarm for $alarmText")
+ return true
}
private fun updateState(leadTimeMinutes: Int, pending: Boolean) {
- _state.value = DepartureAlarmState(leadTimeMinutes, pending)
+ storedLeadTimeMinutes = leadTimeMinutes
+ pendingAlarm = pending
preferences.edit {
putInt(stateKey + LEAD_TIME_SUFFIX, leadTimeMinutes)
putBoolean(stateKey + PENDING_SUFFIX, pending)
+ putLong(stateKey + LAST_USED_SUFFIX, timeSource.nowMillis())
+ }
+ }
+
+ private fun prunePersistedStates() {
+ val bases = preferences.all.keys
+ .filter { it.startsWith("alarm.") && it.endsWith(PENDING_SUFFIX) }
+ .map { it.removeSuffix(PENDING_SUFFIX) }
+ .filter { it != stateKey }
+ .distinct()
+ val excess = bases.size - (MAX_PERSISTED_ALARM_STATES - 1)
+ if (excess <= 0) return
+ bases.sortedBy { base ->
+ preferences.getLong(base + LAST_USED_SUFFIX, Long.MIN_VALUE)
+ }.take(excess).forEach { base ->
+ preferences.edit {
+ remove(base + LEAD_TIME_SUFFIX)
+ remove(base + PENDING_SUFFIX)
+ remove(base + TRACKING_SUFFIX)
+ remove(base + LAST_USED_SUFFIX)
+ }
}
}
@@ -189,13 +220,13 @@ class DepartureAlarmScheduler @JvmOverloads constructor(
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
- private fun buildStateKey(departure: Departure): String = buildString {
+ private fun buildStateKey(itinerary: Itinerary): String = buildString {
append("alarm.")
- appendStation(this, departure.origin)
- appendStation(this, departure.trainDestination)
- append('|').append(departure.line)
- append('|').append(departure.direction)
- append('|').append(departure.platform)
+ appendStation(this, itinerary.origin)
+ appendStation(this, itinerary.trainDestination)
+ append('|').append(itinerary.line)
+ append('|').append(itinerary.direction)
+ append('|').append(itinerary.platform)
}
private fun appendStation(builder: StringBuilder, station: Station?) {
diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmState.kt b/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmState.kt
deleted file mode 100644
index 2eeddb6..0000000
--- a/app/src/main/kotlin/in/izyum/bart/platform/DepartureAlarmState.kt
+++ /dev/null
@@ -1,7 +0,0 @@
-package `in`.izyum.bart.platform
-
-/** Immutable alarm state exposed to lifecycle-aware consumers. */
-data class DepartureAlarmState(
- val leadTimeMinutes: Int = 0,
- val pending: Boolean = false,
-)
diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingAlarm.kt b/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingAlarm.kt
index 6590c87..e917c11 100644
--- a/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingAlarm.kt
+++ b/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingAlarm.kt
@@ -12,7 +12,8 @@ import `in`.izyum.bart.receivers.DeparturePollingReceiver
/** Schedules one-shot alarm-clock wakeups for background followed-trip refreshes. */
object DeparturePollingAlarm {
private const val TAG = "DeparturePollingAlarm"
- private const val REQUEST_CODE = 1241
+ private const val POLL_REQUEST_CODE = 1241
+ private const val SHOW_ACTIVITY_REQUEST_CODE = 1243
private const val ACTION_POLL = "in.izyum.bart.action.POLL_DEPARTURE"
fun schedule(context: Context, delayMillis: Long = 0L) {
@@ -47,14 +48,14 @@ object DeparturePollingAlarm {
fun refresh(context: Context, repository: FollowedTripRepository) {
val applicationContext = context.applicationContext
- val departure = repository.peekFollowedDeparture()
+ val itinerary = repository.peekFollowedItinerary()
if (repository.backgroundPollingNeeded.value &&
- departure != null &&
+ itinerary != null &&
ExactAlarmPermission.isGranted(applicationContext)
) {
schedule(
applicationContext,
- repository.backgroundPollingDelayMillis(departure),
+ repository.backgroundPollingDelayMillis(itinerary),
)
} else {
cancel(applicationContext)
@@ -63,14 +64,14 @@ object DeparturePollingAlarm {
private fun pendingIntent(context: Context): PendingIntent = PendingIntent.getBroadcast(
context,
- REQUEST_CODE,
+ POLL_REQUEST_CODE,
Intent(context, DeparturePollingReceiver::class.java).setAction(ACTION_POLL),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
private fun showIntent(context: Context): PendingIntent = PendingIntent.getActivity(
context,
- REQUEST_CODE,
+ SHOW_ACTIVITY_REQUEST_CODE,
Intent(context, RoutesListActivity::class.java).addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP,
),
diff --git a/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingProcessor.kt b/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingProcessor.kt
index 0b3c74c..ea3eb5a 100644
--- a/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingProcessor.kt
+++ b/app/src/main/kotlin/in/izyum/bart/platform/DeparturePollingProcessor.kt
@@ -2,13 +2,12 @@ package `in`.izyum.bart.platform
import android.content.Context
import `in`.izyum.bart.BartRunnerApplication
-import `in`.izyum.bart.model.Departure
-import `in`.izyum.bart.backend.RouteDepartureProjection
+import `in`.izyum.bart.backend.FollowedItineraryAlarmProjection
import `in`.izyum.bart.receivers.AlarmBroadcastReceiver
/** Performs one background departure refresh and arranges the next alarm. */
object DeparturePollingProcessor {
- fun process(context: Context) {
+ suspend fun process(context: Context) {
val applicationContext = context.applicationContext
val app = applicationContext as BartRunnerApplication
val repository = app.followedTripRepository
@@ -17,7 +16,7 @@ object DeparturePollingProcessor {
return
}
- val current = repository.getFollowedDeparture()
+ val current = repository.getFollowedItinerary()
if (current == null || !repository.backgroundPollingNeeded.value) {
stop(applicationContext)
return
@@ -27,34 +26,25 @@ object DeparturePollingProcessor {
// process kill, or receiver deadline must not strand the follow-up.
DeparturePollingAlarm.refresh(applicationContext, repository)
- app.transitRepository.refreshTripUpdatesNow()
+ app.transitRepository.refreshTripUpdates()
val snapshot = app.transitRepository.getLatestSnapshot()
- val route = current.getStationPair()
- if (snapshot != null && route != null) {
- val departures = RouteDepartureProjection(
- route, app.bartGtfsNetworkSupplier,
- ).project(snapshot).getDepartures()
- departures.firstOrNull { it.identity == current.identity }?.let { updated ->
- if (current.getMeanSecondsLeft(app.timeSource) !=
- updated.getMeanSecondsLeft(app.timeSource) ||
- current.getUncertaintySeconds() != updated.getUncertaintySeconds()
- ) {
- repository.setFollowedDeparture(
- Departure.merge(current, updated, false, app.timeSource),
- refreshBackgroundWork = false,
- )
- }
+ if (snapshot != null) {
+ val updated = FollowedItineraryAlarmProjection(
+ app.bartGtfsNetworkSupplier,
+ ).project(snapshot, current)
+ if (updated != current) {
+ repository.setFollowedItinerary(updated, refreshBackgroundWork = false)
}
}
- val departure = repository.getFollowedDeparture()
- if (departure == null ||
- departure.hasInitialDeparturePassed(
+ val itinerary = repository.getFollowedItinerary()
+ if (itinerary == null ||
+ itinerary.hasInitialDeparturePassed(
app.timeSource.nowMillis(),
pessimistic = true,
) || !repository.backgroundPollingNeeded.value
) {
- if (departure?.hasDeparted(app.timeSource) == true) repository.stopTracking()
+ if (itinerary != null) repository.stopTracking()
stop(applicationContext)
} else {
DeparturePollingAlarm.refresh(applicationContext, repository)
diff --git a/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt b/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt
index 4394965..c616f41 100644
--- a/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt
+++ b/app/src/main/kotlin/in/izyum/bart/presentation/DepartureTextFormatter.kt
@@ -3,6 +3,7 @@ package `in`.izyum.bart.presentation
import android.content.Context
import `in`.izyum.bart.R
import `in`.izyum.bart.model.Departure
+import `in`.izyum.bart.model.Itinerary
import `in`.izyum.bart.model.PredictionSource
import `in`.izyum.bart.model.TimeSource
import `in`.izyum.bart.model.TripLeg
@@ -11,7 +12,6 @@ import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
-import java.util.Locale
import kotlin.math.abs
/** Android-facing formatting for departure text shown by the UI. */
@@ -32,126 +32,26 @@ object DepartureTextFormatter {
}
@JvmStatic
- fun transferDetails(context: Context, departure: Departure): String {
- if (!departure.hasTransfers()) return ""
- val timeFormat = timeFormatter(context)
- return departure.tripLegs.mapIndexed { index, leg ->
- val lineName = leg.line?.getDisplayName() ?: context.getString(R.string.train)
- val departureTime = if (leg.departureTime <= 0) {
- context.getString(R.string.trip_no_departure_scheduled)
- } else {
- formatTime(timeFormat, leg.departureTime)
- }
- val route = if (leg.origin != null && leg.destination != null) {
- context.getString(
- R.string.route_title_arrow,
- leg.origin.shortName,
- leg.destination.shortName,
- )
- } else {
- null
- }
- val legText = if (route == null) {
- context.getString(R.string.transfer_leg, lineName, departureTime)
- } else {
- context.getString(R.string.transfer_leg_route, lineName, departureTime, route)
- }
- buildString {
- if (index > 0) append('\n')
- append(legText)
- if (leg.arrivalTime > 0) {
- append(context.getString(
- R.string.transfer_leg_arrival,
- formatTime(timeFormat, leg.arrivalTime),
- ))
- }
- val nextLeg = departure.tripLegs.getOrNull(index + 1)
- if (nextLeg != null && leg.arrivalTime > 0 && nextLeg.departureTime > 0) {
- val safeMargin = (nextLeg.departureTime - leg.arrivalTime).coerceAtLeast(0)
- val marginMinutes = safeMargin / 60000L
- val marginSeconds = (safeMargin % 60000L) / 1000L
- val marginText = when {
- marginMinutes > 0 && marginSeconds > 0 -> context.resources.getQuantityString(
- R.plurals.connection_margin_minutes_seconds,
- marginMinutes.toInt(),
- marginMinutes,
- marginSeconds,
- )
- marginMinutes > 0 -> context.resources.getQuantityString(
- R.plurals.connection_margin_minutes,
- marginMinutes.toInt(),
- marginMinutes,
- )
- else -> context.resources.getQuantityString(
- R.plurals.connection_margin_seconds,
- marginSeconds.toInt(),
- marginSeconds,
- )
- }
- append(context.getString(
- R.string.transfer_connection_separator,
- context.getString(R.string.transfer_connection_margin, marginText),
- ))
- }
- }
- }.joinToString("\n")
- }
-
- @JvmStatic
- fun estimatedArrivalMinutesLeft(
- context: Context,
- departure: Departure,
- timeSource: TimeSource,
- ): String = estimatedArrivalMinutesLeft(context, departure, timeSource.nowMillis())
-
- @JvmStatic
- fun estimatedArrivalMinutesLeft(context: Context, departure: Departure, nowMillis: Long): String {
- if (!departure.hasAnyArrivalEstimate()) return context.getString(R.string.estimated_arrival_unknown)
- val minutesLeft = departure.getEstimatedArrivalMinutesLeft(nowMillis)
- return when {
- departure.isCanceled() -> ""
- minutesLeft < 0 -> context.getString(R.string.arrived_at_destination)
- minutesLeft == 0L -> context.getString(
- R.string.arrives_around_less_than_minute,
- estimatedArrivalTime(context, departure, false),
- )
- minutesLeft == 1L -> context.getString(
- R.string.arrives_around_one_minute,
- estimatedArrivalTime(context, departure, false),
- )
- else -> context.getString(
- R.string.arrives_around_minutes,
- estimatedArrivalTime(context, departure, false),
- minutesLeft,
- )
- }
- }
-
- @JvmStatic
- fun estimatedArrivalTime(context: Context, departure: Departure): String =
- estimatedArrivalTime(context, departure, false)
-
- @JvmStatic
- fun estimatedArrivalTime(context: Context, departure: Departure, compact: Boolean): String {
+ fun estimatedArrivalTime(context: Context, departure: Departure): String {
if (!departure.hasAnyArrivalEstimate()) return ""
return formatTime(timeFormatter(context), departure.getEstimatedArrivalTime())
}
@JvmStatic
- fun estimatedDepartureTime(context: Context, departure: Departure): String =
- estimatedDepartureTime(context, departure, false)
+ fun estimatedArrivalTime(context: Context, itinerary: Itinerary): String =
+ if (!itinerary.hasAnyArrivalEstimate()) ""
+ else formatTime(timeFormatter(context), itinerary.getEstimatedArrivalTime())
@JvmStatic
- fun estimatedDepartureTime(context: Context, departure: Departure, compact: Boolean): String {
+ fun estimatedDepartureTime(context: Context, departure: Departure): String {
if (departure.getMeanEstimate() <= 0) return ""
return formatTime(timeFormatter(context), departure.getMeanEstimate())
}
@JvmStatic
- fun departureScheduleDetails(context: Context, departure: Departure): String {
- val leg = departure.tripLegs.firstOrNull() ?: return ""
- return legScheduleDetails(context, leg)
- }
+ fun estimatedDepartureTime(context: Context, itinerary: Itinerary): String =
+ if (itinerary.getInitialDepartureTime() <= 0L) ""
+ else formatTime(timeFormatter(context), itinerary.getInitialDepartureTime())
@JvmStatic
fun legScheduleDetails(context: Context, leg: TripLeg): String {
@@ -163,18 +63,6 @@ object DepartureTextFormatter {
)
}
- @JvmStatic
- fun stopScheduleDetails(
- context: Context,
- stop: TripStop,
- departure: Boolean,
- ): String = scheduleDetails(
- context,
- if (departure) stop.scheduledDepartureTime else stop.scheduledArrivalTime,
- if (departure) stop.departureTime else stop.arrivalTime,
- if (departure) stop.departureSource else stop.arrivalSource,
- )
-
@JvmStatic
fun departureSchedulePresentation(context: Context, departure: Departure): ScheduleDetails {
val leg = departure.tripLegs.firstOrNull() ?: return ScheduleDetails()
@@ -321,7 +209,7 @@ object DepartureTextFormatter {
val secondsLeft = (arrivalTime - nowMillis) / 1000L
return when {
departure.isCanceled() -> context.getString(R.string.departure_canceled)
- nowMillis >= departureTime -> context.getString(if (departure.isListedInETDs()) R.string.leaving else R.string.departed)
+ nowMillis >= departureTime -> context.getString(R.string.departed)
nowMillis >= arrivalTime -> context.getString(R.string.departure_at_station)
else -> context.getString(
R.string.departure_countdown,
@@ -330,12 +218,6 @@ object DepartureTextFormatter {
}
}
- @JvmStatic
- fun uncertainty(context: Context, departure: Departure, timeSource: TimeSource): String {
- if (departure.hasDeparted(timeSource) || departure.isCanceled()) return ""
- return context.getString(R.string.uncertainty_seconds, departure.getUncertaintySeconds())
- }
-
@JvmStatic
fun trainLengthAndPlatform(context: Context, departure: Departure): String {
val length = departure.trainLength
@@ -350,11 +232,6 @@ object DepartureTextFormatter {
@JvmStatic
fun formatTime(context: Context, millis: Long): String = formatTime(timeFormatter(context), millis)
- @JvmStatic
- fun formatBartScheduleTime(millis: Long): String = DateTimeFormatter.ofPattern("h:mma", Locale.US)
- .withZone(ZoneId.systemDefault())
- .format(Instant.ofEpochMilli(millis))
-
private fun formatTime(formatter: DateTimeFormatter, millis: Long): String =
formatter.format(Instant.ofEpochMilli(millis))
diff --git a/app/src/main/kotlin/in/izyum/bart/receivers/AlarmBroadcastReceiver.kt b/app/src/main/kotlin/in/izyum/bart/receivers/AlarmBroadcastReceiver.kt
index 0ff12ac..8d722b1 100644
--- a/app/src/main/kotlin/in/izyum/bart/receivers/AlarmBroadcastReceiver.kt
+++ b/app/src/main/kotlin/in/izyum/bart/receivers/AlarmBroadcastReceiver.kt
@@ -41,14 +41,15 @@ class AlarmBroadcastReceiver : BroadcastReceiver() {
return
}
val application = context.applicationContext as BartRunnerApplication
- val boardedDeparture = application.followedTripRepository.handleAlarmTriggered()
+ val boardedItinerary = application.followedTripRepository.handleAlarmTriggered()
?: return
+ val boardedDeparture = boardedItinerary.toDeparture()
val targetIntent = Intent(context, TripInProgressActivity::class.java).apply {
RouteArguments.putTrip(
this,
boardedDeparture.getStationPair(),
- boardedDeparture.identity,
+ boardedItinerary.selectionIdentity,
RouteArguments.MODE_FOLLOWED,
)
addFlags(
@@ -141,7 +142,7 @@ class AlarmBroadcastReceiver : BroadcastReceiver() {
.setUsage(VibrationAttributes.USAGE_ALARM)
.build(),
)
- } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ } else {
vibrateWithAudioAttributes(
vibrator,
VibrationEffect.createWaveform(pattern, -1),
@@ -149,9 +150,6 @@ class AlarmBroadcastReceiver : BroadcastReceiver() {
.setUsage(AudioAttributes.USAGE_ALARM)
.build(),
)
- } else {
- @Suppress("DEPRECATION")
- vibrator.vibrate(pattern, -1)
}
}
diff --git a/app/src/main/kotlin/in/izyum/bart/receivers/BootCompletedReceiver.kt b/app/src/main/kotlin/in/izyum/bart/receivers/BootCompletedReceiver.kt
new file mode 100644
index 0000000..ea502b6
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/receivers/BootCompletedReceiver.kt
@@ -0,0 +1,23 @@
+package `in`.izyum.bart.receivers
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import `in`.izyum.bart.BartRunnerApplication
+import `in`.izyum.bart.platform.DeparturePollingAlarm
+import `in`.izyum.bart.platform.ExactAlarmPermission
+
+/** Re-arms persisted followed-trip work after Android clears alarms at reboot. */
+class BootCompletedReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != Intent.ACTION_BOOT_COMPLETED &&
+ intent.action != Intent.ACTION_MY_PACKAGE_REPLACED
+ ) return
+
+ val application = context.applicationContext as BartRunnerApplication
+ if (ExactAlarmPermission.isGranted(application)) {
+ application.followedTripRepository.rescheduleAlarmIfPending()
+ }
+ DeparturePollingAlarm.refresh(application, application.followedTripRepository)
+ }
+}
diff --git a/app/src/main/kotlin/in/izyum/bart/routing/RaptorRouter.kt b/app/src/main/kotlin/in/izyum/bart/routing/RaptorRouter.kt
new file mode 100644
index 0000000..2d42351
--- /dev/null
+++ b/app/src/main/kotlin/in/izyum/bart/routing/RaptorRouter.kt
@@ -0,0 +1,657 @@
+package `in`.izyum.bart.routing
+
+import `in`.izyum.bart.model.Line
+import `in`.izyum.bart.model.PredictionSource
+import `in`.izyum.bart.model.Route
+import `in`.izyum.bart.model.Station
+import `in`.izyum.bart.transit.gtfs.BartGtfsNetwork
+import java.util.LinkedHashMap
+
+/**
+ * RAPTOR router for a time-scoped timetable. Each round advances one boarding
+ * layer; the retained Pareto frontier gives the at-most-k result. A round scans
+ * only patterns serving stations improved in the preceding layer, and each
+ * such pattern is scanned once from its first marked stop. Timetable trips are
+ * split into non-overtaking route groups so one active trip is sufficient
+ * during a scan.
+ *
+ * BART transfers happen between lines serving the same station, so no separate
+ * footpath relaxation is needed. Labels retain their incoming pattern because
+ * transfer margins can depend on the incoming/outgoing line and Yellow route.
+ */
+class RaptorRouter(
+ trips: List,
+ private val network: BartGtfsNetwork,
+ private val transferPolicy: TransferPolicy = TransferPolicy(network),
+) {
+ data class StopTime(
+ val station: Station,
+ val arrivalTime: Long,
+ val departureTime: Long,
+ val scheduledArrivalTime: Long = 0L,
+ val scheduledDepartureTime: Long = 0L,
+ val arrivalSource: PredictionSource = PredictionSource.UNKNOWN,
+ val departureSource: PredictionSource = PredictionSource.UNKNOWN,
+ val platform: String? = null,
+ )
+
+ data class Trip(
+ val id: String,
+ val line: Line,
+ val direction: String?,
+ val trainDestination: Station?,
+ val stops: List,
+ val payload: Any? = null,
+ val canceled: Boolean = false,
+ )
+
+ data class Leg(
+ val trip: Trip,
+ val fromIndex: Int,
+ val toIndex: Int,
+ ) {
+ val origin: Station get() = trip.stops[fromIndex].station
+ val destination: Station get() = trip.stops[toIndex].station
+ val departureTime: Long get() = trip.stops[fromIndex].departureTime
+ val arrivalTime: Long get() = trip.stops[toIndex].arrivalTime
+ }
+
+ data class Journey(val legs: List) {
+ val arrivalTime: Long get() = legs.lastOrNull()?.arrivalTime ?: 0L
+ val transferCount: Int get() = (legs.size - 1).coerceAtLeast(0)
+ }
+
+ private data class PatternKey(val line: Line, val stations: List)
+
+ /** A route group has a shared stop pattern and no overtaking trips. */
+ private data class RoutePattern(
+ val key: PatternKey,
+ val tripsByStop: List>,
+ ) {
+ val stations: List get() = key.stations
+ }
+
+ private data class RoutePosition(val routeIndex: Int, val stopIndex: Int)
+
+ private data class LabelKey(
+ val station: Station,
+ val incomingLine: Line?,
+ val incomingPattern: PatternKey?,
+ )
+
+ /** Parent-linked label: extending a journey never copies its leg list. */
+ private data class Label(
+ val station: Station,
+ val arrivalTime: Long,
+ val boardings: Int,
+ val incomingLine: Line?,
+ val incomingPattern: PatternKey?,
+ val parent: Label?,
+ val leg: Leg?,
+ )
+
+ private data class ActiveTrip(
+ val trip: Trip,
+ val boardIndex: Int,
+ val parent: Label,
+ )
+
+ private data class BoardingCandidate(
+ val trip: Trip,
+ val boardIndex: Int,
+ val parent: Label,
+ val departureTime: Long,
+ )
+
+ private data class TransferMarginKey(
+ val station: Station,
+ val fromLine: Line,
+ val incomingPattern: PatternKey?,
+ val outgoingPattern: PatternKey,
+ )
+
+ private val routes: List = buildRoutes(trips)
+ private val routesByStation: Array> =
+ Array(Station.values().size) { mutableListOf() }
+
+ init {
+ routes.forEachIndexed { routeIndex, route ->
+ route.stations.forEachIndexed { stopIndex, station ->
+ routesByStation[station.ordinal] += RoutePosition(routeIndex, stopIndex)
+ }
+ }
+ }
+
+ /** Returns the Pareto-optimal journeys by arrival time and boardings. */
+ fun journeys(
+ origin: Station,
+ destination: Station,
+ departureTime: Long,
+ maxBoardings: Int = MAX_BOARDINGS,
+ ): List {
+ if (origin == destination || departureTime <= 0L || maxBoardings <= 0) {
+ return emptyList()
+ }
+ return search(origin, destination, departureTime, maxBoardings)
+ }
+
+ private fun search(
+ origin: Station,
+ destination: Station,
+ departureTime: Long,
+ maxBoardings: Int,
+ ): List {
+ val labelsByState = LinkedHashMap>()
+ val destinationFrontier = mutableListOf