connection settings cleanup and mock test added. removed bluetooth implementation

This commit is contained in:
Constantin Leue
2026-08-05 20:01:25 +02:00
parent 8e4df2d0d3
commit f65dceb338
15 changed files with 113 additions and 895 deletions
@@ -1,110 +0,0 @@
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../transport/bluetooth/bluetooth_classic_transport.dart';
import '../../transport/bluetooth/bluetooth_device_info.dart';
import '../../transport/link_transport.dart';
import 'database_provider.dart';
/// App-lebenslanger Bluetooth-Classic-Transport (Doku Kommunikationsschicht
/// Abschnitt 3), verdrahtet gegen die gemerkte Geraete-MAC in den
/// Einstellungen. Bewusst nicht autoDispose: die Verbindung soll bestehen
/// bleiben, waehrend zwischen Fly- und Plan-Modus gewechselt wird, und erst
/// beim Verlassen des Fly-Modus explizit getrennt werden (Doku 3,
/// Robustheit: "Verbindung beim Verlassen des Fly-Modus sauber schliessen").
final bluetoothTransportProvider = Provider<BluetoothClassicTransport>((ref) {
final settingsRepo = ref.watch(appSettingsRepositoryProvider);
final transport = BluetoothClassicTransport(
getRememberedAddress: settingsRepo.loadConnectionDeviceAddress,
rememberAddress: settingsRepo.setConnectionDeviceAddress,
);
ref.onDispose(transport.dispose);
return transport;
});
/// Reaktiver [LinkState] des Bluetooth-Transports fuer die Oberflaeche
/// (Verbindungsindikator, Abnahmekriterium: "Zustand jederzeit sichtbar").
final linkStateProvider = StreamProvider<LinkState>((ref) {
final transport = ref.watch(bluetoothTransportProvider);
return transport.state;
});
/// Grund des zuletzt gemeldeten [LinkState.error] (Doku 3, Robustheit: "Grund
/// mitfuehren und in der Oberflaeche anzeigen"). Wird bei jedem neuen
/// LinkState neu ausgelesen, da der Transport ihn synchron mitfuehrt.
final linkErrorReasonProvider = Provider<LinkErrorReason?>((ref) {
ref.watch(linkStateProvider);
return ref.watch(bluetoothTransportProvider).lastErrorReason;
});
/// Gekoppelte Geraete fuer die manuelle Auswahlliste (Doku 3.2c). Wird bei
/// jedem [LinkState]-Wechsel neu geladen, damit eine frisch angeschlossene
/// Kopplung (ueber den "Geraet koppeln"-Knopf) ohne expliziten Reload
/// auftaucht.
final bondedDevicesProvider = FutureProvider<List<BluetoothDeviceInfo>>((ref) {
ref.watch(linkStateProvider);
return ref.watch(bluetoothTransportProvider).listBondedDevices();
});
/// Ein Eintrag im Verbindungsprotokoll (Doku 7: "einfache Textansicht der
/// letzten Ereignisse ... spart im Feld viel Ratearbeit").
class ConnectionLogEntry {
const ConnectionLogEntry(this.timestamp, this.message);
final DateTime timestamp;
final String message;
}
/// Verbindungsprotokoll + Paketzaehler (Doku 7). Haengt sich an den
/// LinkState- und den Rohdaten-Stream des Transports, damit auch ohne
/// MSP-Decoder schon sichtbar ist, dass ueberhaupt Bytes ankommen.
class ConnectionLogNotifier extends Notifier<List<ConnectionLogEntry>> {
static const _maxEntries = 50;
StreamSubscription<LinkState>? _stateSub;
StreamSubscription<void>? _dataSub;
int _packetCount = 0;
int get packetCount => _packetCount;
@override
List<ConnectionLogEntry> build() {
final transport = ref.watch(bluetoothTransportProvider);
_stateSub?.cancel();
_dataSub?.cancel();
_packetCount = 0;
_stateSub = transport.state.listen(_onStateChanged);
_dataSub = transport.incoming.listen((_) => _packetCount++);
ref.onDispose(() {
_stateSub?.cancel();
_dataSub?.cancel();
});
return const [];
}
void _onStateChanged(LinkState linkState) {
final transport = ref.read(bluetoothTransportProvider);
final message = switch (linkState) {
LinkState.disconnected => 'Disconnected',
LinkState.connecting => 'Connecting...',
LinkState.connected =>
'Connected${transport.connectedDevice != null ? ' (${transport.connectedDevice!.displayName})' : ''}',
LinkState.error =>
'Error: ${transport.lastErrorMessage ?? transport.lastErrorReason?.name ?? 'unknown'}',
};
_append(message);
}
void _append(String message) {
final entry = ConnectionLogEntry(DateTime.now(), message);
final next = [...state, entry];
state = next.length > _maxEntries
? next.sublist(next.length - _maxEntries)
: next;
}
}
final connectionLogProvider =
NotifierProvider<ConnectionLogNotifier, List<ConnectionLogEntry>>(
ConnectionLogNotifier.new);
+2 -5
View File
@@ -11,11 +11,8 @@ import 'wifi_connection_provider.dart';
/// FlightControllerLink fuer den Fly-Modus (Doku 3.1): bei WLAN als
/// gewaehlter Verbindungsart ein echter MSP-Link ueber den UDP-Transport,
/// sonst (Bluetooth/5G/USB, oder solange die Einstellungen noch nicht
/// geladen sind) weiterhin der Mock fuer UI-Entwicklung ohne Hardware -
/// Bluetooth ist auf der eingesetzten mLRS-Bruecke ohnehin nicht moeglich
/// (Doku Kommunikationsschicht v2, Abschnitt 1), 5G/USB sind noch nicht
/// umgesetzt.
/// sonst (ConnectionType.mock, oder solange die Einstellungen noch nicht
/// geladen sind) der Mock fuer UI-Entwicklung/Testphase ohne Hardware.
///
/// connectionType wird reaktiv beobachtet (ref.watch), nicht nur einmalig
/// gelesen - beim ersten App-Start ist connectionSettingsProvider oft noch
+15 -13
View File
@@ -233,19 +233,21 @@ class _FlyScreenState extends ConsumerState<FlyScreen> {
);
// Drohnen-Status fuer die Drohnen-Pille (Doku: "im fly modus zeigt die
// drone pille den zustand der drohne") - null solange keine Telemetrie
// vorliegt, dann zeigt BottomStatsBar weiterhin den Drohnennamen-Chip.
final droneStatus = telemetry != null
? computeDroneStatus(
armed: telemetry.armed,
hasFix: telemetry.hasFix,
numSat: telemetry.numSat,
hdop: telemetry.hdop,
linkQuality: telemetry.linkQuality,
snrDb: telemetry.snrDb,
navMode: telemetry.navMode,
)
: null;
// drone pille den zustand der drohne") - das Aussehen des Fly-Modus darf
// nicht am Vorhandensein eines Telemetrie-Frames haengen (sonst faellt
// BottomStatsBar auf den Drohnennamen-Chip zurueck, den Plan-Modus-Look).
// Ohne Frame (Verbindungsaufbau laeuft noch) liefern die Platzhalterwerte
// ueber computeDroneStatus zuverlaessig idle/rot/rot - eine ehrliche
// "keine Daten"-Anzeige statt eines unterschiedlichen Widget-Typs.
final droneStatus = computeDroneStatus(
armed: telemetry?.armed ?? false,
hasFix: telemetry?.hasFix ?? false,
numSat: telemetry?.numSat ?? 0,
hdop: telemetry?.hdop ?? 99.0,
linkQuality: telemetry?.linkQuality ?? 0,
snrDb: telemetry?.snrDb ?? -99,
navMode: telemetry?.navMode ?? 0,
);
return Stack(
children: [
+24 -236
View File
@@ -1,13 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../transport/bluetooth/bluetooth_device_info.dart';
import '../../../transport/bluetooth/bluetooth_system_settings.dart';
import '../../../transport/connection_type.dart';
import '../../../transport/flight_controller_link.dart';
import '../../../transport/link_transport.dart';
import '../../dmc_colors.dart';
import '../../providers/bluetooth_connection_provider.dart';
import '../../providers/connection_settings_provider.dart';
import '../../providers/database_provider.dart';
import '../../providers/telemetry_provider.dart';
@@ -56,8 +53,8 @@ class _ConnectionSection extends ConsumerWidget {
children: [
// Fuer WLAN rendert _WifiPanel das Typ-Dropdown selbst als Teil
// seiner kompakten ersten Zeile (zusammen mit Connect/Disconnect
// und den Status-Pillen) - fuer die anderen Verbindungsarten
// bleibt die bisherige, einfachere Kopfzeile bestehen.
// und den Status-Pillen) - fuer Mock bleibt die bisherige,
// einfachere Kopfzeile bestehen.
if (selectedType != ConnectionType.wifi) ...[
Text('Connection', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 12),
@@ -79,11 +76,7 @@ class _ConnectionSection extends ConsumerWidget {
],
switch (selectedType) {
ConnectionType.wifi => const _WifiPanel(),
ConnectionType.bluetooth => const _BluetoothPanel(),
ConnectionType.cellular5g => const _NotAvailablePanel(
label: '5G',
),
ConnectionType.usb => const _NotAvailablePanel(label: 'USB'),
ConnectionType.mock => const _MockPanel(),
},
],
),
@@ -98,21 +91,31 @@ class _ConnectionSection extends ConsumerWidget {
/// gleich lauten.
const _connectionTypeItems = [
DropdownMenuItem(value: ConnectionType.wifi, child: Text('WiFi mLRS UDP')),
DropdownMenuItem(value: ConnectionType.cellular5g, child: Text('5G (soon)')),
DropdownMenuItem(value: ConnectionType.bluetooth, child: Text('Bluetooth')),
DropdownMenuItem(value: ConnectionType.usb, child: Text('USB (soon)')),
DropdownMenuItem(value: ConnectionType.mock, child: Text('Mock (Test)')),
];
class _NotAvailablePanel extends StatelessWidget {
const _NotAvailablePanel({required this.label});
final String label;
/// Zeigt die simulierte Telemetrie von [MockFlightControllerLink] (Doku:
/// "Mock-Daten fuer die Live-Details-Ansicht nutzbar machen") - der Mock
/// verbindet sich selbst ohne "Connect"-Knopf (siehe telemetryProvider), es
/// gibt hier also nichts zu bedienen, nur zur Kontrolle zu beobachten.
class _MockPanel extends ConsumerWidget {
const _MockPanel();
@override
Widget build(BuildContext context) {
return Text(
'$label support is not available yet.',
style: const TextStyle(fontSize: 12, color: Colors.grey),
Widget build(BuildContext context, WidgetRef ref) {
final telemetry = ref.watch(telemetryProvider).value;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Simulated telemetry for UI testing without hardware.',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
const SizedBox(height: 12),
Text('Telemetry', style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 4),
_TelemetryFields(telemetry: telemetry),
],
);
}
}
@@ -352,161 +355,6 @@ class _WifiErrorHint extends StatelessWidget {
}
}
class _BluetoothPanel extends ConsumerWidget {
const _BluetoothPanel();
@override
Widget build(BuildContext context, WidgetRef ref) {
final linkState = ref.watch(linkStateProvider).value;
final errorReason = ref.watch(linkErrorReasonProvider);
final bondedDevices = ref.watch(bondedDevicesProvider);
final connectionSettings = ref.watch(connectionSettingsProvider).value;
final log = ref.watch(connectionLogProvider);
final packetCount = ref.watch(connectionLogProvider.notifier).packetCount;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text('Bluetooth', style: Theme.of(context).textTheme.titleSmall),
const Spacer(),
_StatePill(state: linkState),
],
),
if (errorReason != null) ...[
const SizedBox(height: 12),
_ErrorHint(reason: errorReason),
],
const SizedBox(height: 16),
Row(
children: [
ElevatedButton(
onPressed: () => _connect(ref),
child: const Text('Connect'),
),
const SizedBox(width: 8),
OutlinedButton(
onPressed: () => ref.read(bluetoothTransportProvider).disconnect(),
child: const Text('Disconnect'),
),
const SizedBox(width: 8),
TextButton(
onPressed: BluetoothSystemSettings.openBluetoothSettings,
child: const Text('Pair device'),
),
],
),
const SizedBox(height: 16),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Auto-connect when entering Fly mode'),
value: connectionSettings?.connectionAutoConnect ?? true,
onChanged: (value) async {
await ref
.read(appSettingsRepositoryProvider)
.setConnectionAutoConnect(value);
ref.invalidate(connectionSettingsProvider);
},
),
const SizedBox(height: 8),
Text('Paired devices', style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 4),
bondedDevices.when(
data: (devices) => devices.isEmpty
? const Text(
'No paired devices yet. Pair one once via the system '
'dialog using "Pair device".',
style: TextStyle(fontSize: 12, color: Colors.grey),
)
: RadioGroup<String>(
groupValue: connectionSettings?.connectionDeviceAddress,
onChanged: (address) => _selectDevice(ref, address, devices),
child: Column(
children: [
for (final device in devices)
RadioListTile<String>(
contentPadding: EdgeInsets.zero,
dense: true,
value: device.address,
title: Text(device.displayName),
subtitle: Text(
device.address,
style: const TextStyle(fontSize: 11),
),
),
],
),
),
loading: () => const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: LinearProgressIndicator(),
),
error: (e, _) => Text(
'Could not read paired devices: $e',
style: const TextStyle(fontSize: 12, color: Colors.grey),
),
),
const SizedBox(height: 16),
Text(
'Connection log ($packetCount packets received)',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 4),
SizedBox(
height: 120,
child: log.isEmpty
? const Text(
'No events yet.',
style: TextStyle(fontSize: 12, color: Colors.grey),
)
: ListView.builder(
reverse: true,
itemCount: log.length,
itemBuilder: (context, index) {
final entry = log[log.length - 1 - index];
return Text(
'${_formatTime(entry.timestamp)} ${entry.message}',
style: const TextStyle(fontSize: 12, fontFamily: 'monospace'),
);
},
),
),
],
);
}
Future<void> _connect(WidgetRef ref) async {
try {
await ref.read(bluetoothTransportProvider).connect();
} on LinkConnectException {
// Grund/Nachricht sind bereits ueber lastErrorReason/state gemeldet
// (siehe LinkConnectException-Doku) - die Oberflaeche reagiert darauf
// ueber linkErrorReasonProvider/_ErrorHint, hier ist nichts weiter zu tun.
}
}
String _formatTime(DateTime t) =>
'${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}:${t.second.toString().padLeft(2, '0')}';
Future<void> _selectDevice(
WidgetRef ref,
String? address,
List<BluetoothDeviceInfo> devices,
) async {
if (address == null) return;
await ref
.read(appSettingsRepositoryProvider)
.setConnectionDeviceAddress(address);
ref.invalidate(connectionSettingsProvider);
try {
await ref.read(bluetoothTransportProvider).connect();
} on LinkConnectException {
// siehe _connect() oben
}
}
}
/// Zeigt neben [_StatePill], ob gerade UDP-Pakete ankommen ("receiving") -
/// unabhaengig vom Verbindungszustand, der Socket kann offen sein, ohne
/// dass die Gegenstelle sendet (siehe wifiStreamActivityProvider).
@@ -569,63 +417,3 @@ class _StatePill extends StatelessWidget {
}
}
class _ErrorHint extends StatelessWidget {
const _ErrorHint({required this.reason});
final LinkErrorReason reason;
@override
Widget build(BuildContext context) {
final (text, action) = switch (reason) {
LinkErrorReason.bluetoothOff => (
'Bluetooth is off. Please enable it in system settings.',
_HintAction('Settings', BluetoothSystemSettings.openBluetoothSettings),
),
LinkErrorReason.permissionDenied => (
'The "Nearby devices" permission is required. Please tap '
'"Connect" again.',
null,
),
LinkErrorReason.permissionDeniedPermanently => (
'The "Nearby devices" permission was permanently denied. Please '
'grant it manually in the app settings.',
_HintAction('App settings', BluetoothSystemSettings.openAppSettings),
),
LinkErrorReason.deviceSelectionRequired => (
'No paired mLRS device found. Please select a device below.',
null,
),
LinkErrorReason.connectionFailed => (
'Connection to the device failed.',
null,
),
// networkUnavailable/networkLost betreffen nur den WLAN-Transport
// (siehe _WifiErrorHint) - hier nur der Vollstaendigkeit halber, damit
// der gemeinsame LinkErrorReason-Enum exhaustiv bleibt.
LinkErrorReason.networkUnavailable ||
LinkErrorReason.networkLost ||
LinkErrorReason.unknown =>
('Unknown connection error.', null),
};
return Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: DmcColors.warnRed.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Expanded(child: Text(text, style: const TextStyle(fontSize: 12))),
if (action != null)
TextButton(onPressed: action.onTap, child: Text(action.label)),
],
),
);
}
}
class _HintAction {
const _HintAction(this.label, this.onTap);
final String label;
final Future<void> Function() onTap;
}
+46 -3
View File
@@ -26,8 +26,12 @@ import '../dmc_colors.dart';
class BatteryIndicatorBar extends StatelessWidget {
const BatteryIndicatorBar({super.key, required this.percent});
/// 0-100, ungeklemmter Rohwert aus TelemetryFrame.batteryPercent.
final int percent;
/// 0-100, ungeklemmter Rohwert aus TelemetryFrame.batteryPercent - null,
/// solange noch kein Telemetrie-Frame vorliegt (Verbindungsaufbau laeuft
/// noch). Rendert dann einen neutralen "keine Daten"-Zustand statt eines
/// Balkens bei 0%, das faelschlich als kritischer Ladestand gelesen werden
/// koennte (siehe MissionFooterBar.showBattery).
final int? percent;
/// Absolute Positionen (vom linken Rand aus), an denen rot in orange und
/// orange in gruen uebergeht - siehe Klassendoku.
@@ -51,7 +55,46 @@ class BatteryIndicatorBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
final clampedPercent = percent.clamp(0, 100);
final rawPercent = percent;
if (rawPercent == null) {
return SizedBox(
height: _pillHeight,
width: double.infinity,
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: 0,
right: 0,
top: (_pillHeight - _barHeight) / 2,
height: _barHeight,
child: ColoredBox(color: Colors.white.withValues(alpha: _trackAlpha)),
),
Center(
child: Container(
height: _pillHeight,
constraints: const BoxConstraints(minWidth: _pillMinWidth),
padding: const EdgeInsets.symmetric(horizontal: 6),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: _pillNeutralAlpha),
borderRadius: BorderRadius.circular(_pillHeight / 2),
),
child: const Text(
'--%',
style: TextStyle(
color: Colors.white70,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
),
),
],
),
);
}
final clampedPercent = rawPercent.clamp(0, 100);
return SizedBox(
height: _pillHeight,
+13 -5
View File
@@ -48,7 +48,11 @@ class MissionFooterBar extends ConsumerWidget {
final FlyMissionStatus? flyMissionStatus;
/// Nur im Fly-Modus gesetzt (Doku: "im fly modus zeigt die drone pille
/// den zustand der drohne") - siehe BottomStatsBar.droneStatus.
/// den zustand der drohne") - siehe BottomStatsBar.droneStatus. FlyScreen
/// setzt hier immer einen Wert (auch ohne Telemetrie-Frame, siehe dortige
/// Doku), Plan-Modus nie - dient deshalb hier zugleich als Fly/Plan-
/// Unterscheidung fuer die Sichtbarkeit von [batteryPercent], statt dafuer
/// ein eigenes Flag zu fuehren.
final DroneStatus? droneStatus;
final List<MissionWarning> warnings;
@@ -61,8 +65,12 @@ class MissionFooterBar extends ConsumerWidget {
/// Nur im Fly-Modus gesetzt (Doku: "Batterieanzeige im Fly-Modus
/// hinzufuegen") - zeigt den Batteriebalken ueber der BottomStatsBar an,
/// unter einem ggf. ausgeklappten Hoehenprofil. Bleibt im Plan-Modus null
/// (keine Telemetrie), die Anzeige entfaellt dann vollstaendig.
/// unter einem ggf. ausgeklappten Hoehenprofil. Sichtbarkeit haengt an
/// [droneStatus] statt an diesem Wert selbst (siehe dort) - im Fly-Modus
/// bleibt der Balken deshalb auch ohne Telemetrie-Frame sichtbar, nur der
/// Prozentwert ist dann null (BatteryIndicatorBar zeigt dafuer einen
/// neutralen "keine Daten"-Zustand statt 0%, das faelschlich als
/// kritischer Ladestand gelesen werden koennte).
final int? batteryPercent;
/// Siehe BottomStatsBar.forceShowWarningsButton.
@@ -105,10 +113,10 @@ class MissionFooterBar extends ConsumerWidget {
activeIndex: activeIndex,
),
),
if (batteryPercent != null)
if (droneStatus != null)
Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 0),
child: BatteryIndicatorBar(percent: batteryPercent!),
child: BatteryIndicatorBar(percent: batteryPercent),
),
BottomStatsBar(
waypointCount: waypoints.length,