Flutter低功耗蓝牙通信插件bluetooth_low_energy_backend的使用

Flutter低功耗蓝牙通信插件bluetooth_low_energy_backend的使用

在Flutter开发中,bluetooth_low_energy_backend 插件可以帮助开发者实现低功耗蓝牙(BLE)设备的通信功能。以下是一个完整的示例,展示如何使用该插件进行 BLE 设备的扫描、连接和数据交互。

使用步骤

首先,确保你已经在 pubspec.yaml 文件中添加了 bluetooth_low_energy_backend 插件:

dependencies:
  bluetooth_low_energy_backend: ^版本号

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

接下来,我们通过一个完整的示例来展示如何使用该插件。


完整示例代码

以下代码展示了如何使用 bluetooth_low_energy_backend 插件扫描附近的 BLE 设备,并与其中一个设备建立连接,发送和接收数据。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BLEExample(),
    );
  }
}

class BLEExample extends StatefulWidget {
  @override
  _BLEExampleState createState() => _BLEExampleState();
}

class _BLEExampleState extends State<BLEExample> {
  final bleCentral = BluetoothLowEnergyCentral(backend: CentralManager());

  List<String> scannedDevices = [];

  @override
  void initState() {
    super.initState();
    // 初始化时开始扫描设备
    scanDevices();
  }

  Future<void> scanDevices() async {
    // 开始扫描 BLE 设备
    await bleCentral.startScan(timeout: Duration(seconds: 10));
    // 获取扫描到的设备列表
    final devices = bleCentral.getDiscoveredDevices();
    setState(() {
      scannedDevices = devices.map((device) => device.name).toList();
    });
  }

  Future<void> connectToDevice(String deviceId) async {
    // 连接到指定的设备
    final connectedDevice = await bleCentral.connect(deviceId);
    if (connectedDevice != null) {
      // 发送数据到设备
      await connectedDevice.writeValue(Uint8List.fromList([0x01, 0x02, 0x03]));
      // 接收设备返回的数据
      Uint8List response = await connectedDevice.readValue();
      print('Received data from device: $response');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BLE Communication Example'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: scannedDevices.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(scannedDevices[index]),
                  onTap: () {
                    // 点击设备名称,尝试连接
                    connectToDevice(scannedDevices[index]);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    // 停止扫描并释放资源
    bleCentral.stopScan();
    super.dispose();
  }
}

示例说明

  1. 初始化 BLE 中央管理器

    final bleCentral = BluetoothLowEnergyCentral(backend: CentralManager());
    

    创建一个 BluetoothLowEnergyCentral 实例,用于管理 BLE 操作。

  2. 扫描 BLE 设备

    await bleCentral.startScan(timeout: Duration(seconds: 10));
    final devices = bleCentral.getDiscoveredDevices();
    

    调用 startScan 方法开始扫描设备,并在超时后获取扫描到的设备列表。

  3. 连接到设备

    final connectedDevice = await bleCentral.connect(deviceId);
    

    使用设备的唯一标识符 (deviceId) 进行连接。

  4. 发送和接收数据

    await connectedDevice.writeValue(Uint8List.fromList([0x01, 0x02, 0x03]));
    Uint8List response = await connectedDevice.readValue();
    

    向设备写入数据并读取设备返回的数据。

  5. 释放资源: 在页面销毁时停止扫描并释放资源:

    bleCentral.stopScan();
    

更多关于Flutter低功耗蓝牙通信插件bluetooth_low_energy_backend的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter低功耗蓝牙通信插件bluetooth_low_energy_backend的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


bluetooth_low_energy_backend 是一个用于在 Flutter 应用中实现低功耗蓝牙(BLE)通信的插件。它提供了与 BLE 设备进行通信的接口,支持扫描、连接、读写特征值等操作。以下是如何使用 bluetooth_low_energy_backend 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  bluetooth_low_energy_backend: ^0.1.0  # 请检查最新版本

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

2. 初始化插件

在你的 Dart 文件中导入插件并初始化:

import 'package:bluetooth_low_energy_backend/bluetooth_low_energy_backend.dart';

final bluetoothLE = BluetoothLowEnergyBackend();

3. 检查蓝牙状态

在开始使用 BLE 功能之前,检查设备的蓝牙状态:

Future<void> checkBluetoothState() async {
  final state = await bluetoothLE.state;
  if (state == BluetoothState.on) {
    print("Bluetooth is on");
  } else {
    print("Bluetooth is off");
  }
}

4. 扫描设备

使用 startScan 方法开始扫描附近的 BLE 设备:

void startScanning() {
  bluetoothLE.startScan().listen((scanResult) {
    print('Found device: ${scanResult.device.name}');
  });
}

5. 停止扫描

使用 stopScan 方法停止扫描:

void stopScanning() {
  bluetoothLE.stopScan();
}

6. 连接设备

使用 connect 方法连接到指定的 BLE 设备:

void connectToDevice(BluetoothDevice device) async {
  await bluetoothLE.connect(device);
  print('Connected to device: ${device.name}');
}

7. 发现服务

连接成功后,发现设备提供的服务:

void discoverServices(BluetoothDevice device) async {
  final services = await bluetoothLE.discoverServices(device);
  for (var service in services) {
    print('Service: ${service.uuid}');
  }
}

8. 读写特征值

发现服务后,可以读取或写入特征值:

void readCharacteristic(BluetoothCharacteristic characteristic) async {
  final value = await bluetoothLE.readCharacteristic(characteristic);
  print('Characteristic value: $value');
}

void writeCharacteristic(BluetoothCharacteristic characteristic, List<int> value) async {
  await bluetoothLE.writeCharacteristic(characteristic, value);
  print('Characteristic value written');
}

9. 断开连接

使用 disconnect 方法断开与设备的连接:

void disconnectDevice(BluetoothDevice device) async {
  await bluetoothLE.disconnect(device);
  print('Disconnected from device: ${device.name}');
}

10. 处理权限

在 Android 上,使用 BLE 功能需要获取位置权限。确保在 AndroidManifest.xml 中添加以下权限:

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

并在运行时请求权限:

import 'package:permission_handler/permission_handler.dart';

Future<void> requestPermissions() async {
  if (await Permission.location.isDenied) {
    await Permission.location.request();
  }
}

11. 处理错误

在使用 BLE 功能时,可能会遇到各种错误,确保在代码中处理这些错误:

try {
  await bluetoothLE.connect(device);
} catch (e) {
  print('Failed to connect: $e');
}

12. 释放资源

在应用退出时,释放 BLE 相关的资源:

void dispose() {
  bluetoothLE.dispose();
}
回到顶部