Flutter USB 串口

问题描述 投票:0回答:1

我是颤振的初学者。目前,我正在尝试编写一些代码,以便通过 USB 电缆在热敏打印机和 Android 手机之间建立连接。目前我正在使用 USB 串行库。当我修改库代码以根据我的需要对其进行自定义时,一切都不再起作用,当我将打印机连接到手机时,手机甚至检测不到我的打印机。换句话说,我自定义代码,以便可以通过其特征(名称、供应商ID、产品ID)检测到我的打印机,但唯一显示的是“没有可用的串行设备”,即打印机是否已连接。我将把我的代码放在下面,请随时让我知道您的所有评论。我已经处理了 AndroidManifest.xml 中的“权限”。我的目标是打印,并在建立连接后剪切。谢谢。

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,
              ])),
        ));
  }
}

我真的很想在单击“连接”按钮时在打印机和手机之间建立连接。我还想根据打印机是否连接来观察状态的变化。我的目标是打印,并在建立连接后剪切。我使用 android Studio。

dart flutter-dependencies thermal-printer usbserial escpos
1个回答
0
投票

manifest.xml 可能有问题,首先检查一下您是否编辑了正确的文件;如果您使用 Android studio,应该有一个位于 android/app/src/profile 下,另一个位于 android/app/src/main 下。另外,我不知道您是否已经这样做了,但您放入 device-filter.xml 中的值应该是十六进制。

您放在这里的代码看起来与USB串行开发文档中的代码完全一样,所以这个应该没有问题。

抱歉,如果我没有说清楚,希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.