mirror of
https://github.com/kuhyx/screen-locker.git
synced 2026-11-18 22:34:25 +01:00
Persist and bridge GPS runs across death
Checkpoint codec and file store, gap bridging at 2:30-12:00 min/km, watchdog (suggest finish, 5 h auto end), recorder restore. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWW75Epgijvt2eJ1ErR
This commit is contained in:
parent
bdf79ca6be
commit
d45e67a02c
@ -54,6 +54,20 @@ enum RunSource {
|
||||
values.firstWhere((s) => s.storageKey == key);
|
||||
}
|
||||
|
||||
/// How a [RunPoint] joins the one before it.
|
||||
enum RunLink {
|
||||
/// Reached in the normal flow of fixes.
|
||||
continuous,
|
||||
|
||||
/// A new segment: after a pause (or a GPS jump re-anchor). The line from
|
||||
/// the previous point is not drawn and credits nothing.
|
||||
segmentStart,
|
||||
|
||||
/// Reached across a gap (phone dead, GPS lost): a straight line from the
|
||||
/// previous point, drawn always, credited only at a running pace.
|
||||
bridge,
|
||||
}
|
||||
|
||||
/// One accepted GPS fix.
|
||||
@immutable
|
||||
class RunPoint {
|
||||
@ -64,6 +78,7 @@ class RunPoint {
|
||||
required this.longitude,
|
||||
required this.distanceM,
|
||||
this.altitudeM,
|
||||
this.link = RunLink.continuous,
|
||||
}) : time = time.toUtc();
|
||||
|
||||
/// When the fix was taken (UTC).
|
||||
@ -84,9 +99,13 @@ class RunPoint {
|
||||
/// values, so this is the field the recorder must keep honest.
|
||||
final double distanceM;
|
||||
|
||||
/// How this point joins the previous one.
|
||||
final RunLink link;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is RunPoint &&
|
||||
other.link == link &&
|
||||
other.time == time &&
|
||||
other.latitude == latitude &&
|
||||
other.longitude == longitude &&
|
||||
@ -95,7 +114,7 @@ class RunPoint {
|
||||
|
||||
@override
|
||||
int get hashCode =>
|
||||
Object.hash(time, latitude, longitude, altitudeM, distanceM);
|
||||
Object.hash(time, latitude, longitude, altitudeM, distanceM, link);
|
||||
}
|
||||
|
||||
/// A finished (or in-progress) track.
|
||||
|
||||
@ -3,6 +3,7 @@ library;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/run_gap_bridge.dart';
|
||||
import 'package:workout_app/services/run_math.dart';
|
||||
|
||||
/// Worst horizontal accuracy (metres, 68 % radius) a fix may report.
|
||||
@ -65,14 +66,24 @@ enum FixVerdict {
|
||||
/// Accumulates accepted points and their cumulative credited distance.
|
||||
///
|
||||
/// A step between two accepted points adds distance only when it is a moving
|
||||
/// step (see [isMovingStep]): a dropout longer than [kMaxCreditGapSeconds]
|
||||
/// and standing-still jitter credit nothing. The PC judges windows of 10 s or
|
||||
/// more and keeps a dropout moving at 1 m/s or faster, so it can credit more
|
||||
/// than this does (see `run_math.dart`).
|
||||
/// step (see [isMovingStep]): standing-still jitter credits nothing. A gap
|
||||
/// over [kMaxCreditGapSeconds] (phone dead, GPS dropout) is bridged by a
|
||||
/// straight line, always kept, credited only at a plausible pace
|
||||
/// ([bridgeCredits]); the jump cap does not apply across it.
|
||||
class GpsFilter {
|
||||
/// Creates a filter; every recording uses the running jump cap.
|
||||
GpsFilter();
|
||||
|
||||
/// Rebuilds a filter from a checkpoint: the [points] so far, whether a
|
||||
/// pause is still waiting for its next fix, and the jump count.
|
||||
GpsFilter.restore({
|
||||
required List<RunPoint> points,
|
||||
this._segmentBreak = false,
|
||||
this._jumps = 0,
|
||||
}) {
|
||||
_points.addAll(points);
|
||||
}
|
||||
|
||||
final List<RunPoint> _points = [];
|
||||
int _jumps = 0;
|
||||
bool _segmentBreak = false;
|
||||
@ -80,6 +91,12 @@ class GpsFilter {
|
||||
/// Accepted points so far, in time order.
|
||||
List<RunPoint> get points => List.unmodifiable(_points);
|
||||
|
||||
/// Whether the next accepted fix starts a new segment (a pause is open).
|
||||
bool get segmentBreak => _segmentBreak;
|
||||
|
||||
/// Consecutive too-fast fixes seen since the last accepted one.
|
||||
int get jumps => _jumps;
|
||||
|
||||
/// Cumulative credited distance in metres.
|
||||
double get distanceM => _points.isEmpty ? 0 : _points.last.distanceM;
|
||||
|
||||
@ -103,7 +120,7 @@ class GpsFilter {
|
||||
isUtc: true,
|
||||
);
|
||||
if (_points.isEmpty) {
|
||||
_accept(fix, time, 0);
|
||||
_accept(fix, time, 0, RunLink.continuous);
|
||||
return FixVerdict.accepted;
|
||||
}
|
||||
final last = _points.last;
|
||||
@ -111,7 +128,7 @@ class GpsFilter {
|
||||
if (gap <= 0) return FixVerdict.outOfOrder;
|
||||
if (_segmentBreak) {
|
||||
_segmentBreak = false;
|
||||
_accept(fix, time, 0);
|
||||
_accept(fix, time, 0, RunLink.segmentStart);
|
||||
return FixVerdict.accepted;
|
||||
}
|
||||
final step = haversineM(
|
||||
@ -120,20 +137,24 @@ class GpsFilter {
|
||||
fix.latitude,
|
||||
fix.longitude,
|
||||
);
|
||||
if (gap > kMaxCreditGapSeconds) {
|
||||
final credited = bridgeCredits(stepM: step, gapSeconds: gap);
|
||||
_accept(fix, time, credited ? step : 0, RunLink.bridge);
|
||||
return FixVerdict.accepted;
|
||||
}
|
||||
if (step / gap > kRunningMaxSpeedMps) {
|
||||
_jumps++;
|
||||
if (_jumps < kMaxConsecutiveJumps) return FixVerdict.tooFast;
|
||||
// The anchor, not the fixes, was wrong: continue from here, no credit.
|
||||
_accept(fix, time, 0);
|
||||
_accept(fix, time, 0, RunLink.segmentStart);
|
||||
return FixVerdict.accepted;
|
||||
}
|
||||
final moving =
|
||||
gap <= kMaxCreditGapSeconds && step / gap >= kMinMovingSpeedMps;
|
||||
_accept(fix, time, moving ? step : 0);
|
||||
final moving = step / gap >= kMinMovingSpeedMps;
|
||||
_accept(fix, time, moving ? step : 0, RunLink.continuous);
|
||||
return FixVerdict.accepted;
|
||||
}
|
||||
|
||||
void _accept(GpsFix fix, DateTime time, double credited) {
|
||||
void _accept(GpsFix fix, DateTime time, double credited, RunLink link) {
|
||||
_jumps = 0;
|
||||
_points.add(
|
||||
RunPoint(
|
||||
@ -142,6 +163,7 @@ class GpsFilter {
|
||||
longitude: fix.longitude,
|
||||
altitudeM: fix.altitudeM,
|
||||
distanceM: distanceM + credited,
|
||||
link: link,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -0,0 +1,168 @@
|
||||
/// Everything needed to rebuild a [RunRecorder] after the process died.
|
||||
///
|
||||
/// The recorder offers one after every accepted fix and on pause or resume;
|
||||
/// the host stores it (see `run_checkpoint_store.dart`). The JSON is versioned
|
||||
/// and strict: [RunCheckpoint.fromJson] throws a [FormatException] on anything
|
||||
/// it does not understand, so a damaged file is reported, never half-read.
|
||||
library;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/run_phase.dart';
|
||||
|
||||
/// The JSON layout version written by [RunCheckpoint.toJson].
|
||||
const int kCheckpointVersion = 1;
|
||||
|
||||
/// A snapshot of an active run: recording or paused.
|
||||
@immutable
|
||||
class RunCheckpoint {
|
||||
/// Creates a checkpoint; times are normalised to UTC.
|
||||
RunCheckpoint({
|
||||
required DateTime startedAt,
|
||||
required DateTime savedAt,
|
||||
required this.phase,
|
||||
required this.points,
|
||||
required this.movingSeconds,
|
||||
required this.distanceM,
|
||||
required this.km,
|
||||
required this.segmentBreak,
|
||||
required this.jumps,
|
||||
this.paceTargetSeconds,
|
||||
}) : startedAt = startedAt.toUtc(),
|
||||
savedAt = savedAt.toUtc();
|
||||
|
||||
/// Reads a checkpoint written by [toJson]; throws [FormatException] when
|
||||
/// [json] is of another version, is missing a field or has a wrong type.
|
||||
factory RunCheckpoint.fromJson(Map<String, Object?> json) {
|
||||
if (json['v'] != kCheckpointVersion) {
|
||||
throw FormatException('unsupported checkpoint version ${json['v']}');
|
||||
}
|
||||
final phase = RunPhase.values.asNameMap()[_field<String>(json, 'phase')];
|
||||
if (phase != RunPhase.recording && phase != RunPhase.paused) {
|
||||
throw FormatException('checkpoint phase ${json['phase']} is not active');
|
||||
}
|
||||
return RunCheckpoint(
|
||||
startedAt: _time(json, 'startedAt'),
|
||||
savedAt: _time(json, 'savedAt'),
|
||||
phase: phase!,
|
||||
points: [
|
||||
for (final p in _field<List<Object?>>(json, 'points')) _point(p),
|
||||
],
|
||||
movingSeconds: _field<int>(json, 'moving'),
|
||||
distanceM: _field<num>(json, 'distance').toDouble(),
|
||||
km: _field<int>(json, 'km'),
|
||||
segmentBreak: _field<bool>(json, 'segBreak'),
|
||||
jumps: _field<int>(json, 'jumps'),
|
||||
paceTargetSeconds: _optional<int>(json, 'target'),
|
||||
);
|
||||
}
|
||||
|
||||
/// When the run began (wall clock, UTC); the auto-end is measured from it.
|
||||
final DateTime startedAt;
|
||||
|
||||
/// When this snapshot was taken (UTC).
|
||||
final DateTime savedAt;
|
||||
|
||||
/// Recording or paused.
|
||||
final RunPhase phase;
|
||||
|
||||
/// Accepted points so far, with their segment and bridge markers.
|
||||
final List<RunPoint> points;
|
||||
|
||||
/// Credited moving time in seconds.
|
||||
final int movingSeconds;
|
||||
|
||||
/// Credited distance in metres.
|
||||
final double distanceM;
|
||||
|
||||
/// Whole kilometres already announced.
|
||||
final int km;
|
||||
|
||||
/// Whether a pause is still waiting for its next fix (starts a segment).
|
||||
final bool segmentBreak;
|
||||
|
||||
/// Consecutive too-fast fixes the filter had seen.
|
||||
final int jumps;
|
||||
|
||||
/// The pace target in seconds per kilometre, or null when off.
|
||||
final int? paceTargetSeconds;
|
||||
|
||||
/// The track id the run will save under (its first point, else its start).
|
||||
String get id =>
|
||||
RunTrack.idFor(points.isEmpty ? startedAt : points.first.time);
|
||||
|
||||
/// A JSON-encodable form, read back by [RunCheckpoint.fromJson].
|
||||
Map<String, Object?> toJson() => {
|
||||
'v': kCheckpointVersion,
|
||||
'id': id,
|
||||
'startedAt': startedAt.toIso8601String(),
|
||||
'savedAt': savedAt.toIso8601String(),
|
||||
'phase': phase.name,
|
||||
'moving': movingSeconds,
|
||||
'distance': distanceM,
|
||||
'km': km,
|
||||
'segBreak': segmentBreak,
|
||||
'jumps': jumps,
|
||||
'target': paceTargetSeconds,
|
||||
// [epoch ms, lat, lon, altitude|null, credited distance, link index]
|
||||
'points': [
|
||||
for (final p in points)
|
||||
[
|
||||
p.time.millisecondsSinceEpoch,
|
||||
p.latitude,
|
||||
p.longitude,
|
||||
p.altitudeM,
|
||||
p.distanceM,
|
||||
p.link.index,
|
||||
],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
T _field<T>(Map<String, Object?> json, String key) {
|
||||
final value = json[key];
|
||||
if (value is T) return value;
|
||||
throw FormatException('checkpoint field "$key" is missing or not a $T');
|
||||
}
|
||||
|
||||
T? _optional<T>(Map<String, Object?> json, String key) {
|
||||
final value = json[key];
|
||||
if (value == null || value is T) return value as T?;
|
||||
throw FormatException('checkpoint field "$key" is not a $T');
|
||||
}
|
||||
|
||||
DateTime _time(Map<String, Object?> json, String key) {
|
||||
final parsed = DateTime.tryParse(_field<String>(json, key));
|
||||
if (parsed == null) throw FormatException('checkpoint "$key" is no time');
|
||||
return parsed;
|
||||
}
|
||||
|
||||
RunPoint _point(Object? raw) {
|
||||
if (raw is! List<Object?> || raw.length != 6) {
|
||||
throw FormatException('checkpoint point $raw is not 6 values');
|
||||
}
|
||||
final ms = raw[0];
|
||||
final lat = raw[1];
|
||||
final lon = raw[2];
|
||||
final alt = raw[3];
|
||||
final dist = raw[4];
|
||||
final link = raw[5];
|
||||
if (ms is! int ||
|
||||
lat is! num ||
|
||||
lon is! num ||
|
||||
(alt != null && alt is! num) ||
|
||||
dist is! num ||
|
||||
link is! int ||
|
||||
link < 0 ||
|
||||
link >= RunLink.values.length) {
|
||||
throw FormatException('checkpoint point $raw has a bad value');
|
||||
}
|
||||
return RunPoint(
|
||||
time: DateTime.fromMillisecondsSinceEpoch(ms, isUtc: true),
|
||||
latitude: lat.toDouble(),
|
||||
longitude: lon.toDouble(),
|
||||
altitudeM: (alt as num?)?.toDouble(),
|
||||
distanceM: dist.toDouble(),
|
||||
link: RunLink.values[link],
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,120 @@
|
||||
/// Where the run's checkpoint lives between process deaths.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:developer';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:workout_app/services/run_checkpoint.dart';
|
||||
|
||||
/// Keeps the newest [RunCheckpoint] of the run in progress.
|
||||
abstract interface class RunCheckpointStore {
|
||||
/// Replaces the stored checkpoint with [c].
|
||||
Future<void> save(RunCheckpoint c);
|
||||
|
||||
/// The stored checkpoint, or null when there is none (or it was corrupt).
|
||||
Future<RunCheckpoint?> load();
|
||||
|
||||
/// Forgets the checkpoint: the run ended and was saved.
|
||||
Future<void> clear();
|
||||
}
|
||||
|
||||
/// A store in memory, for tests and hosts that keep nothing on disk.
|
||||
class MemoryRunCheckpointStore implements RunCheckpointStore {
|
||||
RunCheckpoint? _held;
|
||||
|
||||
@override
|
||||
Future<void> save(RunCheckpoint c) async => _held = c;
|
||||
|
||||
@override
|
||||
Future<RunCheckpoint?> load() async => _held;
|
||||
|
||||
@override
|
||||
Future<void> clear() async => _held = null;
|
||||
}
|
||||
|
||||
void _logLoud(String message) => log(message, level: 1000);
|
||||
|
||||
/// One JSON file, written atomically (temp file, then rename) so a kill
|
||||
/// mid-write leaves the previous checkpoint whole.
|
||||
///
|
||||
/// Saves are coalesced: while one write is in flight, later saves replace
|
||||
/// each other and only the newest is written next, so the 2 s fix stream
|
||||
/// can never queue up writes behind a slow disk.
|
||||
class FileRunCheckpointStore implements RunCheckpointStore {
|
||||
/// A store at [file]. [clock] stamps the name of a corrupt file moved
|
||||
/// aside; [onLoud] hears every problem (default: a level-1000 log).
|
||||
FileRunCheckpointStore(
|
||||
this.file, {
|
||||
this._clock = DateTime.now,
|
||||
void Function(String message) onLoud = _logLoud,
|
||||
}) : _loud = onLoud;
|
||||
|
||||
/// The checkpoint file.
|
||||
final File file;
|
||||
|
||||
final DateTime Function() _clock;
|
||||
final void Function(String message) _loud;
|
||||
RunCheckpoint? _newest;
|
||||
Future<void>? _draining;
|
||||
|
||||
File get _tmp => File('${file.path}.tmp');
|
||||
|
||||
@override
|
||||
Future<void> save(RunCheckpoint c) {
|
||||
_newest = c;
|
||||
return _draining ??= _drain();
|
||||
}
|
||||
|
||||
Future<void> _drain() async {
|
||||
try {
|
||||
while (_newest != null) {
|
||||
final c = _newest!;
|
||||
_newest = null;
|
||||
await _write(c);
|
||||
}
|
||||
} finally {
|
||||
_draining = null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _write(RunCheckpoint c) async {
|
||||
await file.parent.create(recursive: true);
|
||||
await _tmp.writeAsString(jsonEncode(c.toJson()), flush: true);
|
||||
await _tmp.rename(file.path);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<RunCheckpoint?> load() async {
|
||||
if (!file.existsSync()) return null;
|
||||
try {
|
||||
final json = jsonDecode(utf8.decode(await file.readAsBytes()));
|
||||
if (json is! Map<String, Object?>) {
|
||||
throw FormatException(
|
||||
'top level is ${json.runtimeType}, not an object',
|
||||
);
|
||||
}
|
||||
return RunCheckpoint.fromJson(json);
|
||||
} on FormatException catch (e) {
|
||||
await _moveAside(e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _moveAside(FormatException why) async {
|
||||
final aside = '${file.path}.corrupt-${_clock().millisecondsSinceEpoch}';
|
||||
await file.rename(aside);
|
||||
_loud(
|
||||
'RunCheckpointStore: the run checkpoint is corrupt (${why.message}); '
|
||||
'moved to $aside and starting without it. The run it held is lost.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clear() async {
|
||||
for (final f in [file, _tmp]) {
|
||||
if (f.existsSync()) await f.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
/// When a straight line across a gap in the fixes may credit distance.
|
||||
///
|
||||
/// A gap is any stretch over `kMaxCreditGapSeconds` between two accepted fixes
|
||||
/// that the runner did not pause: the phone died and was restored, or GPS
|
||||
/// dropped out. The recorder always draws the line from the last fix before
|
||||
/// the gap to the first one after it; it credits the distance (and the gap's
|
||||
/// time as moving time) only when the implied pace is a plausible run.
|
||||
library;
|
||||
|
||||
/// Fastest pace a bridge may credit, in seconds per kilometre (2:30 min/km).
|
||||
/// Faster is a vehicle: the line is drawn, nothing is credited.
|
||||
const int kBridgeFastestSecPerKm = 150;
|
||||
|
||||
/// Slowest pace a bridge may credit, in seconds per kilometre (12:00 min/km).
|
||||
/// Slower is standing about, not a run.
|
||||
const int kBridgeSlowestSecPerKm = 720;
|
||||
|
||||
/// The slowest speed a credited bridge can have, in metres per second.
|
||||
const double kBridgeMinSpeedMps = 1000 / kBridgeSlowestSecPerKm;
|
||||
|
||||
/// Whether a bridge of [stepM] straight-line metres over [gapSeconds] is
|
||||
/// credited: its pace lies within 2:30 and 12:00 min/km, bounds included.
|
||||
bool bridgeCredits({required double stepM, required int gapSeconds}) {
|
||||
if (stepM <= 0 || gapSeconds <= 0) return false;
|
||||
final secPerKm = gapSeconds * 1000 / stepM;
|
||||
return secPerKm >= kBridgeFastestSecPerKm &&
|
||||
secPerKm <= kBridgeSlowestSecPerKm;
|
||||
}
|
||||
@ -10,22 +10,23 @@
|
||||
/// 30 s or less earns moving time at 0.5 m/s or faster; a longer one (a GPS
|
||||
/// dropout) at 1 m/s or faster; paused time earns nothing.
|
||||
///
|
||||
/// The app mirrors only the bounds, per pair of its 2 s fixes, and is stricter:
|
||||
/// a pair over 30 s credits nothing, where the PC keeps a dropout at 1 m/s or
|
||||
/// faster. The app writes zero distance across such a gap, so the PC does not
|
||||
/// credit a dropout in an app-recorded run. Its on-screen moving time is
|
||||
/// therefore an estimate, not the number the PC will credit.
|
||||
/// The app mirrors the bounds per pair of its 2 s fixes. Across a gap over 30 s
|
||||
/// it bridges with a straight line (see `run_gap_bridge.dart`): the distance is
|
||||
/// credited only at 2:30 to 12:00 min/km, and the gap counts as moving time
|
||||
/// exactly when its distance was credited. Its on-screen moving time is an
|
||||
/// estimate, not the number the PC will credit.
|
||||
library;
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/run_gap_bridge.dart';
|
||||
|
||||
/// Mean Earth radius in metres (IUGG), the haversine constant.
|
||||
const double kEarthRadiusM = 6371008.8;
|
||||
|
||||
/// A pair of fixes further apart in time than this earns neither distance
|
||||
/// nor moving time: a GPS dropout whose motion is unknown.
|
||||
/// A pair of fixes further apart in time than this is a gap: bridged by a
|
||||
/// straight line (see `run_gap_bridge.dart`), not a normal step.
|
||||
///
|
||||
/// Mirrors `WALK_MAX_GAP_SECONDS` in the PC's `screen_locker/_constants.py`.
|
||||
const int kMaxCreditGapSeconds = 30;
|
||||
@ -56,18 +57,22 @@ double haversineM(double lat1, double lon1, double lat2, double lon2) {
|
||||
return 2 * kEarthRadiusM * math.asin(math.min(1, math.sqrt(a)));
|
||||
}
|
||||
|
||||
/// Whether the step from [a] to [b] counts as moving: seen within
|
||||
/// [kMaxCreditGapSeconds] and travelled at a speed in
|
||||
/// `[kMinMovingSpeedMps, maxSpeed]`.
|
||||
/// Whether the step from [a] to [b] counts as moving: travelled at a speed in
|
||||
/// `[kMinMovingSpeedMps, maxSpeed]`, or across a gap over
|
||||
/// [kMaxCreditGapSeconds] at one in `[kBridgeMinSpeedMps, maxSpeed]` (only a
|
||||
/// credited bridge has any distance at all).
|
||||
///
|
||||
/// Speed comes from the cumulative `distanceM` difference, as the PC reads a
|
||||
/// TCX, but over one pair of fixes rather than a window of 10 s or more, so the
|
||||
/// two can disagree on a jittery or stop-and-go stretch.
|
||||
bool isMovingStep(RunPoint a, RunPoint b, double maxSpeed) {
|
||||
final gap = b.time.difference(a.time).inMilliseconds / 1000;
|
||||
if (gap <= 0 || gap > kMaxCreditGapSeconds) return false;
|
||||
if (gap <= 0) return false;
|
||||
final speed = (b.distanceM - a.distanceM) / gap;
|
||||
return speed >= kMinMovingSpeedMps && speed <= maxSpeed;
|
||||
final floor = gap > kMaxCreditGapSeconds
|
||||
? kBridgeMinSpeedMps
|
||||
: kMinMovingSpeedMps;
|
||||
return speed >= floor && speed <= maxSpeed;
|
||||
}
|
||||
|
||||
/// Moving seconds over [points]: the summed gaps of every moving step.
|
||||
|
||||
@ -55,3 +55,19 @@ enum RunIssue {
|
||||
bool get isAccess =>
|
||||
this == denied || this == deniedForever || this == serviceOff;
|
||||
}
|
||||
|
||||
/// Why the recorder suggests the runner finish. It never ends a run itself
|
||||
/// (the 5 h auto end is a separate callback).
|
||||
enum RunSuggestion {
|
||||
/// Under 50 m of progress in 10 minutes; repeats every 10 minutes.
|
||||
stationary,
|
||||
|
||||
/// Faster than 25 km/h for a minute: probably in a vehicle.
|
||||
vehicleSpeed,
|
||||
|
||||
/// No GPS fix for 5 minutes.
|
||||
gpsLost,
|
||||
|
||||
/// The run was just restored from a checkpoint after the app died.
|
||||
restored,
|
||||
}
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
@ -11,10 +10,17 @@ import 'package:workout_app/services/gps_filter.dart';
|
||||
import 'package:workout_app/services/pace_band.dart';
|
||||
import 'package:workout_app/services/pace_coach.dart';
|
||||
import 'package:workout_app/services/position_source.dart';
|
||||
import 'package:workout_app/services/run_checkpoint.dart';
|
||||
import 'package:workout_app/services/run_math.dart';
|
||||
import 'package:workout_app/services/run_phase.dart';
|
||||
import 'package:workout_app/services/run_recorder_log.dart';
|
||||
import 'package:workout_app/services/run_watchdog.dart';
|
||||
|
||||
export 'package:workout_app/services/run_phase.dart';
|
||||
export 'package:workout_app/services/run_watchdog.dart' show RunLimits;
|
||||
|
||||
part 'run_recorder_fixes.dart';
|
||||
part 'run_recorder_persist.dart';
|
||||
|
||||
/// Records one GPS activity from a [PositionSource].
|
||||
///
|
||||
@ -25,13 +31,38 @@ export 'package:workout_app/services/run_phase.dart';
|
||||
/// walked while paused and the first fix after it credit nothing. Moving time
|
||||
/// is [movingSeconds] applied as fixes arrive: an estimate that mirrors the
|
||||
/// PC's bounds per pair of fixes, not its 10 s windows (see `run_math.dart`).
|
||||
///
|
||||
/// The run survives a dead process: [onCheckpoint] hands the host a
|
||||
/// [RunCheckpoint] after every accepted fix and on pause or resume, and
|
||||
/// `restore` (see `run_recorder_persist.dart`) rebuilds the recording from
|
||||
/// one. A gap (dead phone, GPS dropout) is bridged by a straight line (see
|
||||
/// `run_gap_bridge.dart`). A [RunWatchdog] suggests finishing and ends the
|
||||
/// run after 5 h of wall clock.
|
||||
class RunRecorder extends ChangeNotifier {
|
||||
/// Creates a recorder; [sourceFor] builds the fix stream on [start].
|
||||
///
|
||||
/// [clock] is the wall-clock seam; [autoEndAfter] and [limits] default to
|
||||
/// the agreed rules and are shrunk by the sandbox and the tests.
|
||||
RunRecorder({
|
||||
required this.sourceFor,
|
||||
this.onKilometre,
|
||||
void Function(PaceCue cue)? onPaceCue,
|
||||
}) : coach = PaceCoach(onCue: onPaceCue);
|
||||
this.onSuggestFinish,
|
||||
this.onAutoEnd,
|
||||
this.onCheckpoint,
|
||||
DateTime Function() clock = DateTime.now,
|
||||
Duration autoEndAfter = const Duration(hours: 5),
|
||||
RunLimits limits = const RunLimits(),
|
||||
}) : _clock = clock,
|
||||
coach = PaceCoach(onCue: onPaceCue) {
|
||||
_watch = RunWatchdog(
|
||||
clock: clock,
|
||||
onSuggest: (why) => onSuggestFinish?.call(why),
|
||||
onAutoEnd: () => onAutoEnd?.call(),
|
||||
autoEndAfter: autoEndAfter,
|
||||
limits: limits,
|
||||
);
|
||||
}
|
||||
|
||||
/// Builds the source for one recording.
|
||||
final PositionSource Function() sourceFor;
|
||||
@ -39,13 +70,26 @@ class RunRecorder extends ChangeNotifier {
|
||||
/// Called with 1, 2, 3 ... as each whole kilometre is credited.
|
||||
final void Function(int km)? onKilometre;
|
||||
|
||||
/// Advice to finish the run (never ends it).
|
||||
final void Function(RunSuggestion why)? onSuggestFinish;
|
||||
|
||||
/// Called once after 5 h of wall clock; the host then calls [finish].
|
||||
final void Function()? onAutoEnd;
|
||||
|
||||
/// Hears a fresh checkpoint after every accepted fix, on start, pause and
|
||||
/// resume: the host stores it.
|
||||
final void Function(RunCheckpoint checkpoint)? onCheckpoint;
|
||||
|
||||
/// The pace target's state: current pace, band and cues.
|
||||
final PaceCoach coach;
|
||||
|
||||
final DateTime Function() _clock;
|
||||
late final RunWatchdog _watch;
|
||||
RunPhase _phase = RunPhase.idle;
|
||||
RunIssue _issue = RunIssue.none;
|
||||
GpsFilter? _filter;
|
||||
StreamSubscription<GpsFix>? _sub;
|
||||
late DateTime _startedAt;
|
||||
bool _starting = false;
|
||||
int _moving = 0;
|
||||
int _km = 0;
|
||||
@ -93,19 +137,14 @@ class RunRecorder extends ChangeNotifier {
|
||||
try {
|
||||
final source = sourceFor();
|
||||
final access = await source.requestAccess();
|
||||
if (!access.isGranted) {
|
||||
_refuse(access);
|
||||
if (!await _open(source, access, afterAccess, GpsFilter())) {
|
||||
return false;
|
||||
}
|
||||
await afterAccess?.call();
|
||||
_filter = GpsFilter();
|
||||
_sub = source
|
||||
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
|
||||
.listen(_onFix, onError: _onError, onDone: _onDone);
|
||||
_issue = RunIssue.none;
|
||||
_startedAt = _clock().toUtc();
|
||||
_phase = RunPhase.recording;
|
||||
_watch.begin(_startedAt);
|
||||
SandboxLog.event('run started');
|
||||
notifyListeners();
|
||||
_announce();
|
||||
return true;
|
||||
} finally {
|
||||
_starting = false;
|
||||
@ -117,8 +156,9 @@ class RunRecorder extends ChangeNotifier {
|
||||
if (_phase != RunPhase.recording) return;
|
||||
_filter!.breakSegment();
|
||||
_phase = RunPhase.paused;
|
||||
_watch.pause();
|
||||
SandboxLog.event('run paused', {'m': distanceM});
|
||||
notifyListeners();
|
||||
_announce();
|
||||
}
|
||||
|
||||
/// Continues after [pause].
|
||||
@ -126,14 +166,16 @@ class RunRecorder extends ChangeNotifier {
|
||||
if (_phase != RunPhase.paused) return;
|
||||
_phase = RunPhase.recording;
|
||||
coach.restartAt(_filter!.points.length);
|
||||
_watch.resume();
|
||||
SandboxLog.event('run resumed', {'m': distanceM});
|
||||
notifyListeners();
|
||||
_announce();
|
||||
}
|
||||
|
||||
/// Ends the recording and returns the track, or null when there were too
|
||||
/// few usable fixes (then [issue] is [RunIssue.tooShort]).
|
||||
Future<RunTrack?> finish() async {
|
||||
if (!_phase.isActive) return null;
|
||||
_watch.stop();
|
||||
await _sub?.cancel();
|
||||
_sub = null;
|
||||
_phase = RunPhase.finished;
|
||||
@ -142,11 +184,7 @@ class RunRecorder extends ChangeNotifier {
|
||||
RunTrack? track;
|
||||
if (points.length < 2) {
|
||||
_issue = RunIssue.tooShort;
|
||||
log(
|
||||
'RunRecorder: finished with ${points.length} usable GPS fix(es) '
|
||||
'-- not enough for a track, so nothing is saved.',
|
||||
level: 1000,
|
||||
);
|
||||
logTooShort(points.length);
|
||||
} else {
|
||||
track = RunTrack.started(
|
||||
sport: RunSport.running,
|
||||
@ -166,81 +204,26 @@ class RunRecorder extends ChangeNotifier {
|
||||
return track;
|
||||
}
|
||||
|
||||
/// [notifyListeners] for the `part` files' extensions, which may not call
|
||||
/// a protected member themselves.
|
||||
void _changed() => notifyListeners();
|
||||
|
||||
/// Tells listeners and hands the host a fresh checkpoint.
|
||||
void _announce() {
|
||||
notifyListeners();
|
||||
final c = onCheckpoint == null ? null : checkpoint();
|
||||
if (c != null) onCheckpoint!(c);
|
||||
}
|
||||
|
||||
void _refuse(LocationAccess access) {
|
||||
_issue = RunIssue.forAccess(access);
|
||||
final fix = access == LocationAccess.serviceOff
|
||||
? 'Switch location on'
|
||||
: 'Grant location to the app in system settings';
|
||||
log(
|
||||
'RunRecorder: not recording -- location access is ${access.name}. '
|
||||
'$fix and start again.',
|
||||
level: 1000,
|
||||
);
|
||||
logRefused(access);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _onFix(GpsFix fix) {
|
||||
if (_phase != RunPhase.recording) return;
|
||||
final verdict = _filter!.add(fix);
|
||||
if (verdict != FixVerdict.accepted) {
|
||||
_noteDropped(verdict);
|
||||
return;
|
||||
}
|
||||
_issue = RunIssue.none;
|
||||
final points = _filter!.points;
|
||||
final n = points.length;
|
||||
if (n >= 2 &&
|
||||
isMovingStep(points[n - 2], points[n - 1], kRunningMaxSpeedMps)) {
|
||||
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
|
||||
}
|
||||
_live.value = points;
|
||||
coach.update(points);
|
||||
while (distanceM ~/ 1000 > _km) {
|
||||
_km++;
|
||||
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
|
||||
onKilometre?.call(_km);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _noteDropped(FixVerdict verdict) {
|
||||
if (verdict == FixVerdict.mocked) {
|
||||
_issue = RunIssue.mockedLocation;
|
||||
notifyListeners();
|
||||
}
|
||||
// Said once per kind and run: a bad tunnel would otherwise flood the log.
|
||||
if (!_seenVerdicts.add(verdict)) return;
|
||||
log(
|
||||
'RunRecorder: dropped a GPS fix (${verdict.name}); further drops of '
|
||||
'this kind are not logged. Mock fixes never count towards a run.',
|
||||
level: 900,
|
||||
);
|
||||
}
|
||||
|
||||
void _onError(Object error, StackTrace stack) {
|
||||
_issue = RunIssue.streamError;
|
||||
log(
|
||||
'RunRecorder: the location stream failed ($error) -- fixes may have '
|
||||
'stopped; time and distance are not crediting until they resume.',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stack,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _onDone() {
|
||||
if (!_phase.isActive) return;
|
||||
log(
|
||||
'RunRecorder: the location stream ended while still recording; '
|
||||
'finish the run to save what was captured.',
|
||||
level: 900,
|
||||
);
|
||||
SandboxLog.event('run stream ended', {'m': distanceM});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_watch.stop();
|
||||
unawaited(_sub?.cancel());
|
||||
_live.dispose();
|
||||
super.dispose();
|
||||
|
||||
@ -0,0 +1,51 @@
|
||||
// What the recorder does with each fix, error and end of the stream: a `part`
|
||||
// file so the state machine itself stays short.
|
||||
part of 'run_recorder.dart';
|
||||
|
||||
extension _FixHandling on RunRecorder {
|
||||
void _onFix(GpsFix fix) {
|
||||
if (_phase != RunPhase.recording) return;
|
||||
final verdict = _filter!.add(fix);
|
||||
_watch.onFix(fix, verdict, distanceM);
|
||||
if (verdict != FixVerdict.accepted) {
|
||||
_noteDropped(verdict);
|
||||
return;
|
||||
}
|
||||
_issue = RunIssue.none;
|
||||
final points = _filter!.points;
|
||||
final n = points.length;
|
||||
if (n >= 2 &&
|
||||
isMovingStep(points[n - 2], points[n - 1], kRunningMaxSpeedMps)) {
|
||||
_moving += points[n - 1].time.difference(points[n - 2].time).inSeconds;
|
||||
}
|
||||
_live.value = points;
|
||||
coach.update(points);
|
||||
while (distanceM ~/ 1000 > _km) {
|
||||
_km++;
|
||||
SandboxLog.event('run km', {'km': _km, 'secs': _moving});
|
||||
onKilometre?.call(_km);
|
||||
}
|
||||
_announce();
|
||||
}
|
||||
|
||||
void _noteDropped(FixVerdict verdict) {
|
||||
if (verdict == FixVerdict.mocked) {
|
||||
_issue = RunIssue.mockedLocation;
|
||||
_changed();
|
||||
}
|
||||
// Said once per kind and run: a bad tunnel would otherwise flood the log.
|
||||
if (_seenVerdicts.add(verdict)) logDropped(verdict);
|
||||
}
|
||||
|
||||
void _onError(Object error, StackTrace stack) {
|
||||
_issue = RunIssue.streamError;
|
||||
logStreamError(error, stack);
|
||||
_changed();
|
||||
}
|
||||
|
||||
void _onDone() {
|
||||
if (!_phase.isActive) return;
|
||||
logStreamEnded();
|
||||
SandboxLog.event('run stream ended', {'m': distanceM});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
/// The recorder's log lines, kept apart so the state machine stays short.
|
||||
///
|
||||
/// Level 1000 is "something is wrong and the user must act or lose data";
|
||||
/// 900 is a warning. Nothing here is silent: see the repo's
|
||||
/// "NEVER fail silently" rule.
|
||||
library;
|
||||
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:workout_app/services/gps_filter.dart';
|
||||
import 'package:workout_app/services/position_source.dart';
|
||||
|
||||
/// Recording was refused because location access is [access].
|
||||
void logRefused(LocationAccess access) {
|
||||
final fix = access == LocationAccess.serviceOff
|
||||
? 'Switch location on'
|
||||
: 'Grant location to the app in system settings';
|
||||
log(
|
||||
'RunRecorder: not recording -- location access is ${access.name}. '
|
||||
'$fix and start again.',
|
||||
level: 1000,
|
||||
);
|
||||
}
|
||||
|
||||
/// A fix was dropped for [verdict]; the caller says it once per kind.
|
||||
void logDropped(FixVerdict verdict) => log(
|
||||
'RunRecorder: dropped a GPS fix (${verdict.name}); further drops of '
|
||||
'this kind are not logged. Mock fixes never count towards a run.',
|
||||
level: 900,
|
||||
);
|
||||
|
||||
/// The location stream reported [error].
|
||||
void logStreamError(Object error, StackTrace stack) => log(
|
||||
'RunRecorder: the location stream failed ($error) -- fixes may have '
|
||||
'stopped; time and distance are not crediting until they resume.',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stack,
|
||||
);
|
||||
|
||||
/// The location stream ended while a run was still active.
|
||||
void logStreamEnded() => log(
|
||||
'RunRecorder: the location stream ended while still recording; '
|
||||
'finish the run to save what was captured.',
|
||||
level: 900,
|
||||
);
|
||||
|
||||
/// A run finished with [count] usable fixes, too few to save.
|
||||
void logTooShort(int count) => log(
|
||||
'RunRecorder: finished with $count usable GPS fix(es) '
|
||||
'-- not enough for a track, so nothing is saved.',
|
||||
level: 1000,
|
||||
);
|
||||
|
||||
/// Restoring the checkpointed run failed with [error].
|
||||
void logRestoreFailed(Object error, StackTrace stack) => log(
|
||||
'RunRecorder: could not reopen the position source to restore the run '
|
||||
'($error) -- the run stays unrecovered; its checkpoint is kept.',
|
||||
level: 1000,
|
||||
error: error,
|
||||
stackTrace: stack,
|
||||
);
|
||||
@ -0,0 +1,95 @@
|
||||
// Checkpointing and restore: a `part` file so they can use the recorder's
|
||||
// private state while the recorder itself stays short.
|
||||
part of 'run_recorder.dart';
|
||||
|
||||
/// Persistence of a run across a dead process.
|
||||
extension RunRecorderPersistence on RunRecorder {
|
||||
/// A snapshot to rebuild the run from, or null when idle or finished.
|
||||
RunCheckpoint? checkpoint() {
|
||||
final filter = _filter;
|
||||
if (!_phase.isActive || filter == null) return null;
|
||||
return RunCheckpoint(
|
||||
startedAt: _startedAt,
|
||||
savedAt: _clock(),
|
||||
phase: _phase,
|
||||
points: filter.points,
|
||||
movingSeconds: _moving,
|
||||
distanceM: filter.distanceM,
|
||||
km: _km,
|
||||
segmentBreak: filter.segmentBreak,
|
||||
jumps: filter.jumps,
|
||||
paceTargetSeconds: coach.target,
|
||||
);
|
||||
}
|
||||
|
||||
/// Rebuilds the run from [c] after the process died and reopens the
|
||||
/// position source (without prompting). The next fix is bridged across the
|
||||
/// dead time. Fires [RunRecorder.onSuggestFinish] with
|
||||
/// [RunSuggestion.restored], or [RunRecorder.onAutoEnd] at once when 5 h
|
||||
/// have passed. False (logged) when the source cannot open or a run is
|
||||
/// already going.
|
||||
Future<bool> restore(
|
||||
RunCheckpoint c, {
|
||||
Future<void> Function()? afterAccess,
|
||||
}) async {
|
||||
if (_phase != RunPhase.idle || _starting) return false;
|
||||
_starting = true;
|
||||
try {
|
||||
final source = sourceFor();
|
||||
final filter = GpsFilter.restore(
|
||||
points: c.points,
|
||||
segmentBreak: c.segmentBreak,
|
||||
jumps: c.jumps,
|
||||
);
|
||||
final access = await source.checkAccess();
|
||||
if (!await _open(source, access, afterAccess, filter)) return false;
|
||||
_startedAt = c.startedAt;
|
||||
_moving = c.movingSeconds;
|
||||
_km = c.km;
|
||||
coach
|
||||
..setTarget(c.paceTargetSeconds)
|
||||
..restartAt(c.points.length);
|
||||
_live.value = c.points;
|
||||
_phase = c.phase;
|
||||
SandboxLog.event('run restored', {'m': c.distanceM});
|
||||
_announce();
|
||||
_watch.restored(
|
||||
c.startedAt,
|
||||
paused: c.phase == RunPhase.paused,
|
||||
distanceM: c.distanceM,
|
||||
);
|
||||
return true;
|
||||
} on Object catch (e, stack) {
|
||||
logRestoreFailed(e, stack);
|
||||
await _sub?.cancel();
|
||||
_sub = null;
|
||||
_filter = null;
|
||||
_phase = RunPhase.idle;
|
||||
_issue = RunIssue.streamError;
|
||||
_changed();
|
||||
return false;
|
||||
} finally {
|
||||
_starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens [source] under [access] with [filter]; false when refused.
|
||||
Future<bool> _open(
|
||||
PositionSource source,
|
||||
LocationAccess access,
|
||||
Future<void> Function()? afterAccess,
|
||||
GpsFilter filter,
|
||||
) async {
|
||||
if (!access.isGranted) {
|
||||
_refuse(access);
|
||||
return false;
|
||||
}
|
||||
await afterAccess?.call();
|
||||
_filter = filter;
|
||||
_sub = source
|
||||
.fixes() // the source's default 2 s, far under kMaxCreditGapSeconds
|
||||
.listen(_onFix, onError: _onError, onDone: _onDone);
|
||||
_issue = RunIssue.none;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,209 @@
|
||||
/// Watches a run for the signs that it should end: suggests finishing, and
|
||||
/// ends it after 5 hours of wall clock.
|
||||
///
|
||||
/// It never finishes a run itself: [onSuggest] is advice, [onAutoEnd] tells
|
||||
/// the host to call `finish()`. Checks run off a periodic [Timer] and the
|
||||
/// injected [clock], not only when a fix arrives, so a silent GPS is noticed.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:workout_app/services/gps_filter.dart';
|
||||
import 'package:workout_app/services/run_math.dart';
|
||||
import 'package:workout_app/services/run_phase.dart';
|
||||
|
||||
/// The suggest-finish thresholds; the defaults are the agreed rules, the
|
||||
/// sandbox and the tests shrink them.
|
||||
class RunLimits {
|
||||
/// Creates limits.
|
||||
const RunLimits({
|
||||
this.stationaryWindow = const Duration(minutes: 10),
|
||||
this.stationaryMinM = 50,
|
||||
this.vehicleSpeedMps = 25 / 3.6,
|
||||
this.vehicleWindow = const Duration(seconds: 60),
|
||||
this.noFixAfter = const Duration(minutes: 5),
|
||||
this.tick = const Duration(seconds: 5),
|
||||
});
|
||||
|
||||
/// The progress window for [RunSuggestion.stationary].
|
||||
final Duration stationaryWindow;
|
||||
|
||||
/// Credited metres a [stationaryWindow] needs to stay quiet.
|
||||
final double stationaryMinM;
|
||||
|
||||
/// Speed above which a stretch looks like a vehicle, in metres per second.
|
||||
final double vehicleSpeedMps;
|
||||
|
||||
/// How long that speed must hold.
|
||||
final Duration vehicleWindow;
|
||||
|
||||
/// How long without a usable fix before [RunSuggestion.gpsLost].
|
||||
final Duration noFixAfter;
|
||||
|
||||
/// How often the timer checks.
|
||||
final Duration tick;
|
||||
}
|
||||
|
||||
/// The suggest-finish and auto-end rules of one run.
|
||||
class RunWatchdog {
|
||||
/// Creates a watchdog with the agreed rules unless [limits] or
|
||||
/// [autoEndAfter] say otherwise.
|
||||
RunWatchdog({
|
||||
required this.clock,
|
||||
required this.onSuggest,
|
||||
required this.onAutoEnd,
|
||||
this.autoEndAfter = const Duration(hours: 5),
|
||||
this.limits = const RunLimits(),
|
||||
});
|
||||
|
||||
/// The wall clock.
|
||||
final DateTime Function() clock;
|
||||
|
||||
/// Hears each suggestion to finish.
|
||||
final void Function(RunSuggestion why) onSuggest;
|
||||
|
||||
/// Hears the auto end, once; the host then finishes the run.
|
||||
final void Function() onAutoEnd;
|
||||
|
||||
/// Wall-clock run length (pauses and phone-off time included) that ends it.
|
||||
final Duration autoEndAfter;
|
||||
|
||||
/// The suggest-finish thresholds.
|
||||
final RunLimits limits;
|
||||
|
||||
Timer? _timer;
|
||||
DateTime? _startedAt;
|
||||
bool _paused = false;
|
||||
bool _ended = false;
|
||||
late DateTime _lastFixAt;
|
||||
late DateTime _anchorAt;
|
||||
double _anchorM = 0;
|
||||
double _distanceM = 0;
|
||||
bool _lostFired = false;
|
||||
GpsFix? _prev;
|
||||
DateTime? _fastSince;
|
||||
bool _fastFired = false;
|
||||
|
||||
/// Starts watching a run that began at [startedAt].
|
||||
void begin(DateTime startedAt) {
|
||||
_startedAt = startedAt.toUtc();
|
||||
_ended = false;
|
||||
_paused = false;
|
||||
_distanceM = 0;
|
||||
_rebase();
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(limits.tick, (_) => check());
|
||||
}
|
||||
|
||||
/// Starts watching a run restored from a checkpoint: advises finishing, or
|
||||
/// ends it at once when 5 hours have already passed.
|
||||
void restored(
|
||||
DateTime startedAt, {
|
||||
required bool paused,
|
||||
required double distanceM,
|
||||
}) {
|
||||
begin(startedAt);
|
||||
_paused = paused;
|
||||
_distanceM = distanceM;
|
||||
_anchorM = distanceM;
|
||||
if (_expired()) {
|
||||
check();
|
||||
} else {
|
||||
onSuggest(RunSuggestion.restored);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops all checks (finish or dispose). Safe to call twice.
|
||||
void stop() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_startedAt = null;
|
||||
}
|
||||
|
||||
/// A pause: nothing fires until [resume].
|
||||
void pause() => _paused = true;
|
||||
|
||||
/// After a pause the windows start afresh, so paused time never reads as
|
||||
/// standing still or a lost signal.
|
||||
void resume() {
|
||||
_paused = false;
|
||||
_rebase();
|
||||
}
|
||||
|
||||
/// Folds in one raw fix and the filter's [verdict] on it.
|
||||
///
|
||||
/// Too-fast fixes count: a vehicle never yields an accepted fix, the
|
||||
/// filter drops it as a jump, so speed is read off raw consecutive fixes.
|
||||
void onFix(GpsFix fix, FixVerdict verdict, double distanceM) {
|
||||
if (verdict != FixVerdict.accepted && verdict != FixVerdict.tooFast) {
|
||||
return;
|
||||
}
|
||||
_distanceM = distanceM;
|
||||
_lastFixAt = clock();
|
||||
_lostFired = false;
|
||||
_readSpeed(fix);
|
||||
check();
|
||||
}
|
||||
|
||||
void _readSpeed(GpsFix fix) {
|
||||
final prev = _prev;
|
||||
if (prev == null) {
|
||||
_prev = fix;
|
||||
return;
|
||||
}
|
||||
final dt = fix.time.difference(prev.time).inSeconds;
|
||||
if (dt <= 0) return; // a same-second fix says nothing about speed
|
||||
_prev = fix;
|
||||
final speed =
|
||||
haversineM(prev.latitude, prev.longitude, fix.latitude, fix.longitude) /
|
||||
dt;
|
||||
if (speed <= limits.vehicleSpeedMps) {
|
||||
_fastSince = null;
|
||||
_fastFired = false;
|
||||
return;
|
||||
}
|
||||
_fastSince ??= fix.time;
|
||||
if (!_fastFired &&
|
||||
fix.time.difference(_fastSince!) >= limits.vehicleWindow) {
|
||||
_fastFired = true;
|
||||
onSuggest(RunSuggestion.vehicleSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs every rule against the clock; the timer calls this every [tick].
|
||||
void check() {
|
||||
final started = _startedAt;
|
||||
if (started == null || _ended) return;
|
||||
if (_expired()) {
|
||||
_ended = true;
|
||||
_timer?.cancel();
|
||||
onAutoEnd();
|
||||
return;
|
||||
}
|
||||
if (_paused) return;
|
||||
final now = clock();
|
||||
if (!_lostFired && now.difference(_lastFixAt) >= limits.noFixAfter) {
|
||||
_lostFired = true;
|
||||
onSuggest(RunSuggestion.gpsLost);
|
||||
}
|
||||
if (now.difference(_anchorAt) >= limits.stationaryWindow) {
|
||||
final progress = _distanceM - _anchorM;
|
||||
_anchorAt = now;
|
||||
_anchorM = _distanceM;
|
||||
if (progress < limits.stationaryMinM) onSuggest(RunSuggestion.stationary);
|
||||
}
|
||||
}
|
||||
|
||||
bool _expired() => !_ended && clock().difference(_startedAt!) >= autoEndAfter;
|
||||
|
||||
void _rebase() {
|
||||
final now = clock();
|
||||
_lastFixAt = now;
|
||||
_anchorAt = now;
|
||||
_anchorM = _distanceM;
|
||||
_lostFired = false;
|
||||
_prev = null;
|
||||
_fastSince = null;
|
||||
_fastFired = false;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,108 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/gps_filter.dart';
|
||||
import 'package:workout_app/services/run_math.dart';
|
||||
|
||||
const double _degM = 111194.9;
|
||||
|
||||
GpsFix _fix(int seconds, double northM, {double accuracy = 5}) => GpsFix(
|
||||
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: seconds)),
|
||||
latitude: 48.8584 + northM / _degM,
|
||||
longitude: 2.2945,
|
||||
altitudeM: 30,
|
||||
accuracyM: accuracy,
|
||||
);
|
||||
|
||||
GpsFilter _runningTo30m() => GpsFilter()
|
||||
..add(_fix(0, 0))
|
||||
..add(_fix(10, 30));
|
||||
|
||||
void main() {
|
||||
group('a gap over 30 s is bridged by a straight line', () {
|
||||
test('at 5:00/km the line is credited and flagged as a bridge', () {
|
||||
final f = _runningTo30m();
|
||||
expect(f.add(_fix(310, 30 + 1000)), FixVerdict.accepted);
|
||||
expect(f.distanceM, closeTo(1030, 1));
|
||||
expect(f.points.last.link, RunLink.bridge);
|
||||
});
|
||||
|
||||
test('a bridge faster than 2:30/km is drawn but earns 0 m', () {
|
||||
final f = _runningTo30m();
|
||||
expect(f.add(_fix(70, 30 + 1000)), FixVerdict.accepted); // 60 s, 1 km
|
||||
expect(f.distanceM, closeTo(30, 0.5));
|
||||
expect(f.points.last.link, RunLink.bridge);
|
||||
expect(f.points.last.latitude, closeTo(48.8584 + 1030 / _degM, 1e-6));
|
||||
});
|
||||
|
||||
test('a bridge slower than 12:00/km earns 0 m', () {
|
||||
final f = _runningTo30m()..add(_fix(1010, 30 + 100)); // 1000 s, 100 m
|
||||
expect(f.distanceM, closeTo(30, 0.5));
|
||||
expect(f.points.last.link, RunLink.bridge);
|
||||
});
|
||||
|
||||
test('the jump cap does not reject the first fix after a gap', () {
|
||||
final f = _runningTo30m();
|
||||
expect(f.add(_fix(3610, 30 + 50000)), FixVerdict.accepted);
|
||||
expect(f.distanceM, closeTo(30, 0.5));
|
||||
});
|
||||
|
||||
test('exactly 30 s is not a gap', () {
|
||||
final f = _runningTo30m()..add(_fix(40, 30 + 90)); // 30 s, 3 m/s
|
||||
expect(f.points.last.link, RunLink.continuous);
|
||||
expect(f.distanceM, closeTo(120, 0.5));
|
||||
});
|
||||
|
||||
test('31 s is a gap and still credited at a running pace', () {
|
||||
final f = _runningTo30m()..add(_fix(41, 30 + 93));
|
||||
expect(f.points.last.link, RunLink.bridge);
|
||||
expect(f.distanceM, closeTo(123, 0.5));
|
||||
});
|
||||
|
||||
test('a pause still earns nothing and is a segment start', () {
|
||||
final f = _runningTo30m()
|
||||
..breakSegment()
|
||||
..add(_fix(310, 30 + 1000));
|
||||
expect(f.distanceM, closeTo(30, 0.5));
|
||||
expect(f.points.last.link, RunLink.segmentStart);
|
||||
});
|
||||
|
||||
test('moving time counts only a credited bridge', () {
|
||||
final credited = _runningTo30m()..add(_fix(310, 1030));
|
||||
expect(movingSeconds(credited.points), 10 + 300);
|
||||
final vehicle = _runningTo30m()..add(_fix(70, 1030));
|
||||
expect(movingSeconds(vehicle.points), 10);
|
||||
});
|
||||
});
|
||||
|
||||
group('GpsFilter.restore', () {
|
||||
test('rebuilds points, segment break and jump count', () {
|
||||
final f = _runningTo30m()..breakSegment();
|
||||
final back = GpsFilter.restore(
|
||||
points: f.points,
|
||||
segmentBreak: f.segmentBreak,
|
||||
jumps: f.jumps,
|
||||
);
|
||||
expect(back.points, f.points);
|
||||
expect(back.segmentBreak, isTrue);
|
||||
expect(back.distanceM, f.distanceM);
|
||||
expect(back.add(_fix(310, 5000)), FixVerdict.accepted);
|
||||
expect(back.points.last.link, RunLink.segmentStart);
|
||||
});
|
||||
|
||||
test('an empty restore behaves like a fresh filter', () {
|
||||
final back = GpsFilter.restore(points: const []);
|
||||
expect(back.distanceM, 0);
|
||||
expect(back.add(_fix(0, 0)), FixVerdict.accepted);
|
||||
});
|
||||
|
||||
test('the jump count carries over', () {
|
||||
final back = GpsFilter.restore(
|
||||
points: _runningTo30m().points,
|
||||
jumps: kMaxConsecutiveJumps - 1,
|
||||
);
|
||||
// 4 earlier jumps + this one = 5: re-anchors instead of rejecting.
|
||||
expect(back.add(_fix(12, 30 + 1000)), FixVerdict.accepted);
|
||||
expect(back.points.last.link, RunLink.segmentStart);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -90,15 +90,15 @@ void main() {
|
||||
expect(f.points.first.altitudeM, 30);
|
||||
});
|
||||
|
||||
test('standing-still jitter and a long dropout earn no distance', () {
|
||||
test('standing-still jitter earns nothing, a long dropout is bridged', () {
|
||||
final f = GpsFilter()
|
||||
..add(_fix(0, 0))
|
||||
..add(_fix(10, 2)); // 0.2 m/s: standing
|
||||
expect(f.distanceM, 0);
|
||||
f.add(_fix(60, 100)); // 50 s later: unseen motion
|
||||
expect(f.distanceM, 0);
|
||||
f.add(_fix(60, 100)); // 50 s later, 98 m: 8:30/km, bridged and credited
|
||||
expect(f.distanceM, closeTo(98, 0.2));
|
||||
f.add(_fix(70, 127)); // seen again, moving
|
||||
expect(f.distanceM, closeTo(27, 0.2));
|
||||
expect(f.distanceM, closeTo(125, 0.2));
|
||||
expect(f.points, hasLength(4));
|
||||
});
|
||||
|
||||
|
||||
@ -0,0 +1,159 @@
|
||||
@TestOn('vm')
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/run_checkpoint.dart';
|
||||
import 'package:workout_app/services/run_checkpoint_store.dart';
|
||||
import 'package:workout_app/services/run_phase.dart';
|
||||
|
||||
RunCheckpoint _checkpoint({int moving = 6}) => RunCheckpoint(
|
||||
startedAt: DateTime.utc(2026, 11, 9, 12),
|
||||
savedAt: DateTime.utc(2026, 11, 9, 12, 5),
|
||||
phase: RunPhase.recording,
|
||||
points: [
|
||||
RunPoint(
|
||||
time: DateTime.utc(2026, 11, 9, 12),
|
||||
latitude: 48.8584,
|
||||
longitude: 2.2945,
|
||||
distanceM: 0,
|
||||
),
|
||||
],
|
||||
movingSeconds: moving,
|
||||
distanceM: 0,
|
||||
km: 0,
|
||||
segmentBreak: false,
|
||||
jumps: 0,
|
||||
);
|
||||
|
||||
void main() {
|
||||
late Directory dir;
|
||||
late File file;
|
||||
|
||||
setUp(() {
|
||||
dir = Directory.systemTemp.createTempSync('run_checkpoint_store_');
|
||||
file = File('${dir.path}/sub/run_checkpoint.json');
|
||||
});
|
||||
|
||||
tearDown(() => dir.deleteSync(recursive: true));
|
||||
|
||||
group('FileRunCheckpointStore', () {
|
||||
test('load with no file is null', () async {
|
||||
expect(await FileRunCheckpointStore(file).load(), isNull);
|
||||
});
|
||||
|
||||
test('save then load returns the same checkpoint', () async {
|
||||
final store = FileRunCheckpointStore(file);
|
||||
await store.save(_checkpoint());
|
||||
final back = (await store.load())!;
|
||||
expect(back.movingSeconds, 6);
|
||||
expect(back.startedAt, DateTime.utc(2026, 11, 9, 12));
|
||||
expect(back.points, hasLength(1));
|
||||
});
|
||||
|
||||
test('a save leaves no temp file behind', () async {
|
||||
await FileRunCheckpointStore(file).save(_checkpoint());
|
||||
final names = file.parent.listSync().map((e) => e.path).toList();
|
||||
expect(names, [file.path]);
|
||||
});
|
||||
|
||||
test('a second save replaces the first', () async {
|
||||
final store = FileRunCheckpointStore(file);
|
||||
await store.save(_checkpoint());
|
||||
await store.save(_checkpoint(moving: 99));
|
||||
expect((await store.load())!.movingSeconds, 99);
|
||||
});
|
||||
|
||||
test('overlapping saves keep the newest and all complete', () async {
|
||||
final store = FileRunCheckpointStore(file);
|
||||
final saves = [
|
||||
for (var i = 1; i <= 20; i++) store.save(_checkpoint(moving: i)),
|
||||
];
|
||||
await Future.wait(saves);
|
||||
expect((await store.load())!.movingSeconds, 20);
|
||||
expect(file.parent.listSync(), hasLength(1));
|
||||
});
|
||||
|
||||
test('clear removes the file and is safe when there is none', () async {
|
||||
final store = FileRunCheckpointStore(file);
|
||||
await store.clear();
|
||||
await store.save(_checkpoint());
|
||||
await store.clear();
|
||||
expect(file.existsSync(), isFalse);
|
||||
expect(await store.load(), isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'a corrupt file is moved aside, logged loudly, load is null',
|
||||
() async {
|
||||
file.parent.createSync(recursive: true);
|
||||
file.writeAsStringSync('{"v":1, truncated');
|
||||
final logs = <String>[];
|
||||
final store = FileRunCheckpointStore(
|
||||
file,
|
||||
clock: () => DateTime.utc(2026, 11, 9, 13),
|
||||
onLoud: logs.add,
|
||||
);
|
||||
expect(await store.load(), isNull);
|
||||
expect(file.existsSync(), isFalse);
|
||||
final aside = file.parent
|
||||
.listSync()
|
||||
.map((e) => e.path)
|
||||
.where((p) => p.contains('.corrupt-'))
|
||||
.toList();
|
||||
expect(aside, hasLength(1));
|
||||
expect(File(aside.single).readAsStringSync(), contains('truncated'));
|
||||
expect(logs.single, contains('corrupt'));
|
||||
expect(aside.single, contains('.corrupt-'));
|
||||
},
|
||||
);
|
||||
|
||||
test('valid JSON of the wrong shape is corrupt too', () async {
|
||||
file.parent.createSync(recursive: true);
|
||||
file.writeAsStringSync('[1, 2, 3]');
|
||||
expect(await FileRunCheckpointStore(file).load(), isNull);
|
||||
expect(file.existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test('JSON that fails the codec is corrupt too', () async {
|
||||
file.parent.createSync(recursive: true);
|
||||
file.writeAsStringSync('{"v": 1}');
|
||||
expect(await FileRunCheckpointStore(file).load(), isNull);
|
||||
expect(file.existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test('bytes that are not UTF-8 are corrupt too', () async {
|
||||
file.parent.createSync(recursive: true);
|
||||
file.writeAsBytesSync([0xff, 0xfe, 0x00, 0x80]);
|
||||
expect(await FileRunCheckpointStore(file).load(), isNull);
|
||||
expect(file.existsSync(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'an unreadable file surfaces the error instead of hiding it',
|
||||
() async {
|
||||
file.parent.createSync(recursive: true);
|
||||
file.writeAsStringSync('{}');
|
||||
Process.runSync('chmod', ['000', file.path]);
|
||||
addTearDown(() => Process.runSync('chmod', ['644', file.path]));
|
||||
await expectLater(
|
||||
FileRunCheckpointStore(file).load(),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('MemoryRunCheckpointStore', () {
|
||||
test('keeps the last save until cleared', () async {
|
||||
final store = MemoryRunCheckpointStore();
|
||||
expect(await store.load(), isNull);
|
||||
await store.save(_checkpoint());
|
||||
expect((await store.load())!.movingSeconds, 6);
|
||||
await store.clear();
|
||||
expect(await store.load(), isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,198 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/run_checkpoint.dart';
|
||||
import 'package:workout_app/services/run_phase.dart';
|
||||
|
||||
RunPoint _point(
|
||||
int i, {
|
||||
RunLink link = RunLink.continuous,
|
||||
double? altitude = 30,
|
||||
}) => RunPoint(
|
||||
time: DateTime.utc(2026, 11, 9, 12).add(Duration(seconds: i * 2)),
|
||||
latitude: 48.8584 + i * 0.00002,
|
||||
longitude: 2.2945 - i * 0.000013,
|
||||
altitudeM: altitude,
|
||||
distanceM: i * 6.25,
|
||||
link: link,
|
||||
);
|
||||
|
||||
RunCheckpoint _checkpoint({
|
||||
RunPhase phase = RunPhase.recording,
|
||||
List<RunPoint>? points,
|
||||
int? target = 330,
|
||||
}) => RunCheckpoint(
|
||||
startedAt: DateTime.utc(2026, 11, 9, 11, 59, 58),
|
||||
savedAt: DateTime.utc(2026, 11, 9, 12, 5),
|
||||
phase: phase,
|
||||
points: points ?? [for (var i = 0; i < 4; i++) _point(i)],
|
||||
movingSeconds: 6,
|
||||
distanceM: 18.75,
|
||||
km: 0,
|
||||
segmentBreak: phase == RunPhase.paused,
|
||||
jumps: 2,
|
||||
paceTargetSeconds: target,
|
||||
);
|
||||
|
||||
Map<String, Object?> _roundTripped(RunCheckpoint c) =>
|
||||
jsonDecode(jsonEncode(c.toJson())) as Map<String, Object?>;
|
||||
|
||||
void _expectSame(RunCheckpoint a, RunCheckpoint b) {
|
||||
expect(b.id, a.id);
|
||||
expect(b.startedAt, a.startedAt);
|
||||
expect(b.savedAt, a.savedAt);
|
||||
expect(b.phase, a.phase);
|
||||
expect(b.points, a.points);
|
||||
expect(b.movingSeconds, a.movingSeconds);
|
||||
expect(b.distanceM, a.distanceM);
|
||||
expect(b.km, a.km);
|
||||
expect(b.segmentBreak, a.segmentBreak);
|
||||
expect(b.jumps, a.jumps);
|
||||
expect(b.paceTargetSeconds, a.paceTargetSeconds);
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('round trip through JSON text', () {
|
||||
test('a recording checkpoint', () {
|
||||
final c = _checkpoint();
|
||||
_expectSame(c, RunCheckpoint.fromJson(_roundTripped(c)));
|
||||
});
|
||||
|
||||
test('a paused one with no pace target', () {
|
||||
final c = _checkpoint(phase: RunPhase.paused, target: null);
|
||||
final back = RunCheckpoint.fromJson(_roundTripped(c));
|
||||
_expectSame(c, back);
|
||||
expect(back.paceTargetSeconds, isNull);
|
||||
});
|
||||
|
||||
test('a run that has no fix yet', () {
|
||||
final c = _checkpoint(points: const []);
|
||||
final back = RunCheckpoint.fromJson(_roundTripped(c));
|
||||
_expectSame(c, back);
|
||||
expect(back.id, '2026-11-09T11:59:58Z');
|
||||
});
|
||||
|
||||
test('segment and bridge markers and a missing altitude survive', () {
|
||||
final c = _checkpoint(
|
||||
points: [
|
||||
_point(0),
|
||||
_point(1, link: RunLink.bridge, altitude: null),
|
||||
_point(2, link: RunLink.segmentStart),
|
||||
],
|
||||
);
|
||||
final back = RunCheckpoint.fromJson(_roundTripped(c));
|
||||
expect(back.points[1].link, RunLink.bridge);
|
||||
expect(back.points[1].altitudeM, isNull);
|
||||
expect(back.points[2].link, RunLink.segmentStart);
|
||||
_expectSame(c, back);
|
||||
});
|
||||
|
||||
test('the id is the first point time, like the saved track', () {
|
||||
expect(_checkpoint().id, '2026-11-09T12:00:00Z');
|
||||
});
|
||||
|
||||
test('many random shapes survive (seeded)', () {
|
||||
final rng = Random(20261117);
|
||||
for (var n = 0; n < 200; n++) {
|
||||
final count = rng.nextInt(40);
|
||||
final points = [
|
||||
for (var i = 0; i < count; i++)
|
||||
RunPoint(
|
||||
time: DateTime.utc(
|
||||
2026,
|
||||
11,
|
||||
9,
|
||||
12,
|
||||
).add(Duration(seconds: i * (1 + rng.nextInt(90)))),
|
||||
latitude: rng.nextDouble() * 180 - 90,
|
||||
longitude: rng.nextDouble() * 360 - 180,
|
||||
altitudeM: rng.nextBool() ? rng.nextDouble() * 4000 - 400 : null,
|
||||
distanceM: rng.nextDouble() * 50000,
|
||||
link: RunLink.values[rng.nextInt(RunLink.values.length)],
|
||||
),
|
||||
];
|
||||
final c = RunCheckpoint(
|
||||
startedAt: DateTime.utc(2026, 11, 9, 11, rng.nextInt(60)),
|
||||
savedAt: DateTime.utc(2026, 11, 9, 13, rng.nextInt(60)),
|
||||
phase: rng.nextBool() ? RunPhase.recording : RunPhase.paused,
|
||||
points: points,
|
||||
movingSeconds: rng.nextInt(20000),
|
||||
distanceM: rng.nextDouble() * 50000,
|
||||
km: rng.nextInt(50),
|
||||
segmentBreak: rng.nextBool(),
|
||||
jumps: rng.nextInt(5),
|
||||
paceTargetSeconds: rng.nextBool() ? 200 + rng.nextInt(400) : null,
|
||||
);
|
||||
_expectSame(c, RunCheckpoint.fromJson(_roundTripped(c)));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('fromJson rejects bad data with a FormatException', () {
|
||||
final good = _roundTripped(_checkpoint());
|
||||
|
||||
void rejects(String why, Map<String, Object?> Function() make) {
|
||||
test(why, () {
|
||||
expect(() => RunCheckpoint.fromJson(make()), throwsFormatException);
|
||||
});
|
||||
}
|
||||
|
||||
rejects('an unknown version', () => {...good, 'v': 99});
|
||||
rejects('no version', () => {...good}..remove('v'));
|
||||
rejects('a missing field', () => {...good}..remove('moving'));
|
||||
rejects('a wrongly typed field', () => {...good, 'moving': 'six'});
|
||||
rejects('a bad start time', () => {...good, 'startedAt': 'yesterday'});
|
||||
rejects('a non-string start time', () => {...good, 'startedAt': 5});
|
||||
rejects('idle as the phase', () => {...good, 'phase': 'idle'});
|
||||
rejects('finished as the phase', () => {...good, 'phase': 'finished'});
|
||||
rejects('an unknown phase', () => {...good, 'phase': 'dancing'});
|
||||
rejects('points that are not a list', () => {...good, 'points': 'many'});
|
||||
rejects(
|
||||
'a point that is not a list',
|
||||
() => {
|
||||
...good,
|
||||
'points': [5],
|
||||
},
|
||||
);
|
||||
rejects(
|
||||
'a short point',
|
||||
() => {
|
||||
...good,
|
||||
'points': [
|
||||
[1, 2.0],
|
||||
],
|
||||
},
|
||||
);
|
||||
rejects(
|
||||
'a point with a text coordinate',
|
||||
() => {
|
||||
...good,
|
||||
'points': [
|
||||
[1, 'x', 2.0, null, 3.0, 0],
|
||||
],
|
||||
},
|
||||
);
|
||||
rejects(
|
||||
'a point with a bad altitude',
|
||||
() => {
|
||||
...good,
|
||||
'points': [
|
||||
[1, 1.0, 2.0, 'high', 3.0, 0],
|
||||
],
|
||||
},
|
||||
);
|
||||
rejects(
|
||||
'a point with an unknown link',
|
||||
() => {
|
||||
...good,
|
||||
'points': [
|
||||
[1, 1.0, 2.0, null, 3.0, 7],
|
||||
],
|
||||
},
|
||||
);
|
||||
rejects('a non-numeric pace target', () => {...good, 'target': 'fast'});
|
||||
rejects('a non-bool segment break', () => {...good, 'segBreak': 1});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/services/run_gap_bridge.dart';
|
||||
|
||||
void main() {
|
||||
group('bridgeCredits (2:30 to 12:00 min/km)', () {
|
||||
test('a steady 5:00/km jog across a gap is credited', () {
|
||||
expect(bridgeCredits(stepM: 1000, gapSeconds: 300), isTrue);
|
||||
});
|
||||
|
||||
test('the pace bounds are inclusive', () {
|
||||
expect(bridgeCredits(stepM: 1000, gapSeconds: 150), isTrue); // 2:30
|
||||
expect(bridgeCredits(stepM: 1000, gapSeconds: 720), isTrue); // 12:00
|
||||
});
|
||||
|
||||
test('faster than 2:30/km is a vehicle: drawn, not credited', () {
|
||||
expect(bridgeCredits(stepM: 1000, gapSeconds: 149), isFalse);
|
||||
});
|
||||
|
||||
test('slower than 12:00/km is standing about: not credited', () {
|
||||
expect(bridgeCredits(stepM: 1000, gapSeconds: 721), isFalse);
|
||||
});
|
||||
|
||||
test('no movement or no time credits nothing', () {
|
||||
expect(bridgeCredits(stepM: 0, gapSeconds: 600), isFalse);
|
||||
expect(bridgeCredits(stepM: 100, gapSeconds: 0), isFalse);
|
||||
expect(bridgeCredits(stepM: -1, gapSeconds: 60), isFalse);
|
||||
});
|
||||
|
||||
test('the minimum speed constant matches the slowest pace', () {
|
||||
expect(kBridgeMinSpeedMps, closeTo(1000 / 720, 1e-9));
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,369 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/models/run_track.dart';
|
||||
import 'package:workout_app/services/gps_filter.dart';
|
||||
import 'package:workout_app/services/position_source.dart';
|
||||
import 'package:workout_app/services/run_checkpoint.dart';
|
||||
import 'package:workout_app/services/run_recorder.dart';
|
||||
|
||||
import '../run_test_fixtures.dart';
|
||||
|
||||
final DateTime _t0 = DateTime.utc(2026, 11, 9, 12);
|
||||
|
||||
/// A recorder plus everything it reports, on a clock the test moves.
|
||||
class _Host {
|
||||
_Host({
|
||||
ManualPositionSource? source,
|
||||
DateTime? at,
|
||||
Duration autoEnd = const Duration(hours: 5),
|
||||
}) : source = source ?? ManualPositionSource(),
|
||||
now = at ?? _t0 {
|
||||
recorder = RunRecorder(
|
||||
sourceFor: () => this.source,
|
||||
onKilometre: km.add,
|
||||
onSuggestFinish: suggestions.add,
|
||||
onAutoEnd: () => autoEnds++,
|
||||
onCheckpoint: checkpoints.add,
|
||||
clock: () => now,
|
||||
autoEndAfter: autoEnd,
|
||||
);
|
||||
}
|
||||
|
||||
final ManualPositionSource source;
|
||||
late final RunRecorder recorder;
|
||||
DateTime now;
|
||||
final km = <int>[];
|
||||
final suggestions = <RunSuggestion>[];
|
||||
final checkpoints = <RunCheckpoint>[];
|
||||
int autoEnds = 0;
|
||||
|
||||
/// Finishes inside `testWidgets`, where awaiting a stream cancel hangs the
|
||||
/// fake-async zone: it runs in the real one instead.
|
||||
Future<RunTrack?> finishIn(WidgetTester tester) async =>
|
||||
await tester.runAsync<RunTrack?>(recorder.finish);
|
||||
|
||||
/// Delivers [fixes]; inside `testWidgets` pass the tester, whose pump
|
||||
/// drains the queue where a real-time `pumpEventQueue` would hang.
|
||||
Future<void> feed(Iterable<GpsFix> fixes, {WidgetTester? tester}) async {
|
||||
for (final fix in fixes) {
|
||||
source.controller.add(fix);
|
||||
}
|
||||
await (tester?.pump() ?? pumpEventQueue());
|
||||
}
|
||||
}
|
||||
|
||||
RunCheckpoint _viaJson(RunCheckpoint c) => RunCheckpoint.fromJson(
|
||||
jsonDecode(jsonEncode(c.toJson())) as Map<String, Object?>,
|
||||
);
|
||||
|
||||
Future<RunCheckpoint> _checkpointAfter(int fixes, {bool pause = false}) async {
|
||||
final h = _Host();
|
||||
await h.recorder.start();
|
||||
await h.feed(straightRun(fixes));
|
||||
if (pause) h.recorder.pause();
|
||||
final c = h.recorder.checkpoint()!;
|
||||
await h.recorder.finish();
|
||||
h.recorder.dispose();
|
||||
return _viaJson(c);
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('checkpoint()', () {
|
||||
test('is null when idle and after finish', () async {
|
||||
final h = _Host();
|
||||
expect(h.recorder.checkpoint(), isNull);
|
||||
await h.recorder.start();
|
||||
expect(h.recorder.checkpoint(), isNotNull);
|
||||
await h.recorder.finish();
|
||||
expect(h.recorder.checkpoint(), isNull);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('holds the whole recording state', () async {
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 3)));
|
||||
await h.recorder.start();
|
||||
h.recorder.setPaceTarget(330);
|
||||
await h.feed(straightRun(10));
|
||||
final c = h.recorder.checkpoint()!;
|
||||
expect(c.startedAt, _t0.add(const Duration(minutes: 3)));
|
||||
expect(c.savedAt, h.now);
|
||||
expect(c.phase, RunPhase.recording);
|
||||
expect(c.points, hasLength(10));
|
||||
expect(c.distanceM, closeTo(54, 0.5));
|
||||
expect(c.movingSeconds, 18);
|
||||
expect(c.paceTargetSeconds, 330);
|
||||
expect(c.segmentBreak, isFalse);
|
||||
expect(c.id, '2026-11-09T12:00:00Z');
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('a pause is recorded with its segment break', () async {
|
||||
final c = await _checkpointAfter(5, pause: true);
|
||||
expect(c.phase, RunPhase.paused);
|
||||
expect(c.segmentBreak, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('onCheckpoint', () {
|
||||
test('fires on start, every accepted fix, pause and resume', () async {
|
||||
final h = _Host();
|
||||
await h.recorder.start();
|
||||
expect(h.checkpoints, hasLength(1));
|
||||
await h.feed(straightRun(3));
|
||||
expect(h.checkpoints, hasLength(4));
|
||||
await h.feed([fixAt(6, 18, accuracy: 99)]); // dropped: no checkpoint
|
||||
expect(h.checkpoints, hasLength(4));
|
||||
h.recorder.pause();
|
||||
h.recorder.resume();
|
||||
expect(h.checkpoints.map((c) => c.phase), [
|
||||
RunPhase.recording,
|
||||
RunPhase.recording,
|
||||
RunPhase.recording,
|
||||
RunPhase.recording,
|
||||
RunPhase.paused,
|
||||
RunPhase.recording,
|
||||
]);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
group('restore()', () {
|
||||
test('re-enters recording with the state and tells the host', () async {
|
||||
final saved = await _checkpointAfter(10);
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
|
||||
expect(await h.recorder.restore(saved), isTrue);
|
||||
expect(h.recorder.phase, RunPhase.recording);
|
||||
expect(h.recorder.seconds, 18);
|
||||
expect(h.recorder.distanceM, closeTo(54, 0.5));
|
||||
expect(h.recorder.livePoints.value, hasLength(10));
|
||||
expect(h.source.subscriptions, 1);
|
||||
expect(h.suggestions, [RunSuggestion.restored]);
|
||||
expect(h.autoEnds, 0);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('the dead time is bridged and credited at a running pace', () async {
|
||||
final saved = await _checkpointAfter(10); // last fix: 18 s, 54 m
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
|
||||
await h.recorder.restore(saved);
|
||||
await h.feed([fixAt(318, 954)]); // 300 s later, 900 m on: 3 m/s
|
||||
expect(h.recorder.distanceM, closeTo(954, 1));
|
||||
expect(h.recorder.seconds, 18 + 300);
|
||||
expect(h.recorder.livePoints.value.last.link, RunLink.bridge);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('a vehicle-speed gap is drawn but earns nothing', () async {
|
||||
final saved = await _checkpointAfter(10);
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
|
||||
await h.recorder.restore(saved);
|
||||
await h.feed([fixAt(78, 54 + 600)]); // 60 s, 600 m: 36 km/h
|
||||
expect(h.recorder.distanceM, closeTo(54, 0.5));
|
||||
expect(h.recorder.seconds, 18);
|
||||
expect(h.recorder.livePoints.value, hasLength(11));
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('kilometres already announced are not announced again', () async {
|
||||
final h0 = _Host();
|
||||
await h0.recorder.start();
|
||||
await h0.feed(straightRun(340)); // 2 km
|
||||
final saved = _viaJson(h0.recorder.checkpoint()!);
|
||||
expect(h0.km, [1, 2]);
|
||||
await h0.recorder.finish();
|
||||
h0.recorder.dispose();
|
||||
|
||||
final h = _Host(at: _t0.add(const Duration(hours: 1)));
|
||||
await h.recorder.restore(saved);
|
||||
await h.feed([fixAt(681, 2043)]); // still km 2
|
||||
expect(h.km, isEmpty);
|
||||
await h.feed([fixAt(1000, 2043 + 1000)]); // km 3 across a bridge
|
||||
expect(h.km, [3]);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('a paused run comes back paused, ignoring fixes', () async {
|
||||
final saved = await _checkpointAfter(5, pause: true);
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 5)));
|
||||
expect(await h.recorder.restore(saved), isTrue);
|
||||
expect(h.recorder.phase, RunPhase.paused);
|
||||
await h.feed([fixAt(300, 900)]);
|
||||
expect(h.recorder.livePoints.value, hasLength(5));
|
||||
h.recorder.resume();
|
||||
await h.feed([fixAt(310, 930)]);
|
||||
expect(h.recorder.livePoints.value.last.link, RunLink.segmentStart);
|
||||
expect(h.recorder.distanceM, closeTo(24, 0.5)); // nothing for the walk
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('the pace target comes back', () async {
|
||||
final h0 = _Host();
|
||||
await h0.recorder.start();
|
||||
h0.recorder.setPaceTarget(300);
|
||||
await h0.feed(straightRun(3));
|
||||
final saved = _viaJson(h0.recorder.checkpoint()!);
|
||||
h0.recorder.dispose();
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 1)));
|
||||
await h.recorder.restore(saved);
|
||||
expect(h.recorder.coach.target, 300);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('a run with no fix yet restores and then records', () async {
|
||||
final h0 = _Host();
|
||||
await h0.recorder.start();
|
||||
final saved = _viaJson(h0.recorder.checkpoint()!);
|
||||
h0.recorder.dispose();
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 1)));
|
||||
expect(await h.recorder.restore(saved), isTrue);
|
||||
await h.feed(straightRun(3));
|
||||
expect(h.recorder.livePoints.value, hasLength(3));
|
||||
final track = (await h.recorder.finish())!;
|
||||
expect(track.points, hasLength(3));
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('finishing a restored run saves one track with the bridge', () async {
|
||||
final saved = await _checkpointAfter(10);
|
||||
final h = _Host(at: _t0.add(const Duration(minutes: 10)));
|
||||
await h.recorder.restore(saved);
|
||||
await h.feed([fixAt(318, 954), fixAt(320, 960)]);
|
||||
final track = (await h.recorder.finish())!;
|
||||
expect(track.points, hasLength(12));
|
||||
expect(track.id, '2026-11-09T12:00:00Z');
|
||||
expect(track.totalSeconds, 18 + 300 + 2);
|
||||
expect(track.distanceM, closeTo(960, 1));
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test(
|
||||
'is refused (false, issue set) when location access is gone',
|
||||
() async {
|
||||
final saved = await _checkpointAfter(3);
|
||||
final source = ManualPositionSource(access: LocationAccess.denied);
|
||||
final h = _Host(source: source);
|
||||
expect(await h.recorder.restore(saved), isFalse);
|
||||
expect(h.recorder.phase, RunPhase.idle);
|
||||
expect(h.recorder.issue, RunIssue.denied);
|
||||
expect(h.suggestions, isEmpty);
|
||||
expect(source.subscriptions, 0);
|
||||
h.recorder.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test('is false when opening the source throws', () async {
|
||||
final saved = await _checkpointAfter(3);
|
||||
final h = _Host(source: _ThrowingSource());
|
||||
expect(await h.recorder.restore(saved), isFalse);
|
||||
expect(h.recorder.phase, RunPhase.idle);
|
||||
expect(h.recorder.issue, RunIssue.streamError);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('is false when a run is already going', () async {
|
||||
final saved = await _checkpointAfter(3);
|
||||
final h = _Host();
|
||||
await h.recorder.start();
|
||||
expect(await h.recorder.restore(saved), isFalse);
|
||||
expect(h.recorder.phase, RunPhase.recording);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test(
|
||||
'runs afterAccess (the foreground service) before listening',
|
||||
() async {
|
||||
final saved = await _checkpointAfter(3);
|
||||
final h = _Host();
|
||||
var served = false;
|
||||
await h.recorder.restore(saved, afterAccess: () async => served = true);
|
||||
expect(served, isTrue);
|
||||
h.recorder.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test('past 5 h of wall clock it auto-ends at once on restore', () async {
|
||||
final saved = await _checkpointAfter(10);
|
||||
final h = _Host(at: _t0.add(const Duration(hours: 5, seconds: 1)));
|
||||
await h.recorder.restore(saved);
|
||||
expect(h.autoEnds, 1);
|
||||
expect(h.suggestions, isEmpty);
|
||||
// The host now finishes; the run saves like a manual finish.
|
||||
expect(await h.recorder.finish(), isNotNull);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
group('suggestions and auto end, off the timer and the clock', () {
|
||||
testWidgets('no fix for 5 min suggests finishing, never ends', (
|
||||
tester,
|
||||
) async {
|
||||
final h = _Host();
|
||||
await h.recorder.start();
|
||||
await h.feed(straightRun(3), tester: tester);
|
||||
for (var i = 0; i < 61; i++) {
|
||||
h.now = h.now.add(const Duration(seconds: 5));
|
||||
await tester.pump(const Duration(seconds: 5));
|
||||
}
|
||||
expect(h.suggestions, [RunSuggestion.gpsLost]);
|
||||
expect(h.recorder.phase, RunPhase.recording);
|
||||
await h.finishIn(tester);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
testWidgets('5 h wall clock ends the run once, pauses included', (
|
||||
tester,
|
||||
) async {
|
||||
final h = _Host(autoEnd: const Duration(minutes: 2));
|
||||
await h.recorder.start();
|
||||
await h.feed(straightRun(3), tester: tester);
|
||||
h.recorder.pause();
|
||||
for (var i = 0; i < 30; i++) {
|
||||
h.now = h.now.add(const Duration(seconds: 5));
|
||||
await tester.pump(const Duration(seconds: 5));
|
||||
}
|
||||
expect(h.autoEnds, 1);
|
||||
expect(h.suggestions, isEmpty); // paused: only the auto end
|
||||
expect(await h.finishIn(tester), isNotNull);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
testWidgets('finish() stops the timer: nothing fires afterwards', (
|
||||
tester,
|
||||
) async {
|
||||
final h = _Host(autoEnd: const Duration(minutes: 1));
|
||||
await h.recorder.start();
|
||||
await h.feed(straightRun(3), tester: tester);
|
||||
await h.finishIn(tester);
|
||||
h.now = h.now.add(const Duration(hours: 1));
|
||||
await tester.pump(const Duration(minutes: 10));
|
||||
expect(h.autoEnds, 0);
|
||||
expect(h.suggestions, isEmpty);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
test('a car (jump-rejected fixes) suggests finishing', () async {
|
||||
final h = _Host();
|
||||
await h.recorder.start();
|
||||
await h.feed(straightRun(2));
|
||||
await h.feed([for (var s = 4; s <= 100; s += 2) fixAt(s, s * 10.0)]);
|
||||
expect(h.suggestions, [RunSuggestion.vehicleSpeed]);
|
||||
h.recorder.dispose();
|
||||
});
|
||||
|
||||
testWidgets('dispose cancels the watchdog timer', (tester) async {
|
||||
final h = _Host(autoEnd: const Duration(seconds: 1));
|
||||
await h.recorder.start();
|
||||
h.now = h.now.add(const Duration(hours: 1));
|
||||
h.recorder.dispose();
|
||||
await tester.pump(const Duration(seconds: 30));
|
||||
expect(h.autoEnds, 0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class _ThrowingSource extends ManualPositionSource {
|
||||
@override
|
||||
Stream<GpsFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
|
||||
throw StateError('provider gone');
|
||||
}
|
||||
@ -0,0 +1,262 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:workout_app/services/gps_filter.dart';
|
||||
import 'package:workout_app/services/run_recorder.dart';
|
||||
import 'package:workout_app/services/run_watchdog.dart';
|
||||
|
||||
import '../run_test_fixtures.dart';
|
||||
|
||||
final DateTime _start = DateTime.utc(2026, 11, 9, 12);
|
||||
|
||||
class _Rig {
|
||||
_Rig({this.autoEnd = const Duration(hours: 5)}) {
|
||||
dog = RunWatchdog(
|
||||
clock: () => now,
|
||||
onSuggest: suggestions.add,
|
||||
onAutoEnd: () => autoEnds++,
|
||||
autoEndAfter: autoEnd,
|
||||
);
|
||||
}
|
||||
|
||||
final Duration autoEnd;
|
||||
late final RunWatchdog dog;
|
||||
DateTime now = _start;
|
||||
final suggestions = <RunSuggestion>[];
|
||||
int autoEnds = 0;
|
||||
double metres = 0;
|
||||
|
||||
void advance(Duration d) {
|
||||
now = now.add(d);
|
||||
dog.check();
|
||||
}
|
||||
|
||||
/// [minutes] minutes with a fresh, motionless fix every minute.
|
||||
void idle(int minutes) {
|
||||
for (var i = 0; i < minutes; i++) {
|
||||
now = now.add(const Duration(minutes: 1));
|
||||
fix();
|
||||
dog.check();
|
||||
}
|
||||
}
|
||||
|
||||
/// An accepted fix at the current clock, [stepM] further on.
|
||||
void fix({double stepM = 0, int secondsIntoRun = 0}) {
|
||||
metres += stepM;
|
||||
dog.onFix(fixAt(secondsIntoRun, metres), FixVerdict.accepted, metres);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('stationary (under 50 m in 10 min)', () {
|
||||
test('fires after 10 idle minutes and then every 10, with no limit', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.idle(30);
|
||||
expect(r.suggestions, List.filled(3, RunSuggestion.stationary));
|
||||
});
|
||||
|
||||
test('does not fire before 10 minutes', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.idle(9);
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
|
||||
test('50 m of progress in the window stays quiet and re-arms', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.idle(4);
|
||||
r.fix(stepM: 50);
|
||||
r.idle(6);
|
||||
expect(r.suggestions, isEmpty);
|
||||
// The next window starts at 10:00 with 50 m banked: 49 m is too few.
|
||||
r.fix(stepM: 49);
|
||||
r.idle(10);
|
||||
expect(r.suggestions, [RunSuggestion.stationary]);
|
||||
});
|
||||
|
||||
test('nothing fires while paused, and resume restarts the window', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.idle(8);
|
||||
r.dog.pause();
|
||||
r.advance(const Duration(minutes: 30));
|
||||
expect(r.suggestions, isEmpty);
|
||||
r.dog.resume();
|
||||
r.idle(9);
|
||||
expect(r.suggestions, isEmpty);
|
||||
r.idle(1);
|
||||
expect(r.suggestions, [RunSuggestion.stationary]);
|
||||
});
|
||||
});
|
||||
|
||||
group('no GPS fix for 5 min', () {
|
||||
test('fires once per loss, not before 5 minutes', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.advance(const Duration(minutes: 4, seconds: 59));
|
||||
expect(r.suggestions, isEmpty);
|
||||
r.advance(const Duration(seconds: 1));
|
||||
expect(r.suggestions, [RunSuggestion.gpsLost]);
|
||||
r.advance(const Duration(minutes: 2));
|
||||
expect(r.suggestions, [RunSuggestion.gpsLost]);
|
||||
});
|
||||
|
||||
test('a fix re-arms it', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.advance(const Duration(minutes: 5));
|
||||
r.fix();
|
||||
r.advance(const Duration(minutes: 5));
|
||||
expect(
|
||||
r.suggestions.where((s) => s == RunSuggestion.gpsLost),
|
||||
hasLength(2),
|
||||
);
|
||||
});
|
||||
|
||||
test('fixes the filter rejects as too inaccurate do not count', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.advance(const Duration(minutes: 4));
|
||||
r.dog.onFix(fixAt(0, 0), FixVerdict.inaccurate, 0);
|
||||
r.dog.onFix(fixAt(2, 0), FixVerdict.mocked, 0);
|
||||
r.advance(const Duration(minutes: 1));
|
||||
expect(r.suggestions, contains(RunSuggestion.gpsLost));
|
||||
});
|
||||
|
||||
test('nothing fires while paused', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.dog.pause();
|
||||
r.advance(const Duration(minutes: 20));
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('vehicle speed (over 25 km/h for 60 s)', () {
|
||||
// 10 m/s is 36 km/h. Rejected jump fixes still count: a car never
|
||||
// produces an accepted fix, the filter drops it as too fast.
|
||||
void drive(_Rig r, {required int seconds, required double mps}) {
|
||||
for (var s = 0; s <= seconds; s += 2) {
|
||||
r.dog.onFix(fixAt(s, s * mps), FixVerdict.tooFast, r.metres);
|
||||
}
|
||||
}
|
||||
|
||||
test('fires once after 60 s of it', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
drive(r, seconds: 120, mps: 10);
|
||||
expect(r.suggestions, [RunSuggestion.vehicleSpeed]);
|
||||
});
|
||||
|
||||
test('59 s is not sustained', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
drive(r, seconds: 58, mps: 10);
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
|
||||
test('slowing down resets it', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
drive(r, seconds: 50, mps: 10);
|
||||
r.dog.onFix(fixAt(52, 500), FixVerdict.accepted, 0); // standing
|
||||
for (var s = 54; s <= 100; s += 2) {
|
||||
r.dog.onFix(fixAt(s, 500 + (s - 52) * 10.0), FixVerdict.tooFast, 0);
|
||||
}
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
|
||||
test('running speed never fires it', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
drive(r, seconds: 300, mps: 3);
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
|
||||
test('a second ride after slowing fires again', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
drive(r, seconds: 70, mps: 10);
|
||||
r.dog.onFix(fixAt(72, 700), FixVerdict.accepted, 0);
|
||||
for (var s = 74; s <= 200; s += 2) {
|
||||
r.dog.onFix(fixAt(s, 700 + (s - 72) * 10.0), FixVerdict.tooFast, 0);
|
||||
}
|
||||
expect(r.suggestions, [
|
||||
RunSuggestion.vehicleSpeed,
|
||||
RunSuggestion.vehicleSpeed,
|
||||
]);
|
||||
});
|
||||
|
||||
test('same-second fixes and mocked fixes are ignored', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.dog.onFix(fixAt(0, 0), FixVerdict.accepted, 0);
|
||||
r.dog.onFix(fixAt(0, 500), FixVerdict.tooFast, 0);
|
||||
r.dog.onFix(fixAt(2, 900), FixVerdict.mocked, 0);
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('auto end after 5 h of wall clock', () {
|
||||
test('fires once at 5 h, pauses and gaps included', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.dog.pause();
|
||||
r.advance(const Duration(hours: 4, minutes: 59));
|
||||
expect(r.autoEnds, 0);
|
||||
r.advance(const Duration(minutes: 1));
|
||||
expect(r.autoEnds, 1);
|
||||
r.advance(const Duration(hours: 1));
|
||||
expect(r.autoEnds, 1);
|
||||
});
|
||||
|
||||
test('a shortened limit is honoured', () {
|
||||
final r = _Rig(autoEnd: const Duration(minutes: 3))..dog.begin(_start);
|
||||
r.advance(const Duration(minutes: 3));
|
||||
expect(r.autoEnds, 1);
|
||||
});
|
||||
|
||||
test('restored past the limit ends at once, with no restore hint', () {
|
||||
final r = _Rig();
|
||||
r.now = _start.add(const Duration(hours: 6));
|
||||
r.dog.restored(_start, paused: false, distanceM: 0);
|
||||
expect(r.autoEnds, 1);
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
|
||||
test('restored inside the limit suggests finishing', () {
|
||||
final r = _Rig();
|
||||
r.now = _start.add(const Duration(hours: 1));
|
||||
r.dog.restored(_start, paused: false, distanceM: 2000);
|
||||
expect(r.autoEnds, 0);
|
||||
expect(r.suggestions, [RunSuggestion.restored]);
|
||||
});
|
||||
|
||||
test('restored while paused stays paused: only the restore hint', () {
|
||||
final r = _Rig();
|
||||
r.now = _start.add(const Duration(minutes: 30));
|
||||
r.dog.restored(_start, paused: true, distanceM: 0);
|
||||
r.advance(const Duration(hours: 1));
|
||||
expect(r.suggestions, [RunSuggestion.restored]);
|
||||
});
|
||||
|
||||
test('stop() silences everything and is safe twice', () {
|
||||
final r = _Rig()..dog.begin(_start);
|
||||
r.dog.stop();
|
||||
r.dog.stop();
|
||||
r.advance(const Duration(hours: 6));
|
||||
expect(r.suggestions, isEmpty);
|
||||
expect(r.autoEnds, 0);
|
||||
});
|
||||
|
||||
test('fix and pause calls before begin are harmless', () {
|
||||
final r = _Rig();
|
||||
r.dog.pause();
|
||||
r.dog.resume();
|
||||
r.fix();
|
||||
r.dog.check();
|
||||
expect(r.suggestions, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('the timer, not a fix, drives the checks', (tester) async {
|
||||
var now = _start;
|
||||
final suggestions = <RunSuggestion>[];
|
||||
final dog = RunWatchdog(
|
||||
clock: () => now,
|
||||
onSuggest: suggestions.add,
|
||||
onAutoEnd: () {},
|
||||
)..begin(_start);
|
||||
for (var i = 0; i < 61; i++) {
|
||||
now = now.add(const Duration(seconds: 5));
|
||||
await tester.pump(const Duration(seconds: 5));
|
||||
}
|
||||
expect(suggestions, contains(RunSuggestion.gpsLost));
|
||||
dog.stop();
|
||||
});
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user