Flutter USB设备管理插件flutter_usb_device_manage的使用

Flutter USB设备管理插件flutter_usb_device_manage的使用

主要用于项目中USB设备的集中授权及硬件功能实现,目前包含了USB指纹模块和RFID通讯模块。

USB指纹模块

USB指纹模块主要功能是指纹的注册登记上报和采集匹配模版上报。

openDevice(打开设备)

打开指纹模块的通讯端口。

_flutterUsbFingerprintManagePlugin.openDevice();

closeDevice(关闭设备)

关闭指纹模块的通讯端口。

_flutterUsbFingerprintManagePlugin.closeDevice();

registration(指纹登记)

通讯端口打开后调用该方法进行指纹的登记,包含登记次数参数(enrolCount),登记成功后会通过异步消息返回指纹特征的Base64字符串。

_flutterUsbFingerprintManagePlugin.registration(3);

collecting(指纹采集)

通讯端口打开后调用该方法进行指纹采集,采集成功后会通过异步消息返回指纹特征的Base64字符串,可用于服务端比对。

_flutterUsbFingerprintManagePlugin.collecting();

RFID通讯模块

openAndroidUsbSerial(打开USB串口)

打开RFID模块的USB转串口通讯。

_flutterUsbRFIDManagePlugin.openUsbSerial();

closeAndroidUsbSerial(关闭USB串口)

关闭RFID模块的USB转串口通讯。

_flutterUsbRFIDManagePlugin.closeUsbSerial();

startRead(开始读取)

打开通讯后可通过调用该方法进行RFID标签的读取上报,参数包含模式(mode)、超时时间(timeout),标签上报通过异步消息上报。

_flutterUsbRFIDManagePlugin.startRead(1, 500000);

stopRead(停止读取)

打开通讯后可通过调用该方法停止RFID标签的读取上报。

_flutterUsbRFIDManagePlugin.stopRead();

完整示例代码

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

import 'package:flutter_usb_device_manage/flutter_usb_device_manage.dart';
import 'package:flutter_usb_device_manage/flutter_usb_fingerprint_manage.dart';
import 'package:flutter_usb_device_manage/flutter_usb_rfid_manage.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _message = 'Unknown';
  final _flutterUsbDeviceManagePlugin = FlutterUsbDeviceManage();
  final _flutterUsbFingerprintManagePlugin = FlutterUsbFingerprintManage();
  final _flutterUsbRFIDManagePlugin = FlutterUsbRFIDManage();

  [@override](/user/override)
  void initState() {
    super.initState();
    initListenMessage();
  }

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initListenMessage() async {
    _flutterUsbDeviceManagePlugin.listenerEvent(
        (message) => {
              setState(() {
                _message = message;
              })
            },
        // 忽略:避免打印
        (error) => {print("$error")});
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('串口设备调试程序'),
        ),
        body: Column(
          children: [
            TextField(
                style: const TextStyle(color: Color(0xFFA7ABBB), fontSize: 15),
                controller: TextEditingController.fromValue(
                    TextEditingValue(text: _message)),
                decoration: InputDecoration(
                  counterText: '',
                  hintMaxLines: 10,
                  filled: true,
                  hintStyle: const TextStyle(
                      color: Color.fromARGB(255, 5, 5, 6), fontSize: 15),
                  hintText: '消息内容',
                  contentPadding:
                      const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(6),
                      borderSide: BorderSide.none),
                  focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(6),
                      borderSide: BorderSide.none),
                )),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('USB设备授权'),
                    onPressed: () {
                      _flutterUsbDeviceManagePlugin.requestPermission();
                    }),
              ],
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('打开指纹模块'),
                    onPressed: () {
                      _flutterUsbFingerprintManagePlugin.openDevice();
                    }),
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('登记指纹'),
                    onPressed: () {
                      _flutterUsbFingerprintManagePlugin.registration(3);
                    }),
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('采集指纹'),
                    onPressed: () {
                      _flutterUsbFingerprintManagePlugin.collecting();
                    }),
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('关闭指纹模块'),
                    onPressed: () {
                      _flutterUsbFingerprintManagePlugin.closeDevice();
                    }),
              ],
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('打开RFID模块通讯'),
                    onPressed: () {
                      _flutterUsbRFIDManagePlugin.openUsbSerial();
                    }),
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('开始读取'),
                    onPressed: () {
                      _flutterUsbRFIDManagePlugin.startRead(1, 500000);
                    }),
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('停止读取'),
                    onPressed: () {
                      _flutterUsbRFIDManagePlugin.stopRead();
                    }),
                MaterialButton(
                    color: Colors.blue,
                    textColor: Colors.white,
                    child: const Text('关闭RFID模块通信'),
                    onPressed: () {
                      _flutterUsbRFIDManagePlugin.closeUsbSerial();
                    }),
              ],
            )
          ],
        ),
      ),
    );
  }
}

更多关于Flutter USB设备管理插件flutter_usb_device_manage的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter USB设备管理插件flutter_usb_device_manage的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_usb_device_manage 是一个用于在 Flutter 应用中管理 USB 设备的插件。它允许你与连接的 USB 设备进行交互,例如读取和写入数据、获取设备信息等。以下是如何使用 flutter_usb_device_manage 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_usb_device_manage 插件的依赖。

dependencies:
  flutter:
    sdk: flutter
  flutter_usb_device_manage: ^0.1.0  # 请使用最新版本

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

2. 导入插件

在你的 Dart 文件中导入插件:

import 'package:flutter_usb_device_manage/flutter_usb_device_manage.dart';

3. 初始化插件

在使用插件之前,通常需要初始化它。你可以通过以下方式初始化:

UsbDeviceManager usbDeviceManager = UsbDeviceManager();

4. 获取连接的 USB 设备

你可以使用 getDevices 方法获取当前连接的 USB 设备列表:

List<UsbDevice> devices = await usbDeviceManager.getDevices();
for (var device in devices) {
  print('Device ID: ${device.deviceId}, Name: ${device.deviceName}');
}

5. 打开 USB 设备

要与特定的 USB 设备进行交互,你需要先打开它:

UsbDevice device = devices.first;  // 假设我们打开第一个设备
bool isOpened = await usbDeviceManager.openDevice(device);
if (isOpened) {
  print('Device opened successfully');
} else {
  print('Failed to open device');
}

6. 读取和写入数据

一旦设备被打开,你可以使用 readwrite 方法与设备进行数据交互。

// 写入数据
List<int> dataToWrite = [0x01, 0x02, 0x03];
bool isWritten = await usbDeviceManager.writeData(device, dataToWrite);
if (isWritten) {
  print('Data written successfully');
} else {
  print('Failed to write data');
}

// 读取数据
List<int> dataRead = await usbDeviceManager.readData(device);
print('Data read: $dataRead');

7. 关闭 USB 设备

完成操作后,记得关闭设备以释放资源:

await usbDeviceManager.closeDevice(device);
print('Device closed');

8. 处理权限

在某些平台上(如 Android),访问 USB 设备可能需要特定的权限。你可能需要在 AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.USB_PERMISSION" />

9. 处理设备插拔事件

你还可以监听 USB 设备的插拔事件:

usbDeviceManager.onDeviceAttached.listen((UsbDevice device) {
  print('Device attached: ${device.deviceName}');
});

usbDeviceManager.onDeviceDetached.listen((UsbDevice device) {
  print('Device detached: ${device.deviceName}');
});

10. 错误处理

在使用插件时,务必处理可能出现的异常和错误:

try {
  // 你的代码
} catch (e) {
  print('An error occurred: $e');
}
回到顶部