Flutter蓝牙后端管理插件ble_backend_factory的使用

Flutter蓝牙后端管理插件ble_backend_factory的使用

BLE backend factory 的简介

ble_backend_factory 是一个用于管理蓝牙后端的 Flutter 插件。它提供了创建和操作蓝牙设备的核心功能,包括扫描设备、连接设备、读写特征值等。


使用方法

首先,你需要通过 createCentral() 方法创建一个中央设备实例,该实例将作为蓝牙操作的入口点。

final bleCentral = createCentral();

完整示例代码

以下是一个完整的示例代码,展示了如何使用 ble_backend_factory 插件来实现蓝牙设备的扫描、连接、读写操作等。

示例代码

import 'package:ble_backend/ble_central.dart';
import 'package:ble_backend/ble_connector.dart';
import 'package:ble_backend/utils/converters.dart';
import 'package:ble_backend_factory/ble_central.dart';

// 定义服务和特征值的 UUID
const serviceId = "dac890c2-35a1-11ef-aba0-9b95565f4ffb";
const rxCharacteristicId = "dac89194-35a1-11ef-aba1-b37714ad9a54";
const txCharacteristicId = "dac89266-35a1-11ef-aba2-0f0127bce478";
const characteristicId = "dac89338-35a1-11ef-aba3-8746a2fdea8c";

// 等待条件满足的辅助函数
Future<void> wait(bool Function() predicate) async {
  for (int i = 0; i < 10; i++) {
    await Future.delayed(const Duration(milliseconds: 100));
    if (predicate()) return;
  }
}

void main() async {
  // 创建蓝牙中央设备实例
  print("中央设备状态: ${bleCentral.state}");
  bleCentral.stateStream.listen((state) => print("中央设备状态改变: $state"));

  // 等待蓝牙状态变为非未知状态
  await wait(() => bleCentral.state != BleCentralStatus.unknown);
  if (bleCentral.state != BleCentralStatus.ready) {
    print("蓝牙未准备好");
    return;
  }

  // 创建扫描器并开始扫描
  final bleScanner = bleCentral.createScanner(serviceIds: [serviceId]);
  bleScanner.stateStream.listen((state) => print("扫描状态: ${state.isScanInProgress}"));
  await bleScanner.scan();
  await Future.delayed(const Duration(seconds: 1));
  await bleScanner.stop();

  // 检查是否找到设备
  if (bleScanner.state.devices.isEmpty) {
    print("未找到设备");
    return;
  }

  // 获取第一个扫描到的设备
  final blePeripheral = bleScanner.state.devices.first;
  print("设备 ID: ${blePeripheral.id}");
  print("设备名称: ${blePeripheral.name}");
  print("设备信号强度: ${blePeripheral.rssi}");

  // 创建连接器并连接设备
  final bleConnector = blePeripheral.createConnector();
  print("连接器状态: ${bleConnector.state}");
  bleConnector.stateStream.listen((state) => print("连接器状态改变: $state"));
  await bleConnector.connect();

  // 等待连接完成
  await wait(() => bleConnector.state == BleConnectorStatus.connected);
  if (bleConnector.state != BleConnectorStatus.connected) {
    print("设备未成功连接");
    return;
  }

  // 请求最大传输单元(MTU)
  final bleMtu = bleConnector.createMtu();
  if (bleMtu.isRequestSupported) {
    print("请求的 MTU 大小: ${await bleMtu.request(mtu: 128)}");
  }

  // 创建特征值并读取数据
  final bleCharacteristic = bleConnector.createCharacteristic(
      serviceId: serviceId, characteristicId: characteristicId);
  bleCharacteristic.dataStream.listen((data) => print("特征值数据改变: $data"));
  await bleCharacteristic.startNotifications();
  print("特征值数据: ${await bleCharacteristic.read()}");
  await bleCharacteristic.write(data: uint8ToBytes(1));
  await bleCharacteristic.writeWithoutResponse(data: uint8ToBytes(2));
  await bleCharacteristic.stopNotifications();

  // 创建串行通信接口
  final bleSerial = bleConnector.createSerial(
      serviceId: serviceId,
      rxCharacteristicId: rxCharacteristicId,
      txCharacteristicId: txCharacteristicId);
  bleSerial.dataStream.listen((data) => print("串行数据接收: $data"));
  await bleSerial.startNotifications();
  await bleSerial.send(data: uint8ToBytes(3));
  bleSerial.waitData(timeoutCallback: () => print("串行数据未接收到"));
  await Future.delayed(const Duration(milliseconds: 100));
  await bleSerial.stopNotifications();

  // 断开连接
  await bleConnector.disconnect();
}

