connect method
Open connection to deviceId (as returned by listDevices).
Implementation
Future<void> connect(String deviceId) async {
await disconnect(); // clean up any previous connection
if (Platform.isAndroid) {
final device = _androidDevices[deviceId];
if (device == null) throw StateError('Device not found: $deviceId');
final port = await device.create();
if (port == null) throw StateError('Failed to create port for $deviceId');
final opened = await port.open();
if (!opened) throw StateError('Permission denied or port busy: $deviceId');
await port.setPortParameters(
baudRate,
UsbPort.DATABITS_8,
UsbPort.STOPBITS_1,
UsbPort.PARITY_NONE,
);
await port.setDTR(true);
await port.setRTS(true);
_usbPort = port;
} else if (Platform.isWindows) {
final port = SerialPort(deviceId);
if (!port.openReadWrite()) {
throw StateError(
'Cannot open $deviceId: ${SerialPort.lastError?.message}');
}
final cfg = SerialPortConfig()
..baudRate = baudRate
..bits = 8
..stopBits = 1
..parity = SerialPortParity.none
..xonXoff = 0
..rts = SerialPortRts.flowControl
..cts = SerialPortCts.ignore
..dsr = SerialPortDsr.ignore
..dtr = SerialPortDtr.flowControl;
port.config = cfg;
_winPort = port;
} else {
throw UnsupportedError('USB serial not supported on this platform.');
}
// Allow port to stabilise (as specified in the protocol doc).
await Future<void>.delayed(const Duration(milliseconds: 200));
// Start the persistent reader for Windows now that the port is stable.
if (Platform.isWindows) {
_winReader = SerialPortReader(_winPort!);
_winReaderSub = _winReader!.stream.listen(
(data) {
if (!_winRx.isClosed) _winRx.add(data);
},
onError: (Object e) {
if (!_winRx.isClosed) _winRx.addError(e);
},
cancelOnError: false,
);
}
}