// The band's data from Gadgetbridge to the dashboard, through the sync (no Syncthing): Gadgetbridge's
// database export on this phone (Gadgetbridge ▸ Settings ▸ Automations ▸ Auto export), picked once,
// is read at every sync (the app's and the background task's, background.dart) when it changed; the new rows of the six tables the dashboard's gb.py reads
// (only those columns) go into the store as health.
rows — ids = the band's timestamps, as
// gb.RELAY_SYNC — and travel like any change. The Pi imports them (gb.import_relay).
//
// Incremental like gb.py: rows from the newest relayed minute minus OVERLAP (the band hands over
// sleep and late minutes after the fact); an unchanged row isn't put again. Rows older than KEEP
// days that were sent are dropped here without a delete marker — the Pi keeps them.
// With them goes the phone's time zone (health.RELAY_INFO "tz"): the dashboard reads the band's times in it
// unless Settings ▸ Health sets one.
import 'dart:io';
import 'package:gb_export/gb_export.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite3/sqlite3.dart';
import 'store.dart';
const overlapS = 2 * 86400;
const keepDays = 14;
/// table → (id prefix, timestamp column, timestamp in ms?, columns sent) — gb.RELAY_SCHEMA / RELAY_SYNC
const relayTables = {
'XIAOMI_ACTIVITY_SAMPLE': ('a', 'TIMESTAMP', false, ['TIMESTAMP', 'HEART_RATE', 'STEPS', 'DISTANCE_CM']),
'XIAOMI_DAILY_SUMMARY_SAMPLE': ('d', 'TIMESTAMP', true, ['TIMESTAMP', 'HR_RESTING']),
'XIAOMI_SLEEP_STAGE_SAMPLE': ('s', 'TIMESTAMP', true, ['TIMESTAMP', 'STAGE']),
'XIAOMI_SLEEP_TIME_SAMPLE': ('t', 'TIMESTAMP', true, ['TIMESTAMP', 'WAKEUP_TIME']),
'BASE_ACTIVITY_SUMMARY': ('w', 'START_TIME', true, ['START_TIME', 'END_TIME', 'ACTIVITY_KIND', 'OVERRIDE_ACTIVITY_KIND']),
'XIAOMI_MANUAL_SAMPLE': ('m', 'TIMESTAMP', true, ['TIMESTAMP', 'TYPE', 'VALUE']),
};
class GbRelay {
GbRelay(this.store);
final SyncStore store;
String? get uri => store.metaText('gb_uri');
String? get lastResult => store.metaText('gb_result');
int get lastRun => store.meta('gb_run'); // ms
/// The system file picker → remember the export (null = cancelled).
Future pick() async {
final u = await pickExport();
if (u == null) return false;
store.setMetaText('gb_uri', u);
store.setMetaText('gb_stamp', null); // read it at the next sync
return true;
}
void forget() {
store.setMetaText('gb_uri', null);
store.setMetaText('gb_stamp', null);
}
/// Read the export if it changed → rows put (0 = nothing new; null = no export picked).
Future run() async {
final u = uri;
if (u == null) return null;
final info = await exportInfo(u);
if (info == null) {
_done('can\'t open the export — choose it again');
return 0;
}
await _zone();
final stamp = '${info['size']}:${info['modified']}';
var put = 0;
if (stamp != store.metaText('gb_stamp')) {
final tmp = '${(await getTemporaryDirectory()).path}/gb_export.db';
if (!await copyExport(u, tmp)) {
_done('can\'t read the export');
return 0;
}
try {
put = _read(tmp);
store.setMetaText('gb_stamp', stamp);
_done('$put new or changed rows from the export of ${_when(info['modified']!)}');
} catch (e) {
_done('the export couldn\'t be read: $e');
} finally {
for (final f in [tmp, '$tmp-wal', '$tmp-shm', '$tmp-journal']) {
final x = File(f);
if (x.existsSync()) x.deleteSync();
}
}
}
_trim();
return put;
}
int _read(String path) {
final gb = sqlite3.open(path, mode: OpenMode.readOnly);
var put = 0, newest = store.meta('gb_last');
final since = newest == 0 ? 0 : newest - overlapS;
try {
store.db.execute('BEGIN');
for (final MapEntry(key: t, value: (prefix, ts, ms, cols)) in relayTables.entries) {
final have = gb.select("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [t]);
if (have.isEmpty) continue;
for (final r in gb.select('SELECT ${cols.join(', ')} FROM $t WHERE $ts >= ? ORDER BY $ts', [ms ? since * 1000 : since])) {
final data = {for (final c in cols) c: r[c]};
final id = t == 'XIAOMI_MANUAL_SAMPLE' ? '$prefix:${r['TIMESTAMP']}:${r['TYPE']}' : '$prefix:${r[ts]}';
final old = store.row('health.$t', id);
if (old != null && cols.every((c) => old[c] == data[c])) continue;
store.put('health.$t', id, data);
put++;
if (t == 'XIAOMI_ACTIVITY_SAMPLE' && (r[ts] as int) > newest) newest = r[ts] as int;
}
}
store.setMeta('gb_last', newest);
store.db.execute('COMMIT');
} catch (_) {
store.db.execute('ROLLBACK');
rethrow;
} finally {
gb.close();
}
return put;
}
/// The phone's time zone → health.RELAY_INFO (only when it changed: a trip abroad, the clocks moved by hand).
Future _zone() async {
final z = await timeZone();
if (z == null || z.isEmpty || store.row('health.RELAY_INFO', 'i:tz')?['v'] == z) return;
store.put('health.RELAY_INFO', 'i:tz', {'k': 'tz', 'v': z});
}
/// Drop rows older than keepDays that were already sent — here only (no delete marker).
void _trim() {
final cut = DateTime.now().millisecondsSinceEpoch ~/ 1000 - keepDays * 86400, pushed = store.meta('pushed');
for (final MapEntry(key: t, value: (_, ts, ms, _)) in relayTables.entries) {
store.db.execute("DELETE FROM rec WHERE t = ? AND h <= ? AND json_extract(data, '\$.$ts') < ?",
['health.$t', pushed, ms ? cut * 1000 : cut]);
}
}
void _done(String result) {
store.setMetaText('gb_result', result);
store.setMeta('gb_run', DateTime.now().millisecondsSinceEpoch);
}
static String _when(int ms) {
final d = DateTime.fromMillisecondsSinceEpoch(ms);
return '${d.day}.${d.month}. ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}
}