diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 593964d6..0d0985d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,29 @@ 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* + - 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 + image: name: Docker image runs-on: ubuntu-latest diff --git a/AGENTS.md b/AGENTS.md index 48b2322a..5609d531 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ repeat it. Here is the operational knowledge on top of that. - **Protocol changes:** update `docs/protocol.md`, both sides, bump `PROTOCOL_VERSION` for breaking changes. - **Structural decisions:** add an ADR to `docs/adr/` (NNNN-short-name.md; - context, decision, consequences). There are 28 so far. + context, decision, consequences). There are 29 so far. - **Feature design:** significant features go through the superpowers workflow — a design spec and an implementation plan in `docs/superpowers/{specs,plans}/` (see the 2026-10-19 examples). Follow that pattern for new features. diff --git a/app/android/app/build.gradle b/app/android/app/build.gradle index 8e2f854e..30c8116a 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,19 @@ android { proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } + 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. +// 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{ @@ -65,10 +82,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..330a2bfd --- /dev/null +++ b/app/android/app/src/androidTest/java/com/openradlr/app/ride/BackgroundRideTest.java @@ -0,0 +1,190 @@ +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<>(); + 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) { + // 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")); } + } + 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 = 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) { + 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(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); } + } + })); + 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"); + 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("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("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) { + @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"); + 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; + 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 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"); + 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); }); + 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..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 @@ -13,7 +13,9 @@ 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(); + 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/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..796db744 --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideEngine.java @@ -0,0 +1,210 @@ +package com.openradlr.app.ride; + +import java.nio.ByteBuffer; +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) { + 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 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; } + + /** 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; } + + /** 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; + 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 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); + 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..60e91a6e --- /dev/null +++ b/app/android/app/src/main/java/com/openradlr/app/ride/RideService.java @@ -0,0 +1,482 @@ +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 classSegments = new HashMap<>(); + 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(() -> { + boolean wasBackground = background; + 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).put("resumed", wasBackground)); + } + }); + } + + /** 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); + 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")); + 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); + } + 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<>(); + 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); + 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(() -> { + 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) { + 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("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(() -> { + 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("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"); + 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) { + 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 00000000..54522f4c Binary files /dev/null and b/app/android/app/src/main/res/drawable-nodpi/notification_brand.png differ 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/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/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..b473a42f --- /dev/null +++ b/app/android/app/src/test/java/com/openradlr/app/ride/RideEngineTest.java @@ -0,0 +1,153 @@ +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); + } + + 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/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 4e6d4e9a..c85165b0 100644 --- a/client/public/index.html +++ b/client/public/index.html @@ -32,6 +32,7 @@ + @@ -397,6 +398,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 f4be6aa7..7de147b6 100644 --- a/client/public/js/i18n/de.js +++ b/client/public/js/i18n/de.js @@ -796,6 +796,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 56fe8e27..5c202006 100644 --- a/client/public/js/i18n/en.js +++ b/client/public/js/i18n/en.js @@ -796,6 +796,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 144a92ae..50c4d812 100644 --- a/client/public/js/main.js +++ b/client/public/js/main.js @@ -3,12 +3,13 @@ * 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 { renderAndroidAppLink, renderExternalLink } from "./view/externalLink.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"; @@ -132,6 +133,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)); } @@ -291,6 +294,7 @@ const activeRider = () => riders.active; const riderStore = riderStorage(rawStorage, activeRider); const profiles = new ProfileStore({ storage: riderStore }); + const deviceLog = new DeviceLog(deviceLogOptions(location.search)); /** Every open panel, so Esc closes the top one. */ const panels = createPanelStack(); @@ -1342,7 +1346,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; } @@ -1442,6 +1446,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); @@ -1972,7 +1984,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); @@ -2024,7 +2036,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. */ @@ -2052,7 +2064,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" }); @@ -2083,6 +2095,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(); @@ -2237,6 +2255,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); @@ -2311,7 +2330,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); @@ -2371,6 +2390,7 @@ function startRide() { app.recorder = new RideRecorder(); if (app.restored) restoreRide(app.restored); + await startNativeRide(); startSplits(); initFinish(); initAfkPrompt(); @@ -2390,6 +2410,51 @@ 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; + } + 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"); }, + }); + 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()); @@ -2780,6 +2845,7 @@ function updateStudioPanels() { } function studioFrame() { + if (nativeRide?.active && app.nativeSyncing) return; const studio = app.studio; if (!studio.state) return; const time = now(); @@ -2842,7 +2908,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; } @@ -3713,11 +3779,16 @@ 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. - // The clear must hit the autosave of the rider who finished, not whoever is active by then (#115). + // Pin cleanup to the rider who left, and start stopping before another ride can start. if (!recoverable) { const autosave = app.autosave; - app.autosaveClearing = Promise.resolve(app.finishSave).then(() => autosave.clear()); + const stopped = nativeRide?.stop(false); + app.autosaveClearing = Promise.all([app.finishSave, stopped]).then(async () => { + await nativeRide?.clear(); + await autosave.clear(); + }); } + endRide(); return true; } @@ -3806,6 +3877,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; @@ -4022,7 +4099,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({ @@ -4163,6 +4240,8 @@ function saveRide() { function rideSnapshot() { return { version: 1, + profileId: activeRider(), + ...(app.nativeRideId && { nativeRideId: app.nativeRideId }), savedAt: Date.now(), serverUrl: defaultServerUrl(), routeId: app.route.id, @@ -4170,6 +4249,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, @@ -4185,9 +4265,16 @@ async function refreshUnfinished() { app.autosaveClearing = null; await clearing?.catch(() => {}); const generation = app.riderGeneration; - const saved = await app.autosave.load(); + const profileId = activeRider(); + const autosave = app.autosave; + const saved = await autosave.load(); + if (generation !== app.riderGeneration) return; + const recovered = nativeRide && !nativeRide.active ? await nativeRide.recover(saved, profileId).catch(() => saved) : saved; + if (generation !== app.riderGeneration) return; + app.unfinished = recovered; + if (recovered !== saved) await autosave.save(recovered); if (generation !== app.riderGeneration) return; - app.unfinished = saved; + renderUnfinished(); } @@ -4204,6 +4291,7 @@ async function discardUnfinished() { app.recoveryUpload?.dispose(); app.recoveryUpload = null; await app.autosave.clear(); + await nativeRide?.clear(); app.unfinished = null; renderUnfinished(); } @@ -4217,7 +4305,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) { app.nativeSyncing = true; nativeRide.flush().catch((error) => { app.nativeSyncing = false; console.warn(error); }); } + return; + } + if (nativeRide?.active) { app.nativeWasHidden = true; app.nativeSyncing = true; } saveRide(); saveWorkoutRecord(); }); @@ -5493,7 +5585,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); @@ -5577,7 +5669,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..e407a116 --- /dev/null +++ b/client/public/js/native/backgroundRide.js @@ -0,0 +1,172 @@ +/** 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 = (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") { + 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); + 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, profileId = "main") { + const { snapshot } = await this.#plugin.recover(); + 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, 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])); + 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), + 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, + routeLengths: Object.fromEntries([...routes].map(([id, route]) => [id, route.length])), + routeLoops: Object.fromEntries([...routes].map(([id, route]) => [id, Boolean(route.loop)])), + 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/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/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/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 new file mode 100644 index 00000000..a71b8f86 --- /dev/null +++ b/client/test/nativeRide.test.js @@ -0,0 +1,187 @@ +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, 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 () => { + 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); +}); + +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]); +}); + +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 }]); +}); + +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); +}); + +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/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/0029-android-ride-service.md b/docs/adr/0029-android-ride-service.md new file mode 100644 index 00000000..ad966b28 --- /dev/null +++ b/docs/adr/0029-android-ride-service.md @@ -0,0 +1,24 @@ +# 0029 — 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 79583cf6..a9474b5c 100644 --- a/docs/app.md +++ b/docs/app.md @@ -78,6 +78,86 @@ 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. 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 +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. Snapshots carry a local `profileId`; recovery accepts only the active +profile's journal. Older unscoped journals belong to the original `main` rider. +Snapshot creation and recovery use the active local rider roster. Recovery reads +are discarded if the rider generation changes while they are pending. +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. + +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 +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 @@ -259,17 +339,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..6f83b866 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-android-background-riding.md @@ -0,0 +1,14 @@ +# Android background riding implementation plan + +Spec: `../specs/2026-11-16-android-background-riding-design.md`. + +- [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. 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.