Flutter蓝牙数据转换插件ble_data_converter的使用

Flutter蓝牙数据转换插件ble_data_converter的使用

目的

本插件用于将原始数据(List<int>)轻松转换为可以发送到BLE设备的数据。该插件支持的类型包括 utf8int8/16/32/64uint8/16/32/64。它还支持大端序和小端序。

如何使用

字符串转UTF-8(大端序)

// 编码(大端序)
const String sampleStr = "sample";
final List<int> strData = BLEDataConverter.str.stringToUtf8(sampleStr);

print(strData); // [115, 97, 109, 112, 108, 101]

// 解码(大端序)
final String decodeStr = BLEDataConverter.str.stringFromUtf8(strData);

print(decodeStr); // "sample"

整数转64位字节数据(大端序)

// 编码(大端序)
final int i64Max = 9223372036854775807;
final List<int> value = BLEDataConverter.i64.intToBytes(i64Max);

print(value); // [127, 255, 255, 255, 255, 255, 255, 255]

// 解码(大端序)
final int decode = BLEDataConverter.i64.bytesToInt(value);

print(decode); // 9223372036854775807

支持小端序

// 编码(小端序)
final int i64Max = 9223372036854775807;
final List<int> value =
    BLEDataConverter.i64.intToBytes(i64Max, endian: Endian.little);

print(value); //[127, 255, 255, 255, 255, 255, 255, 255]

// 解码(小端序)
final int decode =
    BLEDataConverter.i64.bytesToInt(value, endian: Endian.little);

print(decode); // 9223372036854775807

兼容类型

类型 字节长度 最大值 最小值
Int8 1 127 -128
Int16 2 32767 -32768
Int32 4 2147483647 -2147483648
Int64 8 9223372036854775807 -9223372036854775808
UInt8 1 255 0
UInt16 2 65535 0
UInt32 4 4294967295 0
UInt64 8 18446744073709551615 0
类型 字节长度
utf8 参考 Byte Counter

完整示例

以下是使用 ble_data_converter 插件的完整示例:

import 'package:ble_data_converter/ble_data_converter.dart';

void main() {
  tryConverter();
}

void tryConverter() {
  List<int> body = [];

  // ID (i16)
  const sampleID = 0x0200;
  final sampleData = BLEDataConverter.i16.intToBytes(sampleID).reversed.toList();
  body.addAll(sampleData);

  // 请求ID (i8)
  const requestId = 255;
  final requestData = BLEDataConverter.i8.intToBytes(requestId);
  body.addAll(requestData);

  // 随机字符串 (utf8)
  const randomStr = "sample";
  final strData = BLEDataConverter.str.stringToUtf8(randomStr);
  body.addAll(strData);

  // 时间戳 (i64)
  final milSeconds = DateTime.now().millisecondsSinceEpoch;
  // 将毫秒转换为秒
  final seconds = milSeconds ~/ 1000;

  final timestampData = BLEDataConverter.i64.intToBytes(seconds).reversed.toList();
  body.addAll(timestampData);

  // 打印时间戳字节
  print(_bytesToDateTime(timestampData));

  // 随机数字 (i16)
  const fizzType = 32769;
  final fizzData = BLEDataConverter.i16.intToBytes(fizzType).reversed.toList();
  body.addAll(fizzData);

  // 打印最终的字节数据
  print(body); // [2, 0, 255, 97, 100, 102, 0, 0, 1, 134, 33, 13, 184, 13, 128, 1]
  print(body.length); // 16
}

// 秒数转日期时间
DateTime _bytesToDateTime(List<int> bytes) {
  final intValue = BLEDataConverter.i64.bytesToInt(bytes.reversed.toList());
  return DateTime.fromMillisecondsSinceEpoch(intValue * 1000);
}

更多关于Flutter蓝牙数据转换插件ble_data_converter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙数据转换插件ble_data_converter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用ble_data_converter插件来处理蓝牙数据转换的一个基本示例。这个插件假设能帮助你将从蓝牙设备接收到的原始数据转换为更有用的格式。

首先,确保你已经在pubspec.yaml文件中添加了ble_data_converter依赖:

dependencies:
  flutter:
    sdk: flutter
  ble_data_converter: ^x.y.z  # 替换为最新版本号

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

示例代码

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:flutter_reactive_ble/flutter_reactive_ble.dart';
import 'package:ble_data_converter/ble_data_converter.dart';

注意:flutter_reactive_ble是一个常用的蓝牙库,用于与蓝牙设备进行通信。在这个示例中,我们假设你已经使用它建立了与蓝牙设备的连接并接收到了数据。

  1. 创建一个简单的数据转换函数

假设你有一个特定的数据格式需要从蓝牙设备接收并转换,比如一个包含温度数据的字节数组。

class BleDataProcessor {
  static double convertTemperatureData(Uint8List data) {
    // 假设温度数据在字节数组的第一个字节,并且需要转换为摄氏度
    // 这只是一个示例,实际转换逻辑可能不同
    int rawValue = data[0];
    // 假设我们有一个简单的线性转换,比如 rawValue = 100 表示 25.0°C
    double temperature = (rawValue - 100.0) / 4.0; // 示例转换公式
    return temperature;
  }
}

然而,如果你使用ble_data_converter库,可能会有一些预定义的转换方法或者更复杂的逻辑。假设ble_data_converter有一个方法convertTemperature可以直接使用:

class BleDataProcessor {
  static double convertTemperatureData(Uint8List data) {
    // 使用ble_data_converter库的方法
    return BleDataConverter.convertTemperature(data); // 假设此方法存在
  }
}

注意:上面的BleDataConverter.convertTemperature方法是一个假设的方法,具体使用哪个方法需要参考ble_data_converter的文档。

  1. 接收并处理蓝牙数据
class BluetoothPage extends StatefulWidget {
  @override
  _BluetoothPageState createState() => _BluetoothPageState();
}

class _BluetoothPageState extends State<BluetoothPage> {
  final FlutterReactiveBle flutterReactiveBle = FlutterReactiveBle();
  
  @override
  void initState() {
    super.initState();
    // 假设你已经建立了连接并订阅了特征值
    connectAndSubscribeToDevice();
  }

  void connectAndSubscribeToDevice() async {
    // 连接设备的代码(省略)
    // ...

    // 订阅特征值的通知
    flutterReactiveBle
      .subscribeToCharacteristic(
        deviceId: 'your-device-id',
        serviceUuid: 'your-service-uuid',
        characteristicUuid: 'your-characteristic-uuid',
      )
      .listen((characteristic) {
        Uint8List data = characteristic.value;
        double temperature = BleDataProcessor.convertTemperatureData(data);

        // 更新UI或处理数据
        setState(() {
          // 例如,更新一个显示温度的Text组件
        });
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Bluetooth Data')),
      body: Center(
        // 显示温度或其他数据的组件
        // 例如:Text('Temperature: ${temperature.toStringAsFixed(1)}°C')
      ),
    );
  }
}

在这个示例中,我们假设你已经成功连接到了一个蓝牙设备,并且订阅了某个特征值的通知。当特征值的数据发生变化时,我们接收数据并使用BleDataProcessor中的方法将其转换为温度值,然后更新UI来显示这个温度。

注意:具体的蓝牙连接和特征值订阅代码没有在这个示例中详细展开,因为这通常涉及到更多的错误处理和设备管理逻辑。请参考flutter_reactive_ble的文档来了解如何连接设备和订阅特征值。

希望这个示例能帮助你理解如何在Flutter项目中使用ble_data_converter插件来处理蓝牙数据转换。

回到顶部