The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
401 lines
20 KiB
Dart
401 lines
20 KiB
Dart
// Health ▸ Activity (as on the web page's Activity tab), from the Pi's summaries: tiles (steps, workouts,
|
||
// fitness · form, vitality), steps and energy per day, training (fitness / fatigue / form) and the
|
||
// workouts — tap one for its heart rate on the zone bands and time in zones (WorkoutPage).
|
||
import 'dart:math';
|
||
|
||
import 'package:flutter/material.dart';
|
||
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import '../widgets/bar_chart.dart';
|
||
import '../widgets/line_chart.dart';
|
||
import 'body_page.dart' show dm, dmy;
|
||
import 'cycle_model.dart' show iso, parseDay, today;
|
||
import 'range.dart';
|
||
import 'summaries.dart';
|
||
|
||
const vitalityGoal = 150; // intensity minutes a week (calc.VITALITY_GOAL, WHO)
|
||
const zoneNames = ['Resting', 'Warm-up', 'Fat burn', 'Aerobic', 'Anaerobic', 'Maximum'];
|
||
const zoneColors = [Color(0xFF4A5266), Color(0xFF8FA3BF), Color(0xFF5CC8FF), Color(0xFF7FD6A3), Color(0xFFFFB33A), Color(0xFFFF6B7A)];
|
||
const _fitC = Color(0xFF5CC8FF), _fatC = Color(0xFFFF8FC8);
|
||
|
||
/// watch.FORM
|
||
(String, String) formLabel(double v) => v < -30
|
||
? ('Overload', 'fatigue far above fitness — rest soon')
|
||
: v < -10
|
||
? ('Building', 'training hard, fitness rising')
|
||
: v < 10
|
||
? ('Neutral', 'steady')
|
||
: ('Fresh', 'rested, ready for a hard session');
|
||
|
||
/// watch.hm: minutes → "1h 05m"
|
||
String hm(num? minutes) {
|
||
if (minutes == null) return '—';
|
||
final m = minutes.round();
|
||
return '${m ~/ 60}h ${(m % 60).toString().padLeft(2, '0')}m';
|
||
}
|
||
|
||
String thousands(num v) => v.round().toString().replaceAllMapped(RegExp(r'\B(?=(\d{3})+$)'), (_) => ',');
|
||
|
||
class ActivityPage extends StatelessWidget {
|
||
const ActivityPage({super.key, required this.sync, required this.range});
|
||
final SyncService sync;
|
||
final HealthRange range;
|
||
|
||
@override
|
||
Widget build(BuildContext context) => ListenableBuilder(
|
||
listenable: Listenable.merge([sync, range]),
|
||
builder: (context, _) {
|
||
final sm = Summaries(sync.store);
|
||
final days = sm.all('day');
|
||
final wks = sm.all('workout');
|
||
if (days.isEmpty && wks.isEmpty) {
|
||
return const Center(child: Padding(
|
||
padding: EdgeInsets.all(24),
|
||
child: Text('Nothing from the band yet — it comes from the dashboard once it has synced.',
|
||
textAlign: TextAlign.center, style: TextStyle(color: muted)),
|
||
));
|
||
}
|
||
final now = today();
|
||
final first = parseDay([...days, ...wks].map((x) => x['_day'] as String).reduce((a, b) => a.compareTo(b) < 0 ? a : b));
|
||
final a = range.from(first, now);
|
||
bool inRange(Map x) => !parseDay(x['_day'] as String).isBefore(a);
|
||
final rd = days.where(inRange).toList(), rw = wks.where(inRange).toList();
|
||
DateTime at(Map x) => parseDay(x['_day'] as String);
|
||
|
||
final steps = [for (final x in rd) if (x['steps'] != null) (at(x), (x['steps'] as num).toDouble())];
|
||
final energy = [
|
||
for (final x in rd)
|
||
if (x['energy'] != null && (x['steps'] != null || rw.any((w) => w['_day'] == x['_day'])))
|
||
(at(x), ((x['energy'] as Map)['total'] as num).toDouble())
|
||
];
|
||
final todays = days.isNotEmpty && days.last['_day'] == iso(now) ? days.last : null;
|
||
final train = [for (final x in days) if (x['fitness'] != null) x];
|
||
final cur = train.isEmpty ? null : train.last;
|
||
final vit = days.where((x) => now.difference(at(x)).inDays < 7).fold<num>(0, (s, x) => s + ((x['vitality'] as num?) ?? 0));
|
||
double avg(List<(DateTime, double)> xs) => xs.isEmpty ? 0 : xs.map((p) => p.$2).reduce((p, q) => p + q) / xs.length;
|
||
final mins = rw.fold<num>(0, (s, w) => s + (w['minutes'] as num)), kcal = rw.fold<num>(0, (s, w) => s + ((w['kcal'] as num?) ?? 0));
|
||
final wide = MediaQuery.of(context).size.width >= 700;
|
||
|
||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
|
||
GridView.count(
|
||
crossAxisCount: wide ? 4 : 2,
|
||
shrinkWrap: true, physics: const NeverScrollableScrollPhysics(),
|
||
mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75,
|
||
children: [
|
||
_tile('Steps', steps.isEmpty ? '—' : thousands(avg(steps)), 'a day · today ${todays?['steps'] == null ? '—' : thousands(todays!['steps'] as num)}',
|
||
'The band\'s steps, the average day of the ${steps.length} days with steps in this period'),
|
||
_tile('Workouts', '${rw.length}', '${hm(mins)} · ${thousands(kcal)} kcal',
|
||
'Workouts in this period: their time and the energy above resting (from heart rate)'),
|
||
_tile('Fitness · form', cur == null ? '—' : '${(cur['fitness'] as num).round()} · ${(cur['form'] as num).round()}',
|
||
cur == null ? 'no workouts yet' : formLabel((cur['form'] as num).toDouble()).$1,
|
||
'Fitness = your training load over 42 days, fatigue over 7, form = fitness − fatigue.'
|
||
'${cur == null ? '' : ' Now: ${formLabel((cur['form'] as num).toDouble()).$2}.'}'),
|
||
_tile('Vitality', '${vit.round()} / $vitalityGoal', 'intensity minutes, 7 days',
|
||
'Moderate minutes + 2 × vigorous ones, from the whole day\'s heart rate — WHO: at least 150 a week',
|
||
color: vit >= vitalityGoal ? good : null),
|
||
],
|
||
),
|
||
const SizedBox(height: 12),
|
||
_card('Steps', 'The band\'s steps per day (per week from 4 months: the average day)',
|
||
BarChart(points: steps, from: a, to: now, color: good, range: range,
|
||
fmt: (v) => '${thousands(v)} steps')),
|
||
const SizedBox(height: 12),
|
||
if (energy.isNotEmpty) ...[
|
||
_card('Energy', 'Estimated energy a day: resting (Mifflin–St Jeor) + walking (steps outside workouts) '
|
||
'+ workouts (heart rate). Average ${thousands(avg(energy))} kcal a day.',
|
||
BarChart(points: energy, from: a, to: now, color: accent, fmt: (v) => '${thousands(v)} kcal')),
|
||
const SizedBox(height: 12),
|
||
],
|
||
if (train.isNotEmpty) ...[
|
||
_card('Training', 'Fitness (42-day load), fatigue (7-day load) and form = fitness − fatigue. '
|
||
'Below −10: building, below −30: overload; above 10: fresh.',
|
||
Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Wrap(spacing: 14, children: [
|
||
for (final (n, col) in [('Fitness', _fitC), ('Fatigue', _fatC), ('Form', accent)])
|
||
Row(mainAxisSize: MainAxisSize.min, children: [
|
||
Container(width: 10, height: 10, decoration: BoxDecoration(color: col, shape: BoxShape.circle)),
|
||
const SizedBox(width: 5), Text(n, style: const TextStyle(color: muted, fontSize: 12.5)),
|
||
]),
|
||
]),
|
||
const SizedBox(height: 6),
|
||
LineChart(from: a, to: now, decimals: 0, series: [
|
||
Series('Fitness', [for (final x in train) (at(x), (x['fitness'] as num).toDouble())], _fitC),
|
||
Series('Fatigue', [for (final x in train) (at(x), (x['fatigue'] as num).toDouble())], _fatC),
|
||
Series('Form', [for (final x in train) (at(x), (x['form'] as num).toDouble())], accent),
|
||
]),
|
||
])),
|
||
const SizedBox(height: 12),
|
||
],
|
||
_workouts(context, rw),
|
||
]);
|
||
},
|
||
);
|
||
|
||
Widget _tile(String label, String value, String sub, String tip, {Color? color}) => Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
showDuration: const Duration(seconds: 6),
|
||
message: tip,
|
||
child: Card(child: Padding(
|
||
padding: const EdgeInsets.all(12),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [
|
||
Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||
FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: color))),
|
||
Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)),
|
||
]),
|
||
)),
|
||
);
|
||
|
||
Widget _card(String title, String tip, Widget child) => Card(child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 8, 10, 10),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Row(children: [
|
||
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||
_info(tip),
|
||
]),
|
||
child,
|
||
]),
|
||
));
|
||
|
||
Widget _workouts(BuildContext context, List<Map<String, dynamic>> rw) {
|
||
final rows = rw.reversed.take(60).toList();
|
||
return Card(child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 8, 10, 6),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Row(children: [
|
||
const Expanded(child: Text('Workouts', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||
_info('Calories = above resting, from heart rate. Effect = this workout\'s load vs your usual one (6 weeks before). '
|
||
'The strip = time in each heart-rate zone.'),
|
||
]),
|
||
if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 12), child: Text('None in this period', style: TextStyle(color: muted))),
|
||
for (final w in rows)
|
||
InkWell(
|
||
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => WorkoutPage(w: w))),
|
||
child: Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Row(children: [
|
||
Expanded(child: Text(w['name'] as String, style: const TextStyle(fontWeight: FontWeight.bold))),
|
||
Text('${(w['kcal'] as num?)?.round() ?? '—'} kcal', style: const TextStyle(color: accent)),
|
||
]),
|
||
Text([dmy(parseDay(w['_day'] as String)), hm(w['minutes'] as num), if (w['avg_hr'] != null) '${(w['avg_hr'] as num).round()} bpm', if (w['effect'] != null) w['effect']].join(' · '),
|
||
style: const TextStyle(color: muted, fontSize: 12.5)),
|
||
const SizedBox(height: 5),
|
||
ZoneStrip(pct: ((w['zone_pct'] as List?) ?? const []).cast<num>()),
|
||
]),
|
||
),
|
||
),
|
||
if (rw.length > rows.length)
|
||
Padding(padding: const EdgeInsets.only(bottom: 6), child: Text('… and ${rw.length - rows.length} more', style: const TextStyle(color: muted))),
|
||
]),
|
||
));
|
||
}
|
||
}
|
||
|
||
Widget _info(String tip) => Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
showDuration: const Duration(seconds: 8),
|
||
message: tip,
|
||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
|
||
);
|
||
|
||
class ZoneStrip extends StatelessWidget {
|
||
const ZoneStrip({super.key, required this.pct, this.height = 6});
|
||
final List<num> pct;
|
||
final double height;
|
||
@override
|
||
Widget build(BuildContext context) => ClipRRect(
|
||
borderRadius: BorderRadius.circular(3),
|
||
child: SizedBox(height: height, child: Row(children: [
|
||
for (var i = 0; i < pct.length && i < zoneColors.length; i++)
|
||
if (pct[i] > 0) Expanded(flex: max(1, pct[i].round()), child: Container(color: zoneColors[i])),
|
||
if (pct.every((p) => p <= 0)) Expanded(child: Container(color: card2)),
|
||
])),
|
||
);
|
||
}
|
||
|
||
/// One workout (the web's workout page): stats, heart rate on the zone bands, time in zones.
|
||
class WorkoutPage extends StatelessWidget {
|
||
const WorkoutPage({super.key, required this.w});
|
||
final Map<String, dynamic> w;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final start = DateTime.parse(w['start'] as String);
|
||
final zones = ((w['zones'] as List?) ?? const []).cast<num>(), pct = ((w['zone_pct'] as List?) ?? const []).cast<num>();
|
||
final bounds = ((w['bounds'] as List?) ?? const []).cast<num>();
|
||
final hr = [for (final p in (w['hr'] as List? ?? const [])) ((p as List)[0] as num, p[1] as num)];
|
||
String t(DateTime d) => d.toIso8601String().substring(11, 16);
|
||
final end = DateTime.parse(w['end'] as String);
|
||
final stats = [
|
||
('Time', hm(w['minutes'] as num)),
|
||
('Calories', '${(w['kcal'] as num?)?.round() ?? '—'} kcal'),
|
||
('Average', w['avg_hr'] == null ? '—' : '${(w['avg_hr'] as num).round()} bpm'),
|
||
('Highest', w['max_hr'] == null ? '—' : '${w['max_hr']} bpm'),
|
||
if (w['distance'] != null) ('Distance', '${((w['distance'] as num) / 1000).toStringAsFixed(2)} km'),
|
||
if (w['steps'] != null && (w['steps'] as num) > 0) ('Steps', thousands(w['steps'] as num)),
|
||
if (w['load'] != null) ('Load', '${(w['load'] as num).round()}'),
|
||
if (w['effect'] != null) ('Effect', w['effect'] as String),
|
||
];
|
||
return Scaffold(
|
||
appBar: AppBar(title: Text(w['name'] as String)),
|
||
body: ListView(padding: const EdgeInsets.all(12), children: [
|
||
Text('${dm(start)} ${start.year} · ${t(start)} – ${t(end)}', style: const TextStyle(color: muted)),
|
||
const SizedBox(height: 10),
|
||
Card(child: Padding(
|
||
padding: const EdgeInsets.all(12),
|
||
child: Wrap(spacing: 18, runSpacing: 10, children: [
|
||
for (final (l, v) in stats)
|
||
Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
message: switch (l) {
|
||
'Calories' => 'Above resting, from your heart rate (with resting: ${(w['kcal_total'] as num?)?.round() ?? '—'} kcal)',
|
||
'Load' => 'Training load (TRIMP): minutes × how hard, from heart rate',
|
||
'Effect' => 'This load vs your usual one (the workouts of the 6 weeks before${w['usual'] == null ? '' : ': ${(w['usual'] as num).round()}'})',
|
||
_ => l,
|
||
},
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||
Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)),
|
||
Text(v, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)),
|
||
]),
|
||
),
|
||
]),
|
||
)),
|
||
const SizedBox(height: 12),
|
||
if (hr.length > 1)
|
||
Card(child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(8, 12, 12, 8),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
const Padding(padding: EdgeInsets.only(left: 6, bottom: 8), child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||
_HrGraph(hr: hr, bounds: bounds, start: start, seconds: end.difference(start).inSeconds.toDouble()),
|
||
]),
|
||
)),
|
||
const SizedBox(height: 12),
|
||
if (zones.isNotEmpty)
|
||
Card(child: Padding(
|
||
padding: const EdgeInsets.all(12),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
const Text('Time in zones', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
|
||
const SizedBox(height: 8),
|
||
for (var i = zones.length - 1; i >= 0; i--)
|
||
Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||
child: Row(children: [
|
||
SizedBox(width: 118, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||
Text(zoneNames[i]),
|
||
Text(_range(i, bounds), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||
])),
|
||
Expanded(child: ClipRRect(
|
||
borderRadius: BorderRadius.circular(3),
|
||
child: LinearProgressIndicator(value: (i < pct.length ? pct[i] : 0) / 100, minHeight: 8,
|
||
color: zoneColors[i], backgroundColor: card2),
|
||
)),
|
||
SizedBox(width: 90, child: Text('${(zones[i] / 60).round()} min · ${i < pct.length ? pct[i] : 0} %',
|
||
textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))),
|
||
]),
|
||
),
|
||
]),
|
||
)),
|
||
]),
|
||
);
|
||
}
|
||
|
||
static String _range(int i, List<num> b) {
|
||
if (b.isEmpty) return '';
|
||
if (i == 0) return 'under ${b[0]}';
|
||
return i < b.length ? '${b[i - 1]}–${b[i] - 1} bpm' : '${b[i - 1]}+ bpm';
|
||
}
|
||
}
|
||
|
||
class _HrGraph extends StatefulWidget {
|
||
const _HrGraph({required this.hr, required this.bounds, required this.start, required this.seconds});
|
||
final List<(num, num)> hr; // (seconds from start, bpm)
|
||
final List<num> bounds;
|
||
final DateTime start;
|
||
final double seconds;
|
||
@override
|
||
State<_HrGraph> createState() => _HrGraphState();
|
||
}
|
||
|
||
class _HrGraphState extends State<_HrGraph> {
|
||
int? hit;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final h = hit == null ? null : widget.hr[hit!];
|
||
return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
LayoutBuilder(builder: (context, box) {
|
||
void pick(Offset o) {
|
||
final s = (o.dx - 34) / (box.maxWidth - 34) * widget.seconds;
|
||
var best = 0;
|
||
for (var i = 1; i < widget.hr.length; i++) {
|
||
if ((widget.hr[i].$1 - s).abs() < (widget.hr[best].$1 - s).abs()) best = i;
|
||
}
|
||
setState(() => hit = best);
|
||
}
|
||
|
||
return GestureDetector(
|
||
onTapDown: (d) => pick(d.localPosition),
|
||
onHorizontalDragUpdate: (d) => pick(d.localPosition),
|
||
child: CustomPaint(size: Size(box.maxWidth, 200), painter: _HrPainter(widget, hit)),
|
||
);
|
||
}),
|
||
SizedBox(
|
||
height: 20,
|
||
child: h == null
|
||
? const Text('Tap the graph for a minute\'s heart rate', textAlign: TextAlign.center, style: TextStyle(color: muted, fontSize: 12.5))
|
||
: Text('${(h.$1 / 60).floor()} min: ${h.$2} bpm', textAlign: TextAlign.center, style: const TextStyle(fontSize: 13)),
|
||
),
|
||
]);
|
||
}
|
||
}
|
||
|
||
class _HrPainter extends CustomPainter {
|
||
_HrPainter(this.g, this.hit);
|
||
final _HrGraph g;
|
||
final int? hit;
|
||
|
||
@override
|
||
void paint(Canvas c, Size size) {
|
||
const ml = 34.0, mb = 16.0, mt = 4.0;
|
||
final vs = g.hr.map((p) => p.$2.toDouble());
|
||
final lo = (min(vs.reduce(min), g.bounds.isEmpty ? 999 : g.bounds.first.toDouble()) / 10).floor() * 10.0 - 5;
|
||
final hi = (vs.reduce(max) / 10).ceil() * 10.0 + 5;
|
||
final h = size.height - mb - mt, w = size.width - ml;
|
||
double y(double v) => mt + h - h * (v - lo) / (hi - lo);
|
||
double x(num s) => ml + w * s / max(1, g.seconds);
|
||
// zone bands (z1…z5), faint
|
||
for (var i = 0; i < g.bounds.length; i++) {
|
||
final top = i + 1 < g.bounds.length ? g.bounds[i + 1].toDouble() : hi;
|
||
final a = y(min(top, hi)), b = y(max(g.bounds[i].toDouble(), lo));
|
||
if (b > a) c.drawRect(Rect.fromLTRB(ml, a, size.width, b), Paint()..color = zoneColors[i + 1].withValues(alpha: .13));
|
||
}
|
||
final txt = const TextStyle(color: muted, fontSize: 10.5);
|
||
void label(String s, Offset o, {bool right = false}) {
|
||
final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout();
|
||
tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0));
|
||
}
|
||
|
||
for (var v = (lo / 20).ceil() * 20.0; v <= hi; v += 20) {
|
||
label('${v.round()}', Offset(ml - 4, y(v)), right: true);
|
||
}
|
||
final mins = g.seconds / 60, every = mins <= 30 ? 5 : mins <= 75 ? 15 : mins <= 150 ? 30 : 60;
|
||
for (var m = 0; m <= mins; m += every) {
|
||
label('$m′', Offset(x(m * 60), size.height - mb + 3));
|
||
}
|
||
final path = Path();
|
||
for (var i = 0; i < g.hr.length; i++) {
|
||
final p = Offset(x(g.hr[i].$1), y(g.hr[i].$2.toDouble()));
|
||
i == 0 ? path.moveTo(p.dx, p.dy) : path.lineTo(p.dx, p.dy);
|
||
}
|
||
c.drawPath(path, Paint()..color = const Color(0xFFFF6B7A)..strokeWidth = 2..style = PaintingStyle.stroke..strokeJoin = StrokeJoin.round);
|
||
if (hit != null) {
|
||
final p = Offset(x(g.hr[hit!].$1), y(g.hr[hit!].$2.toDouble()));
|
||
c.drawLine(Offset(p.dx, mt), Offset(p.dx, size.height - mb), Paint()..color = muted.withValues(alpha: .5));
|
||
c.drawCircle(p, 4, Paint()..color = Colors.white);
|
||
}
|
||
}
|
||
|
||
@override
|
||
bool shouldRepaint(covariant _HrPainter old) => true;
|
||
}
|