Initialize USB Supoport for Andriod and Desktop

This commit is contained in:
just_stuff_tm
2026-03-01 23:08:51 -05:00
committed by just-stuff-tm
parent 7d8e049745
commit 22a53439b1
45 changed files with 2083 additions and 47 deletions
+201
View File
@@ -0,0 +1,201 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../l10n/l10n.dart';
import 'scanner_screen.dart';
import 'usb_screen.dart';
/// Entry point that lets the user choose between USB or Bluetooth.
class ConnectionChoiceScreen extends StatelessWidget {
const ConnectionChoiceScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: FittedBox(
fit: BoxFit.scaleDown,
child: Text(l10n.appTitle, textAlign: TextAlign.center),
),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
child: LayoutBuilder(
builder: (context, constraints) {
final availableHeight = constraints.maxHeight.isFinite
? constraints.maxHeight
: 600.0;
final gap = math.max(
8.0,
math.min(20.0, availableHeight * 0.035),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Flexible(
flex: 3,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
l10n.connectionChoiceTitle,
textAlign: TextAlign.center,
style: theme.textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
),
),
SizedBox(height: math.max(4.0, gap * 0.5)),
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
l10n.connectionChoiceSubtitle,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
),
],
),
),
),
SizedBox(height: gap),
Expanded(
flex: 4,
child: _ConnectionMethodButton(
icon: Icons.usb,
label: l10n.connectionChoiceUsbLabel,
color: theme.colorScheme.primaryContainer,
iconColor: theme.colorScheme.onPrimaryContainer,
onPressed: () {
debugPrint(
'ConnectionChoiceScreen: USB selected, opening UsbScreen',
);
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const UsbScreen()),
);
},
),
),
SizedBox(height: gap),
Expanded(
flex: 4,
child: _ConnectionMethodButton(
icon: Icons.bluetooth,
label: l10n.connectionChoiceBluetoothLabel,
color: theme.colorScheme.surfaceContainerHighest,
iconColor: theme.colorScheme.onSurfaceVariant,
onPressed: () {
debugPrint(
'ConnectionChoiceScreen: Bluetooth selected, opening ScannerScreen',
);
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => const ScannerScreen(),
),
);
},
),
),
],
);
},
),
),
),
);
}
}
class _ConnectionMethodButton extends StatelessWidget {
const _ConnectionMethodButton({
required this.icon,
required this.label,
required this.onPressed,
required this.color,
required this.iconColor,
});
final IconData icon;
final String label;
final VoidCallback onPressed;
final Color color;
final Color iconColor;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: color,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
minimumSize: const Size.fromHeight(0),
),
onPressed: onPressed,
child: LayoutBuilder(
builder: (context, constraints) {
final availableHeight = constraints.maxHeight.isFinite
? constraints.maxHeight
: 200.0;
final availableWidth = constraints.maxWidth.isFinite
? constraints.maxWidth
: 320.0;
final isCompact = availableHeight < 72.0 || availableWidth < 180.0;
final baseGap = isCompact ? 8.0 : 12.0;
final content = Flex(
direction: isCompact ? Axis.horizontal : Axis.vertical,
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: isCompact ? 24.0 : 60.0, color: iconColor),
SizedBox(
width: isCompact ? baseGap : 0,
height: isCompact ? 0 : baseGap,
),
Text(
label,
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.visible,
style:
(isCompact
? theme.textTheme.titleMedium
: theme.textTheme.titleLarge)
?.copyWith(fontWeight: FontWeight.w600),
),
],
);
return Center(
child: FittedBox(
fit: BoxFit.scaleDown,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: math.max(0, availableWidth - 12),
maxHeight: math.max(0, availableHeight - 12),
),
child: content,
),
),
);
},
),
);
}
}
+17 -7
View File
@@ -20,6 +20,7 @@ class ScannerScreen extends StatefulWidget {
class _ScannerScreenState extends State<ScannerScreen> {
bool _changedNavigation = false;
late final MeshCoreConnector _connector;
late final VoidCallback _connectionListener;
BluetoothAdapterState _bluetoothState = BluetoothAdapterState.unknown;
late StreamSubscription<BluetoothAdapterState> _bluetoothStateSubscription;
@@ -27,12 +28,12 @@ class _ScannerScreenState extends State<ScannerScreen> {
@override
void initState() {
super.initState();
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
_connector = Provider.of<MeshCoreConnector>(context, listen: false);
_connectionListener = () {
if (connector.state == MeshCoreConnectionState.disconnected) {
if (_connector.state == MeshCoreConnectionState.disconnected) {
_changedNavigation = false;
} else if (connector.state == MeshCoreConnectionState.connected &&
} else if (_connector.state == MeshCoreConnectionState.connected &&
!_changedNavigation) {
_changedNavigation = true;
if (mounted) {
@@ -43,7 +44,7 @@ class _ScannerScreenState extends State<ScannerScreen> {
}
};
connector.addListener(_connectionListener);
_connector.addListener(_connectionListener);
_bluetoothStateSubscription = FlutterBluePlus.adapterState.listen(
(state) {
@@ -53,7 +54,7 @@ class _ScannerScreenState extends State<ScannerScreen> {
});
// Cancel scan if Bluetooth turns off while scanning
if (state != BluetoothAdapterState.on) {
unawaited(connector.stopScan());
unawaited(_connector.stopScan());
}
}
},
@@ -65,16 +66,25 @@ class _ScannerScreenState extends State<ScannerScreen> {
@override
void dispose() {
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
connector.removeListener(_connectionListener);
_connector.removeListener(_connectionListener);
unawaited(_bluetoothStateSubscription.cancel());
super.dispose();
}
@override
Widget build(BuildContext context) {
final canPop = Navigator.of(context).canPop();
return Scaffold(
appBar: AppBar(
leading: canPop
? IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
debugPrint('ScannerScreen: back button pressed');
Navigator.of(context).maybePop();
},
)
: null,
title: AdaptiveAppBarTitle(context.l10n.scanner_title),
centerTitle: true,
automaticallyImplyLeading: false,
+456
View File
@@ -0,0 +1,456 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import 'contacts_screen.dart';
class UsbScreen extends StatefulWidget {
const UsbScreen({super.key});
@override
State<UsbScreen> createState() => _UsbScreenState();
}
class _UsbScreenState extends State<UsbScreen> {
final List<String> _ports = <String>[];
bool _isLoadingPorts = true;
bool _isConnecting = false;
bool _navigatedToContacts = false;
String? _selectedPort;
String? _errorText;
late final MeshCoreConnector _connector;
late final VoidCallback _connectionListener;
@override
void initState() {
super.initState();
_connector = context.read<MeshCoreConnector>();
_connectionListener = () {
if (!mounted) return;
if (_connector.state == MeshCoreConnectionState.disconnected) {
_navigatedToContacts = false;
if (_isConnecting) {
setState(() {
_isConnecting = false;
});
}
}
if (_connector.state == MeshCoreConnectionState.connected &&
_connector.isUsbTransportConnected &&
!_navigatedToContacts) {
_navigatedToContacts = true;
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const ContactsScreen()),
);
}
};
_connector.addListener(_connectionListener);
unawaited(_loadPorts());
}
@override
void dispose() {
_connector.removeListener(_connectionListener);
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l10n = context.l10n;
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
debugPrint('UsbScreen: back button pressed');
Navigator.of(context).maybePop();
},
),
title: Text(
l10n.connectionChoiceUsbLabel,
style: theme.textTheme.titleLarge,
),
centerTitle: true,
),
body: SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final availableHeight = constraints.maxHeight.isFinite
? constraints.maxHeight
: 600.0;
final availableWidth = constraints.maxWidth.isFinite
? constraints.maxWidth
: 800.0;
final gap = math.max(8.0, math.min(16.0, availableHeight * 0.025));
final iconSize = math.max(
28.0,
math.min(72.0, availableHeight * 0.12),
);
final isNarrow = availableWidth < 460.0;
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Flexible(
flex: 3,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.usb,
size: iconSize,
color: theme.colorScheme.primary,
),
SizedBox(height: gap),
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
l10n.usbScreenTitle,
textAlign: TextAlign.center,
style: theme.textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
),
),
SizedBox(height: math.max(4.0, gap * 0.5)),
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
l10n.usbScreenSubtitle,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
),
SizedBox(height: gap),
FittedBox(
fit: BoxFit.scaleDown,
child: Chip(
label: Text(
_selectedPort == null
? l10n.usbScreenStatus
: _friendlyPortName(_selectedPort!),
overflow: TextOverflow.ellipsis,
),
backgroundColor:
theme.colorScheme.surfaceContainerHighest,
),
),
],
),
),
),
SizedBox(height: gap),
Expanded(child: _buildPortList(context)),
if (_errorText != null) ...[
SizedBox(height: gap),
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
_errorText!,
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.error,
),
),
),
),
],
SizedBox(height: gap),
if (isNarrow)
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
OutlinedButton.icon(
onPressed: _isLoadingPorts || _isConnecting
? null
: () {
debugPrint(
'UsbScreen: refresh ports pressed',
);
_loadPorts();
},
icon: const Icon(Icons.refresh),
label: Text(l10n.repeater_refresh),
),
SizedBox(height: gap),
FilledButton.icon(
onPressed: _canConnect
? () {
final rawPortName = _normalizedPortName(
_selectedPort!,
);
debugPrint(
'UsbScreen: connect pressed for $_selectedPort (raw: $rawPortName)',
);
_connectSelectedPort();
}
: null,
icon: _isConnecting
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.usb),
label: Text(l10n.common_connect),
),
],
)
else
Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: _isLoadingPorts || _isConnecting
? null
: () {
debugPrint(
'UsbScreen: refresh ports pressed',
);
_loadPorts();
},
icon: const Icon(Icons.refresh),
label: Text(l10n.repeater_refresh),
),
),
SizedBox(width: gap),
Expanded(
child: FilledButton.icon(
onPressed: _canConnect
? () {
final rawPortName = _normalizedPortName(
_selectedPort!,
);
debugPrint(
'UsbScreen: connect pressed for $_selectedPort (raw: $rawPortName)',
);
_connectSelectedPort();
}
: null,
icon: _isConnecting
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.usb),
label: Text(l10n.common_connect),
),
),
],
),
SizedBox(height: math.max(4.0, gap * 0.75)),
Flexible(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
l10n.usbScreenNote,
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
),
],
),
);
},
),
),
);
}
bool get _canConnect =>
!_isLoadingPorts &&
!_isConnecting &&
_selectedPort != null &&
_selectedPort!.isNotEmpty;
Widget _buildPortList(BuildContext context) {
final theme = Theme.of(context);
final l10n = context.l10n;
if (_isLoadingPorts) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 12),
Text(l10n.common_loading),
],
),
);
}
if (_ports.isEmpty) {
return Center(
child: Text(
l10n.usbScreenEmptyState,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
);
}
return ListView.separated(
itemCount: _ports.length,
itemBuilder: (context, index) {
final port = _ports[index];
final isSelected = port == _selectedPort;
final displayName = _friendlyPortName(port);
final rawName = _normalizedPortName(port);
final showRawName = rawName != displayName;
return Material(
color: isSelected
? theme.colorScheme.primaryContainer
: theme.colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(16),
child: ListTile(
onTap: _isConnecting
? null
: () {
setState(() {
_selectedPort = port;
_errorText = null;
});
debugPrint('UsbScreen: selected port $port');
},
leading: Icon(
Icons.usb,
color: isSelected
? theme.colorScheme.onPrimaryContainer
: theme.colorScheme.onSurfaceVariant,
),
title: Text(
displayName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith(
color: isSelected ? theme.colorScheme.onPrimaryContainer : null,
),
),
subtitle: showRawName
? Text(
rawName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall?.copyWith(
color: isSelected
? theme.colorScheme.onPrimaryContainer
: theme.colorScheme.onSurfaceVariant,
),
)
: null,
trailing: isSelected
? Icon(
Icons.check_circle,
color: theme.colorScheme.onPrimaryContainer,
)
: null,
),
);
},
separatorBuilder: (context, index) => const SizedBox(height: 10),
);
}
Future<void> _loadPorts() async {
if (!mounted) return;
setState(() {
_isLoadingPorts = true;
_errorText = null;
});
try {
final ports = await _connector.listUsbPorts();
if (!mounted) return;
setState(() {
_ports
..clear()
..addAll(ports);
if (_ports.isEmpty) {
_selectedPort = null;
} else if (!_ports.contains(_selectedPort)) {
_selectedPort = _ports.first;
}
_isLoadingPorts = false;
});
} catch (error) {
if (!mounted) return;
setState(() {
_ports.clear();
_selectedPort = null;
_errorText = error.toString();
_isLoadingPorts = false;
});
}
}
Future<void> _connectSelectedPort() async {
final selectedPort = _selectedPort;
if (selectedPort == null || selectedPort.isEmpty) {
return;
}
final rawPortName = _normalizedPortName(selectedPort);
setState(() {
_isConnecting = true;
_errorText = null;
});
try {
await _connector.connectUsb(portName: rawPortName);
} catch (error) {
if (!mounted) return;
setState(() {
_isConnecting = false;
_errorText = error.toString();
});
}
}
String _normalizedPortName(String portLabel) {
final separatorIndex = portLabel.indexOf(' - ');
final normalized = separatorIndex >= 0
? portLabel.substring(0, separatorIndex)
: portLabel;
return normalized.trim();
}
String _friendlyPortName(String portLabel) {
final separatorIndex = portLabel.indexOf(' - ');
if (separatorIndex < 0) {
return portLabel.trim();
}
final friendlyName = portLabel.substring(separatorIndex + 3).trim();
if (friendlyName.isEmpty) {
return _normalizedPortName(portLabel);
}
return friendlyName;
}
}