Flutter串口通信插件flutter_weigh_serial的使用

Flutter串口通信插件flutter_weigh_serial的使用

flutter_weigh_serial 是一个用于 Flutter 应用程序的包,提供获取电子秤数据的能力,支持 Android 和 Windows 平台。

注意事项

该库仅支持通过串口方式连接(包括 USB 转串口)的称重设备。

使用方式

添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  flutter_weigh_serial: ^1.0.0+1

API 调用方式

首先,在你的 Dart 文件中导入 flutter_weigh_serial 包,并创建一个 WeighSerialProvider 实例。然后,你可以调用相应的方法来连接和读取数据。

import 'package:flutter/material.dart';
import 'package:flutter_weigh_serial/flutter_weigh_serial.dart';
import 'package:fluttertoast/fluttertoast.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late WeighSerialProvider weighSerialProvider;
  StreamSubscription<WeighResult>? _subscription;
  String weighData = '';

  @override
  void initState() {
    super.initState();
    weighSerialProvider = WeighSerialProvider();
  }

  @override
  void dispose() {
    _closeWeigh();
    _subscription?.cancel();
    super.dispose();
  }

  Future<void> _closeWeigh() {
    return weighSerialProvider.close();
  }

  void _connectWeigh() {
    weighSerialProvider.findAndConnect().then(
      (success) {
        if (success) {
          Fluttertoast.showToast(msg: '称重设备连接成功');
          _subscription = weighSerialProvider.weighListener?.listen(
            (data) {
              log('称重数据 - ${data.toMap().toString()}');
              setState(() {
                weighData = '${data.weight} kg (${data.isStable ? '稳定' : '不稳定'})';
              });
            },
          );
        } else {
          Fluttertoast.showToast(msg: '称重设备连接失败');
        }
      },
      onError: (e) {
        Fluttertoast.showToast(msg: '称重设备连接失败(${e.toString()})');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('称重 demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              weighSerialProvider.isConnect
                  ? Text('已连接 - 称重数据: $weighData')
                  : const Text('未连接'),
              const SizedBox(height: 15),
              TextButton(
                onPressed: _connectWeigh,
                child: const Text('连接称重'),
              ),
              const SizedBox(height: 15),
              TextButton(
                onPressed: () async {
                  await _closeWeigh();
                  setState(() {});
                },
                child: const Text('停止称重'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

称重返回的模型数据 WeighResult 结构

class WeighResult {
  /// 重量  单位是kg
  final double weight;

  /// 结果是否稳定  稳定:true  不稳定: false
  final bool isStable;

  // 构造函数
  WeighResult(this.weight, this.isStable);

  // 将结果转换为 Map
  Map<String, dynamic> toMap() {
    return {
      'weight': weight,
      'isStable': isStable,
    };
  }
}

扩展

该库支持以下 vIdpId 组合的称重设备:

// vId - pId
static Map<int, List<int>> weighDeviceList = {
  1027: [24577, 24592, 24593, 24596, 24597],
  4292: [60000, 60016, 60017],
  1659: [8963, 9123, 9139, 9155, 9171, 9187, 9203],
  6790: [21795, 29987, 21972],
  9025: [],
  5824: [1155],
  1003: [8260],
  7855: [4],
  3368: [516],
  1155: [22336],
  11914: [5, 10],
};

可以通过以下方式扩展支持的组合:

// 示例,扩展 vId 为 1111, pId 为 1234, 1235 的称重设备
WeighSerialConfig.weighDeviceList[1111] = [1234, 1235];

更多关于Flutter串口通信插件flutter_weigh_serial的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter串口通信插件flutter_weigh_serial的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_weigh_serial 是一个用于在 Flutter 应用中实现串口通信的插件,特别适用于与称重设备等硬件进行通信。以下是如何使用 flutter_weigh_serial 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 flutter_weigh_serial 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_weigh_serial: ^版本号

请将 ^版本号 替换为当前插件的最新版本号。

2. 导入插件

在需要使用串口通信的 Dart 文件中导入插件:

import 'package:flutter_weigh_serial/flutter_weigh_serial.dart';

3. 初始化串口

在使用串口之前,需要进行初始化:

WeighSerial weighSerial = WeighSerial();

4. 打开串口

打开串口并配置相关参数,如波特率、数据位、停止位、校验位等:

bool isOpened = await weighSerial.open(
  devicePath: '/dev/ttyS1', // 串口设备路径,根据实际设备修改
  baudRate: 9600,           // 波特率
  dataBits: 8,              // 数据位
  stopBits: 1,              // 停止位
  parity: 0,                // 校验位(0: None, 1: Odd, 2: Even)
);

if (isOpened) {
  print('串口打开成功');
} else {
  print('串口打开失败');
}

5. 读取数据

通过串口读取数据,通常是循环读取或监听数据流:

weighSerial.onDataReceived.listen((data) {
  print('收到数据: $data');
});

6. 发送数据

通过串口发送数据:

List<int> sendData = [0x01, 0x02, 0x03]; // 要发送的数据
weighSerial.send(sendData);

7. 关闭串口

在使用完串口后,记得关闭串口:

await weighSerial.close();

8. 处理异常

在实际使用中,可能会遇到各种异常情况,建议使用 try-catch 块来捕获并处理异常:

try {
  bool isOpened = await weighSerial.open(
    devicePath: '/dev/ttyS1',
    baudRate: 9600,
    dataBits: 8,
    stopBits: 1,
    parity: 0,
  );

  if (isOpened) {
    print('串口打开成功');
  } else {
    print('串口打开失败');
  }
} catch (e) {
  print('发生异常: $e');
}
回到顶部