I am a beginner in flutter. Currently I'm trying to write some code that will allow me to establish a connection between my thermal printer and my Android phone through my USB cable. At the moment I am using the USB Serial library. When I modify the library code to customize it to my needs, nothing works anymore and when I connect my printer to my phone, the phone doesn't even detect my printer. In other words, I customize the code so that my printer can be detected through its characteristics (name, vendorID, productID) but the only thing that is displayed is "No serial devices available", which the printer is connected or not. I will put my code below, do not hesitate to let me know all your comments. I have already handled the "permissions" in the AndroidManifest.xml. My goal would be to print, and cut after the connection has been established. THANKS.
import 'package:flutter/material.dart';
import 'package:usb_serial/transaction.dart';
import 'package:usb_serial/usb_serial.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
UsbPort? _port;
String _status = "Idle";
List<Widget> _ports = [];
List<Widget> _serialData = [];
StreamSubscription<String>? _subscription;
Transaction<String>? _transaction;
UsbDevice? _device;
TextEditingController _textController = TextEditingController();
Future<bool> _connectTo(UsbDevice? device) async {
// Le reste du code reste inchangé
if (device == null) {
_device = null;
setState(() {
_status = "Disconnected";
});
return true;
}
_port = await device.create();
if (await (_port!.open()) != true) {
setState(() {
_status = "Failed to open port";
});
return false;
}
_device = device;
await _port!.setDTR(true);
await _port!.setRTS(true);
await _port!.setPortParameters(115200, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);
_transaction = Transaction.stringTerminated(_port!.inputStream as Stream<Uint8List>, Uint8List.fromList([13, 10]));
_subscription = _transaction!.stream.listen((String line) {
setState(() {
_serialData.add(Text(line));
if (_serialData.length > 20) {
_serialData.removeAt(0);
}
});
});
setState(() {
_status = "Connected";
});
return true;
}
void _getPorts() async {
_ports = [];
List<UsbDevice> devices = await UsbSerial.listDevices();
// Votre imprimante spécifique
String desiredPrinterName = "CP290HRS-12V";
int desiredVendorId = 6868;
int desiredProductId = 2;
bool printerFound = false;
devices.forEach((device) {
_ports.add(ListTile(
leading: Icon(Icons.usb),
title: Text(device.manufacturerName!),
subtitle: Text(device.productName!),
trailing: ElevatedButton(
child: Text(_device == device ? "Disconnect" : "Connect"),
onPressed: () {
_connectTo(_device == device ? null : device).then((res) {
_getPorts();
});
},
),
));
// Identifier votre imprimante
if (device.productName == desiredPrinterName &&
device.vid== desiredVendorId &&
device.pid == desiredProductId) {
_connectTo(device);
printerFound = true;
}
});
if (!printerFound) {
_connectTo(null);
}
setState(() {});
}
@override
void dispose() {
super.dispose();
_connectTo(null);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('USB Serial Plugin example app'),
),
body: Center(
child: Column(children: <Widget>[
Text(_ports.length > 0 ? "Available Serial Ports" : "No serial devices available", style: Theme.of(context).textTheme.headline6),
..._ports,
Text('Status: $_status\n'),
Text('info: ${_port.toString()}\n'),
ListTile(
title: TextField(
controller: _textController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Text To Send',
),
),
trailing: ElevatedButton(
child: Text("Send"),
onPressed: _port == null
? null
: () async {
if (_port == null) {
return;
}
String data = _textController.text + "\r\n";
await _port!.write(Uint8List.fromList(data.codeUnits));
_textController.text = "";
},
),
),
Text("Result Data", style: Theme.of(context).textTheme.headline6),
..._serialData,
])),
));
}
}
I would really like to establish the connection between my printer and my phone when I click the "Connect" button. I would also like to observe a change in status depending on whether the printer is connected or not. My goal would be to print, and cut after the connection has been established. I work with android Studio.