From e8e7b225d0a8db8f5112571d011888de18ef98ae Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 12:18:20 +0100 Subject: [PATCH 01/12] build(app): Prepare Android build 2 for production --- app/android/app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 3f6e203d..361f77cf 100644 --- a/app/android/app/build.gradle +++ b/app/android/app/build.gradle @@ -20,7 +20,7 @@ android { targetSdkVersion rootProject.ext.targetSdkVersion // Google Play takes every versionCode once: raise it for each upload. // The client comes from the server, so this only changes with the native shell. - versionCode 1 + versionCode 2 versionName "0.1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { From 33ee2f81971437bb980e9eaebe68f2fa26aba603 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 14:02:04 +0100 Subject: [PATCH 02/12] feat(app): Identify app releases in aggregate server metrics --- app/android/app/build.gradle | 5 +- .../java/com/openradlr/app/MainActivity.java | 13 +- app/ios/App/App/WebAuthPlugin.swift | 12 ++ docs/app.md | 44 +++++ docs/deploy.md | 9 + server/crates/server/src/app.rs | 1 + server/crates/server/src/client_requests.rs | 155 ++++++++++++++++++ server/crates/server/src/http.rs | 26 ++- server/crates/server/src/lib.rs | 1 + server/crates/server/tests/websocket_flow.rs | 51 ++++++ 10 files changed, 312 insertions(+), 5 deletions(-) create mode 100644 server/crates/server/src/client_requests.rs diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 361f77cf..13fa1cc8 100644 --- a/app/android/app/build.gradle +++ b/app/android/app/build.gradle @@ -13,6 +13,9 @@ def uploadStoreFile = uploadKey('storeFile', 'OPENRADLR_UPLOAD_STORE_FILE') android { namespace = "com.openradlr.app" + buildFeatures { + buildConfig true + } compileSdk = rootProject.ext.compileSdkVersion defaultConfig { applicationId "com.openradlr.app" @@ -20,7 +23,7 @@ android { targetSdkVersion rootProject.ext.targetSdkVersion // Google Play takes every versionCode once: raise it for each upload. // The client comes from the server, so this only changes with the native shell. - versionCode 2 + versionCode 3 versionName "0.1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { diff --git a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java index 062ea71e..c09ab12a 100644 --- a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java +++ b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java @@ -1,5 +1,16 @@ package com.openradlr.app; +import android.webkit.WebView; import com.getcapacitor.BridgeActivity; -public class MainActivity extends BridgeActivity {} +public class MainActivity extends BridgeActivity { + @Override + protected void load() { + // Set this before the bridge loads its first page, including that first request. + // Use the built package's version; syncing Capacitor must not freeze an old build number. + WebView webView = findViewById(com.getcapacitor.android.R.id.webview); + String suffix = " OpenRadlr/" + BuildConfig.VERSION_NAME + " (android; build/" + BuildConfig.VERSION_CODE + ")"; + webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + suffix); + super.load(); + } +} diff --git a/app/ios/App/App/WebAuthPlugin.swift b/app/ios/App/App/WebAuthPlugin.swift index 706c68f7..6212c7f4 100644 --- a/app/ios/App/App/WebAuthPlugin.swift +++ b/app/ios/App/App/WebAuthPlugin.swift @@ -1,9 +1,21 @@ import AuthenticationServices import Capacitor import UIKit +import WebKit /// The app's web view with the app's own plugins registered. class AppViewController: CAPBridgeViewController { + override open func webViewConfiguration(for instanceConfiguration: InstanceConfiguration) -> WKWebViewConfiguration { + let configuration = super.webViewConfiguration(for: instanceConfiguration) + // Configure before the first navigation; these are release facts, not a device identifier. + let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown" + let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0" + let suffix = "OpenRadlr/\(version) (ios; build/\(build))" + configuration.applicationNameForUserAgent = [configuration.applicationNameForUserAgent, suffix] + .compactMap { $0 }.joined(separator: " ") + return configuration + } + override open func capacitorDidLoad() { bridge?.registerPluginInstance(WebAuthPlugin()) } diff --git a/docs/app.md b/docs/app.md index 0141311f..8a6af38e 100644 --- a/docs/app.md +++ b/docs/app.md @@ -245,3 +245,47 @@ description. website (rule 4.2). Native Bluetooth is the argument; expect questions. - The app icon is scaled up from the 512 px maskable icon, the largest master in the repo. A 1024 px original would look sharper on the App Store. + +## App release information on requests + +The native web view appends its platform and the installed package's version and +build number to the standard HTTP user agent. For example: + +```text +OpenRadlr/0.1.0 (android; build/3) +OpenRadlr/1.0 (ios; build/1) +``` + +This is set before the first navigation and also accompanies the web view's API +requests and WebSocket upgrade. It describes the native shell; `client_version` +in the WebSocket protocol continues to describe the web client served by the +server. A client can forge a user agent, so it is not an authentication signal. + +The server exports `openradlr_client_requests_total` on its existing +`/internal/metrics` endpoint, grouped by `client` (`android`, `ios`, or `browser`), +`app_version` and `app_build`. The `browser` bucket also includes older app builds +without the marker and requests with an invalid marker. Health checks and metrics +scrapes are excluded. WebSocket upgrades count as HTTP requests; individual +WebSocket messages do not. + +These are request totals, not unique users, installations or sessions. The +counter keeps no raw user agents, IP addresses, device identifiers, rider names, +request paths or individual request records. It lives in memory and resets when +the server restarts. At most 32 app release combinations have separate counters; +additional combinations share an `other` version/build bucket per platform, so +untrusted headers cannot create unlimited metric series. Keep the endpoint on +the host's private monitoring network as described in [Deployment](deploy.md). + +Example PromQL for a dashboard connected to the endpoint: + +```promql +sum by (client) (rate(openradlr_client_requests_total[5m])) +``` + +Requests by Android release over the last day: + +```promql +sum by (app_version, app_build) ( + increase(openradlr_client_requests_total{client="android"}[24h]) +) +``` diff --git a/docs/deploy.md b/docs/deploy.md index 48de3ef3..d04228be 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -247,3 +247,12 @@ read-only, so a new file only needs `make restart`. See [routes](routes.md). For a server without a reverse proxy, the bundled Caddy can handle TLS: `COMPOSE_PROFILES=tls` and `OPENRADLR_DOMAIN=ride.example.org` in `.env` (ports 80 and 443 must be reachable). + +### Requests by native app release + +The private `/internal/metrics` endpoint also exports +`openradlr_client_requests_total{client,app_version,app_build}`. This aggregate +counter helps compare native app releases and diagnose release-specific issues. +It excludes health and scrape requests and does not estimate unique people or +devices. See [App release information](app.md#app-release-information-on-requests) +for label limits, compatibility with older app builds and example PromQL. diff --git a/server/crates/server/src/app.rs b/server/crates/server/src/app.rs index 50fbf649..135c51bd 100644 --- a/server/crates/server/src/app.rs +++ b/server/crates/server/src/app.rs @@ -325,6 +325,7 @@ pub fn build_with_stats(config: &Config) -> Result<(Router, DistanceStats), BoxE }; let state = AppState { + client_requests: crate::client_requests::ClientRequests::default(), worlds: Arc::new(worlds), maps: Arc::new(maps), info, diff --git a/server/crates/server/src/client_requests.rs b/server/crates/server/src/client_requests.rs new file mode 100644 index 00000000..b2c6af0f --- /dev/null +++ b/server/crates/server/src/client_requests.rs @@ -0,0 +1,155 @@ +//! Aggregate request counts by app platform and release; no request or rider records. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +// User agents are untrusted: a client must not create unbounded metric labels. +const MAX_RELEASES: usize = 32; + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Release { + client: &'static str, + version: String, + build: String, +} + +impl Release { + fn browser() -> Self { + Self { + client: "browser", + version: String::new(), + build: String::new(), + } + } + + fn parse(agent: &str) -> Option { + let (prefix, suffix) = agent.split_once("OpenRadlr/")?; + if !prefix.is_empty() && !prefix.ends_with(char::is_whitespace) { + return None; + } + let (version, suffix) = suffix.split_once(" (")?; + let (platform, build) = suffix.trim_end().strip_suffix(')')?.split_once("; build/")?; + let client = match platform { + "android" => "android", + "ios" => "ios", + _ => return None, + }; + if version.is_empty() + || !version.as_bytes()[0].is_ascii_digit() + || version.len() > 32 + || !version + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) + || build.is_empty() + || build.len() > 10 + || !build.bytes().all(|b| b.is_ascii_digit()) + { + return None; + } + Some(Self { + client, + version: version.into(), + build: build.into(), + }) + } +} + +/// Shared only inside one server process; counts requests, not people or devices. +#[derive(Clone, Default)] +pub struct ClientRequests(Arc>>); + +impl ClientRequests { + pub fn record(&self, user_agent: Option<&str>) { + let mut release = user_agent.and_then(Release::parse).unwrap_or_else(Release::browser); + let mut counts = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if release.client != "browser" + && !counts.contains_key(&release) + && counts + .keys() + .filter(|r| r.client != "browser" && r.version != "other") + .count() + >= MAX_RELEASES + { + release.version = "other".into(); + release.build = "other".into(); + } + let count = counts.entry(release).or_default(); + *count = count.saturating_add(1); + } + + pub fn metrics(&self) -> String { + use std::fmt::Write; + let counts = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let mut output = String::from("# HELP openradlr_client_requests_total HTTP requests by client platform and app release since server start, excluding health and metrics probes.\n# TYPE openradlr_client_requests_total counter\n"); + for (release, count) in counts.iter() { + // The parser permits only label-safe ASCII; the full user agent is never kept. + writeln!( + output, + "openradlr_client_requests_total{{client=\"{}\",app_version=\"{}\",app_build=\"{}\"}} {}", + release.client, release.version, release.build, count + ) + .expect("write to String"); + } + output + } +} + +#[cfg(test)] +mod tests { + use super::ClientRequests; + + #[test] + fn requests_from_the_same_app_release_share_one_counter() { + let stats = ClientRequests::default(); + stats.record(Some("Mozilla/5.0 OpenRadlr/0.1.0 (android; build/3)")); + stats.record(Some("A different WebView OpenRadlr/0.1.0 (android; build/3)")); + assert!(stats + .metrics() + .contains("client=\"android\",app_version=\"0.1.0\",app_build=\"3\"} 2\n")); + } + + #[test] + fn ios_and_android_are_separate_release_counters() { + let stats = ClientRequests::default(); + stats.record(Some("Mozilla/5.0 OpenRadlr/1.0 (ios; build/1)")); + stats.record(Some("Mozilla/5.0 OpenRadlr/1.0 (android; build/1)")); + assert!(stats + .metrics() + .contains("client=\"ios\",app_version=\"1.0\",app_build=\"1\"} 1\n")); + assert!(stats + .metrics() + .contains("client=\"android\",app_version=\"1.0\",app_build=\"1\"} 1\n")); + } + + #[test] + fn unmarked_and_malformed_requests_do_not_create_app_labels() { + let stats = ClientRequests::default(); + for agent in [ + None, + Some("Mozilla/5.0 (Android; wv)"), + Some("NotOpenRadlr/0.1.0 (android; build/3)"), + Some("OpenRadlr/evil\"label (android; build/3)"), + Some("OpenRadlr/0.1.0 (android; build/not-a-number)"), + Some("OpenRadlr/other (android; build/1)"), + ] { + stats.record(agent); + } + assert!(stats + .metrics() + .contains("client=\"browser\",app_version=\"\",app_build=\"\"} 6\n")); + assert!(!stats.metrics().contains("evil")); + assert!(!stats.metrics().contains("Mozilla")); + } + + #[test] + fn release_cardinality_is_bounded_even_for_valid_forged_versions() { + let stats = ClientRequests::default(); + for build in 1..=1000 { + stats.record(Some(&format!("OpenRadlr/0.1.0 (android; build/{build})"))); + } + let metrics = stats.metrics(); + let rows: Vec<_> = metrics.lines().filter(|line| !line.starts_with('#')).collect(); + assert_eq!(rows.len(), 33); + assert!(metrics.contains("client=\"android\",app_version=\"other\",app_build=\"other\"} 968\n")); + } +} diff --git a/server/crates/server/src/http.rs b/server/crates/server/src/http.rs index 4c9ef672..5caf13fb 100644 --- a/server/crates/server/src/http.rs +++ b/server/crates/server/src/http.rs @@ -14,6 +14,7 @@ use crate::afk::{AfkCounts, AfkStats}; use crate::app::unix_now_s; use crate::auth::{self, Strava}; +use crate::client_requests::ClientRequests; use crate::connection; use crate::guard::{client_ip, origin_allowed, ConnectionLimits, Slots}; use crate::map_file::Maps; @@ -25,8 +26,10 @@ use crate::worlds::{StudioEntry, WorldEntry, Worlds}; use crate::ServerInfo; use axum::extract::connect_info::ConnectInfo; use axum::extract::ws::WebSocketUpgrade; +use axum::extract::Request; use axum::extract::{DefaultBodyLimit, Query, State}; use axum::http::{header, Extensions, HeaderMap, HeaderValue, StatusCode}; +use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Json, Router}; @@ -71,6 +74,8 @@ impl Protection { #[derive(Clone)] pub struct AppState { + /// Aggregate HTTP counts by client platform and native app release. + pub client_requests: ClientRequests, pub worlds: Arc, /// Road network files by map id (ADR 0010). pub maps: Arc, @@ -289,6 +294,7 @@ pub struct RouteQuery { /// `headers` (see [`crate::headers`]) go on every response that doesn't set them itself. pub fn router(state: AppState, static_dir: Option<&Path>, headers: &[(header::HeaderName, String)]) -> Router { + let client_requests = state.client_requests.clone(); let router = Router::new() .route("/healthz", get(healthz)) .route("/internal/metrics", get(metrics)) @@ -329,6 +335,19 @@ pub fn router(state: AppState, static_dir: Option<&Path>, headers: &[(header::He router .layer(CompressionLayer::new().br(true).gzip(true)) .layer(TraceLayer::new_for_http()) + .layer(middleware::from_fn_with_state(client_requests, count_client_request)) +} + +async fn count_client_request(State(stats): State, request: Request, next: Next) -> Response { + if !matches!(request.uri().path(), "/healthz" | "/internal/metrics") { + stats.record( + request + .headers() + .get(header::USER_AGENT) + .and_then(|value| value.to_str().ok()), + ); + } + next.run(request).await } async fn healthz() -> &'static str { @@ -336,11 +355,11 @@ async fn healthz() -> &'static str { } // This endpoint is intended for the host's private Prometheus network. It only -// exports aggregate counters already exposed by /api/info; never rider data, -// names, IDs, credentials, or request details. +// exports aggregate operational counters; never rider data, names, IDs, +// credentials, or individual request records. async fn metrics(State(state): State) -> ([(header::HeaderName, &'static str); 1], String) { let distance = state.stats.snapshot(); - let body = metrics_body( + let mut body = metrics_body( state.worlds.player_count(), state.worlds.phone_count(), state.max_players, @@ -349,6 +368,7 @@ async fn metrics(State(state): State) -> ([(header::HeaderName, &'stat distance.paddle_m, state.afk.snapshot(), ); + body.push_str(&state.client_requests.metrics()); ( [(header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8")], body, diff --git a/server/crates/server/src/lib.rs b/server/crates/server/src/lib.rs index e4b3044d..c8132dec 100644 --- a/server/crates/server/src/lib.rs +++ b/server/crates/server/src/lib.rs @@ -26,6 +26,7 @@ pub mod afk; pub mod app; pub mod auth; +pub mod client_requests; pub mod config; pub mod connection; pub mod events_file; diff --git a/server/crates/server/tests/websocket_flow.rs b/server/crates/server/tests/websocket_flow.rs index 2ce503b1..f02dd845 100644 --- a/server/crates/server/tests/websocket_flow.rs +++ b/server/crates/server/tests/websocket_flow.rs @@ -1249,3 +1249,54 @@ async fn an_unknown_pair_code_is_refused() { let error = expect_type(&mut phone, "error").await; assert_eq!(error["code"], "pair_code_invalid"); } + +#[tokio::test] +async fn request_metrics_group_app_releases_without_counting_health_or_scrape_requests() { + let addr = start_server(0).await; + let client = reqwest::Client::new(); + let app_agent = "Mozilla/5.0 OpenRadlr/0.1.0 (android; build/3)"; + for _ in 0..2 { + client + .get(format!("http://{addr}/api/info")) + .header("user-agent", app_agent) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); + } + client + .get(format!("http://{addr}/api/info")) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); + client + .get(format!("http://{addr}/healthz")) + .header("user-agent", app_agent) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); + let scrape = || { + client + .get(format!("http://{addr}/internal/metrics")) + .header("user-agent", app_agent) + .send() + }; + let first = scrape().await.unwrap().text().await.unwrap(); + let second = scrape().await.unwrap().text().await.unwrap(); + let client_rows = |body: &str| { + body.lines() + .filter(|line| line.starts_with("openradlr_client_requests_total{")) + .map(str::to_owned) + .collect::>() + }; + assert_eq!(client_rows(&first), client_rows(&second)); + assert!( + first.contains("openradlr_client_requests_total{client=\"android\",app_version=\"0.1.0\",app_build=\"3\"} 2\n") + ); + assert!(first.contains("openradlr_client_requests_total{client=\"browser\",app_version=\"\",app_build=\"\"} 1\n")); +} From 0f405005d0b8bce4b07572c55b1e54a111acc0e7 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 17:51:22 +0100 Subject: [PATCH 03/12] fix(app): Extend the island behind status icons and address release metric review --- .env.example | 3 + README.md | 3 +- app/android/app/build.gradle | 2 + .../myapp/ExampleInstrumentedTest.java | 2 +- .../com/openradlr/app/SystemBarsTest.java | 85 ++++++++ .../java/com/openradlr/app/MainActivity.java | 6 + .../app/src/main/res/values/styles.xml | 2 + app/capacitor.config.ts | 5 + client/public/js/main.js | 6 + client/public/js/native/app.js | 6 +- client/public/styles.css | 4 +- client/test/nativeBluetooth.test.js | 19 +- docker-compose.yml | 1 + docs/app.md | 53 ++++- docs/deploy.md | 6 +- server/crates/server/src/app.rs | 3 +- server/crates/server/src/client_requests.rs | 206 +++++++++++++----- server/crates/server/src/config.rs | 21 ++ server/crates/server/src/http.rs | 20 +- server/crates/server/tests/websocket_flow.rs | 14 ++ 20 files changed, 383 insertions(+), 84 deletions(-) create mode 100644 app/android/app/src/androidTest/java/com/openradlr/app/SystemBarsTest.java diff --git a/.env.example b/.env.example index 50dd89d9..af98284c 100644 --- a/.env.example +++ b/.env.example @@ -7,6 +7,9 @@ # Name shown to riders. OPENRADLR_SERVER_NAME=OpenRadlr +# Native app releases with separate menu-request counters (platform/version/build). +# Unknown releases share an "other" bucket; max 32 entries. Empty disables release detail. +OPENRADLR_APP_METRIC_RELEASES=android/0.1.0/3,ios/1.0/1 # Default route (file in ./routes without .json). Every other route in ./routes # is offered on the start screen too, each as its own world. diff --git a/README.md b/README.md index c2147a6a..7c8e430b 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,8 @@ Later, to deploy new commits: `make update`. The server exposes aggregate Prometheus metrics at `/internal/metrics` for connected riders, configured rider capacity, community distance totals and AFK -warning outcomes (`openradlr_afk_events_total`). The +warning outcomes (`openradlr_afk_events_total`), plus start-menu requests by app +platform and release (`openradlr_client_requests_total`). The endpoint contains no rider names, IDs, credentials or request details. The Monitoring stack scrapes it over the private `openradlr-metrics` Docker network; its Grafana dashboard also probes the public `/healthz` URL. diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 13fa1cc8..8e2f854e 100644 --- a/app/android/app/build.gradle +++ b/app/android/app/build.gradle @@ -66,6 +66,8 @@ dependencies { implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" implementation project(':capacitor-android') testImplementation "junit:junit:$junitVersion" + // Keep the test APK's old split stdlibs aligned with the BLE plugin's Kotlin runtime. + androidTestImplementation platform("org.jetbrains.kotlin:kotlin-bom:2.2.20") androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" implementation project(':capacitor-cordova-android-plugins') diff --git a/app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java index f2c2217e..6b14b61d 100644 --- a/app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java +++ b/app/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java @@ -21,6 +21,6 @@ public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); - assertEquals("com.getcapacitor.app", appContext.getPackageName()); + assertEquals("com.openradlr.app", appContext.getPackageName()); } } diff --git a/app/android/app/src/androidTest/java/com/openradlr/app/SystemBarsTest.java b/app/android/app/src/androidTest/java/com/openradlr/app/SystemBarsTest.java new file mode 100644 index 00000000..e21dc80a --- /dev/null +++ b/app/android/app/src/androidTest/java/com/openradlr/app/SystemBarsTest.java @@ -0,0 +1,85 @@ +package com.openradlr.app; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import android.content.pm.ActivityInfo; +import android.content.res.Configuration; +import android.view.View; +import android.view.ViewTreeObserver; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowCompat; +import androidx.core.view.WindowInsetsCompat; +import androidx.lifecycle.Lifecycle; +import androidx.test.core.app.ActivityScenario; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** Device checks for the start screen's real system-bar appearance. */ +@RunWith(AndroidJUnit4.class) +public class SystemBarsTest { + @Test + public void startScreenKeepsTheStatusBarVisible() throws Exception { + try (ActivityScenario scenario = ActivityScenario.launch(MainActivity.class)) { + assertStatusBarVisible(scenario, Configuration.ORIENTATION_UNDEFINED); + } + } + + @Test + public void startScreenDrawsBehindTheStatusBarWithLightSystemIcons() throws Exception { + try (ActivityScenario scenario = ActivityScenario.launch(MainActivity.class)) { + scenario.onActivity(activity -> { + View decor = activity.getWindow().getDecorView(); + assertEquals("The island must extend under the status icons", 0, decor.getPaddingTop()); + assertFalse(WindowCompat.getInsetsController(activity.getWindow(), decor).isAppearanceLightStatusBars()); + }); + } + } + + @Test + public void statusBarStaysVisibleAfterReturningToTheStartScreen() throws Exception { + try (ActivityScenario scenario = ActivityScenario.launch(MainActivity.class)) { + scenario.moveToState(Lifecycle.State.CREATED); + scenario.moveToState(Lifecycle.State.RESUMED); + assertStatusBarVisible(scenario, Configuration.ORIENTATION_UNDEFINED); + } + } + + @Test + public void startScreenKeepsItsStatusBarInLandscape() throws Exception { + try (ActivityScenario scenario = ActivityScenario.launch(MainActivity.class)) { + scenario.onActivity(activity -> activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)); + try { + assertStatusBarVisible(scenario, Configuration.ORIENTATION_LANDSCAPE); + } finally { + scenario.onActivity(activity -> activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)); + } + } + } + + private static void assertStatusBarVisible(ActivityScenario scenario, int orientation) throws Exception { + CountDownLatch visible = new CountDownLatch(1); + scenario.onActivity(activity -> { + View decor = activity.getWindow().getDecorView(); + decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { + @Override + public boolean onPreDraw() { + WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(decor); + if ((orientation == Configuration.ORIENTATION_UNDEFINED + || activity.getResources().getConfiguration().orientation == orientation) + && insets != null && insets.isVisible(WindowInsetsCompat.Type.statusBars())) { + decor.getViewTreeObserver().removeOnPreDrawListener(this); + visible.countDown(); + } + return true; + } + }); + decor.invalidate(); + }); + assertTrue("The start screen should show Android's status bar", visible.await(5, TimeUnit.SECONDS)); + } +} diff --git a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java index c09ab12a..3a1f4f85 100644 --- a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java +++ b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java @@ -1,6 +1,8 @@ package com.openradlr.app; import android.webkit.WebView; +import androidx.core.view.WindowCompat; +import androidx.core.view.WindowInsetsControllerCompat; import com.getcapacitor.BridgeActivity; public class MainActivity extends BridgeActivity { @@ -12,5 +14,9 @@ protected void load() { String suffix = " OpenRadlr/" + BuildConfig.VERSION_NAME + " (android; build/" + BuildConfig.VERSION_CODE + ")"; webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + suffix); super.load(); + // Ride visibility is controlled by SystemBars from the client. Keep edge + // swipes available while hidden, without forcing fullscreen on the menu. + WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView()) + .setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); } } diff --git a/app/android/app/src/main/res/values/styles.xml b/app/android/app/src/main/res/values/styles.xml index 00086e56..900c6c71 100644 --- a/app/android/app/src/main/res/values/styles.xml +++ b/app/android/app/src/main/res/values/styles.xml @@ -13,6 +13,8 @@ false true @null + + @color/splashBackground diff --git a/app/capacitor.config.ts b/app/capacitor.config.ts index b8f943bb..c08575a0 100644 --- a/app/capacitor.config.ts +++ b/app/capacitor.config.ts @@ -28,6 +28,11 @@ const config: CapacitorConfig = { contentInset: "never", }, plugins: { + SystemBars: { + style: "DARK", + initialViewportFitValueHint: "cover", + hidden: false, + }, BluetoothLe: { displayStrings: { scanning: "Looking for devices…", diff --git a/client/public/js/main.js b/client/public/js/main.js index eca87284..42913bef 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -127,6 +127,10 @@ import { createScreensDialog } from "./view/screensDialog.js"; // Inside the OpenRadlr app: native Bluetooth, wake lock and file saving (docs/app.md). const nativeApp = installNativeApp(); +function setNativeImmersive(enabled) { + nativeApp?.setImmersive?.(enabled).catch((error) => console.warn("System bars:", error)); +} +setNativeImmersive(false); const $ = (id) => document.getElementById(id); const now = () => performance.now() / 1000; /** How often a ride is written to the browser while it goes on (#73). */ @@ -2043,6 +2047,7 @@ function endRide() { initBiomePicker(); document.body.classList.remove("riding"); $("setup").hidden = false; + setNativeImmersive(false); delete $("join").dataset.busy; // A join that failed never left the menu: it is only paused. if (app.menu) { @@ -2139,6 +2144,7 @@ function startRide() { setDifficultyInputs(app.profile.difficulty); $("setup").hidden = true; $("ride").hidden = false; + setNativeImmersive(true); clearInterval(app.infoTimer); app.infoTimer = setInterval(refreshServerPlayers, INFO_REFRESH_MS * 2); refreshServerPlayers(); diff --git a/client/public/js/native/app.js b/client/public/js/native/app.js index 058700bc..8e5deb21 100644 --- a/client/public/js/native/app.js +++ b/client/public/js/native/app.js @@ -24,9 +24,10 @@ export const APP_SCHEME = "openradlr"; * saveFiles: ((files: {blob: Blob, name: string}[]) => Promise) | null, * signIn: ((url: string) => Promise) | null, * onBack: ((back: () => boolean) => void) | null, + * setImmersive: ((enabled: boolean) => Promise) | null, * } | null} */ -export function installNativeApp({ plugins = nativePlugins(), navigator: nav = globalThis.navigator, storage } = {}) { +export function installNativeApp({ plugins = nativePlugins(), navigator: nav = globalThis.navigator, storage, platform = globalThis.Capacitor?.getPlatform?.() } = {}) { if (!plugins) return null; if (plugins.BluetoothLe && !nav.bluetooth) define(nav, "bluetooth", new NativeBluetooth({ plugin: plugins.BluetoothLe, ...(storage !== undefined && { storage }) })); // The web view's own wake lock may exist and still let the screen dim. @@ -43,6 +44,9 @@ export function installNativeApp({ plugins = nativePlugins(), navigator: nav = g saveFiles: canShare ? (files) => shareFiles(plugins, files) : null, signIn: canSignIn ? (url) => systemSignIn(plugins, url) : null, onBack: plugins.App ? (back) => onBackButton(plugins.App, back) : null, + setImmersive: platform === "android" && plugins.SystemBars + ? (enabled) => Promise.resolve().then(() => enabled ? plugins.SystemBars.hide() : plugins.SystemBars.show()) + : null, }; } diff --git a/client/public/styles.css b/client/public/styles.css index 902a623b..af96b9b2 100644 --- a/client/public/styles.css +++ b/client/public/styles.css @@ -4769,8 +4769,8 @@ body { } /* Edge to edge (the app on Android 15+, iOS home screen): the status bar lies over the page. - Outside a ride a strip in the page's colour keeps scrolled text from running under the clock. */ -body:not(.riding)::after { + Secondary pages keep a strip behind the clock; the start screen shows the island underneath. */ +body:not(.riding):not(:has(.start))::after { content: ""; position: fixed; inset: 0 0 auto; diff --git a/client/test/nativeBluetooth.test.js b/client/test/nativeBluetooth.test.js index 1d997feb..1e100722 100644 --- a/client/test/nativeBluetooth.test.js +++ b/client/test/nativeBluetooth.test.js @@ -275,7 +275,7 @@ test("large files are encoded in chunks", async () => { test("only the features with native plugins are offered", () => { const share = { Filesystem: {}, Share: {} }; - assert.deepEqual(Object.keys(installNativeApp({ plugins: {}, navigator: {} })), ["saveFiles", "signIn", "onBack"]); + assert.deepEqual(Object.keys(installNativeApp({ plugins: {}, navigator: {} })), ["saveFiles", "signIn", "onBack", "setImmersive"]); assert.equal(installNativeApp({ plugins: {}, navigator: {} }).saveFiles, null); assert.equal(typeof installNativeApp({ plugins: share, navigator: {} }).saveFiles, "function"); assert.equal(typeof installNativeApp({ plugins: { WebAuth: {} }, navigator: {} }).signIn, "function"); @@ -368,3 +368,20 @@ test("with nothing left to go back to, the back button sends the app to the back test("without the App plugin there is no back button to handle", () => { assert.equal(installNativeApp({ plugins: {}, navigator: {} }).onBack, null); }); + +test("Android system bars hide for a ride and return for the start screen", async () => { + const calls = []; + const app = installNativeApp({ + plugins: { SystemBars: { hide: async () => calls.push("hide"), show: async () => calls.push("show") } }, + navigator: {}, + platform: "android", + }); + await app.setImmersive(true); + await app.setImmersive(false); + assert.deepEqual(calls, ["hide", "show"]); +}); + +test("system-bar control stays optional on other platforms and older shells", () => { + assert.equal(installNativeApp({ plugins: {}, navigator: {}, platform: "android" }).setImmersive, null); + assert.equal(installNativeApp({ plugins: { SystemBars: {} }, navigator: {}, platform: "ios" }).setImmersive, null); +}); diff --git a/docker-compose.yml b/docker-compose.yml index d175ae8e..fa94eda5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,6 +21,7 @@ services: restart: unless-stopped environment: OPENRADLR_SERVER_NAME: ${OPENRADLR_SERVER_NAME:-OpenRadlr} + OPENRADLR_APP_METRIC_RELEASES: ${OPENRADLR_APP_METRIC_RELEASES-android/0.1.0/3,ios/1.0/1} OPENRADLR_ROUTE_FILE: /app/routes/${OPENRADLR_ROUTE:-rolling-hills}.json OPENRADLR_TARGET_RIDERS: ${OPENRADLR_TARGET_RIDERS:-12} OPENRADLR_MAX_PLAYERS: ${OPENRADLR_MAX_PLAYERS:-50} diff --git a/docs/app.md b/docs/app.md index 8a6af38e..a7e1806a 100644 --- a/docs/app.md +++ b/docs/app.md @@ -47,6 +47,32 @@ end a ride or a workout without asking: iOS has no back button, and in a browser the back button still leaves the page. +## Fullscreen on Android + +The Android start screen keeps the clock and system icons visible over the island +background, which extends behind the transparent status bar. During a ride, the +status and navigation bars are hidden to give the road more room. Swipe from the screen edge to reveal Android's controls +temporarily; returning to the start screen shows the bars again. The keyboard +still opens normally for names, chat and other text fields. + +Deploy the web client together with the shell update: it switches the native +SystemBars API when entering and leaving the ride screen. + +Device regression checks (with an Android emulator or phone attached): + +```bash +cd app/android +./gradlew :app:assembleDebug :app:assembleDebugAndroidTest +adb install -r app/build/outputs/apk/debug/app-debug.apk +adb install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk +adb shell am instrument -w com.openradlr.app.test/androidx.test.runner.AndroidJUnitRunner +``` + +The device tests check status-bar visibility, content extending underneath it, +and light icons, including visibility after backgrounding and in landscape. +Client tests cover entering and leaving immersive mode. With more than one +device attached, select one with `adb -s`. + ## Strava sign-in Google and Apple don't allow sign-in inside an embedded web view. So in the @@ -264,16 +290,21 @@ server. A client can forge a user agent, so it is not an authentication signal. The server exports `openradlr_client_requests_total` on its existing `/internal/metrics` endpoint, grouped by `client` (`android`, `ios`, or `browser`), `app_version` and `app_build`. The `browser` bucket also includes older app builds -without the marker and requests with an invalid marker. Health checks and metrics -scrapes are excluded. WebSocket upgrades count as HTTP requests; individual -WebSocket messages do not. - -These are request totals, not unique users, installations or sessions. The -counter keeps no raw user agents, IP addresses, device identifiers, rider names, -request paths or individual request records. It lives in memory and resets when -the server restarts. At most 32 app release combinations have separate counters; -additional combinations share an `other` version/build bucket per platform, so -untrusted headers cannot create unlimited metric series. Keep the endpoint on +without the marker and requests with an invalid marker. Only successful `GET /api/info` responses are counted: the start menu requests +this endpoint when it loads and while it remains open. Static files, failures, +health checks, scrapes and WebSocket messages do not contribute. This measures +menu-load and refresh activity, not unique users, installations or ride sessions. + +The counter keeps no raw user agents, IP addresses, device identifiers, rider +names, request paths or individual request records. It lives in memory and resets +when the server restarts. Separate release labels come only from an operator +allowlist, never from request-controlled allocation. The default is +`android/0.1.0/3,ios/1.0/1`; override `OPENRADLR_APP_METRIC_RELEASES` with a +comma-separated `platform/version/build` list (at most 32 entries, empty disables +release detail). Include the releases you still support when adding a new one. +Unknown valid releases use `other` version/build buckets per platform. iOS build +numbers may contain dot-separated numeric components. All counters are atomic; +no global request lock is needed. Keep the endpoint on the host's private monitoring network as described in [Deployment](deploy.md). Example PromQL for a dashboard connected to the endpoint: @@ -282,7 +313,7 @@ Example PromQL for a dashboard connected to the endpoint: sum by (client) (rate(openradlr_client_requests_total[5m])) ``` -Requests by Android release over the last day: +Start-menu requests by Android release over the last day: ```promql sum by (app_version, app_build) ( diff --git a/docs/deploy.md b/docs/deploy.md index d04228be..0ccca4e2 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -253,6 +253,8 @@ For a server without a reverse proxy, the bundled Caddy can handle TLS: The private `/internal/metrics` endpoint also exports `openradlr_client_requests_total{client,app_version,app_build}`. This aggregate counter helps compare native app releases and diagnose release-specific issues. -It excludes health and scrape requests and does not estimate unique people or -devices. See [App release information](app.md#app-release-information-on-requests) +It counts successful `GET /api/info` responses, excluding static assets, health +checks and scrapes; menu refreshes count again. It does not estimate unique +people or sessions. Set `OPENRADLR_APP_METRIC_RELEASES` to a comma-separated +allowlist such as `android/0.1.0/3,ios/1.0/1` when supporting additional releases. See [App release information](app.md#app-release-information-on-requests) for label limits, compatibility with older app builds and example PromQL. diff --git a/server/crates/server/src/app.rs b/server/crates/server/src/app.rs index 135c51bd..cfb718b6 100644 --- a/server/crates/server/src/app.rs +++ b/server/crates/server/src/app.rs @@ -325,7 +325,8 @@ pub fn build_with_stats(config: &Config) -> Result<(Router, DistanceStats), BoxE }; let state = AppState { - client_requests: crate::client_requests::ClientRequests::default(), + client_requests: crate::client_requests::ClientRequests::with_releases(&config.app_metric_releases) + .expect("validated app release allowlist"), worlds: Arc::new(worlds), maps: Arc::new(maps), info, diff --git a/server/crates/server/src/client_requests.rs b/server/crates/server/src/client_requests.rs index b2c6af0f..e21f3610 100644 --- a/server/crates/server/src/client_requests.rs +++ b/server/crates/server/src/client_requests.rs @@ -1,37 +1,39 @@ -//! Aggregate request counts by app platform and release; no request or rider records. +//! Aggregate start-menu loads by app platform and release; no request or rider records. use std::collections::BTreeMap; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; -// User agents are untrusted: a client must not create unbounded metric labels. +pub const DEFAULT_RELEASES: &str = "android/0.1.0/3,ios/1.0/1"; const MAX_RELEASES: usize = 32; +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Platform { + Android, + Ios, +} + +impl Platform { + fn label(self) -> &'static str { + match self { + Self::Android => "android", + Self::Ios => "ios", + } + } +} + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] struct Release { - client: &'static str, + platform: Platform, version: String, build: String, } impl Release { - fn browser() -> Self { - Self { - client: "browser", - version: String::new(), - build: String::new(), - } - } - - fn parse(agent: &str) -> Option { - let (prefix, suffix) = agent.split_once("OpenRadlr/")?; - if !prefix.is_empty() && !prefix.ends_with(char::is_whitespace) { - return None; - } - let (version, suffix) = suffix.split_once(" (")?; - let (platform, build) = suffix.trim_end().strip_suffix(')')?.split_once("; build/")?; - let client = match platform { - "android" => "android", - "ios" => "ios", + fn new(platform: &str, version: &str, build: &str) -> Option { + let platform = match platform { + "android" => Platform::Android, + "ios" => Platform::Ios, _ => return None, }; if version.is_empty() @@ -41,54 +43,100 @@ impl Release { .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) || build.is_empty() - || build.len() > 10 - || !build.bytes().all(|b| b.is_ascii_digit()) + || build.len() > 32 + || !build + .split('.') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())) + || (platform == Platform::Android && build.contains('.')) { return None; } Some(Self { - client, + platform, version: version.into(), build: build.into(), }) } + + fn parse(agent: &str) -> Option { + let (prefix, suffix) = agent.split_once("OpenRadlr/")?; + if !prefix.is_empty() && !prefix.ends_with(char::is_whitespace) { + return None; + } + let (version, suffix) = suffix.split_once(" (")?; + let (marker, trailing) = suffix.split_once(')')?; + if !trailing.is_empty() && !trailing.starts_with(char::is_whitespace) { + return None; + } + let (platform, build) = marker.split_once("; build/")?; + Self::new(platform, version, build) + } +} + +#[derive(Default)] +struct Counters { + browser: AtomicU64, + android_other: AtomicU64, + ios_other: AtomicU64, + releases: BTreeMap, } -/// Shared only inside one server process; counts requests, not people or devices. -#[derive(Clone, Default)] -pub struct ClientRequests(Arc>>); +/// Shared only inside one server process; counts menu loads, not people or devices. +#[derive(Clone)] +pub struct ClientRequests(Arc); + +impl Default for ClientRequests { + fn default() -> Self { + Self::with_releases(DEFAULT_RELEASES).expect("built-in app releases are valid") + } +} impl ClientRequests { - pub fn record(&self, user_agent: Option<&str>) { - let mut release = user_agent.and_then(Release::parse).unwrap_or_else(Release::browser); - let mut counts = self.0.lock().unwrap_or_else(|e| e.into_inner()); - if release.client != "browser" - && !counts.contains_key(&release) - && counts - .keys() - .filter(|r| r.client != "browser" && r.version != "other") - .count() - >= MAX_RELEASES - { - release.version = "other".into(); - release.build = "other".into(); + /// Only operator-approved releases get labels. User agents never allocate slots. + pub fn with_releases(releases: &str) -> Result { + let mut counters = Counters::default(); + for entry in releases.split(',').filter(|s| !s.trim().is_empty()) { + let parts: Vec<_> = entry.trim().split('/').collect(); + let release = match parts.as_slice() { + [platform, version, build] => Release::new(platform, version, build), + _ => None, + } + .ok_or("must be comma-separated platform/version/build entries (android or ios)")?; + counters.releases.entry(release).or_default(); + if counters.releases.len() > MAX_RELEASES { + return Err("must contain at most 32 distinct app releases"); + } } - let count = counts.entry(release).or_default(); - *count = count.saturating_add(1); + Ok(Self(Arc::new(counters))) + } + + pub fn record(&self, user_agent: Option<&str>) { + let counter = match user_agent.and_then(Release::parse) { + None => &self.0.browser, + Some(release) => self.0.releases.get(&release).unwrap_or(match release.platform { + Platform::Android => &self.0.android_other, + Platform::Ios => &self.0.ios_other, + }), + }; + counter.fetch_add(1, Ordering::Relaxed); } pub fn metrics(&self) -> String { use std::fmt::Write; - let counts = self.0.lock().unwrap_or_else(|e| e.into_inner()); - let mut output = String::from("# HELP openradlr_client_requests_total HTTP requests by client platform and app release since server start, excluding health and metrics probes.\n# TYPE openradlr_client_requests_total counter\n"); - for (release, count) in counts.iter() { - // The parser permits only label-safe ASCII; the full user agent is never kept. - writeln!( - output, - "openradlr_client_requests_total{{client=\"{}\",app_version=\"{}\",app_build=\"{}\"}} {}", - release.client, release.version, release.build, count - ) - .expect("write to String"); + let mut output = String::from("# HELP openradlr_client_requests_total Successful GET /api/info responses by client platform and app release since server start; not unique users or sessions.\n# TYPE openradlr_client_requests_total counter\n"); + let mut row = |client, version: &str, build: &str, count: &AtomicU64| { + let count = count.load(Ordering::Relaxed); + if count > 0 { + // Only validated label-safe release facts are retained, never the user agent. + writeln!(output, "openradlr_client_requests_total{{client=\"{client}\",app_version=\"{version}\",app_build=\"{build}\"}} {count}") + .expect("write to String"); + } + }; + row("browser", "", "", &self.0.browser); + row("android", "other", "other", &self.0.android_other); + row("ios", "other", "other", &self.0.ios_other); + for (release, count) in &self.0.releases { + row(release.platform.label(), &release.version, &release.build, count); } output } @@ -98,6 +146,21 @@ impl ClientRequests { mod tests { use super::ClientRequests; + #[test] + fn invalid_or_oversized_release_allowlists_are_rejected() { + for invalid in [ + "bad", + "desktop/1/1", + "ios/1/1..3", + "android/1/1.2", + "ios/1/unsafe\"label", + ] { + assert!(ClientRequests::with_releases(invalid).is_err(), "{invalid}"); + } + let too_many = (1..=33).map(|n| format!("android/1/{n}")).collect::>().join(","); + assert!(ClientRequests::with_releases(&too_many).is_err()); + } + #[test] fn requests_from_the_same_app_release_share_one_counter() { let stats = ClientRequests::default(); @@ -110,7 +173,7 @@ mod tests { #[test] fn ios_and_android_are_separate_release_counters() { - let stats = ClientRequests::default(); + let stats = ClientRequests::with_releases("ios/1.0/1,android/1.0/1").unwrap(); stats.record(Some("Mozilla/5.0 OpenRadlr/1.0 (ios; build/1)")); stats.record(Some("Mozilla/5.0 OpenRadlr/1.0 (android; build/1)")); assert!(stats @@ -141,6 +204,37 @@ mod tests { assert!(!stats.metrics().contains("Mozilla")); } + #[test] + fn app_marker_can_precede_an_oem_suffix() { + let stats = ClientRequests::default(); + stats.record(Some("Mozilla/5.0 OpenRadlr/0.1.0 (android; build/3) OEM/42")); + assert!(stats + .metrics() + .contains("client=\"android\",app_version=\"0.1.0\",app_build=\"3\"} 1\n")); + } + + #[test] + fn forged_releases_cannot_displace_a_known_release() { + let stats = ClientRequests::default(); + for build in 10..1000 { + stats.record(Some(&format!("OpenRadlr/9.9.9 (android; build/{build})"))); + } + stats.record(Some("OpenRadlr/0.1.0 (android; build/3)")); + assert!(stats + .metrics() + .contains("client=\"android\",app_version=\"0.1.0\",app_build=\"3\"} 1\n")); + } + + #[test] + fn dotted_ios_builds_are_classified_as_app_requests() { + let stats = ClientRequests::with_releases("ios/1.0/1.0.3").unwrap(); + stats.record(Some("OpenRadlr/1.0 (ios; build/1.0.3)")); + assert!(stats + .metrics() + .contains("client=\"ios\",app_version=\"1.0\",app_build=\"1.0.3\"} 1\n")); + assert!(!stats.metrics().contains("client=\"browser\"")); + } + #[test] fn release_cardinality_is_bounded_even_for_valid_forged_versions() { let stats = ClientRequests::default(); @@ -149,7 +243,7 @@ mod tests { } let metrics = stats.metrics(); let rows: Vec<_> = metrics.lines().filter(|line| !line.starts_with('#')).collect(); - assert_eq!(rows.len(), 33); - assert!(metrics.contains("client=\"android\",app_version=\"other\",app_build=\"other\"} 968\n")); + assert_eq!(rows.len(), 2); + assert!(metrics.contains("client=\"android\",app_version=\"other\",app_build=\"other\"} 999\n")); } } diff --git a/server/crates/server/src/config.rs b/server/crates/server/src/config.rs index 00dd1bc6..2cf8fc0d 100644 --- a/server/crates/server/src/config.rs +++ b/server/crates/server/src/config.rs @@ -48,6 +48,8 @@ pub struct Config { /// Directory with the browser client. `None` disables static hosting. pub static_dir: Option, pub server_name: String, + /// Native releases allowed separate aggregate counters (platform/version/build). + pub app_metric_releases: String, pub tick_hz: u32, pub broadcast_hz: u32, pub max_players: usize, @@ -405,6 +407,15 @@ impl Config { )?; } + let app_metric_releases = reader + .raw("OPENRADLR_APP_METRIC_RELEASES") + .unwrap_or_else(|| crate::client_requests::DEFAULT_RELEASES.into()); + crate::client_requests::ClientRequests::with_releases(&app_metric_releases).map_err(|reason| ConfigError { + key: "OPENRADLR_APP_METRIC_RELEASES", + value: app_metric_releases.clone(), + reason: reason.into(), + })?; + Ok(Self { bind_addr: reader.parse("OPENRADLR_BIND", SocketAddr::from(([0, 0, 0, 0], 8080)))?, route_file: reader @@ -419,6 +430,7 @@ impl Config { .filter(|s| !s.is_empty()) .map(PathBuf::from), server_name, + app_metric_releases, tick_hz, broadcast_hz, max_players, @@ -540,6 +552,15 @@ mod tests { Config::from_lookup(|key| map.get(key).cloned()) } + #[test] + fn app_metric_allowlist_is_validated_before_startup() { + let parsed = config(&[("OPENRADLR_APP_METRIC_RELEASES", "ios/2.0/1.0.3")]).unwrap(); + assert_eq!(parsed.app_metric_releases, "ios/2.0/1.0.3"); + let error = config(&[("OPENRADLR_APP_METRIC_RELEASES", "bad")]).unwrap_err(); + assert_eq!(error.key, "OPENRADLR_APP_METRIC_RELEASES"); + assert!(config(&[("OPENRADLR_APP_METRIC_RELEASES", "")]).is_ok()); + } + #[test] fn defaults_are_sensible() { let c = config(&[]).unwrap(); diff --git a/server/crates/server/src/http.rs b/server/crates/server/src/http.rs index 5caf13fb..4df1286c 100644 --- a/server/crates/server/src/http.rs +++ b/server/crates/server/src/http.rs @@ -339,15 +339,19 @@ pub fn router(state: AppState, static_dir: Option<&Path>, headers: &[(header::He } async fn count_client_request(State(stats): State, request: Request, next: Next) -> Response { - if !matches!(request.uri().path(), "/healthz" | "/internal/metrics") { - stats.record( - request - .headers() - .get(header::USER_AGENT) - .and_then(|value| value.to_str().ok()), - ); + if request.method() != axum::http::Method::GET || request.uri().path() != "/api/info" { + return next.run(request).await; + } + let user_agent = request + .headers() + .get(header::USER_AGENT) + .and_then(|value| value.to_str().ok()) + .map(str::to_owned); + let response = next.run(request).await; + if response.status().is_success() { + stats.record(user_agent.as_deref()); } - next.run(request).await + response } async fn healthz() -> &'static str { diff --git a/server/crates/server/tests/websocket_flow.rs b/server/crates/server/tests/websocket_flow.rs index f02dd845..b0c5bdfe 100644 --- a/server/crates/server/tests/websocket_flow.rs +++ b/server/crates/server/tests/websocket_flow.rs @@ -1280,6 +1280,20 @@ async fn request_metrics_group_app_releases_without_counting_health_or_scrape_re .unwrap() .error_for_status() .unwrap(); + for path in ["/styles.css", "/js/main.js", "/scanner-missing"] { + client + .get(format!("http://{addr}{path}")) + .header("user-agent", app_agent) + .send() + .await + .unwrap(); + } + client + .post(format!("http://{addr}/api/info")) + .header("user-agent", app_agent) + .send() + .await + .unwrap(); let scrape = || { client .get(format!("http://{addr}/internal/metrics")) From 92c90ffed1994341fdf1927d1cc3c954c740364a Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 19:50:20 +0100 Subject: [PATCH 04/12] feat(app): Keep Android trainer rides running in the background --- .github/workflows/ci.yml | 22 + app/android/app/build.gradle | 3 + .../app/ride/BackgroundRideTest.java | 174 +++++++ .../openradlr/app/ride/RidePreviewTest.java | 71 +++ app/android/app/src/debug/AndroidManifest.xml | 7 + .../openradlr/app/ride/RideTestActivity.java | 4 + app/android/app/src/main/AndroidManifest.xml | 9 + .../java/com/openradlr/app/MainActivity.java | 1 + .../app/ride/BackgroundRidePlugin.java | 124 +++++ .../com/openradlr/app/ride/BleTransport.java | 11 + .../com/openradlr/app/ride/NativeBle.java | 83 ++++ .../com/openradlr/app/ride/RideEngine.java | 180 +++++++ .../com/openradlr/app/ride/RideJournal.java | 82 ++++ .../com/openradlr/app/ride/RideService.java | 453 ++++++++++++++++++ .../res/drawable-nodpi/notification_brand.png | Bin 0 -> 21338 bytes .../drawable/ride_notification_background.xml | 4 + .../src/main/res/layout/ride_notification.xml | 21 + .../res/layout/ride_notification_compact.xml | 13 + .../app/src/main/res/values-de/strings.xml | 19 + .../app/src/main/res/values/strings.xml | 24 +- .../app/src/main/res/xml/backup_rules.xml | 3 + .../main/res/xml/data_extraction_rules.xml | 4 + .../openradlr/app/ride/RideEngineTest.java | 112 +++++ .../openradlr/app/ride/RideJournalTest.java | 47 ++ client/public/index.html | 2 + client/public/js/ble/nativeBluetooth.js | 9 +- client/public/js/i18n/de.js | 8 + client/public/js/i18n/en.js | 8 + client/public/js/main.js | 105 +++- client/public/js/native/app.js | 6 +- client/public/js/native/backgroundRide.js | 164 +++++++ client/public/js/net/connection.js | 5 +- client/public/js/ride/workout.js | 7 + client/public/js/view/deviceSetup.js | 8 + client/test/deviceSetup.test.js | 25 + client/test/nativeBluetooth.test.js | 19 +- client/test/nativeRide.test.js | 116 +++++ client/test/workoutPlan.test.js | 9 + docs/adr/0028-android-ride-service.md | 24 + docs/app.md | 72 ++- .../2026-11-16-android-background-riding.md | 11 + ...-11-16-android-background-riding-design.md | 53 ++ 42 files changed, 2089 insertions(+), 33 deletions(-) create mode 100644 app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java create mode 100644 app/android/app/src/androidTest/java/com/openradlr/app/ride/RidePreviewTest.java create mode 100644 app/android/app/src/debug/AndroidManifest.xml create mode 100644 app/android/app/src/debug/java/com/openradlr/app/ride/RideTestActivity.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/ride/BackgroundRidePlugin.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/ride/BleTransport.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/ride/NativeBle.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/ride/RideJournal.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/ride/RideService.java create mode 100644 app/android/app/src/main/res/drawable-nodpi/notification_brand.png create mode 100644 app/android/app/src/main/res/drawable/ride_notification_background.xml create mode 100644 app/android/app/src/main/res/layout/ride_notification.xml create mode 100644 app/android/app/src/main/res/layout/ride_notification_compact.xml create mode 100644 app/android/app/src/main/res/values-de/strings.xml create mode 100644 app/android/app/src/main/res/xml/backup_rules.xml create mode 100644 app/android/app/src/main/res/xml/data_extraction_rules.xml create mode 100644 app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java create mode 100644 app/android/app/src/test/java/com/openradlr/app/ride/RideJournalTest.java create mode 100644 client/public/js/native/backgroundRide.js create mode 100644 client/test/nativeRide.test.js create mode 100644 docs/adr/0028-android-ride-service.md create mode 100644 docs/superpowers/plans/2026-11-16-android-background-riding.md create mode 100644 docs/superpowers/specs/2026-11-16-android-background-riding-design.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 593964d6..047bcacd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,28 @@ jobs: - run: npm run lint - run: npm test + android: + name: Android (native tests and lint) + runs-on: ubuntu-latest + defaults: + run: + working-directory: app + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: 21 + cache: gradle + cache-dependency-path: app/android/**/*.gradle* + - run: sdkmanager "platforms;android-36" "build-tools;36.0.0" + - run: npm ci --no-audit --no-fund + - run: npx cap sync android + - run: ./android/gradlew -p android :app:testDebugUnitTest :app:lintDebug :app:assembleDebug + image: name: Docker image runs-on: ubuntu-latest diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 8e2f854e..71012b33 100644 --- a/app/android/app/build.gradle +++ b/app/android/app/build.gradle @@ -65,10 +65,13 @@ dependencies { implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" implementation project(':capacitor-android') + implementation "com.squareup.okhttp3:okhttp:4.12.0" testImplementation "junit:junit:$junitVersion" + testImplementation "org.json:json:20250517" // Keep the test APK's old split stdlibs aligned with the BLE plugin's Kotlin runtime. androidTestImplementation platform("org.jetbrains.kotlin:kotlin-bom:2.2.20") androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "com.squareup.okhttp3:mockwebserver:4.12.0" androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" implementation project(':capacitor-cordova-android-plugins') } diff --git a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java new file mode 100644 index 00000000..2aa6781f --- /dev/null +++ b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java @@ -0,0 +1,174 @@ +package com.openradlr.app.ride; + +import static org.junit.Assert.*; +import android.app.*; +import android.view.accessibility.AccessibilityNodeInfo; +import android.content.*; +import android.os.*; +import androidx.core.content.ContextCompat; +import androidx.lifecycle.Lifecycle; +import androidx.test.core.app.ActivityScenario; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.getcapacitor.*; +import com.openradlr.app.MainActivity; +import java.util.Map; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import okhttp3.*; +import okhttp3.mockwebserver.*; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** Real Android lifecycle/socket/disk/notification, with only the radio and peer faked. */ +@RunWith(AndroidJUnit4.class) +public class BackgroundRideTest { + private static final String BIKE = "notification|trainer|00001826-0000-1000-8000-00805f9b34fb|00002ad2-0000-1000-8000-00805f9b34fb"; + private static final class Radio implements BleTransport { + final Map> listeners = new ConcurrentHashMap<>(); + @Override public void listen(String event, Consumer listener) { listeners.putIfAbsent(event, listener); } + @Override public void invoke(String method, JSObject options, Consumer ok, Consumer fail) { ok.accept(new JSObject()); } + @Override public void close() { listeners.clear(); } + void pedal() { Consumer listener = listeners.get(BIKE); if (listener != null) listener.accept(new JSObject().put("value", "44001c0cb000d700")); } + } + private static void shell(String command) throws Exception { + try (java.io.InputStream input = new ParcelFileDescriptor.AutoCloseInputStream(InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(command))) { + byte[] buffer = new byte[1024]; while (input.read(buffer) >= 0) { /* Drain shell output. */ } + } + } + private static void await(CountDownLatch latch, String message) throws Exception { assertTrue(message, latch.await(15, TimeUnit.SECONDS)); } + + @Test public void screenOffKeepsMeasuredTelemetryAndRecordingAndNotificationEndSavesTheRide() throws Exception { + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + if (Build.VERSION.SDK_INT >= 31) { shell("pm grant " + context.getPackageName() + " android.permission.BLUETOOTH_CONNECT"); shell("pm grant " + context.getPackageName() + " android.permission.BLUETOOTH_SCAN"); } + if (Build.VERSION.SDK_INT >= 33) shell("pm grant " + context.getPackageName() + " android.permission.POST_NOTIFICATIONS"); + AtomicReference service = new AtomicReference<>(); + CountDownLatch bound = new CountDownLatch(1), joined = new CountDownLatch(1), started = new CountDownLatch(1), measured = new CountDownLatch(1), recorded = new CountDownLatch(1), ended = new CountDownLatch(1); + ServiceConnection connection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder binder) { service.set(((RideService.LocalBinder) binder).service()); bound.countDown(); } + @Override public void onServiceDisconnected(ComponentName name) {} + }; + Radio radio = new Radio(); + ScheduledExecutorService peripheral = Executors.newSingleThreadScheduledExecutor(); + MockWebServer server = new MockWebServer(); + AtomicReference peer = new AtomicReference<>(); + server.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() { + double metres; + @Override public void onOpen(WebSocket socket, Response response) { peer.set(socket); } + @Override public void onClosing(WebSocket socket, int code, String reason) { socket.close(code, reason); } + @Override public void onMessage(WebSocket socket, String text) { + try { + JSONObject message = new JSONObject(text); + switch (message.optString("type")) { + case "hello" -> socket.send("{\"type\":\"welcome\",\"protocol_version\":2}"); + case "join" -> socket.send("{\"type\":\"joined\",\"rider_id\":7,\"resume_token\":\"test-token\"}"); + case "telemetry" -> { + if (message.optDouble("power") == 215) measured.countDown(); + assertFalse("Heart rate must remain local", message.has("heart_rate")); + metres += 1; + socket.send("{\"type\":\"state\",\"riders\":[{\"id\":7,\"route\":\"test-route\",\"distance\":" + metres + ",\"speed\":4}]}"); + } + } + } catch (Exception e) { throw new AssertionError(e); } + } + })); + server.start(); + try (ActivityScenario scenario = ActivityScenario.launch(RideTestActivity.class)) { + context.bindService(new Intent(context, RideService.class), connection, Context.BIND_AUTO_CREATE); + await(bound, "Bind native ride service"); + RideService ride = service.get(); + ride.attach(radio, event -> { + try { + if (event.optString("type").equals("open")) ride.send("test-socket", "{\"type\":\"hello\",\"protocol_version\":2,\"client_version\":\"device-test\"}"); + if (event.optString("type").equals("message")) { + JSONObject message = new JSONObject(event.optString("data")); + if (message.optString("type").equals("welcome")) ride.send("test-socket", "{\"type\":\"join\",\"name\":\"Device test\",\"weight_kg\":75}"); + if (message.optString("type").equals("joined")) joined.countDown(); + } + if (event.optString("type").equals("rideState") && event.optBoolean("ended")) ended.countDown(); + } catch (Exception e) { throw new AssertionError(e); } + }); + ride.observeEvent(BIKE); + ride.openSocket("test-socket", server.url("/ws").toString().replace("http:", "ws:"), null); + await(joined, "Join through native WebSocket"); + JSObject snapshot = new JSObject().put("version", 1).put("nativeRideId", "device-test") + .put("rideStartedAt", System.currentTimeMillis() - 65000).put("savedAt", System.currentTimeMillis()) + .put("routeId", "test-route").put("routeName", "Rolling Hills · device test").put("distance", "true".equals(InstrumentationRegistry.getArguments().getString("preview")) ? 12400 : 0) + .put("recordDurationS", "true".equals(InstrumentationRegistry.getArguments().getString("preview")) ? 1458 : 0) + .put("serverUrl", server.url("/ws").toString()).put("trainerKind", "trainer") + .put("recorder", new JSObject().put("samples", new JSArray()).put("pauses", new JSArray())); + ride.startRide(new JSObject().put("snapshot", snapshot).put("trainerId", "trainer") + .put("control", new JSObject().put("canControl", true).put("routeLengths", new JSObject().put("test-route", 1000))), value -> started.countDown(), reason -> { throw new AssertionError(reason); }); + await(started, "Start native recorder"); + ContextCompat.startForegroundService(context, new Intent(context, RideService.class)); + FileObserver journal = new FileObserver(context.getFilesDir().getAbsolutePath(), FileObserver.MODIFY) { + @Override public void onEvent(int event, String path) { + if ("active-ride.jsonl".equals(path)) ride.snapshot(-1, value -> { if (value.optJSONArray("samples").length() >= 3) recorded.countDown(); if (value.optBoolean("ended")) ended.countDown(); }); + } + }; + journal.startWatching(); + peripheral.scheduleAtFixedRate(radio::pedal, 0, 500, TimeUnit.MILLISECONDS); + scenario.moveToState(Lifecycle.State.CREATED); + ride.background(true); + shell("input keyevent 223"); + await(measured, "Native telemetry must keep measured power with the screen off"); + await(recorded, "Native journal must keep recording with the screen off"); + shell("input keyevent 224"); shell("wm dismiss-keyguard"); + NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + Notification notification = null; + for (var current : manager.getActiveNotifications()) if (current.getId() == 310) notification = current.getNotification(); + assertNotNull("The ride must have a visible ongoing notification", notification); + assertTrue((notification.flags & Notification.FLAG_FOREGROUND_SERVICE) != 0); + assertNotNull("Expanded stats card", notification.bigContentView); + assertEquals("Return and End/save actions", 2, notification.actions.length); + assertTrue(notification.extras.getCharSequence(Notification.EXTRA_TEXT).toString().contains("215")); + if ("true".equals(InstrumentationRegistry.getArguments().getString("preview"))) { + BroadcastReceiver commands = new BroadcastReceiver() { + @Override public void onReceive(Context c, Intent intent) { + String command = intent.getStringExtra("command"); + if ("end".equals(command)) { + for (var current : manager.getActiveNotifications()) if (current.getId() == 310) try { current.getNotification().actions[1].actionIntent.send(); } catch (Exception e) { throw new AssertionError(e); } + return; + } + AccessibilityNodeInfo root = InstrumentationRegistry.getInstrumentation().getUiAutomation().getRootInActiveWindow(); + if (root == null) return; + for (AccessibilityNodeInfo brand : root.findAccessibilityNodeInfosByText("OpenRadlr")) { + AccessibilityNodeInfo row = brand; + while (row != null && !"com.android.systemui:id/expandableNotificationRow".equals(row.getViewIdResourceName())) row = row.getParent(); + if (row != null) for (AccessibilityNodeInfo button : row.findAccessibilityNodeInfosByViewId("android:id/expand_button")) { + System.out.println("OPENRADLR_EXPAND " + button.performAction(AccessibilityNodeInfo.ACTION_CLICK)); return; + } + } + } + }; + ContextCompat.registerReceiver(context, commands, new IntentFilter("com.openradlr.app.TEST_NOTIFICATION"), ContextCompat.RECEIVER_EXPORTED); + System.out.println("OPENRADLR_NOTIFICATION_PREVIEW"); + try { assertTrue("End/save action from notification", ended.await(180, TimeUnit.SECONDS)); } + finally { context.unregisterReceiver(commands); } + } else { + notification.actions[1].actionIntent.send(); + await(ended, "End/save action from notification"); + } + journal.stopWatching(); + CountDownLatch recovered = new CountDownLatch(1); + ride.recover(value -> { + JSObject saved = value.getJSObject("snapshot"); + assertTrue(saved.optBoolean("finished")); + assertTrue(saved.getJSObject("recorder").optJSONArray("samples").length() >= 3); + recovered.countDown(); + }, reason -> { throw new AssertionError(reason); }); + await(recovered, "Completed ride must be recoverable from disk"); + assertEquals("Ending removes the ongoing notification", 0, manager.getActiveNotifications().length); + CountDownLatch cleared = new CountDownLatch(1); + ride.clear(reason -> cleared.countDown()); await(cleared, "Clear synthetic test ride"); + } finally { + peripheral.shutdownNow(); + context.unbindService(connection); + if (peer.get() != null) peer.get().close(1000, "Test complete"); + server.shutdown(); + shell("input keyevent 224"); shell("wm dismiss-keyguard"); + } + } +} diff --git a/app/android/app/src/androidTest/java/com/openradlr/app/ride/RidePreviewTest.java b/app/android/app/src/androidTest/java/com/openradlr/app/ride/RidePreviewTest.java new file mode 100644 index 00000000..41867880 --- /dev/null +++ b/app/android/app/src/androidTest/java/com/openradlr/app/ride/RidePreviewTest.java @@ -0,0 +1,71 @@ +package com.openradlr.app.ride; + +import static org.junit.Assert.*; +import android.content.*; +import android.os.*; +import android.webkit.WebView; +import androidx.test.core.app.ActivityScenario; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import com.getcapacitor.*; +import com.openradlr.app.MainActivity; +import java.util.Map; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** Opt-in interactive smoke check: the real app/client/server, with native radio packets supplied at the I/O boundary. */ +@RunWith(AndroidJUnit4.class) +public class RidePreviewTest { + private static final String EVENT = "notification|capture-ftms|00001826-0000-1000-8000-00805f9b34fb|00002ad2-0000-1000-8000-00805f9b34fb"; + @Test public void interactiveNativeRidePreview() throws Exception { + org.junit.Assume.assumeTrue("true".equals(InstrumentationRegistry.getArguments().getString("interactive"))); + Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); + CountDownLatch bound = new CountDownLatch(1), ended = new CountDownLatch(1); + AtomicReference owner = new AtomicReference<>(); + ServiceConnection connection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder binder) { owner.set(((RideService.LocalBinder) binder).service()); bound.countDown(); } + @Override public void onServiceDisconnected(ComponentName name) {} + }; + Map> listeners = new ConcurrentHashMap<>(); + BleTransport radio = new BleTransport() { + @Override public void listen(String event, Consumer listener) { listeners.putIfAbsent(event, listener); } + @Override public void invoke(String method, JSObject options, Consumer ok, Consumer fail) { ok.accept(new JSObject()); } + @Override public void close() { listeners.clear(); } + }; + ScheduledExecutorService packets = Executors.newSingleThreadScheduledExecutor(); + try (ActivityScenario scenario = ActivityScenario.launch(MainActivity.class)) { + CountDownLatch page = new CountDownLatch(1); + Handler main = new Handler(Looper.getMainLooper()); + Runnable ready = new Runnable() { + @Override public void run() { + scenario.onActivity(activity -> activity.getBridge().getWebView().evaluateJavascript("Boolean(document.querySelector('#route-list button'))", result -> { + if ("true".equals(result)) page.countDown(); else main.postDelayed(this, 100); + })); + } + }; + main.post(ready); + assertTrue("Local client ready", page.await(45, TimeUnit.SECONDS)); + context.bindService(new Intent(context, RideService.class), connection, Context.BIND_AUTO_CREATE); + assertTrue(bound.await(10, TimeUnit.SECONDS)); + RideService ride = owner.get(); + ride.attach(radio, null); + ride.observeEvent(EVENT); + FileObserver journal = new FileObserver(context.getFilesDir().getAbsolutePath(), FileObserver.MODIFY) { + @Override public void onEvent(int event, String path) { + if ("active-ride.jsonl".equals(path)) ride.snapshot(-1, state -> { if (state.optBoolean("ended")) ended.countDown(); }); + } + }; + journal.startWatching(); + packets.scheduleAtFixedRate(() -> { Consumer listener = listeners.get(EVENT); if (listener != null) listener.accept(new JSObject().put("value", "44001c0cb000d700")); }, 0, 500, TimeUnit.MILLISECONDS); + System.out.println("OPENRADLR_APP_PREVIEW_READY"); + assertTrue("End the synthetic ride from the app/notification", ended.await(150, TimeUnit.SECONDS)); + journal.stopWatching(); + } finally { + packets.shutdownNow(); + context.unbindService(connection); + } + } +} diff --git a/app/android/app/src/debug/AndroidManifest.xml b/app/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..2ea71417 --- /dev/null +++ b/app/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/app/android/app/src/debug/java/com/openradlr/app/ride/RideTestActivity.java b/app/android/app/src/debug/java/com/openradlr/app/ride/RideTestActivity.java new file mode 100644 index 00000000..3b1ef885 --- /dev/null +++ b/app/android/app/src/debug/java/com/openradlr/app/ride/RideTestActivity.java @@ -0,0 +1,4 @@ +package com.openradlr.app.ride; + +/** A visible host for service lifecycle instrumentation without loading a WebView. */ +public class RideTestActivity extends android.app.Activity {} diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index a0eca39b..0cf0afae 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -2,6 +2,8 @@ + + + + + + + diff --git a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java index 3a1f4f85..8dd970cc 100644 --- a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java +++ b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java @@ -13,6 +13,7 @@ protected void load() { WebView webView = findViewById(com.getcapacitor.android.R.id.webview); String suffix = " OpenRadlr/" + BuildConfig.VERSION_NAME + " (android; build/" + BuildConfig.VERSION_CODE + ")"; webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + suffix); + registerPlugin(com.openradlr.app.ride.BackgroundRidePlugin.class); super.load(); // Ride visibility is controlled by SystemBars from the client. Keep edge // swipes available while hidden, without forcing fullscreen on the menu. diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/BackgroundRidePlugin.java b/app/android/app/src/main/java/com/openradlr/app/ride/BackgroundRidePlugin.java new file mode 100644 index 00000000..5d0df60b --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/BackgroundRidePlugin.java @@ -0,0 +1,124 @@ +package com.openradlr.app.ride; + +import android.Manifest; +import android.content.*; +import android.net.Uri; +import android.os.*; +import android.provider.Settings; +import android.webkit.CookieManager; +import androidx.core.content.ContextCompat; +import androidx.lifecycle.Lifecycle; +import com.getcapacitor.*; +import com.getcapacitor.annotation.*; +import java.net.URI; +import java.util.*; +import java.util.function.Consumer; + +@CapacitorPlugin(name = "BackgroundRide", permissions = @Permission(alias = "notifications", strings = Manifest.permission.POST_NOTIFICATIONS)) +public class BackgroundRidePlugin extends Plugin { + private RideService service; + private boolean binding; + private final List> pending = new ArrayList<>(); + private final ServiceConnection connection = new ServiceConnection() { + @Override public void onServiceConnected(ComponentName name, IBinder binder) { + service = ((RideService.LocalBinder) binder).service(); + service.attach(new NativeBle(bridge), event -> notifyListeners("event", event)); + service.background(!getActivity().hasWindowFocus()); + List> ready = new ArrayList<>(pending); pending.clear(); + for (Consumer task : ready) task.accept(service); + } + @Override public void onServiceDisconnected(ComponentName name) { + service = null; binding = false; + notifyListeners("event", new JSObject().put("type", "serviceLost")); + } + }; + private void withService(Consumer task) { + bridge.executeOnMainThread(() -> { + if (service != null) { task.accept(service); return; } + pending.add(task); + if (!binding) { + binding = true; + if (!getContext().bindService(new Intent(getContext(), RideService.class), connection, Context.BIND_AUTO_CREATE)) { + binding = false; pending.clear(); + notifyListeners("event", new JSObject().put("type", "serviceLost")); + } + } + }); + } + @PluginMethod public void openSocket(PluginCall call) { + String id = call.getString("id"), url = call.getString("url"); + try { + URI address = URI.create(url), server = URI.create(bridge.getConfig().getServerUrl()); + String scheme = server.getScheme().equals("https") ? "wss" : "ws"; + if (id == null || !scheme.equals(address.getScheme()) || !Objects.equals(server.getHost(), address.getHost()) + || server.getPort() != address.getPort() || !"/ws".equals(address.getPath()) || address.getUserInfo() != null) { + call.reject("The ride socket must use this app's server"); return; + } + bridge.executeOnMainThread(() -> { + String cookie = CookieManager.getInstance().getCookie(server.toString()); + withService(s -> { s.openSocket(id, url, cookie); call.resolve(); }); + }); + } catch (RuntimeException e) { call.reject("Invalid ride server URL"); } + } + @PluginMethod public void sendSocket(PluginCall call) { + String text = call.getString("data", ""); + if (text.length() > 16384) { call.reject("Ride message is too large"); return; } + withService(s -> { s.send(call.getString("id"), text); call.resolve(); }); + } + @PluginMethod public void closeSocket(PluginCall call) { withService(s -> { s.closeSocket(call.getString("id")); call.resolve(); }); } + @PluginMethod public void observeEvent(PluginCall call) { + String event = call.getString("event", ""); + if (event.length() > 256) { call.reject("Invalid Bluetooth event"); return; } + withService(s -> { s.observeEvent(event); call.resolve(); }); + } + @PluginMethod public void bleOperation(PluginCall call) { + String method = call.getString("method", ""); + if (!Arrays.asList("connect", "getServices", "startNotifications", "write", "writeWithoutResponse").contains(method)) { call.reject("Unsupported Bluetooth operation"); return; } + JSObject options = call.getObject("options"); + if (options == null) { call.reject("Bluetooth options are missing"); return; } + withService(s -> s.bleOperation(method, options, call::resolve, call::reject)); + } + @PluginMethod public void startRide(PluginCall call) { + if (Build.VERSION.SDK_INT >= 33 && getPermissionState("notifications") != PermissionState.GRANTED + && !getContext().getSharedPreferences("ride", Context.MODE_PRIVATE).getBoolean("askedNotification", false)) { + getContext().getSharedPreferences("ride", Context.MODE_PRIVATE).edit().putBoolean("askedNotification", true).apply(); + requestPermissionForAlias("notifications", call, "notificationsResult"); + return; + } + begin(call); + } + @PermissionCallback private void notificationsResult(PluginCall call) { begin(call); } + private void begin(PluginCall call) { + withService(s -> { + if (getActivity().isFinishing() || !getActivity().getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) { call.reject("Start background riding while the app is visible", "BACKGROUND_START"); return; } + s.startRide(call.getData(), result -> bridge.executeOnMainThread(() -> { + try { + ContextCompat.startForegroundService(getContext(), new Intent(getContext(), RideService.class)); + call.resolve(result); + } catch (RuntimeException e) { + s.stopRide(false, stopped -> call.reject("Android could not start background riding", "BACKGROUND_START", e)); + } + }), reason -> call.reject(reason, "BACKGROUND_START")); + }); + } + @PluginMethod public void updateRide(PluginCall call) { withService(s -> { s.update(call.getData()); call.resolve(); }); } + @PluginMethod public void snapshot(PluginCall call) { withService(s -> s.snapshot(call.getLong("since", -1L), call::resolve)); } + @PluginMethod public void stopRide(PluginCall call) { withService(s -> s.stopRide(call.getBoolean("finished", false), call::resolve)); } + @PluginMethod public void recover(PluginCall call) { withService(s -> s.recover(call::resolve, call::reject)); } + @PluginMethod public void clear(PluginCall call) { withService(s -> s.clear(error -> { if (error == null) call.resolve(); else call.reject(error); })); } + @PluginMethod public void openSettings(PluginCall call) { + bridge.executeOnMainThread(() -> { + String kind = call.getString("kind", "app"); + Intent intent = kind.equals("bluetooth") ? new Intent(Settings.ACTION_BLUETOOTH_SETTINGS) + : new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getContext().getPackageName())); + try { getActivity().startActivity(intent); call.resolve(); } + catch (RuntimeException e) { call.reject("Settings could not be opened", e); } + }); + } + @Override protected void handleOnStop() { if (service != null) service.background(true); } + @Override protected void handleOnResume() { if (service != null) service.background(false); } + @Override protected void handleOnDestroy() { + if (service != null) service.detach(); + if (binding) { getContext().unbindService(connection); binding = false; } + } +} diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/BleTransport.java b/app/android/app/src/main/java/com/openradlr/app/ride/BleTransport.java new file mode 100644 index 00000000..7efbb82a --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/BleTransport.java @@ -0,0 +1,11 @@ +package com.openradlr.app.ride; + +import com.getcapacitor.JSObject; +import java.util.function.Consumer; + +/** Native radio boundary: production delegates to the installed BLE plugin. */ +public interface BleTransport { + void listen(String event, Consumer listener); + void invoke(String method, JSObject options, Consumer ok, Consumer fail); + void close(); +} diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/NativeBle.java b/app/android/app/src/main/java/com/openradlr/app/ride/NativeBle.java new file mode 100644 index 00000000..0dae5eaf --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/NativeBle.java @@ -0,0 +1,83 @@ +package com.openradlr.app.ride; + +import com.capacitorjs.community.plugins.bluetoothle.BluetoothLe; +import com.getcapacitor.*; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; + +/** Reuses the BLE plugin's public native calls; there is only one GATT owner. */ +public final class NativeBle implements BleTransport { + private final Bridge bridge; + private final BluetoothLe plugin; + private final Map listeners = new HashMap<>(); + private long sequence; + private boolean closed; + private final ExecutorService operations = Executors.newSingleThreadExecutor(); + private final Map> queues = new HashMap<>(); + public NativeBle(Bridge bridge) { + this.bridge = bridge; + plugin = (BluetoothLe) bridge.getPlugin("BluetoothLe").getInstance(); + } + public synchronized void listen(String event, Consumer listener) { + if (closed) return; + if (listeners.containsKey(event)) return; + PluginCall call = call("addListener", new JSObject().put("eventName", event), listener, error -> {}); + listeners.put(event, call); + bridge.saveCall(call); + operations.execute(() -> plugin.addListener(call)); + } + public synchronized void invoke(String method, JSObject options, Consumer ok, Consumer error) { + if (closed) { error.accept("Ride Bluetooth transport is closed"); return; } + String id = options.getString("deviceId", "adapter"); + ArrayDeque queue = queues.computeIfAbsent(id, key -> new ArrayDeque<>()); + queue.add(() -> { + PluginCall call = call(method, options, value -> { complete(id); ok.accept(value); }, reason -> { complete(id); error.accept(reason); }); + operations.execute(() -> { + try { + switch (method) { + case "connect" -> plugin.connect(call); + case "getServices" -> plugin.getServices(call); + case "startNotifications" -> plugin.startNotifications(call); + case "write" -> plugin.write(call); + case "writeWithoutResponse" -> plugin.writeWithoutResponse(call); + default -> call.reject("Unsupported native BLE operation"); + } + } catch (RuntimeException e) { call.reject(e.getMessage()); } + }); + }); + if (queue.size() == 1) queue.peekFirst().run(); + } + private synchronized void complete(String id) { + ArrayDeque queue = queues.get(id); + if (queue == null) return; + queue.removeFirst(); + if (closed || queue.isEmpty()) queues.remove(id); + else queue.peekFirst().run(); + } + private PluginCall call(String method, JSObject options, Consumer ok, Consumer error) { + return new PluginCall(null, "BluetoothLe", "ride-native-" + (++sequence), method, options) { + @Override public void resolve(JSObject value) { ok.accept(value == null ? new JSObject() : value); } + @Override public void resolve() { ok.accept(new JSObject()); } + @Override public void reject(String message, String code, Exception exception, JSObject data) { error.accept(message); } + @Override public void setKeepAlive(Boolean value) { /* Native listeners are released explicitly. */ } + }; + } + public synchronized void close() { + if (closed) return; + closed = true; + for (var entry : listeners.entrySet()) { + PluginCall remove = call("removeListener", new JSObject().put("eventName", entry.getKey()) + .put("callbackId", entry.getValue().getCallbackId()), result -> {}, error -> {}); + operations.execute(() -> plugin.removeListener(remove)); + } + listeners.clear(); + operations.shutdown(); + } + public static String hex(byte[] bytes) { + StringBuilder out = new StringBuilder(); + for (byte b : bytes) out.append(String.format(java.util.Locale.ROOT, "%02x", b & 255)); + return out.toString(); + } +} diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java new file mode 100644 index 00000000..419c2fd8 --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java @@ -0,0 +1,180 @@ +package com.openradlr.app.ride; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +/** Clock/sensor/control logic; no Android, WebView, networking or file I/O. */ +public final class RideEngine { + public record Sample(long t, double distance, double power, Double cadence, Double heartRate, + double speed, String route, Double routeM) {} + public record Command(Double power, double grade, double crr, double cw) { + public byte[] bytes() { + ByteBuffer b = ByteBuffer.allocate(power == null ? 7 : 3).order(ByteOrder.LITTLE_ENDIAN); + if (power != null) b.put((byte) 5).putShort((short) Math.round(clamp(power, 0, 4000))); + else b.put((byte) 17).putShort((short) 0).putShort((short) Math.round(clamp(grade * 100, -32768, 32767))) + .put((byte) Math.round(clamp(crr * 10000, 0, 255))).put((byte) Math.round(clamp(cw * 100, 0, 255))); + return b.array(); + } + } + public static final class Control { + public double difficulty = 1, crr = .004, ftp = 200, intensity = 1; + public double ratio = 0, referenceRatio = 1, mass = 85, cda = .32, airDensity = 1.225; + public Double target = null; + public double[][] segments = new double[0][]; + public double elapsed = 0; + public boolean classClock = false, erg = false; + } + private final Consumer sink; + private double ftmsPower, cpsPower; + private Double cadence, embeddedHeartRate, strapHeartRate; + private long ftmsAt = Long.MIN_VALUE / 2, cpsAt = Long.MIN_VALUE / 2; + private long cadenceAt = Long.MIN_VALUE / 2, heartAt = Long.MIN_VALUE / 2, strapAt = Long.MIN_VALUE / 2; + private int crankRevs = -1, crankTime; + private long crankChangedAt; + private long lastTick = -1, lastSample = Long.MIN_VALUE / 2, stateAt = Long.MIN_VALUE / 2; + private double speed, routeM; + private String route; + private boolean hasState; + private double grade, easedGrade; + private boolean hasGrade; + public double distance, durationS; + public boolean paused, background; + public Control control = new Control(); + public final Map routeLengths = new HashMap<>(); + + public RideEngine(Consumer sink) { this.sink = sink; } + + /** Malformed/truncated radio packets cannot partially update a reading. */ + public synchronized void packet(String role, String characteristic, String hex, long now) { + try { + String clean = hex.replace(" ", ""); + if (clean.length() % 2 != 0) return; + byte[] bytes = new byte[clean.length() / 2]; + for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) Integer.parseInt(clean.substring(i * 2, i * 2 + 2), 16); + ByteBuffer b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); + if (characteristic.equals("2ad2") && role.equals("trainer")) { + int flags = u16(b), p = 2; + if ((flags & 1) == 0) p += 2; + if ((flags & 2) != 0) p += 2; + Double nextCadence = null, nextPower = null, nextHr = null; + if ((flags & 4) != 0) { nextCadence = (double) Short.toUnsignedInt(b.getShort(p)) / 2; p += 2; } + if ((flags & 8) != 0) p += 2; + if ((flags & 16) != 0) p += 3; + if ((flags & 32) != 0) p += 2; + if ((flags & 64) != 0) { nextPower = (double) b.getShort(p); p += 2; } + if ((flags & 128) != 0) p += 2; + if ((flags & 256) != 0) p += 5; + if ((flags & 512) != 0) nextHr = (double) Byte.toUnsignedInt(b.get(p)); + if (nextPower != null) { ftmsPower = clamp(nextPower, 0, 4000); ftmsAt = now; } + if (nextCadence != null) { cadence = clamp(nextCadence, 0, 250); cadenceAt = now; } + if (nextHr != null) { embeddedHeartRate = validHr(nextHr); heartAt = now; } + } else if (characteristic.equals("2a63") && role.equals("trainer")) { + int flags = u16(b); + double power = b.getShort(); + int p = 4 + ((flags & 1) != 0 ? 1 : 0) + ((flags & 4) != 0 ? 2 : 0) + ((flags & 16) != 0 ? 6 : 0); + if ((flags & 32) != 0) crank(Short.toUnsignedInt(b.getShort(p)), Short.toUnsignedInt(b.getShort(p + 2)), now); + cpsPower = clamp(power, 0, 4000); cpsAt = now; + } else if (characteristic.equals("2a37") && role.equals("hr")) { + int flags = Byte.toUnsignedInt(b.get()); + strapHeartRate = validHr((flags & 1) == 0 ? Byte.toUnsignedInt(b.get()) : u16(b)); + strapAt = now; + } + } catch (IllegalArgumentException | IndexOutOfBoundsException | java.nio.BufferUnderflowException ignored) { + // The next valid notification can still be used. + } + } + + private void crank(int revs, int time, long now) { + if (crankRevs >= 0) { + int dRevs = (revs - crankRevs + 65536) % 65536, dTime = (time - crankTime + 65536) % 65536; + if (dRevs > 0 && dTime > 0) { cadence = clamp(dRevs * 60.0 * 1024 / dTime, 0, 250); crankChangedAt = now; } + else if (now - crankChangedAt > 3000) cadence = 0.0; + cadenceAt = now; + } else crankChangedAt = now; + crankRevs = revs; crankTime = time; + } + + public synchronized boolean fresh(long now) { return now - Math.max(ftmsAt, cpsAt) <= 5000; } + public synchronized double progress() { + double total = 0; for (double[] s : control.segments) total += s[0]; + if (total > 0) return clamp(control.elapsed / total, 0, 1); + double length = routeLengths.getOrDefault(route, 0.0); + return length > 0 ? clamp(routeM / length, 0, 1) : -1; + } + public synchronized double power(long now) { + if (now - ftmsAt <= 2000) return ftmsPower; + return now - cpsAt <= 5000 ? cpsPower : now - ftmsAt <= 5000 ? ftmsPower : 0; + } + public synchronized Double cadence(long now) { return now - cadenceAt <= 5000 ? cadence : null; } + public synchronized Double heartRate(long now) { return now - strapAt <= 5000 ? strapHeartRate : now - heartAt <= 5000 ? embeddedHeartRate : null; } + public synchronized double[] telemetry(long now) { Double rpm = cadence(now); return new double[] {power(now), rpm == null ? Double.NaN : rpm}; } + public synchronized void disconnected() { ftmsAt = cpsAt = cadenceAt = Long.MIN_VALUE / 2; } + public synchronized void resistance(double grade) { if (!Double.isFinite(grade)) return; this.grade = grade; if (!hasGrade) easedGrade = grade; hasGrade = true; } + + /** Server positions wrap on a lap. Do not invent distance during an outage. */ + public synchronized void state(String nextRoute, double metres, double nextSpeed, long now) { + if (!Double.isFinite(metres) || !Double.isFinite(nextSpeed)) return; + if (hasState && !paused && now - stateAt <= 3000) { + double delta = metres - routeM; + boolean same = java.util.Objects.equals(route, nextRoute); + if (same && delta < 0 && routeLengths.containsKey(route)) delta += routeLengths.get(route); + double estimated = Math.max(0, nextSpeed) * Math.max(0, now - stateAt) / 1000; + distance += same && delta >= 0 && delta <= estimated * 3 + 20 ? delta : estimated; + } + route = nextRoute; routeM = metres; speed = Math.max(0, nextSpeed); stateAt = now; hasState = true; + } + public synchronized void resetPosition() { hasState = false; } + + public synchronized void tick(long wall, long now) { + double dt = lastTick < 0 ? 0 : Math.max(0, now - lastTick) / 1000.0; + lastTick = now; + if (!paused) durationS += dt; + if (background && !paused) { + Double rpm = cadence(now); + if (control.classClock || (now - Math.max(ftmsAt, cpsAt) <= 5000 && (rpm == null || rpm >= 15))) control.elapsed += dt; + } + if (hasGrade) { + double gap = grade - easedGrade, step = gap * (1 - Math.exp(-dt / 1.5)); + easedGrade += clamp(step, -1.5 * dt, 1.5 * dt); + if (Math.abs(grade - easedGrade) < .05) easedGrade = grade; + } + if (!paused && now - lastSample >= 1000) { + lastSample = now; + sink.accept(new Sample(wall, distance, power(now), cadence(now), heartRate(now), + now - stateAt <= 2000 ? speed : 0, route, hasState ? routeM : null)); + } + } + + public synchronized Command command(long now) { + Control c = control; + if (paused || now - Math.max(ftmsAt, cpsAt) > 5000) return new Command(null, 0, c.crr, .51); + Double target = c.target; + if (c.segments.length > 0 && c.erg) { + double elapsed = c.elapsed; + target = c.ftp * .5; + for (double[] segment : c.segments) { + if (elapsed < 0) break; + if (elapsed < segment[0]) { target = (segment[1] + (segment[2] - segment[1]) * elapsed / segment[0]) * c.ftp * c.intensity; break; } + elapsed -= segment[0]; + } + } + if (c.erg && target != null) return new Command(clamp(target, 0, 4000), 0, c.crr, .51); + double road = easedGrade >= 0 ? easedGrade * clamp(c.difficulty, 0, 1) : easedGrade * .5; + if (c.ratio > 0 && c.referenceRatio > 0) { + double theta = Math.atan(easedGrade / 100), weight = Math.max(1, c.mass) * 9.80665; + double v = now - stateAt <= 2000 ? speed : 0; + double force = weight * (Math.sin(theta) + c.crr * Math.cos(theta)) + .5 * c.airDensity * c.cda * v * v; + double wanted = c.ratio / c.referenceRatio * Math.max(force, weight * .015); + double sin = clamp(wanted / weight - c.crr, -.99, .99); + road = clamp(Math.round(Math.tan(Math.asin(sin)) * 1000) / 10.0, -10, 20); + return new Command(null, road, c.crr, 0); + } + return new Command(null, road, c.crr, .51); + } + private static int u16(ByteBuffer b) { return Short.toUnsignedInt(b.getShort()); } + private static Double validHr(double value) { return value > 0 && value <= 255 ? value : null; } + private static double clamp(double v, double lo, double hi) { return Math.min(hi, Math.max(lo, v)); } +} diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideJournal.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideJournal.java new file mode 100644 index 00000000..53576095 --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideJournal.java @@ -0,0 +1,82 @@ +package com.openradlr.app.ride; + +import com.getcapacitor.JSArray; +import com.getcapacitor.JSObject; +import java.io.*; +import java.nio.charset.StandardCharsets; +import org.json.JSONObject; + +/** One app-private, append-only ride; each complete sample is synced to disk. */ +public final class RideJournal { + private final File file; + private FileOutputStream output; + public RideJournal(File directory) { file = new File(directory, "active-ride.jsonl"); } + public synchronized void start(JSObject snapshot) throws IOException { + close(); + output = new FileOutputStream(file, false); + append(new JSObject().put("snapshot", snapshot)); + } + public synchronized void sample(RideEngine.Sample sample) throws IOException { + append(new JSObject().put("sample", sampleJson(sample))); + } + public synchronized void checkpoint(JSObject snapshot) throws IOException { append(new JSObject().put("checkpoint", snapshot)); } + private void append(JSObject value) throws IOException { + if (output == null) return; + output.write((value + "\n").getBytes(StandardCharsets.UTF_8)); + output.getFD().sync(); + } + public synchronized JSObject recover() throws IOException { + JSObject snapshot = null; + JSArray samples = new JSArray(); + if (!file.exists()) return null; + try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { + String line; + while ((line = input.readLine()) != null) { + try { + JSONObject entry = new JSONObject(line); + if (entry.has("snapshot")) snapshot = JSObject.fromJSONObject(entry.getJSONObject("snapshot")); + if (entry.has("checkpoint") && snapshot != null) { + JSONObject update = entry.getJSONObject("checkpoint"); + for (var keys = update.keys(); keys.hasNext();) { + String key = keys.next(); + if (key.equals("recorder") && update.optJSONObject(key) != null && snapshot.optJSONObject(key) != null) { + JSONObject record = snapshot.getJSONObject(key), patch = update.getJSONObject(key); + for (var fields = patch.keys(); fields.hasNext();) { String field = fields.next(); record.put(field, patch.get(field)); } + } else snapshot.put(key, update.get(key)); + } + } + if (entry.has("sample")) samples.put(entry.getJSONObject("sample")); + } catch (org.json.JSONException ignored) { break; } // A torn final write does not discard earlier samples. + } + } + if (snapshot == null) return null; + JSONObject recorder = snapshot.optJSONObject("recorder"); + if (recorder == null) recorder = new JSONObject(); + JSArray combined = new JSArray(); + org.json.JSONArray prior = recorder.optJSONArray("samples"); + if (prior != null) for (int i = 0; i < prior.length(); i++) combined.put(prior.opt(i)); + for (int i = 0; i < samples.length(); i++) combined.put(samples.opt(i)); + try { + recorder.put("samples", combined); + if (!recorder.has("pauses")) recorder.put("pauses", new JSArray()); + snapshot.put("recorder", recorder); + if (samples.length() > 0) { + JSONObject last = samples.getJSONObject(samples.length() - 1); + snapshot.put("savedAt", last.getLong("t")); + snapshot.put("distance", last.getDouble("distance")); + if (!snapshot.optBoolean("studio")) snapshot.put("resumePoint", new JSObject() + .put("routeId", last.opt("route")).put("distanceM", last.opt("routeM"))); + } + } catch (org.json.JSONException e) { throw new IOException(e); } + return snapshot; + } + public synchronized void close() throws IOException { if (output != null) { output.close(); output = null; } } + public synchronized void clear() throws IOException { close(); if (file.exists() && !file.delete()) throw new IOException("Cannot remove ride journal"); } + public static JSObject sampleJson(RideEngine.Sample s) { + return new JSObject().put("t", s.t()).put("distance", s.distance()).put("power", s.power()) + .put("cadence", s.cadence() == null ? JSONObject.NULL : s.cadence()) + .put("heartRate", s.heartRate() == null ? JSONObject.NULL : s.heartRate()) + .put("speed", s.speed()).put("lat", JSONObject.NULL).put("lon", JSONObject.NULL).put("elevation", JSONObject.NULL).put("route", s.route() == null ? JSONObject.NULL : s.route()) + .put("routeM", s.routeM() == null ? JSONObject.NULL : s.routeM()); + } +} diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java new file mode 100644 index 00000000..bca950ad --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java @@ -0,0 +1,453 @@ +package com.openradlr.app.ride; + +import android.app.*; +import android.content.*; +import android.content.pm.ServiceInfo; +import android.os.*; +import android.widget.RemoteViews; +import android.view.View; +import androidx.core.app.NotificationCompat; +import com.getcapacitor.*; +import com.openradlr.app.BuildConfig; +import com.openradlr.app.MainActivity; +import com.openradlr.app.R; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import okhttp3.*; +import org.json.*; + +/** A user-started ride owns its radio callbacks, socket, clock and journal here. */ +public class RideService extends Service { + public static final String END = "com.openradlr.app.END_RIDE"; + private static final int NOTIFICATION_ID = 310; + private static final String CHANNEL = "active-ride"; + public final class LocalBinder extends Binder { public RideService service() { return RideService.this; } } + private final LocalBinder binder = new LocalBinder(); + private Handler worker; + private HandlerThread thread; + private PowerManager.WakeLock wakeLock; + private final OkHttpClient http = new OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS).build(); + private WebSocket socket; + private String socketId, url, cookie, hello, join; + private long socketGeneration; + private int reconnectAttempt; + private boolean reconnecting, intentionalClose; + private Consumer emitter; + private BleTransport ble; + private final Map watched = new LinkedHashMap<>(); + private final Set reconnectingDevices = new HashSet<>(); + private final Map freshBle = new LinkedHashMap<>(); + private final Set disconnectedDevices = new HashSet<>(); + private final Map latestFrames = new LinkedHashMap<>(); + private final ArrayDeque importantFrames = new ArrayDeque<>(); + private final List samples = new ArrayList<>(); + private RideEngine engine; + private RideJournal journal; + private JSObject baseline; + private long riderId = -1, anchorWall, anchorElapsed, lastNotification; + private String trainerId, hrId, error; + private boolean imperial; + private boolean active, ended, background, writing, canControl, controlRefused, afkWarning; + private byte[] lastControl; + + @Override public void onCreate() { + super.onCreate(); + thread = new HandlerThread("OpenRadlr ride"); thread.start(); worker = new Handler(thread.getLooper()); + journal = new RideJournal(getFilesDir()); + PowerManager power = (PowerManager) getSystemService(POWER_SERVICE); + wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "OpenRadlr:ride"); + if (Build.VERSION.SDK_INT >= 26) { + NotificationChannel channel = new NotificationChannel(CHANNEL, getString(R.string.ride_channel), NotificationManager.IMPORTANCE_LOW); + channel.setDescription(getString(R.string.ride_channel_description)); + channel.setShowBadge(false); + ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).createNotificationChannel(channel); + } + } + @Override public IBinder onBind(Intent intent) { return binder; } + @Override public int onStartCommand(Intent intent, int flags, int startId) { + if (intent != null && END.equals(intent.getAction())) { + worker.post(() -> endFromNotification()); + return START_NOT_STICKY; + } + if (Build.VERSION.SDK_INT >= 29) startForeground(NOTIFICATION_ID, notification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE); + else startForeground(NOTIFICATION_ID, notification()); + return START_NOT_STICKY; + } + public void execute(Runnable task) { worker.post(task); } + public void attach(BleTransport nativeBle, Consumer events) { execute(() -> { if (!active && ble != nativeBle) { if (ble != null) ble.close(); watched.clear(); freshBle.clear(); ble = nativeBle; } if (events != null) emitter = events; }); } + public void background(boolean value) { + execute(() -> { + background = value; + if (engine != null) engine.background = value; + if (!value) { + for (JSObject packet : freshBle.values()) if (SystemClock.elapsedRealtime() - packet.optLong("at") <= 2000) emit(packet); + for (String id : disconnectedDevices) emit(new JSObject().put("type", "ble").put("event", "disconnected|" + id).put("value", new JSObject())); + for (JSObject frame : importantFrames) emit(frame); + importantFrames.clear(); + for (JSObject frame : latestFrames.values()) emit(frame); + latestFrames.clear(); + emit(new JSObject().put("type", "rideState").put("ended", ended)); + } + }); + } + + /** Starts with an existing native BLE connection and the existing game's rider. */ + public void startRide(JSObject data, Consumer ok, Consumer fail) { + execute(() -> { + try { + if (active) { fail.accept("A ride is already active"); return; } + baseline = data.getJSObject("snapshot", new JSObject()); + trainerId = data.getString("trainerId"); hrId = data.getString("hrId"); + if (trainerId == null || socket == null || riderId < 0) { fail.accept("Connect a trainer and join a ride first"); return; } + samples.clear(); error = null; ended = false; controlRefused = afkWarning = false; + anchorWall = System.currentTimeMillis(); anchorElapsed = SystemClock.elapsedRealtime(); + journal.start(baseline); + engine = new RideEngine(sample -> { + JSObject value = RideJournal.sampleJson(sample); + samples.add(value); + try { journal.sample(sample); } catch (IOException e) { recordingError(); } + }); + engine.distance = baseline.optDouble("distance", 0); + engine.durationS = baseline.optDouble("recordDurationS", 0); + engine.background = background; + configure(data.getJSObject("control", new JSObject())); + for (JSObject packet : freshBle.values()) { + if (SystemClock.elapsedRealtime() - packet.optLong("at") > 2000) continue; + String[] parts = packet.optString("event").split("\\|", -1); + if (parts.length == 4) engine.packet(parts[1].equals(trainerId) ? "trainer" : parts[1].equals(hrId) ? "hr" : "other", shortUuid(parts[3]), packet.getJSObject("value", new JSObject()).optString("value", ""), packet.optLong("at")); + } + active = true; + worker.removeCallbacks(tick); worker.post(tick); + wakeLock.acquire(12 * 60 * 60 * 1000L); + ok.accept(new JSObject().put("active", true)); + } catch (Exception e) { active = false; stopResources(); fail.accept(e.getMessage()); } + }); + } + public void update(JSObject data) { execute(() -> { + if (!active) return; + if (!background) { JSObject control = data.getJSObject("control"); if (control != null) configure(control); } + JSObject checkpoint = data.getJSObject("checkpoint"); + if (checkpoint != null) try { journal.checkpoint(checkpoint); } catch (IOException e) { recordingError(); } + }); } + private void configure(JSObject data) { + if (engine == null) return; + RideEngine.Control c = new RideEngine.Control(); + c.difficulty = finite(data, "difficulty", 1); c.crr = finite(data, "crr", .004); + c.ftp = finite(data, "ftp", 200); c.intensity = finite(data, "intensity", 1); + c.ratio = finite(data, "ratio", 0); c.referenceRatio = finite(data, "referenceRatio", 1); + c.mass = finite(data, "mass", 85); c.cda = finite(data, "cda", .32); c.airDensity = finite(data, "airDensity", 1.225); + c.elapsed = finite(data, "elapsed", 0); c.erg = data.optBoolean("erg"); c.classClock = data.optBoolean("classClock"); + if (!data.isNull("target") && data.has("target")) c.target = finite(data, "target", 0); + JSONArray segments = data.optJSONArray("segments"); + if (segments != null && segments.length() <= 500) { + List valid = new ArrayList<>(); + for (int i = 0; i < segments.length(); i++) { + JSONObject s = segments.optJSONObject(i); + if (s != null && s.optDouble("durationS", 0) > 0) valid.add(new double[] {Math.min(21600, s.optDouble("durationS")), Math.max(0, Math.min(3, s.optDouble("from"))), Math.max(0, Math.min(3, s.optDouble("to")))}); + } + c.segments = valid.toArray(new double[0][]); + } + engine.control = c; + imperial = "imperial".equals(data.optString("units")); + engine.paused = data.optBoolean("paused"); canControl = data.optBoolean("canControl"); + JSONObject lengths = data.optJSONObject("routeLengths"); + if (lengths != null) for (Iterator keys = lengths.keys(); keys.hasNext();) { + String key = keys.next(); double length = lengths.optDouble(key, 0); + if (length > 0 && Double.isFinite(length)) engine.routeLengths.put(key, length); + } + } + public void snapshot(long since, Consumer ok) { execute(() -> { + JSArray pending = new JSArray(); + for (JSObject sample : samples) if (sample.optLong("t") > since && pending.length() < 1000) pending.put(sample); + ok.accept(new JSObject().put("samples", pending).put("active", active).put("ended", ended) + .put("distance", engine == null ? 0 : engine.distance).put("elapsed", engine == null ? 0 : engine.control.elapsed) + .put("background", background).put("error", error == null ? JSONObject.NULL : error)); + }); } + public void recover(Consumer ok, Consumer fail) { execute(() -> { + try { JSObject recovered = journal.recover(); ok.accept(new JSObject().put("snapshot", recovered == null ? JSONObject.NULL : recovered)); } + catch (IOException e) { fail.accept(e.getMessage()); } + }); } + public void clear(Consumer done) { execute(() -> { try { + if (active) { done.accept("Cannot discard an active ride"); return; } + journal.clear(); done.accept(null); + } catch (IOException e) { done.accept(e.getMessage()); } }); } + public void stopRide(boolean finished, Consumer ok) { execute(() -> { + finishJournal(finished); active = false; ended = finished; stopResources(); + snapshot(samples.size() > 1000 ? samples.get(samples.size() - 1001).optLong("t") : -1, ok); + }); } + private void finishJournal(boolean finished) { + try { journal.checkpoint(new JSObject().put("finished", finished)); journal.close(); } + catch (IOException e) { recordingError(); } + } + private void stopResources() { + if (wakeLock.isHeld()) wakeLock.release(); + stopForeground(STOP_FOREGROUND_REMOVE); stopSelf(); + } + private void recordingError() { + error = "journal"; + notifyStats(); + } + private final Runnable tick = new Runnable() { + @Override public void run() { + if (active && engine != null) { + long elapsed = SystemClock.elapsedRealtime(); + engine.tick(anchorWall + elapsed - anchorElapsed, elapsed); + if (background) { + double[] reading = engine.telemetry(elapsed); + JSObject telemetry = new JSObject().put("type", "telemetry").put("power", reading[0]); + if (Double.isFinite(reading[1])) telemetry.put("cadence", reading[1]); + sendNative(telemetry.toString()); + if (canControl && !writing) writeControl(engine.command(elapsed).bytes()); + } + if (elapsed - lastNotification >= 2000) { lastNotification = elapsed; notifyStats(); } + } + if (active) worker.postDelayed(this, 250); + } + }; + + /** Native subscription taps receive packets even if JavaScript is suspended. */ + public void observeEvent(String requestedEvent) { execute(() -> { + if (ble == null) return; + String[] parts = requestedEvent.split("\\|", -1); + if (parts.length == 4 && parts[0].equals("notification")) { + if (parts[2].length() == 4) parts[2] = uuid(parts[2]); + if (parts[3].length() == 4) parts[3] = uuid(parts[3]); + } + String event = parts.length == 4 ? parts[0] + "|" + parts[1] + "|" + parts[2] + "|" + parts[3] : requestedEvent; + if (parts.length == 4 && parts[0].equals("notification")) { + JSObject options = new JSObject().put("deviceId", parts[1]).put("service", parts[2]).put("characteristic", parts[3]); + watched.put(event, options); + } + ble.listen(event, value -> execute(() -> { + long now = SystemClock.elapsedRealtime(); + JSObject packet = new JSObject().put("type", "ble").put("event", event).put("value", value).put("at", now); + if (parts.length == 4 && parts[0].equals("notification")) { + freshBle.put(event, packet); + if (parts[1].equals(trainerId) && "2ad9".equals(shortUuid(parts[3]))) { + String response = value.optString("value", "").replace(" ", "").toLowerCase(java.util.Locale.ROOT); + if (response.length() >= 6 && response.startsWith("80") && !response.substring(4, 6).equals("01")) { canControl = false; controlRefused = true; } + } + if (active && engine != null) engine.packet(parts[1].equals(trainerId) ? "trainer" : parts[1].equals(hrId) ? "hr" : "other", shortUuid(parts[3]), value.optString("value", ""), now); + } + if (parts.length == 2 && parts[0].equals("disconnected")) { + disconnectedDevices.add(parts[1]); + if (parts[1].equals(trainerId) && engine != null) engine.disconnected(); + if (active && background && (parts[1].equals(trainerId) || parts[1].equals(hrId))) reconnectDevice(parts[1], 0); + } + if (!active || !background) emit(packet); + })); + }); } + public void bleOperation(String method, JSObject options, Consumer ok, Consumer fail) { + execute(() -> { + if (background && active && (method.equals("write") || method.equals("writeWithoutResponse")) + && Objects.equals(trainerId, options.getString("deviceId")) && "2ad9".equals(shortUuid(options.getString("characteristic", "")))) { + ok.accept(new JSObject()); return; + } + if (ble == null) { fail.accept("Bluetooth is unavailable"); return; } + ble.invoke(method, options, value -> { + if (method.equals("connect")) execute(() -> disconnectedDevices.remove(options.getString("deviceId"))); + ok.accept(value); + }, fail); + }); + } + private void reconnectDevice(String id, int attempt) { + if (!active || !background || !reconnectingDevices.add(id)) return; + worker.postDelayed(() -> { + if (!active || !background) { reconnectingDevices.remove(id); return; } + JSObject options = new JSObject().put("deviceId", id).put("timeout", 10000); + ble.invoke("connect", options, connected -> ble.invoke("getServices", options, services -> execute(() -> { + List subscriptions = new ArrayList<>(); + for (JSObject value : watched.values()) if (id.equals(value.getString("deviceId"))) subscriptions.add(value); + restoreSubscriptions(id, subscriptions, 0, attempt); + }), reason -> retryDevice(id, attempt)), reason -> retryDevice(id, attempt)); + }, Math.min(15000, 1000L << Math.min(attempt, 4))); + } + private void retryDevice(String id, int attempt) { execute(() -> { reconnectingDevices.remove(id); reconnectDevice(id, attempt + 1); }); } + private void restoreSubscriptions(String id, List subscriptions, int index, int attempt) { + if (index == subscriptions.size()) { + reconnectingDevices.remove(id); disconnectedDevices.remove(id); lastControl = null; + if (id.equals(trainerId) && canControl) requestControl(); + return; + } + ble.invoke("startNotifications", subscriptions.get(index), result -> execute(() -> restoreSubscriptions(id, subscriptions, index + 1, attempt)), reason -> retryDevice(id, attempt)); + } + private JSObject controlOptions(byte[] bytes) { + return new JSObject().put("deviceId", trainerId).put("service", uuid("1826")) + .put("characteristic", uuid("2ad9")).put("value", NativeBle.hex(bytes)); + } + private void requestControl() { + ble.invoke("write", controlOptions(new byte[] {0}), value -> ble.invoke("write", controlOptions(new byte[] {7}), started -> {}, error -> {}), error -> {}); + } + private void writeControl(byte[] bytes) { + if (ble == null || trainerId == null || Arrays.equals(bytes, lastControl)) return; + writing = true; + ble.invoke("write", controlOptions(bytes), value -> execute(() -> { writing = false; lastControl = bytes; }), reason -> execute(() -> { writing = false; lastControl = null; })); + } + + public void openSocket(String id, String address, String cookies) { execute(() -> { + intentionalClose = true; + if (socket != null) socket.cancel(); + socketId = id; url = address; cookie = cookies; hello = join = null; riderId = -1; + reconnectAttempt = 0; reconnecting = false; intentionalClose = false; connectSocket(false); + }); } + private void connectSocket(boolean resume) { + long generation = ++socketGeneration; + Request.Builder request = new Request.Builder().url(url).header("User-Agent", "OpenRadlr/" + BuildConfig.VERSION_NAME + " (android; build/" + BuildConfig.VERSION_CODE + ")"); + if (cookie != null && !cookie.isEmpty()) request.header("Cookie", cookie); + socket = http.newWebSocket(request.build(), new WebSocketListener() { + @Override public void onOpen(WebSocket webSocket, Response response) { execute(() -> { + if (generation != socketGeneration) return; + if (resume && hello != null) webSocket.send(hello); + else socketEvent("open", null); + }); } + @Override public void onMessage(WebSocket webSocket, String text) { execute(() -> { + if (generation != socketGeneration) return; + if (resume && handleResumeHandshake(text)) return; + handleServer(text); socketEvent("message", text); + }); } + @Override public void onFailure(WebSocket webSocket, Throwable throwable, Response response) { execute(() -> socketLost(generation)); } + @Override public void onClosed(WebSocket webSocket, int code, String reason) { execute(() -> socketLost(generation)); } + }); + } + private boolean handleResumeHandshake(String text) { + try { + JSONObject message = new JSONObject(text); + if (message.optString("type").equals("welcome") && join != null) { sendNative(join); return true; } + } catch (JSONException ignored) {} + return false; + } + private void socketLost(long generation) { + if (generation != socketGeneration || intentionalClose) return; + if (active && background && join != null && hello != null) { + reconnecting = true; + int attempt = reconnectAttempt++; + worker.postDelayed(() -> { if (active && reconnecting && generation == socketGeneration) connectSocket(true); }, Math.min(30000, 1000L << Math.min(attempt, 5))); + } else { socketEvent("close", null); } + } + public void send(String id, String text) { execute(() -> { + if (!Objects.equals(id, socketId)) return; + try { + JSONObject message = new JSONObject(text); String type = message.optString("type"); + if (type.equals("hello")) hello = text; + if (type.equals("join")) join = text; + if (type.equals("telemetry") && background && active) return; + if (engine != null && (type.equals("pause") || type.equals("resume"))) engine.paused = type.equals("pause"); + sendNative(text); + if (type.equals("leave")) { finishJournal(true); active = false; ended = true; stopResources(); } + } catch (JSONException ignored) {} + }); } + public void closeSocket(String id) { execute(() -> { + if (!Objects.equals(id, socketId)) return; + intentionalClose = true; reconnecting = false; ++socketGeneration; + if (socket != null) socket.close(1000, "Ride closed"); + socketEvent("close", null); socket = null; + }); } + private void sendNative(String text) { if (socket != null) socket.send(text); } + private void handleServer(String text) { + try { + JSONObject message = new JSONObject(text); String type = message.optString("type"); + if (type.equals("joined")) { + riderId = message.optLong("rider_id", -1); reconnectAttempt = 0; reconnecting = false; + if (engine != null) engine.resetPosition(); + if (join != null && message.has("resume_token")) { + JSONObject profile = new JSONObject(join); profile.put("resume_token", message.get("resume_token")); join = profile.toString(); + if (active) journal.checkpoint(new JSObject().put("resumeToken", message.get("resume_token")).put("riderId", riderId)); + } + } + if (engine == null) return; + if (type.equals("error") && "pause_rejected".equals(message.optString("code"))) engine.paused = false; + if (type.equals("resistance")) engine.resistance(message.optDouble("grade_percent", 0)); + if (type.equals("state") || type.equals("studio_state")) { + JSONArray riders = message.optJSONArray("riders"); + if (riders != null) for (int i = 0; i < riders.length(); i++) { + JSONObject rider = riders.optJSONObject(i); + if (rider != null && rider.optLong("id", -2) == riderId) { + String route = rider.isNull("route") ? null : rider.optString("route", null); + engine.state(route, rider.optDouble("distance", 0), rider.optDouble("speed", 0), SystemClock.elapsedRealtime()); + if (join != null && route != null) { + JSONObject profile = new JSONObject(join); + profile.put("resume", new JSObject().put("route_id", route).put("distance_m", rider.optDouble("distance", 0))); + join = profile.toString(); + } + } + } + } + if (type.equals("afk_warning") && background) { afkWarning = true; notifyStats(); } + } catch (JSONException | IOException ignored) {} + } + private void socketEvent(String type, String text) { + JSObject event = new JSObject().put("type", type).put("id", socketId); + if (text != null) event.put("data", text); + if (active && background && type.equals("message")) { + try { + String messageType = new JSONObject(text).optString("type"); + if (Arrays.asList("state", "studio_state", "resistance").contains(messageType)) latestFrames.put(messageType, event); + else { if (importantFrames.size() >= 64) importantFrames.removeFirst(); importantFrames.addLast(event); } + } catch (JSONException ignored) {} + } else emit(event); + } + private void emit(JSObject event) { + if (emitter != null) try { emitter.accept(event); } catch (RuntimeException ignored) { emitter = null; } + } + public void detach() { execute(() -> emitter = null); } + + private void endFromNotification() { + if (!active) return; + if (canControl && ble != null) ble.invoke("write", controlOptions(new RideEngine.Command(null, 0, .004, .51).bytes()), value -> {}, reason -> {}); + intentionalClose = true; + sendNative("{\"type\":\"leave\"}"); + if (socket != null) socket.close(1000, "Ride ended"); reconnecting = false; + finishJournal(true); active = false; ended = true; stopResources(); + emit(new JSObject().put("type", "rideState").put("ended", true)); + } + private Notification notification() { + long elapsed = SystemClock.elapsedRealtime(); + double watts = engine == null ? 0 : engine.power(elapsed), distance = engine == null ? 0 : engine.distance; + long duration = engine == null ? 0 : Math.max(0, (long) engine.durationS); + PendingIntent back = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent end = PendingIntent.getService(this, 1, new Intent(this, RideService.class).setAction(END), PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); + double shownDistance = distance / (imperial ? 1609.344 : 1000); + String unit = imperial ? "mi" : "km"; + String clock = String.format(java.util.Locale.getDefault(), "%02d:%02d", duration / 60, duration % 60); + String stats = getString(R.string.ride_stats, Math.round(watts), clock, shownDistance, unit); + RemoteViews compact = new RemoteViews(getPackageName(), R.layout.ride_notification_compact); + compact.setTextViewText(R.id.compact_stats, getString(R.string.ride_compact_stats, Math.round(watts), shownDistance, unit)); + compact.setChronometer(R.id.compact_clock, SystemClock.elapsedRealtime() - duration * 1000, "%s", active && engine != null && !engine.paused); + RemoteViews expanded = new RemoteViews(getPackageName(), R.layout.ride_notification); + expanded.setTextViewText(R.id.notification_route, baseline == null ? "OpenRadlr" : baseline.optString("routeName", "OpenRadlr")); + expanded.setTextViewText(R.id.notification_power, getString(R.string.ride_watts, Math.round(watts))); + Double cadence = engine == null ? null : engine.cadence(elapsed); + expanded.setTextViewText(R.id.notification_cadence, cadence == null ? "– rpm" : getString(R.string.ride_cadence, Math.round(cadence))); + expanded.setTextViewText(R.id.notification_distance, getString(R.string.ride_distance, shownDistance, unit)); + expanded.setTextViewText(R.id.notification_time, getString(R.string.ride_elapsed, duration / 3600, duration / 60 % 60, duration % 60)); + int status = error != null ? R.string.ride_storage_error : afkWarning ? R.string.ride_afk : controlRefused ? R.string.ride_control_refused : engine != null && engine.fresh(elapsed) ? R.string.ride_background_message : R.string.ride_no_signal; + expanded.setTextViewText(R.id.notification_status, getString(status)); + double progress = engine == null ? -1 : engine.progress(); + expanded.setViewVisibility(R.id.notification_progress, progress < 0 ? View.GONE : View.VISIBLE); + expanded.setProgressBar(R.id.notification_progress, 1000, (int) Math.round(Math.max(0, progress) * 1000), false); + NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL) + .setSmallIcon(R.drawable.notification_brand).setColor(0xffffcf00) + .setContentTitle(getString(R.string.ride_notification_title)).setContentText(stats) + .setSubText(baseline == null ? "OpenRadlr" : baseline.optString("routeName", "OpenRadlr")) + .setStyle(new NotificationCompat.DecoratedCustomViewStyle()).setCustomContentView(compact).setCustomBigContentView(expanded) + .setOngoing(true).setOnlyAlertOnce(true).setSilent(true).setContentIntent(back) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .addAction(0, getString(R.string.ride_return), back).addAction(0, getString(R.string.ride_end_save), end); + return builder.build(); + } + private void notifyStats() { if (!active) return; ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notification()); } + @Override public void onDestroy() { + active = false; worker.removeCallbacksAndMessages(null); + intentionalClose = true; if (socket != null) socket.cancel(); + if (ble != null) ble.close(); + try { journal.close(); } catch (IOException ignored) {} + if (wakeLock.isHeld()) wakeLock.release(); + http.dispatcher().executorService().shutdown(); thread.quitSafely(); + super.onDestroy(); + } + private static double finite(JSONObject data, String key, double fallback) { double value = data.optDouble(key, fallback); return Double.isFinite(value) ? value : fallback; } + private static String uuid(String shortId) { return "0000" + shortId + "-0000-1000-8000-00805f9b34fb"; } + private static String shortUuid(String value) { return value.startsWith("0000") && value.length() == 36 ? value.substring(4, 8) : value; } +} diff --git a/app/android/app/src/main/res/drawable-nodpi/notification_brand.png b/app/android/app/src/main/res/drawable-nodpi/notification_brand.png new file mode 100644 index 0000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N9#g39WVcXG6|At>>bP&!F?Cj-uC18BL={ z3TC;=!MqYa7ir^_)B%HzRnbiNX2NXipnW0jAH*8xc#k}wihOXae{L}FP2C{aid z;1UkKh~7gTSoYvbz4V87jri^Uy*m$t6^RQLfF5}0Z|hC|VT>gjJ$?LRS-Rl{pWF;X z$5c9#K4W%n`q?MY<&($o1=Ggxn6X2VZcURv#L)LV0t4fDewS-86yz<-GqEWe-NeYb zPVEL@7Skb*tC})efVkf>pw0lZjY9& z-f)B8`TYNSo&O<>rP^?AzA(%47Xy|*#5DZ50x;&nGrLYXeJ19N8EVZPF$gn;4N`+f zW;7a_8L$-q?HiF7h?@-qA_m%bC8ivnRK!wD5fKg(`R$hhumDydOVa`r1s!?9-oxT{ z_F$7I>Yn>n=&kpz8N6cqnmthip`|xKox2E{0C}yf?LVBc)b%(sLH3ot;Y35)R5~-X zF`1io-bple=0r8VwS{L6Z`Y$TX*Hxhr5YO&roAD7L{k#56~nd&iUlm%2dnHGjWK|y zIUHyyV$k227wYY&PLS+*u@fCT_nE`peP-3;tL5MmYlrLt3S08IY`I>?Qh<9K)D0UT zuLUpi|2bo+HXH!-@#C|6!_pw)P(cf&_~R6SCZM^sx$(fDk;AONx6ZPD(>_ zBRJIvSQe-wM{Rv2!;VtjMNjfYm%95kvU?86v7HCoY1c06SU$IVU%mHZDZqUg)(uO2 hQudY35WgB<{|_B)567*sKNJ7}002ovPDHLkV1l8GUm^ei literal 0 HcmV?d00001 diff --git a/app/android/app/src/main/res/drawable/ride_notification_background.xml b/app/android/app/src/main/res/drawable/ride_notification_background.xml new file mode 100644 index 00000000..f149411a --- /dev/null +++ b/app/android/app/src/main/res/drawable/ride_notification_background.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/android/app/src/main/res/layout/ride_notification.xml b/app/android/app/src/main/res/layout/ride_notification.xml new file mode 100644 index 00000000..2d676e51 --- /dev/null +++ b/app/android/app/src/main/res/layout/ride_notification.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + diff --git a/app/android/app/src/main/res/layout/ride_notification_compact.xml b/app/android/app/src/main/res/layout/ride_notification_compact.xml new file mode 100644 index 00000000..12ae7d1b --- /dev/null +++ b/app/android/app/src/main/res/layout/ride_notification_compact.xml @@ -0,0 +1,13 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/values-de/strings.xml b/app/android/app/src/main/res/values-de/strings.xml new file mode 100644 index 00000000..e4620f62 --- /dev/null +++ b/app/android/app/src/main/res/values-de/strings.xml @@ -0,0 +1,19 @@ + + + Aktive Fahrt + Aktuelle Trainerdaten und Steuerung während der Fahrt. + Deine Fahrt geht weiter + %1$d W · %2$s · %3$.1f %4$s + Trainer verbunden. Tippen, um zur Fahrt zurückzukehren. + Fahrtdaten konnten nicht gespeichert werden. OpenRadlr öffnen. + Zur Fahrt + Beenden & speichern + %1$d W + %1$d rpm + %1$.1f %2$s + %1$02d:%2$02d:%3$02d + Trainersignal unterbrochen. Verbindung wird wiederhergestellt… + Öffne OpenRadlr, um zu bestätigen, dass du noch fährst. + Trainersteuerung wurde abgelehnt. Öffne OpenRadlr, um es erneut zu versuchen. + %1$d W · %2$.1f %3$s + diff --git a/app/android/app/src/main/res/values/strings.xml b/app/android/app/src/main/res/values/strings.xml index 5d1900d6..88e4a8e7 100644 --- a/app/android/app/src/main/res/values/strings.xml +++ b/app/android/app/src/main/res/values/strings.xml @@ -1,7 +1,23 @@ - OpenRadlr - OpenRadlr - com.openradlr.app - com.openradlr.app + OpenRadlr + OpenRadlr + com.openradlr.app + com.openradlr.app + Active ride + Live trainer stats and controls while riding. + Your ride continues + %1$d W · %2$s · %3$.1f %4$s + Trainer connected. Tap to return to your ride. + Ride storage needs attention. Return to OpenRadlr. + Return to ride + End & save + %1$d W + %1$d rpm + %1$.1f %2$s + %1$02d:%2$02d:%3$02d + Trainer signal interrupted. Reconnecting… + Return to OpenRadlr to confirm you are still riding. + Trainer control was refused. Return to OpenRadlr to retry. + %1$d W · %2$.1f %3$s diff --git a/app/android/app/src/main/res/xml/backup_rules.xml b/app/android/app/src/main/res/xml/backup_rules.xml new file mode 100644 index 00000000..9e537944 --- /dev/null +++ b/app/android/app/src/main/res/xml/backup_rules.xml @@ -0,0 +1,3 @@ + + + diff --git a/app/android/app/src/main/res/xml/data_extraction_rules.xml b/app/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000..87840532 --- /dev/null +++ b/app/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java b/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java new file mode 100644 index 00000000..0244a467 --- /dev/null +++ b/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java @@ -0,0 +1,112 @@ +package com.openradlr.app.ride; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +public class RideEngineTest { + @Test public void nativeTicksKeepRecordingWithoutAnyWebViewFrames() { + List samples = new ArrayList<>(); + RideEngine engine = new RideEngine(samples::add); + engine.packet("trainer", "2ad2", "44001c0cB000d700", 0); + engine.tick(1000, 1000); + engine.tick(2000, 2000); + assertEquals(2, samples.size()); + assertEquals(215, samples.get(1).power(), 0); + } + @Test public void stalePowerIsNeverReplayedAfterATrainerDrop() { + RideEngine engine = new RideEngine(sample -> {}); + engine.packet("trainer", "2ad2", "44001c0cb000d700", 0); + engine.tick(1000, 1000); + engine.tick(7000, 7000); + assertEquals(0, engine.power(7000), 0); + } + @Test public void truncatedPacketsDoNotTurnIntoInventedReadings() { + RideEngine engine = new RideEngine(sample -> {}); + engine.packet("trainer", "2ad2", "4400", 1000); + assertEquals(0, engine.power(1000), 0); + } + @Test public void backgroundTelemetryNeverContainsHeartRate() { + RideEngine engine = new RideEngine(sample -> {}); + engine.packet("trainer", "2ad2", "44021c0cb000d70090", 0); + assertEquals(144, engine.heartRate(1000), 0); + assertArrayEquals(new double[] {215, 88}, engine.telemetry(1000), 0); + } + @Test public void repeatedTicksDoNotDuplicateASample() { + List samples = new ArrayList<>(); + RideEngine engine = new RideEngine(samples::add); + engine.tick(1000, 1000); + engine.tick(1100, 1100); + assertEquals(1, samples.size()); + } + @Test public void pausedRidesDoNotRecordSamples() { + List samples = new ArrayList<>(); + RideEngine engine = new RideEngine(samples::add); + engine.paused = true; + engine.tick(1000, 1000); + assertTrue(samples.isEmpty()); + } + @Test public void roadDistanceWrapsWithoutLosingALap() { + RideEngine e = new RideEngine(sample -> {}); + e.routeLengths.put("r", 1000.0); + e.state("r", 995, 10, 0); + e.state("r", 5, 10, 1000); + assertEquals(10, e.distance, 0); + } + @Test public void aSocketOutageDoesNotAddImaginaryDistance() { + RideEngine e = new RideEngine(sample -> {}); + e.state("r", 10, 10, 0); + e.state("r", 1000, 10, 60000); + assertEquals(0, e.distance, 0); + } + @Test public void aWorkoutRunsOnlyWithFreshPedallingData() { + RideEngine e = new RideEngine(sample -> {}); + e.background = true; + e.packet("trainer", "2ad2", "44001c0cb000d700", 0); + e.tick(0, 0); + e.tick(1000, 1000); + assertEquals(1, e.control.elapsed, 0); + e.tick(7000, 7000); + assertEquals(1, e.control.elapsed, 0); + } + @Test public void aWorkoutRampControlsTheTrainerWithoutWebViewFrames() { + RideEngine e = new RideEngine(sample -> {}); + e.packet("trainer", "2ad2", "44001c0cb000d700", 0); + e.control.erg = true; e.control.ftp = 200; e.control.elapsed = 30; + e.control.segments = new double[][] {{60, .5, 1}}; + assertEquals(150, e.command(1000).power(), 0); + } + @Test public void roadResistanceIsEasedRatherThanJumpingAfterAChange() { + RideEngine e = new RideEngine(sample -> {}); + e.packet("trainer", "2ad2", "44001c0cb000d700", 0); + e.resistance(0); e.tick(0, 0); e.resistance(10); e.tick(1000, 1000); + assertEquals(1.5, e.command(1000).grade(), 0); + } + @Test public void staleSensorsReleaseAnErgTarget() { + RideEngine e = new RideEngine(sample -> {}); + e.packet("trainer", "2ad2", "44001c0cb000d700", 0); + e.control.erg = true; e.control.target = 300.0; + assertNull(e.command(7000).power()); + assertEquals(0, e.command(7000).grade(), 0); + } + @Test public void ftmsEncodingMatchesTheWebClient() { + assertArrayEquals(new byte[] {17, 0, 0, (byte) 144, 1, 40, 51}, new RideEngine.Command(null, 4, .004, .51).bytes()); + } + @Test public void theNotificationClockCountsSecondsAndFreezesWhilePaused() { + RideEngine e = new RideEngine(sample -> {}); + e.tick(0, 0); e.tick(65000, 65000); + assertEquals(65, e.durationS, 0); + e.paused = true; e.tick(70000, 70000); + assertEquals(65, e.durationS, 0); + } + @Test public void quarterSecondTicksAdvanceTheClockAndResistanceRamp() { + RideEngine e = new RideEngine(sample -> {}); + e.packet("trainer", "2ad2", "44001c0cb000d700", 0); + e.background = true; e.resistance(0); e.tick(0, 0); e.resistance(10); + e.tick(250, 250); e.tick(500, 500); e.tick(750, 750); e.tick(1000, 1000); + assertEquals(1, e.durationS, 0.00001); + assertEquals(1, e.control.elapsed, 0.00001); + assertEquals(1.5, e.command(1000).grade(), 0.00001); + } +} diff --git a/app/android/app/src/test/java/com/openradlr/app/ride/RideJournalTest.java b/app/android/app/src/test/java/com/openradlr/app/ride/RideJournalTest.java new file mode 100644 index 00000000..da3a24ea --- /dev/null +++ b/app/android/app/src/test/java/com/openradlr/app/ride/RideJournalTest.java @@ -0,0 +1,47 @@ +package com.openradlr.app.ride; + +import static org.junit.Assert.*; +import com.getcapacitor.*; +import java.io.*; +import java.nio.file.Files; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class RideJournalTest { + @Rule public TemporaryFolder directory = new TemporaryFolder(); + private JSObject snapshot() { return new JSObject().put("nativeRideId", "r").put("recorder", new JSObject().put("samples", new JSArray()).put("pauses", new JSArray())); } + private RideEngine.Sample sample(long t) { return new RideEngine.Sample(t, 10, 215, 88.0, 144.0, 4, "r", 10.0); } + @Test public void aNewProcessRecoversSyncedSamples() throws Exception { + RideJournal journal = new RideJournal(directory.getRoot()); + journal.start(snapshot()); journal.sample(sample(1000)); journal.close(); + JSObject recovered = new RideJournal(directory.getRoot()).recover(); + assertEquals(215, recovered.getJSObject("recorder").getJSONArray("samples").getJSONObject(0).getDouble("power"), 0); + assertEquals(1000, recovered.getLong("savedAt")); + } + @Test public void aTornLastWriteDoesNotLoseEarlierSamples() throws Exception { + RideJournal journal = new RideJournal(directory.getRoot()); + journal.start(snapshot()); journal.sample(sample(1000)); journal.close(); + try (FileWriter file = new FileWriter(new File(directory.getRoot(), "active-ride.jsonl"), true)) { file.write("{broken"); } + assertEquals(1, journal.recover().getJSObject("recorder").getJSONArray("samples").length()); + } + @Test public void endAndSaveSurvivesAProcessRestart() throws Exception { + RideJournal journal = new RideJournal(directory.getRoot()); + journal.start(snapshot()); journal.sample(sample(1000)); journal.checkpoint(new JSObject().put("finished", true)); journal.close(); + assertTrue(new RideJournal(directory.getRoot()).recover().getBoolean("finished")); + } + @Test public void updatingPauseMetadataPreservesSamplesFromAContinuedRide() throws Exception { + JSObject saved = snapshot(); + saved.put("recorder", new JSObject().put("samples", new JSArray().put(RideJournal.sampleJson(sample(500)))).put("pauses", new JSArray())); + RideJournal journal = new RideJournal(directory.getRoot()); journal.start(saved); + journal.checkpoint(new JSObject().put("recorder", new JSObject().put("pauses", new JSArray().put(new JSObject().put("from", 600).put("to", 900))))); + journal.sample(sample(1000)); journal.close(); + JSObject record = journal.recover().getJSObject("recorder"); + assertEquals(2, record.getJSONArray("samples").length()); + assertEquals(1, record.getJSONArray("pauses").length()); + } + @Test public void discardingRemovesTheRecoveryJournal() throws Exception { + RideJournal journal = new RideJournal(directory.getRoot()); journal.start(snapshot()); journal.sample(sample(1000)); journal.clear(); + assertNull(journal.recover()); + } +} diff --git a/client/public/index.html b/client/public/index.html index 4608fb66..4b460947 100644 --- a/client/public/index.html +++ b/client/public/index.html @@ -32,6 +32,7 @@ + @@ -383,6 +384,7 @@

Events + diff --git a/client/public/js/ble/nativeBluetooth.js b/client/public/js/ble/nativeBluetooth.js index 35a62272..d69327cc 100644 --- a/client/public/js/ble/nativeBluetooth.js +++ b/client/public/js/ble/nativeBluetooth.js @@ -72,7 +72,7 @@ function commonPrefix(texts) { } const domError = (name, message) => Object.assign(new Error(message), { name }); -const noAdapter = () => domError("NotFoundError", "Bluetooth adapter not available."); // i18n-ok (Chrome's own message) +const noAdapter = (code = "BLUETOOTH_UNAVAILABLE") => Object.assign(domError("NotFoundError", "Bluetooth adapter not available."), { code }); // i18n-ok (Chrome's own message) /** The plugin's start-up failures as the errors a browser gives, so the device setup explains them. */ function initializeError(error) { @@ -99,7 +99,7 @@ export class NativeBluetooth { await this.#initialize(); // Switched off, the picker would just stay empty: say so, as Chrome does. const enabled = await this.#plugin.isEnabled?.(); - if (enabled && !enabled.value) throw noAdapter(); + if (enabled && !enabled.value) throw noAdapter("BLUETOOTH_OFF"); let found; try { found = await this.#plugin.requestDevice(scanOptions(options)); @@ -231,7 +231,10 @@ class NativeDevice { this.#services = services; } catch (error) { this.run(() => this.#plugin.disconnect({ deviceId: this.id })).catch(() => {}); - throw domError("NetworkError", error?.message ?? String(error)); + const message = error?.message ?? String(error); + if (/permission|not authori[sz]ed|not allowed/i.test(message)) throw domError("NotAllowedError", message); + if (/timed? ?out|timeout/i.test(message)) throw domError("TimeoutError", message); + throw domError("NetworkError", message); } this.gatt.connected = true; return this.gatt; diff --git a/client/public/js/i18n/de.js b/client/public/js/i18n/de.js index 5c350834..0d9a26ae 100644 --- a/client/public/js/i18n/de.js +++ b/client/public/js/i18n/de.js @@ -789,6 +789,14 @@ export default { "setup.mode.sim": "Simulator", "setup.mode.simHint": "Einfach ausprobieren", "setup.studioNeedsTrainer": "Studio-Kurse brauchen eine Rolle oder den Simulator.", + "setup.err.unsupported": "Bluetooth LE ist auf diesem Gerät nicht verfügbar.", + "setup.err.nativePermission": "OpenRadlr darf Bluetooth nicht verwenden. Erlaube „Geräte in der Nähe“ in den App-Einstellungen und versuche es erneut.", + "setup.bluetoothSettings": "Bluetooth-Einstellungen", + "setup.appPermissions": "App-Berechtigungen", + "setup.settingsUnavailable": "Einstellungen konnten nicht geöffnet werden. Öffne OpenRadlr in den App-Einstellungen deines Telefons.", + "nativeRide.failed": "Hintergrundfahrt benötigt Aufmerksamkeit. Deine gespeicherte Fahrt bleibt erhalten; öffne OpenRadlr.", + "nativeRide.unavailable": "Hintergrundfahrt konnte nicht starten. Lass OpenRadlr zum Aufzeichnen geöffnet.", + "nativeRide.storageError": "Fahrtdaten konnten nicht gespeichert werden. Öffne OpenRadlr, um deine Fahrt zu sichern.", "setup.err.adapter": "Bluetooth ist auf diesem Gerät aus. Schalte es ein und versuche es erneut.", "setup.err.halfConnected": "Diese Hälfte ist schon verbunden: wähle die andere {name} (weck sie mit einem Tastendruck).", "setup.err.timeout": "Keine Antwort von {name}. Ist es wach und frei von anderen Apps (Zwift, die App der Rolle)?", diff --git a/client/public/js/i18n/en.js b/client/public/js/i18n/en.js index c43c6f19..7758dab8 100644 --- a/client/public/js/i18n/en.js +++ b/client/public/js/i18n/en.js @@ -789,6 +789,14 @@ export default { "setup.mode.sim": "Simulator", "setup.mode.simHint": "Just try it", "setup.studioNeedsTrainer": "Studio classes need a trainer or the simulator.", + "setup.err.unsupported": "Bluetooth LE isn't available on this device.", + "setup.err.nativePermission": "OpenRadlr isn't allowed to use Bluetooth. Allow Nearby devices in the phone's app settings, then try again.", + "setup.bluetoothSettings": "Bluetooth settings", + "setup.appPermissions": "App permissions", + "setup.settingsUnavailable": "Could not open settings. Open OpenRadlr in your phone’s app settings.", + "nativeRide.failed": "Background riding needs attention. Your saved ride is kept; return to OpenRadlr.", + "nativeRide.unavailable": "Background riding could not start. Keep OpenRadlr visible to continue recording.", + "nativeRide.storageError": "Ride storage needs attention. Return to OpenRadlr to save your ride.", "setup.err.adapter": "Bluetooth is off on this device. Turn it on and try again.", "setup.err.halfConnected": "That half is already connected: pick the other {name} (wake it with a button press).", "setup.err.timeout": "No answer from {name}. Is it awake, and free of other apps (Zwift, the trainer's app)?", diff --git a/client/public/js/main.js b/client/public/js/main.js index 42913bef..2c5cbba6 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -3,11 +3,12 @@ * to the DOM and runs the render loop. All logic lives in the imported * modules, which are unit-tested; this file only connects them. */ +import { nativeControl, enrichNativeSample } from "./native/backgroundRide.js"; import { loadAnalytics } from "./analytics.js"; import { DeviceLog, deviceLogOptions } from "./ble/deviceLog.js"; import { HeartRateMonitor, PaddleTrainer, SimulatedTrainer, SmartTrainer, canExportRide, couldControlResistance, deviceKind, hasRealPowerSource, isBluetoothAvailable } from "./ble/devices.js"; import { KnownDevices, grantedDevices, whenInRange } from "./ble/knownDevices.js"; -import { addonsShown, chooseRideMode, connectErrorText, controllerCheck, controllerLine, deviceActions, deviceLine, expectsOtherHalf, heartRateCheck, liveCheck, missingHalfHint, needsDownButton, remapForDown, rideModes } from "./view/deviceSetup.js"; +import { addonsShown, chooseRideMode, connectionHelp, controllerCheck, controllerLine, deviceActions, deviceLine, expectsOtherHalf, heartRateCheck, liveCheck, missingHalfHint, needsDownButton, remapForDown, rideModes } from "./view/deviceSetup.js"; import { connectController, openController } from "./ble/controllers.js"; import { ControllerInput, MergedControllers, alternatives, controllerNavigates } from "./input/controller.js"; import { activateFocused, focusableIn, moveFocus } from "./input/focusNav.js"; @@ -127,6 +128,8 @@ import { createScreensDialog } from "./view/screensDialog.js"; // Inside the OpenRadlr app: native Bluetooth, wake lock and file saving (docs/app.md). const nativeApp = installNativeApp(); +const nativeRide = nativeApp?.backgroundRide; +const createRideSocket = nativeRide ? (url) => nativeRide.createSocket(url) : undefined; function setNativeImmersive(enabled) { nativeApp?.setImmersive?.(enabled).catch((error) => console.warn("System bars:", error)); } @@ -1171,7 +1174,7 @@ async function connectDevice(connect, onConnected, kind, { pending = t("devices. } catch (error) { // Given up quietly (another device was connected meanwhile) or the picker was closed: nothing to say. const cancelled = error.name === "AbortError" || /cancel/i.test(error.message ?? ""); - settle(cancelled ? null : { state: "error", text: connectErrorText(error, deviceName) }); + settle(cancelled ? null : { state: "error", ...connectionHelp(error, { native: Boolean(nativeRide), deviceName }) }); if (!cancelled && error.name !== "NotFoundError") deviceLog.error(`Connecting failed: ${error.message}`); return false; } @@ -1271,6 +1274,14 @@ function renderDeviceLine(kind) { /** Every device line with its actions: Reconnect a known device (the chooser then reads "Other"), else connect, change or add. */ function renderDeviceLines() { + const help = Object.values(app.deviceAttempts).find((attempt) => attempt?.settings); + const settings = $("bluetooth-settings"); + settings.hidden = !nativeRide || !help; + if (help) { + settings.textContent = t(help.settings === "bluetooth" ? "setup.bluetoothSettings" : "setup.appPermissions"); + settings.onclick = () => nativeRide.openSettings(help.settings).catch(() => notify(t("setup.settingsUnavailable"), "error")); + } + const connectedNow = { trainer: Boolean(lineTrainer()), hr: Boolean(app.heartRateMonitor), controller: app.controllers.length > 0 }; for (const kind of Object.keys(DEVICES)) { renderDeviceLine(kind); @@ -1799,7 +1810,7 @@ async function joinRide(restored = null) { app.smoother = new RiderSmoother(app.route, { routeOf: (rider) => app.routes.get(rider.route), laneDelayOf: ownLaneNow }); } - const connection = new GameConnection({ url: defaultServerUrl() }); + const connection = new GameConnection({ url: defaultServerUrl(), ...(createRideSocket && { createSocket: createRideSocket }) }); wireConnection(connection); app.connection = connection; if (app.trainer instanceof PaddleTrainer) app.trainer.setFtp(app.profile.ftp); @@ -1851,7 +1862,7 @@ async function joinRide(restored = null) { onError: (error) => notify(t("ride.trainerError", { message: error.message }), "error"), }); app.session.start(); - startRide(); + await startRide(); } /** The café workout (#77): joins the default route's world without a trainer and runs the plan. */ @@ -1879,7 +1890,7 @@ async function joinWorkout(profile, errors) { app.routes = new Map([[app.route.id, app.route]]); app.smoother = new RiderSmoother(app.route, { routeOf: (rider) => app.routes.get(rider.route), laneDelayOf: ownLaneNow }); - const connection = new GameConnection({ url: defaultServerUrl() }); + const connection = new GameConnection({ url: defaultServerUrl(), ...(createRideSocket && { createSocket: createRideSocket }) }); wireConnection(connection); app.connection = connection; app.riderId = await connection.join({ ...app.profile, routeId, level: levelOf(app.profile), device: "workout" }); @@ -1910,6 +1921,12 @@ function learnLevel() { * Trainer, heart rate monitor and controllers stay connected. */ function endRide() { + if (nativeRide?.active) { + if (app.nativeEnding) return; + app.nativeEnding = nativeRide.stop(false).then(() => { saveRide(); app.nativeEnding = null; endRide(); }) + .catch((error) => { app.nativeEnding = null; notify(t("nativeRide.failed"), "error"); console.warn(error); }); + return; + } const ride = app.ride; if (!ride) return; app.finishUpload?.dispose(); @@ -2064,6 +2081,7 @@ function endRide() { function wireConnection(connection) { // An ended ride's connection closes on its own; it no longer drives the screen. const on = (type, handler) => connection.on(type, (message) => connection === app.connection && handler(message)); + on("rejoined", (message) => { app.riderId = message.rider_id; }); on("state", (message) => { // My rider decides which road I'm on: my route, another one I turned onto, or off every route. const mine = message.riders.find((rider) => rider.id === app.riderId); @@ -2138,7 +2156,7 @@ function stampExercise(rider) { return { ...rider, exerciseSince: app.exerciseSince.get(rider.id).since }; } -function startRide() { +async function startRide() { const info = app.connection.serverInfo; $("server-label").textContent = app.studio ? `${info.server_name} · ${app.route.name}` : `${info.server_name} · ${app.route.name} · ${formatDistanceWithUnit(app.route.length, 1)}`; setDifficultyInputs(app.profile.difficulty); @@ -2198,6 +2216,7 @@ function startRide() { app.recorder = new RideRecorder(); if (app.restored) restoreRide(app.restored); + await startNativeRide(); startSplits(); initFinish(); initAfkPrompt(); @@ -2217,6 +2236,50 @@ function startRide() { requestAnimationFrame(loop); } +/** The native journal is authoritative for measured Android rides, including while hidden. */ +async function startNativeRide() { + if (!nativeRide || !(app.trainer instanceof SmartTrainer)) { app.nativeRideId = null; return; } + app.nativeRideId = crypto.randomUUID(); + app.nativeWasHidden = false; + app.nativeSyncing = false; + const recorder = app.recorder; + const control = () => nativeControl({ + profile: app.profile, training: app.training, gearbox: app.gearbox, routes: app.routes, + studio: app.studio, physics: app.connection?.physics, paused: Boolean(app.pause?.pausedAt), + canControl: canControl(app.trainer), nowS: now(), + }); + try { + await nativeRide.start({ snapshot: rideSnapshot(), trainerId: app.trainer.id, hrId: app.heartRateMonitor?.id ?? null, control: control() }, { + onSamples: (samples) => { + for (const sample of samples) recorder.add(enrichNativeSample(sample, app.routes.get(sample.route), toLatLon)); + if (app.recorder === recorder) updateSplits(); + }, + onState: async (state) => { + if (app.recorder !== recorder) return; + if (app.nativeWasHidden && !document.hidden) { + app.training?.player?.restoreElapsed(state.elapsed, now()); + app.rideDistance = state.distance; + const riders = app.state?.riders ?? app.studio?.state?.riders ?? []; + app.lastMyDistance = riders.find((rider) => rider.id === app.riderId)?.distance ?? null; + app.nativeWasHidden = false; + } + app.nativeSyncing = false; + if (state.error && !app.nativeRecordError) { app.nativeRecordError = true; notify(t("nativeRide.storageError"), "error"); } + const checkpoint = rideSnapshot(); + checkpoint.recorder = { pauses: recorder.pauses, intervalMs: recorder.intervalMs }; + await nativeRide.update(control(), checkpoint); + }, + onEnded: () => finishRide(), + onError: () => { app.nativeSyncing = false; notify(t("nativeRide.failed"), "error"); }, + }); + await app.autosave.save(rideSnapshot()); + } catch (error) { + app.nativeSyncing = false; + notify(t("nativeRide.unavailable"), "error"); + console.warn("Native background ride:", error); + } +} + function startRoad({ simulated, setSimPower }) { $("start-race").addEventListener("click", () => app.connection.startRace(Number($("race-laps").value))); $("leave-race").addEventListener("click", () => app.connection.leaveRace()); @@ -2607,6 +2670,7 @@ function updateStudioPanels() { } function studioFrame() { + if (nativeRide?.active && app.nativeSyncing) return; const studio = app.studio; if (!studio.state) return; const time = now(); @@ -2669,7 +2733,7 @@ function studioFrame() { app.rideDistance = me ? app.distanceOffset + me.distance : app.rideDistance; // Offline the rider's last state is stale: they don't move until the server is back. - if (!app.finished && app.recorder.add({ t: Date.now(), distance: app.rideDistance, power, cadence, heartRate, speed: app.offline ? 0 : (me?.speed ?? 0), elevation: null })) updateSplits(); + if (!nativeRide?.active && !app.finished && app.recorder.add({ t: Date.now(), distance: app.rideDistance, power, cadence, heartRate, speed: app.offline ? 0 : (me?.speed ?? 0), elevation: null })) updateSplits(); const silentFor = time - (app.lastTrainerDataAt ?? app.rideStartedAt); $("trainer-warning").hidden = silentFor < 5; } @@ -3484,7 +3548,7 @@ function leaveRide() { if (question && !confirm(question)) return false; // Keep an unsaved finished ride for download or status checking from the menu. // Wait for the final snapshot before clearing, so it cannot resurrect a discarded ride. - if (!recoverable) app.autosaveClearing = Promise.resolve(app.finishSave).then(() => app.autosave.clear()); + if (!recoverable) app.autosaveClearing = Promise.resolve(app.finishSave).then(async () => { await nativeRide?.stop(false); await app.autosave.clear(); await nativeRide?.clear(); }); endRide(); return true; } @@ -3573,6 +3637,12 @@ function finishStats() { */ function finishRide() { if (!app.ride || app.finished) return; + if (nativeRide?.active) { + if (app.nativeFinishing) return; + app.nativeFinishing = nativeRide.stop(true).then(() => { app.nativeFinishing = null; finishRide(); }) + .catch((error) => { app.nativeFinishing = null; notify(t("nativeRide.failed"), "error"); console.warn(error); }); + return; + } app.menuDialog?.cancelConfirm(); app.viewPopover?.close(); $("reconnecting").hidden = true; @@ -3779,7 +3849,7 @@ function connectionLost(lost) { /** One attempt: a new connection that asks for the same rider back. */ async function rejoin(lost) { - const connection = new GameConnection({ url: defaultServerUrl() }); + const connection = new GameConnection({ url: defaultServerUrl(), ...(createRideSocket && { createSocket: createRideSocket }) }); wireConnection(connection); try { const riderId = await connection.join({ @@ -3920,6 +3990,7 @@ function saveRide() { function rideSnapshot() { return { version: 1, + ...(app.nativeRideId && { nativeRideId: app.nativeRideId }), savedAt: Date.now(), serverUrl: defaultServerUrl(), routeId: app.route.id, @@ -3927,6 +3998,7 @@ function rideSnapshot() { studio: Boolean(app.studio), trainerKind: deviceKind(app.trainer), rideStartedAt: Date.now() - (now() - app.rideStartedAt) * 1000, + recordDurationS: app.recorder.summary().durationS, distance: app.rideDistance, riderId: app.riderId, distanceOffset: app.distanceOffset, @@ -3941,7 +4013,9 @@ async function refreshUnfinished() { const clearing = app.autosaveClearing; app.autosaveClearing = null; await clearing?.catch(() => {}); - app.unfinished = await app.autosave.load(); + const saved = await app.autosave.load(); + app.unfinished = nativeRide && !nativeRide.active ? await nativeRide.recover(saved).catch(() => saved) : saved; + if (app.unfinished !== saved) await app.autosave.save(app.unfinished); renderUnfinished(); } @@ -3958,6 +4032,7 @@ async function discardUnfinished() { app.recoveryUpload?.dispose(); app.recoveryUpload = null; await app.autosave.clear(); + await nativeRide?.clear(); app.unfinished = null; renderUnfinished(); } @@ -3971,7 +4046,11 @@ function initRecovery() { window.addEventListener("focus", () => deviceLog.info("Window has focus")); document.addEventListener("visibilitychange", () => { deviceLog.info(`Page ${document.visibilityState}`); - if (document.visibilityState !== "hidden") return; + if (document.visibilityState !== "hidden") { + if (nativeRide?.active) nativeRide.flush().catch((error) => { app.nativeSyncing = false; console.warn(error); }); + return; + } + if (nativeRide?.active) { app.nativeWasHidden = true; app.nativeSyncing = true; } saveRide(); saveWorkoutRecord(); }); @@ -5247,7 +5326,7 @@ function performPause(actions, time) { } function frame() { - if (!app.state) return; + if (!app.state || (nativeRide?.active && app.nativeSyncing)) return; const time = now(); const everyone = app.smoother.sample(time); @@ -5331,7 +5410,7 @@ function frame() { const position = me ? app.route.positionAt(me.distance) : null; const onRoad = me && me.route !== OFF_ROUTE_ID; // No samples while paused: the ride file holds the pause instead (#89). - const kept = !app.finished && !app.pause?.pausedAt && app.recorder.add({ + const kept = !nativeRide?.active && !app.finished && !app.pause?.pausedAt && app.recorder.add({ t: Date.now(), ...(position ? toLatLon(position.x, position.y, app.route.geo) : {}), route: onRoad ? (me.route ?? app.route.id) : null, diff --git a/client/public/js/native/app.js b/client/public/js/native/app.js index 8e5deb21..76b74522 100644 --- a/client/public/js/native/app.js +++ b/client/public/js/native/app.js @@ -5,6 +5,7 @@ * the client never needs to know where it runs. */ +import { NativeRide } from "./backgroundRide.js"; import { NativeBluetooth } from "../ble/nativeBluetooth.js"; /** The app's native plugins, or null in a browser. */ @@ -24,12 +25,14 @@ export const APP_SCHEME = "openradlr"; * saveFiles: ((files: {blob: Blob, name: string}[]) => Promise) | null, * signIn: ((url: string) => Promise) | null, * onBack: ((back: () => boolean) => void) | null, + * backgroundRide: NativeRide | null, * setImmersive: ((enabled: boolean) => Promise) | null, * } | null} */ export function installNativeApp({ plugins = nativePlugins(), navigator: nav = globalThis.navigator, storage, platform = globalThis.Capacitor?.getPlatform?.() } = {}) { if (!plugins) return null; - if (plugins.BluetoothLe && !nav.bluetooth) define(nav, "bluetooth", new NativeBluetooth({ plugin: plugins.BluetoothLe, ...(storage !== undefined && { storage }) })); + const backgroundRide = platform === "android" && plugins.BackgroundRide ? new NativeRide({ plugin: plugins.BackgroundRide }) : null; + if (plugins.BluetoothLe && !nav.bluetooth) define(nav, "bluetooth", new NativeBluetooth({ plugin: backgroundRide ? backgroundRide.bluetooth(plugins.BluetoothLe) : plugins.BluetoothLe, ...(storage !== undefined && { storage }) })); // The web view's own wake lock may exist and still let the screen dim. if (plugins.KeepAwake) define(nav, "wakeLock", nativeWakeLock(plugins.KeepAwake)); const canShare = Boolean(plugins.Filesystem && plugins.Share); @@ -44,6 +47,7 @@ export function installNativeApp({ plugins = nativePlugins(), navigator: nav = g saveFiles: canShare ? (files) => shareFiles(plugins, files) : null, signIn: canSignIn ? (url) => systemSignIn(plugins, url) : null, onBack: plugins.App ? (back) => onBackButton(plugins.App, back) : null, + backgroundRide, setImmersive: platform === "android" && plugins.SystemBars ? (enabled) => Promise.resolve().then(() => enabled ? plugins.SystemBars.hide() : plugins.SystemBars.show()) : null, diff --git a/client/public/js/native/backgroundRide.js b/client/public/js/native/backgroundRide.js new file mode 100644 index 00000000..5ad0b42b --- /dev/null +++ b/client/public/js/native/backgroundRide.js @@ -0,0 +1,164 @@ +/** Android owns live transport and recording; the web client owns presentation. */ +export class NativeRide { + active = false; + #ready; + #plugin; + #sockets = new Map(); + #ble = new Map(); + #makeId; + #schedule; + #cancel; + #timer = null; + #since = -1; + #pull = null; + #stopping = null; + #finishRequested = false; + #callbacks = {}; + #onError; + + constructor({ plugin, makeId = () => globalThis.crypto.randomUUID(), schedule = globalThis.setInterval, cancel = globalThis.clearInterval, onError = () => {} }) { + this.#plugin = plugin; this.#makeId = makeId; this.#schedule = schedule; this.#cancel = cancel; this.#onError = (error) => { onError(error); this.#callbacks.onError?.(error); }; + this.#ready = Promise.resolve(plugin.addListener("event", (event) => { + if (event.type === "ble") { + for (const listener of this.#ble.get(event.event) ?? []) listener(event.value); + } else if (event.type === "rideState") { + if (event.ended && this.active) this.flush().then(() => this.#callbacks.onEnded?.()).catch(this.#onError); + } else if (event.type === "serviceLost") { + for (const socket of this.#sockets.values()) socket.dispatch("close"); + this.active = false; this.#cancel(this.#timer); + this.#onError(new Error("Native ride service stopped")); // i18n-ok (internal bridge error) + } else this.#sockets.get(event.id)?.dispatch(event.type, event.data); + })); + this.#ready.catch(this.#onError); + } + + createSocket(url) { + const id = this.#makeId(), listeners = new Map(), owner = this; + const socket = { + readyState: 0, + addEventListener(type, listener) { if (!listeners.has(type)) listeners.set(type, new Set()); listeners.get(type).add(listener); }, + dispatch(type, data) { + if (type === "open") { if (this.readyState !== 0) return; this.readyState = 1; } + if (type === "close") { if (this.readyState === 3) return; this.readyState = 3; owner.#sockets.delete(id); } + for (const listener of listeners.get(type) ?? []) listener({ type, data }); + }, + send(data) { + if (this.readyState !== 1) return; + owner.#plugin.sendSocket({ id, data }).catch((error) => { this.dispatch("error", error); this.dispatch("close"); }); + }, + close() { + const wasOpen = this.readyState === 1; + this.dispatch("close"); + if (wasOpen) owner.#plugin.closeSocket({ id }).catch(owner.#onError); + }, + }; + this.#sockets.set(id, socket); + this.#ready.then(async () => { + if (socket.readyState === 3) return; + await this.#plugin.openSocket({ id, url }); + if (socket.readyState === 3) await this.#plugin.closeSocket({ id }); + }).catch((error) => { socket.dispatch("error", error); socket.dispatch("close"); }); + return socket; + } + + bluetooth(plugin) { + const wrapped = Object.create(plugin); + wrapped.addListener = async (event, listener) => { + await this.#ready; + if (!this.#ble.has(event)) this.#ble.set(event, new Set()); + const listeners = this.#ble.get(event); + listeners.add(listener); + try { await this.#plugin.observeEvent({ event }); } + catch (error) { listeners.delete(listener); throw error; } + return { remove: async () => listeners.delete(listener) }; + }; + for (const method of ["connect", "getServices", "startNotifications", "write", "writeWithoutResponse"]) { + wrapped[method] = (options) => this.#plugin.bleOperation({ method, options }); + } + return wrapped; + } + + async start(data, callbacks = {}) { + await this.#ready; + this.#callbacks = callbacks; + this.#since = data.snapshot?.recorder?.samples?.at(-1)?.t ?? -1; + await this.#plugin.startRide(data); + this.active = true; + this.#timer = this.#schedule(() => this.flush().catch(this.#onError), 1000); + } + flush() { + if (!this.active) return Promise.resolve(); + this.#pull ??= (async () => { + let state; + do { + state = await this.#plugin.snapshot({ since: this.#since }); + const fresh = (state.samples ?? []).filter((sample) => sample.t > this.#since).sort((a, b) => a.t - b.t); + if (fresh.length) { + await this.#callbacks.onSamples?.(fresh); + this.#since = fresh.at(-1).t; + } + await this.#callbacks.onState?.(state); + } while ((state.samples?.length ?? 0) >= 1000); + })().finally(() => { this.#pull = null; }); + return this.#pull; + } + async update(control, checkpoint) { + if (this.active) await this.#plugin.updateRide({ control, ...(checkpoint && { checkpoint }) }); + } + stop(finished = false) { + if (!this.active) return Promise.resolve(); + this.#finishRequested ||= finished; + this.#stopping ??= (async () => { + this.#cancel(this.#timer); this.#timer = null; + await this.flush(); + const state = await this.#plugin.stopRide({ finished: this.#finishRequested }); + const fresh = (state.samples ?? []).filter((sample) => sample.t > this.#since); + if (fresh.length) await this.#callbacks.onSamples?.(fresh); + this.active = false; + })().finally(() => { this.#stopping = null; this.#finishRequested = false; }); + return this.#stopping; + } + async recover(saved) { + const { snapshot } = await this.#plugin.recover(); + return mergeNativeRecovery(saved, snapshot); + } + clear() { return this.#plugin.clear(); } + openSettings(kind) { return this.#plugin.openSettings({ kind }); } +} + +/** Prefer the browser's enriched samples, but recover native-only seconds. */ +export function mergeNativeRecovery(saved, native) { + if (!native?.nativeRideId || !native.recorder) return saved; + if (saved && saved.nativeRideId !== native.nativeRideId) return saved; + if (!saved) return native; + const samples = new Map((native.recorder.samples ?? []).map((sample) => [sample.t, sample])); + for (const sample of saved.recorder?.samples ?? []) samples.set(sample.t, sample); + return { ...saved, ...native, recorder: { ...native.recorder, ...saved.recorder, samples: [...samples.values()].sort((a, b) => a.t - b.t) } }; +} + +/** A serializable control model, independent of frame rendering. */ +export function nativeControl({ profile, training, gearbox, routes = new Map(), studio, physics, paused = false, canControl = false, nowS = 0 }) { + const player = training?.player; + const plan = studio?.plan; + return { + difficulty: profile.difficulty, ftp: profile.ftp, units: profile.units, + target: studio ? studio.targetWatts(nowS) : training?.targetWatts() ?? null, + intensity: studio?.intensity ?? training?.intensity ?? 1, + erg: studio ? studio.erg : training?.mode === "erg", + segments: plan ? plan.segments.map((s) => ({ durationS: s.duration_s, from: s.from, to: s.to })) : player?.workout.segments ?? [], + elapsed: studio ? studio.elapsed(nowS) ?? 0 : player?.elapsedS ?? 0, + classClock: Boolean(studio), + ratio: gearbox?.ratio ?? 0, referenceRatio: profile.chainring / profile.cog, + mass: physics?.mass_kg ?? profile.weightKg + 9, cda: physics?.cda_m2 ?? .32, + crr: physics?.crr ?? .004, airDensity: physics?.air_density ?? 1.225, + routeLengths: Object.fromEntries([...routes].map(([id, route]) => [id, route.length])), + paused, canControl, + }; +} + +/** Adds virtual coordinates when the corresponding route geometry is available. */ +export function enrichNativeSample(sample, route, toLatLon) { + if (!route || !Number.isFinite(sample.routeM)) return sample; + const position = route.positionAt(sample.routeM); + return { ...sample, ...toLatLon(position.x, position.y, route.geo), elevation: route.elevationAt(sample.routeM) }; +} diff --git a/client/public/js/net/connection.js b/client/public/js/net/connection.js index 8c898522..057f1fa5 100644 --- a/client/public/js/net/connection.js +++ b/client/public/js/net/connection.js @@ -46,13 +46,16 @@ export class GameConnection extends Emitter { this.graceS = message.grace_s ?? 0; this.#send(ClientMessages.join(profile)); break; - case "joined": + case "joined": { + const rejoined = joined; joined = true; this.riderId = message.rider_id; this.resumeToken = message.resume_token ?? null; this.physics = message.physics ?? null; resolve(message.rider_id); + if (rejoined) this.emit("rejoined", message); break; + } case "error": if (!joined) reject(Object.assign(new Error(`${message.code}: ${message.message}`), { code: message.code, serverMessage: message.message })); this.emit("error", message); diff --git a/client/public/js/ride/workout.js b/client/public/js/ride/workout.js index fa55134b..8b27358f 100644 --- a/client/public/js/ride/workout.js +++ b/client/public/js/ride/workout.js @@ -152,6 +152,13 @@ export class WorkoutPlayer { return this.#elapsed; } + /** Reconciles time recorded by the native ride clock before frame ticks resume. */ + restoreElapsed(elapsedS, nowS) { + if (!Number.isFinite(elapsedS) || elapsedS < 0 || !Number.isFinite(nowS)) return; + this.#elapsed = elapsedS; + this.#lastTick = nowS; + } + /** Advances the workout clock to `nowS`. */ tick(nowS) { if (this.#lastTick !== null && !this.paused) this.#elapsed += Math.max(0, nowS - this.#lastTick); diff --git a/client/public/js/view/deviceSetup.js b/client/public/js/view/deviceSetup.js index 55b22743..bb703b00 100644 --- a/client/public/js/view/deviceSetup.js +++ b/client/public/js/view/deviceSetup.js @@ -60,6 +60,14 @@ export function connectErrorText(error, deviceName = null) { return t("setup.err.unknown", { message }); } +/** A native failure's explanation and optional system-settings action. */ +export function connectionHelp(error, { native = false, deviceName = null } = {}) { + if (error?.code === "BLUETOOTH_UNAVAILABLE") return { text: t("setup.err.unsupported"), settings: null }; + if (error?.code === "BLUETOOTH_OFF") return { text: t("setup.err.adapter"), settings: native ? "bluetooth" : null }; + if (native && ["SecurityError", "NotAllowedError"].includes(error?.name)) return { text: t("setup.err.nativePermission"), settings: "app" }; + return { text: connectErrorText(error, deviceName), settings: null }; +} + /** After this long without a packet the trainer is probably asleep or taken by another app. */ export const SILENT_AFTER_MS = 5000; diff --git a/client/test/deviceSetup.test.js b/client/test/deviceSetup.test.js index cd20f7fc..6cc83e9c 100644 --- a/client/test/deviceSetup.test.js +++ b/client/test/deviceSetup.test.js @@ -206,3 +206,28 @@ test("the heart rate check: waiting for the first beat, the bpm, a hint when bea assert.equal(heartRateCheck({ sinceDataMs: 12000, heartRate: 144 }).state, "silent"); assert.match(heartRateCheck({ sinceDataMs: 12000, heartRate: 144 }).text, /12 s/); }); + +test("native Bluetooth failures offer the relevant Android settings", async () => { + const { connectionHelp } = await import("../public/js/view/deviceSetup.js"); + const off = connectionHelp({ code: "BLUETOOTH_OFF", name: "NotFoundError" }, { native: true }); + assert.equal(off.settings, "bluetooth"); + assert.match(off.text, /Bluetooth is off/); + const denied = connectionHelp({ name: "NotAllowedError" }, { native: true }); + assert.equal(denied.settings, "app"); + assert.match(denied.text, /phone.*settings/); +}); + +test("a timeout suggests possible causes without claiming another app owns the trainer", async () => { + const { connectionHelp } = await import("../public/js/view/deviceSetup.js"); + const help = connectionHelp({ name: "TimeoutError" }, { native: true }); + assert.equal(help.settings, null); + assert.match(help.text, /awake|pedal/); + assert.doesNotMatch(help.text, /is connected to another app/); +}); + +test("missing Bluetooth hardware is not confused with a cancelled picker", async () => { + const { connectionHelp } = await import("../public/js/view/deviceSetup.js"); + const help = connectionHelp({ code: "BLUETOOTH_UNAVAILABLE", name: "NotFoundError" }, { native: true }); + assert.match(help.text, /doesn't support|not available|isn't available/); + assert.equal(help.settings, null); +}); diff --git a/client/test/nativeBluetooth.test.js b/client/test/nativeBluetooth.test.js index 1e100722..79971ed4 100644 --- a/client/test/nativeBluetooth.test.js +++ b/client/test/nativeBluetooth.test.js @@ -161,10 +161,10 @@ test("disconnecting on purpose closes the native link and stops reconnecting", a assert.deepEqual(events, [], "a goodbye, not a drop to reconnect from"); }); -test("a failed connect rejects with a NetworkError and releases the link", async () => { +test("a failed connect preserves its timeout category and releases the link", async () => { const { fake, bluetooth } = setup(); fake.fail.getServices = "Connection timeout"; - await assert.rejects(SmartTrainer.connect(bluetooth), { name: "NetworkError", message: "Connection timeout" }); + await assert.rejects(SmartTrainer.connect(bluetooth), { name: "TimeoutError", message: "Connection timeout" }); await new Promise((resolve) => setTimeout(resolve, 0)); assert.ok(fake.calls.some((call) => call.method === "disconnect")); }); @@ -275,7 +275,7 @@ test("large files are encoded in chunks", async () => { test("only the features with native plugins are offered", () => { const share = { Filesystem: {}, Share: {} }; - assert.deepEqual(Object.keys(installNativeApp({ plugins: {}, navigator: {} })), ["saveFiles", "signIn", "onBack", "setImmersive"]); + assert.deepEqual(Object.keys(installNativeApp({ plugins: {}, navigator: {} })), ["saveFiles", "signIn", "onBack", "backgroundRide", "setImmersive"]); assert.equal(installNativeApp({ plugins: {}, navigator: {} }).saveFiles, null); assert.equal(typeof installNativeApp({ plugins: share, navigator: {} }).saveFiles, "function"); assert.equal(typeof installNativeApp({ plugins: { WebAuth: {} }, navigator: {} }).signIn, "function"); @@ -385,3 +385,16 @@ test("system-bar control stays optional on other platforms and older shells", () assert.equal(installNativeApp({ plugins: {}, navigator: {}, platform: "android" }).setImmersive, null); assert.equal(installNativeApp({ plugins: { SystemBars: {} }, navigator: {}, platform: "ios" }).setImmersive, null); }); + +test("Bluetooth being off retains a category distinct from cancelling the picker", async () => { + const { fake, bluetooth } = setup(); + fake.plugin.isEnabled = async () => ({ value: false }); + await assert.rejects(bluetooth.requestDevice({}), { code: "BLUETOOTH_OFF" }); +}); + +test("a native GATT timeout retains an actionable timeout category", async () => { + const { fake, bluetooth } = setup(); + const device = await bluetooth.requestDevice({}); + fake.fail.connect = "Connection timeout."; + await assert.rejects(device.gatt.connect(), { name: "TimeoutError" }); +}); diff --git a/client/test/nativeRide.test.js b/client/test/nativeRide.test.js new file mode 100644 index 00000000..27933628 --- /dev/null +++ b/client/test/nativeRide.test.js @@ -0,0 +1,116 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { NativeRide, mergeNativeRecovery, nativeControl } from "../public/js/native/backgroundRide.js"; + +function fakePlugin() { + let emit; + const calls = []; + const snapshots = []; + return { + calls, snapshots, emit: (event) => emit(event), + addListener: async (name, listener) => { assert.equal(name, "event"); emit = listener; return { remove() {} }; }, + openSocket: async (value) => calls.push(["open", value]), + sendSocket: async (value) => calls.push(["send", value]), + closeSocket: async (value) => calls.push(["close", value]), + observeEvent: async (value) => calls.push(["observe", value]), + bleOperation: async (value) => { calls.push(["ble", value]); return {}; }, + startRide: async (value) => { calls.push(["start", value]); return { active: true }; }, + snapshot: async () => snapshots.shift() ?? { samples: [], active: true, ended: false }, + stopRide: async () => ({ samples: [], active: false }), + updateRide: async (value) => calls.push(["update", value]), + }; +} +const flush = async () => { for (let i = 0; i < 10; i++) await Promise.resolve(); }; + +test("the native socket registers its listener before opening", async () => { + const plugin = fakePlugin(); + const ride = new NativeRide({ plugin, makeId: () => "s1" }); + const socket = ride.createSocket("wss://example.com/ws"); + let opened = false; + socket.addEventListener("open", () => { opened = true; }); + await flush(); + plugin.emit({ type: "open", id: "s1" }); + assert.equal(opened, true); + assert.equal(socket.readyState, 1); + socket.send("hello"); + await flush(); + assert.deepEqual(plugin.calls.at(-1), ["send", { id: "s1", data: "hello" }]); +}); + +test("a socket that closes before native setup never opens afterward", async () => { + const plugin = fakePlugin(); + const ride = new NativeRide({ plugin, makeId: () => "s1" }); + const socket = ride.createSocket("wss://example.com/ws"); + socket.close(); + await flush(); + assert.equal(plugin.calls.some(([kind]) => kind === "open"), false); + assert.equal(socket.readyState, 3); +}); + +test("native recording imports each sample once without waiting for animation frames", async () => { + const plugin = fakePlugin(); + const kept = []; + const ride = new NativeRide({ plugin, schedule: () => 1, cancel() {} }); + await ride.start({ snapshot: { recorder: { samples: [] } }, trainerId: "trainer" }, { onSamples: (samples) => kept.push(...samples) }); + plugin.snapshots.push({ samples: [{ t: 1000, power: 200 }], active: true }); + await ride.flush(); + plugin.snapshots.push({ samples: [{ t: 1000, power: 200 }, { t: 2000, power: 210 }], active: true }); + await ride.flush(); + assert.deepEqual(kept.map((s) => s.t), [1000, 2000]); +}); + +test("finishing imports pending samples before releasing native recording", async () => { + const plugin = fakePlugin(); + const kept = []; + plugin.snapshots.push({ samples: [{ t: 1000 }], active: true }); + const ride = new NativeRide({ plugin, schedule: () => 1, cancel() {} }); + await ride.start({ snapshot: { recorder: { samples: [] } }, trainerId: "trainer" }, { onSamples: (samples) => kept.push(...samples) }); + await ride.stop(true); + assert.deepEqual(kept.map((s) => s.t), [1000]); + assert.equal(ride.active, false); +}); + +test("Bluetooth notifications use the native tap instead of queued WebView callbacks", async () => { + const plugin = fakePlugin(); + const ride = new NativeRide({ plugin }); + const bluetooth = ride.bluetooth({ initialize: () => "initialized" }); + const values = []; + await bluetooth.addListener("notification|trainer|s|c", (data) => values.push(data.value)); + plugin.emit({ type: "ble", event: "notification|trainer|s|c", value: { value: "aabb" } }); + assert.deepEqual(values, ["aabb"]); + assert.equal(bluetooth.initialize(), "initialized"); +}); + +test("recovery merges journal samples without discarding enriched browser positions", () => { + const stored = { nativeRideId: "ride-1", recorder: { samples: [{ t: 1000, power: 200, lat: 1, lon: 2 }], pauses: [] } }; + const native = { nativeRideId: "ride-1", savedAt: 2000, distance: 20, recorder: { samples: [{ t: 1000, power: 200 }, { t: 2000, power: 210 }] } }; + const merged = mergeNativeRecovery(stored, native); + assert.equal(merged.recorder.samples.length, 2); + assert.equal(merged.recorder.samples[0].lat, 1); + assert.equal(merged.savedAt, 2000); +}); + +test("a journal from another ride never replaces an existing unfinished ride", () => { + const saved = { nativeRideId: "a", recorder: { samples: [] } }; + assert.equal(mergeNativeRecovery(saved, { nativeRideId: "b", recorder: { samples: [] } }), saved); +}); + +test("background control includes the active workout and selected virtual gear", () => { + const data = nativeControl({ profile: { ftp: 200, difficulty: .5, weightKg: 75, chainring: 40, cog: 20 }, + training: { mode: "erg", intensity: 1.1, targetWatts: () => 220, player: { elapsedS: 42, workout: { segments: [{ durationS: 60, from: .5, to: 1 }] } } }, + gearbox: { ratio: 2 }, routes: new Map([["r", { length: 1000 }]]) }); + assert.equal(data.elapsed, 42); + assert.equal(data.referenceRatio, 2); + assert.equal(data.segments[0].durationS, 60); + assert.deepEqual(data.routeLengths, { r: 1000 }); +}); + +test("concurrent end requests stop the native recorder only once", async () => { + const plugin = fakePlugin(); + let stops = 0; + plugin.stopRide = async () => { stops++; return { samples: [], active: false }; }; + const ride = new NativeRide({ plugin, schedule: () => 1, cancel() {} }); + await ride.start({ snapshot: {}, trainerId: "trainer" }); + await Promise.all([ride.stop(true), ride.stop(true)]); + assert.equal(stops, 1); +}); diff --git a/client/test/workoutPlan.test.js b/client/test/workoutPlan.test.js index c0d300e7..72857dc7 100644 --- a/client/test/workoutPlan.test.js +++ b/client/test/workoutPlan.test.js @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { EXERCISES, createPlan, planDuration, planPositionAt, planSummary, withGetReady } from "../public/js/workout/plan.js"; +import { WorkoutPlayer, createWorkout, steady } from "../public/js/ride/workout.js"; import { PRESETS } from "../public/js/workout/presets.js"; test("a plan keeps its blocks and labels them", () => { @@ -73,3 +74,11 @@ test("a flow's movements each point at one of its steps", () => { for (const index of flow.order) assert.ok(index >= 0 && index < steps.length, String(index)); assert.deepEqual([...new Set(flow.order)], steps.map((_, i) => i)); }); + + +test("a workout reconciles its native background clock without counting the gap twice", () => { + const player = new WorkoutPlayer(createWorkout({ name: "Native", segments: [steady(120, .5)] }), 200); + player.tick(10); + player.restoreElapsed(60, 70); + assert.equal(player.tick(71).elapsedS, 61); +}); diff --git a/docs/adr/0028-android-ride-service.md b/docs/adr/0028-android-ride-service.md new file mode 100644 index 00000000..eaec121a --- /dev/null +++ b/docs/adr/0028-android-ride-service.md @@ -0,0 +1,24 @@ +# 0028 — Own Android background rides in a foreground service + +## Context + +A WebView's animation frames and timers are not reliable background clocks. +Keeping Bluetooth connected alone does not keep game telemetry or recording alive. + +## Decision + +A ride-scoped Android connected-device service owns the WebSocket, native sensor +listeners, telemetry timer and local sample journal. A deterministic engine is +separate from Android lifecycle and transport. The foreground client uses the +same transport and journal, so backgrounding is a change of control ownership, +not a second rider or duplicate recorder. Existing BLE plugin native operations +are reused through public plugin APIs rather than a fork or a second GATT stack. + +## Consequences + +Android gains a visible ride notification, a scoped wake lock and native clock +and control tests. Android must declare the connected-device foreground service +in Play Console. The web deployment and app update must ship together. Native +control codecs mirror a small part of the client and require parity fixtures. +Force-stop does not auto-resume: the journal is recoverable, but live riding +requires an explicit new start. iOS remains under its existing lifecycle limits. diff --git a/docs/app.md b/docs/app.md index a7e1806a..30d0430b 100644 --- a/docs/app.md +++ b/docs/app.md @@ -73,6 +73,63 @@ and light icons, including visibility after backgrounding and in landscape. Client tests cover entering and leaving immersive mode. With more than one device attached, select one with `adb -s`. +## Android background rides + +During a measured trainer ride, Android runs a `connectedDevice` foreground +service with its own sensor callbacks, WebSocket, telemetry clock and local +journal. Switching to another app or locking the screen does not depend on +WebView animation frames to keep power, cadence and recording going. Native +reconnect restores the trainer/strap subscriptions and resumes the server rider +using the existing protocol token. Readings older than five seconds are not +replayed as fresh power; a lost server connection does not invent distance. + +An ongoing notification shows the OpenRadlr emblem, live watts, distance and a +minutes/seconds clock even when collapsed. Expand it for cadence, elapsed time, +route/workout progress and **Return to ride** / **End & save**. Android asks for +notification permission the first time. Declining it does not prevent Android +from running the service, but its notification is then subject to Android's +notification-permission visibility rules. End/save keeps the recording locally, +leaves the game and releases trainer resistance; it never uploads a ride. + +The service runs only for a real-trainer ride. It stops its timer and wake lock +when the ride ends. The native journal is private to the app and excluded from +Android backups; it is reconciled with the usual unfinished-ride recovery on the +next launch. Force-stop, reboot or process termination stop live riding: recovery +preserves completed samples without pretending the ride kept running. Background +support here is Android-specific; iOS keeps the limitations below. + +Bluetooth connection failures distinguish a switched-off adapter, unavailable +hardware, denied permission and a timeout. Native permission/adapter explanations +offer Android settings shortcuts. A timeout suggests waking the trainer and +closing other apps without claiming another app definitely owns it. A refused +control point remains distinguishable from a power-only trainer. + +Deploy this web client with the updated Android shell. Older shells retain their +existing foreground behavior. The unreleased Android version code remains **3**. +For Google Play, declare the connected-device foreground service and describe its +user-started trainer connection, ongoing notification, and stop action. + +Native checks (alongside `make check`): + +```bash +cd app/android +./gradlew :app:testDebugUnitTest :app:assembleDebug :app:assembleDebugAndroidTest +adb install -r app/build/outputs/apk/debug/app-debug.apk +adb install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk +adb shell am instrument -w com.openradlr.app.test/androidx.test.runner.AndroidJUnitRunner +``` + +The background instrumentation test uses the real Android service, screen lock, +WebSocket and journal with a fake peripheral/peer at their I/O boundaries. It +checks measured telemetry, notification controls and completed-ride recovery. +`RidePreviewTest` is an opt-in interactive smoke fixture (`-e interactive true`) +for the local server, not an automatic CI test or production simulator. + +Before store rollout, test a physical FTMS trainer and heart-rate strap: switch +apps, lock for several minutes, disconnect/reconnect the trainer, interrupt the +network, resume a workout and end from the notification. Emulator fakes verify +lifecycle and data flow, not radio/firmware interoperability. + ## Strava sign-in Google and Apple don't allow sign-in inside an embedded web view. So in the @@ -254,17 +311,16 @@ description. 10. Android: back works as in [Back button](#back-button). Mid-ride it asks before finishing, mid-workout it pauses and asks, and on the start menu the app goes to the background. -11. Lock the phone or switch apps for a minute mid-ride, then come back: the - trainer is still connected (iOS) and the ride goes on. +11. Android: lock the phone or switch apps mid-ride. Check the live notification, + continued samples, reconnection and End/save. Returning restores the recorded + ride. Test on physical hardware as well as the emulator. ## Known limitations -- **Background:** on iOS the app declares the `bluetooth-central` background - mode, so the trainer, strap and controllers stay connected while the app is - in the background. The page and its server connection are still paused - there, so your rider stops and the ride picks up again when you come back. App Review asks why an app uses this mode; the answer is "keeps the - rider's fitness devices connected". Android has no equivalent yet (it would - need a foreground service); there the devices reconnect when you return. +- **iOS background:** `bluetooth-central` keeps fitness-device connections + available, but the page and server connection can still pause. Android's native + background-ride service does not change iOS execution. App Review may ask for + the purpose of the background mode: keeping the rider's fitness devices connected. - **Picker filters:** the native picker takes one filter (see ADR 0021). Zwift controllers are found by their name prefix "Zwift". - **App Store review:** an app that wraps a website must offer more than the diff --git a/docs/superpowers/plans/2026-11-16-android-background-riding.md b/docs/superpowers/plans/2026-11-16-android-background-riding.md new file mode 100644 index 00000000..0e6397e3 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-android-background-riding.md @@ -0,0 +1,11 @@ +# Android background riding implementation plan + +Spec: `../specs/2026-11-16-android-background-riding-design.md`. + +- [ ] Add failing deterministic native engine and client adapter tests. +- [ ] Implement native sensor parsing, clocks, control and private journal. +- [ ] Implement foreground service, native BLE subscriptions and WebSocket bridge. +- [ ] Wire measured Android rides, recording, recovery and workout reconciliation. +- [ ] Add categorized connection failures, settings shortcuts and EN/DE text. +- [ ] Run `make check`, native tests and emulator lifecycle/visual checks. +- [ ] Rebuild signed build 3, update PR #118 and release artifact checksums. diff --git a/docs/superpowers/specs/2026-11-16-android-background-riding-design.md b/docs/superpowers/specs/2026-11-16-android-background-riding-design.md new file mode 100644 index 00000000..6158636f --- /dev/null +++ b/docs/superpowers/specs/2026-11-16-android-background-riding-design.md @@ -0,0 +1,53 @@ +# Android background riding and connection recovery + +## Intent + +Android build 3 should keep a measured trainer ride going when the rider switches +apps or locks the screen. A visible foreground service owns the transport, +telemetry clock and private ride journal; WebView rendering is not the clock. + +## Design + +- A `connectedDevice` foreground service runs only during a real-trainer ride. + It holds a partial wake lock, shows a localized return-to-ride notification, + and stops when the ride ends. Collapsed stats show the brand mark and mm:ss; + expanded stats include progress and a local End/save action. No boot receiver or sticky restart. +- The app's native ride plugin owns the WebSocket from the initial handshake. + The client uses a WebSocket-shaped adapter; the server protocol is unchanged. + Native reconnect uses the existing resume token and last route position. +- Reuse the BLE plugin's native listeners and operations through its public + PluginCall API. Native listeners receive packets without executing JavaScript. + Background reconnect restores the subscribed trainer/heart-rate characteristics. +- A deterministic native engine parses FTMS, cycling power and heart rate, + rejects stale readings, advances telemetry and resistance, and records one + sample per second. Heart rate stays local and is never sent to the game. +- The native journal is the Android ride's sample source in foreground too, + avoiding duplicate/missing samples at handover. The web client enriches samples + with virtual-route position and elevation and keeps the existing export flow. + An app-private journal survives process loss; restart offers recovery rather + than restarting a ride or replaying old power. +- Background control follows road grades with easing, manual ERG and serialized + workout/class targets. User settings and workout progress cross the bridge; + returning to the foreground reconciles the clock before continuing it. +- Bluetooth errors retain meaningful categories. Native settings actions are + offered for adapter/permission errors. Timeout text suggests waking the device + and closing competing apps; it must not claim that another app owns a trainer + unless the control point actually refused control. + +## Constraints and boundaries + +Android only for background execution in this release. iOS background execution +is unchanged. Force-stop, reboot and OS process termination stop live riding; +recover recorded samples, never fabricate continuity or fresh sensor readings. +No battery-optimization exemption, location permission or automatic uploads. +Permission failure leaves foreground riding usable with an actionable explanation. + +## Validation + +Plain-node tests cover socket lifecycle, bridge handover, journal deduplication, +recovery, workout reconciliation and localized troubleshooting. Native JVM tests +use injected time and sinks for stale readings, packet decoding, control ramps, +recording and lifecycle. Android instrumentation verifies service notification, +background/lock transitions, stop and restart recovery with native packet fakes. +The emulator cannot validate actual radio interoperability: document a physical +trainer checklist and do not represent fake packets as physical-device testing. From 86a08ab2943baabe91c42c46661be4244539360b Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 19:51:51 +0100 Subject: [PATCH 05/12] fix(app): Preserve the server origin on native ride sockets --- .../java/com/openradlr/app/ride/BackgroundRideTest.java | 3 +++ .../app/src/main/java/com/openradlr/app/ride/RideService.java | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java index 2aa6781f..bbbe4322 100644 --- a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java +++ b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java @@ -93,6 +93,9 @@ private static void shell(String command) throws Exception { ride.observeEvent(BIKE); ride.openSocket("test-socket", server.url("/ws").toString().replace("http:", "ws:"), null); await(joined, "Join through native WebSocket"); + RecordedRequest upgrade = server.takeRequest(5, TimeUnit.SECONDS); + assertNotNull(upgrade); + assertEquals(server.url("/").toString().replaceAll("/$", ""), upgrade.getHeader("Origin")); JSObject snapshot = new JSObject().put("version", 1).put("nativeRideId", "device-test") .put("rideStartedAt", System.currentTimeMillis() - 65000).put("savedAt", System.currentTimeMillis()) .put("routeId", "test-route").put("routeName", "Rolling Hills · device test").put("distance", "true".equals(InstrumentationRegistry.getArguments().getString("preview")) ? 12400 : 0) diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java index bca950ad..b954f0b8 100644 --- a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java @@ -294,7 +294,9 @@ public void openSocket(String id, String address, String cookies) { execute(() - }); } private void connectSocket(boolean resume) { long generation = ++socketGeneration; - Request.Builder request = new Request.Builder().url(url).header("User-Agent", "OpenRadlr/" + BuildConfig.VERSION_NAME + " (android; build/" + BuildConfig.VERSION_CODE + ")"); + Request.Builder request = new Request.Builder().url(url) + .header("Origin", (url.startsWith("wss:") ? "https://" : "http://") + java.net.URI.create(url).getRawAuthority()) + .header("User-Agent", "OpenRadlr/" + BuildConfig.VERSION_NAME + " (android; build/" + BuildConfig.VERSION_CODE + ")"); if (cookie != null && !cookie.isEmpty()) request.header("Cookie", cookie); socket = http.newWebSocket(request.build(), new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { execute(() -> { From 5881c9528b75f712a412ad9a4298deafbf739d74 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 19:54:52 +0100 Subject: [PATCH 06/12] fix(app): Reconcile native ride time before rendering resumes --- .../main/java/com/openradlr/app/ride/RideService.java | 3 ++- client/public/js/main.js | 5 +++-- client/public/js/native/backgroundRide.js | 4 ++++ client/test/nativeRide.test.js | 11 +++++++++++ 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java index b954f0b8..4ce70473 100644 --- a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java @@ -79,6 +79,7 @@ public final class LocalBinder extends Binder { public RideService service() { r public void attach(BleTransport nativeBle, Consumer events) { execute(() -> { if (!active && ble != nativeBle) { if (ble != null) ble.close(); watched.clear(); freshBle.clear(); ble = nativeBle; } if (events != null) emitter = events; }); } public void background(boolean value) { execute(() -> { + boolean wasBackground = background; background = value; if (engine != null) engine.background = value; if (!value) { @@ -88,7 +89,7 @@ public void background(boolean value) { importantFrames.clear(); for (JSObject frame : latestFrames.values()) emit(frame); latestFrames.clear(); - emit(new JSObject().put("type", "rideState").put("ended", ended)); + emit(new JSObject().put("type", "rideState").put("ended", ended).put("resumed", wasBackground)); } }); } diff --git a/client/public/js/main.js b/client/public/js/main.js index 786926b0..113507c3 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -2263,12 +2263,13 @@ async function startNativeRide() { app.lastMyDistance = riders.find((rider) => rider.id === app.riderId)?.distance ?? null; app.nativeWasHidden = false; } - app.nativeSyncing = false; + if (!document.hidden) app.nativeSyncing = false; if (state.error && !app.nativeRecordError) { app.nativeRecordError = true; notify(t("nativeRide.storageError"), "error"); } const checkpoint = rideSnapshot(); checkpoint.recorder = { pauses: recorder.pauses, intervalMs: recorder.intervalMs }; await nativeRide.update(control(), checkpoint); }, + onResume: () => { app.nativeWasHidden = true; app.nativeSyncing = true; }, onEnded: () => finishRide(), onError: () => { app.nativeSyncing = false; notify(t("nativeRide.failed"), "error"); }, }); @@ -4047,7 +4048,7 @@ function initRecovery() { document.addEventListener("visibilitychange", () => { deviceLog.info(`Page ${document.visibilityState}`); if (document.visibilityState !== "hidden") { - if (nativeRide?.active) nativeRide.flush().catch((error) => { app.nativeSyncing = false; console.warn(error); }); + if (nativeRide?.active) { app.nativeSyncing = true; nativeRide.flush().catch((error) => { app.nativeSyncing = false; console.warn(error); }); } return; } if (nativeRide?.active) { app.nativeWasHidden = true; app.nativeSyncing = true; } diff --git a/client/public/js/native/backgroundRide.js b/client/public/js/native/backgroundRide.js index 5ad0b42b..31699ea7 100644 --- a/client/public/js/native/backgroundRide.js +++ b/client/public/js/native/backgroundRide.js @@ -23,6 +23,10 @@ export class NativeRide { for (const listener of this.#ble.get(event.event) ?? []) listener(event.value); } else if (event.type === "rideState") { if (event.ended && this.active) this.flush().then(() => this.#callbacks.onEnded?.()).catch(this.#onError); + else if (event.resumed && this.active) { + this.#callbacks.onResume?.(); + this.flush().catch(this.#onError); + } } else if (event.type === "serviceLost") { for (const socket of this.#sockets.values()) socket.dispatch("close"); this.active = false; this.#cancel(this.#timer); diff --git a/client/test/nativeRide.test.js b/client/test/nativeRide.test.js index 27933628..8af1ef93 100644 --- a/client/test/nativeRide.test.js +++ b/client/test/nativeRide.test.js @@ -114,3 +114,14 @@ test("concurrent end requests stop the native recorder only once", async () => { await Promise.all([ride.stop(true), ride.stop(true)]); assert.equal(stops, 1); }); + +test("native resume gates frames before reconciling the background workout clock", async () => { + const plugin = fakePlugin(); + const order = []; + plugin.snapshots.push({ samples: [], active: true, elapsed: 42 }); + const ride = new NativeRide({ plugin, schedule: () => 1, cancel() {} }); + await ride.start({ snapshot: {}, trainerId: "trainer" }, { onResume: () => order.push("gate"), onState: (state) => order.push(state.elapsed) }); + plugin.emit({ type: "rideState", resumed: true, ended: false }); + await flush(); + assert.deepEqual(order, ["gate", 42]); +}); From f2dc8f8c54f6a11085fe020b2eefda50621b9ee1 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 19:56:18 +0100 Subject: [PATCH 07/12] fix(app): Follow class changes and preserve completed background rides --- .../app/ride/BackgroundRideTest.java | 3 ++ .../com/openradlr/app/ride/RideService.java | 33 ++++++++++++++----- client/public/js/native/backgroundRide.js | 1 + client/test/nativeRide.test.js | 7 ++++ 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java index bbbe4322..2b93cb00 100644 --- a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java +++ b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java @@ -155,6 +155,9 @@ private static void shell(String command) throws Exception { await(ended, "End/save action from notification"); } journal.stopWatching(); + CountDownLatch stopped = new CountDownLatch(1); + ride.stopRide(false, state -> stopped.countDown()); + await(stopped, "A late UI stop cannot undo End/save"); CountDownLatch recovered = new CountDownLatch(1); ride.recover(value -> { JSObject saved = value.getJSObject("snapshot"); diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java index 4ce70473..82eb2a51 100644 --- a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java @@ -36,6 +36,7 @@ public final class LocalBinder extends Binder { public RideService service() { r private boolean reconnecting, intentionalClose; private Consumer emitter; private BleTransport ble; + private final Map classSegments = new HashMap<>(); private final Map watched = new LinkedHashMap<>(); private final Set reconnectingDevices = new HashSet<>(); private final Map freshBle = new LinkedHashMap<>(); @@ -141,14 +142,10 @@ private void configure(JSObject data) { c.mass = finite(data, "mass", 85); c.cda = finite(data, "cda", .32); c.airDensity = finite(data, "airDensity", 1.225); c.elapsed = finite(data, "elapsed", 0); c.erg = data.optBoolean("erg"); c.classClock = data.optBoolean("classClock"); if (!data.isNull("target") && data.has("target")) c.target = finite(data, "target", 0); - JSONArray segments = data.optJSONArray("segments"); - if (segments != null && segments.length() <= 500) { - List valid = new ArrayList<>(); - for (int i = 0; i < segments.length(); i++) { - JSONObject s = segments.optJSONObject(i); - if (s != null && s.optDouble("durationS", 0) > 0) valid.add(new double[] {Math.min(21600, s.optDouble("durationS")), Math.max(0, Math.min(3, s.optDouble("from"))), Math.max(0, Math.min(3, s.optDouble("to")))}); - } - c.segments = valid.toArray(new double[0][]); + c.segments = segmentsOf(data.optJSONArray("segments")); + JSONObject classes = data.optJSONObject("classes"); + if (classes != null) for (Iterator keys = classes.keys(); keys.hasNext();) { + String id = keys.next(); classSegments.put(id, segmentsOf(classes.optJSONArray(id))); } engine.control = c; imperial = "imperial".equals(data.optString("units")); @@ -159,6 +156,17 @@ private void configure(JSObject data) { if (length > 0 && Double.isFinite(length)) engine.routeLengths.put(key, length); } } + private static double[][] segmentsOf(JSONArray segments) { + List valid = new ArrayList<>(); + if (segments != null && segments.length() <= 500) for (int i = 0; i < segments.length(); i++) { + JSONObject segment = segments.optJSONObject(i); + if (segment == null) continue; + double duration = segment.optDouble("durationS", 0), from = segment.optDouble("from", Double.NaN), to = segment.optDouble("to", Double.NaN); + if (duration > 0 && Double.isFinite(duration) && Double.isFinite(from) && Double.isFinite(to)) + valid.add(new double[] {Math.min(21600, duration), Math.max(0, Math.min(3, from)), Math.max(0, Math.min(3, to))}); + } + return valid.toArray(new double[0][]); + } public void snapshot(long since, Consumer ok) { execute(() -> { JSArray pending = new JSArray(); for (JSObject sample : samples) if (sample.optLong("t") > since && pending.length() < 1000) pending.put(sample); @@ -175,7 +183,7 @@ public void clear(Consumer done) { execute(() -> { try { journal.clear(); done.accept(null); } catch (IOException e) { done.accept(e.getMessage()); } }); } public void stopRide(boolean finished, Consumer ok) { execute(() -> { - finishJournal(finished); active = false; ended = finished; stopResources(); + ended = ended || finished; finishJournal(ended); active = false; stopResources(); snapshot(samples.size() > 1000 ? samples.get(samples.size() - 1001).optLong("t") : -1, ok); }); } private void finishJournal(boolean finished) { @@ -361,6 +369,13 @@ private void handleServer(String text) { } if (engine == null) return; if (type.equals("error") && "pause_rejected".equals(message.optString("code"))) engine.paused = false; + if (type.equals("studio_state") && engine.control.classClock) { + JSONObject currentClass = message.optJSONObject("class"); + if (currentClass != null) { + engine.control.segments = classSegments.getOrDefault(currentClass.optString("id"), new double[0][]); + engine.control.elapsed = finite(currentClass, "elapsed_s", 0); + } + } if (type.equals("resistance")) engine.resistance(message.optDouble("grade_percent", 0)); if (type.equals("state") || type.equals("studio_state")) { JSONArray riders = message.optJSONArray("riders"); diff --git a/client/public/js/native/backgroundRide.js b/client/public/js/native/backgroundRide.js index 31699ea7..637448d8 100644 --- a/client/public/js/native/backgroundRide.js +++ b/client/public/js/native/backgroundRide.js @@ -152,6 +152,7 @@ export function nativeControl({ profile, training, gearbox, routes = new Map(), segments: plan ? plan.segments.map((s) => ({ durationS: s.duration_s, from: s.from, to: s.to })) : player?.workout.segments ?? [], elapsed: studio ? studio.elapsed(nowS) ?? 0 : player?.elapsedS ?? 0, classClock: Boolean(studio), + classes: studio?.classes ? Object.fromEntries([...studio.classes].map(([id, plan]) => [id, plan.segments.map((s) => ({ durationS: s.duration_s, from: s.from, to: s.to }))])) : {}, ratio: gearbox?.ratio ?? 0, referenceRatio: profile.chainring / profile.cog, mass: physics?.mass_kg ?? profile.weightKg + 9, cda: physics?.cda_m2 ?? .32, crr: physics?.crr ?? .004, airDensity: physics?.air_density ?? 1.225, diff --git a/client/test/nativeRide.test.js b/client/test/nativeRide.test.js index 8af1ef93..34c51b04 100644 --- a/client/test/nativeRide.test.js +++ b/client/test/nativeRide.test.js @@ -125,3 +125,10 @@ test("native resume gates frames before reconciling the background workout clock await flush(); assert.deepEqual(order, ["gate", 42]); }); + +test("the native class catalog can follow the next scheduled studio class while hidden", () => { + const segments = [{ duration_s: 60, from: .5, to: 1 }]; + const data = nativeControl({ profile: { ftp: 200, difficulty: 1, weightKg: 75, chainring: 40, cog: 20 }, + studio: { classes: new Map([["next-class", { segments }]]), plan: { segments }, intensity: 1, erg: true, targetWatts: () => 150, elapsed: () => 30 } }); + assert.deepEqual(data.classes["next-class"], [{ durationS: 60, from: .5, to: 1 }]); +}); From 1f4df9cf43a8149f569822ad33c3ff273e35da03 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 20:32:06 +0100 Subject: [PATCH 08/12] ci: Install the Android SDK before native checks --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 047bcacd..18ac6358 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,6 +65,7 @@ jobs: java-version: 21 cache: gradle cache-dependency-path: app/android/**/*.gradle* + - uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3 - run: sdkmanager "platforms;android-36" "build-tools;36.0.0" - run: npm ci --no-audit --no-fund - run: npx cap sync android From 6544d5eab95c5d77b239db4612f0b66013ebba9e Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 20:43:16 +0100 Subject: [PATCH 09/12] ci: Use the runner Android SDK without an additional action --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 18ac6358..0d0985d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -65,8 +65,8 @@ jobs: java-version: 21 cache: gradle cache-dependency-path: app/android/**/*.gradle* - - uses: android-actions/setup-android@9fc6c4e9069bf8d3d10b2204b1fb8f6ef7065407 # v3 - - run: sdkmanager "platforms;android-36" "build-tools;36.0.0" + - name: Install the Android SDK packages + run: '"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" "platforms;android-36" "build-tools;36.0.0"' - run: npm ci --no-audit --no-fund - run: npx cap sync android - run: ./android/gradlew -p android :app:testDebugUnitTest :app:lintDebug :app:assembleDebug From 57600a022ccf4b7f7600b53c73876cb48e8751e5 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 20:48:20 +0100 Subject: [PATCH 10/12] feat(app): Add an untethered bundled-client preview build --- app/android/app/build.gradle | 16 ++++++ .../java/com/openradlr/app/MainActivity.java | 1 + .../openradlr/app/preview/BundledPreview.java | 53 +++++++++++++++++++ .../openradlr/app/preview/PreviewPath.java | 23 ++++++++ .../app/preview/PreviewPathTest.java | 32 +++++++++++ docs/app.md | 18 +++++++ .../2026-11-16-android-background-riding.md | 17 +++--- 7 files changed, 153 insertions(+), 7 deletions(-) create mode 100644 app/android/app/src/main/java/com/openradlr/app/preview/BundledPreview.java create mode 100644 app/android/app/src/main/java/com/openradlr/app/preview/PreviewPath.java create mode 100644 app/android/app/src/test/java/com/openradlr/app/preview/PreviewPathTest.java diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 71012b33..9e7c65aa 100644 --- a/app/android/app/build.gradle +++ b/app/android/app/build.gradle @@ -10,6 +10,7 @@ if (keystorePropertiesFile.exists()) { } def uploadKey = { String name, String env -> System.getenv(env) ?: keystoreProperties.getProperty(name) } def uploadStoreFile = uploadKey('storeFile', 'OPENRADLR_UPLOAD_STORE_FILE') +def bundledPreview = providers.gradleProperty('bundledPreview').map { it == 'true' }.getOrElse(false) android { namespace = "com.openradlr.app" @@ -25,6 +26,7 @@ android { // The client comes from the server, so this only changes with the native shell. versionCode 3 versionName "0.1.0" + buildConfigField 'boolean', 'BUNDLED_PREVIEW', 'false' testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. @@ -43,6 +45,9 @@ android { } } buildTypes { + debug { + buildConfigField 'boolean', 'BUNDLED_PREVIEW', bundledPreview.toString() + } release { if (uploadStoreFile) { signingConfig signingConfigs.release @@ -51,7 +56,18 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } + sourceSets.debug.assets.srcDir(layout.buildDirectory.dir('generated/previewAssets')) +} + +// Opt-in developer build: current client assets with the configured live backend. +// Release bundles always keep the normal server-delivered client. +def previewAssets = tasks.register('preparePreviewAssets', Sync) { + if (bundledPreview) { + from('../../../client/public') { into 'bundled-preview' } + } + into layout.buildDirectory.dir('generated/previewAssets') } +tasks.named('preBuild').configure { dependsOn previewAssets } repositories { flatDir{ diff --git a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java index 8dd970cc..6313d510 100644 --- a/app/android/app/src/main/java/com/openradlr/app/MainActivity.java +++ b/app/android/app/src/main/java/com/openradlr/app/MainActivity.java @@ -15,6 +15,7 @@ protected void load() { webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + suffix); registerPlugin(com.openradlr.app.ride.BackgroundRidePlugin.class); super.load(); + if (BuildConfig.BUNDLED_PREVIEW) com.openradlr.app.preview.BundledPreview.install(bridge); // Ride visibility is controlled by SystemBars from the client. Keep edge // swipes available while hidden, without forcing fullscreen on the menu. WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView()) diff --git a/app/android/app/src/main/java/com/openradlr/app/preview/BundledPreview.java b/app/android/app/src/main/java/com/openradlr/app/preview/BundledPreview.java new file mode 100644 index 00000000..470fcea9 --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/preview/BundledPreview.java @@ -0,0 +1,53 @@ +package com.openradlr.app.preview; + +import android.webkit.ServiceWorkerClient; +import android.webkit.ServiceWorkerController; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebView; +import com.getcapacitor.Bridge; +import com.getcapacitor.BridgeWebViewClient; +import java.io.IOException; +import java.util.Map; + +/** Local branch assets under the real backend origin, exclusively for opt-in debug builds. */ +public final class BundledPreview { + private BundledPreview() {} + public static void install(Bridge bridge) { + String origin = bridge.getConfig().getServerUrl(); + bridge.setWebViewClient(new BridgeWebViewClient(bridge) { + @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { + WebResourceResponse local = response(bridge, origin, request); + return local == null ? super.shouldInterceptRequest(view, request) : local; + } + }); + // An existing network-first worker must also receive the bundled assets. + ServiceWorkerController.getInstance().setServiceWorkerClient(new ServiceWorkerClient() { + @Override public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) { + return response(bridge, origin, request); + } + }); + bridge.getWebView().stopLoading(); + bridge.getWebView().loadUrl(origin); + } + private static WebResourceResponse response(Bridge bridge, String origin, WebResourceRequest request) { + String path = PreviewPath.asset(origin, request.getMethod(), request.getUrl().toString()); + if (path == null) return null; + try { + return new WebResourceResponse(mime(path), "UTF-8", 200, "OK", + Map.of("Cache-Control", "no-store", "X-OpenRadlr-Client", "bundled-preview"), + bridge.getContext().getAssets().open("bundled-preview/" + path)); + } catch (IOException e) { return null; } + } + private static String mime(String path) { + if (path.endsWith(".js")) return "application/javascript"; + if (path.endsWith(".css")) return "text/css"; + if (path.endsWith(".html")) return "text/html"; + if (path.endsWith(".json") || path.endsWith(".webmanifest")) return "application/json"; + if (path.endsWith(".svg")) return "image/svg+xml"; + if (path.endsWith(".png")) return "image/png"; + if (path.endsWith(".webp")) return "image/webp"; + if (path.endsWith(".woff2")) return "font/woff2"; + return "application/octet-stream"; + } +} diff --git a/app/android/app/src/main/java/com/openradlr/app/preview/PreviewPath.java b/app/android/app/src/main/java/com/openradlr/app/preview/PreviewPath.java new file mode 100644 index 00000000..2cd536e3 --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/preview/PreviewPath.java @@ -0,0 +1,23 @@ +package com.openradlr.app.preview; + +import java.net.URI; +import java.util.Objects; + +/** Routing policy for the opt-in, bundled-client developer build. */ +public final class PreviewPath { + private PreviewPath() {} + public static String asset(String origin, String method, String address) { + if (!"GET".equals(method)) return null; + try { + URI base = URI.create(origin), url = URI.create(address); + if (!Objects.equals(base.getScheme(), url.getScheme()) + || !Objects.equals(base.getHost(), url.getHost()) || base.getPort() != url.getPort() + || url.getUserInfo() != null) return null; + String path = url.getRawPath(); + if (path == null || path.contains("%") || path.contains("\\") || path.contains("..")) return null; + if (path.equals("/api") || path.startsWith("/api/") || path.equals("/auth") + || path.startsWith("/auth/") || path.equals("/ws")) return null; + return path.isEmpty() || path.equals("/") ? "index.html" : path.substring(1); + } catch (IllegalArgumentException e) { return null; } + } +} diff --git a/app/android/app/src/test/java/com/openradlr/app/preview/PreviewPathTest.java b/app/android/app/src/test/java/com/openradlr/app/preview/PreviewPathTest.java new file mode 100644 index 00000000..1a4b3d18 --- /dev/null +++ b/app/android/app/src/test/java/com/openradlr/app/preview/PreviewPathTest.java @@ -0,0 +1,32 @@ +package com.openradlr.app.preview; + +import static org.junit.Assert.*; +import org.junit.Test; + +public class PreviewPathTest { + private static final String ORIGIN = "https://app.openradlr.com"; + @Test public void rootUsesTheBundledStartScreen() { + assertEquals("index.html", PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/?lang=de")); + } + @Test public void modulesUseTheBundledVersion() { + assertEquals("js/main.js", PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/js/main.js?v=3")); + } + @Test public void productionApiRemainsOnTheNetwork() { + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/api/info")); + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/auth/strava")); + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/ws")); + } + @Test public void externalOriginsNeverReceiveBundledAssets() { + assertNull(PreviewPath.asset(ORIGIN, "GET", "https://example.org/js/main.js")); + assertNull(PreviewPath.asset(ORIGIN, "GET", "http://app.openradlr.com/js/main.js")); + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + ":8443/js/main.js")); + } + @Test public void writesAlwaysReachTheNetwork() { + assertNull(PreviewPath.asset(ORIGIN, "POST", ORIGIN + "/index.html")); + } + @Test public void pathsCannotEscapeTheBundledDirectory() { + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/../capacitor.config.json")); + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/%2e%2e/secret")); + assertNull(PreviewPath.asset(ORIGIN, "GET", ORIGIN + "/js%2fmain.js")); + } +} diff --git a/docs/app.md b/docs/app.md index 30d0430b..f45613f3 100644 --- a/docs/app.md +++ b/docs/app.md @@ -109,6 +109,24 @@ existing foreground behavior. The unreleased Android version code remains **3**. For Google Play, declare the connected-device foreground service and describe its user-started trainer connection, ongoing notification, and stop action. +For an untethered developer test of an unmerged client against production, build +an opt-in bundled-client debug APK. It uses the configured server origin for +API, authentication and ride sockets, while loading this checkout's static +client assets from the APK. No local server or `adb reverse` is needed after +installation. This changes the client on the test device only. + +```bash +cd app +npx cap sync android # default: https://app.openradlr.com +cd android +./gradlew -PbundledPreview=true :app:assembleDebug +adb -s install -r app/build/outputs/apk/debug/app-debug.apk +``` + +The preview uses the debug signing key; it can update a matching debug install, +but cannot replace a Play-signed app in place. Release bundles always use the +server-delivered client. Keep the Android version code unchanged for this preview. + Native checks (alongside `make check`): ```bash diff --git a/docs/superpowers/plans/2026-11-16-android-background-riding.md b/docs/superpowers/plans/2026-11-16-android-background-riding.md index 0e6397e3..6f83b866 100644 --- a/docs/superpowers/plans/2026-11-16-android-background-riding.md +++ b/docs/superpowers/plans/2026-11-16-android-background-riding.md @@ -2,10 +2,13 @@ Spec: `../specs/2026-11-16-android-background-riding-design.md`. -- [ ] Add failing deterministic native engine and client adapter tests. -- [ ] Implement native sensor parsing, clocks, control and private journal. -- [ ] Implement foreground service, native BLE subscriptions and WebSocket bridge. -- [ ] Wire measured Android rides, recording, recovery and workout reconciliation. -- [ ] Add categorized connection failures, settings shortcuts and EN/DE text. -- [ ] Run `make check`, native tests and emulator lifecycle/visual checks. -- [ ] Rebuild signed build 3, update PR #118 and release artifact checksums. +- [x] Add failing deterministic native engine and client adapter tests. +- [x] Implement native sensor parsing, clocks, control and private journal. +- [x] Implement foreground service, native BLE subscriptions and WebSocket bridge. +- [x] Wire measured Android rides, recording, recovery and workout reconciliation. +- [x] Add categorized connection failures, settings shortcuts and EN/DE text. +- [x] Run `make check`, native tests and emulator lifecycle/visual checks. +- [x] Rebuild signed build 3, update follow-up PR #120 and release artifact checksums. + +Developer testing also includes an opt-in bundled-client APK against production, +so manual trainer tests can continue without a local server or USB connection. From 6cd32e4df9fb5101700d7c83bb0c00c42171b270 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Mon, 16 Nov 2026 20:51:28 +0100 Subject: [PATCH 11/12] fix(app): Bind native ride timers to the WebView global --- client/public/js/native/backgroundRide.js | 2 +- client/test/nativeRide.test.js | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/client/public/js/native/backgroundRide.js b/client/public/js/native/backgroundRide.js index 637448d8..71e2bd8f 100644 --- a/client/public/js/native/backgroundRide.js +++ b/client/public/js/native/backgroundRide.js @@ -16,7 +16,7 @@ export class NativeRide { #callbacks = {}; #onError; - constructor({ plugin, makeId = () => globalThis.crypto.randomUUID(), schedule = globalThis.setInterval, cancel = globalThis.clearInterval, onError = () => {} }) { + constructor({ plugin, makeId = () => globalThis.crypto.randomUUID(), schedule = (fn, ms) => globalThis.setInterval(fn, ms), cancel = (id) => globalThis.clearInterval(id), onError = () => {} }) { this.#plugin = plugin; this.#makeId = makeId; this.#schedule = schedule; this.#cancel = cancel; this.#onError = (error) => { onError(error); this.#callbacks.onError?.(error); }; this.#ready = Promise.resolve(plugin.addListener("event", (event) => { if (event.type === "ble") { diff --git a/client/test/nativeRide.test.js b/client/test/nativeRide.test.js index 34c51b04..de4a5e83 100644 --- a/client/test/nativeRide.test.js +++ b/client/test/nativeRide.test.js @@ -132,3 +132,24 @@ test("the native class catalog can follow the next scheduled studio class while studio: { classes: new Map([["next-class", { segments }]]), plan: { segments }, intensity: 1, erg: true, targetWatts: () => 150, elapsed: () => 30 } }); assert.deepEqual(data.classes["next-class"], [{ durationS: 60, from: .5, to: 1 }]); }); + +test("starting a native ride calls browser timers with their Window receiver", async (t) => { + t.mock.method(globalThis, "setInterval", function () { + assert.equal(this, globalThis, "WebView timers require the global receiver"); + return 7; + }); + const ride = new NativeRide({ plugin: fakePlugin(), cancel() {} }); + await ride.start({ snapshot: {} }); + await ride.stop(); +}); + +test("finishing a native ride calls browser timer cancellation with its Window receiver", async (t) => { + t.mock.method(globalThis, "clearInterval", function (timer) { + assert.equal(this, globalThis, "WebView timers require the global receiver"); + assert.equal(timer, 7); + }); + const ride = new NativeRide({ plugin: fakePlugin(), schedule: () => 7 }); + await ride.start({ snapshot: {} }); + await ride.stop(true); + assert.equal(ride.active, false); +}); From 0e958314f42d92c352e8752a32d48bf2e561a2b7 Mon Sep 17 00:00:00 2001 From: Thore Koritzius Date: Tue, 17 Nov 2026 08:31:34 +0100 Subject: [PATCH 12/12] fix(app): Preserve background drafting and journal ownership --- app/android/app/build.gradle | 1 + .../app/ride/BackgroundRideTest.java | 20 +- .../com/openradlr/app/ride/RideEngine.java | 32 +++- .../com/openradlr/app/ride/RideService.java | 11 ++ .../openradlr/app/ride/RideEngineTest.java | 41 ++++ client/public/js/main.js | 9 +- client/public/js/native/backgroundRide.js | 9 +- client/test/fixtures/native-drafting.json | 179 ++++++++++++++++++ client/test/nativeDraftParity.test.js | 19 ++ client/test/nativeRide.test.js | 34 +++- docs/app.md | 9 +- 11 files changed, 351 insertions(+), 13 deletions(-) create mode 100644 client/test/fixtures/native-drafting.json create mode 100644 client/test/nativeDraftParity.test.js diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 9e7c65aa..30c8116a 100644 --- a/app/android/app/build.gradle +++ b/app/android/app/build.gradle @@ -57,6 +57,7 @@ android { } } sourceSets.debug.assets.srcDir(layout.buildDirectory.dir('generated/previewAssets')) + sourceSets.test.resources.srcDir('../../../client/test/fixtures') } // Opt-in developer build: current client assets with the configured live backend. diff --git a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java index 2b93cb00..330a2bfd 100644 --- a/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java +++ b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java @@ -28,8 +28,13 @@ public class BackgroundRideTest { private static final String BIKE = "notification|trainer|00001826-0000-1000-8000-00805f9b34fb|00002ad2-0000-1000-8000-00805f9b34fb"; private static final class Radio implements BleTransport { final Map> listeners = new ConcurrentHashMap<>(); + final CountDownLatch drafted = new CountDownLatch(1); @Override public void listen(String event, Consumer listener) { listeners.putIfAbsent(event, listener); } - @Override public void invoke(String method, JSObject options, Consumer ok, Consumer fail) { ok.accept(new JSObject()); } + @Override public void invoke(String method, JSObject options, Consumer ok, Consumer fail) { + // Web effectiveGrade: 12 m/s, 85 kg, 30% draft saving => 2.4% FTMS grade. + if (method.equals("write") && "110000f0002800".equals(options.optString("value"))) drafted.countDown(); + ok.accept(new JSObject()); + } @Override public void close() { listeners.clear(); } void pedal() { Consumer listener = listeners.get(BIKE); if (listener != null) listener.accept(new JSObject().put("value", "44001c0cb000d700")); } } @@ -55,7 +60,7 @@ private static void shell(String command) throws Exception { MockWebServer server = new MockWebServer(); AtomicReference peer = new AtomicReference<>(); server.enqueue(new MockResponse().withWebSocketUpgrade(new WebSocketListener() { - double metres; + double metres = 998; @Override public void onOpen(WebSocket socket, Response response) { peer.set(socket); } @Override public void onClosing(WebSocket socket, int code, String reason) { socket.close(code, reason); } @Override public void onMessage(WebSocket socket, String text) { @@ -68,7 +73,9 @@ private static void shell(String command) throws Exception { if (message.optDouble("power") == 215) measured.countDown(); assertFalse("Heart rate must remain local", message.has("heart_rate")); metres += 1; - socket.send("{\"type\":\"state\",\"riders\":[{\"id\":7,\"route\":\"test-route\",\"distance\":" + metres + ",\"speed\":4}]}"); + socket.send(new JSObject().put("type", "state").put("riders", new JSArray() + .put(new JSObject().put("id", 7).put("route", "test-route").put("distance", metres % 1000).put("speed", 12).put("lane", 2)) + .put(new JSObject().put("id", 8).put("route", "test-route").put("distance", (metres + 2) % 1000).put("speed", 12).put("lane", 2))).toString()); } } } catch (Exception e) { throw new AssertionError(e); } @@ -96,14 +103,15 @@ private static void shell(String command) throws Exception { RecordedRequest upgrade = server.takeRequest(5, TimeUnit.SECONDS); assertNotNull(upgrade); assertEquals(server.url("/").toString().replaceAll("/$", ""), upgrade.getHeader("Origin")); - JSObject snapshot = new JSObject().put("version", 1).put("nativeRideId", "device-test") + JSObject snapshot = new JSObject().put("version", 1).put("nativeRideId", "device-test").put("profileId", "test-rider") .put("rideStartedAt", System.currentTimeMillis() - 65000).put("savedAt", System.currentTimeMillis()) .put("routeId", "test-route").put("routeName", "Rolling Hills · device test").put("distance", "true".equals(InstrumentationRegistry.getArguments().getString("preview")) ? 12400 : 0) .put("recordDurationS", "true".equals(InstrumentationRegistry.getArguments().getString("preview")) ? 1458 : 0) .put("serverUrl", server.url("/ws").toString()).put("trainerKind", "trainer") .put("recorder", new JSObject().put("samples", new JSArray()).put("pauses", new JSArray())); ride.startRide(new JSObject().put("snapshot", snapshot).put("trainerId", "trainer") - .put("control", new JSObject().put("canControl", true).put("routeLengths", new JSObject().put("test-route", 1000))), value -> started.countDown(), reason -> { throw new AssertionError(reason); }); + .put("control", new JSObject().put("canControl", true).put("ratio", 1).put("referenceRatio", 1) + .put("routeLoops", new JSObject().put("test-route", true)).put("routeLengths", new JSObject().put("test-route", 1000))), value -> started.countDown(), reason -> { throw new AssertionError(reason); }); await(started, "Start native recorder"); ContextCompat.startForegroundService(context, new Intent(context, RideService.class)); FileObserver journal = new FileObserver(context.getFilesDir().getAbsolutePath(), FileObserver.MODIFY) { @@ -118,6 +126,7 @@ private static void shell(String command) throws Exception { shell("input keyevent 223"); await(measured, "Native telemetry must keep measured power with the screen off"); await(recorded, "Native journal must keep recording with the screen off"); + await(radio.drafted, "Background FTMS resistance must include the group draft across the loop start"); shell("input keyevent 224"); shell("wm dismiss-keyguard"); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = null; @@ -162,6 +171,7 @@ private static void shell(String command) throws Exception { ride.recover(value -> { JSObject saved = value.getJSObject("snapshot"); assertTrue(saved.optBoolean("finished")); + assertEquals("test-rider", saved.optString("profileId")); assertTrue(saved.getJSObject("recorder").optJSONArray("samples").length() >= 3); recovered.countDown(); }, reason -> { throw new AssertionError(reason); }); diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java index 419c2fd8..796db744 100644 --- a/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java @@ -4,10 +4,12 @@ import java.nio.ByteOrder; import java.util.HashMap; import java.util.Map; +import java.util.List; import java.util.function.Consumer; /** Clock/sensor/control logic; no Android, WebView, networking or file I/O. */ public final class RideEngine { + public record Rider(long id, String route, double distance, double lane) {} public record Sample(long t, double distance, double power, Double cadence, Double heartRate, double speed, String route, Double routeM) {} public record Command(Double power, double grade, double crr, double cw) { @@ -38,12 +40,15 @@ public static final class Control { private double speed, routeM; private String route; private boolean hasState; + private double dragFactor = 1; + private long draftAt = Long.MIN_VALUE / 2; private double grade, easedGrade; private boolean hasGrade; public double distance, durationS; public boolean paused, background; public Control control = new Control(); public final Map routeLengths = new HashMap<>(); + public final Map routeLoops = new HashMap<>(); public RideEngine(Consumer sink) { this.sink = sink; } @@ -128,6 +133,30 @@ public synchronized void state(String nextRoute, double metres, double nextSpeed } public synchronized void resetPosition() { hasState = false; } + /** Same nearest-rider, lane, loop and rounded saving rules as ride/draft.js. */ + public synchronized void draft(long riderId, List riders, long now) { + dragFactor = 1; draftAt = now; + Rider me = null; + for (Rider rider : riders) if (rider.id == riderId) { me = rider; break; } + if (me == null || me.route == null || !Double.isFinite(me.lane) || !Double.isFinite(me.distance)) return; + double nearest = Double.POSITIVE_INFINITY; + for (Rider other : riders) { + if (other.id == me.id || !me.route.equals(other.route) || !Double.isFinite(other.lane) + || !Double.isFinite(other.distance) || Math.abs(other.lane - me.lane) >= .5) continue; + double gap = other.distance - me.distance; + double length = routeLengths.getOrDefault(me.route, 0.0); + if (routeLoops.getOrDefault(me.route, false) && length > 0) { + gap = ((gap % length) + length) % length; + if (gap > length / 2) gap -= length; + } + if (gap > 0 && gap < nearest) nearest = gap; + } + if (nearest <= 6.5) { + double saving = Math.round(30 * (1 - (Math.max(nearest, 2) - 2) / 4.5)); + dragFactor = 1 - saving / 100; + } + } + public synchronized void tick(long wall, long now) { double dt = lastTick < 0 ? 0 : Math.max(0, now - lastTick) / 1000.0; lastTick = now; @@ -166,7 +195,8 @@ public synchronized Command command(long now) { if (c.ratio > 0 && c.referenceRatio > 0) { double theta = Math.atan(easedGrade / 100), weight = Math.max(1, c.mass) * 9.80665; double v = now - stateAt <= 2000 ? speed : 0; - double force = weight * (Math.sin(theta) + c.crr * Math.cos(theta)) + .5 * c.airDensity * c.cda * v * v; + double draft = now - draftAt <= 2000 ? dragFactor : 1; + double force = weight * (Math.sin(theta) + c.crr * Math.cos(theta)) + .5 * c.airDensity * c.cda * draft * v * v; double wanted = c.ratio / c.referenceRatio * Math.max(force, weight * .015); double sin = clamp(wanted / weight - c.crr, -.99, .99); road = clamp(Math.round(Math.tan(Math.asin(sin)) * 1000) / 10.0, -10, 20); diff --git a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java index 82eb2a51..60e91a6e 100644 --- a/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java @@ -155,6 +155,10 @@ private void configure(JSObject data) { String key = keys.next(); double length = lengths.optDouble(key, 0); if (length > 0 && Double.isFinite(length)) engine.routeLengths.put(key, length); } + JSONObject loops = data.optJSONObject("routeLoops"); + if (loops != null) for (Iterator keys = loops.keys(); keys.hasNext();) { + String key = keys.next(); engine.routeLoops.put(key, loops.optBoolean(key)); + } } private static double[][] segmentsOf(JSONArray segments) { List valid = new ArrayList<>(); @@ -379,6 +383,13 @@ private void handleServer(String text) { if (type.equals("resistance")) engine.resistance(message.optDouble("grade_percent", 0)); if (type.equals("state") || type.equals("studio_state")) { JSONArray riders = message.optJSONArray("riders"); + List drafting = new ArrayList<>(); + if (type.equals("state") && riders != null) for (int i = 0; i < riders.length(); i++) { + JSONObject rider = riders.optJSONObject(i); + if (rider != null && rider.isNull("studio")) drafting.add(new RideEngine.Rider(rider.optLong("id", -2), + rider.optString("route", null), rider.optDouble("distance", Double.NaN), rider.optDouble("lane", Double.NaN))); + } + engine.draft(riderId, drafting, SystemClock.elapsedRealtime()); if (riders != null) for (int i = 0; i < riders.length(); i++) { JSONObject rider = riders.optJSONObject(i); if (rider != null && rider.optLong("id", -2) == riderId) { diff --git a/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java b/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java index 0244a467..b473a42f 100644 --- a/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java +++ b/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java @@ -109,4 +109,45 @@ public class RideEngineTest { assertEquals(1, e.control.elapsed, 0.00001); assertEquals(1.5, e.command(1000).grade(), 0.00001); } + + private RideEngine draftingEngine() { + RideEngine e = new RideEngine(sample -> {}); + e.packet("trainer", "2ad2", "44001c0cb000d700", 0); + e.state("r", 100, 12, 0); e.resistance(0); + e.control.ratio = 1; e.control.referenceRatio = 1; + e.routeLengths.put("r", 1000.0); + return e; + } + @Test public void draftingMatchesTheSharedWebClientFixtures() throws Exception { + org.json.JSONObject fixture; + try (var input = getClass().getResourceAsStream("/native-drafting.json")) { + assertNotNull("Shared client/native drafting fixture", input); + fixture = new org.json.JSONObject(new String(input.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)); + } + var physics = fixture.getJSONObject("physics"); + var cases = fixture.getJSONArray("cases"); + for (int i = 0; i < cases.length(); i++) { + var row = cases.getJSONObject(i); var me = row.getJSONObject("me"); + RideEngine e = draftingEngine(); + e.control.mass = physics.getDouble("massKg"); e.control.cda = physics.getDouble("cda"); + e.control.crr = physics.getDouble("crr"); e.control.airDensity = physics.getDouble("airDensity"); + e.control.ratio = physics.getDouble("ratio"); e.control.referenceRatio = physics.getDouble("referenceRatio"); + e.routeLoops.put("r", row.getBoolean("loop")); + e.state("r", me.getDouble("distance"), physics.getDouble("speed"), 0); + java.util.List riders = new java.util.ArrayList<>(); + var positions = new org.json.JSONArray(row.getJSONArray("others").toString()).put(me); + for (int j = 0; j < positions.length(); j++) { + var rider = positions.getJSONObject(j); + riders.add(new RideEngine.Rider(rider.getLong("id"), rider.getString("route"), rider.getDouble("distance"), rider.getDouble("lane"))); + } + e.draft(me.getLong("id"), riders, 0); + assertEquals(row.getString("name"), row.getDouble("grade"), e.command(1000).grade(), 0); + } + } + @Test public void leavingTheGroupClearsThePreviousDraftSaving() { + RideEngine e = draftingEngine(); + e.draft(1, java.util.List.of(new RideEngine.Rider(1, "r", 100, 2), new RideEngine.Rider(2, "r", 102, 2)), 0); + e.draft(1, java.util.List.of(new RideEngine.Rider(1, "r", 100, 2)), 1000); + assertEquals(3.4, e.command(1000).grade(), 0); + } } diff --git a/client/public/js/main.js b/client/public/js/main.js index d51dc73b..065b1225 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -272,6 +272,8 @@ function buildRideWorld() { } const profiles = new ProfileStore(); +// Single-rider storage today; #115 supplies this accessor from its rider roster. +const activeRider = () => "main"; const deviceLog = new DeviceLog(deviceLogOptions(location.search)); /** Every open panel, so Esc closes the top one. */ const panels = createPanelStack(); @@ -3993,6 +3995,7 @@ function saveRide() { function rideSnapshot() { return { version: 1, + profileId: activeRider(), ...(app.nativeRideId && { nativeRideId: app.nativeRideId }), savedAt: Date.now(), serverUrl: defaultServerUrl(), @@ -4016,8 +4019,12 @@ async function refreshUnfinished() { const clearing = app.autosaveClearing; app.autosaveClearing = null; await clearing?.catch(() => {}); + const profileId = activeRider(); const saved = await app.autosave.load(); - app.unfinished = nativeRide && !nativeRide.active ? await nativeRide.recover(saved).catch(() => saved) : saved; + if (profileId !== activeRider()) return; + const recovered = nativeRide && !nativeRide.active ? await nativeRide.recover(saved, profileId).catch(() => saved) : saved; + if (profileId !== activeRider()) return; + app.unfinished = recovered; if (app.unfinished !== saved) await app.autosave.save(app.unfinished); renderUnfinished(); } diff --git a/client/public/js/native/backgroundRide.js b/client/public/js/native/backgroundRide.js index 71e2bd8f..e407a116 100644 --- a/client/public/js/native/backgroundRide.js +++ b/client/public/js/native/backgroundRide.js @@ -122,17 +122,19 @@ export class NativeRide { })().finally(() => { this.#stopping = null; this.#finishRequested = false; }); return this.#stopping; } - async recover(saved) { + async recover(saved, profileId = "main") { const { snapshot } = await this.#plugin.recover(); - return mergeNativeRecovery(saved, snapshot); + return mergeNativeRecovery(saved, snapshot, profileId); } clear() { return this.#plugin.clear(); } openSettings(kind) { return this.#plugin.openSettings({ kind }); } } /** Prefer the browser's enriched samples, but recover native-only seconds. */ -export function mergeNativeRecovery(saved, native) { +export function mergeNativeRecovery(saved, native, profileId = "main") { if (!native?.nativeRideId || !native.recorder) return saved; + // Unscoped journals predate rider profiles and belong to the original rider. + if ((native.profileId ?? "main") !== profileId || (saved?.profileId ?? profileId) !== profileId) return saved; if (saved && saved.nativeRideId !== native.nativeRideId) return saved; if (!saved) return native; const samples = new Map((native.recorder.samples ?? []).map((sample) => [sample.t, sample])); @@ -157,6 +159,7 @@ export function nativeControl({ profile, training, gearbox, routes = new Map(), mass: physics?.mass_kg ?? profile.weightKg + 9, cda: physics?.cda_m2 ?? .32, crr: physics?.crr ?? .004, airDensity: physics?.air_density ?? 1.225, routeLengths: Object.fromEntries([...routes].map(([id, route]) => [id, route.length])), + routeLoops: Object.fromEntries([...routes].map(([id, route]) => [id, Boolean(route.loop)])), paused, canControl, }; } diff --git a/client/test/fixtures/native-drafting.json b/client/test/fixtures/native-drafting.json new file mode 100644 index 00000000..5f43a4db --- /dev/null +++ b/client/test/fixtures/native-drafting.json @@ -0,0 +1,179 @@ +{ + "physics": { + "speed": 12, + "massKg": 85, + "cda": 0.32, + "crr": 0.004, + "airDensity": 1.225, + "ratio": 1, + "referenceRatio": 1 + }, + "cases": [ + { + "name": "full draft", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 100, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 102, + "lane": 2 + } + ], + "savingPercent": 30, + "grade": 2.4 + }, + { + "name": "partial draft", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 100, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 104.25, + "lane": 2 + } + ], + "savingPercent": 15, + "grade": 2.9 + }, + { + "name": "adjacent lane", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 100, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 102, + "lane": 2.5 + } + ], + "savingPercent": 0, + "grade": 3.4 + }, + { + "name": "different route", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 100, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "elsewhere", + "distance": 102, + "lane": 2 + } + ], + "savingPercent": 0, + "grade": 3.4 + }, + { + "name": "loop start line", + "loop": true, + "me": { + "id": 1, + "route": "r", + "distance": 999, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 1, + "lane": 2 + } + ], + "savingPercent": 30, + "grade": 2.4 + }, + { + "name": "open start line", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 999, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 1, + "lane": 2 + } + ], + "savingPercent": 0, + "grade": 3.4 + }, + { + "name": "rider behind", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 100, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 99, + "lane": 2 + } + ], + "savingPercent": 0, + "grade": 3.4 + }, + { + "name": "nearest leader wins", + "loop": false, + "me": { + "id": 1, + "route": "r", + "distance": 100, + "lane": 2 + }, + "others": [ + { + "id": 2, + "route": "r", + "distance": 106, + "lane": 2 + }, + { + "id": 3, + "route": "r", + "distance": 102, + "lane": 2 + } + ], + "savingPercent": 30, + "grade": 2.4 + } + ] +} diff --git a/client/test/nativeDraftParity.test.js b/client/test/nativeDraftParity.test.js new file mode 100644 index 00000000..cb4d9de2 --- /dev/null +++ b/client/test/nativeDraftParity.test.js @@ -0,0 +1,19 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { draftInfo } from "../public/js/ride/draft.js"; +import { effectiveGrade } from "../public/js/ride/virtualShifting.js"; +import { onRoute } from "../public/js/ride/roadRiders.js"; +import { RouteGeometry } from "../public/js/route/geometry.js"; + +// Android's RideEngineTest reads this same file as a JVM test resource. +const fixture = JSON.parse(readFileSync(new URL("./fixtures/native-drafting.json", import.meta.url), "utf8")); +for (const row of fixture.cases) { + test(`web/native drafting parity: ${row.name}`, () => { + const route = new RouteGeometry({ id: "r", loop: row.loop, points: [[0, 0, 0], [500, 0, 0], [0, 0, 0]] }); + const riders = [row.me, ...row.others].filter((rider) => onRoute(rider, route.id)); + const saving = draftInfo(row.me, riders, route)?.savingPercent ?? 0; + assert.equal(saving, row.savingPercent); + assert.equal(effectiveGrade({ ...fixture.physics, gradePercent: 0, dragFactor: 1 - saving / 100 }), row.grade); + }); +} diff --git a/client/test/nativeRide.test.js b/client/test/nativeRide.test.js index de4a5e83..a71b8f86 100644 --- a/client/test/nativeRide.test.js +++ b/client/test/nativeRide.test.js @@ -98,11 +98,12 @@ test("a journal from another ride never replaces an existing unfinished ride", ( test("background control includes the active workout and selected virtual gear", () => { const data = nativeControl({ profile: { ftp: 200, difficulty: .5, weightKg: 75, chainring: 40, cog: 20 }, training: { mode: "erg", intensity: 1.1, targetWatts: () => 220, player: { elapsedS: 42, workout: { segments: [{ durationS: 60, from: .5, to: 1 }] } } }, - gearbox: { ratio: 2 }, routes: new Map([["r", { length: 1000 }]]) }); + gearbox: { ratio: 2 }, routes: new Map([["r", { length: 1000, loop: true }]]) }); assert.equal(data.elapsed, 42); assert.equal(data.referenceRatio, 2); assert.equal(data.segments[0].durationS, 60); assert.deepEqual(data.routeLengths, { r: 1000 }); + assert.deepEqual(data.routeLoops, { r: true }); }); test("concurrent end requests stop the native recorder only once", async () => { @@ -153,3 +154,34 @@ test("finishing a native ride calls browser timer cancellation with its Window r await ride.stop(true); assert.equal(ride.active, false); }); + +test("a different rider cannot recover the shared journal into an empty autosave", () => { + const journal = { profileId: "alice", nativeRideId: "ride-a", recorder: { samples: [{ t: 1, power: 200 }] } }; + assert.equal(mergeNativeRecovery(null, journal, "bob"), null); +}); + +test("the journal owner can recover a ride without a browser autosave", () => { + const journal = { profileId: "alice", nativeRideId: "ride-a", recorder: { samples: [] } }; + assert.equal(mergeNativeRecovery(null, journal, "alice"), journal); +}); + +test("legacy unowned journals belong only to the original main rider", () => { + const journal = { nativeRideId: "legacy", recorder: { samples: [] } }; + assert.equal(mergeNativeRecovery(null, journal, "bob"), null); + assert.equal(mergeNativeRecovery(null, journal, "main"), journal); +}); + +test("matching ride ids cannot merge samples across profile owners", () => { + const saved = { profileId: "bob", nativeRideId: "ride", recorder: { samples: [{ t: 1 }] } }; + const journal = { profileId: "alice", nativeRideId: "ride", recorder: { samples: [{ t: 2 }] } }; + assert.equal(mergeNativeRecovery(saved, journal, "bob"), saved); +}); + +test("the native adapter checks the active rider before returning a journal", async () => { + const plugin = fakePlugin(); + const journal = { profileId: "alice", nativeRideId: "a", recorder: { samples: [] } }; + plugin.recover = async () => ({ snapshot: journal }); + const ride = new NativeRide({ plugin }); + assert.equal(await ride.recover(null, "bob"), null); + assert.equal(await ride.recover(null, "alice"), journal); +}); diff --git a/docs/app.md b/docs/app.md index 91feb0e2..cd0c0a08 100644 --- a/docs/app.md +++ b/docs/app.md @@ -85,7 +85,8 @@ service with its own sensor callbacks, WebSocket, telemetry clock and local journal. Switching to another app or locking the screen does not depend on WebView animation frames to keep power, cadence and recording going. Native reconnect restores the trainer/strap subscriptions and resumes the server rider -using the existing protocol token. Readings older than five seconds are not +using the existing protocol token. Virtual gears retain the web client's drafting +savings, including loop start-line gaps. Readings older than five seconds are not replayed as fresh power; a lost server connection does not invent distance. An ongoing notification shows the OpenRadlr emblem, live watts, distance and a @@ -99,7 +100,11 @@ leaves the game and releases trainer resistance; it never uploads a ride. The service runs only for a real-trainer ride. It stops its timer and wake lock when the ride ends. The native journal is private to the app and excluded from Android backups; it is reconciled with the usual unfinished-ride recovery on the -next launch. Force-stop, reboot or process termination stop live riding: recovery +next launch. Snapshots carry a local `profileId`; recovery accepts only the active +profile's journal. Older unscoped journals belong to the original `main` rider. +The composition root currently exposes that single rider; #115 must use its +roster-backed `activeRider()` accessor for both snapshot and recovery ownership. +Force-stop, reboot or process termination stop live riding: recovery preserves completed samples without pretending the ride kept running. Background support here is Android-specific; iOS keeps the limitations below.