Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ The beta is live on Google Play (closed testing) — no sideloading needed. Goog
## Features

- **5-minute (RRS 26) and 3-minute start sequences**
- **Sync to nearest minute** — tap SYNC at any gun to correct the countdown (3:22 → 3:00, 3:40 → 4:00)
- **Sync to nearest minute** — tap SYNC at any gun to correct the countdown (3:22 → 3:00, 3:40 → 4:00), or turn the crown when the glass is wet
- **Automatic count-up** after the start for elapsed race time
- **Haptic signals**: double buzz at 4:00 (prep), long buzz at 1:00, ticks through the final 10 seconds, gun blast at 0:00
- **Screen never leaves the app** while armed or counting down; count-up dims to an always-on ambient display
- **Wet-proof**: countdown, display, and haptics keep running even when water forces the watch into ambient mode; huge half-screen touch targets; long-press-guarded reset so splashes can't kill your sequence
- **Wet-proof**: countdown, display, and haptics keep running even when water forces the watch into ambient mode; huge half-screen touch targets; spray is filtered out by contact size, and the crown syncs when you don't trust the screen at all; long-press-guarded reset
- **Quick-launch tile**: swipe from the watch face, tap 5 min or 3 min, and the timer opens pre-armed
- **Watch-face complication**: weather-style ring where the dot is time remaining, ticking countdown in the center — one tap starts the last-used sequence right from the face
- **Survives interruptions**: an in-flight countdown or race is restored at the correct time even if the app is closed — or the watch reboots
Expand Down Expand Up @@ -88,6 +88,8 @@ Needs Wear OS 5+ (minSdk 34). `adb` ships with [Android platform-tools](https://

Requires JDK 17+ and the Android SDK (compileSdk 37). Release signing reads `keystore.properties` at the repo root (gitignored); CI restores it from the `KEYSTORE_B64` / `KEYSTORE_PASSWORD` secrets.

Debug builds use the applicationId `com.johnhringiv.regattatimer.debug`, so a dev build installs alongside a Play Store copy on the same watch instead of colliding with its signature.

After cloning, enable the repo hooks (auto-formats Markdown with Prettier on commit; CI enforces):

```
Expand Down
9 changes: 7 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ android {
targetSdk = 36
// versionCode bumps on every feature-branch change (CI-enforced > main).
// versionName bumps once per PR to main (CI-enforced).
versionCode = 19
versionName = "0.7"
versionCode = 21
versionName = "0.8"
}

signingConfigs {
Expand All @@ -37,6 +37,11 @@ android {
}

buildTypes {
debug {
// Distinct applicationId so a dev build can sit alongside the Play Store install on a
// real watch — signatures differ, so without this the two cannot coexist.
applicationIdSuffix = ".debug"
}
release {
isMinifyEnabled = true
isShrinkResources = true
Expand Down
10 changes: 10 additions & 0 deletions app/src/debug/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Debug builds carry a distinct name so a dev build can never be mistaken for the Play Store
install sitting alongside it (see applicationIdSuffix in app/build.gradle.kts). The launcher
entry, the tile and the complication all label from @string/app_name, so overriding it here
renames all three at once.
-->
<resources>
<string name="app_name">RT DEBUG</string>
</resources>
44 changes: 44 additions & 0 deletions app/src/main/java/com/johnhringiv/regattatimer/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package com.johnhringiv.regattatimer

import android.content.Intent
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.MotionEvent
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
Expand All @@ -21,10 +24,17 @@ const val EXTRA_MODE = "mode"
/** Intent extra (set by the complication) to start the sequence immediately on launch. */
const val EXTRA_AUTO_START = "auto_start"

private const val TAG = "RegattaTimer"

class MainActivity : ComponentActivity() {

private val viewModel: TimerViewModel by viewModels()

// TEMPORARY: contact characterisation. Feeds the touch-guard calibration logging in
// dispatchTouchEvent - remove along with it once the thresholds are settled.
private var contactDownMs = 0L
private var contactPeakMajor = 0f

private var isAmbient by mutableStateOf(false)
private var ambientTick by mutableIntStateOf(0)

Expand Down Expand Up @@ -78,12 +88,46 @@ class MainActivity : ComponentActivity() {
onToggleMode = viewModel::toggleMode,
onStart = viewModel::start,
onSync = viewModel::sync,
// The crown is water-immune, so a rotary sync skips the contact-size guard.
onCrownSync = { viewModel.sync(fromTouch = false) },
onReset = viewModel::reset,
onAnyTap = viewModel::noteInteraction,
)
}
}

/**
* Records the contact size of every touch-down before Compose routes it, so the sync and
* mode-toggle guards can tell a fingertip from water. Taken here rather than in a pointer
* modifier because Compose's PointerInputChange doesn't carry touch-major, and dispatch order
* here is unambiguous. Never consumes the event — the guards decide, not this.
*/
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (ev.pointerCount > 0) {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
viewModel.noteContactSize(ev.getTouchMajor(0))
contactDownMs = SystemClock.elapsedRealtime()
contactPeakMajor = ev.getTouchMajor(0)
Log.d(TAG, "down major=${ev.getTouchMajor(0)}")
}
// Peak, not the down value: a contact grows as it settles, and the peak is what
// separates a fingertip from water.
MotionEvent.ACTION_MOVE -> {
contactPeakMajor = maxOf(contactPeakMajor, ev.getTouchMajor(0))
viewModel.noteContactPeak(ev.getTouchMajor(0))
}

MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
val heldMs = SystemClock.elapsedRealtime() - contactDownMs
val cancelled = ev.actionMasked == MotionEvent.ACTION_CANCEL
Log.d(TAG, "up peak=$contactPeakMajor heldMs=$heldMs cancelled=$cancelled")
}
}
}
return super.dispatchTouchEvent(ev)
}

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
armModeFromIntent(intent)
Expand Down
99 changes: 99 additions & 0 deletions app/src/main/java/com/johnhringiv/regattatimer/TimerLogic.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,107 @@ sealed interface TimerState {
fun syncRemaining(remainingMs: Long): Long =
((remainingMs + 30_000L) / 60_000L) * 60_000L

/**
* Whole seconds to show for a countdown, derived ONLY from the anchor and the instant
* being rendered. Ceil, so 5:00 shows for the whole first second.
*
* Every surface must call this with the current [now]; caching the result and redrawing
* it later shows a stale time (the display lags by exactly the redraw gap). That matters
* in ambient, where redraws are throttled to roughly once a minute.
*/
fun countdownSecondsAt(deadline: Long, now: Long): Long {
val remaining = deadline - now
return if (remaining <= 0L) 0L else (remaining + 999L) / 1000L
}

/** Whole seconds elapsed since the gun, derived only from the anchor and [now]. */
fun elapsedSecondsAt(zero: Long, now: Long): Long = (now - zero).coerceAtLeast(0L) / 1000L

/**
* Smallest contact the timer will accept as a deliberate fingertip, in MotionEvent
* touch-major units.
*
* Calibrated on a Pixel Watch 3 (NVTCapacitiveTouchScreen, ABS_MT_TOUCH_MAJOR 0..255,
* touch.size.calibration=GEOMETRIC). MotionEvent.getTouchMajor() reports on the same 0..255
* scale as the raw axis — getSize() is exactly touchMajor/255 — and values are quantised at
* raw * 0.997555, so raw 12 arrives as 11.97.
*
* Judged on the TOUCH-DOWN value: a tap lands firm, so its first sample is representative, and
* the down value is the conservative reading against water contacts that grow after landing.
* Measured touch-down values on-watch:
*
* water 2, 3.99, 4.99, 6.98, 8.98, 9.98 then 13.97 for a heavy direct drip
* real tap 10.97, 11.97, 12.97 ... 18.95 and 8.98 for a deliberately light tap
*
* The populations overlap: a light tap can land at 8.98, exactly where droplets land. Measured on
* a dry finger, 2 of 8 deliberately-light taps fell below this floor and were refused. That cost
* is deliberate — a refused tap is visible and repeatable, an accepted droplet is neither.
*
* Water reads SMALLER than skin, so the guard is a floor. 10.0 looks a hair above the largest
* water reading (9.98) but the margin is safe: values quantise at raw * 0.997555, so raw 10
* arrives as 9.97555 and raw 11 as 10.973105 — nothing can land in between. 10.0 therefore
* cleanly means "raw 11 or greater".
*
* An earlier 11.5 refused a third of genuine taps — twice in a row at 10.97 — while rejecting
* exactly the same water, since the heavy drip at 13.97 defeats both. Lowering it costs no
* water rejection at all.
*
* The heavy-drip case is unsolved and unsolvable by contact size alone: water poured straight
* onto the glass reads identically to a fingertip. The crown is the guaranteed path.
*
* Why it matters: a droplet running across the glass registers as a tap, and the top half of
* a live countdown is SYNC — one stray contact silently moves the gun by up to 30s.
*/
const val FINGER_CONTACT_FLOOR = 10.0f

/**
* Floor for the long-press reset, judged on the gesture's PEAK contact rather than its touch-down
* value (a press lands soft and spreads — see the peak tracking in TimerViewModel).
*
* Lower than [FINGER_CONTACT_FLOOR] because presses and taps have different profiles. Measured
* peaks on-watch:
*
* water 2.99, 6.98, 7.98, 8.98, 9.98 then 12.97, 14.96 for heavy direct drips
* real press 10.97, 12.97, 16.96
*
* 11.5 refused half of all genuine resets, including one held for 1204ms that peaked at 10.97.
* 10.5 sits in the empty band between 9.98 and 10.97, so it admits those presses while rejecting
* exactly the same water as 11.5 did — the heavy drips at 12.97+ defeat both, so nothing is given
* up. Strictly better, not a loosening.
*/
const val RESET_CONTACT_FLOOR = 10.5f

/**
* Whether [touchMajor] is plausibly a fingertip rather than water.
*
* Fails OPEN: a non-positive value means the device does not report contact size (the axis is
* device-specific and this app ships to Wear OS 5+ generally), and an unmeasured watch must
* behave exactly as it did before rather than refuse a real sync at the gun.
*/
fun isFingerContact(touchMajor: Float, floor: Float = FINGER_CONTACT_FLOOR): Boolean =
touchMajor <= 0f || touchMajor >= floor

fun formatMmSs(totalSeconds: Long): String {
val m = totalSeconds / 60
val s = totalSeconds % 60
return String.format(Locale.ROOT, "%d:%02d", m, s)
}

/**
* Elapsed race time for the count-up display.
*
* Under an hour this is plain M:SS — identical to the countdown, so the digits do not change shape
* at the gun, which is the moment a sailor is least able to reread the screen. Past an hour it
* rolls into H:MM:SS instead of letting the minute field grow without bound.
*
* Unbounded minutes was not hypothetical. Nothing ends a race, so a timer left running after one
* reached "1022:47" on-watch: too wide for the display, so it wrapped onto a second line and shoved
* the RACE label off the screen entirely. [com.johnhringiv.regattatimer.ui] shrinks the type for
* these longer strings; this function keeps them as short as they can honestly be.
*/
fun formatElapsed(totalSeconds: Long): String {
val total = totalSeconds.coerceAtLeast(0L)
val hours = total / 3600
if (hours == 0L) return formatMmSs(total)
return String.format(Locale.ROOT, "%d:%02d:%02d", hours, (total % 3600) / 60, total % 60)
}
65 changes: 62 additions & 3 deletions app/src/main/java/com/johnhringiv/regattatimer/TimerViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.app.Application
import android.content.Context
import android.os.PowerManager
import android.os.SystemClock
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Job
Expand Down Expand Up @@ -34,6 +35,51 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) {
private var idleGuard: Job? = null
private var inAmbient = false

/**
* Contact size of the most recent touch-down, in MotionEvent touch-major units, recorded by
* MainActivity.dispatchTouchEvent before Compose sees the event. 0 = device doesn't report it.
*/
private var lastContactSize = 0f

/** Peak contact size seen during the current gesture. See [noteContactPeak]. */
private var lastContactPeak = 0f

/** Records the contact size of a touch-down so the sync/toggle guards can consult it. */
fun noteContactSize(touchMajor: Float) {
lastContactSize = touchMajor
lastContactPeak = touchMajor
}

/**
* Records the largest contact seen so far in this gesture.
*
* A quick tap lands firm, so its touch-down value is representative. A deliberate PRESS lands
* soft and spreads as the finger flattens — measured on-watch as down=7.98 growing to
* peak=14.96 over a 1676ms hold. Judging a long-press by its touch-down value therefore
* rejects real presses, which is why reset consults the peak instead.
*/
fun noteContactPeak(touchMajor: Float) {
lastContactPeak = maxOf(lastContactPeak, touchMajor)
}

/**
* Whether the last touch-down was a fingertip rather than water. Rejections are silent — no
* haptic — because a buzz would tell the sailor something happened when nothing did.
*
* Logged either way at DEBUG so the floor can be refined from real sailing data rather than
* the small lab sample it was derived from.
*/
private fun acceptTouch(
action: String,
usePeak: Boolean = false,
floor: Float = FINGER_CONTACT_FLOOR,
): Boolean {
val contact = if (usePeak) lastContactPeak else lastContactSize
val ok = isFingerContact(contact, floor)
Log.d(TAG, "$action contact=$contact peak=$usePeak accepted=$ok floor=$floor")
return ok
}

// Water on the screen triggers the palm gesture and forces ambient mode; a partial
// wake lock keeps the ticker (display + haptic cues) running through the countdown.
private val powerManager = app.getSystemService(Context.POWER_SERVICE) as PowerManager
Expand Down Expand Up @@ -134,6 +180,8 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) {

fun toggleMode() {
val st = _state.value
// Armed, a stray contact silently swaps a 5-minute RRS 26 start for a 3-minute club one.
if (!acceptTouch("toggleMode")) return
if (st is TimerState.Idle) {
val next = st.mode.other()
_state.value = TimerState.Idle(next)
Expand Down Expand Up @@ -161,9 +209,15 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) {
}
}

/** Round the remaining time to the nearest whole minute (correct on the next gun). */
fun sync() {
/**
* Round the remaining time to the nearest whole minute (correct on the next gun).
*
* [fromTouch] false bypasses the contact-size guard — the crown is water-immune, so a rotary
* sync is always deliberate and must never be second-guessed.
*/
fun sync(fromTouch: Boolean = true) {
val st = _state.value
if (fromTouch && !acceptTouch("sync")) return
if (st is TimerState.Countdown) {
val now = SystemClock.elapsedRealtime()
val newRemaining = syncRemaining(st.deadline - now)
Expand All @@ -184,6 +238,10 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) {

fun reset() {
val st = _state.value
// Water held on the glass long enough to trip the long-press and wiped a live countdown
// on-watch, so reset is guarded too. Judged on the PEAK, not the touch-down value: a
// deliberate press lands soft and spreads, so the down value rejects real presses.
if (!acceptTouch("reset", usePeak = true, floor = RESET_CONTACT_FLOOR)) return
if (st !is TimerState.Idle) {
_state.value = TimerState.Idle(st.mode)
_displaySeconds.value = st.mode.durationSeconds
Expand Down Expand Up @@ -246,7 +304,7 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) {
lastShown = -1L
continue
}
val sec = (remaining + 999) / 1000 // ceil: shows 5:00 for the first second
val sec = countdownSecondsAt(st.deadline, now) // ceil: 5:00 for the first second
if (sec != lastShown) {
if (lastShown != -1L) countdownCue(sec, st.mode)
lastShown = sec
Expand All @@ -271,6 +329,7 @@ class TimerViewModel(app: Application) : AndroidViewModel(app) {
private companion object {
const val IDLE_SCREEN_HOLD_MS = 10 * 60_000L
const val GUN_LATENESS_MS = 2_000L
const val TAG = "RegattaTimer"
}

// LAST in the class: init runs in declaration order, and restoring a race touches
Expand Down
Loading