ble filtering

This commit is contained in:
Ben Allfree
2026-02-24 22:41:03 -08:00
parent e3148dd449
commit d88786bb0f
+16 -102
View File
@@ -30,7 +30,6 @@ import '../storage/message_store.dart';
import '../storage/unread_store.dart'; import '../storage/unread_store.dart';
import '../utils/app_logger.dart'; import '../utils/app_logger.dart';
import '../utils/battery_utils.dart'; import '../utils/battery_utils.dart';
import '../utils/platform_info.dart';
import 'meshcore_protocol.dart'; import 'meshcore_protocol.dart';
class MeshCoreUuids { class MeshCoreUuids {
@@ -686,22 +685,16 @@ class MeshCoreConnector extends ChangeNotifier {
}) async { }) async {
if (_state == MeshCoreConnectionState.scanning) return; if (_state == MeshCoreConnectionState.scanning) return;
try {
_scanResults.clear(); _scanResults.clear();
_setState(MeshCoreConnectionState.scanning); _setState(MeshCoreConnectionState.scanning);
// Ensure any previous scan is fully stopped // Ensure any previous scan is fully stopped
try {
await FlutterBluePlus.stopScan(); await FlutterBluePlus.stopScan();
} catch (_) {}
try {
await _scanSubscription?.cancel(); await _scanSubscription?.cancel();
} catch (_) {}
_scanSubscription = null;
// On iOS/macOS, wait for Bluetooth to be powered on before scanning // On iOS/macOS, wait for Bluetooth to be powered on before scanning
if (PlatformInfo.isIOS || PlatformInfo.isMacOS) { if (defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS) {
// Wait for adapter state to be powered on // Wait for adapter state to be powered on
final adapterState = await FlutterBluePlus.adapterState.first; final adapterState = await FlutterBluePlus.adapterState.first;
if (adapterState != BluetoothAdapterState.on) { if (adapterState != BluetoothAdapterState.on) {
@@ -721,76 +714,30 @@ class MeshCoreConnector extends ChangeNotifier {
await Future.delayed(const Duration(milliseconds: 300)); await Future.delayed(const Duration(milliseconds: 300));
} }
_scanSubscription = FlutterBluePlus.scanResults.listen( _scanSubscription = FlutterBluePlus.scanResults.listen((results) {
(results) {
_scanResults.clear(); _scanResults.clear();
for (var result in results) { _scanResults.addAll(results);
if (result.device.platformName.startsWith("MeshCore-") ||
result.advertisementData.advName.startsWith("MeshCore-") ||
result.advertisementData.advName.startsWith("Whisper-")) {
_scanResults.add(result);
}
}
notifyListeners(); notifyListeners();
}, });
onError: (Object e) {
debugPrint("scanResults stream error: $e");
stopScan();
},
);
if (PlatformInfo.isWeb) {
await FlutterBluePlus.startScan( await FlutterBluePlus.startScan(
withServices: [Guid(MeshCoreUuids.service)], withKeywords: ["MeshCore-", "Whisper-"],
); webOptionalServices: [Guid(MeshCoreUuids.service)],
// On web, the chooser returns once a device is picked, but the scanResults
// stream might take a moment to emit the last result. Wait briefly so the
// device appears in the UI before stopScan() clears the list.
await Future.delayed(const Duration(milliseconds: 500));
} else {
await FlutterBluePlus.startScan(
withServices: [Guid(MeshCoreUuids.service)],
timeout: timeout, timeout: timeout,
androidScanMode: AndroidScanMode.lowLatency, androidScanMode: AndroidScanMode.lowLatency,
); );
await Future.delayed(timeout); await Future.delayed(timeout);
}
} catch (e) {
debugPrint("Scan error: $e");
// On web, suppress common cancellation and chooser errors
if (kIsWeb) return;
if (!PlatformInfo.isWeb) {
rethrow;
}
} finally {
await stopScan(); await stopScan();
} }
}
Future<void> stopScan() async { Future<void> stopScan() async {
if (_state == MeshCoreConnectionState.scanning) {
_setState(MeshCoreConnectionState.disconnected);
}
try {
await FlutterBluePlus.stopScan(); await FlutterBluePlus.stopScan();
} catch (e) { await _scanSubscription?.cancel();
debugPrint("stopScan error: $e");
}
try {
if (_scanSubscription != null) {
await _scanSubscription!.cancel();
}
} catch (_) {}
_scanSubscription = null; _scanSubscription = null;
// On web, don't clear results immediately so the picked device remains visible if (_state == MeshCoreConnectionState.scanning) {
if (!PlatformInfo.isWeb) { _setState(MeshCoreConnectionState.disconnected);
_scanResults.clear();
notifyListeners();
} }
} }
@@ -818,17 +765,11 @@ class MeshCoreConnector extends ChangeNotifier {
notifyListeners(); notifyListeners();
try { try {
_connectionSubscription = device.connectionState.listen( _connectionSubscription = device.connectionState.listen((state) {
(state) {
if (state == BluetoothConnectionState.disconnected && isConnected) { if (state == BluetoothConnectionState.disconnected && isConnected) {
_handleDisconnection(); _handleDisconnection();
} }
}, });
onError: (Object e) {
debugPrint("connectionState stream error: $e");
if (isConnected) _handleDisconnection();
},
);
await device.connect( await device.connect(
timeout: const Duration(seconds: 15), timeout: const Duration(seconds: 15),
@@ -837,18 +778,12 @@ class MeshCoreConnector extends ChangeNotifier {
); );
// Request larger MTU for sending larger frames // Request larger MTU for sending larger frames
if (!PlatformInfo.isWeb) {
try { try {
final mtu = await device.requestMtu(185); final mtu = await device.requestMtu(185);
debugPrint('MTU set to: $mtu'); debugPrint('MTU set to: $mtu');
} catch (e) { } catch (e) {
debugPrint('MTU request failed: $e, using default'); debugPrint('MTU request failed: $e, using default');
} }
} else {
// On Chrome Web Bluetooth, give the GATT connection a moment to settle
// before discovering services, which is a common quirk to avoid timeouts.
await Future.delayed(const Duration(milliseconds: 500));
}
List<BluetoothService> services = await device.discoverServices(); List<BluetoothService> services = await device.discoverServices();
@@ -877,35 +812,13 @@ class MeshCoreConnector extends ChangeNotifier {
throw Exception("MeshCore characteristics not found"); throw Exception("MeshCore characteristics not found");
} }
// Setup listener BEFORE enabling notifications so we don't miss anything // Retry setNotifyValue with increasing delays
_notifySubscription = _txCharacteristic!.onValueReceived.listen(
_handleFrame,
onError: (Object e) {
debugPrint("onValueReceived stream error: $e");
},
);
debugPrint('Starting setNotifyValue(true)');
if (PlatformInfo.isWeb) {
// On Web, setNotifyValue often hangs indefinitely on the Promise resolution.
// We trigger it but don't await its completion to avoid blocking the connection flow.
debugPrint('Web: Calling setNotifyValue(true) without awaiting');
// ignore: unawaited_futures
_txCharacteristic!.setNotifyValue(true, timeout: 2).catchError((e) {
debugPrint('Web setNotifyValue error (ignoring): $e');
return false; // catchError must return a bool to match Future<bool>
});
// Give the browser a moment to process the underlying startNotifications call
await Future.delayed(const Duration(milliseconds: 500));
} else {
// Native platforms handle setNotifyValue blockingly with CCCD descriptors
bool notifySet = false; bool notifySet = false;
for (int attempt = 0; attempt < 3 && !notifySet; attempt++) { for (int attempt = 0; attempt < 3 && !notifySet; attempt++) {
try { try {
if (attempt > 0) { if (attempt > 0) {
await Future.delayed(Duration(milliseconds: 500 * attempt)); await Future.delayed(Duration(milliseconds: 500 * attempt));
} }
debugPrint('Calling setNotifyValue(true), attempt ${attempt + 1}');
await _txCharacteristic!.setNotifyValue(true); await _txCharacteristic!.setNotifyValue(true);
notifySet = true; notifySet = true;
} catch (e) { } catch (e) {
@@ -913,8 +826,9 @@ class MeshCoreConnector extends ChangeNotifier {
if (attempt == 2) rethrow; if (attempt == 2) rethrow;
} }
} }
} _notifySubscription = _txCharacteristic!.onValueReceived.listen(
debugPrint('setNotifyValue(true) configuration completed'); _handleFrame,
);
_setState(MeshCoreConnectionState.connected); _setState(MeshCoreConnectionState.connected);