Skip to content

Offline gym log for Android. No account, no ads, no internet.

Wear OS: sync the watch with the phone over Bluetooth

InlitX4df7ed4def51
diff --git a/WEAR.md b/WEAR.md
new file mode 100644
index 0000000..e52777a
--- /dev/null
+++ b/WEAR.md
@@ -0,0 +1,99 @@
+# GymMane on Wear OS
+
+GymMane has a watch app, in beta. It's the same app as on the phone, with its own layout for the
+wrist: today's routine, sets you log with the crown, the rest timer, a tile and a complication. It
+works on its own, without the phone nearby, and syncs with the phone over Bluetooth.
+
+It runs on any watch with Wear OS 3 or newer: Galaxy Watch 4 and later, Pixel Watch, TicWatch, Fossil,
+OnePlus Watch and others. It isn't on the Play Store, so you install it from a computer. It takes about
+five minutes and you only do it once.
+
+Found a bug, or something that doesn't work on your watch? Please
+[open an issue](https://github.com/InlitX/GymMane/issues/new/choose) with your watch model. That's
+how the watch app gets better.
+
+## 1. Get the watch ready
+
+1. On the watch, open **Settings › System › About › Versions** and tap **Build number** seven times.
+ You'll see that developer options are on.
+2. Go back to **Settings › Developer options** and turn on **ADB debugging** and **Wireless
+ debugging** (on older watches it's called **Debug over Wi-Fi**).
+3. Make sure the watch and your computer are on the same Wi-Fi.
+
+## 2. Install GymMane
+
+Download the installer and run it. It sets up adb if you don't have it, connects to the watch, picks
+the right version for it and installs it.
+
+**Windows** (PowerShell):
+
+```powershell
+irm https://raw.githubusercontent.com/InlitX/GymMane/main/wear/install.ps1 -OutFile install.ps1; .\install.ps1
+```
+
+**Linux or macOS:**
+
+```sh
+curl -fsSL https://raw.githubusercontent.com/InlitX/GymMane/main/wear/install.sh -o install.sh && sh install.sh
+```
+
+It asks for two things shown on the watch, in **Developer options › Wireless debugging**:
+
+- the **IP address and port** at the top;
+- the first time only, a **pairing code**: tap **Pair new device** and type the address and code it
+ shows.
+
+If the watch asks to allow debugging, tap **Allow**. When it's done, turn Wireless debugging off.
+
+To update GymMane later, run the installer again. Your data stays.
+
+<details>
+<summary>Installing by hand</summary>
+
+With [platform-tools](https://developer.android.com/tools/releases/platform-tools):
+
+```sh
+adb pair <pairing address:port> <code>
+adb connect <IP address:port>
+adb shell getprop ro.product.cpu.abilist
+adb install -r GymMane-<abi>.apk
+```
+
+Take the APK from the [latest release](https://github.com/InlitX/GymMane/releases/latest) that matches
+the first value the third command prints: `arm64-v8a` or `armeabi-v7a`.
+
+</details>
+
+## 3. Sync with the phone
+
+The phone and the watch sync over the Bluetooth link they already share. No internet, no account and
+no Google services.
+
+1. **On the phone:** Settings › Data & backup › **Wear OS watch**, turn on **Sync with the watch** and allow
+ Bluetooth.
+2. **On the watch:** open GymMane, go to Settings and tap **Allow Bluetooth**.
+3. **Open GymMane on both.** They sync on their own whenever both are open at the same time. You can
+ also tap **Sync now** on either one.
+
+The watch gets your routines, weekly plan, settings and history. Notes, photos and nutrition stay on
+the phone. Workouts you do on the watch reach the phone the next time both apps are open.
+
+<details>
+<summary>If Bluetooth sync doesn't work on your watch</summary>
+
+A computer can carry the data instead. On the phone, turn on Settings › Data & backup › Auto backup to a
+folder and copy that folder to the computer. Then, with the watch connected over adb as in step 2:
+
+```sh
+curl -fsSL https://raw.githubusercontent.com/InlitX/GymMane/main/wear/sync.sh -o sync.sh && sh sync.sh <folder>
+```
+
+```powershell
+irm https://raw.githubusercontent.com/InlitX/GymMane/main/wear/sync.ps1 -OutFile sync.ps1; .\sync.ps1 <folder>
+```
+
+It sends the newest backup to the watch and brings back the workouts done on it. On the watch, tap
+**Sync now** afterwards. Please also open an issue with your watch model, so Bluetooth can be fixed
+for it.
+
+</details>
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 65c563e..358162e 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -6,6 +6,8 @@
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.NFC"/>
+ <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
@@ -33,6 +35,7 @@
<uses-feature android:name="android.hardware.type.watch" android:required="false"/>
<uses-feature android:name="android.hardware.touchscreen" android:required="false"/>
<uses-feature android:name="android.hardware.nfc" android:required="false"/>
+ <uses-feature android:name="android.hardware.bluetooth" android:required="false"/>
<application
android:label="GymMane"
@@ -41,6 +44,26 @@
android:icon="@mipmap/ic_launcher"
android:enableOnBackInvokedCallback="true">
<meta-data android:name="com.google.android.wearable.standalone" android:value="true"/>
+ <service
+ android:name=".TodayTileService"
+ android:exported="true"
+ android:icon="@drawable/ic_qs_today"
+ android:label="@string/qs_today"
+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
+ <intent-filter>
+ <action android:name="android.service.quicksettings.action.QS_TILE"/>
+ </intent-filter>
+ </service>
+ <service
+ android:name=".PassTileService"
+ android:exported="true"
+ android:icon="@drawable/ic_qs_pass"
+ android:label="@string/qs_pass"
+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
+ <intent-filter>
+ <action android:name="android.service.quicksettings.action.QS_TILE"/>
+ </intent-filter>
+ </service>
<service
android:name=".GymTileService"
android:exported="true"
diff --git a/android/app/src/main/kotlin/com/gymmane/app/WatchLinkBridge.kt b/android/app/src/main/kotlin/com/gymmane/app/WatchLinkBridge.kt
new file mode 100644
index 0000000..da3c97e
--- /dev/null
+++ b/android/app/src/main/kotlin/com/gymmane/app/WatchLinkBridge.kt
@@ -0,0 +1,274 @@
+package com.gymmane.app
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothClass
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothServerSocket
+import android.bluetooth.BluetoothSocket
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.provider.Settings
+import io.flutter.plugin.common.MethodChannel
+import java.io.DataInputStream
+import java.io.DataOutputStream
+import java.util.UUID
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+@SuppressLint("MissingPermission")
+object WatchLinkBridge {
+ const val CHANNEL = "gymmane/watchlink"
+ private const val REQUEST_CODE = 4391
+ private const val NAME = "GymMane"
+ private const val MAX = 48 * 1024 * 1024
+ private val SECURE: UUID = UUID.fromString("6a0f3c1e-5b7d-4e2a-9c41-8d2f7b1e6a53")
+ private val OPEN: UUID = UUID.fromString("6a0f3c1e-5b7d-4e2a-9c41-8d2f7b1e6a54")
+ private val main = Handler(Looper.getMainLooper())
+ private var channel: MethodChannel? = null
+ private var pending: MethodChannel.Result? = null
+ @Volatile private var generation = 0
+ private val servers = mutableListOf<BluetoothServerSocket>()
+
+ fun attach(activity: Activity, ch: MethodChannel) {
+ channel = ch
+ ch.setMethodCallHandler { call, result ->
+ when (call.method) {
+ "state" -> result.success(state(activity))
+ "permission" -> askPermission(activity, result)
+ "listen" -> {
+ if (call.argument<Boolean>("on") == true) startServer(activity) else stopServer()
+ result.success(null)
+ }
+ "exchange" -> exchange(
+ activity,
+ call.argument<ByteArray>("data") ?: ByteArray(0),
+ call.argument<String>("last") ?: "",
+ call.argument<Boolean>("toWatch") == true,
+ result,
+ )
+ "settings" -> {
+ runCatching { activity.startActivity(Intent(Settings.ACTION_BLUETOOTH_SETTINGS)) }
+ result.success(null)
+ }
+ else -> result.notImplemented()
+ }
+ }
+ }
+
+ fun detach() {
+ stopServer()
+ channel = null
+ }
+
+ fun onPermissionResult(requestCode: Int, results: IntArray): Boolean {
+ if (requestCode != REQUEST_CODE) return false
+ val result = pending ?: return true
+ pending = null
+ result.success(results.isNotEmpty() && results.all { it == PackageManager.PERMISSION_GRANTED })
+ return true
+ }
+
+ private fun adapter(context: Context): BluetoothAdapter? =
+ (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
+
+ private fun granted(context: Context): Boolean =
+ Build.VERSION.SDK_INT < 31 ||
+ context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
+
+ private fun state(context: Context): Map<String, Any> {
+ val a = adapter(context)
+ val ok = granted(context)
+ return mapOf(
+ "available" to (a != null),
+ "granted" to ok,
+ "enabled" to (ok && runCatching { a?.isEnabled == true }.getOrDefault(false)),
+ )
+ }
+
+ private fun askPermission(activity: Activity, result: MethodChannel.Result) {
+ if (granted(activity)) {
+ result.success(true)
+ return
+ }
+ pending?.success(false)
+ pending = result
+ activity.requestPermissions(arrayOf(Manifest.permission.BLUETOOTH_CONNECT), REQUEST_CODE)
+ }
+
+ @Synchronized
+ private fun startServer(context: Context) {
+ if (servers.isNotEmpty() || !granted(context)) return
+ val a = adapter(context) ?: return
+ val gen = ++generation
+ accept(gen) { a.listenUsingRfcommWithServiceRecord(NAME, SECURE) }
+ accept(gen) { a.listenUsingInsecureRfcommWithServiceRecord(NAME, OPEN) }
+ }
+
+ private fun accept(gen: Int, open: () -> BluetoothServerSocket) {
+ Thread {
+ while (generation == gen) {
+ var s: BluetoothServerSocket? = null
+ try {
+ s = open()
+ synchronized(this) {
+ if (generation != gen) {
+ runCatching { s.close() }
+ return@Thread
+ }
+ servers.add(s)
+ }
+ while (generation == gen) serve(s.accept())
+ } catch (_: Exception) {
+ if (generation == gen) runCatching { Thread.sleep(3000) }
+ } finally {
+ if (s != null) {
+ synchronized(this) { servers.remove(s) }
+ runCatching { s.close() }
+ }
+ }
+ }
+ }.apply {
+ isDaemon = true
+ start()
+ }
+ }
+
+ @Synchronized
+ private fun stopServer() {
+ generation++
+ for (s in servers.toList()) runCatching { s.close() }
+ servers.clear()
+ }
+
+ private fun serve(sock: BluetoothSocket) {
+ try {
+ val input = DataInputStream(sock.inputStream)
+ val output = DataOutputStream(sock.outputStream)
+ val request = readFrame(input)
+ val name = runCatching { sock.remoteDevice.name }.getOrNull() ?: ""
+ val address = runCatching { sock.remoteDevice.address }.getOrNull() ?: ""
+ val latch = CountDownLatch(1)
+ var reply: ByteArray? = null
+ main.post {
+ val ch = channel
+ if (ch == null) {
+ latch.countDown()
+ return@post
+ }
+ ch.invokeMethod(
+ "request",
+ mapOf("data" to request, "name" to name, "address" to address),
+ object : MethodChannel.Result {
+ override fun success(value: Any?) {
+ reply = value as? ByteArray
+ latch.countDown()
+ }
+
+ override fun error(code: String, message: String?, details: Any?) {
+ latch.countDown()
+ }
+
+ override fun notImplemented() {
+ latch.countDown()
+ }
+ },
+ )
+ }
+ latch.await(90, TimeUnit.SECONDS)
+ writeFrame(output, reply ?: ByteArray(0))
+ runCatching { input.read() }
+ } catch (_: Exception) {
+ } finally {
+ runCatching { sock.close() }
+ }
+ }
+
+ private fun wanted(device: BluetoothDevice, toWatch: Boolean): Boolean {
+ val major = runCatching { device.bluetoothClass?.majorDeviceClass }.getOrNull()
+ ?: return true
+ return when (major) {
+ BluetoothClass.Device.Major.WEARABLE, BluetoothClass.Device.Major.UNCATEGORIZED,
+ BluetoothClass.Device.Major.MISC, BluetoothClass.Device.Major.HEALTH -> true
+ BluetoothClass.Device.Major.PHONE -> !toWatch
+ else -> false
+ }
+ }
+
+ private fun exchange(
+ context: Context,
+ data: ByteArray,
+ last: String,
+ toWatch: Boolean,
+ result: MethodChannel.Result,
+ ) {
+ val a = adapter(context)
+ if (a == null || !granted(context) || !runCatching { a.isEnabled }.getOrDefault(false)) {
+ result.success(null)
+ return
+ }
+ Thread {
+ val bonded = runCatching { a.bondedDevices.toList() }.getOrDefault(emptyList())
+ val known = bonded.firstOrNull { it.address == last }
+ val order = if (known != null) listOf(known) + bonded.filter { it != known && wanted(it, toWatch) }
+ else bonded.filter { wanted(it, toWatch) }
+ var answer: Map<String, Any>? = null
+ for (device in order) {
+ val reply = talk(device, data, true) ?: talk(device, data, false) ?: continue
+ answer = mapOf(
+ "data" to reply,
+ "name" to (runCatching { device.name }.getOrNull() ?: ""),
+ "address" to device.address,
+ )
+ break
+ }
+ main.post { result.success(answer) }
+ }.apply {
+ isDaemon = true
+ start()
+ }
+ }
+
+ private fun talk(device: BluetoothDevice, data: ByteArray, secure: Boolean): ByteArray? {
+ var sock: BluetoothSocket? = null
+ return try {
+ sock = if (secure) device.createRfcommSocketToServiceRecord(SECURE)
+ else device.createInsecureRfcommSocketToServiceRecord(OPEN)
+ sock.connect()
+ val output = DataOutputStream(sock.outputStream)
+ val input = DataInputStream(sock.inputStream)
+ writeFrame(output, data)
+ val reply = readFrame(input)
+ runCatching {
+ output.write(1)
+ output.flush()
+ }
+ reply.takeIf { it.isNotEmpty() }
+ } catch (_: Exception) {
+ null
+ } finally {
+ runCatching { sock?.close() }
+ }
+ }
+
+ private fun readFrame(input: DataInputStream): ByteArray {
+ val n = input.readInt()
+ if (n < 0 || n > MAX) throw IllegalStateException("size")
+ val bytes = ByteArray(n)
+ input.readFully(bytes)
+ return bytes
+ }
+
+ private fun writeFrame(output: DataOutputStream, bytes: ByteArray) {
+ output.writeInt(bytes.size)
+ output.write(bytes)
+ output.flush()
+ }
+}
diff --git a/lib/main.dart b/lib/main.dart
index 5c50308..d4d4870 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -1,3 +1,5 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/date_symbol_data_local.dart';
@@ -17,8 +19,11 @@ import 'services/graphics_mode.dart';
import 'services/rest_alarm.dart';
import 'services/screen_awake.dart';
import 'state/fit_state.dart';
+import 'services/quick_tiles.dart';
+import 'services/watch_phone.dart';
import 'wear/wear_app.dart';
import 'wear/wear_surfaces.dart';
+import 'wear/wear_sync.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -51,15 +56,20 @@ Future<void> main() async {
if (watch) {
WearSurfaces.watch();
+ unawaited(WearSync.instance.init());
runApp(const WearApp());
+ GraphicsMode.watchFirstFrame();
return;
}
fit.onWidgetsShouldUpdate = HomeWidgetBridge.update;
NutritionWidgets.watch(HomeWidgetBridge.update);
AutoBackup.instance.init();
+ unawaited(WatchPhone.init());
+ unawaited(QuickTiles.init());
runApp(const GymManeApp());
+ GraphicsMode.watchFirstFrame();
WidgetsBinding.instance.addPostFrameCallback((_) => HomeWidgetBridge.update());
}
diff --git a/lib/services/watch_link.dart b/lib/services/watch_link.dart
new file mode 100644
index 0000000..29b5543
--- /dev/null
+++ b/lib/services/watch_link.dart
@@ -0,0 +1,201 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+
+import 'local_store.dart';
+
+typedef LinkMessage = Map<String, dynamic>;
+
+Uint8List packLink(LinkMessage m) => Uint8List.fromList(gzip.encode(utf8.encode(jsonEncode(m))));
+
+LinkMessage? unpackLink(Object? bytes) {
+ if (bytes is! Uint8List || bytes.isEmpty) return null;
+ try {
+ final decoded = jsonDecode(utf8.decode(gzip.decode(bytes)));
+ return decoded is LinkMessage ? decoded : null;
+ } catch (_) {
+ return null;
+ }
+}
+
+class WatchLink extends ChangeNotifier with WidgetsBindingObserver {
+ WatchLink._();
+ static final WatchLink instance = WatchLink._();
+
+ static const _ch = MethodChannel('gymmane/watchlink');
+ static const _note = 'watchLink';
+
+ bool onWatch = false;
+ bool available = false;
+ bool granted = false;
+ bool enabled = false;
+ bool on = false;
+ bool busy = false;
+ bool? lastOk;
+ String peer = '';
+ String _address = '';
+ DateTime? at;
+ bool _listening = false;
+ bool _started = false;
+
+ Future<LinkMessage> Function()? outgoing;
+ Future<LinkMessage?> Function(LinkMessage message)? onRequest;
+ Future<void> Function(LinkMessage reply)? onReply;
+ VoidCallback? onResumed;
+
+ bool get ready => available && granted && enabled && (onWatch || on);
+
+ Future<void> init({required bool watch}) async {
+ if (_started || kIsWeb || !Platform.isAndroid) return;
+ _started = true;
+ onWatch = watch;
+ _load();
+ _ch.setMethodCallHandler(_handle);
+ WidgetsBinding.instance.addObserver(this);
+ await refresh();
+ await _listen();
+ }
+
+ void _load() {
+ final raw = Store.instance.note(_note);
+ if (raw == null || raw.isEmpty) return;
+ try {
+ final j = jsonDecode(raw) as Map<String, dynamic>;
+ on = j['on'] == true;
+ peer = j['peer'] as String? ?? '';
+ _address = j['address'] as String? ?? '';
+ final a = (j['at'] as num?)?.toInt();
+ at = a == null ? null : DateTime.fromMillisecondsSinceEpoch(a);
+ } catch (_) {}
+ }
+
+ void _save() {
+ Store.instance.setNote(
+ _note,
+ jsonEncode({
+ 'on': on,
+ 'peer': peer,
+ 'address': _address,
+ if (at != null) 'at': at!.millisecondsSinceEpoch,
+ }));
+ notifyListeners();
+ }
+
+ Future<void> refresh() async {
+ try {
+ final s = await _ch.invokeMapMethod<String, dynamic>('state');
+ available = s?['available'] == true;
+ granted = s?['granted'] == true;
+ enabled = s?['enabled'] == true;
+ } catch (_) {
+ available = false;
+ }
+ notifyListeners();
+ }
+
+ Future<bool> askPermission() async {
+ try {
+ granted = await _ch.invokeMethod<bool>('permission') ?? false;
+ } catch (_) {
+ granted = false;
+ }
+ await refresh();
+ await _listen();
+ return granted;
+ }
+
+ Future<void> setOn(bool value) async {
+ if (value && !granted && !await askPermission()) return;
+ on = value;
+ _save();
+ await _listen();
+ if (on) unawaited(exchange());
+ }
+
+ Future<void> openSettings() async {
+ try {
+ await _ch.invokeMethod<void>('settings');
+ } catch (_) {}
+ }
+
+ Future<void> _listen() async {
+ final want = ready && WidgetsBinding.instance.lifecycleState != AppLifecycleState.paused;
+ if (want == _listening) return;
+ _listening = want;
+ try {
+ await _ch.invokeMethod<void>('listen', {'on': want});
+ } catch (_) {}
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (state == AppLifecycleState.resumed) {
+ unawaited(() async {
+ await refresh();
+ await _listen();
+ onResumed?.call();
+ }());
+ } else if (state == AppLifecycleState.paused) {
+ _listening = false;
+ unawaited(_ch.invokeMethod<void>('listen', {'on': false}).catchError((_) {}));
+ }
+ }
+
+ void _done(String name, String address) {
+ if (name.isNotEmpty) peer = name;
+ if (address.isNotEmpty) _address = address;
+ at = DateTime.now();
+ lastOk = true;
+ }
+
+ Future<bool> exchange({bool manual = false}) async {
+ final make = outgoing;
+ if (make == null || busy) return false;
+ await refresh();
+ if (!ready) return false;
+ busy = true;
+ notifyListeners();
+ var ok = false;
+ try {
+ final r = await _ch.invokeMapMethod<String, dynamic>('exchange', {
+ 'data': packLink(await make()),
+ 'last': _address,
+ 'toWatch': !onWatch,
+ });
+ final reply = unpackLink(r?['data']);
+ if (reply != null) {
+ await onReply?.call(reply);
+ _done(r?['name'] as String? ?? '', r?['address'] as String? ?? '');
+ ok = true;
+ }
+ } catch (e) {
+ debugPrint('WatchLink: $e');
+ }
+ if (!ok && manual) lastOk = false;
+ busy = false;
+ _save();
+ return ok;
+ }
+
+ Future<Object?> _handle(MethodCall call) async {
+ if (call.method != 'request') return null;
+ final args = call.arguments as Map?;
+ final message = unpackLink(args?['data']);
+ final handler = onRequest;
+ if (message == null || handler == null || (!onWatch && !on)) return null;
+ try {
+ final reply = await handler(message);
+ if (reply == null) return null;
+ _done(args?['name'] as String? ?? '', args?['address'] as String? ?? '');
+ _save();
+ return packLink(reply);
+ } catch (e) {
+ debugPrint('WatchLink request: $e');
+ return null;
+ }
+ }
+}
diff --git a/lib/services/watch_phone.dart b/lib/services/watch_phone.dart
new file mode 100644
index 0000000..7dec0b1
--- /dev/null
+++ b/lib/services/watch_phone.dart
@@ -0,0 +1,51 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:archive/archive.dart';
+import 'package:flutter/foundation.dart';
+
+import '../state/fit_state.dart';
+import '../wear/wear_sync.dart';
+import 'backup_zip.dart';
+import 'local_store.dart';
+import 'watch_link.dart';
+
+class WatchPhone {
+ WatchPhone._();
+
+ static Future<void> init() async {
+ final link = WatchLink.instance
+ ..outgoing = _state
+ ..onRequest = _fromWatch
+ ..onReply = _merge
+ ..onResumed = () => unawaited(WatchLink.instance.exchange());
+ await link.init(watch: false);
+ if (link.ready) unawaited(link.exchange());
+ }
+
+ static Future<LinkMessage> _state() async {
+ fit.persistNow();
+ final local = jsonDecode(jsonEncode(Store.finite(fit.toJson()))) as Map<String, dynamic>;
+ return {'role': 'phone', 'state': slimForWatch(local)};
+ }
+
+ static Future<LinkMessage?> _fromWatch(LinkMessage m) async {
+ if (m['role'] != 'watch') return null;
+ await _merge(m);
+ return _state();
+ }
+
+ static Future<void> _merge(LinkMessage m) async {
+ final sessions = m['sessions'];
+ if (m['role'] != 'watch' || sessions is! List || sessions.isEmpty || fit.isSessionActive) return;
+ final known = {for (final s in fit.sessions) s.date.toIso8601String()};
+ if (sessions.every((s) => known.contains(sessionKey(s)))) return;
+ final bytes = utf8.encode(jsonEncode({'sessions': sessions}));
+ final zip = ZipEncoder().encode(Archive()..addFile(ArchiveFile(kBackupJsonEntry, bytes.length, bytes)));
+ try {
+ await mergeBackupZip(Uint8List.fromList(zip), incomingNewer: false);
+ } catch (e) {
+ debugPrint('WatchPhone merge: $e');
+ }
+ }
+}
diff --git a/lib/state/fit_state.dart b/lib/state/fit_state.dart
index 022d037..8d876dc 100644
--- a/lib/state/fit_state.dart
+++ b/lib/state/fit_state.dart
@@ -638,6 +638,7 @@ class FitState extends FitCore
'place': activePlaceId,
if (gymPasses.isNotEmpty) 'passes': gymPasses.map((p) => p.toJson()).toList(),
if (lastPassId.isNotEmpty) 'lastPass': lastPassId,
+ if (quickPassId.isNotEmpty) 'quickPass': quickPassId,
'checkins': checkins.toList(),
if (daysOff.isNotEmpty) 'daysOff': daysOff,
'routines': routines.map((r) => r.toJson()).toList(),
@@ -753,6 +754,7 @@ class FitState extends FitCore
activePlaceId = '';
gymPasses.clear();
lastPassId = '';
+ quickPassId = '';
checkins.clear();
daysOff.clear();
routines.clear();
diff --git a/lib/wear/wear_shell.dart b/lib/wear/wear_shell.dart
index ddbb9bc..446e030 100644
--- a/lib/wear/wear_shell.dart
+++ b/lib/wear/wear_shell.dart
@@ -10,11 +10,13 @@ import '../l10n/l10n.dart';
import '../models/live_session.dart';
import '../models/workout.dart';
import '../services/screen_awake.dart';
+import '../services/watch_link.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
import '../widgets/timer_panel.dart';
import '../widgets/ui_kit.dart' show sentenceCase;
+import 'wear_sync.dart';
class WearRotary {
WearRotary._();
@@ -153,6 +155,7 @@ class _WearShellState extends State<WearShell> with WidgetsBindingObserver {
}
if (state == AppLifecycleState.resumed) {
fit.syncRest();
+ unawaited(WearSync.instance.sync());
_wake();
}
}
@@ -511,20 +514,30 @@ class _WeekRing extends StatelessWidget {
@override
Widget build(BuildContext context) {
final pct = goal <= 0 ? 0.0 : (done / goal).clamp(0.0, 1.0);
- return SizedBox(
- width: 80,
- height: 80,
- child: CustomPaint(
- painter: _RingPainter(track: gc.bgRaised2, fill: gc.accent, pct: pct),
- child: Center(
- child: Column(mainAxisSize: MainAxisSize.min, children: [
- Text('$done/$goal', style: AppTheme.f(20, weight: FontWeight.w800, color: gc.text)),
- Text(t.thisWeek,
- style: AppTheme.f(9, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 0.8)),
- ]),
+ return Column(mainAxisSize: MainAxisSize.min, children: [
+ SizedBox(
+ width: 76,
+ height: 76,
+ child: CustomPaint(
+ painter: _RingPainter(track: gc.bgRaised2, fill: gc.accent, pct: pct),
+ child: Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text('$done/$goal', style: AppTheme.f(21, weight: FontWeight.w800, color: gc.text)),
+ ),
+ ),
+ ),
),
),
- );
+ const SizedBox(height: 5),
+ Text(t.thisWeekTitle,
+ textAlign: TextAlign.center,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.textSecondary)),
+ ]);
}
}
@@ -793,6 +806,63 @@ class WearSettings extends StatelessWidget {
),
),
),
+ const SizedBox(height: 14),
+ _label(gc, t.wearSyncTitle),
+ ListenableBuilder(
+ listenable: Listenable.merge([WearSync.instance, WatchLink.instance]),
+ builder: (context, _) {
+ final sync = WearSync.instance;
+ final link = WatchLink.instance;
+ final at = sync.pulledAt;
+ final status = sync.busy || link.busy
+ ? t.wearSyncSearching
+ : !link.enabled && link.granted
+ ? t.wearSyncBluetoothOff
+ : link.lastOk == false
+ ? t.wearSyncNotFound
+ : at == null
+ ? t.wearSyncNever
+ : t.wearSyncLast('${t.shortDate(at)} · ${t.clockTime(at)}');
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Center(
+ child: Text(status,
+ textAlign: TextAlign.center,
+ maxLines: 3,
+ style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text, height: 1.25)),
+ ),
+ if (sync.waiting > 0) ...[
+ const SizedBox(height: 4),
+ Center(
+ child: Text(t.wearSyncWaiting(sync.waiting),
+ textAlign: TextAlign.center,
+ maxLines: 3,
+ style: AppTheme.f(11.5, weight: FontWeight.w600, color: gc.accent, height: 1.25)),
+ ),
+ ],
+ const SizedBox(height: 8),
+ if (link.available && !link.granted)
+ WearButton(
+ label: t.wearSyncAllow,
+ icon: PhosphorIconsBold.bluetooth,
+ onTap: () => unawaited(link.askPermission().then((ok) {
+ if (ok) unawaited(sync.sync(manual: true));
+ })),
+ )
+ else
+ WearButton(
+ label: t.wearSyncNow,
+ icon: PhosphorIconsBold.arrowsClockwise,
+ onTap: sync.busy || link.busy ? null : () => unawaited(sync.sync(manual: true)),
+ ),
+ const SizedBox(height: 6),
+ Center(
+ child: Text(t.wearSyncHow,
+ textAlign: TextAlign.center,
+ style: AppTheme.f(11, weight: FontWeight.w500, color: gc.textTertiary, height: 1.3)),
+ ),
+ ]);
+ },
+ ),
]);
}
diff --git a/lib/wear/wear_sync.dart b/lib/wear/wear_sync.dart
new file mode 100644
index 0000000..e81f583
--- /dev/null
+++ b/lib/wear/wear_sync.dart
@@ -0,0 +1,331 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math' as math;
+
+import 'package:archive/archive_io.dart';
+import 'package:flutter/foundation.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:sync/sync.dart';
+
+import '../services/backup_zip.dart';
+import '../services/local_store.dart';
+import '../services/watch_link.dart';
+import '../state/fit_state.dart';
+
+const Set<String> _watchOwn = {
+ 'keepAwake',
+ 'live',
+ 'liveStart',
+ 'liveElapsed',
+ 'livePaused',
+ 'alarmSound',
+ 'alarmSoundName',
+};
+
+const Set<String> _phoneOnly = {
+ 'notes',
+ 'exNotes',
+ 'shots',
+ 'moments',
+ 'bodyTl',
+ 'nutrition',
+ 'measures',
+ 'steps',
+ 'health',
+ 'media',
+};
+
+String sessionKey(Object? session) => session is Map ? '${session['d'] ?? ''}' : '';
+
+Map<String, dynamic> mirrorPhone(Map<String, dynamic> watch, Map<String, dynamic> phone) {
+ final out = slimForWatch(phone);
+ for (final k in _watchOwn) {
+ if (watch.containsKey(k)) out[k] = watch[k];
+ }
+ final seen = <String>{};
+ final sessions = <Object?>[];
+ for (final s in [...(phone['sessions'] as List? ?? const []), ...(watch['sessions'] as List? ?? const [])]) {
+ final k = sessionKey(s);
+ if (k.isEmpty || seen.add(k)) sessions.add(s);
+ }
+ sessions.sort((a, b) => sessionKey(a).compareTo(sessionKey(b)));
+ out['sessions'] = sessions;
+ out['onboarded'] = true;
+ return out;
+}
+
+Map<String, dynamic> slimForWatch(Map<String, dynamic> phone) {
+ final out = <String, dynamic>{};
+ for (final e in phone.entries) {
+ if (_phoneOnly.contains(e.key) || mediaGroups.contains(e.key) || _watchOwn.contains(e.key)) continue;
+ out[e.key] = e.value;
+ }
+ final profile = out['profile'];
+ if (profile is Map) out['profile'] = {...profile}..remove('photo')..remove('banner');
+ return out;
+}
+
+Map<String, dynamic> watchExport(Map<String, dynamic> watch, Iterable<String> mine) {
+ final keep = mine.toSet();
+ return {
+ 'sessions': [
+ for (final s in (watch['sessions'] as List? ?? const []))
+ if (keep.contains(sessionKey(s))) s,
+ ],
+ };
+}
+
+class WearSync extends ChangeNotifier {
+ WearSync._();
+ static final WearSync instance = WearSync._();
+
+ static const _note = 'wearSync';
+ static const folder = 'sync';
+
+ String device = '';
+ final List<String> _mine = [];
+ final Map<String, int> _pulled = {};
+ final Set<String> _known = {};
+ DateTime? pulledAt;
+ DateTime? sentAt;
+ String _sent = '';
+ bool busy = false;
+ bool _applying = false;
+ Directory? _dir;
+
+ int get waiting => _mine.length;
+
+ String? get path => _dir?.path;
+
+ Future<void> init() async {
+ _load();
+ try {
+ final base = await getExternalStorageDirectory();
+ if (base != null) {
+ _dir = Directory('${base.path}/$folder');
+ await _dir!.create(recursive: true);
+ }
+ } catch (e) {
+ debugPrint('WearSync: $e');
+ }
+ _known.addAll(_keys());
+ fit.addListener(_onFit);
+ final link = WatchLink.instance
+ ..outgoing = _outgoing
+ ..onRequest = _fromPhone
+ ..onReply = _phoneReply;
+ await link.init(watch: true);
+ await sync();
+ }
+
+ Map<String, dynamic> _local() {
+ fit.persistNow();
+ return jsonDecode(jsonEncode(Store.finite(fit.toJson()))) as Map<String, dynamic>;
+ }
+
+ Future<Map<String, dynamic>> _outgoing() async =>
+ {'role': 'watch', 'device': device, 'sessions': watchExport(_local(), _mine)['sessions']};
+
+ Future<Map<String, dynamic>?> _fromPhone(Map<String, dynamic> m) async {
+ if (m['role'] != 'phone') return null;
+ final state = m['state'];
+ if (state is Map<String, dynamic> && !fit.isSessionActive) {
+ _apply(state);
+ _save();
+ }
+ return _outgoing();
+ }
+
+ Future<void> _phoneReply(Map<String, dynamic> m) async {
+ final state = m['state'];
+ if (m['role'] != 'phone' || state is! Map<String, dynamic> || fit.isSessionActive) return;
+ _apply(state);
+ }
+
+ bool _apply(Map<String, dynamic> phone) {
+ if (phone['routines'] is! List) return false;
+ final next = mirrorPhone(_local(), phone);
+ _applying = true;
+ final ok = fit.tryApplyBackup(next);
+ _applying = false;
+ if (!ok) return false;
+ final theirs = {for (final s in (phone['sessions'] as List? ?? const [])) sessionKey(s)};
+ _mine.removeWhere(theirs.contains);
+ _known
+ ..clear()
+ ..addAll(_keys());
+ pulledAt = DateTime.now();
+ return true;
+ }
+
+ Iterable<String> _keys() => fit.sessions.map((s) => s.date.toIso8601String());
+
+ void _load() {
+ final raw = Store.instance.note(_note);
+ if (raw != null && raw.isNotEmpty) {
+ try {
+ final j = jsonDecode(raw) as Map<String, dynamic>;
+ device = j['device'] as String? ?? '';
+ _mine.addAll(((j['mine'] as List?) ?? const []).whereType<String>());
+ ((j['pulled'] as Map?) ?? const {}).forEach((k, v) {
+ if (k is String && v is num) _pulled[k] = v.toInt();
+ });
+ final pa = (j['pulledAt'] as num?)?.toInt();
+ pulledAt = pa == null ? null : DateTime.fromMillisecondsSinceEpoch(pa);
+ final sa = (j['sentAt'] as num?)?.toInt();
+ sentAt = sa == null ? null : DateTime.fromMillisecondsSinceEpoch(sa);
+ _sent = j['sent'] as String? ?? '';
+ } catch (_) {}
+ }
+ if (device.isEmpty) {
+ final r = math.Random.secure();
+ device = 'watch${String.fromCharCodes([for (var i = 0; i < 4; i++) 97 + r.nextInt(26)])}';
+ _save();
+ }
+ }
+
+ void _save() {
+ Store.instance.setNote(
+ _note,
+ jsonEncode({
+ 'device': device,
+ 'mine': _mine,
+ 'pulled': _pulled,
+ if (pulledAt != null) 'pulledAt': pulledAt!.millisecondsSinceEpoch,
+ if (sentAt != null) 'sentAt': sentAt!.millisecondsSinceEpoch,
+ 'sent': _sent,
+ }));
+ notifyListeners();
+ }
+
+ void _onFit() {
+ if (_applying) return;
+ final now = _keys().toSet();
+ final fresh = now.difference(_known);
+ _known
+ ..clear()
+ ..addAll(now);
+ if (fresh.isEmpty) return;
+ _mine.addAll(fresh.where((k) => !_mine.contains(k)));
+ _save();
+ unawaited(sync());
+ }
+
+ Future<bool> sync({bool manual = false}) async {
+ if (busy || fit.isSessionActive) return false;
+ busy = true;
+ notifyListeners();
+ var changed = false;
+ final dir = _dir;
+ if (dir != null) {
+ try {
+ changed = await _pull(dir);
+ await _push(dir);
+ } catch (e) {
+ debugPrint('WearSync failed: $e');
+ }
+ }
+ busy = false;
+ _save();
+ if (await WatchLink.instance.exchange(manual: manual)) {
+ changed = true;
+ _save();
+ }
+ return changed;
+ }
+
+ static SyncFile? _parse(String name) =>
+ SyncFile.parse(name.toLowerCase().endsWith('.json') ? '${name.substring(0, name.length - 5)}.zip' : name);
+
+ Future<Map<String, dynamic>?> _read(File f) async {
+ try {
+ if (f.path.toLowerCase().endsWith('.json')) {
+ final decoded = jsonDecode(await f.readAsString());
+ return decoded is Map<String, dynamic> ? decoded : null;
+ }
+ final input = InputFileStream(f.path);
+ try {
+ final archive = ZipDecoder().decodeStream(input);
+ ArchiveFile? found;
+ for (final e in archive.files) {
+ if (!e.isFile || !e.name.toLowerCase().endsWith('.json')) continue;
+ if (e.name == kBackupJsonEntry) {
+ found = e;
+ break;
+ }
+ found ??= e;
+ }
+ final bytes = found?.readBytes();
+ if (bytes == null) return null;
+ final decoded = jsonDecode(utf8.decode(bytes));
+ return decoded is Map<String, dynamic> ? decoded : null;
+ } finally {
+ await input.close();
+ }
+ } catch (e) {
+ debugPrint('WearSync read failed: $e');
+ return null;
+ }
+ }
+
+ Future<bool> _pull(Directory dir) async {
+ final files = <(SyncFile, File)>[];
+ await for (final e in dir.list()) {
+ if (e is! File) continue;
+ final name = e.uri.pathSegments.last;
+ final f = _parse(name);
+ if (f == null || f.device.startsWith('watch')) continue;
+ files.add((f, e));
+ }
+ if (files.isEmpty) return false;
+ files.sort((a, b) => b.$1.at.compareTo(a.$1.at));
+ final (newest, file) = files.first;
+ for (final (_, old) in files.skip(1)) {
+ try {
+ await old.delete();
+ } catch (_) {}
+ }
+ final stamp = newest.at.millisecondsSinceEpoch;
+ if (stamp <= (_pulled.values.fold<int>(0, math.max))) return false;
+ final phone = await _read(file);
+ if (phone == null || !_apply(phone)) return false;
+ _pulled
+ ..clear()
+ ..[newest.device] = stamp;
+ return true;
+ }
+
+ Future<void> _push(Directory dir) async {
+ final mine = <File>[];
+ await for (final e in dir.list()) {
+ if (e is File && e.uri.pathSegments.last.startsWith('$syncPrefix$device-')) mine.add(e);
+ }
+ final signature = _mine.join('|');
+ if (_mine.isEmpty) {
+ for (final f in mine) {
+ try {
+ await f.delete();
+ } catch (_) {}
+ }
+ _sent = '';
+ return;
+ }
+ if (signature == _sent && mine.isNotEmpty) return;
+ final bytes = utf8.encode(jsonEncode(watchExport(_local(), _mine)));
+ final zip = ZipEncoder().encode(Archive()..addFile(ArchiveFile(kBackupJsonEntry, bytes.length, bytes)));
+ final now = DateTime.now();
+ final target = File('${dir.path}/${syncName(device, now)}');
+ final tmp = File('${target.path}.part');
+ await tmp.writeAsBytes(zip, flush: true);
+ await tmp.rename(target.path);
+ for (final f in mine) {
+ if (f.path == target.path) continue;
+ try {
+ await f.delete();
+ } catch (_) {}
+ }
+ _sent = signature;
+ sentAt = now;
+ }
+}
diff --git a/lib/widgets/watch_sheet.dart b/lib/widgets/watch_sheet.dart
new file mode 100644
index 0000000..9b2c94b
--- /dev/null
+++ b/lib/widgets/watch_sheet.dart
@@ -0,0 +1,218 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../l10n/l10n.dart';
+import '../services/watch_link.dart';
+import '../theme/app_colors.dart';
+import '../theme/app_theme.dart';
+import 'glass.dart';
+import 'ui_kit.dart';
+
+const _kGuideUrl = 'https://github.com/InlitX/GymMane/blob/main/WEAR.md';
+
+void showWatchSheet(BuildContext context) {
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => const _WatchSheet(),
+ );
+}
+
+class _WatchSheet extends StatefulWidget {
+ const _WatchSheet();
+
+ @override
+ State<_WatchSheet> createState() => _WatchSheetState();
+}
+
+class _WatchSheetState extends State<_WatchSheet> {
+ @override
+ void initState() {
+ super.initState();
+ WatchLink.instance.refresh();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ return Container(
+ padding: sheetPad(context),
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.92),
+ decoration: sheetDecoration(gc),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ Flexible(
+ child: SingleChildScrollView(
+ child: ListenableBuilder(
+ listenable: WatchLink.instance,
+ builder: (context, _) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: _body(context, gc, WatchLink.instance),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ List<Widget> _body(BuildContext context, GymColors gc, WatchLink link) {
+ return [
+ SheetTitle(t.watchTitle, subtitle: t.watchSubtitle),
+ const SizedBox(height: 18),
+ const _Hero(),
+ const SizedBox(height: 18),
+ Container(
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 4),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(20)),
+ child: Column(children: [
+ Semantics(
+ button: true,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => launchUrl(Uri.parse(_kGuideUrl), mode: LaunchMode.externalApplication),
+ child: _Point(
+ icon: PhosphorIconsRegular.downloadSimple,
+ title: t.watchPoint1,
+ body: t.watchPoint1Body,
+ trailing: PhosphorIconsRegular.arrowUpRight),
+ ),
+ ),
+ _Point(icon: PhosphorIconsRegular.bluetooth, title: t.watchPoint2, body: t.watchPoint2Body),
+ _Point(icon: PhosphorIconsRegular.arrowsClockwise, title: t.watchPoint3, body: t.watchPoint3Body),
+ ]),
+ ),
+ const SizedBox(height: 12),
+ Semantics(
+ toggled: link.on,
+ child: Pressable(
+ onTap: () {
+ HapticFeedback.selectionClick();
+ link.setOn(!link.on);
+ },
+ child: Container(
+ constraints: const BoxConstraints(minHeight: 58),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(20)),
+ child: Row(children: [
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(t.watchUse, style: AppTheme.f(14.5, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 3),
+ Text(t.watchUseHint,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.3)),
+ ]),
+ ),
+ const SizedBox(width: 12),
+ TinySwitch(on: link.on),
+ ]),
+ ),
+ ),
+ ),
+ if (link.on) ...[
+ const SizedBox(height: 16),
+ Text(_status(link),
+ textAlign: TextAlign.center,
+ style: AppTheme.f(12.5,
+ weight: FontWeight.w600,
+ color: link.lastOk == false && !link.busy ? gc.danger : gc.textSecondary,
+ height: 1.4)),
+ const SizedBox(height: 14),
+ if (!link.enabled)
+ PrimaryButton(label: t.watchTurnOnBluetooth, onTap: link.openSettings)
+ else
+ PrimaryButton(
+ label: link.busy ? t.watchSearching : t.watchSyncNow,
+ onTap: link.busy ? null : () => link.exchange(manual: true),
+ ),
+ ],
+ const SizedBox(height: 12),
+ Text(t.watchTip,
+ textAlign: TextAlign.center,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textTertiary, height: 1.4)),
+ ];
+ }
+
+ String _status(WatchLink link) {
+ if (!link.enabled) return t.watchBluetoothOff;
+ if (link.busy) return t.watchSearchingHint;
+ if (link.lastOk == false) return t.watchNotFound;
+ final at = link.at;
+ if (at == null) return t.watchNever;
+ final when = '${t.shortDate(at)} · ${t.clockTime(at)}';
+ return link.peer.isEmpty ? t.watchLast(when) : t.watchLastWith(link.peer, when);
+ }
+}
+
+class _Hero extends StatelessWidget {
+ const _Hero();
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ Widget disc(IconData icon) => Container(
+ width: 64,
+ height: 64,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(color: gc.bgRaised2, shape: BoxShape.circle),
+ child: Icon(icon, size: 28, color: gc.text),
+ );
+ return ExcludeSemantics(
+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
+ disc(PhosphorIconsRegular.deviceMobile),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: Icon(PhosphorIconsBold.arrowsLeftRight, size: 18, color: gc.accent),
+ ),
+ disc(PhosphorIconsRegular.watch),
+ ]),
+ );
+ }
+}
+
+class _Point extends StatelessWidget {
+ const _Point({required this.icon, required this.title, required this.body, this.trailing});
+
+ final IconData icon;
+ final String title;
+ final String body;
+ final IconData? trailing;
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 11),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 1),
+ child: Icon(icon, size: 19, color: gc.textSecondary),
+ ),
+ const SizedBox(width: 14),
+ Expanded(
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 3),
+ Text(body, style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),
+ ]),
+ ),
+ if (trailing != null) ...[
+ const SizedBox(width: 10),
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Icon(trailing, size: 16, color: gc.textTertiary),
+ ),
+ ],
+ ]),
+ );
+ }
+}
diff --git a/test/wear_test.dart b/test/wear_test.dart
index 4c37647..1eee258 100644
--- a/test/wear_test.dart
+++ b/test/wear_test.dart
@@ -1,11 +1,18 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:gymmane/catalog/program_templates.dart';
import 'package:gymmane/l10n/l10n.dart';
+import 'package:gymmane/services/local_store.dart';
+import 'package:gymmane/services/watch_link.dart';
import 'package:gymmane/state/fit_state.dart';
import 'package:gymmane/wear/wear_app.dart';
import 'package:gymmane/wear/wear_shell.dart';
+import 'package:gymmane/wear/wear_sync.dart';
import 'package:gymmane/widgets/ui_kit.dart' show sentenceCase;
+import 'package:sync/sync.dart';
void _reset() {
fit.saveAndExit();
@@ -213,4 +220,128 @@ void main() {
expect(fit.weeklyPlan.values.toSet(), {fit.routines.single.id});
expect(fit.weeklyPlan.keys, containsAll([1, 3, 5]));
});
+
+ group('datos entre el móvil y el reloj', () {
+ Map<String, dynamic> session(String d) => {
+ 'd': d,
+ 'dur': 1800,
+ 'ex': [
+ {
+ 'id': 'EIeI8Vf',
+ 'n': 'Bench',
+ 's': [
+ {'r': 8, 'w': 60},
+ ],
+ },
+ ],
+ };
+
+ test('el reloj copia lo del móvil, guarda sus entrenos y no carga con fotos ni notas', () {
+ final watch = {
+ 'units': 'lb',
+ 'keepAwake': false,
+ 'routines': [
+ {'id': 'old', 'name': 'Borrada en el móvil'},
+ ],
+ 'sessions': [session('2026-11-10T10:00:00.000'), session('2026-11-12T10:00:00.000')],
+ };
+ final phone = {
+ 'units': 'kg',
+ 'keepAwake': true,
+ 'profile': {'name': 'Ana', 'photo': 'AAAA', 'banner': 'BBBB', 'goal': 4},
+ 'routines': [
+ {'id': 'r1', 'name': 'Push'},
+ ],
+ 'sessions': [session('2026-11-10T10:00:00.000'), session('2026-11-11T10:00:00.000')],
+ 'notes': [
+ {'id': 'n1'},
+ ],
+ 'nutrition': {'x': 1},
+ 'noteMedia': {'a.jpg': 'media/notes/a.jpg'},
+ };
+ final out = mirrorPhone(watch, phone);
+ expect(out['units'], 'kg');
+ expect(out['keepAwake'], false, reason: 'la pantalla encendida es cosa del reloj');
+ expect((out['routines'] as List).map((r) => (r as Map)['id']), ['r1'], reason: 'lo borrado en el móvil se va');
+ expect((out['sessions'] as List).map(sessionKey),
+ ['2026-11-10T10:00:00.000', '2026-11-11T10:00:00.000', '2026-11-12T10:00:00.000']);
+ expect(out['profile'], {'name': 'Ana', 'goal': 4});
+ expect(out.containsKey('notes'), isFalse);
+ expect(out.containsKey('nutrition'), isFalse);
+ expect(out.containsKey('noteMedia'), isFalse);
+ expect(out['onboarded'], true);
+ });
+
+ test('al móvil solo van los entrenos hechos en el reloj', () {
+ final watch = {
+ 'units': 'kg',
+ 'routines': [
+ {'id': 'r1'},
+ ],
+ 'sessions': [session('2026-11-10T10:00:00.000'), session('2026-11-12T10:00:00.000')],
+ };
+ final out = watchExport(watch, ['2026-11-12T10:00:00.000']);
+ expect(out.keys, ['sessions']);
+ expect((out['sessions'] as List).map(sessionKey), ['2026-11-12T10:00:00.000']);
+ });
+
+ test('el móvil junta el entreno del reloj sin tocar nada más', () {
+ final phone = {
+ 'units': 'kg',
+ 'routines': [
+ {'id': 'r1', 'name': 'Push'},
+ ],
+ 'sessions': [session('2026-11-10T10:00:00.000')],
+ };
+ final fromWatch = watchExport({
+ 'sessions': [session('2026-11-10T10:00:00.000'), session('2026-11-12T10:00:00.000')],
+ }, ['2026-11-12T10:00:00.000']);
+ for (final newer in [true, false]) {
+ final merged = mergeStates(phone, fromWatch, incomingNewer: newer);
+ expect((merged['sessions'] as List).map(sessionKey), ['2026-11-10T10:00:00.000', '2026-11-12T10:00:00.000']);
+ expect(merged['units'], 'kg');
+ expect((merged['routines'] as List).single, {'id': 'r1', 'name': 'Push'});
+ }
+ });
+
+ test('lo que el reloj copia del móvil se puede cargar', () {
+ _reset();
+ final id = _push();
+ fit.persistNow();
+ final phone = fit.toJson();
+ fit.routines.clear();
+ final next = mirrorPhone(fit.toJson(), jsonDecode(jsonEncode(Store.finite(phone))) as Map<String, dynamic>);
+ expect(fit.tryApplyBackup(next), isTrue);
+ expect(fit.routines.single.id, id);
+ expect(fit.onboarded, isTrue);
+ });
+
+ test('lo que viaja por Bluetooth va comprimido, sin fotos ni notas, y llega igual', () {
+ final phone = {
+ 'units': 'kg',
+ 'profile': {'name': 'Ana', 'photo': 'AAAA'},
+ 'routines': [
+ {'id': 'r1', 'name': 'Push'},
+ ],
+ 'sessions': [for (var i = 1; i <= 9; i++) session('2026-11-0${i}T10:00:00.000')],
+ 'notes': [
+ {'id': 'n1'},
+ ],
+ 'noteMedia': {'a': 'b'},
+ 'live': {'x': 1},
+ };
+ final message = {'role': 'phone', 'state': slimForWatch(phone)};
+ final bytes = packLink(message);
+ expect(bytes.length, lessThan(utf8.encode(jsonEncode(message)).length));
+ final back = unpackLink(bytes)!;
+ expect(back['role'], 'phone');
+ final state = back['state'] as Map<String, dynamic>;
+ expect(state['profile'], {'name': 'Ana'});
+ expect(state.containsKey('notes'), isFalse);
+ expect(state.containsKey('noteMedia'), isFalse);
+ expect(state.containsKey('live'), isFalse);
+ expect((state['sessions'] as List).length, 9);
+ expect(unpackLink(Uint8List.fromList([1, 2, 3])), isNull);
+ });
+ });
}
diff --git a/wear/install.ps1 b/wear/install.ps1
new file mode 100644
index 0000000..a825656
--- /dev/null
+++ b/wear/install.ps1
@@ -0,0 +1,116 @@
+param(
+ [Parameter(Position = 0)][string]$Apk
+)
+
+$ErrorActionPreference = 'Continue'
+$ProgressPreference = 'SilentlyContinue'
+$repo = 'InlitX/GymMane'
+$tools = Join-Path $env:LOCALAPPDATA 'GymMane\platform-tools'
+
+function Say($t) { Write-Host " $t" }
+function Step($n, $t) { Write-Host ''; Write-Host " $n/4 $t" -ForegroundColor White; Write-Host '' }
+function Ok($t) { Write-Host " OK $t" -ForegroundColor Green }
+function Fail($t) { Write-Host ''; Write-Host " $t" -ForegroundColor Red; Write-Host ''; exit 1 }
+function Ask($q) { Write-Host " ? $q " -NoNewline -ForegroundColor Yellow; return (Read-Host).Trim() }
+
+if ($Apk -in '-h', '--help') {
+ Write-Host 'GymMane watch installer'
+ Write-Host ''
+ Write-Host ' .\install.ps1 connects to the watch and installs the right APK from the latest release'
+ Write-Host ' .\install.ps1 <file.apk> installs that APK instead'
+ exit 0
+}
+
+Write-Host ''
+Write-Host ' GymMane for Wear OS' -ForegroundColor White
+Say 'Before you start, on the watch: Settings > System > About > Versions, tap Build number 7 times.'
+Say 'Then Settings > Developer options: turn on ADB debugging and Wireless debugging.'
+Say 'The watch and this computer must be on the same Wi-Fi.'
+
+Step 1 'adb'
+$adb = (Get-Command adb -ErrorAction SilentlyContinue).Source
+if (-not $adb -and (Test-Path "$tools\adb.exe")) { $adb = "$tools\adb.exe" }
+if (-not $adb) {
+ Say 'adb (Android platform-tools) is not installed. Downloading it from Google...'
+ $zip = Join-Path ([IO.Path]::GetTempPath()) 'gymmane-platform-tools.zip'
+ try {
+ Invoke-WebRequest -UseBasicParsing 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip' -OutFile $zip -ErrorAction Stop
+ Expand-Archive -Path $zip -DestinationPath (Split-Path $tools) -Force -ErrorAction Stop
+ } catch {
+ Fail 'Could not download platform-tools. Get them from developer.android.com/tools/releases/platform-tools and run this again.'
+ } finally {
+ Remove-Item $zip -ErrorAction SilentlyContinue
+ }
+ $adb = "$tools\adb.exe"
+}
+Ok $adb
+
+function Watches {
+ $list = @()
+ foreach ($line in (& $adb devices | Select-Object -Skip 1)) {
+ if ($line -notmatch '^(\S+)\s+device$') { continue }
+ $serial = $Matches[1]
+ $features = & $adb -s $serial shell pm list features 2>$null
+ if ($features -match 'android.hardware.type.watch') { $list += $serial }
+ }
+ return $list
+}
+
+Step 2 'Connect to the watch'
+$watch = @(Watches) | Select-Object -First 1
+if (-not $watch) {
+ Say 'On the watch, open Developer options > Wireless debugging.'
+ $address = Ask 'IP address and port shown there (like 192.168.1.20:41235):'
+ if (-not $address) { Fail 'No address given.' }
+ $out = & $adb connect $address 2>&1 | Out-String
+ if ($out -notmatch 'connected to' -or $out -match 'failed|unable') {
+ Say 'The watch needs pairing first. On the watch, tap Pair new device.'
+ $pair = Ask 'Pairing address and port shown in that dialog:'
+ $code = Ask 'Pairing code:'
+ $p = & $adb pair $pair $code 2>&1 | Out-String
+ if ($p -notmatch 'Successfully paired') { Fail "Pairing failed: $($p.Trim())" }
+ Ok 'Paired'
+ & $adb connect $address | Out-Null
+ }
+ Start-Sleep -Seconds 1
+ $watch = @(Watches) | Select-Object -First 1
+ if (-not $watch) { Fail 'The watch did not answer. Check that it is awake, on the same Wi-Fi, and that you allowed debugging on its screen.' }
+}
+$model = (& $adb -s $watch shell getprop ro.product.model).Trim()
+Ok "$model ($watch)"
+
+Step 3 'GymMane'
+$tmp = $null
+if ($Apk) {
+ if (-not (Test-Path $Apk -PathType Leaf)) { Fail "$Apk does not exist." }
+ $file = (Resolve-Path $Apk).Path
+} else {
+ $abis = (& $adb -s $watch shell getprop ro.product.cpu.abilist).Trim() -split ','
+ $abi = $abis | ForEach-Object { $_.Trim() } | Where-Object { @('arm64-v8a', 'armeabi-v7a', 'x86_64') -contains $_ } | Select-Object -First 1
+ if (-not $abi) { Fail "This watch reports $($abis -join ', '), and there is no GymMane APK for it." }
+ $tmp = Join-Path ([IO.Path]::GetTempPath()) "GymMane-$abi.apk"
+ Say "Downloading GymMane for $abi from the latest release..."
+ try {
+ Invoke-WebRequest -UseBasicParsing "https://github.com/$repo/releases/latest/download/GymMane-$abi.apk" -OutFile $tmp -ErrorAction Stop
+ } catch {
+ Fail 'Could not download the APK. Check the connection and try again.'
+ }
+ $file = $tmp
+}
+Ok (Split-Path $file -Leaf)
+
+Step 4 'Install'
+try {
+ $r = & $adb -s $watch install -r $file 2>&1 | Out-String
+} finally {
+ if ($tmp) { Remove-Item $tmp -ErrorAction SilentlyContinue }
+}
+if ($r -match 'VERSION_DOWNGRADE') { Fail 'The watch already has a newer GymMane than this one. Nothing to do.' }
+if ($r -match 'UPDATE_INCOMPATIBLE') { Fail 'The GymMane on the watch was signed by someone else. Uninstall it from the watch first, then run this again.' }
+if ($r -notmatch 'Success') { Fail "The watch refused the install: $($r.Trim())" }
+Ok 'GymMane is on the watch'
+
+Write-Host ''
+Say 'Open GymMane on the watch. To sync it with your phone, see WEAR.md.'
+Say 'You can turn Wireless debugging off now.'
+Write-Host ''
diff --git a/wear/install.sh b/wear/install.sh
new file mode 100644
index 0000000..b569def
--- /dev/null
+++ b/wear/install.sh
@@ -0,0 +1,127 @@
+#!/bin/sh
+set -eu
+
+REPO=InlitX/GymMane
+TOOLS="${HOME}/.local/share/gymmane/platform-tools"
+APK="${1:-}"
+
+say() { printf ' %s\n' "$*"; }
+step() { printf '\n %s/4 %s\n\n' "$1" "$2"; }
+ok() { printf ' OK %s\n' "$*"; }
+fail() { printf '\n %s\n\n' "$*" >&2; exit 1; }
+ask() { printf ' ? %s ' "$1"; IFS= read -r REPLY </dev/tty || REPLY=""; }
+have() { command -v "$1" >/dev/null 2>&1; }
+fetch() { if have curl; then curl -fsSL "$1" -o "$2"; else wget -q "$1" -O "$2"; fi; }
+
+case "$APK" in
+ -h|--help)
+ echo 'GymMane watch installer'
+ echo
+ echo ' ./install.sh connects to the watch and installs the right APK from the latest release'
+ echo ' ./install.sh <file.apk> installs that APK instead'
+ exit 0 ;;
+esac
+
+printf '\n GymMane for Wear OS\n'
+say 'Before you start, on the watch: Settings > System > About > Versions, tap Build number 7 times.'
+say 'Then Settings > Developer options: turn on ADB debugging and Wireless debugging.'
+say 'The watch and this computer must be on the same Wi-Fi.'
+
+step 1 adb
+if have adb; then
+ ADB=$(command -v adb)
+elif [ -x "$TOOLS/adb" ]; then
+ ADB="$TOOLS/adb"
+else
+ have curl || have wget || fail 'This script needs curl or wget.'
+ have unzip || fail 'This script needs unzip to set up adb. Install unzip, or install adb (android-tools) yourself.'
+ case "$(uname -s)" in
+ Darwin) os=darwin ;;
+ *) os=linux ;;
+ esac
+ say 'adb (Android platform-tools) is not installed. Downloading it from Google...'
+ tmpzip=$(mktemp)
+ fetch "https://dl.google.com/android/repository/platform-tools-latest-$os.zip" "$tmpzip" ||
+ fail 'Could not download platform-tools. Install adb (android-tools) and run this again.'
+ mkdir -p "$(dirname "$TOOLS")"
+ unzip -qo "$tmpzip" -d "$(dirname "$TOOLS")"
+ rm -f "$tmpzip"
+ ADB="$TOOLS/adb"
+fi
+ok "$ADB"
+
+watches() {
+ "$ADB" devices | sed 1d | while read -r serial state; do
+ [ "$state" = device ] || continue
+ if "$ADB" -s "$serial" shell pm list features 2>/dev/null | grep -q android.hardware.type.watch; then
+ echo "$serial"
+ fi
+ done
+}
+
+step 2 'Connect to the watch'
+WATCH=$(watches | head -n 1)
+if [ -z "$WATCH" ]; then
+ say 'On the watch, open Developer options > Wireless debugging.'
+ ask 'IP address and port shown there (like 192.168.1.20:41235):'
+ address=$REPLY
+ [ -n "$address" ] || fail 'No address given.'
+ out=$("$ADB" connect "$address" 2>&1 || true)
+ case "$out" in
+ *"connected to"*) ;;
+ *)
+ say 'The watch needs pairing first. On the watch, tap Pair new device.'
+ ask 'Pairing address and port shown in that dialog:'
+ pair=$REPLY
+ ask 'Pairing code:'
+ code=$REPLY
+ p=$("$ADB" pair "$pair" "$code" 2>&1 || true)
+ case "$p" in
+ *"Successfully paired"*) ok Paired ;;
+ *) fail "Pairing failed: $p" ;;
+ esac
+ "$ADB" connect "$address" >/dev/null 2>&1 || true ;;
+ esac
+ sleep 1
+ WATCH=$(watches | head -n 1)
+ [ -n "$WATCH" ] || fail 'The watch did not answer. Check that it is awake, on the same Wi-Fi, and that you allowed debugging on its screen.'
+fi
+model=$("$ADB" -s "$WATCH" shell getprop ro.product.model | tr -d '\r')
+ok "$model ($WATCH)"
+
+step 3 GymMane
+TMPAPK=""
+if [ -n "$APK" ]; then
+ [ -f "$APK" ] || fail "$APK does not exist."
+ FILE=$APK
+else
+ have curl || have wget || fail 'This script needs curl or wget.'
+ abis=$("$ADB" -s "$WATCH" shell getprop ro.product.cpu.abilist | tr -d '\r')
+ abi=""
+ for a in $(echo "$abis" | tr ',' ' '); do
+ case "$a" in arm64-v8a|armeabi-v7a|x86_64) abi=$a; break ;; esac
+ done
+ [ -n "$abi" ] || fail "This watch reports $abis, and there is no GymMane APK for it."
+ TMPAPK=$(mktemp)
+ say "Downloading GymMane for $abi from the latest release..."
+ fetch "https://github.com/$REPO/releases/latest/download/GymMane-$abi.apk" "$TMPAPK" ||
+ { rm -f "$TMPAPK"; fail 'Could not download the APK. Check the connection and try again.'; }
+ FILE=$TMPAPK
+ ok "GymMane-$abi.apk"
+fi
+[ -n "$TMPAPK" ] || ok "$(basename "$FILE")"
+
+step 4 Install
+r=$("$ADB" -s "$WATCH" install -r "$FILE" 2>&1 || true)
+[ -z "$TMPAPK" ] || rm -f "$TMPAPK"
+case "$r" in
+ *Success*) ok 'GymMane is on the watch' ;;
+ *VERSION_DOWNGRADE*) fail 'The watch already has a newer GymMane than this one. Nothing to do.' ;;
+ *UPDATE_INCOMPATIBLE*) fail 'The GymMane on the watch was signed by someone else. Uninstall it from the watch first, then run this again.' ;;
+ *) fail "The watch refused the install: $r" ;;
+esac
+
+printf '\n'
+say 'Open GymMane on the watch. To sync it with your phone, see WEAR.md.'
+say 'You can turn Wireless debugging off now.'
+printf '\n'
diff --git a/wear/sync.ps1 b/wear/sync.ps1
new file mode 100644
index 0000000..1c8f86b
--- /dev/null
+++ b/wear/sync.ps1
@@ -0,0 +1,101 @@
+param(
+ [Parameter(Position = 0)][string]$Source,
+ [Parameter(Position = 1)][string]$Serial
+)
+
+$ErrorActionPreference = 'Stop'
+$watchDir = '/sdcard/Android/data/com.gymmane.app/files/sync'
+$prefix = 'gymmane-auto-'
+
+if (-not $Source -or $Source -in '-h', '--help') {
+ Write-Host 'GymMane watch sync'
+ Write-Host ''
+ Write-Host ' .\sync.ps1 <folder> the folder where your phone or server leaves its backups'
+ Write-Host ' .\sync.ps1 <backup.zip> a single backup exported from the phone'
+ Write-Host ' .\sync.ps1 <folder> <serial> pick the watch when more than one device is connected'
+ Write-Host ''
+ Write-Host 'Sends your newest backup to the watch and brings back the workouts done on the watch.'
+ exit 0
+}
+
+if (-not (Get-Command adb -ErrorAction SilentlyContinue)) {
+ Write-Host 'adb was not found. Install Android platform-tools first.'
+ exit 1
+}
+
+function Invoke-Adb {
+ if ($Serial) { & adb -s $Serial @args } else { & adb @args }
+}
+
+if (-not $Serial) {
+ $devices = @(& adb devices | Select-Object -Skip 1 | Where-Object { $_ -match '\tdevice$' })
+ if ($devices.Count -eq 0) { Write-Host 'No device connected. Pair the watch first (see WEAR.md).'; exit 1 }
+ if ($devices.Count -ne 1) {
+ Write-Host 'More than one device is connected. Run it again with the watch serial:'
+ $devices | ForEach-Object { Write-Host " $(($_ -split "`t")[0])" }
+ exit 1
+ }
+}
+
+$installed = Invoke-Adb shell pm path com.gymmane.app 2>$null
+if (-not $installed) { Write-Host 'GymMane is not installed on that device.'; exit 1 }
+Invoke-Adb shell mkdir -p $watchDir | Out-Null
+
+$newest = $null
+if (Test-Path $Source -PathType Container) {
+ $folder = (Resolve-Path $Source).Path
+ $newest = Get-ChildItem $folder -Filter "$prefix*.zip" |
+ Where-Object { $_.Name -match "^$prefix([a-z]+)-(.+)\.zip$" -and $Matches[1] -notlike 'watch*' } |
+ Sort-Object { $_.Name -replace "^$prefix[a-z]+-", '' } | Select-Object -Last 1
+ if ($newest) { $target = [IO.Path]::GetFileNameWithoutExtension($newest.Name) + '.json' }
+} elseif (Test-Path $Source -PathType Leaf) {
+ $newest = Get-Item $Source
+ $folder = $newest.DirectoryName
+ $target = $prefix + 'phone-' + [DateTime]::UtcNow.ToString('yyyy-MM-dd-HHmmss') + '.json'
+} else {
+ Write-Host "$Source is not a folder or a file."
+ exit 1
+}
+
+$tmp = Join-Path ([IO.Path]::GetTempPath()) ("gymmane-watch-" + [Guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path $tmp | Out-Null
+try {
+ if ($newest) {
+ Add-Type -AssemblyName System.IO.Compression.FileSystem
+ $sent = $false
+ $zip = $null
+ try {
+ $zip = [IO.Compression.ZipFile]::OpenRead($newest.FullName)
+ $entry = $zip.Entries | Where-Object { $_.FullName -eq 'gymmane.json' } | Select-Object -First 1
+ if ($entry) {
+ $out = Join-Path $tmp $target
+ [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $out, $true)
+ Invoke-Adb push $out "$watchDir/$target" | Out-Null
+ $sent = $true
+ }
+ } catch {
+ $sent = $false
+ } finally {
+ if ($zip) { $zip.Dispose() }
+ }
+ if ($sent) { Write-Host "Sent to the watch: $($newest.Name)" }
+ else { Write-Host "$($newest.Name) is not a GymMane backup, nothing was sent." }
+ } else {
+ Write-Host "No backup found in $folder, nothing was sent."
+ }
+
+ $brought = 0
+ $names = @(Invoke-Adb shell ls $watchDir 2>$null | ForEach-Object { $_.Trim() } |
+ Where-Object { $_ -match "^${prefix}watch[a-z]*-.+\.zip$" })
+ foreach ($name in $names) {
+ $local = Join-Path $folder $name
+ if (Test-Path $local) { continue }
+ Invoke-Adb pull "$watchDir/$name" $local | Out-Null
+ $brought++
+ }
+ if ($brought -eq 0) { Write-Host 'Nothing new on the watch.' }
+ else { Write-Host "Brought from the watch: $brought file(s) into $folder" }
+ Write-Host 'On the watch, open GymMane > Settings > Sync now.'
+} finally {
+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
+}
diff --git a/wear/sync.sh b/wear/sync.sh
new file mode 100644
index 0000000..f50a8d7
--- /dev/null
+++ b/wear/sync.sh
@@ -0,0 +1,80 @@
+#!/bin/sh
+set -eu
+
+WATCH_DIR=/sdcard/Android/data/com.gymmane.app/files/sync
+PREFIX=gymmane-auto-
+
+if [ $# -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
+ echo "GymMane watch sync"
+ echo ""
+ echo " sh sync.sh <folder> the folder where your phone or server leaves its backups"
+ echo " sh sync.sh <backup.zip> a single backup exported from the phone"
+ echo " sh sync.sh <folder> <serial> pick the watch when more than one device is connected"
+ echo ""
+ echo "Sends your newest backup to the watch and brings back the workouts done on the watch."
+ exit 0
+fi
+
+SOURCE=$1
+SERIAL=${2:-}
+
+command -v adb >/dev/null 2>&1 || { echo "adb was not found. Install Android platform-tools first."; exit 1; }
+command -v unzip >/dev/null 2>&1 || { echo "unzip was not found. Install it and try again."; exit 1; }
+
+adb_() {
+ if [ -n "$SERIAL" ]; then adb -s "$SERIAL" "$@"; else adb "$@"; fi
+}
+
+if [ -z "$SERIAL" ]; then
+ COUNT=$(adb devices | awk 'NR > 1 && $2 == "device"' | wc -l | tr -d ' ')
+ if [ "$COUNT" = 0 ]; then echo "No device connected. Pair the watch first (see WEAR.md)."; exit 1; fi
+ if [ "$COUNT" != 1 ]; then
+ echo "More than one device is connected. Run it again with the watch serial:"
+ adb devices | awk 'NR > 1 && $2 == "device" { print " " $1 }'
+ exit 1
+ fi
+fi
+
+adb_ shell pm path com.gymmane.app >/dev/null 2>&1 || { echo "GymMane is not installed on that device."; exit 1; }
+adb_ shell mkdir -p "$WATCH_DIR"
+
+if [ -d "$SOURCE" ]; then
+ FOLDER=$SOURCE
+ NEWEST=$(ls "$FOLDER" 2>/dev/null | grep "^$PREFIX[a-z]*-.*\.zip$" | grep -v "^${PREFIX}watch" |
+ sed "s/^$PREFIX\([a-z]*\)-\(.*\)\.zip$/\2 &/" | sort | tail -n 1 | cut -d' ' -f2-)
+ [ -z "$NEWEST" ] || NEWEST="$FOLDER/$NEWEST"
+ TARGET=$(basename "${NEWEST:-none}" .zip).json
+elif [ -f "$SOURCE" ]; then
+ FOLDER=$(dirname "$SOURCE")
+ NEWEST=$SOURCE
+ TARGET="${PREFIX}phone-$(date -u +%Y-%m-%d-%H%M%S).json"
+else
+ echo "$SOURCE is not a folder or a file."
+ exit 1
+fi
+
+TMP=$(mktemp -d)
+trap 'rm -rf "$TMP"' EXIT
+
+if [ -n "$NEWEST" ]; then
+ if unzip -p "$NEWEST" gymmane.json >"$TMP/$TARGET" 2>/dev/null && [ -s "$TMP/$TARGET" ]; then
+ adb_ push "$TMP/$TARGET" "$WATCH_DIR/$TARGET" >/dev/null
+ echo "Sent to the watch: $(basename "$NEWEST")"
+ else
+ echo "$(basename "$NEWEST") is not a GymMane backup, nothing was sent."
+ fi
+else
+ echo "No backup found in $FOLDER, nothing was sent."
+fi
+
+BROUGHT=0
+for NAME in $(adb_ shell ls "$WATCH_DIR" 2>/dev/null | tr -d '\r' | grep "^${PREFIX}watch[a-z]*-.*\.zip$" || true); do
+ [ -f "$FOLDER/$NAME" ] && continue
+ adb_ pull "$WATCH_DIR/$NAME" "$FOLDER/$NAME" >/dev/null
+ BROUGHT=$((BROUGHT + 1))
+done
+
+if [ "$BROUGHT" = 0 ]; then echo "Nothing new on the watch."
+else echo "Brought from the watch: $BROUGHT file(s) into $FOLDER"; fi
+
+echo "On the watch, open GymMane > Settings > Sync now."