Flutter蓝牙通信插件brilliant_ble的使用
Flutter蓝牙通信插件brilliant_ble的使用
概述
BrilliantBle 是一个由 brilliant Labs 提供的 Flutter 插件,用于连接到 BLE 设备。它依赖于 flutter_blue_plus
包来连接到 BLE 设备。
dependencies:
brilliant_ble: ^0.0.3
或者通过命令行添加:
flutter pub add brilliant_ble
然后运行 flutter pub get
来安装包。
对于 Android
flutter_blue_plus
只从 Android SDK 版本 21 开始兼容,因此需要在 android/app/build.gradle
文件中进行更改:
android {
defaultConfig {
minSdkVersion: 21
}
}
还需在 AndroidManifest.xml
文件中添加以下权限:
<!-- 告诉 Google Play Store 你的应用使用了 Bluetooth LE -->
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
<!-- Android 12 新的 Bluetooth 权限 -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!-- 对于 Android 11 或更低版本的兼容性 -->
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>
<!-- 对于 Android 9 或更低版本的兼容性 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28" />
对于 iOS
需要在 Info.plist
文件中添加以下权限:
<dict>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>This app always needs Bluetooth to function</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>This app needs Bluetooth Peripheral to function</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app always needs location and when in use to function</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app always needs location to function</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs location when in use to function</string>
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
</dict>
使用示例
初始化
首先初始化并设置连接状态监听器:
ble = await BrilliantBle.create();
ble.onConnected = () {
print("connected");
};
ble.onDisconnected = () {
print("Disconnected");
};
ble.onData = (data) {
// 数据从设备接收
print(String.fromCharCodes(data));
};
await ble.setup();
连接设备
自动连接
自动连接到第一个扫描到的设备:
await ble.connectToFirstDevice();
手动连接
手动扫描并连接到设备:
await ble.scan();
var devices = ble.devices;
for (var d in devices) {
print(d.advName);
}
// 连接到第一个设备
var device = await ble.connect(devices.first);
发送和接收数据
发送数据到设备,并等待响应:
var response = await ble.sendData("print('hello world')\n\r");
print(response); // 输出: hello world
发送数据到设备而不等待响应:
await ble.sendData("print('hello world')\n\r", wait: false);
上传文件到设备:
await ble.uploadFile("file.txt", "file content");
检查连接状态
检查当前是否已连接到设备:
var status = await ble.isConnected();
print(status); // 输出: true 或 false
断开连接
断开与设备的连接:
await ble.disconnect();
获取连接设备名称
获取当前连接设备的名称:
var name = await ble.device.advName();
print(name); // 输出: monocle/frame
更多关于Flutter蓝牙通信插件brilliant_ble的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙通信插件brilliant_ble的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
brilliant_ble
是一个用于 Flutter 的蓝牙通信插件,它提供了简单易用的 API 来执行蓝牙设备扫描、连接、读写等操作。以下是如何使用 brilliant_ble
插件进行蓝牙通信的基本步骤。
1. 添加依赖
首先,在 pubspec.yaml
文件中添加 brilliant_ble
插件的依赖:
dependencies:
flutter:
sdk: flutter
brilliant_ble: ^0.0.1 # 请使用最新版本
然后运行 flutter pub get
来获取依赖。
2. 初始化插件
在你的 Dart 文件中导入 brilliant_ble
插件并初始化它:
import 'package:brilliant_ble/brilliant_ble.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
BrilliantBle.initialize();
runApp(MyApp());
}
3. 扫描蓝牙设备
使用 BrilliantBle
的 startScan
方法来扫描附近的蓝牙设备:
void scanDevices() async {
try {
await BrilliantBle.startScan();
BrilliantBle.scanResults.listen((devices) {
for (var device in devices) {
print('Found device: ${device.name}, ${device.id}');
}
});
} catch (e) {
print('Error scanning devices: $e');
}
}
4. 连接蓝牙设备
使用 BrilliantBle
的 connect
方法来连接指定的蓝牙设备:
void connectToDevice(String deviceId) async {
try {
await BrilliantBle.connect(deviceId);
print('Connected to device: $deviceId');
} catch (e) {
print('Error connecting to device: $e');
}
}
5. 读写数据
一旦连接到设备,你可以使用 BrilliantBle
的 read
和 write
方法来读写数据:
void readData(String characteristicId) async {
try {
var data = await BrilliantBle.read(characteristicId);
print('Read data: $data');
} catch (e) {
print('Error reading data: $e');
}
}
void writeData(String characteristicId, List<int> data) async {
try {
await BrilliantBle.write(characteristicId, data);
print('Data written successfully');
} catch (e) {
print('Error writing data: $e');
}
}
6. 断开连接
使用 BrilliantBle
的 disconnect
方法来断开与设备的连接:
void disconnectDevice(String deviceId) async {
try {
await BrilliantBle.disconnect(deviceId);
print('Disconnected from device: $deviceId');
} catch (e) {
print('Error disconnecting from device: $e');
}
}
7. 停止扫描
使用 BrilliantBle
的 stopScan
方法来停止扫描:
void stopScanning() async {
try {
await BrilliantBle.stopScan();
print('Scanning stopped');
} catch (e) {
print('Error stopping scan: $e');
}
}
8. 处理权限
在 Android 和 iOS 上,蓝牙操作需要特定的权限。确保你在 AndroidManifest.xml
和 Info.plist
文件中添加了必要的权限。
9. 处理错误
在实际应用中,确保你处理了所有可能的错误,并在必要时向用户显示错误信息。
10. 示例应用
以下是一个简单的示例应用,展示了如何使用 brilliant_ble
插件:
import 'package:flutter/material.dart';
import 'package:brilliant_ble/brilliant_ble.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
BrilliantBle.initialize();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: BluetoothScreen(),
);
}
}
class BluetoothScreen extends StatefulWidget {
[@override](/user/override)
_BluetoothScreenState createState() => _BluetoothScreenState();
}
class _BluetoothScreenState extends State<BluetoothScreen> {
List<BluetoothDevice> devices = [];
[@override](/user/override)
void initState() {
super.initState();
scanDevices();
}
void scanDevices() async {
try {
await BrilliantBle.startScan();
BrilliantBle.scanResults.listen((devices) {
setState(() {
this.devices = devices;
});
});
} catch (e) {
print('Error scanning devices: $e');
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bluetooth Devices'),
),
body: ListView.builder(
itemCount: devices.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(devices[index].name ?? 'Unknown'),
subtitle: Text(devices[index].id),
onTap: () => connectToDevice(devices[index].id),
);
},
),
);
}
void connectToDevice(String deviceId) async {
try {
await BrilliantBle.connect(deviceId);
print('Connected to device: $deviceId');
} catch (e) {
print('Error connecting to device: $e');
}
}
}