connection settings cleanup and mock test added. removed bluetooth implementation
This commit is contained in:
@@ -1,257 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_classic_bluetooth/flutter_classic_bluetooth.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
import '../link_transport.dart';
|
||||
import 'bluetooth_device_info.dart';
|
||||
import 'bluetooth_device_selector.dart';
|
||||
|
||||
/// Bluetooth-Classic-(SPP)-Transport (Doku Kommunikationsschicht Abschnitt 3):
|
||||
/// verbindet sich mit dem RadioMaster-Pocket-Backpack (mLRS Tx) ueber RFCOMM.
|
||||
/// Setzt den in Abschnitt 3 beschriebenen Verbindungsablauf um:
|
||||
///
|
||||
/// 1. Bluetooth-Adapter an? (kann ab Android 12 nicht mehr programmatisch
|
||||
/// eingeschaltet werden - meldet stattdessen [LinkErrorReason.bluetoothOff]).
|
||||
/// 2. Geraet bestimmen, ohne zu scannen: gemerkte MAC-Adresse, sonst erstes
|
||||
/// gekoppeltes Geraet mit "mLRS"-Praefix, sonst
|
||||
/// [LinkErrorReason.deviceSelectionRequired] (Oberflaeche zeigt
|
||||
/// Auswahlliste, siehe [listBondedDevices]).
|
||||
/// 3. Laufende Discovery abbrechen, falls eine laeuft.
|
||||
/// 4. Socket oeffnen; danach uebernimmt der eingebaute Reconnect-Mechanismus
|
||||
/// des Plugins (exponentielles Backoff 1s -> 30s) das Wiederverbinden bei
|
||||
/// Verbindungsabbruch.
|
||||
class BluetoothClassicTransport implements LinkTransport {
|
||||
BluetoothClassicTransport({
|
||||
required Future<String?> Function() getRememberedAddress,
|
||||
required Future<void> Function(String address) rememberAddress,
|
||||
FlutterClassicBluetooth? bluetooth,
|
||||
}) : _getRememberedAddress = getRememberedAddress,
|
||||
_rememberAddress = rememberAddress,
|
||||
_bluetooth = bluetooth ?? FlutterClassicBluetooth();
|
||||
|
||||
final Future<String?> Function() _getRememberedAddress;
|
||||
final Future<void> Function(String address) _rememberAddress;
|
||||
final FlutterClassicBluetooth _bluetooth;
|
||||
|
||||
final _incomingController = StreamController<Uint8List>.broadcast();
|
||||
final _stateController = StreamController<LinkState>.broadcast();
|
||||
|
||||
BtcReconnectingConnection? _link;
|
||||
StreamSubscription<Uint8List>? _linkDataSub;
|
||||
StreamSubscription<BtcReconnectState>? _linkStateSub;
|
||||
|
||||
BluetoothDeviceInfo? _connectedDevice;
|
||||
LinkState _state = LinkState.disconnected;
|
||||
LinkErrorReason? _lastErrorReason;
|
||||
String? _lastErrorMessage;
|
||||
|
||||
@override
|
||||
Stream<Uint8List> get incoming => _incomingController.stream;
|
||||
|
||||
@override
|
||||
Stream<LinkState> get state => _stateController.stream;
|
||||
|
||||
@override
|
||||
LinkErrorReason? get lastErrorReason => _lastErrorReason;
|
||||
|
||||
@override
|
||||
String? get lastErrorMessage => _lastErrorMessage;
|
||||
|
||||
/// Das aktuell verbundene (oder zuletzt verbundene) Geraet, falls bekannt.
|
||||
BluetoothDeviceInfo? get connectedDevice => _connectedDevice;
|
||||
|
||||
/// Gekoppelte Geraete fuer die manuelle Auswahlliste (Doku 3.2c). Scannt
|
||||
/// nicht - liefert nur bereits gekoppelte Geraete, das ist sofort verfuegbar.
|
||||
Future<List<BluetoothDeviceInfo>> listBondedDevices() async {
|
||||
final devices = await _bluetooth.getPairedDevices();
|
||||
return [
|
||||
for (final d in devices)
|
||||
BluetoothDeviceInfo(address: d.address, name: d.name ?? d.alias),
|
||||
];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> connect() async {
|
||||
_lastErrorReason = null;
|
||||
_lastErrorMessage = null;
|
||||
_setState(LinkState.connecting);
|
||||
|
||||
try {
|
||||
if (!await _bluetooth.isEnabled()) {
|
||||
_fail(
|
||||
LinkErrorReason.bluetoothOff,
|
||||
'Bluetooth-Adapter ist aus. Kann ab Android 12 nicht mehr aus der '
|
||||
'App heraus eingeschaltet werden.',
|
||||
);
|
||||
}
|
||||
|
||||
final permissionOutcome = await _ensureConnectPermission();
|
||||
if (permissionOutcome == _PermissionOutcome.deniedPermanently) {
|
||||
_fail(
|
||||
LinkErrorReason.permissionDeniedPermanently,
|
||||
'"Geraete in der Naehe"-Berechtigung dauerhaft abgelehnt.',
|
||||
);
|
||||
}
|
||||
if (permissionOutcome == _PermissionOutcome.denied) {
|
||||
_fail(
|
||||
LinkErrorReason.permissionDenied,
|
||||
'"Geraete in der Naehe"-Berechtigung abgelehnt.',
|
||||
);
|
||||
}
|
||||
|
||||
final bonded = await listBondedDevices();
|
||||
final remembered = await _getRememberedAddress();
|
||||
final selection = selectBluetoothDevice(
|
||||
bondedDevices: bonded,
|
||||
rememberedAddress: remembered,
|
||||
);
|
||||
|
||||
if (selection is BluetoothDeviceSelectionRequired) {
|
||||
_fail(
|
||||
LinkErrorReason.deviceSelectionRequired,
|
||||
'Kein gekoppeltes mLRS-Geraet automatisch bestimmbar '
|
||||
'(${bonded.length} gekoppelte Geraete zur Auswahl).',
|
||||
);
|
||||
}
|
||||
final device = (selection as BluetoothDeviceResolved).device;
|
||||
|
||||
if (device.address != remembered) {
|
||||
await _rememberAddress(device.address);
|
||||
}
|
||||
|
||||
try {
|
||||
if (await _bluetooth.isDiscovering()) {
|
||||
await _bluetooth.stopDiscovery();
|
||||
}
|
||||
} catch (_) {
|
||||
// Discovery laeuft ohnehin nicht (mehr) - unkritisch (Doku 3.3).
|
||||
}
|
||||
|
||||
_connectedDevice = device;
|
||||
final link = _bluetooth.connectWithReconnect(
|
||||
address: device.address,
|
||||
uuid: BtcUuid.spp,
|
||||
);
|
||||
_link = link;
|
||||
_linkStateSub = link.state.listen(_onReconnectStateChanged);
|
||||
_linkDataSub = link.input.listen(_incomingController.add);
|
||||
} on BtcException catch (e) {
|
||||
_fail(_reasonForException(e), e.message);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> disconnect() async {
|
||||
await _linkDataSub?.cancel();
|
||||
_linkDataSub = null;
|
||||
await _linkStateSub?.cancel();
|
||||
_linkStateSub = null;
|
||||
await _link?.close();
|
||||
_link = null;
|
||||
_setState(LinkState.disconnected);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> send(Uint8List data) async {
|
||||
final link = _link;
|
||||
if (link == null) {
|
||||
throw const LinkConnectException(
|
||||
LinkErrorReason.connectionFailed,
|
||||
'send() ohne aktive Verbindung aufgerufen.',
|
||||
);
|
||||
}
|
||||
await link.send(data);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_linkDataSub?.cancel();
|
||||
_linkStateSub?.cancel();
|
||||
unawaited(_link?.close());
|
||||
_link = null;
|
||||
_incomingController.close();
|
||||
_stateController.close();
|
||||
}
|
||||
|
||||
void _onReconnectStateChanged(BtcReconnectState s) {
|
||||
switch (s) {
|
||||
case BtcReconnectState.connecting:
|
||||
case BtcReconnectState.reconnecting:
|
||||
_setState(LinkState.connecting);
|
||||
case BtcReconnectState.connected:
|
||||
_lastErrorReason = null;
|
||||
_lastErrorMessage = null;
|
||||
_setState(LinkState.connected);
|
||||
case BtcReconnectState.closed:
|
||||
_setState(LinkState.disconnected);
|
||||
case BtcReconnectState.failed:
|
||||
// Nur erreichbar, wenn BtcReconnectPolicy.maxAttempts gesetzt waere;
|
||||
// die Standardpolicy (Doku 3, Robustheit: 1s->30s, unbegrenzt) haelt
|
||||
// stattdessen einfach LinkState.connecting, bis es klappt oder
|
||||
// disconnect() gerufen wird. Trotzdem hier behandelt, falls die
|
||||
// Policy kuenftig eine Obergrenze bekommt.
|
||||
_setError(
|
||||
LinkErrorReason.connectionFailed,
|
||||
_link?.lastError?.toString() ?? 'Verbindung fehlgeschlagen.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Setzt Fehlergrund/-nachricht und meldet [LinkState.error] ueber den
|
||||
/// Zustands-Stream, ohne selbst zu werfen - fuer asynchrone Beobachter
|
||||
/// (z.B. den Reconnect-Zustands-Listener).
|
||||
void _setError(LinkErrorReason reason, String message) {
|
||||
_lastErrorReason = reason;
|
||||
_lastErrorMessage = message;
|
||||
_setState(LinkState.error);
|
||||
}
|
||||
|
||||
/// Wie [_setError], wirft danach zusaetzlich eine [LinkConnectException]
|
||||
/// mit demselben Grund - siehe dortige Doku. Nur fuer Fehler, die
|
||||
/// synchron innerhalb von [connect] erkannt werden.
|
||||
Never _fail(LinkErrorReason reason, String message) {
|
||||
_setError(reason, message);
|
||||
throw LinkConnectException(reason, message);
|
||||
}
|
||||
|
||||
void _setState(LinkState next) {
|
||||
_state = next;
|
||||
if (!_stateController.isClosed) _stateController.add(next);
|
||||
}
|
||||
|
||||
LinkState get currentState => _state;
|
||||
|
||||
Future<_PermissionOutcome> _ensureConnectPermission() async {
|
||||
// MVP ist auf Android beschraenkt (Doku CLAUDE.md); auf anderen
|
||||
// Plattformen (z.B. Windows-Desktop waehrend der UI-Entwicklung) gibt es
|
||||
// keine "Geraete in der Naehe"-Laufzeitberechtigung zu pruefen.
|
||||
if (!Platform.isAndroid) return _PermissionOutcome.granted;
|
||||
|
||||
var status = await Permission.bluetoothConnect.status;
|
||||
if (status.isGranted) return _PermissionOutcome.granted;
|
||||
if (status.isPermanentlyDenied) {
|
||||
return _PermissionOutcome.deniedPermanently;
|
||||
}
|
||||
|
||||
status = await Permission.bluetoothConnect.request();
|
||||
if (status.isGranted) return _PermissionOutcome.granted;
|
||||
if (status.isPermanentlyDenied) {
|
||||
return _PermissionOutcome.deniedPermanently;
|
||||
}
|
||||
return _PermissionOutcome.denied;
|
||||
}
|
||||
|
||||
LinkErrorReason _reasonForException(BtcException e) {
|
||||
if (e is BtcPermissionException) return LinkErrorReason.permissionDenied;
|
||||
if (e is BtcDisabledException) return LinkErrorReason.bluetoothOff;
|
||||
if (e is BtcConnectionException || e is BtcTimeoutException) {
|
||||
return LinkErrorReason.connectionFailed;
|
||||
}
|
||||
return LinkErrorReason.unknown;
|
||||
}
|
||||
}
|
||||
|
||||
enum _PermissionOutcome { granted, denied, deniedPermanently }
|
||||
@@ -1,23 +0,0 @@
|
||||
/// DMC-eigenes, plugin-unabhaengiges Geraetemodell fuer gekoppelte
|
||||
/// Bluetooth-Classic-Geraete (Doku Kommunikationsschicht Abschnitt 3.2).
|
||||
/// Haelt `flutter_classic_bluetooth`-Typen aus der Oberflaeche heraus, damit
|
||||
/// nur transport/bluetooth/ das Paket kennen muss.
|
||||
class BluetoothDeviceInfo {
|
||||
const BluetoothDeviceInfo({required this.address, this.name});
|
||||
|
||||
final String address;
|
||||
final String? name;
|
||||
|
||||
String get displayName => name ?? address;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is BluetoothDeviceInfo && other.address == address;
|
||||
|
||||
@override
|
||||
int get hashCode => address.hashCode;
|
||||
|
||||
@override
|
||||
String toString() => 'BluetoothDeviceInfo($address, $name)';
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import 'bluetooth_device_info.dart';
|
||||
|
||||
/// Praefix, an dem der mLRS-Backpack in seinem Bluetooth-Namen erkannt wird
|
||||
/// (Doku Kommunikationsschicht Abschnitt 3.2).
|
||||
const mLrsDeviceNamePrefix = 'mLRS';
|
||||
|
||||
/// Ergebnis der automatischen Geraeteauswahl (Doku Abschnitt 3.2): entweder
|
||||
/// ein eindeutig bestimmtes Geraet, oder die Angabe, dass die Oberflaeche
|
||||
/// eine Auswahlliste zeigen muss.
|
||||
sealed class BluetoothDeviceSelection {
|
||||
const BluetoothDeviceSelection();
|
||||
}
|
||||
|
||||
class BluetoothDeviceResolved extends BluetoothDeviceSelection {
|
||||
const BluetoothDeviceResolved(this.device);
|
||||
final BluetoothDeviceInfo device;
|
||||
}
|
||||
|
||||
class BluetoothDeviceSelectionRequired extends BluetoothDeviceSelection {
|
||||
const BluetoothDeviceSelectionRequired(this.candidates);
|
||||
|
||||
/// Gekoppelte Geraete, aus denen die Oberflaeche eine Auswahl anbieten
|
||||
/// muss (Doku 3.2c).
|
||||
final List<BluetoothDeviceInfo> candidates;
|
||||
}
|
||||
|
||||
/// Reine Auswahllogik, unabhaengig vom Bluetooth-Plugin und ohne
|
||||
/// Plattform-Channel - daher ohne Hardware testbar.
|
||||
///
|
||||
/// Reihenfolge (Doku Abschnitt 3.2):
|
||||
/// a) gemerkte MAC-Adresse aus den Einstellungen (falls noch gekoppelt)
|
||||
/// b) erstes gekoppeltes Geraet, dessen Name mit "mLRS" beginnt
|
||||
/// c) sonst: Auswahlliste anzeigen
|
||||
BluetoothDeviceSelection selectBluetoothDevice({
|
||||
required List<BluetoothDeviceInfo> bondedDevices,
|
||||
String? rememberedAddress,
|
||||
}) {
|
||||
if (rememberedAddress != null) {
|
||||
final remembered = _firstWhereOrNull(
|
||||
bondedDevices,
|
||||
(d) => d.address == rememberedAddress,
|
||||
);
|
||||
if (remembered != null) return BluetoothDeviceResolved(remembered);
|
||||
}
|
||||
|
||||
final mLrsDevice = _firstWhereOrNull(
|
||||
bondedDevices,
|
||||
(d) => (d.name ?? '').startsWith(mLrsDeviceNamePrefix),
|
||||
);
|
||||
if (mLrsDevice != null) return BluetoothDeviceResolved(mLrsDevice);
|
||||
|
||||
return BluetoothDeviceSelectionRequired(bondedDevices);
|
||||
}
|
||||
|
||||
BluetoothDeviceInfo? _firstWhereOrNull(
|
||||
List<BluetoothDeviceInfo> devices,
|
||||
bool Function(BluetoothDeviceInfo) test,
|
||||
) {
|
||||
for (final device in devices) {
|
||||
if (test(device)) return device;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import 'package:app_settings/app_settings.dart';
|
||||
import 'package:permission_handler/permission_handler.dart' as ph;
|
||||
|
||||
/// Verlinkt zu den System-/App-Einstellungen fuer die drei Bluetooth-
|
||||
/// Hinweisfaelle aus Doku Kommunikationsschicht Abschnitt 3/7 - haelt die
|
||||
/// Wahl des Settings-Pakets aus ui/ heraus (Doku: kein Bluetooth-/
|
||||
/// Settings-Import ausserhalb von transport/).
|
||||
abstract final class BluetoothSystemSettings {
|
||||
/// "Bluetooth an?" negativ (Doku 3.1) bzw. der "Gerät koppeln"-Knopf
|
||||
/// (Doku 7): oeffnet die System-Bluetooth-Einstellungen, in denen der
|
||||
/// Nutzer sowohl den Adapter einschalten als auch ein neues Geraet koppeln
|
||||
/// kann.
|
||||
static Future<void> openBluetoothSettings() =>
|
||||
AppSettings.openAppSettings(type: AppSettingsType.bluetooth);
|
||||
|
||||
/// Berechtigung dauerhaft abgelehnt (Doku 3, Berechtigungen): oeffnet die
|
||||
/// App-Einstellungen, in denen der Nutzer die Berechtigung manuell erteilen
|
||||
/// kann, da Android den Dialog kein zweites Mal zeigt.
|
||||
static Future<void> openAppSettings() => ph.openAppSettings();
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
/// Verbindungsart, wie sie der Nutzer in den Einstellungen waehlt (Doku
|
||||
/// Kommunikationsschicht Abschnitt 7: "Art: WLAN * USB (spaeter)").
|
||||
/// Protokollneutraler Enum-Typ analog zu [LinkState] - deshalb bewusst auch
|
||||
/// hier in transport/ statt in der UI, aber ohne jede Netzwerk-/Plattform-
|
||||
/// Abhaengigkeit, damit er gefahrlos von database/ und ui/ importiert werden
|
||||
/// kann.
|
||||
/// Verbindungsart, wie sie der Nutzer in den Einstellungen waehlt (MVP-Scope,
|
||||
/// Doku: "nur WiFi/TCP"). Protokollneutraler Enum-Typ analog zu [LinkState] -
|
||||
/// deshalb bewusst auch hier in transport/ statt in der UI, aber ohne jede
|
||||
/// Netzwerk-/Plattform-Abhaengigkeit, damit er gefahrlos von database/ und
|
||||
/// ui/ importiert werden kann.
|
||||
///
|
||||
/// [mock] ist keine echte Transportart, sondern waehlt explizit
|
||||
/// [MockFlightControllerLink] fuer die UI-Entwicklung/Testphase ohne
|
||||
/// Hardware (siehe flightControllerLinkProvider) - vorher liefen 5G/
|
||||
/// Bluetooth/USB implizit auf denselben Mock hinaus, was in den Einstellungen
|
||||
/// wie echte, nur noch nicht fertige Verbindungsarten aussah statt wie das
|
||||
/// Test-Werkzeug, das es tatsaechlich ist.
|
||||
enum ConnectionType {
|
||||
wifi,
|
||||
cellular5g,
|
||||
bluetooth,
|
||||
usb,
|
||||
mock,
|
||||
}
|
||||
|
||||
/// Vorgabe-Port der mLRS-WLAN-Bruecke (Doku Abschnitt 3: "Port 14550").
|
||||
|
||||
Reference in New Issue
Block a user