使用 flutter_blue_plus 连接蓝牙

发布于:2025-03-29 ⋅ 阅读:(122) ⋅ 点赞:(0)

1. 介绍

Flutter Blue Plus 是一个用于 Flutter 的 Bluetooth Low Energy (BLE) 插件,简化了 Flutter 应用程序中的 BLE 开发。它支持跨平台(iOS、Android 和 macOS),提供了丰富的 API,用于扫描、连接、发现服务和特征、读写数据、订阅通知等

https://pub.dev/packages/flutter_blue_plus

2. 安装和配置

pubspec.yaml 文件中添加 flutter_blue_plus 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_blue_plus: ^1.35.3

然后运行以下命令安装依赖:

flutter pub get

3. 平台特定权限

Android:在 AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

iOS:在 Info.plist 文件中添加以下描述:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>This app needs access to Bluetooth to function properly.</string>

4. 基本使用案例

基本案例,包括扫描设备、连接设备、发现服务和特征、读取和写入特征值等操作

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

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

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

class BluetoothScanner extends StatefulWidget {
  
  _BluetoothScannerState createState() => _BluetoothScannerState();
}

class _BluetoothScannerState extends State<BluetoothScanner> {
  FlutterBluePlus flutterBlue = FlutterBluePlus.instance;
  List<BluetoothDevice> lstDevices = [];

  
  void initState() {
    super.initState();
    startScanning();
  }

  void startScanning() async {
    await flutterBlue.startScan();
    flutterBlue.scanResults.listen((results) {
      for (ScanResult result in results) {
        if (!lstDevices.contains(result.device)) {
          setState(() {
            lstDevices.add(result.device);
          });
        }
      }
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BLE Scanner'),
      ),
      body: ListView.builder(
        itemCount: lstDevices.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(lstDevices[index].name),
            subtitle: Text(lstDevices[index].id.toString()),
            onTap: () {
              // 点击连接蓝牙
              connectToDevice(lstDevices[index]);
            },
          );
        },
      ),
    );
  }

  Future<void> connectToDevice(BluetoothDevice device) async {
    await device.connect();
    // 在这里可以进一步发现服务和特征
    List<BluetoothService> services = await device.discoverServices();
    services.forEach((service) {
      // 处理服务和特征
      handleService(service);
    });
  }

  void handleService(BluetoothService service) async {
    // 遍历服务中的特征
    for (BluetoothCharacteristic characteristic in service.characteristics) {
      // 读取特征值
      List<int> value = await characteristic.read();
      print('Characteristic value: $value');

      // 写入特征值(示例)
      if (characteristic.uuid.toString() == 'your_characteristic_uuid') {
        await characteristic.write([0x12, 0x34]);
        print('Characteristic written successfully');
      }

      // 设置通知并监听特征值变化
      await characteristic.setNotifyValue(true);
      characteristic.value.listen((value) {
        print('Notification received: $value');
      });
    }
  }

  
  void dispose() {
    flutterBlue.stopScan();
    super.dispose();
  }
}

通过上述代码,你可以扫描附近的 BLE 设备,连接到设备,发现其服务和特征,并进行读写操作以及订阅通知。

代码说明

  1. 扫描设备:
    • 使用 flutterBlue.startScan() 开始扫描附近的 BLE 设备。
    • 通过监听 flutterBlue.scanResults 获取扫描结果,并将其添加到 lstDevices 列表中。
  2. 连接设备:
    • 点击列表项时,调用 connectToDevice 方法连接到设备。
    • 使用 device.connect() 建立连接。
  3. 发现服务和特征:
    • 连接成功后,调用 device.discoverServices() 发现设备提供的服务。
    • 遍历服务中的特征,读取特征值。
  4. 读取和写入特征值:
    • 使用 characteristic.read() 读取特征值。
    • 使用 characteristic.write() 写入特征值。
  5. 设置通知并监听特征值变化:
    • 使用 characteristic.setNotifyValue(true) 启用通知。
    • 监听 characteristic.value 流,接收特征值变化的通知。

注意事项:

  • 在实际应用中,需要根据具体设备的 UUID 来访问特定的服务和特征。
  • 确保在 Info.plist 和 AndroidManifest.xml 文件中添加了必要的蓝牙权限。
  • 不同的 BLE 设备可能有不同的服务和特征 UUID,需要参考设备的文档来确定正确的 UUID。

网站公告

今日签到

点亮在社区的每一天
去签到