Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
c9f6b58
fix(android): detect boarding from the rider's own track
AvianJay Nov 11, 2026
5987fb5
fix(android): address trip monitor review findings
AvianJay Nov 13, 2026
2c66fac
fix(android): keep the trip monitor's feeds and direction honest
AvianJay Nov 13, 2026
2cc01e7
fix(android): keep one trip's data and decisions out of the next
AvianJay Nov 13, 2026
c8d42d1
fix(android): preserve skipped-stop alerts and newer trip feeds
AvianJay Nov 13, 2026
209fd7b
fix(android): track family vehicles and alert on bus-only overshoots
AvianJay Nov 14, 2026
3d607f6
fix(android): require bounded evidence before identifying a boarding bus
AvianJay Nov 14, 2026
5665a40
fix(android): tie a confirmed ride to the bus it was confirmed on
AvianJay Nov 14, 2026
4fb8c82
fix(android): only an answer to the boarding question names its bus
AvianJay Nov 14, 2026
8901d97
fix(android): tell apart buses that leave the stop close together
AvianJay Nov 15, 2026
514d9c0
fix(android): do not pair an ETA rollover with a bus without evidence
AvianJay Nov 15, 2026
bd52f8c
fix(android): keep an ETA rollover unnamed once two buses were at the…
AvianJay Nov 15, 2026
045b9dd
fix(android): keep a hairpin's two legs apart when projecting onto th…
AvianJay Nov 16, 2026
02c45b4
fix(android): only count evidence the rider's own track on the route …
AvianJay Nov 16, 2026
f5d795c
fix(android): keep an identified ride on its bus without evidence aga…
AvianJay Nov 16, 2026
e504d38
fix: place a bus at the boarding stop by what the feed says of it
AvianJay Nov 16, 2026
c2b2d47
fix: take each observation of the stop feed once, and only from the feed
AvianJay Nov 16, 2026
0b18bdc
fix(android): make each boarding button speak only for its own trip
AvianJay Nov 16, 2026
3502c03
fix(android): bring a ride paused for a destination back as the same …
AvianJay Nov 16, 2026
46ec6ea
fix(android): keep a ride with no boarding stop paused until it has a…
AvianJay Nov 16, 2026
fb6f334
fix(android): fetch each feed on its own, and place a variant's bus o…
AvianJay Nov 16, 2026
9e11816
fix(android): keep a failed fetch, and a bus two routes list, from de…
AvianJay Nov 16, 2026
c2d4035
test: hold the per-bus arriving flag and the stop feed's observation …
AvianJay Nov 16, 2026
016576c
fix(android): act on an answer only for the question still pending, a…
AvianJay Nov 17, 2026
de71e16
fix: read each route's estimate for a shared stop by itself, stop by …
AvianJay Nov 17, 2026
ad64335
fix: keep a trip's feeds, a rider's answer and a route's bus to what …
AvianJay Nov 17, 2026
8e744b5
fix: keep a stop's entry that says only that a bus is arriving
AvianJay Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<!-- The trip monitor has to keep polling while the screen is off;
without this the CPU sleeps between location callbacks and the
refresh loop stops until the user next wakes the phone. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ object AppLaunchConstants {
routeKey: Int,
routeId: String? = null,
pathId: Int? = null,
stopId: Int? = null,
stopId: Long? = null,
destinationPathId: Int? = null,
destinationStopId: Int? = null,
destinationStopId: Long? = null,
): Intent {
return Intent(context, MainActivity::class.java).apply {
putExtra(EXTRA_TARGET, TARGET_ROUTE_DETAIL)
Expand Down Expand Up @@ -100,23 +100,21 @@ object AppLaunchConstants {
if (intent.hasExtra(EXTRA_PATH_ID)) {
payload["pathId"] = intent.getIntExtra(EXTRA_PATH_ID, 0)
}
if (intent.hasExtra(EXTRA_STOP_ID)) {
payload["stopId"] = intent.getIntExtra(EXTRA_STOP_ID, 0)
}
// Stop ids are sent at full width, because Dart keys stops by
// the raw feed id: 高雄's exceed Int, and narrowing them here
// would name a different stop than the app's models hold. The
// native-only fold (`foldStopId`) is for joining the live
// feeds, not for identifying a stop to Flutter.
stopIdExtra(intent, EXTRA_STOP_ID)?.let { payload["stopId"] = it }
val destinationPathId = intent.getIntExtra(
EXTRA_DESTINATION_PATH_ID,
Int.MIN_VALUE,
)
if (destinationPathId != Int.MIN_VALUE) {
payload["destinationPathId"] = destinationPathId
}
val destinationStopId = intent.getIntExtra(
EXTRA_DESTINATION_STOP_ID,
Int.MIN_VALUE,
)
if (destinationStopId != Int.MIN_VALUE) {
payload["destinationStopId"] = destinationStopId
}
stopIdExtra(intent, EXTRA_DESTINATION_STOP_ID)
?.let { payload["destinationStopId"] = it }
payload
}

Expand Down Expand Up @@ -145,6 +143,19 @@ object AppLaunchConstants {
}
}

/**
* Reads a stop id extra as a `Long` whichever width it was stored at.
*
* New intents store a `Long`. Shortcuts pinned to the home screen before
* that keep the `Int` they were created with for as long as they exist, and
* `getLongExtra` answers its default for an extra of another type — which
* would quietly open those shortcuts with no stop selected.
*/
@Suppress("DEPRECATION")
private fun stopIdExtra(intent: Intent, key: String): Long? {
return (intent.extras?.get(key) as? Number)?.toLong()
}

private fun extractAuthCallbackPayload(uri: android.net.Uri?): Map<String, Any?>? {
uri ?: return null
if (uri.scheme?.lowercase() != "yabus" || uri.host?.lowercase() != "auth-callback") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package tw.avianjay.taiwanbus.flutter

import android.content.Context

/** On board with nowhere to get off: the monitor pauses and asks the rider to choose a stop. */
internal const val PAUSE_REASON_BOARDED_NO_DESTINATION = "boarded_no_destination"

object AppRuntimeStateStore {
private const val PREFERENCES_NAME = "app_runtime_state"
private const val KEY_APP_IN_FOREGROUND = "app_in_foreground"
Expand All @@ -12,6 +15,7 @@ object AppRuntimeStateStore {
private const val KEY_PAUSED_DESTINATION_STOP_ID = "trip_monitor_paused_destination_stop_id"
private const val KEY_PAUSED_REASON = "trip_monitor_paused_reason"
private const val KEY_PAUSED_AT_MS = "trip_monitor_paused_at_ms"
private const val KEY_PAUSED_VEHICLE_ID = "trip_monitor_paused_vehicle_id"

fun setAppInForeground(context: Context, value: Boolean) {
preferences(context).edit()
Expand All @@ -23,10 +27,17 @@ object AppRuntimeStateStore {
return preferences(context).getBoolean(KEY_APP_IN_FOREGROUND, false)
}

/**
* [rideVehicleId] is the bus the paused ride had been identified as being
* on, when it had: the detector that knew it is gone once the monitor
* pauses, and with no phone fix that bus is all a resumed ride has to tell
* how far it has got.
*/
fun savePausedTripMonitor(
context: Context,
session: TrackingSession,
reason: String,
rideVehicleId: String? = null,
) {
preferences(context).edit()
.putString(KEY_PAUSED_PROVIDER, session.provider)
Expand All @@ -36,6 +47,7 @@ object AppRuntimeStateStore {
.putInt(KEY_PAUSED_DESTINATION_STOP_ID, session.destinationStopId ?: -1)
.putString(KEY_PAUSED_REASON, reason)
.putLong(KEY_PAUSED_AT_MS, System.currentTimeMillis())
.putString(KEY_PAUSED_VEHICLE_ID, rideVehicleId)
.apply()
}

Expand All @@ -48,6 +60,7 @@ object AppRuntimeStateStore {
.remove(KEY_PAUSED_DESTINATION_STOP_ID)
.remove(KEY_PAUSED_REASON)
.remove(KEY_PAUSED_AT_MS)
.remove(KEY_PAUSED_VEHICLE_ID)
.apply()
}

Expand All @@ -74,6 +87,9 @@ object AppRuntimeStateStore {
?.trim()
?.takeIf { it.isNotEmpty() },
pausedAtMs = preferences.getLong(KEY_PAUSED_AT_MS, 0L),
rideVehicleId = preferences.getString(KEY_PAUSED_VEHICLE_ID, null)
?.trim()
?.takeIf { it.isNotEmpty() },
)
}

Expand All @@ -98,15 +114,30 @@ data class TripMonitorPauseState(
val destinationStopId: Int?,
val reason: String?,
val pausedAtMs: Long,
/** The bus the paused ride was identified as being on; null when it was not. */
val rideVehicleId: String? = null,
) {
/**
* Whether [session] is the trip that was paused.
*
* A ride paused to ask for a destination, with no boarding stop chosen, is
* that ride whichever boarding stop the session names. The route screen
* fills in the stop nearest the rider when none is chosen, and that moves
* down the route as the bus does; read as another trip, it would start
* the monitor afresh, waiting at a stop the rider is riding past, and the
* ride could no longer be picked up when they choose where to get off.
*/
fun matches(session: TrackingSession): Boolean {
return provider == session.provider &&
routeKey == session.routeKey &&
pathId == session.pathId &&
boardingStopId == session.boardingStopId &&
(boardingStopId == session.boardingStopId || awaitsADestinationFromAnyStop) &&
destinationStopId == session.destinationStopId
}

private val awaitsADestinationFromAnyStop: Boolean
get() = reason == PAUSE_REASON_BOARDED_NO_DESTINATION && boardingStopId == null

fun toMap(): Map<String, Any?> {
return mapOf(
"provider" to provider,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,8 @@ object FavoriteGroupWidgetSupport {
)
}

private fun createItemPendingIntent(
/** The tap intent for one widget row. Internal so a test can read it back. */
internal fun createItemPendingIntent(
context: Context,
item: FavoriteWidgetItem,
): PendingIntent {
Expand All @@ -409,9 +410,12 @@ object FavoriteGroupWidgetSupport {
routeKey = item.routeKey,
routeId = item.routeId,
pathId = item.pathId.takeIf { item.type == "boarding" },
stopId = item.stopId.takeIf { item.type == "boarding" },
// The full-width id, not the folded one: Flutter compares this
// against the ids its own stop models carry, and a folded
// 高雄 id matches nothing there.
stopId = item.launchStopId.takeIf { item.type == "boarding" },
destinationPathId = item.destinationPathId,
destinationStopId = item.destinationStopId,
destinationStopId = item.launchDestinationStopId,
).apply {
data = Uri.parse(
"yabus://route/${item.provider}/${item.routeKey}/${Uri.encode(item.routeId.orEmpty())}",
Expand All @@ -434,9 +438,14 @@ object FavoriteGroupWidgetSupport {
val raw = runCatching {
preferences.getString(FAVORITE_GROUPS_KEY, null)
?: preferences.getString(FAVORITE_GROUPS_FALLBACK_KEY, null)
}.getOrNull() ?: return emptyMap()
}.getOrNull()
return parseFavoriteGroups(raw)
}

/** Reads the favourites Dart saved. Internal so a test can feed it a config. */
internal fun parseFavoriteGroups(raw: String?): Map<String, List<FavoriteWidgetItem>> {
val root = try {
JSONObject(raw)
JSONObject(raw ?: return emptyMap())
} catch (_: Exception) {
return emptyMap()
}
Expand All @@ -449,7 +458,13 @@ object FavoriteGroupWidgetSupport {
val item = groupArray.optJSONObject(index) ?: continue
val type = item.optString("type", "boarding").trim().ifEmpty { "boarding" }
val routeKey = item.optInt("routeKey", 0)
val stopId = item.optInt("stopId", 0)
// The config is written by Dart with the id as Dart holds it,
// which exceeds Int for 高雄. It is needed twice, as two
// different numbers: folded the way the live feed is, for the
// ETA lookup; and at full width, for the tap that launches
// back into Flutter.
val dartStopId = item.opt("stopId")
val stopId = foldStopId(dartStopId)
val routeId = item.optString("routeId", "").trim().takeIf { it.isNotEmpty() }
val stationId = item.optString("stationId", "").trim()
val valid = when (type) {
Expand All @@ -461,19 +476,15 @@ object FavoriteGroupWidgetSupport {
if (!valid) {
continue
}
val destinationStopId = item.optInt("destinationStopId", 0)
.takeIf { it > 0 }
val destinationPathId = if (destinationStopId == null) {
null
} else {
item.optInt("destinationPathId", item.optInt("pathId", 0))
}
val dartDestinationStopId = item.opt("destinationStopId")
val hasDestination = foldStopId(dartDestinationStopId) > 0
groupItems += FavoriteWidgetItem(
type = type,
provider = item.optString("provider", "twn"),
routeKey = routeKey,
pathId = item.optInt("pathId", 0),
stopId = stopId,
launchStopId = launchStopId(dartStopId).takeIf { stopId > 0 },
routeId = routeId,
routeName = item.optString("routeName", ""),
routeDescription = item.optString("routeDescription", "")
Expand All @@ -482,8 +493,13 @@ object FavoriteGroupWidgetSupport {
stopName = item.optString("stopName", ""),
stationId = stationId,
stationName = item.optString("stationName", ""),
destinationPathId = destinationPathId,
destinationStopId = destinationStopId,
destinationPathId = if (hasDestination) {
item.optInt("destinationPathId", item.optInt("pathId", 0))
} else {
null
},
launchDestinationStopId = launchStopId(dartDestinationStopId)
.takeIf { hasDestination },
destinationStopName = item.optString("destinationStopName", "")
.trim()
.takeIf { it.isNotEmpty() },
Expand Down Expand Up @@ -690,21 +706,7 @@ object FavoriteGroupWidgetSupport {
return result
}

private fun parseStopId(raw: Any?): Int {
if (raw is Number) {
return raw.toInt()
}
val text = raw?.toString()?.trim().orEmpty()
val parsed = text.toIntOrNull()
if (parsed != null) {
return parsed
}
var hash = 17
for (char in text) {
hash = (hash * 31 + char.code) and 0x7fffffff
}
return hash
}
private fun parseStopId(raw: Any?): Int = foldStopId(raw)

private fun toIntOrNull(raw: Any?): Int? {
return when (raw) {
Expand Down Expand Up @@ -807,15 +809,18 @@ data class FavoriteWidgetItem(
val provider: String,
val routeKey: Int,
val pathId: Int,
/** Folded, as the live feeds are: only usable for looking up ETAs. */
val stopId: Int,
/** Full-width, as Flutter holds it: what a tap is launched with. */
val launchStopId: Long?,
val routeId: String?,
val routeName: String,
val routeDescription: String?,
val stopName: String,
val stationId: String,
val stationName: String,
val destinationPathId: Int?,
val destinationStopId: Int?,
val launchDestinationStopId: Long?,
val destinationStopName: String?,
) {
val identity: String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,10 @@ class MainActivity : FlutterActivity() {
val routeKey = call.argument<Int>("routeKey")
val routeId = call.argument<String>("routeId")?.trim().orEmpty()
val pathId = call.argument<Int>("pathId")
val stopId = call.argument<Int>("stopId")
// Stop ids can exceed Int (高雄's are 64-bit), and the channel decodes a
// Dart int to Integer or Long depending on its magnitude, so both are
// accepted rather than letting the larger ones read back as null.
val stopId = call.argument<Number>("stopId")?.toLong()
val routeName = call.argument<String>("routeName")?.trim().orEmpty()
val stopName = call.argument<String>("stopName")?.trim().orEmpty()
val stationId = call.argument<String>("stationId")?.trim().orEmpty()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package tw.avianjay.taiwanbus.flutter

import android.location.Location
import android.os.SystemClock

/**
* When [location] was measured, on the wall clock the ride detector runs on.
*
* A fix's age is read off the monotonic clock, the only one a fix and "now" are
* guaranteed to share: `Location.time` may come from the satellites, the
* network or the system clock, and none of those has to agree with
* `System.currentTimeMillis()`. Taking that age off the current wall-clock time
* puts a fix cached five minutes ago five minutes in the past — where the
* detector can see it is stale — however the device's clock happens to be set.
*
* A location with no monotonic stamp did not come from the platform (the
* session's seed position is built by hand). Its own `time` is used when it has
* a believable one, and it counts as current otherwise.
*/
internal fun rideFixTimestampMs(
location: Location,
nowWallMs: Long = System.currentTimeMillis(),
nowElapsedNanos: Long = SystemClock.elapsedRealtimeNanos(),
): Long {
val fixElapsedNanos = location.elapsedRealtimeNanos
if (fixElapsedNanos > 0L) {
val ageMs = ((nowElapsedNanos - fixElapsedNanos) / NANOS_PER_MILLI).coerceAtLeast(0L)
return nowWallMs - ageMs
}
return location.time.takeIf { it in 1L..nowWallMs } ?: nowWallMs
}

private const val NANOS_PER_MILLI = 1_000_000L
Loading
Loading