更多关于Flutter蓝牙后端管理插件ble_backend_factory的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter蓝牙后端管理插件ble_backend_factory的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


ble_backend_factory 是一个用于 Flutter 的蓝牙后端管理插件,它可以帮助开发者更方便地管理蓝牙设备的连接、数据传输等操作。以下是如何使用 ble_backend_factory 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  ble_backend_factory: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入插件

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

import 'package:ble_backend_factory/ble_backend_factory.dart';

3. 初始化蓝牙后端

在使用蓝牙功能之前,你需要初始化蓝牙后端:

BleBackendFactory bleBackend = BleBackendFactory();
await bleBackend.initialize();

4. 扫描蓝牙设备

你可以使用 scanForDevices 方法来扫描附近的蓝牙设备:

List<BluetoothDevice> devices = await bleBackend.scanForDevices();
for (var device in devices) {
  print('Found device: ${device.name} - ${device.id}');
}

5. 连接蓝牙设备

选择要连接的设备后,你可以使用 connectToDevice 方法来连接设备:

BluetoothDevice selectedDevice = devices[0]; // 选择第一个设备
await bleBackend.connectToDevice(selectedDevice);

6. 发送和接收数据

连接成功后,你可以使用 writeCharacteristicreadCharacteristic 方法来发送和接收数据:

// 发送数据
await bleBackend.writeCharacteristic(characteristicId, data);

// 接收数据
List<int> receivedData = await bleBackend.readCharacteristic(characteristicId);

7. 断开连接

当你不再需要连接时,可以断开与设备的连接:

await bleBackend.disconnectFromDevice(selectedDevice);

8. 释放资源

在应用退出或不再需要蓝牙功能时,记得释放资源:

await bleBackend.dispose();

示例代码

以下是一个完整的示例代码,展示了如何使用 ble_backend_factory 插件进行蓝牙设备的扫描、连接和数据传输:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  BleBackendFactory bleBackend = BleBackendFactory();
  await bleBackend.initialize();

  runApp(MyApp(bleBackend: bleBackend));
}

class MyApp extends StatelessWidget {
  final BleBackendFactory bleBackend;

  MyApp({required this.bleBackend});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BluetoothScreen(bleBackend: bleBackend),
    );
  }
}

class BluetoothScreen extends StatefulWidget {
  final BleBackendFactory bleBackend;

  BluetoothScreen({required this.bleBackend});

  [@override](/user/override)
  _BluetoothScreenState createState() => _BluetoothScreenState();
}

class _BluetoothScreenState extends State<BluetoothScreen> {
  List<BluetoothDevice> devices = [];
  BluetoothDevice? connectedDevice;

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

  Future<void> _scanForDevices() async {
    devices = await widget.bleBackend.scanForDevices();
    setState(() {});
  }

  Future<void> _connectToDevice(BluetoothDevice device) async {
    await widget.bleBackend.connectToDevice(device);
    setState(() {
      connectedDevice = device;
    });
  }

  Future<void> _sendData() async {
    if (connectedDevice != null) {
      await widget.bleBackend.writeCharacteristic('characteristicId', [0x01, 0x02]);
    }
  }

  Future<void> _disconnectDevice() async {
    if (connectedDevice != null) {
      await widget.bleBackend.disconnectFromDevice(connectedDevice!);
      setState(() {
        connectedDevice = null;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Example'),
      ),
      body: ListView.builder(
        itemCount: devices.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(devices[index].name),
            subtitle: Text(devices[index].id),
            onTap: () => _connectToDevice(devices[index]),
          );
        },
      ),
      floatingActionButton: connectedDevice != null
          ? Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                FloatingActionButton(
                  onPressed: _sendData,
                  child: Icon(Icons.send),
                ),
                SizedBox(height: 10),
                FloatingActionButton(
                  onPressed: _disconnectDevice,
                  child: Icon(Icons.bluetooth_disabled),
                ),
              ],
            )
          : null,
    );
  }
}
回到顶部