diff --git a/README.md b/README.md index 7dd3f3b..c841a17 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,8 @@ la release. Les builds debug ne se mettent jamais à jour. Journal : `adb logcat Aperçu d'un changement sur la box sans toucher à l'app en place : `./gradlew assembleRelease -Ppreview` installe à côté une app `be.lghs.lab.preview` (secrets à envoyer à -`content://be.lghs.lab.preview.secrets/secrets`, mise à jour automatique désactivée). La +`content://be.lghs.lab.preview.secrets/secrets`, mise à jour automatique désactivée, `dashboard/` +de la branche au lieu de celui de `main`). La désinstaller ensuite (`adb uninstall be.lghs.lab.preview`) et relancer `adb shell cmd package set-home-activity be.lghs.lab/.MainActivity`. @@ -106,6 +107,13 @@ GitHub. L'app le relit au démarrage puis toutes les heures, sans réinstallatio (`tec_planned_trips.csv` et `tec_services.csv`, générés eux aussi par l'Action). - `sncb.routes` : trains directs entre deux gares (noms [iRail](https://api.irail.be/stations/?format=json&lang=fr)). +- `minutesFromSpace` (quai ou trajet, optionnel) : minutes pour aller du space au quai ou à la + gare. `travelMode` : `"bike"` pour y aller à vélo (Guillemins), à pied par défaut ; picto à + côté du chrono. Un départ qu'on n'a plus le temps d'attraper est masqué ; chrono (temps avant + le départ) en jaune s'il faut partir maintenant (2 min de marge), en vert si on a le temps. + Valeurs calculées avec l'itinéraire piéton OpenStreetMap + ([OSRM](https://routing.openstreetmap.de)) depuis Rue de la Loi 16, arrondies au-dessus. + Pour les trains, en plus des `departuresPerRoute` atteignables. Trouver un quai : `stops.txt` du [GTFS TEC](https://opendata.tec-wl.be/Current%20GTFS/). @@ -167,8 +175,9 @@ long sur OK. La touche Retour ne quitte pas l'écran d'accueil. | Livraison | [lghs.be/deliveroo](https://lghs.be/deliveroo/?json) : code livreur, décompte, « proche » en évidence avec le son `res/raw/deliveroo.mp3` (une fois par commande) ; commande livrée masquée 15 min après `livraison_estimee` | 15 s | | Musique | moOde : MPD (`idle`) + renderers Spotify/AirPlay/Deezer | instantané / 2 s | | Bus | GTFS-RT TEC (retards) + horaires générés | 30 s | -| Trains | [iRail](https://api.irail.be), trajet par trajet ; derniers trains gardés en cas d'erreur, « pas à jour depuis » après 5 min | 60 s | -| Météo | [Open-Meteo](https://open-meteo.com) | 10 min | +| Trains | [iRail](https://api.irail.be), trajet par trajet, 3 essais à 5 s d'écart ; heure réelle (retard compris) ; train supprimé barré, le suivant du même trajet juste en dessous (« ↳ ») ; derniers trains gardés en cas d'erreur, même après un redémarrage (`trains.json`), « pas à jour depuis » après 5 min | 60 s | +| Météo | [Open-Meteo](https://open-meteo.com) ; sans commande Deliveroo, carte agrandie avec la pluie des 2 prochaines heures au quart d'heure (mm prévus) | 10 min | +| Statut du space | [SpaceAPI](https://spaceapi.lghs.be/) : feu tricolore Fermé / Membres / Ouvert (`open`, `open_to_visitors`) | 60 s | | Arrêts / trajets | `dashboard/` de ce dépôt | 1 h | | Mise à jour de l'app | Releases GitHub de ce dépôt | 5 min | diff --git a/app/src/main/java/be/lghs/lab/Config.kt b/app/src/main/java/be/lghs/lab/Config.kt index db2e147..0b669e6 100644 --- a/app/src/main/java/be/lghs/lab/Config.kt +++ b/app/src/main/java/be/lghs/lab/Config.kt @@ -38,6 +38,9 @@ object Config { const val DOOR_ALERT_AFTER_SEC = 5 * 60L const val MPD_PORT = 6600 + /** Statut ouvert / membres / fermé du space (feu tricolore du site). */ + const val SPACEAPI_URL = "https://spaceapi.lghs.be/" + // Rue de la Loi, Outremeuse const val LATITUDE = 50.6419 const val LONGITUDE = 5.5860 diff --git a/app/src/main/java/be/lghs/lab/MainActivity.kt b/app/src/main/java/be/lghs/lab/MainActivity.kt index a516ccc..4516eeb 100644 --- a/app/src/main/java/be/lghs/lab/MainActivity.kt +++ b/app/src/main/java/be/lghs/lab/MainActivity.kt @@ -19,7 +19,12 @@ import be.lghs.lab.data.NukiRepository import be.lghs.lab.data.RendererClient import be.lghs.lab.data.TecRepository import be.lghs.lab.data.TransportConfigRepository +import be.lghs.lab.data.TrainBoard +import be.lghs.lab.data.TrainCache import be.lghs.lab.data.TrainRepository +import be.lghs.lab.data.TrainRoute +import be.lghs.lab.data.TransportConfig +import be.lghs.lab.data.SpaceApiRepository import be.lghs.lab.data.WeatherRepository import be.lghs.lab.databinding.ActivityMainBinding import be.lghs.lab.ui.Chime @@ -41,6 +46,7 @@ class MainActivity : AppCompatActivity() { private lateinit var transport: TransportPanel private val tec = TecRepository() private lateinit var transportConfig: TransportConfigRepository + private lateinit var trainCache: TrainCache private lateinit var chime: Chime override fun onCreate(savedInstanceState: Bundle?) { @@ -54,6 +60,8 @@ class MainActivity : AppCompatActivity() { info = InfoPanel(binding.panelInfo, onCourierNear = { chime.play(R.raw.deliveroo) }) music = MusicPanel(binding.panelInfo.music, lifecycleScope) transport = TransportPanel(binding.panelTransport, lifecycleScope) + trainCache = TrainCache(java.io.File(filesDir, "trains.json")) + transport.restoreTrains(trainCache.load(), nowSec()) transportConfig = TransportConfigRepository(this) // Tout ne tourne que quand l'app est visible @@ -63,6 +71,8 @@ class MainActivity : AppCompatActivity() { // Seuls bus et trains attendent cette config : le reste démarre tout de suite. launch { transportConfig.load() + // Preview : garde le dashboard/ embarqué (celui de la branche), pas celui de main + if (BuildConfig.APPLICATION_ID.endsWith(".preview")) return@launch poll("config transports", everyMs = Config.REMOTE_CONFIG_REFRESH_MS, retryMs = 5 * 60_000) { transportConfig.refresh() } @@ -100,23 +110,18 @@ class MainActivity : AppCompatActivity() { poll("météo", everyMs = 10 * 60_000, retryMs = 60_000) { info.showWeather(WeatherRepository.fetch()) } + poll("SpaceAPI", everyMs = 60_000) { + info.showSpace(SpaceApiRepository.fetch()) + } poll("TEC", everyMs = 30_000, onError = { transport.showBusError("TEC indisponible", nowSec()) }) { transport.showBuses(tec.fetch(transportConfig.awaitConfig()), nowSec()) } // Un trajet à la fois : un 504 iRail sur l'un n'empêche pas la mise à jour des autres poll("SNCB", everyMs = 60_000) { val config = transportConfig.awaitConfig() - val boards = config.trainRoutes.associateWith { route -> - try { - TrainRepository.fetch(route, config.trainsPerRoute) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - Log.w("Dashboard", "SNCB ${route.from} → ${route.to}: ${e.message}") - null - } - } + val boards = config.trainRoutes.associateWith { fetchTrains(it, config) } transport.showTrains(boards, nowSec()) + trainCache.save(transport.savedTrains) } // Nouvelle release GitHub : une minute après le démarrage, puis toutes les 5 min launch { @@ -201,6 +206,24 @@ class MainActivity : AppCompatActivity() { private fun nowSec() = System.currentTimeMillis() / 1000 + /** + * iRail renvoie des 504 par salves de quelques secondes : on réessaie deux fois avant + * d'attendre le tour suivant. null = échec, le panneau garde les derniers trains. + */ + private suspend fun fetchTrains(route: TrainRoute, config: TransportConfig): TrainBoard? { + repeat(SNCB_ATTEMPTS) { attempt -> + try { + return TrainRepository.fetch(route, config.trainsPerRoute) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("Dashboard", "SNCB ${route.from} → ${route.to} (essai ${attempt + 1}/$SNCB_ATTEMPTS): ${e.message}") + if (attempt < SNCB_ATTEMPTS - 1) delay(SNCB_RETRY_MS) + } + } + return null + } + private fun hideSystemBars() { WindowCompat.setDecorFitsSystemWindows(window, false) WindowInsetsControllerCompat(window, window.decorView).apply { @@ -208,4 +231,9 @@ class MainActivity : AppCompatActivity() { systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } } + + private companion object { + const val SNCB_ATTEMPTS = 3 + const val SNCB_RETRY_MS = 5_000L + } } diff --git a/app/src/main/java/be/lghs/lab/data/SpaceApi.kt b/app/src/main/java/be/lghs/lab/data/SpaceApi.kt new file mode 100644 index 0000000..279a351 --- /dev/null +++ b/app/src/main/java/be/lghs/lab/data/SpaceApi.kt @@ -0,0 +1,22 @@ +package be.lghs.lab.data + +import be.lghs.lab.Config +import org.json.JSONObject + +/** Statut annoncé du hackerspace, comme le feu tricolore du site. */ +enum class SpaceState { OPEN, MEMBERS, CLOSED } + +/** SpaceAPI du LgHS : `state.open` et `state.open_to_visitors`. */ +object SpaceApiRepository { + + suspend fun fetch(): SpaceState = parse(Http.getText(Config.SPACEAPI_URL)) + + internal fun parse(json: String): SpaceState { + val state = JSONObject(json).getJSONObject("state") + return when { + !state.optBoolean("open") -> SpaceState.CLOSED + state.optBoolean("open_to_visitors") -> SpaceState.OPEN + else -> SpaceState.MEMBERS + } + } +} diff --git a/app/src/main/java/be/lghs/lab/data/Tec.kt b/app/src/main/java/be/lghs/lab/data/Tec.kt index 22879f2..1ad0228 100644 --- a/app/src/main/java/be/lghs/lab/data/Tec.kt +++ b/app/src/main/java/be/lghs/lab/data/Tec.kt @@ -15,6 +15,9 @@ data class BusDeparture( val delaySec: Int, /** Dernière course de la journée pour cette ligne à ce quai. */ val last: Boolean, + /** Minutes à pied du space jusqu'au quai, null = inconnu. */ + val minutesFromSpace: Int? = null, + val travelMode: TravelMode = TravelMode.FOOT, ) /** @@ -63,7 +66,8 @@ class TecRepository { .map { c -> val stop = stopsById.getValue(c.stop.stopId).value val last = "${c.serviceDay}|${c.tripId}|${c.stop.stopId}" in config.lastTrips - BusDeparture(c.line, stop.lines.getValue(c.line), stop.name, c.time, c.delay, last) + BusDeparture(c.line, stop.lines.getValue(c.line), stop.name, c.time, c.delay, last, + stop.minutesFromSpace, stop.travelMode) } .sortedBy { it.epochSec } } diff --git a/app/src/main/java/be/lghs/lab/data/Trains.kt b/app/src/main/java/be/lghs/lab/data/Trains.kt index df313ba..376019c 100644 --- a/app/src/main/java/be/lghs/lab/data/Trains.kt +++ b/app/src/main/java/be/lghs/lab/data/Trains.kt @@ -1,7 +1,9 @@ package be.lghs.lab.data import android.net.Uri +import org.json.JSONArray import org.json.JSONObject +import java.io.File import java.util.Calendar import java.util.TimeZone @@ -51,8 +53,13 @@ object TrainRepository { d.epochSec, d.delaySec, d.line, d.platform, d.canceled, last = next != null && serviceDay(next.epochSec) != serviceDay(d.epochSec), ) - }.take(count) - return TrainBoard(route, result) + } + // Trains trop proches pour y arriver à pied (chrono en rouge) + [count] trains atteignables + val nowSec = System.currentTimeMillis() / 1000 + val (tooLate, reachable) = result.partition { + reach(it.epochSec + it.delaySec, nowSec, route.minutesFromSpace) == Reach.TOO_LATE + } + return TrainBoard(route, tooLate + reachable.take(count)) } private class RawDeparture( @@ -66,3 +73,60 @@ object TrainRepository { get(Calendar.YEAR) * 1000 + get(Calendar.DAY_OF_YEAR) } } + +/** + * Derniers trains reçus par trajet, gardés sur la box avec leur heure de réception : après un + * redémarrage (mise à jour, preview), une panne d'iRail n'affiche pas « SNCB indisponible ». + */ +class TrainCache(private val file: File) { + + fun load(): List> = runCatching { decode(file.readText()) }.getOrDefault(emptyList()) + + fun save(boards: List>) { + runCatching { + val tmp = File(file.path + ".tmp") + tmp.writeText(encode(boards)) + tmp.renameTo(file) + } + } + + internal companion object { + fun encode(boards: List>): String = JSONArray().apply { + boards.forEach { (board, receivedSec) -> + put(JSONObject().apply { + put("from", board.route.from) + put("to", board.route.to) + put("received", receivedSec) + put("departures", JSONArray().apply { + board.departures.forEach { d -> + put(JSONObject().apply { + put("time", d.epochSec) + put("delay", d.delaySec) + put("line", d.line) + put("platform", d.platform) + put("canceled", d.canceled) + put("last", d.last) + }) + } + }) + }) + } + }.toString() + + fun decode(text: String): List> { + val boards = JSONArray(text) + return (0 until boards.length()).map { i -> + val b = boards.getJSONObject(i) + val deps = b.getJSONArray("departures") + val departures = (0 until deps.length()).map { j -> + val d = deps.getJSONObject(j) + TrainDeparture( + d.getLong("time"), d.getInt("delay"), d.getString("line"), d.getString("platform"), + d.getBoolean("canceled"), d.getBoolean("last"), + ) + } + TrainBoard(TrainRoute(b.getString("from"), b.getString("to")), departures) to b.getLong("received") + } + } + } +} diff --git a/app/src/main/java/be/lghs/lab/data/TransportConfig.kt b/app/src/main/java/be/lghs/lab/data/TransportConfig.kt index 2435298..e1bfbbe 100644 --- a/app/src/main/java/be/lghs/lab/data/TransportConfig.kt +++ b/app/src/main/java/be/lghs/lab/data/TransportConfig.kt @@ -15,11 +15,45 @@ import java.io.File import java.io.IOException import java.io.InputStream -/** Un quai TEC (un stop_id = un sens) et les lignes à y afficher → libellé de destination. */ -data class TecStop(val id: String, val name: String, val lines: Map) +/** Comment on va du space au quai ou à la gare (`"travelMode"` dans transport.json). */ +enum class TravelMode { FOOT, BIKE } -/** Trains directs de [from] vers [to] (noms de gare iRail). */ -data class TrainRoute(val from: String, val to: String) +/** + * Un quai TEC (un stop_id = un sens) et les lignes à y afficher → libellé de destination. + * [minutesFromSpace] : minutes pour aller du space au quai, null = inconnu. + */ +data class TecStop( + val id: String, + val name: String, + val lines: Map, + val minutesFromSpace: Int? = null, + val travelMode: TravelMode = TravelMode.FOOT, +) + +/** Trains directs de [from] vers [to] (noms de gare iRail), gare à [minutesFromSpace] du space. */ +data class TrainRoute( + val from: String, + val to: String, + val minutesFromSpace: Int? = null, + val travelMode: TravelMode = TravelMode.FOOT, +) + +/** Peut-on encore attraper un départ en quittant le space maintenant ? */ +enum class Reach { TOO_LATE, HURRY, OK } + +/** Marge après le temps de marche pendant laquelle il faut partir tout de suite. */ +const val HURRY_MARGIN_SEC = 2 * 60 + +/** null si le temps de marche est inconnu. [departureSec] = heure réelle (retard compris). */ +fun reach(departureSec: Long, nowSec: Long, minutesFromSpace: Int?): Reach? { + val walkSec = (minutesFromSpace ?: return null) * 60L + val left = departureSec - nowSec + return when { + left < walkSec -> Reach.TOO_LATE + left < walkSec + HURRY_MARGIN_SEC -> Reach.HURRY + else -> Reach.OK + } +} class ScheduledStop(val stopId: String, val sequence: Int, val secondsOfDay: Int) @@ -107,6 +141,14 @@ class TransportConfigRepository(context: Context) { private fun url(file: String) = Config.REMOTE_CONFIG_URL + file + /** `"minutesFromSpace": 4` (optionnel). */ + private fun minutesFromSpace(json: JSONObject): Int? = + if (json.has("minutesFromSpace")) json.getInt("minutesFromSpace") else null + + /** `"travelMode": "bike"` ; à pied par défaut. */ + private fun travelMode(json: JSONObject): TravelMode = + if (json.optString("travelMode") == "bike") TravelMode.BIKE else TravelMode.FOOT + private fun read(open: (String) -> InputStream): Triple { val transportText = open(TRANSPORT).use { it.readBytes().decodeToString() } val generatedText = open(GENERATED).use { it.readBytes().decodeToString() } @@ -122,12 +164,19 @@ class TransportConfigRepository(context: Context) { id = s.getString("id"), name = s.getString("name"), lines = lines.keys().asSequence().associateWith { lines.getString(it) }, + minutesFromSpace = minutesFromSpace(s), + travelMode = travelMode(s), ) } val routesJson = sncb.getJSONArray("routes") val routes = (0 until routesJson.length()).map { i -> val r = routesJson.getJSONObject(i) - TrainRoute(from = r.getString("from"), to = r.getString("to")) + TrainRoute( + from = r.getString("from"), + to = r.getString("to"), + minutesFromSpace = minutesFromSpace(r), + travelMode = travelMode(r), + ) } val schedule = HashMap>() diff --git a/app/src/main/java/be/lghs/lab/data/Weather.kt b/app/src/main/java/be/lghs/lab/data/Weather.kt index a65d846..a3de27c 100644 --- a/app/src/main/java/be/lghs/lab/data/Weather.kt +++ b/app/src/main/java/be/lghs/lab/data/Weather.kt @@ -2,15 +2,25 @@ package be.lghs.lab.data import be.lghs.lab.Config import org.json.JSONObject +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone + +/** Pluie prévue sur le quart d'heure qui commence à [startSec], en mm. */ +data class RainSlot(val startSec: Long, val mm: Double) { + val raining get() = mm > 0.0 +} data class Weather( val temperature: Double, val min: Double, val max: Double, val windKmh: Double, - val rainChance: Int, val code: Int, val isDay: Boolean, + /** Les 2 prochaines heures, par quart d'heure (le premier = le quart d'heure en cours). */ + val rain: List = emptyList(), ) { val icon: String get() = wmo(code, isDay).first val label: String get() = wmo(code, isDay).second @@ -20,25 +30,57 @@ object WeatherRepository { private val url = "https://api.open-meteo.com/v1/forecast" + "?latitude=${Config.LATITUDE}&longitude=${Config.LONGITUDE}" + "¤t=temperature_2m,weather_code,wind_speed_10m,is_day" + - "&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max" + - "&forecast_days=1&timezone=Europe%2FBrussels" + "&daily=temperature_2m_max,temperature_2m_min" + + "&minutely_15=precipitation&forecast_minutely_15=$RAIN_SLOTS" + + "&forecast_days=1&timezone=Europe%2FBrussels&timeformat=unixtime" suspend fun fetch(): Weather { val json = JSONObject(Http.getText(url)) val current = json.getJSONObject("current") val daily = json.getJSONObject("daily") + val minutely = json.getJSONObject("minutely_15") + val times = minutely.getJSONArray("time") + val mm = minutely.getJSONArray("precipitation") return Weather( temperature = current.getDouble("temperature_2m"), min = daily.getJSONArray("temperature_2m_min").getDouble(0), max = daily.getJSONArray("temperature_2m_max").getDouble(0), windKmh = current.getDouble("wind_speed_10m"), - rainChance = daily.getJSONArray("precipitation_probability_max").optInt(0), code = current.getInt("weather_code"), isDay = current.getInt("is_day") == 1, + rain = (0 until times.length()).map { RainSlot(times.getLong(it), mm.optDouble(it, 0.0)) }, ) } + + /** 2 h par quart d'heure. */ + const val RAIN_SLOTS = 8 +} + +/** + * Pluie des 2 prochaines heures en une phrase : « Pluie vers 19:00 », « Pluie jusqu'à 19:15 », + * « Pluie pendant 2 h » ou « Sec jusqu'à 20:30 ». Heures fixes plutôt que « dans 30 min » : + * la prévision n'est relue que toutes les 10 min. + */ +fun rainSummary(slots: List): String? { + if (slots.isEmpty()) return null + val end = slots.last().startSec + 15 * 60 + return if (slots.first().raining) { + val stop = slots.firstOrNull { !it.raining } + if (stop == null) "Pluie pendant 2 h" else "Pluie jusqu'à ${hhmm(stop.startSec)}" + } else { + val start = slots.firstOrNull { it.raining } + if (start == null) "Sec jusqu'à ${hhmm(end)}" else "Pluie vers ${hhmm(start.startSec)}" + } } +/** Début de la prochaine pluie dans les 2 h (« 19:00 »), null s'il ne pleut pas ou déjà. */ +fun nextRain(slots: List): String? = + slots.takeUnless { it.firstOrNull()?.raining == true }?.firstOrNull { it.raining }?.let { hhmm(it.startSec) } + +internal fun hhmm(epochSec: Long): String = + SimpleDateFormat("HH:mm", Locale.FRANCE).apply { timeZone = TimeZone.getTimeZone("Europe/Brussels") } + .format(Date(epochSec * 1000)) + /** Codes météo WMO → (icône, libellé). */ private fun wmo(code: Int, day: Boolean): Pair = when (code) { 0 -> (if (day) "☀️" else "🌙") to "Ciel dégagé" diff --git a/app/src/main/java/be/lghs/lab/ui/InfoPanel.kt b/app/src/main/java/be/lghs/lab/ui/InfoPanel.kt index 834c164..7c8f469 100644 --- a/app/src/main/java/be/lghs/lab/ui/InfoPanel.kt +++ b/app/src/main/java/be/lghs/lab/ui/InfoPanel.kt @@ -8,7 +8,10 @@ import android.view.View import android.view.ViewGroup import be.lghs.lab.R import be.lghs.lab.data.Delivery +import be.lghs.lab.data.SpaceState import be.lghs.lab.data.Weather +import be.lghs.lab.data.nextRain +import be.lghs.lab.data.rainSummary import be.lghs.lab.databinding.PanelInfoBinding import java.text.SimpleDateFormat import java.util.Date @@ -49,10 +52,65 @@ class InfoPanel( b.clock.requestLayout() } + /** Feu tricolore : rouge, orange, vert ; seul le feu du statut actuel est allumé. */ + fun showSpace(state: SpaceState) { + val lit = when (state) { + SpaceState.CLOSED -> 0 + SpaceState.MEMBERS -> 1 + SpaceState.OPEN -> 2 + } + val label = when (state) { + SpaceState.CLOSED -> "Fermé" + SpaceState.MEMBERS -> "Membres" + SpaceState.OPEN -> "Ouvert" + } + // Pastille teintée de la couleur du statut ; seul le feu actuel est allumé + listOf(b.spaceLight0, b.spaceLight1, b.spaceLight2).forEachIndexed { i, light -> + light.backgroundTintList = ColorStateList.valueOf(if (i == lit) SPACE_LIGHTS[i] else LIGHT_OFF) + } + b.spaceLabel.text = label + b.spaceLabel.setTextColor(SPACE_LIGHTS[lit]) + b.spaceStatus.backgroundTintList = ColorStateList.valueOf((SPACE_LIGHTS[lit] and 0x00FFFFFF) or 0x33000000) + b.spaceStatus.visibility = View.VISIBLE + } + + private var weather: Weather? = null + private var weatherExpanded: Boolean? = null + fun showWeather(w: Weather) { + weather = w b.weatherIcon.text = w.icon b.weatherTemp.text = "${w.temperature.roundToInt()}°" - b.weatherDetails.text = "↓${w.min.roundToInt()}° ↑${w.max.roundToInt()}° · 💧${w.rainChance}%" + b.rainChart.show(w.rain) + b.rainSummary.text = rainSummary(w.rain).orEmpty() + b.rainSummary.setTextColor(context.getColor(if (w.rain.any { it.raining }) R.color.rain else R.color.text)) + renderWeatherDetails() + } + + /** + * Sans commande Deliveroo, la carte météo prend de la place : heure et température en plus + * grand, pluie des 2 prochaines heures. Avec une commande, une seule ligne comme avant. + */ + private fun setWeatherExpanded(expanded: Boolean) { + if (expanded == weatherExpanded) return + weatherExpanded = expanded + b.weatherRain.visibility = if (expanded) View.VISIBLE else View.GONE + b.weatherIcon.textSize = if (expanded) 38f else 30f + b.weatherTemp.textSize = if (expanded) 46f else 34f + b.clock.textSize = if (expanded) 60f else 42f + renderWeatherDetails() + } + + private fun renderWeatherDetails() { + val w = weather ?: return + val minMax = "↓${w.min.roundToInt()}° ↑${w.max.roundToInt()}°" + // Replié : la pluie tient en « 🌧 19:00 » (ou « 🌧 » s'il pleut déjà) + val rain = when { + weatherExpanded != false -> null + w.rain.firstOrNull()?.raining == true -> "🌧" + else -> nextRain(w.rain)?.let { "🌧 $it" } + } + b.weatherDetails.text = listOfNotNull(minMax, rain).joinToString(" · ") } private var delivery: Delivery? = null @@ -105,6 +163,7 @@ class InfoPanel( else -> !isStale(d, nowSec) } b.deliveryCard.visibility = if (visible) View.VISIBLE else View.GONE + setWeatherExpanded(!visible) if (!visible || d == null) { setNear(false) return @@ -170,6 +229,9 @@ class InfoPanel( const val STALE_SEC = 15 * 60L const val LEET_TIME = "13:37" const val LEET_GREEN = 0xFF39FF14.toInt() + /** Feu tricolore du statut : fermé, membres, ouvert. */ + val SPACE_LIGHTS = intArrayOf(0xFFFF4D4D.toInt(), 0xFFFFA726.toInt(), 0xFF5FD38D.toInt()) + const val LIGHT_OFF = 0x33FFFFFF const val DELIVERED_SHOWN_SEC = 15 * 60L const val KEY_DELIVERED_CODE = "delivered_code" const val KEY_DELIVERED_AT = "delivered_at" diff --git a/app/src/main/java/be/lghs/lab/ui/MusicPanel.kt b/app/src/main/java/be/lghs/lab/ui/MusicPanel.kt index 4ae95de..0132b94 100644 --- a/app/src/main/java/be/lghs/lab/ui/MusicPanel.kt +++ b/app/src/main/java/be/lghs/lab/ui/MusicPanel.kt @@ -1,11 +1,10 @@ package be.lghs.lab.ui import android.graphics.BitmapFactory -import android.graphics.RenderEffect -import android.graphics.Shader -import android.os.Build +import android.graphics.Bitmap import android.os.SystemClock import android.view.View +import android.widget.TextView import androidx.lifecycle.LifecycleCoroutineScope import be.lghs.lab.data.Http import be.lghs.lab.data.NowPlaying @@ -26,15 +25,10 @@ class MusicPanel(private val b: PanelMusicBinding, private val scope: LifecycleC init { // Fond flouté qui suit les coins arrondis de la carte b.root.clipToOutline = true - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - b.coverBg.setRenderEffect(RenderEffect.createBlurEffect(BLUR_PX, BLUR_PX, Shader.TileMode.CLAMP)) - } else { - b.coverBg.alpha = 0.15f // sans flou, juste une teinte discrète - } // Pochette carrée, calée sur la hauteur du panneau b.root.addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ -> val padding = b.musicContent.paddingTop + b.musicContent.paddingBottom - val size = minOf(bottom - top - padding, ((right - left) * 0.45f).toInt()) + val size = minOf(bottom - top - padding, ((right - left) * 0.40f).toInt()) val lp = b.cover.layoutParams if (lp.width != size || lp.height != size) { b.cover.post { b.cover.layoutParams = lp.apply { width = size; height = size } } @@ -55,11 +49,10 @@ class MusicPanel(private val b: PanelMusicBinding, private val scope: LifecycleC return } np!! - val source = listOfNotNull(np.source, np.format.takeIf { it.isNotEmpty() }).joinToString(" · ") - b.musicState.text = if (np.state == PlayState.PAUSE) "❚❚ En pause · $source" else "▶ $source" - b.musicTitle.text = np.title.ifEmpty { "—" } - b.musicArtist.text = np.artist - b.musicAlbum.text = np.album + b.musicState.text = if (np.state == PlayState.PAUSE) "❚❚ En pause · ${np.source}" else "▶ ${np.source}" + val title = np.title.ifEmpty { "—" } + setIfChanged(b.musicTitle, title) + setIfChanged(b.musicArtist, np.artist) b.musicContent.alpha = if (np.state == PlayState.PLAY) 1f else 0.6f loadCover(np.coverUrl) tick() @@ -68,14 +61,9 @@ class MusicPanel(private val b: PanelMusicBinding, private val scope: LifecycleC /** Avance la barre de progression entre deux événements MPD. */ fun tick() { val np = current - if (np != null && np.source != "moOde" && np.durationSec > 0) { - b.musicProgress.visibility = View.INVISIBLE - b.musicTime.text = mmss(np.durationSec) - return - } - if (np == null || np.durationSec <= 0) { - b.musicProgress.visibility = View.INVISIBLE - b.musicTime.text = "" + // Spotify, AirPlay, Deezer : moOde ne donne pas la position de lecture, pas de barre + if (np == null || np.source != "moOde" || np.durationSec <= 0) { + b.musicProgress.visibility = View.GONE return } val elapsed = if (np.state == PlayState.PLAY) { @@ -84,7 +72,6 @@ class MusicPanel(private val b: PanelMusicBinding, private val scope: LifecycleC val clamped = min(elapsed, np.durationSec) b.musicProgress.visibility = View.VISIBLE b.musicProgress.progress = (clamped / np.durationSec * 1000).toInt() - b.musicTime.text = "${mmss(clamped)} / ${mmss(np.durationSec)}" } private fun loadCover(url: String?) { @@ -95,23 +82,37 @@ class MusicPanel(private val b: PanelMusicBinding, private val scope: LifecycleC b.coverBg.setImageDrawable(null) if (url == null) return coverJob = scope.launch { - val bitmap = runCatching { + val (bitmap, blurred) = runCatching { val bytes = Http.get(url) { it.readBytes() } - withContext(Dispatchers.Default) { BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } - }.getOrNull() + withContext(Dispatchers.Default) { + val full = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + full to full?.let(::blur) + } + }.getOrNull() ?: (null to null) if (coverUrl == url) { b.cover.setImageBitmap(bitmap) - b.coverBg.setImageBitmap(bitmap) + b.coverBg.setImageBitmap(blurred) } } } + /** + * Flou calculé une fois par pochette : réduite à quelques pixels puis agrandie avec lissage. + * Un flou RenderEffect est recalculé par le GPU à chaque image (défilements, chrono) : la box + * tombait à ~6 images/s. + */ + private fun blur(source: Bitmap): Bitmap { + val tiny = Bitmap.createScaledBitmap(source, BLUR_TINY_PX, BLUR_TINY_PX, true) + return Bitmap.createScaledBitmap(tiny, BLUR_SMOOTH_PX, BLUR_SMOOTH_PX, true).also { tiny.recycle() } + } + private companion object { - const val BLUR_PX = 60f + const val BLUR_TINY_PX = 10 + const val BLUR_SMOOTH_PX = 80 } - private fun mmss(sec: Double): String { - val s = sec.toInt() - return "%d:%02d".format(s / 60, s % 60) + /** Réaffecter le même texte relancerait le défilement depuis le début ([TickerTextView]). */ + private fun setIfChanged(view: TextView, text: String) { + if (view.text.toString() != text) view.text = text } } diff --git a/app/src/main/java/be/lghs/lab/ui/RainChartView.kt b/app/src/main/java/be/lghs/lab/ui/RainChartView.kt new file mode 100644 index 0000000..f07c887 --- /dev/null +++ b/app/src/main/java/be/lghs/lab/ui/RainChartView.kt @@ -0,0 +1,66 @@ +package be.lghs.lab.ui + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.RectF +import android.util.AttributeSet +import android.util.TypedValue +import android.view.View +import be.lghs.lab.R +import be.lghs.lab.data.RainSlot +import be.lghs.lab.data.hhmm +import kotlin.math.min +import kotlin.math.sqrt + +/** + * Pluie des 2 prochaines heures : une barre par quart d'heure (hauteur selon les mm prévus), + * heures sous la barre toutes les 30 min. Redessinée seulement quand la prévision change. + */ +class RainChartView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : View(context, attrs) { + + private val density = resources.displayMetrics.density + private val barPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = context.getColor(R.color.rain) } + private val dryPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = DRY } + private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = context.getColor(R.color.text_dim) + textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 13f, resources.displayMetrics) + textAlign = Paint.Align.CENTER + } + private val rect = RectF() + private var slots: List = emptyList() + + fun show(rain: List) { + if (rain == slots) return + slots = rain + invalidate() + } + + override fun onDraw(canvas: Canvas) { + if (slots.isEmpty()) return + val labelHeight = labelPaint.textSize + 4 * density + val chartBottom = height - labelHeight + val gap = 4 * density + val barWidth = (width - gap * (slots.size - 1)) / slots.size + val radius = 3 * density + slots.forEachIndexed { i, slot -> + val left = i * (barWidth + gap) + // Racine : une petite pluie reste visible, une forte ne dépasse pas la carte + val level = sqrt(min(slot.mm / HEAVY_MM, 1.0)).toFloat() + val barHeight = if (slot.raining) maxOf(level * chartBottom, 6 * density) else 3 * density + rect.set(left, chartBottom - barHeight, left + barWidth, chartBottom) + canvas.drawRoundRect(rect, radius, radius, if (slot.raining) barPaint else dryPaint) + // Heure au début de chaque demi-heure + if (i % 2 == 0) canvas.drawText(hhmm(slot.startSec), left + barWidth / 2, height - 2 * density, labelPaint) + } + } + + private companion object { + /** mm par quart d'heure pour une barre pleine (4 mm/h : forte pluie). */ + const val HEAVY_MM = 1.0 + const val DRY = 0x33FFFFFF + } +} diff --git a/app/src/main/java/be/lghs/lab/ui/TickerTextView.kt b/app/src/main/java/be/lghs/lab/ui/TickerTextView.kt new file mode 100644 index 0000000..ed30028 --- /dev/null +++ b/app/src/main/java/be/lghs/lab/ui/TickerTextView.kt @@ -0,0 +1,64 @@ +package be.lghs.lab.ui + +import android.content.Context +import android.graphics.Canvas +import android.util.AttributeSet +import androidx.appcompat.widget.AppCompatTextView + +/** + * Texte sur une ligne qui défile comme un bandeau s'il ne tient pas : pause au début, sortie + * complète par la gauche, puis retour par la droite. Contrairement au marquee Android, pas de + * retour brusque au début, même quand le texte dépasse de peu. + */ +class TickerTextView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : AppCompatTextView(context, attrs) { + + private val speedPxPerSec = SPEED_DP_PER_SEC * resources.displayMetrics.density + private var startNs = 0L + + init { + setSingleLine(true) + ellipsize = null + setHorizontallyScrolling(true) + } + + override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) { + super.onTextChanged(text, start, lengthBefore, lengthAfter) + startNs = 0L // nouveau texte : on repart de la pause au début + } + + override fun onDraw(canvas: Canvas) { + val layout = layout + val available = width - compoundPaddingLeft - compoundPaddingRight + val textWidth = layout?.getLineWidth(0) ?: 0f + if (layout == null || textWidth <= available) { + super.onDraw(canvas) + return + } + val now = System.nanoTime() + if (startNs == 0L) startNs = now + val travel = (textWidth + available) / speedPxPerSec + val t = ((now - startNs) / 1e9f) % (PAUSE_SEC + travel) + // Décalage du texte vers la gauche : 0 → sortie complète, puis entrée depuis le bord droit + val offset = if (t < PAUSE_SEC) 0f else { + val d = (t - PAUSE_SEC) * speedPxPerSec + if (d < textWidth) d else d - textWidth - available + } + + canvas.save() + canvas.clipRect(compoundPaddingLeft, 0, width - compoundPaddingRight, height) + canvas.translate(compoundPaddingLeft - offset, extendedPaddingTop.toFloat()) + paint.color = currentTextColor + paint.drawableState = drawableState + layout.draw(canvas) + canvas.restore() + postInvalidateOnAnimation() + } + + private companion object { + const val SPEED_DP_PER_SEC = 40f + const val PAUSE_SEC = 2.5f + } +} diff --git a/app/src/main/java/be/lghs/lab/ui/TransportPanel.kt b/app/src/main/java/be/lghs/lab/ui/TransportPanel.kt index aeca0bc..7fea7f7 100644 --- a/app/src/main/java/be/lghs/lab/ui/TransportPanel.kt +++ b/app/src/main/java/be/lghs/lab/ui/TransportPanel.kt @@ -11,8 +11,11 @@ import androidx.core.text.inSpans import androidx.lifecycle.LifecycleCoroutineScope import be.lghs.lab.R import be.lghs.lab.data.BusDeparture +import be.lghs.lab.data.Reach import be.lghs.lab.data.TrainBoard import be.lghs.lab.data.TrainRoute +import be.lghs.lab.data.TravelMode +import be.lghs.lab.data.reach import be.lghs.lab.databinding.PanelTransportBinding import be.lghs.lab.databinding.RowDepartureBinding import kotlinx.coroutines.android.awaitFrame @@ -39,6 +42,7 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou /** Une ligne de la liste, bus ou train. */ private class Row( + /** Heure de départ réelle (retard compris), pour le chrono et l'heure affichée. */ val epochSec: Long, val line: String, val isTrain: Boolean, @@ -47,6 +51,13 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou val delaySec: Int, val canceled: Boolean, val last: Boolean, + /** Minutes à pied jusqu'au quai ou à la gare, null = inconnu. */ + val minutesFromSpace: Int?, + val travelMode: TravelMode, + /** Trajet SNCB (« from|to »), pour retrouver le train suivant d'un train supprimé. */ + val route: String? = null, + /** Train supprimé : heure du suivant sur le même trajet, affiché juste en dessous. */ + val nextSec: Long? = null, ) private var buses: List = emptyList() @@ -54,8 +65,14 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou private var busError: String? = null private var trainError: String? = null - /** Derniers trains reçus par trajet, avec l'heure de réception. */ - private val trainBoards = mutableMapOf>() + /** Derniers trains reçus par trajet (gare de départ, d'arrivée), avec l'heure de réception. */ + private val trainBoards = mutableMapOf, Pair>() + + /** Trajets de la config actuelle (temps d'accès compris), connus après la première lecture. */ + private var trainRoutes: Map, TrainRoute> = emptyMap() + + /** À sauver sur la box ([be.lghs.lab.data.TrainCache]). */ + val savedTrains: List> get() = trainBoards.values.toList() /** Nombre de vues de la liste « originale » (avant le repère et la copie). */ private var listLength = 0 @@ -68,7 +85,8 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou fun showBuses(list: List, nowSec: Long) { buses = list.map { Row(it.epochSec, it.line, false, it.destination.ifEmpty { "Ligne ${it.line}" }, it.stop, - it.delaySec, canceled = false, last = it.last) + it.delaySec, canceled = false, last = it.last, minutesFromSpace = it.minutesFromSpace, + travelMode = it.travelMode) } busError = null render(nowSec) @@ -84,24 +102,44 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou * en échec garde ses derniers trains, et on ne le signale qu'après [TRAIN_STALE_SEC]. */ fun showTrains(results: Map, nowSec: Long) { - trainBoards.keys.retainAll(results.keys) // trajet retiré de transport.json - results.forEach { (route, board) -> if (board != null) trainBoards[route] = board to nowSec } - val missing = results.keys.any { it !in trainBoards } + trainRoutes = results.keys.associateBy(::key) + trainBoards.keys.retainAll(trainRoutes.keys) // trajet retiré de transport.json + results.forEach { (route, board) -> if (board != null) trainBoards[key(route)] = board to nowSec } + val missing = trainRoutes.keys.any { it !in trainBoards } val oldest = trainBoards.values.minOfOrNull { it.second } trainError = when { missing -> "SNCB indisponible" oldest != null && nowSec - oldest >= TRAIN_STALE_SEC -> "SNCB : pas à jour depuis ${hhmm.format(Date(oldest * 1000))}" else -> null } - trains = trainBoards.values.flatMap { (board, _) -> - board.departures.map { - Row(it.epochSec, it.line, true, board.route.to, - stationAndPlatform(board.route.from, it.platform), it.delaySec, it.canceled, it.last) + buildTrainRows() + render(nowSec) + } + + /** Trains gardés sur la box, affichés en attendant la première réponse d'iRail. */ + fun restoreTrains(saved: List>, nowSec: Long) { + saved.forEach { trainBoards[key(it.first.route)] = it } + buildTrainRows() + render(nowSec) + } + + private fun buildTrainRows() { + trains = trainBoards.flatMap { (key, entry) -> + val board = entry.first + val route = trainRoutes[key] ?: board.route + board.departures.mapIndexed { i, d -> + // iRail donne l'heure prévue : on affiche l'heure réelle, comme pour les bus + val next = if (d.canceled) board.departures.drop(i + 1).firstOrNull { !it.canceled } else null + Row(d.epochSec + d.delaySec, d.line, true, route.to, + stationAndPlatform(route.from, d.platform), d.delaySec, d.canceled, d.last, + route.minutesFromSpace, route.travelMode, + route = "${route.from}|${route.to}", nextSec = next?.let { it.epochSec + it.delaySec }) } } - render(nowSec) } + private fun key(route: TrainRoute) = route.from to route.to + /** * Recalcule la liste (minutes restantes comprises) sans refaire de requête. * Pour le défilement infini, la liste est suivie d'un repère « début de la liste » @@ -110,11 +148,15 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou fun render(nowSec: Long) { val container = b.departureRows container.removeAllViews() - val rows = (buses + trains).filter { it.epochSec >= nowSec - 30 }.sortedBy { it.epochSec } + val rows = ordered((buses + trains) + .filter { it.epochSec >= nowSec - 30 } + // Départs qu'on n'a plus le temps d'attraper depuis le space : masqués + .filter { reach(it.epochSec, nowSec, it.minutesFromSpace) != Reach.TOO_LATE } + .sortedBy { it.epochSec }) val messages = listOfNotNull(busError, trainError) .ifEmpty { if (rows.isEmpty()) listOf("Aucun départ") else emptyList() } fun addList() { - rows.forEach { container.addView(bind(it, nowSec)) } + rows.forEach { (row, replacement) -> container.addView(bind(row, nowSec, replacement)) } messages.forEach { container.addView(placeholder(it)) } } addList() @@ -126,6 +168,21 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou applyLoopVisibility() } + /** + * Ordre chronologique, sauf le train qui suit un train supprimé (même trajet) : remonté + * juste sous lui, marqué comme remplaçant. + */ + private fun ordered(rows: List): List> { + val replacements = rows.filter { it.canceled && it.nextSec != null }.mapNotNull { canceled -> + rows.firstOrNull { it.route == canceled.route && it.epochSec == canceled.nextSec && !it.canceled } + ?.let { canceled to it } + }.toMap() + val moved = replacements.values.toSet() + return rows.filter { it !in moved }.flatMap { row -> + listOfNotNull(row to false, replacements[row]?.let { it to true }) + } + } + private fun applyLoopVisibility() { val container = b.departureRows for (i in listLength until container.childCount) { @@ -133,8 +190,13 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou } } - private fun bind(row: Row, nowSec: Long): View { + private fun bind(row: Row, nowSec: Long, replacement: Boolean = false): View { val v = RowDepartureBinding.inflate(inflater, b.departureRows, false) + // Train suivant d'un train supprimé : « ↳ » et léger retrait, sous la ligne barrée + if (replacement) { + v.replaces.visibility = View.VISIBLE + v.root.setPaddingRelative((REPLACEMENT_INDENT_DP * context.resources.displayMetrics.density).toInt(), 0, 0, 0) + } v.line.text = row.line // Tram TEC (T1…) en orange, pour le distinguer des bus jaunes val badge = when { @@ -158,19 +220,33 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou val minutes = ((row.epochSec - nowSec) / 60.0).roundToInt() v.time.text = when { minutes <= 0 -> "à quai" - minutes < 30 -> "$minutes min" - else -> hhmm.format(Date(row.epochSec * 1000)) + minutes < 60 -> "$minutes min" + else -> "%d h %02d".format(minutes / 60, minutes % 60) } + // Heure de départ réelle (retard compris), toujours affichée + v.clock.text = hhmm.format(Date(row.epochSec * 1000)) + // Avec le temps pour y aller : jaune s'il faut partir maintenant, vert sinon (ceux qu'on + // ne peut plus attraper sont masqués, le rouge ne sert qu'entre deux rafraîchissements) + val reach = reach(row.epochSec, nowSec, row.minutesFromSpace) v.time.setTextColor( when { row.canceled -> late - minutes <= 2 -> accent + reach == Reach.TOO_LATE -> late + reach == Reach.HURRY -> accent + reach == null && minutes <= 2 -> accent minutes < 30 -> onTime else -> text } ) + // À pied ou à vélo, de la couleur du chrono + if (reach != null && !row.canceled) { + v.travelMode.setImageResource(if (row.travelMode == TravelMode.BIKE) R.drawable.ic_bike else R.drawable.ic_walk) + v.travelMode.imageTintList = android.content.res.ColorStateList.valueOf(v.time.currentTextColor) + v.travelMode.visibility = View.VISIBLE + } if (row.canceled) { v.time.paintFlags = v.time.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + v.clock.paintFlags = v.clock.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG v.destination.alpha = 0.5f } return v.root @@ -257,5 +333,6 @@ class TransportPanel(private val b: PanelTransportBinding, scope: LifecycleCorou const val PAUSE_NS = 3_000_000_000L const val IDLE_CHECK_MS = 1_000L const val TRAIN_STALE_SEC = 5 * 60L + const val REPLACEMENT_INDENT_DP = 20 } } diff --git a/app/src/main/res/drawable/ic_bike.xml b/app/src/main/res/drawable/ic_bike.xml new file mode 100644 index 0000000..4b453f0 --- /dev/null +++ b/app/src/main/res/drawable/ic_bike.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_walk.xml b/app/src/main/res/drawable/ic_walk.xml new file mode 100644 index 0000000..097387b --- /dev/null +++ b/app/src/main/res/drawable/ic_walk.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/app/src/main/res/drawable/light_dot.xml b/app/src/main/res/drawable/light_dot.xml new file mode 100644 index 0000000..90f9729 --- /dev/null +++ b/app/src/main/res/drawable/light_dot.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/drawable/music_scrim.xml b/app/src/main/res/drawable/music_scrim.xml new file mode 100644 index 0000000..51ae41d --- /dev/null +++ b/app/src/main/res/drawable/music_scrim.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/app/src/main/res/layout/panel_info.xml b/app/src/main/res/layout/panel_info.xml index 71cfe72..8750260 100644 --- a/app/src/main/res/layout/panel_info.xml +++ b/app/src/main/res/layout/panel_info.xml @@ -4,16 +4,22 @@ android:layout_height="match_parent" android:orientation="vertical"> - + + + + + + + + + + + + + + + + + + + + + + + + + + + android:textColor="@color/text_dim" + android:textSize="13sp" /> - - - - + android:textSize="24sp" /> - - diff --git a/app/src/main/res/layout/row_departure.xml b/app/src/main/res/layout/row_departure.xml index b6b61da..73eb217 100644 --- a/app/src/main/res/layout/row_departure.xml +++ b/app/src/main/res/layout/row_departure.xml @@ -5,6 +5,17 @@ android:gravity="center_vertical" android:orientation="horizontal"> + + + + + + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 34d9e58..3e140dd 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -12,5 +12,6 @@ #5FD38D #F5C518 #FF7A1A + #4FA3FF #2F6FD6 diff --git a/app/src/test/java/be/lghs/lab/data/RainTest.kt b/app/src/test/java/be/lghs/lab/data/RainTest.kt new file mode 100644 index 0000000..32e0c2e --- /dev/null +++ b/app/src/test/java/be/lghs/lab/data/RainTest.kt @@ -0,0 +1,43 @@ +package be.lghs.lab.data + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** 2 h à partir de 18:30 (heure belge, le 20/11/2026). */ +class RainTest { + private val start = 1795195800L // 2026-11-20 18:30 + + private fun slots(vararg mm: Double) = mm.mapIndexed { i, v -> RainSlot(start + i * 15 * 60L, v) } + + @Test + fun dry() { + val s = slots(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + assertEquals("Sec jusqu'à 20:30", rainSummary(s)) + assertNull(nextRain(s)) + } + + @Test + fun rainLater() { + val s = slots(0.0, 0.0, 0.3, 0.5, 0.0, 0.0, 0.0, 0.0) + assertEquals("Pluie vers 19:00", rainSummary(s)) + assertEquals("19:00", nextRain(s)) + } + + @Test + fun rainingNow() { + val s = slots(0.2, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + assertEquals("Pluie jusqu'à 19:00", rainSummary(s)) + assertNull(nextRain(s)) + } + + @Test + fun rainingAllTheTime() { + assertEquals("Pluie pendant 2 h", rainSummary(slots(0.2, 0.1, 0.4, 0.3, 0.2, 0.1, 0.2, 0.1))) + } + + @Test + fun noForecast() { + assertNull(rainSummary(emptyList())) + } +} diff --git a/app/src/test/java/be/lghs/lab/data/ReachTest.kt b/app/src/test/java/be/lghs/lab/data/ReachTest.kt new file mode 100644 index 0000000..5bb19ad --- /dev/null +++ b/app/src/test/java/be/lghs/lab/data/ReachTest.kt @@ -0,0 +1,51 @@ +package be.lghs.lab.data + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** Quai à 5 min à pied du space. */ +class ReachTest { + private val now = 1_000_000L + + private fun reachIn(seconds: Long) = reach(now + seconds, now, minutesFromSpace = 5) + + @Test + fun tooLateBeforeWalkingTime() { + assertEquals(Reach.TOO_LATE, reachIn(0)) + assertEquals(Reach.TOO_LATE, reachIn(4 * 60 + 59)) + } + + @Test + fun hurryJustAfterWalkingTime() { + assertEquals(Reach.HURRY, reachIn(5 * 60)) + assertEquals(Reach.HURRY, reachIn(6 * 60 + 59)) + } + + @Test + fun okWithMargin() { + assertEquals(Reach.OK, reachIn(7 * 60)) + } + + @Test + fun unknownWithoutWalkingTime() { + assertNull(reach(now + 60, now, minutesFromSpace = null)) + } + + @Test + fun walkingTimeReadFromStop() { + val stop = TecStop("Llgsime1", "Simenon", mapOf("11" to "Liège Expo"), minutesFromSpace = 3) + val trip = "t" + val config = TransportConfig( + tecWindowMinutes = 15, + tecStops = listOf(stop), + trainRoutes = emptyList(), + trainsPerRoute = 3, + schedule = mapOf(trip to listOf(ScheduledStop("Llgsime1", 1, 13 * 3600 + 15 * 60))), + lastTrips = emptySet(), + ) + val feed = listOf(RtTrip(trip, "L0011-1", "20261120", false, 60, emptyList())) + val nowSec = 1795176660L // 2026-11-20 13:11:00 heure belge + assertEquals(3, TecRepository().departures(config, feed, nowSec, nowSec + 15 * 60).single().minutesFromSpace) + } +} diff --git a/app/src/test/java/be/lghs/lab/data/SpaceApiTest.kt b/app/src/test/java/be/lghs/lab/data/SpaceApiTest.kt new file mode 100644 index 0000000..2abd6a4 --- /dev/null +++ b/app/src/test/java/be/lghs/lab/data/SpaceApiTest.kt @@ -0,0 +1,18 @@ +package be.lghs.lab.data + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SpaceApiTest { + private fun state(open: Boolean, visitors: Boolean) = + SpaceApiRepository.parse("""{"space":"LgHS","state":{"open":$open,"open_to_visitors":$visitors}}""") + + @Test + fun open() = assertEquals(SpaceState.OPEN, state(open = true, visitors = true)) + + @Test + fun membersOnly() = assertEquals(SpaceState.MEMBERS, state(open = true, visitors = false)) + + @Test + fun closed() = assertEquals(SpaceState.CLOSED, state(open = false, visitors = false)) +} diff --git a/app/src/test/java/be/lghs/lab/data/TrainCacheTest.kt b/app/src/test/java/be/lghs/lab/data/TrainCacheTest.kt new file mode 100644 index 0000000..df05734 --- /dev/null +++ b/app/src/test/java/be/lghs/lab/data/TrainCacheTest.kt @@ -0,0 +1,20 @@ +package be.lghs.lab.data + +import org.junit.Assert.assertEquals +import org.junit.Test + +class TrainCacheTest { + @Test + fun roundTrip() { + val board = TrainBoard( + TrainRoute("Liège-Saint-Lambert", "Nessonvaux"), + listOf( + TrainDeparture(1795190400, 120, "S41", "2", canceled = false, last = false), + TrainDeparture(1795194000, 0, "S41", "?", canceled = true, last = true), + ), + ) + val (restored, received) = TrainCache.decode(TrainCache.encode(listOf(board to 1795190000L))).single() + assertEquals(board, restored) + assertEquals(1795190000L, received) + } +} diff --git a/dashboard/transport.json b/dashboard/transport.json index adb6589..26f4aae 100644 --- a/dashboard/transport.json +++ b/dashboard/transport.json @@ -1,12 +1,13 @@ { "_doc": "Départs affichés par le tableau de bord LgHS. Modifier puis pousser : la GitHub Action régénère les horaires TEC, l'app se met à jour dans l'heure.", "tec": { - "_doc": "Quais TEC (stop_id GTFS ; un quai = un sens). Ordre = priorité : un bus passant par plusieurs quais est affiché au premier où sa ligne est listée. lines : lignes affichées à ce quai → libellé de destination ; une ligne absente n'est pas affichée à ce quai.", + "_doc": "Quais TEC (stop_id GTFS ; un quai = un sens). Ordre = priorité : un bus passant par plusieurs quais est affiché au premier où sa ligne est listée. lines : lignes affichées à ce quai → libellé de destination ; une ligne absente n'est pas affichée à ce quai. minutesFromSpace : minutes pour aller du space au quai à pied (itinéraire OpenStreetMap, arrondi au-dessus). travelMode : \"bike\" pour un trajet à vélo (à pied par défaut), picto à côté du chrono. Chrono du départ : rouge = trop tard pour l'attraper, jaune = partir maintenant, vert = on a le temps.", "windowMinutes": 15, "stops": [ { "id": "L2Tcurt2", "name": "Curtius", + "minutesFromSpace": 12, "lines": { "T1": "Coronmeuse" } @@ -14,6 +15,7 @@ { "id": "Llgsime1", "name": "Simenon", + "minutesFromSpace": 3, "lines": { "11": "Liège Expo" } @@ -21,6 +23,7 @@ { "id": "Llgsime2", "name": "Simenon", + "minutesFromSpace": 3, "lines": { "11": "Rocourt" } @@ -28,6 +31,7 @@ { "id": "Llgongr3", "name": "Congrès", + "minutesFromSpace": 3, "lines": { "11": "Liège Expo" } @@ -35,6 +39,7 @@ { "id": "Llgongr1", "name": "Congrès", + "minutesFromSpace": 3, "lines": { "6": "Coronmeuse" } @@ -42,6 +47,7 @@ { "id": "Llgongr2", "name": "Congrès", + "minutesFromSpace": 3, "lines": { "6": "Guillemins" } @@ -49,6 +55,7 @@ { "id": "Llgongr4", "name": "Congrès", + "minutesFromSpace": 4, "lines": { "11": "Rocourt" } @@ -56,6 +63,7 @@ { "id": "Llgbavi3", "name": "Bavière", + "minutesFromSpace": 3, "lines": { "38": "Grivegnée" } @@ -63,6 +71,7 @@ { "id": "Llgbavi4", "name": "Bavière", + "minutesFromSpace": 3, "lines": { "38": "Fond des Tawes", "33": "Milmort", @@ -72,6 +81,7 @@ { "id": "Llgoutr1", "name": "Outremeuse", + "minutesFromSpace": 5, "lines": { "6": "Coronmeuse" } @@ -79,6 +89,7 @@ { "id": "Llgoutr2", "name": "Outremeuse", + "minutesFromSpace": 5, "lines": { "6": "Guillemins" } @@ -86,6 +97,7 @@ { "id": "Llgbavi1", "name": "Bavière", + "minutesFromSpace": 4, "lines": { "6": "Coronmeuse" } @@ -93,6 +105,7 @@ { "id": "Llgoutr3", "name": "Outremeuse", + "minutesFromSpace": 6, "lines": { "4": "Léopold", "24": "Léopold" @@ -101,6 +114,7 @@ { "id": "Llgtcha2", "name": "Tchantchès", + "minutesFromSpace": 6, "lines": { "4": "Léopold", "24": "Léopold" @@ -109,6 +123,7 @@ { "id": "Llgbavi0", "name": "Bavière", + "minutesFromSpace": 5, "lines": { "6": "Guillemins", "39": "Vottem P+R" @@ -117,6 +132,7 @@ { "id": "Llgtcha1", "name": "Tchantchès", + "minutesFromSpace": 6, "lines": { "4": "Fléron", "24": "Jupille" @@ -125,16 +141,19 @@ ] }, "sncb": { - "_doc": "Trains directs entre deux gares (noms iRail : https://api.irail.be/stations/?format=json&lang=fr).", + "_doc": "Trains directs entre deux gares (noms iRail : https://api.irail.be/stations/?format=json&lang=fr). minutesFromSpace : minutes pour aller du space à la gare de départ (Saint-Lambert à pied, Guillemins à vélo, le vélo monte dans le train : 16 min d'itinéraire OpenStreetMap).", "departuresPerRoute": 3, "routes": [ { "from": "Liège-Saint-Lambert", - "to": "Nessonvaux" + "to": "Nessonvaux", + "minutesFromSpace": 20 }, { "from": "Liège-Guillemins", - "to": "Welkenraedt" + "to": "Welkenraedt", + "minutesFromSpace": 16, + "travelMode": "bike" } ] }