Flutter蓝牙通信插件blev的使用

Flutter蓝牙通信插件blev的使用

本插件提供了以下功能:

  • 中央设备

    • 发现外设及其服务和特征
      • 读取特征值
      • 连接到外设
      • 建立通过已发现或已知PSM的L2CAP COC连接。
      • 将多个L2CAP COC多路复用到套接字。
  • 外设

    • 广播只读字符串类型的服务和特征
      • 发布L2CAP COC连接。
      • 将多个L2CAP COC多路复用到套接字。

开始前的准备

确保您的项目满足以下最低要求:

  • 最低iOS目标版本:13.0
  • 最低Android SDK版本:29
  • Kotlin版本:1.7.10

安装

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

dependencies:
  blev: ^x.x.x

然后运行以下命令安装:

flutter pub get

升级

要升级插件,请运行:

flutter pub upgrade blev

iOS权限配置

如果您正在构建适用于Apple平台的应用程序,您可能需要更新应用的Info.plist文件。需要添加NSBluetoothAlwaysUsageDescription以利用蓝牙功能。

Info.plist中添加以下内容:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>需要蓝牙权限以便应用能够正常工作。</string>

Android权限配置

请参阅Android蓝牙权限文档了解如何正确声明和请求权限。

使用和示例应用程序

查看示例应用程序以学习如何最好地使用该插件。示例目录位于这里。示例包括两个组合示例:

  • 中央设备外设

    • 演示中央设备和外设通过L2CAP通道发送消息。
  • 中央设备客户端外设服务器

    • 演示中央设备和外设作为客户端和服务器进行SOCKS5上的HTTP通信。

示例代码

以下是一个简单的示例代码,演示如何使用blev插件实现中央设备与外设之间的通信。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('BLEV Example')),
        body: CentralPage(),
      ),
    );
  }
}

class CentralPage extends StatefulWidget {
  [@override](/user/override)
  _CentralPageState createState() => _CentralPageState();
}

class _CentralPageState extends State<CentralPage> {
  Blev blev = Blev();

  [@override](/user/override)
  void initState() {
    super.initState();
    // 初始化蓝牙库
    blev.init();
  }

  [@override](/user/override)
  void dispose() {
    super.dispose();
    // 释放资源
    blev.dispose();
  }

  Future<void> connectToPeripheral() async {
    // 扫描并连接到外设
    await blev.scanAndConnect();
    // 读取外设的特征值
    final value = await blev.readValueFromCharacteristic();
    print('读取到的特征值: $value');
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: () {
          connectToPeripheral();
        },
        child: Text('连接到外设'),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用blev插件进行蓝牙通信的示例代码。blev是一个用于Flutter的蓝牙低功耗(BLE)库,它提供了一套简洁的API来扫描设备、连接设备、读写特性(Characteristics)等。

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

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

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

接下来是一个简单的示例代码,展示如何使用blev插件扫描设备、连接到设备并读取某个特性的值。

示例代码

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  BlevClient? _blevClient;
  List<BlevDevice> _scannedDevices = [];
  BlevDevice? _connectedDevice;
  String _data = '';

  @override
  void initState() {
    super.initState();
    initBle();
  }

  Future<void> initBle() async {
    _blevClient = await BlevClient.create();
    _blevClient!.scanResultsStream.listen((scanResults) {
      setState(() {
        _scannedDevices = scanResults;
      });
    });
  }

  Future<void> connectToDevice(BlevDevice device) async {
    if (_blevClient!.isConnected(device.id)) {
      print('Already connected to ${device.name}');
      return;
    }

    await _blevClient!.connect(device.id);
    setState(() {
      _connectedDevice = device;
    });

    // Discover services and characteristics (optional but recommended)
    await _blevClient!.discoverServices(device.id);

    // Assuming we know the service UUID and characteristic UUID we want to read
    final serviceUuid = 'your-service-uuid';
    final characteristicUuid = 'your-characteristic-uuid';

    // Read characteristic value
    final characteristic = _blevClient!.getCharacteristic(device.id, serviceUuid, characteristicUuid);
    final value = await characteristic!.readValue();
    setState(() {
      _data = utf8.decode(value);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter BLE Communication'),
        ),
        body: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: _scannedDevices.length,
                itemBuilder: (context, index) {
                  final device = _scannedDevices[index];
                  return ListTile(
                    title: Text(device.name ?? 'Unknown Device'),
                    subtitle: Text(device.id),
                    onTap: () => connectToDevice(device),
                  );
                },
              ),
            ),
            if (_connectedDevice != null)
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text('Connected Device: ${_connectedDevice!.name ?? 'Unknown Device'}\nData: $_data'),
              ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _blevClient?.close();
    super.dispose();
  }
}

注意事项

  1. UUIDs:在示例代码中,serviceUuidcharacteristicUuid需要替换为你实际使用的服务的UUID和特性的UUID。
  2. 权限:确保在AndroidManifest.xmlInfo.plist中添加了必要的蓝牙权限。
  3. 错误处理:在实际应用中,添加适当的错误处理逻辑,如处理连接失败、读取失败等情况。
  4. 设备兼容性:不同的设备可能对BLE特性的支持有所不同,确保你的代码能够处理这些差异。

这个示例代码提供了一个基本的框架,展示了如何使用blev插件在Flutter应用中进行蓝牙通信。根据你的具体需求,你可能需要扩展或修改这个示例。

回到顶部