mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-11 16:30:28 +00:00
feat: Add serial compass support #0
This commit is contained in:
50
lib/services/serial/serial_transport.dart
Normal file
50
lib/services/serial/serial_transport.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
import 'package:meshcore_client/meshcore_client.dart';
|
||||
|
||||
import 'serial_transport_stub.dart'
|
||||
if (dart.library.io) 'serial_transport_io.dart'
|
||||
if (dart.library.js_interop) 'serial_transport_web.dart';
|
||||
|
||||
const int kSerialBaudRate = 115200;
|
||||
|
||||
class SerialDeviceInfo {
|
||||
final String id;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final Object handle;
|
||||
|
||||
const SerialDeviceInfo({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.handle,
|
||||
});
|
||||
}
|
||||
|
||||
class SerialConnection {
|
||||
final MeshCoreSerialService service;
|
||||
final String deviceId;
|
||||
final String deviceName;
|
||||
final Future<void> Function() disconnect;
|
||||
|
||||
const SerialConnection({
|
||||
required this.service,
|
||||
required this.deviceId,
|
||||
required this.deviceName,
|
||||
required this.disconnect,
|
||||
});
|
||||
}
|
||||
|
||||
abstract class SerialTransport {
|
||||
bool get isSupported;
|
||||
bool get canRequestDevice;
|
||||
String get actionLabel;
|
||||
String get emptyStateTitle;
|
||||
String get unsupportedMessage;
|
||||
|
||||
Future<List<SerialDeviceInfo>> listDevices();
|
||||
Future<SerialDeviceInfo?> requestDevice();
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device);
|
||||
void dispose();
|
||||
}
|
||||
|
||||
SerialTransport createSerialTransport() => createSerialTransportImpl();
|
||||
283
lib/services/serial/serial_transport_io.dart
Normal file
283
lib/services/serial/serial_transport_io.dart
Normal file
@@ -0,0 +1,283 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_libserialport/flutter_libserialport.dart';
|
||||
import 'package:meshcore_client/meshcore_client.dart';
|
||||
import 'package:usb_serial/usb_serial.dart';
|
||||
|
||||
import 'serial_transport.dart';
|
||||
|
||||
class _IoSerialTransport implements SerialTransport {
|
||||
@override
|
||||
bool get isSupported =>
|
||||
Platform.isAndroid || Platform.isMacOS || Platform.isWindows;
|
||||
|
||||
@override
|
||||
bool get canRequestDevice => false;
|
||||
|
||||
@override
|
||||
String get actionLabel =>
|
||||
Platform.isAndroid ? 'Scan USB devices' : 'Scan serial ports';
|
||||
|
||||
@override
|
||||
String get emptyStateTitle => Platform.isAndroid
|
||||
? 'No USB serial devices found.\nConnect a MeshCore device via OTG cable.'
|
||||
: 'No serial ports found.\nConnect a MeshCore device over USB serial.';
|
||||
|
||||
@override
|
||||
String get unsupportedMessage =>
|
||||
'Serial is supported on Android, macOS, Windows, and compatible web browsers.';
|
||||
|
||||
@override
|
||||
Future<List<SerialDeviceInfo>> listDevices() async {
|
||||
if (Platform.isAndroid) {
|
||||
final devices = await UsbSerial.listDevices();
|
||||
return devices.map(_androidDeviceInfo).toList(growable: false);
|
||||
}
|
||||
if (Platform.isMacOS || Platform.isWindows) {
|
||||
return _desktopSerialDevices();
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SerialDeviceInfo?> requestDevice() async => null;
|
||||
|
||||
@override
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device) async {
|
||||
if (Platform.isAndroid) {
|
||||
return _connectAndroid(device);
|
||||
}
|
||||
if (Platform.isMacOS || Platform.isWindows) {
|
||||
return _connectDesktop(device);
|
||||
}
|
||||
throw UnsupportedError(unsupportedMessage);
|
||||
}
|
||||
|
||||
SerialDeviceInfo _androidDeviceInfo(UsbDevice device) {
|
||||
final title = _firstNonEmpty([
|
||||
device.productName,
|
||||
device.manufacturerName,
|
||||
'USB Serial Device',
|
||||
]);
|
||||
final subtitleParts = <String>[
|
||||
if ((device.manufacturerName ?? '').trim().isNotEmpty)
|
||||
device.manufacturerName!.trim(),
|
||||
if (device.vid != null && device.pid != null)
|
||||
'VID:${_hex(device.vid!)} PID:${_hex(device.pid!)}',
|
||||
];
|
||||
|
||||
return SerialDeviceInfo(
|
||||
id: '${device.deviceId}:${device.vid ?? 'na'}:${device.pid ?? 'na'}:${device.productName ?? 'usb'}',
|
||||
title: title,
|
||||
subtitle: subtitleParts.isEmpty
|
||||
? 'Ready over OTG serial'
|
||||
: subtitleParts.join(' • '),
|
||||
handle: device,
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<SerialDeviceInfo>> _desktopSerialDevices() async {
|
||||
final ports = <SerialDeviceInfo>[];
|
||||
for (final address in SerialPort.availablePorts) {
|
||||
final port = SerialPort(address);
|
||||
try {
|
||||
final title = _firstNonEmpty([
|
||||
port.productName,
|
||||
port.description,
|
||||
address,
|
||||
]);
|
||||
final subtitleParts = <String>[
|
||||
address,
|
||||
if ((port.manufacturer ?? '').trim().isNotEmpty)
|
||||
port.manufacturer!.trim(),
|
||||
if (port.vendorId != null && port.productId != null)
|
||||
'VID:${_hex(port.vendorId!)} PID:${_hex(port.productId!)}',
|
||||
];
|
||||
ports.add(
|
||||
SerialDeviceInfo(
|
||||
id: address,
|
||||
title: title,
|
||||
subtitle: subtitleParts.join(' • '),
|
||||
handle: address,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
port.dispose();
|
||||
}
|
||||
}
|
||||
return ports;
|
||||
}
|
||||
|
||||
Future<SerialConnection> _connectAndroid(SerialDeviceInfo device) async {
|
||||
final usbDevice = device.handle as UsbDevice;
|
||||
final service = MeshCoreSerialService(appName: 'MeshCore SAR');
|
||||
StreamSubscription<Uint8List>? inputSubscription;
|
||||
UsbPort? port;
|
||||
|
||||
try {
|
||||
port = await usbDevice.create();
|
||||
if (port == null) {
|
||||
throw Exception('Failed to create USB port');
|
||||
}
|
||||
final opened = await port.open();
|
||||
if (!opened) {
|
||||
throw Exception('Failed to open USB port');
|
||||
}
|
||||
|
||||
await port.setDTR(true);
|
||||
await port.setRTS(true);
|
||||
await port.setPortParameters(
|
||||
kSerialBaudRate,
|
||||
UsbPort.DATABITS_8,
|
||||
UsbPort.STOPBITS_1,
|
||||
UsbPort.PARITY_NONE,
|
||||
);
|
||||
|
||||
service.writeRaw = (data) async {
|
||||
await port!.write(data);
|
||||
};
|
||||
|
||||
inputSubscription = port.inputStream?.listen(
|
||||
(data) => service.feedRawBytes(data),
|
||||
onError: (error) {
|
||||
debugPrint('❌ [Serial/Android] Read error: $error');
|
||||
service.markDisconnected();
|
||||
},
|
||||
onDone: () {
|
||||
debugPrint('⚠️ [Serial/Android] Port closed');
|
||||
service.markDisconnected();
|
||||
},
|
||||
);
|
||||
|
||||
final connected = await service.markConnected();
|
||||
if (!connected) {
|
||||
throw Exception('Serial session initialization failed');
|
||||
}
|
||||
|
||||
return SerialConnection(
|
||||
service: service,
|
||||
deviceId:
|
||||
'${usbDevice.deviceId}:${usbDevice.vid ?? 'na'}:${usbDevice.pid ?? 'na'}',
|
||||
deviceName: device.title,
|
||||
disconnect: () async {
|
||||
await inputSubscription?.cancel();
|
||||
inputSubscription = null;
|
||||
service.writeRaw = null;
|
||||
await port?.close();
|
||||
port = null;
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
await inputSubscription?.cancel();
|
||||
service.writeRaw = null;
|
||||
await port?.close();
|
||||
service.dispose();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<SerialConnection> _connectDesktop(SerialDeviceInfo device) async {
|
||||
final portName = device.handle as String;
|
||||
final port = SerialPort(portName);
|
||||
final config = SerialPortConfig();
|
||||
final service = MeshCoreSerialService(appName: 'MeshCore SAR');
|
||||
SerialPortReader? reader;
|
||||
StreamSubscription<Uint8List>? inputSubscription;
|
||||
|
||||
try {
|
||||
if (!port.openReadWrite()) {
|
||||
throw Exception(
|
||||
SerialPort.lastError?.message ?? 'Failed to open serial port',
|
||||
);
|
||||
}
|
||||
|
||||
config.baudRate = kSerialBaudRate;
|
||||
config.bits = 8;
|
||||
config.stopBits = 1;
|
||||
config.parity = SerialPortParity.none;
|
||||
config.setFlowControl(SerialPortFlowControl.none);
|
||||
config.dtr = SerialPortDtr.on;
|
||||
config.rts = SerialPortRts.on;
|
||||
port.config = config;
|
||||
|
||||
service.writeRaw = (data) async {
|
||||
var offset = 0;
|
||||
while (offset < data.length) {
|
||||
final written = port.write(data.sublist(offset));
|
||||
if (written <= 0) {
|
||||
throw Exception(
|
||||
SerialPort.lastError?.message ?? 'Failed to write to serial port',
|
||||
);
|
||||
}
|
||||
offset += written;
|
||||
}
|
||||
};
|
||||
|
||||
reader = SerialPortReader(port);
|
||||
inputSubscription = reader.stream.listen(
|
||||
(data) => service.feedRawBytes(data),
|
||||
onError: (error) {
|
||||
debugPrint('❌ [Serial/Desktop] Read error: $error');
|
||||
service.markDisconnected();
|
||||
},
|
||||
onDone: () {
|
||||
debugPrint('⚠️ [Serial/Desktop] Reader closed');
|
||||
service.markDisconnected();
|
||||
},
|
||||
);
|
||||
|
||||
final connected = await service.markConnected();
|
||||
if (!connected) {
|
||||
throw Exception('Serial session initialization failed');
|
||||
}
|
||||
|
||||
return SerialConnection(
|
||||
service: service,
|
||||
deviceId: portName,
|
||||
deviceName: device.title,
|
||||
disconnect: () async {
|
||||
await inputSubscription?.cancel();
|
||||
inputSubscription = null;
|
||||
reader?.close();
|
||||
reader = null;
|
||||
service.writeRaw = null;
|
||||
if (port.isOpen) {
|
||||
port.close();
|
||||
}
|
||||
port.dispose();
|
||||
config.dispose();
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
await inputSubscription?.cancel();
|
||||
reader?.close();
|
||||
service.writeRaw = null;
|
||||
if (port.isOpen) {
|
||||
port.close();
|
||||
}
|
||||
port.dispose();
|
||||
config.dispose();
|
||||
service.dispose();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
String _firstNonEmpty(List<String?> values) {
|
||||
for (final value in values) {
|
||||
final trimmed = value?.trim();
|
||||
if (trimmed != null && trimmed.isNotEmpty) {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
return 'Serial Device';
|
||||
}
|
||||
|
||||
String _hex(int value) => value.toRadixString(16).padLeft(4, '0');
|
||||
|
||||
SerialTransport createSerialTransportImpl() => _IoSerialTransport();
|
||||
35
lib/services/serial/serial_transport_stub.dart
Normal file
35
lib/services/serial/serial_transport_stub.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'serial_transport.dart';
|
||||
|
||||
class _UnsupportedSerialTransport implements SerialTransport {
|
||||
@override
|
||||
bool get isSupported => false;
|
||||
|
||||
@override
|
||||
bool get canRequestDevice => false;
|
||||
|
||||
@override
|
||||
String get actionLabel => 'Serial unsupported';
|
||||
|
||||
@override
|
||||
String get emptyStateTitle => 'Serial is unavailable on this platform.';
|
||||
|
||||
@override
|
||||
String get unsupportedMessage =>
|
||||
'Serial is supported on Android, macOS, Windows, and compatible web browsers.';
|
||||
|
||||
@override
|
||||
Future<List<SerialDeviceInfo>> listDevices() async => const [];
|
||||
|
||||
@override
|
||||
Future<SerialDeviceInfo?> requestDevice() async => null;
|
||||
|
||||
@override
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device) async {
|
||||
throw UnsupportedError(unsupportedMessage);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
SerialTransport createSerialTransportImpl() => _UnsupportedSerialTransport();
|
||||
209
lib/services/serial/serial_transport_web.dart
Normal file
209
lib/services/serial/serial_transport_web.dart
Normal file
@@ -0,0 +1,209 @@
|
||||
import 'dart:async';
|
||||
import 'dart:js_interop';
|
||||
import 'dart:js_interop_unsafe';
|
||||
|
||||
import 'package:meshcore_client/meshcore_client.dart';
|
||||
import 'package:web/web.dart' as web;
|
||||
import 'package:webserial/webserial.dart';
|
||||
|
||||
import 'serial_transport.dart';
|
||||
|
||||
class _WebSerialTransport implements SerialTransport {
|
||||
@override
|
||||
bool get isSupported =>
|
||||
web.window.navigator.hasProperty('serial'.toJS).toDart;
|
||||
|
||||
@override
|
||||
bool get canRequestDevice => true;
|
||||
|
||||
@override
|
||||
String get actionLabel => 'Choose serial device';
|
||||
|
||||
@override
|
||||
String get emptyStateTitle =>
|
||||
'No serial devices granted yet.\nChoose a device and approve access in your browser.';
|
||||
|
||||
@override
|
||||
String get unsupportedMessage =>
|
||||
'Web Serial requires a compatible browser such as Chrome or Edge and a secure context (HTTPS or localhost).';
|
||||
|
||||
@override
|
||||
Future<List<SerialDeviceInfo>> listDevices() async {
|
||||
if (!isSupported) {
|
||||
return const [];
|
||||
}
|
||||
final ports = await serial.getPorts().toDart;
|
||||
return ports
|
||||
.toDart
|
||||
.whereType<JSSerialPort>()
|
||||
.map(_deviceInfoForPort)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SerialDeviceInfo?> requestDevice() async {
|
||||
if (!isSupported) {
|
||||
return null;
|
||||
}
|
||||
final port = await requestWebSerialPort(null);
|
||||
if (port == null) {
|
||||
return null;
|
||||
}
|
||||
return _deviceInfoForPort(port);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device) async {
|
||||
final port = device.handle as JSSerialPort;
|
||||
final service = MeshCoreSerialService(appName: 'MeshCore SAR');
|
||||
web.ReadableStreamDefaultReader? reader;
|
||||
bool keepReading = false;
|
||||
|
||||
try {
|
||||
await port
|
||||
.open(
|
||||
JSSerialOptions(
|
||||
baudRate: kSerialBaudRate,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: 'none',
|
||||
bufferSize: 1024,
|
||||
flowControl: 'none',
|
||||
),
|
||||
)
|
||||
.toDart;
|
||||
|
||||
await port
|
||||
.setSignals(
|
||||
JSSerialOutputSignals(
|
||||
dataTerminalReady: true,
|
||||
requestToSend: true,
|
||||
),
|
||||
)
|
||||
.toDart;
|
||||
|
||||
service.writeRaw = (data) async {
|
||||
final writable = port.writable;
|
||||
if (writable == null) {
|
||||
throw Exception('Serial port is not writable');
|
||||
}
|
||||
final writer =
|
||||
writable.getWriter() as web.WritableStreamDefaultWriter?;
|
||||
if (writer == null) {
|
||||
throw Exception('Failed to acquire serial writer');
|
||||
}
|
||||
try {
|
||||
await writer.write(data.toJS).toDart;
|
||||
} finally {
|
||||
writer.releaseLock();
|
||||
}
|
||||
};
|
||||
|
||||
final readable = port.readable;
|
||||
if (readable == null) {
|
||||
throw Exception('Serial port is not readable');
|
||||
}
|
||||
|
||||
reader = readable.getReader() as web.ReadableStreamDefaultReader?;
|
||||
if (reader == null) {
|
||||
throw Exception('Failed to acquire serial reader');
|
||||
}
|
||||
|
||||
keepReading = true;
|
||||
unawaited(_readLoop(reader, service, () => keepReading));
|
||||
|
||||
final connected = await service.markConnected();
|
||||
if (!connected) {
|
||||
throw Exception('Serial session initialization failed');
|
||||
}
|
||||
|
||||
return SerialConnection(
|
||||
service: service,
|
||||
deviceId: device.id,
|
||||
deviceName: device.title,
|
||||
disconnect: () async {
|
||||
keepReading = false;
|
||||
try {
|
||||
await reader?.cancel().toDart;
|
||||
} catch (_) {}
|
||||
try {
|
||||
reader?.releaseLock();
|
||||
} catch (_) {}
|
||||
reader = null;
|
||||
service.writeRaw = null;
|
||||
try {
|
||||
await port.close().toDart;
|
||||
} catch (_) {}
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
keepReading = false;
|
||||
try {
|
||||
await reader?.cancel().toDart;
|
||||
} catch (_) {}
|
||||
try {
|
||||
reader?.releaseLock();
|
||||
} catch (_) {}
|
||||
service.writeRaw = null;
|
||||
try {
|
||||
await port.close().toDart;
|
||||
} catch (_) {}
|
||||
service.dispose();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _readLoop(
|
||||
web.ReadableStreamDefaultReader reader,
|
||||
MeshCoreSerialService service,
|
||||
bool Function() shouldContinue,
|
||||
) async {
|
||||
while (shouldContinue()) {
|
||||
try {
|
||||
final result = await reader.read().toDart;
|
||||
if (result.done) {
|
||||
break;
|
||||
}
|
||||
final value = result.value;
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
service.feedRawBytes((value as JSUint8Array).toDart);
|
||||
} catch (_) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
service.markDisconnected();
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
SerialDeviceInfo _deviceInfoForPort(JSSerialPort port) {
|
||||
final info = port.getInfo();
|
||||
final vendorId = info.usbVendorId;
|
||||
final productId = info.usbProductId;
|
||||
final title = (vendorId != 0 || productId != 0)
|
||||
? 'USB ${_hex(vendorId)}:${_hex(productId)}'
|
||||
: 'Granted serial device';
|
||||
final subtitle = [
|
||||
if (vendorId != 0 || productId != 0)
|
||||
'VID:${_hex(vendorId)} PID:${_hex(productId)}',
|
||||
'Web Serial',
|
||||
].join(' • ');
|
||||
|
||||
return SerialDeviceInfo(
|
||||
id: '$title::$subtitle',
|
||||
title: title,
|
||||
subtitle: subtitle,
|
||||
handle: port,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
String _hex(int value) => value.toRadixString(16).padLeft(4, '0');
|
||||
|
||||
SerialTransport createSerialTransportImpl() => _WebSerialTransport();
|
||||
Reference in New Issue
Block a user