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>
309 lines
15 KiB
Dart
309 lines
15 KiB
Dart
// Health ▸ Heart (as on the web page's Heart tab): heart rate from the band (the Pi's summaries:
|
||
// the latest day, resting, lowest / highest / resting per day), then the vitals — Blood pressure and
|
||
// Blood oxygen, each its own card: latest + category (ESC 2024 / SpO₂ bands), 30-day average, chart,
|
||
// the readings (tap = edit) and + Add.
|
||
import 'package:flutter/material.dart';
|
||
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import '../widgets/line_chart.dart';
|
||
import 'body_model.dart';
|
||
import 'body_page.dart' show classColor, dm, dmy;
|
||
import 'cycle_model.dart' show day, parseDay, plus, today;
|
||
import 'range.dart';
|
||
import 'summaries.dart';
|
||
|
||
String _hm(DateTime t) => t.toIso8601String().substring(11, 16);
|
||
|
||
class HeartPage extends StatefulWidget {
|
||
const HeartPage({super.key, required this.sync, required this.range});
|
||
final SyncService sync;
|
||
final HealthRange range;
|
||
@override
|
||
State<HeartPage> createState() => _HeartPageState();
|
||
}
|
||
|
||
class _HeartPageState extends State<HeartPage> {
|
||
final shown = {'bp': 5, 'ox': 5};
|
||
|
||
@override
|
||
Widget build(BuildContext context) => ListenableBuilder(
|
||
listenable: Listenable.merge([widget.sync, widget.range]),
|
||
builder: (context, _) {
|
||
final all = vitals(widget.sync.store);
|
||
final bp = all.where((v) => v.isBp).toList(), ox = all.where((v) => v.spo2 != null).toList();
|
||
return LayoutBuilder(builder: (context, box) {
|
||
final cards = [_bp(bp), _ox(ox)];
|
||
final hrCard = _hr();
|
||
return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [
|
||
if (hrCard != null) ...[hrCard, const SizedBox(height: 12)],
|
||
if (box.maxWidth >= 700)
|
||
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||
Expanded(child: cards[0]), const SizedBox(width: 12), Expanded(child: cards[1])])
|
||
else ...[cards[0], const SizedBox(height: 12), cards[1]],
|
||
]);
|
||
});
|
||
},
|
||
);
|
||
|
||
/// Heart rate from the band (the Pi's day summaries): the latest day's low – high, the resting rate
|
||
/// used for zones / calories, and lowest / highest / resting per day over the period.
|
||
Widget? _hr() {
|
||
final sm = Summaries(widget.sync.store);
|
||
final days = sm.all('day').where((x) => x['hr'] != null).toList();
|
||
if (days.isEmpty) return null;
|
||
final person = sm.meta('person') ?? {};
|
||
final last = days.last, h = (last['hr'] as Map).cast<String, dynamic>();
|
||
final from = widget.range.from(parseDay(days.first['_day'] as String), today());
|
||
List<(DateTime, double)> pts(String k) => [
|
||
for (final x in days)
|
||
if ((x['hr'] as Map)[k] != null) (parseDay(x['_day'] as String), ((x['hr'] as Map)[k] as num).toDouble())
|
||
];
|
||
final lastDay = parseDay(last['_day'] as String);
|
||
return Card(
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Row(children: [
|
||
const Expanded(child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||
Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
showDuration: const Duration(seconds: 8),
|
||
message: 'From your band (Gadgetbridge → the dashboard). Resting = the median of the last 90 days '
|
||
'${person['rest_set'] == true ? '(your setting)' : '(worked out)'}; max ${person['hrmax'] ?? '—'} bpm. '
|
||
'Zones and workout calories use both.',
|
||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)),
|
||
),
|
||
]),
|
||
Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||
Text('${h['low'] ?? '—'}–${h['high'] ?? '—'}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
|
||
const Text(' bpm', style: TextStyle(color: muted)),
|
||
const Spacer(),
|
||
Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
|
||
Text('resting ${person['rest'] ?? '—'} bpm', style: const TextStyle(color: good)),
|
||
Text(lastDay == today() ? 'today so far' : dm(lastDay), style: const TextStyle(color: muted, fontSize: 12.5)),
|
||
]),
|
||
const SizedBox(width: 6),
|
||
]),
|
||
const SizedBox(height: 10),
|
||
Padding(
|
||
padding: const EdgeInsets.only(right: 6),
|
||
child: LineChart(from: from, to: plus(today(), 1), unit: 'bpm', decimals: 0, range: widget.range, series: [
|
||
Series('Highest', pts('high'), bad),
|
||
Series('Lowest', pts('low'), const Color(0xFF5CC8FF)),
|
||
Series('Resting', pts('rest'), good),
|
||
]),
|
||
),
|
||
]),
|
||
),
|
||
);
|
||
}
|
||
|
||
/// The readings inside the charts' period (the latest is shown on top regardless).
|
||
List<Vital> _inPeriod(List<Vital> vs) => vs.where((v) => !day(v.t).isBefore(_from(vs))).toList();
|
||
|
||
DateTime _from(List<Vital> vs) => widget.range.from(vs.isEmpty ? today() : day(vs.last.t), today());
|
||
|
||
Widget _bp(List<Vital> vs) {
|
||
final last = vs.firstOrNull;
|
||
final listed = _inPeriod(vs);
|
||
final since = plus(today(), -30);
|
||
final month = vs.where((v) => !v.t.isBefore(since)).toList();
|
||
final avg = month.isEmpty ? null : (
|
||
(month.map((v) => v.sys!).reduce((a, b) => a + b) / month.length).round(),
|
||
(month.map((v) => v.dia!).reduce((a, b) => a + b) / month.length).round());
|
||
final c = bpClass(last?.sys, last?.dia);
|
||
return _VitalCard(
|
||
title: 'Blood pressure',
|
||
head: last == null ? 'No readings yet' : '${last.sys} / ${last.dia} mmHg',
|
||
sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}',
|
||
subColor: classColor(c?.$2),
|
||
extra: avg == null ? null : '30-day average ${avg.$1} / ${avg.$2} (${month.length} reading${month.length != 1 ? 's' : ''})',
|
||
info: 'ESC 2024 (office readings): under 120 / 70 non-elevated · 120–139 / 70–89 elevated · 140 / 90+ hypertension · '
|
||
'180 / 110+ severe. The higher of the two numbers decides; the average of several readings on different days is what counts.',
|
||
chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: 'mmHg', decimals: 0, range: widget.range, series: [
|
||
Series('Systolic', vitalSeries(vs, (v) => v.sys?.toDouble()), accent),
|
||
Series('Diastolic', vitalSeries(vs, (v) => v.dia?.toDouble()), const Color(0xFF5CC8FF)),
|
||
]),
|
||
rows: [
|
||
if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||
child: Text('No readings in this period', style: TextStyle(color: muted))),
|
||
for (final v in listed.take(shown['bp']!))
|
||
_ReadingRow(v, '${v.sys} / ${v.dia}', classColor(bpClass(v.sys, v.dia)?.$2), () => _edit('bp', v)),
|
||
],
|
||
more: listed.length - shown['bp']!,
|
||
onMore: () => setState(() => shown['bp'] = shown['bp']! + 10),
|
||
onAdd: () => _edit('bp', null),
|
||
);
|
||
}
|
||
|
||
Widget _ox(List<Vital> vs) {
|
||
final last = vs.firstOrNull;
|
||
final listed = _inPeriod(vs);
|
||
final c = spo2Class(last?.spo2);
|
||
return _VitalCard(
|
||
title: 'Blood oxygen',
|
||
head: last == null ? 'No readings yet' : '${last.spo2!.round()} %',
|
||
sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}${last.source != null ? ' · ${vitalSources[last.source] ?? last.source}' : ''}',
|
||
subColor: classColor(c?.$2),
|
||
info: 'At rest: 95–100 % normal · 91–94 % low · 90 % or less very low (see a doctor). Wrist sensors read a couple of % low '
|
||
'now and then — a single low spot check isn\'t a verdict.',
|
||
chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: '%', decimals: 0, band: (95, 100), limits: (85, 100), range: widget.range,
|
||
series: [Series('SpO₂', vitalSeries(vs, (v) => v.spo2), accent)]),
|
||
rows: [
|
||
if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6),
|
||
child: Text('No readings in this period', style: TextStyle(color: muted))),
|
||
for (final v in listed.take(shown['ox']!))
|
||
_ReadingRow(v, '${v.spo2!.round()} %', classColor(spo2Class(v.spo2)?.$2), () => _edit('ox', v)),
|
||
],
|
||
more: listed.length - shown['ox']!,
|
||
onMore: () => setState(() => shown['ox'] = shown['ox']! + 10),
|
||
onAdd: () => _edit('ox', null),
|
||
);
|
||
}
|
||
|
||
Future<void> _edit(String kind, Vital? v) => showModalBottomSheet(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
backgroundColor: card,
|
||
builder: (_) => VitalSheet(kind: kind, v: v, sync: widget.sync),
|
||
);
|
||
}
|
||
|
||
class _VitalCard extends StatelessWidget {
|
||
const _VitalCard({required this.title, required this.head, required this.sub, required this.subColor, this.extra,
|
||
required this.info, required this.chart, required this.rows, required this.more, required this.onMore, required this.onAdd});
|
||
final String title, head, sub, info;
|
||
final String? extra;
|
||
final Color subColor;
|
||
final Widget? chart;
|
||
final List<Widget> rows;
|
||
final int more;
|
||
final VoidCallback onMore, onAdd;
|
||
|
||
@override
|
||
Widget build(BuildContext context) => Card(
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Row(children: [
|
||
Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
|
||
Tooltip(triggerMode: TooltipTriggerMode.tap, message: info, showDuration: const Duration(seconds: 8),
|
||
child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted))),
|
||
TextButton.icon(onPressed: onAdd, icon: const Icon(Icons.add, size: 18), label: const Text('Add')),
|
||
]),
|
||
Text(head, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
|
||
if (sub.isNotEmpty) Text(sub, style: TextStyle(color: subColor)),
|
||
if (extra != null) Text(extra!, style: const TextStyle(color: muted, fontSize: 13)),
|
||
if (chart != null) ...[const SizedBox(height: 10), Padding(padding: const EdgeInsets.only(right: 6), child: chart!)],
|
||
...rows,
|
||
if (more > 0) TextButton(onPressed: onMore, child: Text('Show more ($more)')),
|
||
]),
|
||
),
|
||
);
|
||
}
|
||
|
||
class _ReadingRow extends StatelessWidget {
|
||
const _ReadingRow(this.v, this.value, this.color, this.onTap);
|
||
final Vital v;
|
||
final String value;
|
||
final Color color;
|
||
final VoidCallback onTap;
|
||
@override
|
||
Widget build(BuildContext context) => InkWell(
|
||
onTap: onTap,
|
||
child: Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||
child: Row(children: [
|
||
SizedBox(width: 160, child: Text('${v.t.year == today().year ? dm(v.t) : dmy(v.t)} ${_hm(v.t)}', maxLines: 1,
|
||
style: const TextStyle(color: muted))),
|
||
SizedBox(width: 72, child: Text(value, style: TextStyle(color: color))),
|
||
Expanded(child: Text(v.note.isNotEmpty ? v.note : vitalSources[v.source] ?? '', overflow: TextOverflow.ellipsis,
|
||
style: const TextStyle(color: muted, fontSize: 13))),
|
||
]),
|
||
),
|
||
);
|
||
}
|
||
|
||
/// Add / edit one reading: date + time, the numbers of its kind, note; Delete = tap twice.
|
||
class VitalSheet extends StatefulWidget {
|
||
const VitalSheet({super.key, required this.kind, required this.v, required this.sync});
|
||
final String kind;
|
||
final Vital? v;
|
||
final SyncService sync;
|
||
@override
|
||
State<VitalSheet> createState() => _VitalSheetState();
|
||
}
|
||
|
||
class _VitalSheetState extends State<VitalSheet> {
|
||
late DateTime t = widget.v?.t ?? () {
|
||
final n = DateTime.now();
|
||
return DateTime.utc(n.year, n.month, n.day, n.hour, n.minute);
|
||
}();
|
||
late final sys = TextEditingController(text: widget.v?.sys?.toString() ?? '');
|
||
late final dia = TextEditingController(text: widget.v?.dia?.toString() ?? '');
|
||
late final ox = TextEditingController(text: widget.v?.spo2 == null ? '' : widget.v!.spo2!.round().toString());
|
||
late final note = TextEditingController(text: widget.v?.note ?? '');
|
||
String? error;
|
||
bool armed = false;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final bp = widget.kind == 'bp';
|
||
return Padding(
|
||
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom),
|
||
child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
||
Text('${widget.v == null ? 'Add' : 'Edit'} ${bp ? 'blood pressure' : 'blood oxygen'}',
|
||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)),
|
||
Row(children: [
|
||
TextButton.icon(icon: const Icon(Icons.event, size: 18), label: Text(dmy(t)), onPressed: () async {
|
||
final p = await showDatePicker(context: context, initialDate: t, firstDate: DateTime.utc(2000), lastDate: today());
|
||
if (p != null) setState(() => t = DateTime.utc(p.year, p.month, p.day, t.hour, t.minute));
|
||
}),
|
||
TextButton.icon(icon: const Icon(Icons.schedule, size: 18), label: Text(_hm(t)), onPressed: () async {
|
||
final p = await showTimePicker(context: context, initialTime: TimeOfDay(hour: t.hour, minute: t.minute));
|
||
if (p != null) setState(() => t = DateTime.utc(t.year, t.month, t.day, p.hour, p.minute));
|
||
}),
|
||
]),
|
||
if (bp)
|
||
Row(children: [
|
||
Expanded(child: TextField(controller: sys, keyboardType: TextInputType.number, autofocus: widget.v == null,
|
||
textInputAction: TextInputAction.next,
|
||
decoration: const InputDecoration(labelText: 'Systolic (upper)', suffixText: 'mmHg'))),
|
||
const SizedBox(width: 12),
|
||
Expanded(child: TextField(controller: dia, keyboardType: TextInputType.number,
|
||
decoration: const InputDecoration(labelText: 'Diastolic (lower)', suffixText: 'mmHg'))),
|
||
])
|
||
else
|
||
TextField(controller: ox, keyboardType: const TextInputType.numberWithOptions(decimal: true), autofocus: widget.v == null,
|
||
decoration: const InputDecoration(labelText: 'Blood oxygen', suffixText: '%')),
|
||
TextField(controller: note, maxLength: 500, decoration: const InputDecoration(labelText: 'Note')),
|
||
if (error != null) Text(error!, style: const TextStyle(color: bad)),
|
||
Row(children: [
|
||
if (widget.v != null)
|
||
TextButton(
|
||
onPressed: () {
|
||
if (!armed) return setState(() => armed = true);
|
||
widget.sync.store.delete('health.vital', widget.v!.u);
|
||
widget.sync.changed();
|
||
Navigator.pop(context);
|
||
},
|
||
child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)),
|
||
),
|
||
const Spacer(),
|
||
FilledButton(
|
||
onPressed: () {
|
||
final err = saveVital(widget.sync.store, u: widget.v?.u, kind: widget.kind, t: t,
|
||
sys: int.tryParse(sys.text.trim()), dia: int.tryParse(dia.text.trim()),
|
||
spo2: double.tryParse(ox.text.trim().replaceAll(',', '.')), note: note.text);
|
||
if (err != null) return setState(() => error = err);
|
||
widget.sync.changed();
|
||
Navigator.pop(context);
|
||
},
|
||
child: const Text('Save'),
|
||
),
|
||
]),
|
||
]),
|
||
);
|
||
}
|
||
}
|