Flutter USB写入功能插件another_flutter_usb_write的使用

Flutter USB写入功能插件another_flutter_usb_write的使用

flutter_usb_write 插件用于在Android设备上向USB设备写入原始数据。与 USB Serial 插件不同的是,此插件不使用串行协议。

例如,可以通过发送ESC/POS字节来打印到USB POS打印机。

支持的Android设备

只有支持USB主机(USB OTG)的设备才能与USB设备通信。

支持的USB设备

理论上,你可以向任何USB设备写入数据(参见限制)。

该插件已经过多个USB POS打印机的测试。

功能

  • 列出连接到Android设备的所有USB设备。
  • 创建一个流以监听USB设备的插入或移除事件。
  • 自动获取权限(参见权限
  • 打开选定USB设备的连接。
  • 使用打开的连接向USB设备发送字节。
  • 关闭打开的连接。
  • 发送 controlTransfer 字节。

限制

  • 不支持通过USB连接接收消息(如缺纸信息)。
  • 连接固定为所选USB设备的第一个接口。
  • 只支持 USB_ENDPOINT_XFER_BULK 端点。
  • 只支持方向不是 USB_DIR_IN 的USB端点。

权限

如果你不介意每次USB设备物理连接到Android设备时都请求权限,则无需额外操作。插件会在需要时请求权限。

但是,如果你不想每次都请求权限,可以在 AndroidManifest.xml 中添加以下内容:

<intent-filter>
    <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>

<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
           android:resource="@xml/device_filter" />

并将 device_filter.xml 放置在 res/xml 目录下(根据你的设备进行修改)。这将在USB设备物理连接时自动打开你的应用。一旦权限被允许,它将不再询问。

示例 device_filter.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 0x1CBE / 0x0003: USB POS printer 58 mm -->
    <usb-device vendor-id="7358" product-id="3" />
    <!-- 0x1CB0 / 0x0003: USB POS printer 58 mm -->
    <usb-device vendor-id="7344" product-id="3" />
    <!-- 0x0483 / 0x5740: USB POS printer 58 mm -->
    <usb-device vendor-id="1155" product-id="22336" />
    <!-- 0x0493 / 0x8760: USB POS printer 58 mm -->
    <usb-device vendor-id="1171" product-id="34656" />
    <!-- 0x0416 / 0x5011: USB POS printer 58 mm (Issyzone Pos IMP006B) -->
    <usb-device vendor-id="1046" product-id="20497" />
    <!-- 0x0416 / 0xAABB: USB POS printer 58 mm -->
    <usb-device vendor-id="1046" product-id="43707" />
    <!-- 0x1659 / 0x8965: USB POS printer 58 mm -->
    <usb-device vendor-id="5721" product-id="35173" />
    <!-- 0x0483 / 0x5741: USB POS printer 58 mm -->
    <usb-device vendor-id="1155" product-id="22337" />
    <!-- 0x4B43 / 0x3830: USB POS printer 80 mm (GoojPrt MTP-3) -->
    <usb-device vendor-id="19267" product-id="14384" />
    <!-- 0x0525 / 0xA700: USB POS printer 80 mm (MicroPOS WTP100II) -->
    <usb-device vendor-id="1317" product-id="42752" />
    <!-- 0x0525 / 0xA702: USB POS printer 58 mm (Sewoo LK-P20) -->
    <usb-device vendor-id="1317" product-id="42754" />
    <!-- 0x0416 / 0x5011: USB POS printer 58 mm -->
    <usb-device vendor-id="1046" product-id="20497" />      
</resources>

入门指南

首先,你可能想列出所有连接到你的Android设备的USB设备。

try {
  List<UsbDevice> devices = await _flutterUsbPos.listDevices();
} on PlatformException catch (e) {
  print(e.message);
}

一旦找到设备,你需要在尝试写入之前打开连接。每次打开连接时,设备都会获得新的 deviceId。为了打开连接,始终使用 vidpid 参数,方法将返回一个新的 UsbDevice 对象,其中包含 deviceId 值。

Future<UsbDevice> _connect(UsbDevice device) async {
  try {
    var result = await _flutterUsbPos.open(
      vendorId: device.vid,
      productId: device.pid,
    );
    return result;
  } on PermissionException {
    print("Not allowed to do that");
    return null;
  } on PlatformException catch (e) {
    print(e.message);
    return null;
  }
}

之后,你可以尝试向设备写入数据。函数返回 true 如果写入的字节数 >= 0。

bool result = await _flutterUsbPos.write(Uint8List.fromList("Hello world".codeUnits));

完成写入后,关闭连接以释放资源。

Future _disconnect() async {
  try {
    await _flutterUsbPos.close();
  } on PlatformException catch (e) {
    print(e.message);
  }
}

更多关于Flutter USB写入功能插件another_flutter_usb_write的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter USB写入功能插件another_flutter_usb_write的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用another_flutter_usb_write插件来实现USB写入功能的示例代码。这个插件允许你通过Flutter应用与USB设备进行通信,并写入数据。

首先,确保你的Flutter项目已经创建,并且已经配置好开发环境。

1. 添加依赖

pubspec.yaml文件中添加another_flutter_usb_write插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  another_flutter_usb_write: ^最新版本号  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 请求USB权限

在Android和iOS上,你需要请求USB设备的权限。以下是如何在Android和iOS上配置权限。

Android

AndroidManifest.xml文件中添加USB主机权限:

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

iOS

Info.plist文件中添加适当的USB权限描述。

3. 编写Flutter代码

下面是一个基本的Flutter应用示例,展示了如何使用another_flutter_usb_write插件来枚举USB设备并写入数据。

import 'package:flutter/material.dart';
import 'package:another_flutter_usb_write/another_flutter_usb_write.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<UsbDevice> devices = [];
  UsbDevice? selectedDevice;

  @override
  void initState() {
    super.initState();
    enumerateDevices();
  }

  void enumerateDevices() async {
    List<UsbDevice> foundDevices = await UsbManager.shared.enumerateDevices();
    setState(() {
      devices = foundDevices;
    });
  }

  void writeDataToUsb() async {
    if (selectedDevice == null) {
      print("No device selected");
      return;
    }

    UsbInterface? interface = selectedDevice!.interface(0);
    UsbEndpoint? endpoint = interface?.endpoint(0x81); // OUT endpoint

    if (endpoint == null) {
      print("No suitable endpoint found");
      return;
    }

    UsbConnection connection = await UsbConnection.open(selectedDevice!, interface!);
    Uint8List data = Uint8List.fromList([0x12, 0x34, 0x56, 0x78]); // Example data

    try {
      await connection.bulkTransfer(endpoint!, data);
      print("Data written successfully");
    } catch (e) {
      print("Error writing data: $e");
    } finally {
      await connection.close();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('USB Write Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: [
              Text('Available USB Devices:'),
              Expanded(
                child: ListView.builder(
                  itemCount: devices.length,
                  itemBuilder: (context, index) {
                    UsbDevice device = devices[index];
                    return ListTile(
                      title: Text(device.deviceName),
                      onTap: () {
                        setState(() {
                          selectedDevice = device;
                        });
                      },
                    );
                  },
                ),
              ),
              ElevatedButton(
                onPressed: writeDataToUsb,
                child: Text('Write Data to USB'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

注意事项

  1. 权限处理:确保在运行时请求和处理USB权限。
  2. 设备兼容性:不同设备和USB接口可能有所不同,确保正确配置和使用合适的接口和端点。
  3. 数据格式:根据具体的USB设备协议,确保写入的数据格式正确。

这个示例代码只是一个基本框架,你可能需要根据具体的USB设备和需求进行调整和扩展。

回到顶部