iOS and macOS: stay reachable for the trainer app across backgrounding, suspension and sleep

iOS
- The keep-alive now follows the network servers themselves (waiting for a
  client and connected), so the per-method calls are gone.
- After a suspension the listeners are bound again and the advertisement is
  published again. A standstill of the process is the trigger; returning to
  the foreground also re-checks the advertisement and its address.
- The dns_sd bridge reports a lost registration and a changed network path
  to the Dart side, and no longer moves the host record alone when the
  address sits on another interface.
- Wi-Fi trainer hostnames resolve through the system resolver; the in-app
  multicast query is not allowed there and logged an "App crashed" entry
  per attempt. The query socket has an error handler on every platform.

macOS
- The responder is bound again after the Mac slept.

Both
- Home: a step says when BikeControl's own advertisement cannot be found
  on the network even after publishing it again.
- Network check: the live test is inconclusive, not failed, while
  BikeControl browses the network itself and the trainer app may run on
  the same device; an app whose controller method is switched off is
  checked against the trainer bridge it uses instead.
- Diagnostics: recent TCP connections (who dialled, and whether they hung
  up before the first byte), lifecycle and recovery state, and the age of
  the stored network check.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Jonas Acker
2026-11-24 11:00:50 +01:00
parent 0f4f492f95
commit 6df7591a43
45 changed files with 994 additions and 78 deletions

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad: BikeControl now stays awake in the background while it waits for your trainer app (up to 15 minutes), and for 5 minutes after the app disconnects. Before, iOS could put BikeControl to sleep before MyWhoosh and other apps had found it, so the app found nothing or could not connect.
- (Base) iPhone / iPad: when iOS did put BikeControl to sleep, it is found on the network again by itself once you return to it. Before, the network method had to be restarted.
- (Base) iPhone / iPad: BikeControl follows a change of Wi-Fi or hotspot right away instead of advertising the old address.
- (Base) iPhone / iPad: searching for Wi-Fi trainers no longer fills the log with "App crashed" entries.
- (Base) iPhone, iPad and Mac: the home screen tells you when BikeControl cannot be found on the network, with the network check one tap away.
- (Base) Mac: BikeControl is found again after the Mac wakes from sleep, without restarting the network method.
- (Base) Network check: no longer reports a failure while BikeControl is searching the network itself, or when you only use the trainer bridge and have the controller connection switched off.
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Zwift Play / Zwift Ride paddles: tilting inward and tilting outward are now two separate buttons, each mappable to its own action. Your existing paddle mapping applies to both.

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad: BikeControl bleibt jetzt im Hintergrund wach, solange es auf deine Trainer-App wartet (bis zu 15 Minuten), und noch 5 Minuten, nachdem die App die Verbindung getrennt hat. Bisher konnte iOS BikeControl schlafen legen, bevor MyWhoosh und andere Apps es gefunden hatten – die App fand dann nichts oder konnte sich nicht verbinden.
- (Base) iPhone / iPad: Hat iOS BikeControl doch schlafen gelegt, ist es von selbst wieder im Netzwerk zu finden, sobald du zurückkehrst. Bisher musste die Netzwerkmethode neu gestartet werden.
- (Base) iPhone / iPad: BikeControl folgt einem Wechsel des WLANs oder Hotspots sofort, statt weiter die alte Adresse anzukündigen.
- (Base) iPhone / iPad: Die Suche nach WLAN-Trainern füllt das Protokoll nicht mehr mit „App crashed“-Einträgen.
- (Base) iPhone, iPad und Mac: Die Startseite zeigt dir, wenn BikeControl im Netzwerk nicht zu finden ist – die Netzwerkprüfung ist nur einen Tipp entfernt.
- (Base) Mac: BikeControl wird nach dem Aufwachen des Mac wieder gefunden, ohne die Netzwerkmethode neu zu starten.
- (Base) Netzwerkprüfung: meldet keinen Fehler mehr, während BikeControl selbst das Netzwerk durchsucht oder wenn du nur die Trainer-Brücke nutzt und die Controller-Verbindung ausgeschaltet hast.
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Paddel von Zwift Play / Zwift Ride: Nach innen und nach außen kippen sind jetzt zwei eigene Tasten, und du kannst jeder eine eigene Aktion zuweisen. Deine bisherige Paddel-Belegung gilt für beide.

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad: BikeControl ahora sigue activo en segundo plano mientras espera a tu app de entrenamiento (hasta 15 minutos) y durante 5 minutos después de que la app se desconecte. Antes, iOS podía suspender BikeControl antes de que MyWhoosh y otras apps lo encontraran, y la app no encontraba nada o no podía conectarse.
- (Base) iPhone / iPad: si iOS llega a suspender BikeControl, vuelve a ser visible en la red por sí solo en cuanto regresas a él. Antes había que reiniciar el método de red.
- (Base) iPhone / iPad: BikeControl sigue de inmediato un cambio de Wi-Fi o de punto de acceso en lugar de anunciar la dirección anterior.
- (Base) iPhone / iPad: buscar entrenadores Wi-Fi ya no llena el registro de entradas «App crashed».
- (Base) iPhone, iPad y Mac: la pantalla de inicio te avisa cuando BikeControl no se encuentra en la red, con la comprobación de red a un toque.
- (Base) Mac: BikeControl vuelve a encontrarse después de que el Mac salga del reposo, sin reiniciar el método de red.
- (Base) Comprobación de red: ya no informa de un fallo mientras BikeControl está buscando en la red, ni cuando solo usas el puente del entrenador y tienes desactivada la conexión del mando.
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Palancas de Zwift Play / Zwift Ride: inclinar hacia dentro e inclinar hacia fuera son ahora dos botones distintos, cada uno con su propia acción. Tu asignación actual de la palanca se aplica a ambos.

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad : BikeControl reste désormais actif en arrière-plan tant qu'il attend ton app d'entraînement (jusqu'à 15 minutes), et pendant 5 minutes après la déconnexion de l'app. Auparavant, iOS pouvait suspendre BikeControl avant que MyWhoosh et d'autres apps ne l'aient trouvé : l'app ne trouvait rien ou ne pouvait pas se connecter.
- (Base) iPhone / iPad : si iOS suspend malgré tout BikeControl, il redevient visible sur le réseau de lui-même dès que tu y reviens. Auparavant, il fallait redémarrer la méthode réseau.
- (Base) iPhone / iPad : BikeControl suit immédiatement un changement de Wi-Fi ou de partage de connexion au lieu d'annoncer l'ancienne adresse.
- (Base) iPhone / iPad : la recherche de home trainers Wi-Fi ne remplit plus le journal d'entrées « App crashed ».
- (Base) iPhone, iPad et Mac : l'écran d'accueil t'indique quand BikeControl est introuvable sur le réseau, avec la vérification du réseau à portée de main.
- (Base) Mac : BikeControl est de nouveau trouvé après la sortie de veille du Mac, sans redémarrer la méthode réseau.
- (Base) Vérification du réseau : ne signale plus d'échec pendant que BikeControl parcourt lui-même le réseau, ni quand tu utilises seulement le pont du home trainer avec la connexion de la manette désactivée.
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Palettes Zwift Play / Zwift Ride : incliner vers l'intérieur et vers l'extérieur sont maintenant deux boutons distincts, chacun avec sa propre action. Ton assignation actuelle de la palette s'applique aux deux.

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad: BikeControl ora resta attivo in background mentre aspetta la tua app di allenamento (fino a 15 minuti) e per 5 minuti dopo che l'app si è disconnessa. Prima iOS poteva sospendere BikeControl prima che MyWhoosh e altre app lo trovassero, e l'app non trovava nulla o non riusciva a connettersi.
- (Base) iPhone / iPad: se iOS sospende comunque BikeControl, torna visibile sulla rete da solo appena ci ritorni. Prima bisognava riavviare il metodo di rete.
- (Base) iPhone / iPad: BikeControl segue subito un cambio di Wi-Fi o di hotspot invece di annunciare il vecchio indirizzo.
- (Base) iPhone / iPad: la ricerca dei rulli Wi-Fi non riempie più il registro di voci «App crashed».
- (Base) iPhone, iPad e Mac: la schermata principale ti avvisa quando BikeControl non si trova sulla rete, con il controllo di rete a un tocco.
- (Base) Mac: BikeControl viene trovato di nuovo dopo che il Mac esce dallo stop, senza riavviare il metodo di rete.
- (Base) Controllo di rete: non segnala più un errore mentre BikeControl sta cercando sulla rete, né quando usi solo il ponte del rullo e hai disattivato la connessione del controller.
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Levette di Zwift Play / Zwift Ride: inclinare verso l'interno e verso l'esterno sono ora due pulsanti separati, ognuno con la sua azione. La tua assegnazione attuale della levetta vale per entrambi.

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad: BikeControl pozostaje teraz aktywny w tle, gdy czeka na twoją aplikację treningową (do 15 minut), oraz przez 5 minut po rozłączeniu aplikacji. Wcześniej iOS mógł uśpić BikeControl, zanim MyWhoosh i inne aplikacje go znalazły, więc aplikacja nic nie znajdowała albo nie mogła się połączyć.
- (Base) iPhone / iPad: jeśli iOS mimo to uśpi BikeControl, po powrocie do niego sam znów staje się widoczny w sieci. Wcześniej trzeba było zrestartować metodę sieciową.
- (Base) iPhone / iPad: BikeControl od razu podąża za zmianą Wi-Fi lub hotspotu, zamiast ogłaszać stary adres.
- (Base) iPhone / iPad: wyszukiwanie trenażerów Wi-Fi nie zapełnia już dziennika wpisami „App crashed”.
- (Base) iPhone, iPad i Mac: ekran główny informuje, gdy BikeControl nie można znaleźć w sieci, a sprawdzanie sieci jest o jedno stuknięcie dalej.
- (Base) Mac: BikeControl jest ponownie znajdowany po wybudzeniu Maca, bez restartowania metody sieciowej.
- (Base) Sprawdzanie sieci: nie zgłasza już błędu, gdy BikeControl sam przeszukuje sieć, ani gdy używasz tylko mostka trenażera i masz wyłączone połączenie kontrolera.
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Łopatki Zwift Play / Zwift Ride: przechylenie do środka i na zewnątrz to teraz dwa osobne przyciski, każdy z własną akcją. Twoje dotychczasowe przypisanie łopatki działa dla obu.

View File

@@ -1,7 +1,3 @@
7.6.2
Neu:
• Paddel von Zwift Play / Zwift Ride: Nach innen und nach außen kippen sind jetzt zwei eigene Tasten mit je eigener Aktion. Deine bisherige Paddel-Belegung gilt für beide
• Wahoo App: BikeControl erscheint darin auf einem zweiten Gerät als Bluetooth-Smart-Trainer und übernimmt das virtuelle Schalten
• Elite Rizer / Sterzo: Totzone einstellbar
7.7.0
Behoben:
• Elite Rizer: Ein gesperrter Rizer (rote LED) wird jetzt als gesperrt angezeigt
• Netzwerkprüfung: meldet keinen Fehler mehr, während BikeControl selbst das Netzwerk durchsucht oder wenn du nur die Trainer-Brücke nutzt und die Controller-Verbindung ausgeschaltet hast

View File

@@ -1,7 +1,3 @@
7.6.2
New:
• Zwift Play / Zwift Ride paddles: tilting inward and outward are now two separate buttons, each mappable to its own action. Your existing paddle mapping applies to both
• Wahoo app: BikeControl shows up in it as a Bluetooth smart trainer on a second device and does the virtual shifting
• Elite Rizer / Sterzo: adjustable dead zone
7.7.0
Fixed:
• Elite Rizer: a locked Rizer (red LED) now shows as locked
• Network check: no longer reports a failure while BikeControl is searching the network itself, or when you only use the trainer bridge and have the controller connection switched off

View File

@@ -1,7 +1,3 @@
7.6.2
Novedades:
• Palancas de Zwift Play / Zwift Ride: inclinar hacia dentro y hacia fuera son ahora dos botones distintos, cada uno con su propia acción. Tu asignación actual se aplica a ambos
• App Wahoo: BikeControl aparece como rodillo inteligente Bluetooth en un segundo dispositivo y se encarga del cambio virtual
• Elite Rizer / Sterzo: zona muerta ajustable
7.7.0
Corregido:
• Elite Rizer: un Rizer bloqueado (LED rojo) ahora se muestra como bloqueado
• Comprobación de red: ya no informa de un fallo mientras BikeControl está buscando en la red, ni cuando solo usas el puente del entrenador y tienes desactivada la conexión del mando

View File

@@ -1,7 +1,3 @@
7.6.2
Nouveautés :
• Palettes Zwift Play / Zwift Ride : incliner vers l'intérieur et vers l'extérieur sont maintenant deux boutons distincts, chacun avec sa propre action. Ton assignation actuelle s'applique aux deux
• App Wahoo : BikeControl y apparaît comme home trainer Bluetooth sur un second appareil et assure les vitesses virtuelles
• Elite Rizer / Sterzo : zone morte réglable
7.7.0
Corrigé :
• Elite Rizer : un Rizer verrouillé (LED rouge) s'affiche maintenant comme verrouillé
• Vérification du réseau : ne signale plus d'échec pendant que BikeControl parcourt lui-même le réseau, ni quand tu utilises seulement le pont du home trainer avec la connexion de la manette désactivée

View File

@@ -1,7 +1,3 @@
7.6.2
Novità:
• Levette di Zwift Play / Zwift Ride: inclinare verso l'interno e verso l'esterno sono ora due pulsanti separati, ognuno con la sua azione. La tua assegnazione attuale vale per entrambi
• App Wahoo: BikeControl vi compare come rullo smart Bluetooth su un secondo dispositivo e gestisce il cambio virtuale
• Elite Rizer / Sterzo: zona morta regolabile
7.7.0
Corretto:
• Elite Rizer: un Rizer bloccato (LED rosso) ora viene mostrato come bloccato
• Controllo di rete: non segnala più un errore mentre BikeControl sta cercando sulla rete, né quando usi solo il ponte del rullo e hai disattivato la connessione del controller

View File

@@ -1,7 +1,3 @@
7.6.2
Nowości:
• Łopatki Zwift Play / Zwift Ride: przechylenie do środka i na zewnątrz to teraz dwa osobne przyciski, każdy z własną akcją. Dotychczasowe przypisanie działa dla obu
• Aplikacja Wahoo: BikeControl pojawia się jako trenażer smart Bluetooth na drugim urządzeniu i zmienia wirtualne biegi
• Elite Rizer / Sterzo: regulowana martwa strefa
7.7.0
Poprawki:
• Elite Rizer: zablokowany Rizer (czerwona dioda) jest teraz pokazywany jako zablokowany
• Sprawdzanie sieci: nie zgłasza już błędu, gdy BikeControl sam przeszukuje sieć, ani gdy używasz tylko mostka trenażera i masz wyłączone połączenie kontrolera

View File

@@ -1,3 +1,13 @@
### 7.7.0 (24-11-2026)
**Fixes**:
- (Base) iPhone / iPad:BikeControl 现在在后台等待训练应用时会保持运行(最长 15 分钟),并在应用断开后继续保持 5 分钟。以前 iOS 可能在 MyWhoosh 等应用找到 BikeControl 之前就让它休眠,导致应用找不到或无法连接。
- (Base) iPhone / iPad:如果 iOS 仍然让 BikeControl 休眠,回到 BikeControl 后它会自动重新出现在网络上。以前需要重启网络方式。
- (Base) iPhone / iPad:切换 Wi-Fi 或热点后,BikeControl 会立即跟随,而不是继续广播旧地址。
- (Base) iPhone / iPad:搜索 Wi-Fi 骑行台不再让日志充满“App crashed”条目。
- (Base) iPhone、iPad 和 Mac:当网络上找不到 BikeControl 时,主屏幕会提示你,并可一键打开网络检查。
- (Base) Mac:Mac 从睡眠中唤醒后,无需重启网络方式即可再次找到 BikeControl。
- (Base) 网络检查:当 BikeControl 自己正在搜索网络时,或你只使用骑行台桥接并关闭了控制器连接时,不再报告失败。
### 7.6.2 (23-11-2026)
**Features**:
- (Base) Zwift Play / Zwift Ride 拨片:向内拨和向外拨现在是两个独立的按键,可分别设置各自的操作。原有的拨片设置会同时应用到两者。

View File

@@ -1,5 +1,6 @@
import Flutter
import Foundation
import Network
import dnssd
// dns_sd error constants import as Int.
@@ -38,13 +39,22 @@ final class DnsSdAdvertiser: NSObject {
private var nextHandle = 1
/// Set once Bonjour reports the host record or a service gone after it was
/// published (iOS defuncts a suspended app's mDNSResponder connection).
/// `updateHost` then fails so the Dart side registers everything again.
private var registrationLost = false
/// published (iOS defuncts a suspended app's mDNSResponder connection):
/// what was lost and the dns_sd error code. `updateHost` then fails and
/// `lostReason` reports it, so the Dart side registers everything again.
private var lostReason: String?
private var channel: FlutterMethodChannel?
/// Tells the Dart side when the device's network path changes, so the
/// advertised address follows at once instead of at the next timer tick.
private var pathMonitor: NWPathMonitor?
private var pathReported = false
func register(with registry: FlutterPluginRegistry) {
guard let registrar = registry.registrar(forPlugin: "BikeControlDnsSd") else { return }
let channel = FlutterMethodChannel(name: Self.channelName, binaryMessenger: registrar.messenger())
self.channel = channel
channel.setMethodCallHandler { [weak self] call, result in
guard let self else { return result(nil) }
let args = call.arguments as? [String: Any] ?? [:]
@@ -63,6 +73,8 @@ final class DnsSdAdvertiser: NSObject {
case "unregisterHost":
self.unregisterHost()
Self.reply(result, nil)
case "lostReason":
Self.reply(result, self.lostReason)
case "registerService":
self.registerService(args, result: result)
case "unregisterService":
@@ -81,7 +93,8 @@ final class DnsSdAdvertiser: NSObject {
private func registerHost(label: String, ipv4: String, result: @escaping FlutterResult) {
unregisterHost()
registrationLost = false
lostReason = nil
startPathMonitor()
guard var address = Self.parseIPv4(ipv4) else {
return Self.reply(result, FlutterError(code: "address", message: "not an IPv4: \(ipv4)", details: nil))
}
@@ -135,7 +148,7 @@ final class DnsSdAdvertiser: NSObject {
guard let result = pendingHostResult else {
if errorCode != dnsNoError {
NSLog("DnsSdAdvertiser: host record \(hostLabel ?? "?") lost after registration: \(errorCode)")
registrationLost = true
markLost("host record lost: \(errorCode)")
}
return
}
@@ -151,18 +164,20 @@ final class DnsSdAdvertiser: NSObject {
}
private func updateHost(ipv4: String, result: @escaping FlutterResult) {
guard let connection = hostConnection, let record = hostRecord, let label = hostLabel else {
guard let connection = hostConnection, let record = hostRecord, hostLabel != nil else {
return Self.reply(result, FlutterError(code: "state", message: "no host registered", details: nil))
}
if registrationLost {
return Self.reply(result, FlutterError(code: "lost", message: "registration lost", details: nil))
if let lostReason {
return Self.reply(result, FlutterError(code: "lost", message: lostReason, details: nil))
}
guard var address = Self.parseIPv4(ipv4) else {
return Self.reply(result, FlutterError(code: "address", message: "not an IPv4: \(ipv4)", details: nil))
}
// A record pinned to the old interface cannot just change its rdata.
// A record pinned to the old interface cannot just change its rdata, and
// the services are registered on that interface too. The Dart side
// registers the host and every service again.
if Self.interfaceIndex(for: ipv4) != hostInterface {
return registerHost(label: label, ipv4: ipv4, result: result)
return Self.reply(result, FlutterError(code: "interface", message: "address is on another interface", details: nil))
}
let err = withUnsafeBytes(of: &address) { bytes in
DNSServiceUpdateRecord(connection, record, 0, UInt16(bytes.count), bytes.baseAddress, Self.recordTtl)
@@ -170,6 +185,35 @@ final class DnsSdAdvertiser: NSObject {
Self.reply(result, err == dnsNoError ? nil : Self.dnsError("DNSServiceUpdateRecord", err))
}
private func markLost(_ reason: String) {
let first = lostReason == nil
lostReason = reason
if first { sendEvent("lost") }
}
private func sendEvent(_ event: String) {
DispatchQueue.main.async { [weak self] in
self?.channel?.invokeMethod("event", arguments: event)
}
}
/// Runs while a host is registered. The first update only reports the
/// current path, so it is skipped.
private func startPathMonitor() {
guard pathMonitor == nil else { return }
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { [weak self] _ in
guard let self else { return }
if !self.pathReported {
self.pathReported = true
return
}
self.sendEvent("pathChanged")
}
monitor.start(queue: queue)
pathMonitor = monitor
}
/// Deallocating the connection withdraws its records (goodbye packets).
private func unregisterHost() {
hostProbeTimeout?.cancel()
@@ -213,8 +257,8 @@ final class DnsSdAdvertiser: NSObject {
guard errorCode != dnsNoError else { return }
NSLog("DnsSdAdvertiser: service \(name.map { String(cString: $0) } ?? "?") failed: \(errorCode)")
guard let context else { return }
// Callbacks run on `queue`, like every other access to this flag.
Unmanaged<DnsSdAdvertiser>.fromOpaque(context).takeUnretainedValue().registrationLost = true
// Callbacks run on `queue`, like every other access to this state.
Unmanaged<DnsSdAdvertiser>.fromOpaque(context).takeUnretainedValue().markLost("service lost: \(errorCode)")
},
Unmanaged.passUnretained(self).toOpaque()
)

View File

@@ -57,7 +57,6 @@ class WhooshLink extends TrainerConnection {
if (kDebugMode) {
print('Client connected: ${socket.remoteAddress.address}:${socket.remotePort}');
}
SharedLogic.keepAlive();
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_INFO, AppLocalizations.current.myWhooshLinkConnected),
);
@@ -76,7 +75,6 @@ class WhooshLink extends TrainerConnection {
if (kDebugMode) {
print('Client disconnected');
}
SharedLogic.stopKeepAlive();
isConnected.value = false;
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_WARNING, 'MyWhoosh Link disconnected'),

View File

@@ -398,7 +398,6 @@ class OpenBikeControlMdnsEmulator extends TrainerConnection implements OnMessage
owner: this,
label: 'OpenBikeControl',
onClientConnected: (socket) {
SharedLogic.keepAlive();
if (kDebugMode) {
print('Client connected: ${socket.remoteAddress.address}:${socket.remotePort}');
}
@@ -424,7 +423,6 @@ class OpenBikeControlMdnsEmulator extends TrainerConnection implements OnMessage
},
onClientDisconnected: () {
_dirCon = null;
SharedLogic.stopKeepAlive();
core.connection.signalNotification(
AlertNotification(LogLevel.LOGLEVEL_INFO, 'Disconnected from app: ${connectedApp.value?.appId}'),
);

View File

@@ -2371,6 +2371,9 @@
"@chainStepNetworkAddressNoWifiHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "Dieses Gerät ist in zwei Netzwerken ({address}). Bring es und {app} ins selbe WLAN.",
"@chainStepNetworkAddressTwoNetworksHint": {"placeholders": {"address": {"type": "String"}, "app": {"type": "String"}}},
"chainStepNetworkNotVisiblePending": "BikeControl ist im Netzwerk nicht sichtbar",
"chainStepNetworkNotVisibleHint": "{app} findet BikeControl im Netzwerk gerade nicht. Starte die Netzwerkprüfung und dort die Netzwerkmethode neu.",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressAction": "Netzwerk prüfen",
"chainStatusAppDisconnected": "{app} hat die Verbindung getrennt",
"@chainStatusAppDisconnected": {"placeholders": {"app": {"type": "String"}}},

View File

@@ -2609,6 +2609,9 @@
"@chainStepNetworkAddressNoWifiHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "This device is on two networks ({address}). Put it and {app} on the same Wi-Fi.",
"@chainStepNetworkAddressTwoNetworksHint": {"placeholders": {"address": {"type": "String"}, "app": {"type": "String"}}},
"chainStepNetworkNotVisiblePending": "BikeControl isn't visible on the network",
"chainStepNetworkNotVisibleHint": "{app} can't find BikeControl on the network right now. Run the network check and restart the network method there.",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressAction": "Run network check",
"chainStatusAppDisconnected": "{app} disconnected",
"@chainStatusAppDisconnected": {"placeholders": {"app": {"type": "String"}}},

View File

@@ -2369,6 +2369,9 @@
"@chainStepNetworkAddressNoWifiHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "Este dispositivo está en dos redes ({address}). Pon este y {app} en la misma Wi-Fi.",
"@chainStepNetworkAddressTwoNetworksHint": {"placeholders": {"address": {"type": "String"}, "app": {"type": "String"}}},
"chainStepNetworkNotVisiblePending": "BikeControl no es visible en la red",
"chainStepNetworkNotVisibleHint": "{app} no encuentra BikeControl en la red ahora mismo. Ejecuta la comprobación de red y reinicia allí el método de red.",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressAction": "Comprobar la red",
"supportAccountLinkEmailTaken": "{email} ya tiene una cuenta de BikeControl, así que no se puede añadir a este chat. Para usar esa cuenta, inicia sesión en Ajustes → Plan y cuenta. Esta conversación no se trasladará, así que vuelve a enviar tu mensaje desde allí. O introduce otro correo electrónico.",
"@supportAccountLinkEmailTaken": {"placeholders": {"email": {"type": "String"}}},

View File

@@ -2369,6 +2369,9 @@
"@chainStepNetworkAddressNoWifiHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "Cet appareil est sur deux réseaux ({address}). Mets-le sur le même Wi-Fi que {app}.",
"@chainStepNetworkAddressTwoNetworksHint": {"placeholders": {"address": {"type": "String"}, "app": {"type": "String"}}},
"chainStepNetworkNotVisiblePending": "BikeControl n'est pas visible sur le réseau",
"chainStepNetworkNotVisibleHint": "{app} ne trouve pas BikeControl sur le réseau pour le moment. Lance la vérification du réseau et redémarre la méthode réseau depuis celle-ci.",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressAction": "Lancer le test réseau",
"supportAccountLinkEmailTaken": "{email} a déjà un compte BikeControl, cette adresse ne peut donc pas être ajoutée à ce chat. Pour utiliser ce compte, connecte-toi dans Réglages → Offre et compte. Cette conversation ne sera pas transférée, renvoie donc ton message depuis là-bas. Ou saisis une autre adresse e-mail.",
"@supportAccountLinkEmailTaken": {"placeholders": {"email": {"type": "String"}}},

View File

@@ -2369,6 +2369,9 @@
"@chainStepNetworkAddressNoWifiHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "Questo dispositivo è su due reti ({address}). Mettilo sulla stessa Wi-Fi di {app}.",
"@chainStepNetworkAddressTwoNetworksHint": {"placeholders": {"address": {"type": "String"}, "app": {"type": "String"}}},
"chainStepNetworkNotVisiblePending": "BikeControl non è visibile sulla rete",
"chainStepNetworkNotVisibleHint": "{app} al momento non trova BikeControl sulla rete. Avvia il controllo di rete e riavvia da lì il metodo di rete.",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressAction": "Esegui il controllo di rete",
"supportAccountLinkEmailTaken": "{email} ha già un account BikeControl, quindi non può essere aggiunto a questa chat. Per usare quell'account, accedi da Impostazioni → Piano e account. Questa conversazione non verrà trasferita, quindi invia di nuovo il tuo messaggio da lì. Oppure inserisci un'altra email.",
"@supportAccountLinkEmailTaken": {"placeholders": {"email": {"type": "String"}}},

View File

@@ -2369,6 +2369,9 @@
"@chainStepNetworkAddressNoWifiHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "To urządzenie jest w dwóch sieciach ({address}). Połącz je i {app} z tym samym Wi-Fi.",
"@chainStepNetworkAddressTwoNetworksHint": {"placeholders": {"address": {"type": "String"}, "app": {"type": "String"}}},
"chainStepNetworkNotVisiblePending": "BikeControl nie jest widoczny w sieci",
"chainStepNetworkNotVisibleHint": "{app} nie znajduje teraz BikeControl w sieci. Uruchom sprawdzanie sieci i zrestartuj tam metodę sieciową.",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressAction": "Sprawdź sieć",
"supportAccountLinkEmailTaken": "{email} ma już konto BikeControl, więc nie można go dodać do tego czatu. Aby użyć tego konta, zaloguj się w Ustawienia → Plan i konto. Ta rozmowa nie zostanie przeniesiona, więc wyślij swoją wiadomość ponownie stamtąd. Możesz też podać inny adres e-mail.",
"@supportAccountLinkEmailTaken": {"placeholders": {"email": {"type": "String"}}},

View File

@@ -2836,6 +2836,9 @@
}
}
},
"chainStepNetworkNotVisiblePending": "网络上看不到 BikeControl",
"chainStepNetworkNotVisibleHint": "{app} 目前在网络上找不到 BikeControl。请运行网络检查,并在其中重启网络方式。",
"@chainStepNetworkNotVisibleHint": {"placeholders": {"app": {"type": "String"}}},
"chainStepNetworkAddressTwoNetworksHint": "此设备同时连接了两个网络({address})。请让它和 {app} 连接同一个 Wi-Fi。",
"@chainStepNetworkAddressTwoNetworksHint": {
"placeholders": {

View File

@@ -30,6 +30,7 @@ import 'package:prop/utils/shared.dart' show Logger;
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:universal_ble/universal_ble.dart';
import 'package:window_manager/window_manager.dart' as wm;
import 'package:bike_control/services/network_recovery.dart';
import 'package:bike_control/services/app_update.dart';
import 'package:bike_control/widgets/title.dart' show packageInfoValue;
import 'package:path_provider/path_provider.dart';
@@ -194,6 +195,7 @@ Future<void> main(List<String> args) async {
// shape through Bonjour's dns_sd API instead.
if (!kIsWeb) {
ServiceAdvertiser.instance = ServiceAdvertiser.platformDefault();
NetworkRecovery.instance.start();
}
// Catch Flutter framework errors (build/layout/paint)
@@ -958,6 +960,7 @@ class _StarterState extends State<_Starter> with WidgetsBindingObserver {
if (state == AppLifecycleState.resumed) {
unawaited(IAPManager.instance.refreshEntitlementsOnResume());
}
NetworkRecovery.instance.onLifecycleState(state);
// The process can outlive this engine on Android (foreground service);
// release the server ports so the next launch gets them back.
if (!kIsWeb && Platform.isAndroid) unawaited(stopNetworkServersOnLifecycleChange(state));

View File

@@ -358,6 +358,7 @@ ChainLink _appLink(ChainInputs inputs) {
variant: switch (app.advertisedAddressWarningKind) {
AddressWarningKind.noWifi => SetupStepVariant.networkNoWifi,
AddressWarningKind.twoNetworks => SetupStepVariant.networkTwoNetworks,
AddressWarningKind.notVisible => SetupStepVariant.networkNotVisible,
AddressWarningKind.unreachable || null => SetupStepVariant.standard,
},
),

View File

@@ -108,6 +108,10 @@ enum SetupStepVariant {
/// second real network could be the one the trainer app is on.
networkTwoNetworks,
/// [SetupStepId.appNetworkAddress] when the address is fine but
/// BikeControl's own advertisement cannot be found on the network.
networkNotVisible,
/// [SetupStepId.trainerAppBridged] when the trainer app probably still holds
/// a Bluetooth connection from before BikeControl restarted (Windows): the
/// hint says to remove the entry in the app and pair it again.

View File

@@ -47,6 +47,8 @@ import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/utils/iap/iap_manager.dart';
import 'package:bike_control/utils/keymap/apps/bike_control.dart';
import 'package:bike_control/services/local_network_access.dart';
import 'package:bike_control/services/mdns_discovery_scan.dart';
import 'package:bike_control/services/network_recovery.dart';
import 'package:bike_control/services/network_self_test/probes/passive_probes.dart'
show AddressWarningKind, advertisedAddressWarning, advertisedAddressWarningKind;
import 'package:bike_control/utils/requirements/local_network.dart';
@@ -76,6 +78,7 @@ import 'package:bike_control/widgets/ui/colors.dart' show bkAccentText;
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:dartx/dartx.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:prop/utils/advertised_service_registry.dart';
import 'package:prop/emulators/definitions/fitness_bike_definition.dart';
import 'package:prop/emulators/dircon_emulator.dart' show RetrofitMode;
import 'package:prop/mdns/service_advertiser.dart' show ServiceAdvertiser;
@@ -253,15 +256,68 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
/// Why [_advertisedAddressWarning] was raised — see [AppInput.advertisedAddressWarningKind].
AddressWarningKind? _advertisedAddressWarningKind;
Future<void> _refreshAdvertisedAddress() async {
/// The own advertisement was not found on the network, even after it was
/// published again. Set by the look [_refreshAdvertisedAddress] takes when
/// asked to; kept across the cheaper refreshes in between.
bool _advertisementInvisible = false;
/// The visibility look in flight, so overlapping triggers share one browse.
Future<void>? _visibilityLook;
/// When the last look started. A Mac window regains focus many times a
/// minute with the trainer app next to it; one browse per pause is plenty.
DateTime? _lastVisibilityLookAt;
static const _visibilityLookPause = Duration(minutes: 2);
/// Stands in for the address when the advertisement itself is missing.
static const _notVisibleMarker = 'not visible';
Future<void> _lookForOwnAdvertisement() async {
final visible = await NetworkRecovery.instance.ensureAdvertisementVisible(
advertising: () =>
core.logic.hasNetworkMethodEnabled &&
AdvertisedServiceRegistry.instance.records.isNotEmpty &&
!_trainerAppConnectedOverNetwork,
ownAdvertisementSeen: () async => (await MdnsDiscoveryScan().run()).any((service) => service.isSelf),
);
_advertisementInvisible = !visible;
}
bool get _trainerAppConnectedOverNetwork =>
core.obpMdnsEmulator.isConnected.value ||
core.zwiftMdnsEmulator.isConnected.value ||
core.rouvyMdnsEmulator.isConnected.value ||
core.whooshLink.isConnected.value;
/// [lookForAdvertisement] also browses for our own advertisement (a few
/// seconds, and it may publish everything again): on start, on return to
/// the foreground, and while it is flagged missing.
Future<void> _refreshAdvertisedAddress({bool lookForAdvertisement = false}) async {
// The store board sells a finished setup, and a VPN on the screenshot
// machine must not end up in a listing. The web has no interfaces to
// list, and without a network method nothing is advertised at all.
final applies = !kIsWeb && !screenshotMode && core.logic.hasNetworkMethodEnabled;
try {
final report = applies ? await AdvertisedAddressPicker.report() : null;
final warning = report == null ? null : advertisedAddressWarning(report);
final kind = report == null ? null : advertisedAddressWarningKind(report);
var warning = report == null ? null : advertisedAddressWarning(report);
var kind = report == null ? null : advertisedAddressWarningKind(report);
if (!applies) {
_advertisementInvisible = false;
} else if (lookForAdvertisement && warning == null) {
final last = _lastVisibilityLookAt;
// Flagged missing: look again sooner, a restart may have fixed it.
final pause = _advertisementInvisible ? const Duration(seconds: 20) : _visibilityLookPause;
final due = last == null || DateTime.now().difference(last) >= pause;
if (_visibilityLook != null || due) {
_lastVisibilityLookAt = DateTime.now();
await (_visibilityLook ??= _lookForOwnAdvertisement().whenComplete(() => _visibilityLook = null));
}
}
// An address problem explains a missing advertisement, so it wins.
if (warning == null && applies && _advertisementInvisible && !_trainerAppConnectedOverNetwork) {
warning = _notVisibleMarker;
kind = AddressWarningKind.notVisible;
}
// The session keeps the reading an app connected through, whether or
// not this page is still around to show it.
core.appConnectionLatch.noteAddressWarning(warning);
@@ -295,7 +351,8 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
];
void _onAdvertisedAddressChanged() {
unawaited(_refreshAdvertisedAddress());
// A method that was restarted may be visible again: look once more.
unawaited(_refreshAdvertisedAddress(lookForAdvertisement: _advertisementInvisible));
}
@override
@@ -303,7 +360,7 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
super.initState();
unawaited(_refreshLocalNetwork());
unawaited(_refreshAdvertisedAddress());
unawaited(_refreshAdvertisedAddress(lookForAdvertisement: true));
for (final listenable in _advertisedAddressListenables) {
listenable.addListener(_onAdvertisedAddressChanged);
}
@@ -533,7 +590,7 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) unawaited(_refreshAdvertisedAddress());
if (state == AppLifecycleState.resumed) unawaited(_refreshAdvertisedAddress(lookForAdvertisement: true));
}
void _onPurchaseChanged() {

View File

@@ -23,6 +23,7 @@ import 'package:bike_control/services/telemetry_snapshot.dart';
import 'package:bike_control/widgets/ui/type_scale.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/requirements/multi.dart' show Target;
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/widgets/logviewer.dart';
import 'package:bike_control/widgets/menu.dart' show debugText;
@@ -70,6 +71,11 @@ NetworkProbeContext buildProductionContext({DebugDiagnostics? snapshot, Object?
advertisedHostname: target.advertisedHostname,
methodServerLabel: target.serverLabel,
methodPreferredPort: target.preferredPort,
trainerAppOnThisDevice: switch (core.settings.getLastTarget()) {
Target.thisDevice => true,
Target.otherDevice => false,
null => null,
},
platform: platformString(),
resolve: defaultResolve,
tcpProbe: (address, port) => defaultTcpProbe(address, port, label: target.serverLabel),
@@ -104,7 +110,9 @@ String networkPassBody(
app,
OpenBikeControlMdnsEmulator.controllerTileNameFor(core.settings.getTrainerApp()),
),
NetworkMethodKind.rouvyMdns || NetworkMethodKind.zwiftMdns => l10n.networkNextStepPairingScreen(app),
NetworkMethodKind.rouvyMdns ||
NetworkMethodKind.zwiftMdns ||
NetworkMethodKind.trainerBridge => l10n.networkNextStepPairingScreen(app),
};
}

View File

@@ -2,6 +2,7 @@ import 'package:bike_control/main.dart' show recordError;
import 'package:bike_control/services/local_network_access.dart';
import 'package:bike_control/services/mdns_discovery_scan.dart';
import 'package:bike_control/services/mdns_query_privacy.dart';
import 'package:bike_control/services/network_recovery.dart';
import 'package:flutter/foundation.dart';
import 'package:local_network_permission/local_network_permission.dart';
import 'package:prop/mdns/mdns_responder.dart' show MdnsQueryLogEntry;
@@ -75,6 +76,14 @@ class DebugDiagnostics {
/// OS responder handles queries and never tells us about them.
final List<MdnsQueryLogEntry> recentQueries;
/// What clients did on our TCP ports lately: who connected, and whether
/// they hung up before sending anything.
final List<TcpConnectionLogEntry> connections;
/// When the app last left and returned, whether the process stood still
/// and what was repaired afterwards. Empty where that is not tracked.
final List<String> lifecycle;
const DebugDiagnostics({
required this.advertised,
required this.backend,
@@ -86,6 +95,8 @@ class DebugDiagnostics {
required this.servers,
required this.permissions,
this.recentQueries = const [],
this.connections = const [],
this.lifecycle = const [],
});
static Future<DebugDiagnostics> gather({
@@ -150,6 +161,8 @@ class DebugDiagnostics {
servers: servers,
permissions: permissions,
recentQueries: isResponder ? advertiser.recentQueries : const [],
connections: ResilientTcpServer.connectionLog,
lifecycle: NetworkRecovery.instance.diagnosticLines(),
);
}
@@ -324,6 +337,24 @@ class DebugDiagnostics {
}
}
// Without this a "no client" row cannot tell an app that never dialled
// from one that connected and hung up at once.
b.writeln(' TCP connections:');
if (connections.isEmpty) {
b.writeln(' (none since the app started)');
} else {
for (final c in connections) {
b.writeln(' ${c.at.toIso8601String().split('T').last.split('.').first} $c');
}
}
if (lifecycle.isNotEmpty) {
b.writeln(' Lifecycle:');
for (final line in lifecycle) {
b.writeln(' $line');
}
}
final localNetwork = permissions.localNetwork;
if (localNetwork != null) {
b.writeln(' Permissions: local-network=${localNetwork.name}');

View File

@@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:bike_control/main.dart' show recordError;
import 'package:flutter/foundation.dart';
import 'package:prop/mdns/dns_message.dart';
/// Resolves a `.local` hostname to an IPv4 address with a one-shot mDNS
@@ -14,6 +16,11 @@ import 'package:prop/mdns/dns_message.dart';
///
/// Sends a legacy-unicast query (RFC 6762 §6.7) from an ephemeral port, so no
/// socket on 5353 is needed and the responder answers straight back to us.
///
/// Not on iOS: an app may not send multicast there without an entitlement
/// BikeControl does not have, so every query failed with "No route to host"
/// (errno 65). iOS resolves `.local` names through the system resolver, which
/// is used instead.
class MdnsHostResolver {
static final mdnsGroup = InternetAddress('224.0.0.251');
static const mdnsPort = 5353;
@@ -25,10 +32,25 @@ class MdnsHostResolver {
Duration timeout = const Duration(seconds: 2),
InternetAddress? target,
int port = mdnsPort,
bool? useSystemResolver,
Future<List<InternetAddress>> Function(String host)? systemLookup,
}) async {
final name = DnsName.fromString(host);
if (name.labels.isEmpty) return null;
if (useSystemResolver ?? (!kIsWeb && target == null && Platform.isIOS)) {
try {
final lookup = systemLookup ?? ((h) => InternetAddress.lookup(h, type: InternetAddressType.IPv4));
final addresses = await lookup(host).timeout(timeout);
return addresses.where((a) => a.type == InternetAddressType.IPv4).firstOrNull?.address;
} on SocketException {
// The name does not resolve (yet); the caller falls back to the host.
return null;
} on TimeoutException {
return null;
}
}
final RawDatagramSocket socket;
try {
socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);
@@ -55,6 +77,12 @@ class MdnsHostResolver {
return;
}
}
}, onError: (Object e, StackTrace s) {
// dart:io reports a failed send here, not from send(), and closes the
// socket. Without a handler it reached the root zone and was logged as
// an app crash on every attempt.
recordError(e, s, context: 'MdnsHostResolver $host');
if (!result.isCompleted) result.complete(null);
});
// Multicast is lossy; repeat the question a couple of times.

View File

@@ -0,0 +1,143 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart' show AppLifecycleState;
import 'package:prop/mdns/service_advertiser.dart';
import 'package:prop/utils/resilient_tcp_server.dart';
import 'package:prop/utils/shared.dart';
import 'package:prop/utils/suspension_watch.dart';
import '../main.dart' show recordError;
/// Brings the network methods back after the app was suspended (iOS) or the
/// machine slept (macOS), and keeps the record of it for the support bundle.
///
/// iOS closes a suspended app's listening sockets and its Bonjour
/// registration. The servers still look started and the advertisement still
/// looks published, so a trainer app finds nothing until the method is
/// restarted by hand. A Mac that slept can wake with a responder socket that
/// no longer hears the network. Both show up as a standstill on
/// [SuspensionWatch]; this class answers one by binding the listeners again
/// (iOS) and publishing the advertisement again.
class NetworkRecovery {
NetworkRecovery({
SuspensionWatch? watch,
TargetPlatform? platform,
Future<void> Function()? rebindListeners,
Future<void> Function({bool force})? recoverAdvertiser,
void Function()? refreshKeepAlive,
DateTime Function() now = DateTime.now,
}) : _watch = watch ?? SuspensionWatch.instance,
_platform = platform,
_rebindListeners = rebindListeners ?? ResilientTcpServer.rebindAllListeners,
_recoverAdvertiser = recoverAdvertiser ?? RecoverableAdvertiser.recoverInstance,
_refreshKeepAlive = refreshKeepAlive ?? SharedLogic.refreshKeepAlive,
_now = now;
static final NetworkRecovery instance = NetworkRecovery();
final SuspensionWatch _watch;
final TargetPlatform? _platform;
final Future<void> Function() _rebindListeners;
final Future<void> Function({bool force}) _recoverAdvertiser;
final void Function() _refreshKeepAlive;
final DateTime Function() _now;
DateTime? lastBackgroundAt;
DateTime? lastResumeAt;
DateTime? lastRecoveryAt;
bool _started = false;
TargetPlatform get _target => _platform ?? defaultTargetPlatform;
/// Only the Apple platforms for now; the others keep their behaviour.
bool get _applies => !kIsWeb && (_target == TargetPlatform.iOS || _target == TargetPlatform.macOS);
void start() {
if (_started || !_applies) return;
_started = true;
_watch
..addListener(_afterStandstill)
..start();
}
void onLifecycleState(AppLifecycleState state) {
if (!_applies) return;
switch (state) {
case AppLifecycleState.resumed:
lastResumeAt = _now();
// A standstill is acted on now rather than at the next tick.
_watch.check();
_refreshKeepAlive();
// Also without a standstill: the address may have moved, or Bonjour
// may have reported the registration lost while we were away.
_guard(_recoverAdvertiser(), 'NetworkRecovery.resume');
case AppLifecycleState.inactive || AppLifecycleState.hidden || AppLifecycleState.paused:
if (state == AppLifecycleState.paused) lastBackgroundAt = _now();
// The waiting limit counts from the moment the rider leaves.
_refreshKeepAlive();
case AppLifecycleState.detached:
break;
}
}
Future<void> _afterStandstill(Duration gap) async {
lastRecoveryAt = _now();
if (_target == TargetPlatform.iOS) {
await _rebindListeners();
}
await _recoverAdvertiser(force: true);
}
/// Whether a trainer app can find what we advertise, repairing it once
/// when it cannot.
///
/// Browses for our own advertisement the way a trainer app would. When it
/// is missing, the listeners are bound again (iOS) and everything is
/// published again, and the browse is repeated. False only when it is
/// still missing after that; true when nothing is advertised or on a
/// platform this does not apply to.
Future<bool> ensureAdvertisementVisible({
required bool Function() advertising,
required Future<bool> Function() ownAdvertisementSeen,
Duration settle = const Duration(seconds: 2),
}) async {
if (!_applies || !advertising()) return true;
if (await ownAdvertisementSeen()) return true;
lastRecoveryAt = _now();
if (_target == TargetPlatform.iOS) {
await _rebindListeners();
}
await _recoverAdvertiser(force: true);
// Bonjour probes and announces before a browse can see the records.
await Future<void>.delayed(settle);
if (!advertising()) return true;
final seen = await ownAdvertisementSeen();
lastInvisibleAt = seen ? null : _now();
return seen;
}
/// When the advertisement was last found missing even after a repair.
DateTime? lastInvisibleAt;
void _guard(Future<void> future, String context) {
unawaited(future.catchError((Object e, StackTrace s) => recordError(e, s, context: context)));
}
/// Lines for the support bundle: when the app last left and came back,
/// whether the process stood still, and what was repaired.
List<String> diagnosticLines() {
if (!_applies) return const [];
String time(DateTime? at) => at == null ? 'never' : at.toIso8601String().split('.').first;
final advertiser = ServiceAdvertiser.instance;
final recovery = advertiser is RecoverableAdvertiser ? (advertiser as RecoverableAdvertiser).recoveryStatus : null;
return [
'last background ${time(lastBackgroundAt)} · last resume ${time(lastResumeAt)}',
'standstill: ${_watch.status}',
if (lastRecoveryAt != null) 'recovered after a standstill at ${time(lastRecoveryAt)}',
if (recovery != null) 'advertisement: $recovery',
if (lastInvisibleAt != null) 'own advertisement not found after a repair at ${time(lastInvisibleAt)}',
if (_target == TargetPlatform.iOS) 'keep-alive: ${SharedLogic.keepAliveStatus}',
];
}
}

View File

@@ -13,4 +13,8 @@ enum AddressWarningKind {
/// The pick is fine, but a second real network could be the app's.
twoNetworks,
/// The address is fine, but BikeControl's advertisement cannot be found on
/// the network, even after publishing it again.
notVisible,
}

View File

@@ -6,11 +6,20 @@ import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/keymap/apps/supported_app.dart';
import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:prop/emulators/dircon_emulator.dart' show DirconEmulator;
import 'package:prop/mdns/service_advertiser.dart';
import 'package:prop/utils/resilient_tcp_server.dart';
/// Which mDNS network method the self-test examines.
enum NetworkMethodKind { openBikeControl, rouvyMdns, zwiftMdns }
enum NetworkMethodKind {
openBikeControl,
rouvyMdns,
zwiftMdns,
/// The trainer bridge alone: the app's own controller method is switched
/// off and only the bridged trainer is served over the network.
trainerBridge,
}
/// The port prop's `ClickEmulator` binds when nothing else holds it. Mirrors
/// its private `_port`; the TCP server it creates carries the same value as
@@ -61,7 +70,9 @@ class NetworkMethodTarget {
/// [ObpMdnsBackend.platformDefault] denotes.
ObpMdnsBackend get backend => switch (kind) {
NetworkMethodKind.openBikeControl => core.obpMdnsEmulator.activeBackend,
NetworkMethodKind.rouvyMdns || NetworkMethodKind.zwiftMdns => ObpMdnsBackend.platformDefault,
NetworkMethodKind.rouvyMdns ||
NetworkMethodKind.zwiftMdns ||
NetworkMethodKind.trainerBridge => ObpMdnsBackend.platformDefault,
};
/// The hostname the method's advertisement resolves under; null when
@@ -75,6 +86,7 @@ class NetworkMethodTarget {
return core.obpMdnsEmulator.advertisedHostname;
case NetworkMethodKind.rouvyMdns:
case NetworkMethodKind.zwiftMdns:
case NetworkMethodKind.trainerBridge:
if (!isStarted.value) return null;
final advertiser = ServiceAdvertiser.instance;
if (advertiser is ResponderServiceAdvertiser) {
@@ -107,6 +119,12 @@ class NetworkMethodTarget {
case NetworkMethodKind.zwiftMdns:
core.zwiftMdnsEmulator.stop();
await core.zwiftMdnsEmulator.startServer();
case NetworkMethodKind.trainerBridge:
// The bridge belongs to the trainer's connection; stopping it would
// drop the trainer. Its network side is what can be done over:
// bind the listeners again and publish the advertisement again.
await ResilientTcpServer.rebindAllListeners();
await RecoverableAdvertiser.recoverInstance(force: true);
}
} catch (_) {
await _setEnabled(wasEnabled);
@@ -117,17 +135,22 @@ class NetworkMethodTarget {
bool get _isEnabled => switch (kind) {
NetworkMethodKind.openBikeControl => core.settings.getObpMdnsEnabled(),
NetworkMethodKind.rouvyMdns || NetworkMethodKind.zwiftMdns => core.settings.getZwiftMdnsEmulatorEnabled(),
NetworkMethodKind.trainerBridge => true,
};
Future<void> _setEnabled(bool enabled) => switch (kind) {
NetworkMethodKind.openBikeControl => core.settings.setObpMdnsEnabled(enabled),
NetworkMethodKind.rouvyMdns || NetworkMethodKind.zwiftMdns => core.settings.setZwiftMdnsEmulatorEnabled(enabled),
// Follows the trainer's connection; there is no switch to flip.
NetworkMethodKind.trainerBridge => Future<void>.value(),
};
/// What to tell the rider when [restart] threw.
String get restartFailedMessage => switch (kind) {
NetworkMethodKind.openBikeControl => AppLocalizations.current.errorStartingOpenBikeControlServer,
NetworkMethodKind.rouvyMdns || NetworkMethodKind.zwiftMdns => AppLocalizations.current.networkFixFailed,
NetworkMethodKind.rouvyMdns ||
NetworkMethodKind.zwiftMdns ||
NetworkMethodKind.trainerBridge => AppLocalizations.current.networkFixFailed,
};
}
@@ -135,10 +158,27 @@ class NetworkMethodTarget {
/// lists it (the historical behaviour, and the fallback when no app is
/// selected or it has no mDNS method at all); otherwise Rouvy's Click server
/// or Zwift's DirCon server.
NetworkMethodTarget resolveNetworkMethodTarget(SupportedApp? app) {
///
/// One exception: an OpenBikeControl app whose controller method the rider
/// switched off while a trainer bridge is being served. The bridge is then
/// the only network link in use, and checking the switched-off method
/// reported a failure ("not started", "advertisement not seen") on a setup
/// that works. [trainerBridges] lists the bridge emulators; tests pass their
/// own.
NetworkMethodTarget resolveNetworkMethodTarget(
SupportedApp? app, {
Iterable<DirconEmulator> Function()? trainerBridges,
}) {
bool lists(AppConnectionMethod method) => app?.connections.any((c) => c.$1 == method) ?? false;
if (lists(AppConnectionMethod.obpMdns)) return _openBikeControl;
if (lists(AppConnectionMethod.obpMdns)) {
if (!core.settings.getObpMdnsEnabled() && !core.obpMdnsEmulator.isStarted.value) {
final bridges = (trainerBridges ?? _proxyBridges)();
final bridge = bridges.where((e) => e.isStarted.value).firstOrNull;
if (bridge != null) return _trainerBridge(bridge);
}
return _openBikeControl;
}
if (lists(AppConnectionMethod.rouvyMdns)) return _rouvyMdns;
if (lists(AppConnectionMethod.zwiftMdns)) return _zwiftMdns;
return _openBikeControl;
@@ -155,6 +195,16 @@ NetworkMethodTarget get _openBikeControl => NetworkMethodTarget(
isConnected: core.obpMdnsEmulator.isConnected,
);
Iterable<DirconEmulator> _proxyBridges() => core.connection.proxyDevices.map((d) => d.emulator);
NetworkMethodTarget _trainerBridge(DirconEmulator bridge) => NetworkMethodTarget(
kind: NetworkMethodKind.trainerBridge,
serverLabel: 'DirCon',
preferredPort: bridge.preferredPort,
isStarted: bridge.isStarted,
isConnected: bridge.isConnected,
);
NetworkMethodTarget get _rouvyMdns => NetworkMethodTarget(
kind: NetworkMethodKind.rouvyMdns,
serverLabel: 'Click',

View File

@@ -87,6 +87,12 @@ class NetworkProbeContext {
/// above it means a leaked previous instance walked it up.
final int methodPreferredPort;
/// Whether the trainer app runs on this very device, when the rider told
/// us; null when unknown. A same-device app searches through the same
/// system mDNS service as BikeControl's own scans, so its search cannot be
/// told from ours by where it came from.
final bool? trainerAppOnThisDevice;
/// `Platform.operatingSystem`-shaped: 'windows' | 'macos' | 'linux' |
/// 'android' | 'ios' | 'web'.
final String platform;
@@ -132,5 +138,6 @@ class NetworkProbeContext {
required this.onWatchProgress,
this.methodServerLabel = 'OpenBikeControl',
this.methodPreferredPort = OpenBikeControlConstants.TCP_PORT,
this.trainerAppOnThisDevice,
});
}

View File

@@ -186,6 +186,7 @@ class NetworkSelfTestEngine {
// — and then checks every app against the OpenBikeControl server.
methodServerLabel: built.methodServerLabel,
methodPreferredPort: built.methodPreferredPort,
trainerAppOnThisDevice: built.trainerAppOnThisDevice,
onWatchProgress: (progress) {
built.onWatchProgress(progress);
// A tick that arrives after the guided-watch probe's own timeout

View File

@@ -24,14 +24,37 @@ class NetworkSelfTestStore {
return NetworkSelfTestResult.tryParse(core.settings.getNetworkSelfTestResultJson());
}
/// `'Network self-test:\n<toBundleString()>'` or `''` when none stored —
/// the caller (`debugText()`) interpolates this as a whole optional block,
/// so an empty string must add nothing, not even a blank line.
static String bundleSection() {
/// A stored result older than this no longer describes the device: the
/// network, the app version or the method may all have changed since.
static const staleAfter = Duration(hours: 24);
/// `'Network self-test:\n<age line>\n<toBundleString()>'` or `''` when none
/// stored — the caller (`debugText()`) interpolates this as a whole optional
/// block, so an empty string must add nothing, not even a blank line.
///
/// The bundle carries the LAST STORED run, not one made for the bundle, so
/// the age line says how old it is and whether to trust it.
static String bundleSection({DateTime Function() now = DateTime.now}) {
final result = load();
if (result == null) {
return '';
}
return 'Network self-test:\n${result.toBundleString()}';
return 'Network self-test:\n${ageLine(result.at, now())}\n${result.toBundleString()}';
}
/// `age=3d 4h STALE (stored result, run the check again)` / `age=12min`.
static String ageLine(DateTime at, DateTime now) {
final age = now.difference(at);
final String text;
if (age.isNegative) {
text = '0min';
} else if (age.inHours < 1) {
text = '${age.inMinutes}min';
} else if (age.inDays < 1) {
text = '${age.inHours}h ${age.inMinutes % 60}min';
} else {
text = '${age.inDays}d ${age.inHours % 24}h';
}
return age > staleAfter ? 'age=$text STALE (stored result, run the check again)' : 'age=$text';
}
}

View File

@@ -1,4 +1,4 @@
import 'package:prop/mdns/mdns_responder.dart' show MdnsQueryLogEntry;
import 'package:prop/mdns/mdns_responder.dart' show MdnsQueryLogEntry, OwnMdnsBrowsing;
import '../../../bluetooth/devices/openbikecontrol/obp_mdns_backend.dart';
import '../network_check.dart';
@@ -18,7 +18,9 @@ Future<NetworkCheck> guidedWatchCheck(
Duration window = const Duration(seconds: 60),
Duration tick = const Duration(milliseconds: 500),
bool Function()? isCancelled,
bool Function()? ownBrowseActive,
}) async {
final ownBrowsing = ownBrowseActive ?? () => OwnMdnsBrowsing.active;
final osResponder = ctx.backend == ObpMdnsBackend.osResponder;
final start = ctx.now();
@@ -46,11 +48,31 @@ Future<NetworkCheck> guidedWatchCheck(
var resolved = false;
var addressAsks = 0;
// BikeControl browsed the network itself at some point of the watch. A
// trainer app on this device searches through the same system service: its
// search arrives from our own address, or does not arrive at all because
// the system already has that question open for us. Either way "no query
// arrived" would be a statement about our own scan, not about the app.
var ownBrowseSeen = false;
// This device's own addresses, to tell our scan from another device's
// search that happened to arrive while we were scanning. Empty when the
// snapshot is missing: every entry then counts as possibly ours.
final ownAddresses = {
'127.0.0.1',
...?ctx.snapshot?.addressReport.candidates.map((c) => c.address),
};
final knowsOwnAddresses = ctx.snapshot != null;
void classify(MdnsQueryLogEntry entry) {
// Possibly BikeControl's own scan (the self-test's discovery snapshot, the
// Wi-Fi trainer scan): counting it would report a trainer app that never
// asked as having browsed and resolved us.
if (entry.duringOwnBrowse) return;
// asked as having browsed and resolved us. A query from another device's
// address is never our scan, whatever was running here at the time.
if (entry.duringOwnBrowse && (!knowsOwnAddresses || ownAddresses.contains(entry.source))) {
ownBrowseSeen = true;
return;
}
for (final question in entry.questions) {
if (question.startsWith('PTR _openbikecontrol') || question.startsWith('PTR _wahoo-fitness-tnp')) {
browsed = true;
@@ -88,6 +110,8 @@ Future<NetworkCheck> guidedWatchCheck(
}
}
if (!osResponder && ownBrowsing()) ownBrowseSeen = true;
final connected = ctx.trainerAppConnectedNow();
final elapsed = ctx.now().difference(start);
final remaining = window - elapsed;
@@ -137,6 +161,17 @@ Future<NetworkCheck> guidedWatchCheck(
);
}
if (!browsed && ownBrowseSeen && ctx.trainerAppOnThisDevice != false) {
// Nothing to conclude: a search by a trainer app on this device cannot be
// told from our own scan. Failing here told riders with a working link
// that their app is not allowed on the local network.
return const NetworkCheck(
id: NetworkCheckId.guidedWatch,
verdict: NetworkVerdict.warn,
detail: {'note': 'inconclusive: BikeControl was scanning the network itself', 'connected': 'false'},
);
}
if (!browsed) {
// The trainer app never searched. Most often it is not allowed to use the
// local network (Apple asks per app) or sits on another Wi-Fi — causes in

View File

@@ -127,6 +127,10 @@ ChainStepText chainStepText(BuildContext context, SetupStep step, {String? appNa
// because that is the one thing the rider can check against their VPN app.
// Each reason gets its own advice: "turn the VPN off" means nothing to a
// phone that is simply not on Wi-Fi.
SetupStepId.appNetworkAddress when step.variant == SetupStepVariant.networkNotVisible => ChainStepText(
l.chainStepNetworkNotVisiblePending,
l.chainStepNetworkNotVisibleHint(app),
),
SetupStepId.appNetworkAddress => ChainStepText(
l.chainStepNetworkAddressPending,
switch (step.variant) {

View File

@@ -1385,6 +1385,10 @@ void main() {
expect(stepFor(AddressWarningKind.twoNetworks).variant, SetupStepVariant.networkTwoNetworks);
});
test('advertisement not found on the network: its own wording', () {
expect(stepFor(AddressWarningKind.notVisible).variant, SetupStepVariant.networkNotVisible);
});
test('a VPN or bridge keeps the standard wording', () {
expect(stepFor(AddressWarningKind.unreachable).variant, SetupStepVariant.standard);
expect(stepFor(null).variant, SetupStepVariant.standard);

View File

@@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:prop/mdns/mdns_responder.dart' show MdnsQueryLogEntry;
import 'package:prop/utils/advertised_service_registry.dart';
import 'package:prop/utils/network_address.dart';
import 'package:prop/utils/resilient_tcp_server.dart';
void main() {
test('toText renders every section with the expected markers', () {
@@ -420,4 +421,48 @@ void main() {
expect(text, isNot(contains('neighbour')));
});
});
group('TCP connections and lifecycle', () {
DebugDiagnostics diagnostics({
List<TcpConnectionLogEntry> connections = const [],
List<String> lifecycle = const [],
}) => DebugDiagnostics(
advertised: const [],
backend: 'dnssd',
hostLabel: 'BikeControl',
holdsMulticastLock: false,
discovered: const [],
discoveryRan: false,
addressReport: const AddressPickReport(chosen: null, candidates: []),
servers: const [],
permissions: const PermissionsSnapshot(localNetwork: null),
connections: connections,
lifecycle: lifecycle,
);
test('says so when no client ever dialled', () {
final text = diagnostics().toText();
expect(text, contains('TCP connections:\n (none since the app started)'));
});
test('shows a client that hung up before sending anything', () {
final entry = TcpConnectionLogEntry(
at: DateTime(2026, 11, 24, 10, 31, 2),
server: 'DirCon',
port: 36868,
remote: '192.168.178.92',
)..closedAt = DateTime(2026, 11, 24, 10, 31, 2, 12);
final text = diagnostics(connections: [entry]).toText();
expect(text, contains('10:31:02 DirCon:36868 ← 192.168.178.92 closed after 12 ms before the first byte'));
expect(text.indexOf('TCP servers:'), lessThan(text.indexOf('TCP connections:')));
});
test('prints the lifecycle lines when there are any, and no heading otherwise', () {
expect(diagnostics().toText(), isNot(contains('Lifecycle:')));
final text = diagnostics(lifecycle: const ['standstill: 1 standstill(s), last 360 s']).toText();
expect(text, contains(' Lifecycle:\n standstill: 1 standstill(s), last 360 s'));
});
});
}

View File

@@ -74,4 +74,48 @@ void main() {
expect(address, isNull);
expect(questions, isNotEmpty);
});
group('system resolver (iOS)', () {
setUp(() async => startResponder((_) => const []));
test('asks the system and sends no multicast query of its own', () async {
final asked = <String>[];
final address = await MdnsHostResolver.resolveIPv4(
'KICKR-CORE-A5D9.local',
target: InternetAddress.loopbackIPv4,
port: responder.port,
useSystemResolver: true,
systemLookup: (host) async {
asked.add(host);
return [InternetAddress('fe80::1'), InternetAddress('192.168.1.40')];
},
);
expect(address, '192.168.1.40');
expect(asked, ['KICKR-CORE-A5D9.local']);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(questions, isEmpty);
});
test('a name the system cannot resolve gives null, not an error', () async {
final address = await MdnsHostResolver.resolveIPv4(
'gone.local',
useSystemResolver: true,
systemLookup: (host) async => throw const SocketException('Failed host lookup'),
);
expect(address, isNull);
});
test('a lookup that never answers gives null after the timeout', () async {
final address = await MdnsHostResolver.resolveIPv4(
'slow.local',
timeout: const Duration(milliseconds: 50),
useSystemResolver: true,
systemLookup: (host) => Future<List<InternetAddress>>.delayed(const Duration(seconds: 5), () => const []),
);
expect(address, isNull);
});
});
}

View File

@@ -0,0 +1,148 @@
import 'package:bike_control/services/network_recovery.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart' show AppLifecycleState;
import 'package:flutter_test/flutter_test.dart';
import 'package:prop/utils/suspension_watch.dart';
void main() {
late DateTime now;
late SuspensionWatch watch;
late List<String> calls;
NetworkRecovery recovery(TargetPlatform platform) => NetworkRecovery(
watch: watch,
platform: platform,
now: () => now,
rebindListeners: () async => calls.add('rebind'),
recoverAdvertiser: ({bool force = false}) async => calls.add(force ? 'recover(force)' : 'recover'),
refreshKeepAlive: () => calls.add('keepAlive'),
);
Future<void> settle() => Future<void>.delayed(Duration.zero);
setUp(() {
now = DateTime(2026, 11, 24, 10);
watch = SuspensionWatch(now: () => now);
calls = [];
});
tearDown(() => watch.reset());
test('iOS: coming back from a suspension binds the listeners and publishes again', () async {
final r = recovery(TargetPlatform.iOS)..start();
r.onLifecycleState(AppLifecycleState.paused);
calls.clear();
now = now.add(const Duration(minutes: 6));
r.onLifecycleState(AppLifecycleState.resumed);
await settle();
expect(calls, containsAllInOrder(['rebind', 'recover(force)']));
expect(calls, contains('keepAlive'));
expect(r.diagnosticLines().join('\n'), contains('1 standstill(s), last 360 s'));
});
test('iOS: a resume without a standstill only re-checks the advertisement', () async {
final r = recovery(TargetPlatform.iOS)..start();
r.onLifecycleState(AppLifecycleState.paused);
calls.clear();
now = now.add(const Duration(seconds: 4));
r.onLifecycleState(AppLifecycleState.resumed);
await settle();
expect(calls, ['keepAlive', 'recover']);
});
test('iOS: leaving the app starts the keep-alive waiting limit over', () {
final r = recovery(TargetPlatform.iOS)..start();
r.onLifecycleState(AppLifecycleState.inactive);
r.onLifecycleState(AppLifecycleState.paused);
expect(calls, ['keepAlive', 'keepAlive']);
expect(r.lastBackgroundAt, now);
});
test('macOS: waking from sleep publishes again but leaves the listeners alone', () async {
final r = recovery(TargetPlatform.macOS)..start();
now = now.add(const Duration(hours: 2));
watch.check();
await settle();
expect(calls, ['recover(force)']);
});
group('ensureAdvertisementVisible', () {
test('a visible advertisement is left alone', () async {
final r = recovery(TargetPlatform.iOS);
final visible = await r.ensureAdvertisementVisible(
advertising: () => true,
ownAdvertisementSeen: () async => true,
settle: Duration.zero,
);
expect(visible, isTrue);
expect(calls, isEmpty);
});
test('a missing advertisement is repaired and looked for again', () async {
final r = recovery(TargetPlatform.iOS);
var looks = 0;
final visible = await r.ensureAdvertisementVisible(
advertising: () => true,
// Gone on the first look, back once it was published again.
ownAdvertisementSeen: () async => ++looks > 1,
settle: Duration.zero,
);
expect(visible, isTrue);
expect(calls, ['rebind', 'recover(force)']);
expect(r.lastInvisibleAt, isNull);
});
test('reports an advertisement that stays missing after the repair', () async {
final r = recovery(TargetPlatform.macOS);
final visible = await r.ensureAdvertisementVisible(
advertising: () => true,
ownAdvertisementSeen: () async => false,
settle: Duration.zero,
);
expect(visible, isFalse);
expect(calls, ['recover(force)'], reason: 'a Mac keeps its listeners through sleep');
expect(r.diagnosticLines().join('\n'), contains('own advertisement not found after a repair'));
});
test('nothing advertised means nothing to look for', () async {
final r = recovery(TargetPlatform.iOS);
var looked = false;
final visible = await r.ensureAdvertisementVisible(
advertising: () => false,
ownAdvertisementSeen: () async => looked = true,
settle: Duration.zero,
);
expect(visible, isTrue);
expect(looked, isFalse);
});
});
test('other platforms are left as they were', () async {
final r = recovery(TargetPlatform.windows)..start();
now = now.add(const Duration(hours: 2));
watch.check();
r.onLifecycleState(AppLifecycleState.resumed);
await settle();
expect(calls, isEmpty);
expect(watch.isRunning, isFalse);
expect(r.diagnosticLines(), isEmpty);
});
}

View File

@@ -5,7 +5,9 @@ import 'package:bike_control/services/network_self_test/network_check.dart';
import 'package:bike_control/services/network_self_test/network_probe_context.dart';
import 'package:bike_control/services/network_self_test/probes/guided_watch_probe.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:bike_control/services/debug_diagnostics.dart';
import 'package:prop/mdns/mdns_responder.dart';
import 'package:prop/utils/network_address.dart';
const _defaultWindow = Duration(seconds: 3);
const _defaultTick = Duration(seconds: 1);
@@ -23,11 +25,14 @@ NetworkProbeContext ctx({
bool Function()? trainerAppConnectedNow,
WatchProgressCallback? onWatchProgress,
String platform = 'macos',
bool? trainerAppOnThisDevice,
DebugDiagnostics? snapshot,
}) {
var nowCalls = 0;
final base = DateTime(2026, 8, 21);
return NetworkProbeContext(
snapshot: null,
snapshot: snapshot,
trainerAppOnThisDevice: trainerAppOnThisDevice,
snapshotError: null,
emulatorStarted: true,
trainerAppConnected: false,
@@ -46,9 +51,30 @@ NetworkProbeContext ctx({
);
}
MdnsQueryLogEntry _entry(List<String> questions, {int count = 1, bool duringOwnBrowse = false}) => MdnsQueryLogEntry(
/// A snapshot whose only job is to say which addresses are this device's.
DebugDiagnostics _snapshotWithAddress(String address) => DebugDiagnostics(
advertised: const [],
backend: 'responder',
hostLabel: 'BikeControl',
holdsMulticastLock: false,
discovered: const [],
discoveryRan: false,
addressReport: AddressPickReport(
chosen: InternetAddress(address),
candidates: [AddressCandidate(interfaceName: 'en0', address: address, score: 100, isVirtual: false)],
),
servers: const [],
permissions: const PermissionsSnapshot(localNetwork: null),
);
MdnsQueryLogEntry _entry(
List<String> questions, {
int count = 1,
bool duringOwnBrowse = false,
String source = '192.168.1.50',
}) => MdnsQueryLogEntry(
at: DateTime(2026, 8, 21),
source: '192.168.1.50',
source: source,
sourcePort: 5353,
wantsUnicast: false,
questions: questions,
@@ -142,8 +168,81 @@ void main() {
window: _defaultWindow,
tick: _defaultTick,
);
expect(check.verdict, NetworkVerdict.fail);
expect(check.detail['hint'], 'no query arrived');
expect(check.detail['hint'], isNot('no query arrived'));
expect(check.verdict, NetworkVerdict.warn);
expect(check.detail['note'], startsWith('inconclusive'));
});
// The Wi-Fi trainer scan runs for as long as the page is open, a trainer app on the
// same Mac searches through the same system service, and the watch
// blamed the app for a silence our own scan caused.
group('while BikeControl scans the network itself', () {
test('silence is inconclusive, not a failure', () async {
final check = await guidedWatchCheck(
ctx(),
window: _defaultWindow,
tick: _defaultTick,
ownBrowseActive: () => true,
);
expect(check.verdict, NetworkVerdict.warn);
expect(check.detail['note'], startsWith('inconclusive'));
expect(check.fixes, isEmpty, reason: 'no Local Network lecture for a link that may be fine');
});
test('a connecting trainer app still passes', () async {
final check = await guidedWatchCheck(
ctx(trainerAppConnectedNow: () => true),
window: _defaultWindow,
tick: _defaultTick,
ownBrowseActive: () => true,
);
expect(check.verdict, NetworkVerdict.pass);
});
test('a trainer app known to run on another device still fails on silence', () async {
// Its search comes over the network from another address; our scan
// cannot hide it.
final check = await guidedWatchCheck(
ctx(trainerAppOnThisDevice: false),
window: _defaultWindow,
tick: _defaultTick,
ownBrowseActive: () => true,
);
expect(check.verdict, NetworkVerdict.fail);
expect(check.detail['hint'], 'no query arrived');
});
test("another device's search counts even though it arrived during our scan", () async {
final browse = _entry(
const ['PTR _openbikecontrol._tcp.local'],
duringOwnBrowse: true,
source: '192.168.1.77',
);
final check = await guidedWatchCheck(
ctx(
snapshot: _snapshotWithAddress('192.168.1.50'),
trainerAppOnThisDevice: false,
queryLog: _scriptedLog([const [], [browse]]),
),
window: _defaultWindow,
tick: _defaultTick,
ownBrowseActive: () => true,
);
expect(check.verdict, NetworkVerdict.warn);
expect(check.detail['note'], isNot(startsWith('inconclusive')), reason: 'it browsed; it just never resolved');
});
test('a search from our own address during the scan stays uncounted', () async {
final browse = _entry(const ['PTR _openbikecontrol._tcp.local'], duringOwnBrowse: true);
final check = await guidedWatchCheck(
ctx(snapshot: _snapshotWithAddress('192.168.1.50'), queryLog: _scriptedLog([const [], [browse]])),
window: _defaultWindow,
tick: _defaultTick,
ownBrowseActive: () => false,
);
expect(check.verdict, NetworkVerdict.warn);
expect(check.detail['note'], startsWith('inconclusive'));
});
});
test('warn: browsed but never resolved', () async {

View File

@@ -6,7 +6,7 @@ import 'package:bike_control/utils/keymap/apps/my_whoosh.dart';
import 'package:bike_control/utils/keymap/apps/rouvy.dart';
import 'package:bike_control/utils/keymap/apps/zwift.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:prop/emulators/dircon_emulator.dart' show kWahooDirconStandardPort;
import 'package:prop/emulators/dircon_emulator.dart' show DirconEmulator, kWahooDirconStandardPort;
import 'package:prop/mdns/service_advertiser.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -67,6 +67,46 @@ void main() {
expect(target.isConnected, same(core.zwiftMdnsEmulator.isConnected));
});
// Riders who only bridge their trainer were told the method is
// "not started".
group('an OpenBikeControl app with only the trainer bridge in use', () {
late DirconEmulator bridge;
setUp(() {
bridge = DirconEmulator(preferredPort: 36900)..isStarted.value = true;
});
test('is checked against the bridge when the controller method is switched off', () async {
await core.settings.setObpMdnsEnabled(false);
final target = resolveNetworkMethodTarget(MyWhoosh(), trainerBridges: () => [bridge]);
expect(target.kind, NetworkMethodKind.trainerBridge);
expect(target.serverLabel, 'DirCon');
expect(target.preferredPort, 36900);
expect(target.isStarted, same(bridge.isStarted));
expect(target.isConnected, same(bridge.isConnected));
expect(target.backend, ObpMdnsBackend.platformDefault);
});
test('stays on OpenBikeControl while the controller method is switched on', () async {
await core.settings.setObpMdnsEnabled(true);
final target = resolveNetworkMethodTarget(MyWhoosh(), trainerBridges: () => [bridge]);
expect(target.kind, NetworkMethodKind.openBikeControl);
});
test('stays on OpenBikeControl when no bridge is being served', () async {
await core.settings.setObpMdnsEnabled(false);
bridge.isStarted.value = false;
final target = resolveNetworkMethodTarget(MyWhoosh(), trainerBridges: () => [bridge]);
expect(target.kind, NetworkMethodKind.openBikeControl);
});
});
test('no trainer app selected falls back to OpenBikeControl', () {
final target = resolveNetworkMethodTarget(null);

View File

@@ -79,6 +79,36 @@ void main() {
expect(section, contains(NetworkSelfTestStore.load()!.toBundleString()));
});
group('age line', () {
final at = DateTime.utc(2026, 10, 5, 9, 30);
test('a result from minutes ago is given its age and nothing more', () {
expect(NetworkSelfTestStore.ageLine(at, at.add(const Duration(minutes: 12))), 'age=12min');
expect(NetworkSelfTestStore.ageLine(at, at.add(const Duration(hours: 5, minutes: 7))), 'age=5h 7min');
});
test('a result older than a day is marked stale', () {
// A result from weeks ago says nothing about the device today.
final line = NetworkSelfTestStore.ageLine(at, DateTime.utc(2026, 11, 3, 13, 30));
expect(line, startsWith('age=29d 4h STALE'));
});
test('a clock that moved backwards does not print a negative age', () {
expect(NetworkSelfTestStore.ageLine(at, at.subtract(const Duration(hours: 1))), 'age=0min');
});
test('bundleSection puts the age between the heading and the result', () async {
await NetworkSelfTestStore.save(_result());
final stored = NetworkSelfTestStore.load()!;
final section = NetworkSelfTestStore.bundleSection(now: () => stored.at.add(const Duration(days: 3)));
final lines = section.split('\n');
expect(lines[0], 'Network self-test:');
expect(lines[1], startsWith('age=3d 0h STALE'));
expect(lines[2], startsWith('NETWORK '));
});
});
test(
'menu.dart interpolation helper avoids a double blank line: '
'empty section adds nothing, non-empty section adds exactly one trailing newline',