Flutter蓝牙通信插件gatt的使用
Flutter蓝牙通信插件gatt的使用
GATT (通用属性配置文件) 是蓝牙低功耗通信的核心信息协议。此包提供了用于GATT ID的结构化表示,这些ID用于标识服务、特征和描述符。此包还包含许多SIG GATT ID,方便在BLE代码中引用。
使用方法
引用现有的SIG GATT ID或定义自己的ID。
import 'package:gatt/gatt.dart';
// 引用官方SIG ID:
print(batteryLevelCharacteristicId);
// 使用前16位或32位UUID构造一个SIG ID:
print(const SigGattId(0x1234));
// 构造一个自定义的GATT ID:
print(const GattId(0x1234, '-0000-1111-2222-3456789ABCDE'));
// 获取前32位作为整数:
print(const GattId(0x1234, '-0000-1111-2222-3456789ABCDE').leadingHexInt);
// 打印0x1234的整数形式
// 获取前32位作为十六进制字符串:
print(const GattId(0x1234, '-0000-1111-2222-3456789ABCDE').asUuid4Bytes);
// 打印 "0001234"
// 获取前32位的后16位作为十六进制字符串:
print(const GattId(0x1234, '-0000-1111-2222-3456789ABCDE').asUuid2Bytes);
// 打印 "1234"
贡献指南
请遵循标准的贡献指南。
学习更多
以下是一个完整的示例Demo,演示了如何使用Flutter蓝牙通信插件gatt进行蓝牙设备连接和数据读写操作:
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Bluetooth GATT Demo')),
body: Center(child: BlePage()),
),
);
}
}
class BlePage extends StatefulWidget {
[@override](/user/override)
_BlePageState createState() => _BlePageState();
}
class _BlePageState extends State<BlePage> {
FlutterBlue flutterBlue = FlutterBlue.instance;
BluetoothDevice? device;
BluetoothService? service;
BluetoothCharacteristic? characteristic;
[@override](/user/override)
void initState() {
super.initState();
startScan();
}
void startScan() async {
flutterBlue.startScan(timeout: Duration(seconds: 4));
flutterBlue.scanResults.listen((results) {
for (var result in results) {
if (result.device.name == 'Your Device Name') {
stopScan(result.device);
}
}
});
}
void stopScan(BluetoothDevice device) {
flutterBlue.stopScan();
setState(() {
this.device = device;
connectToDevice(device);
});
}
void connectToDevice(BluetoothDevice device) async {
await device.connect();
discoverServices(device);
}
void discoverServices(BluetoothDevice device) async {
List<BluetoothService> services = await device.discoverServices();
for (BluetoothService service in services) {
if (service.uuid.toString().toLowerCase() == 'your-service-uuid') {
setState(() {
this.service = service;
readCharacteristic(service);
});
}
}
}
void readCharacteristic(BluetoothService service) async {
List<BluetoothCharacteristic> characteristics =
service.characteristics;
for (BluetoothCharacteristic characteristic in characteristics) {
if (characteristic.uuid.toString().toLowerCase() == 'your-characteristic-uuid') {
setState(() {
this.characteristic = characteristic;
readValue(characteristic);
});
}
}
}
void readValue(BluetoothCharacteristic characteristic) async {
List<int> value = await characteristic.read();
print('Read value: $value');
}
[@override](/user/override)
Widget build(BuildContext context) {
return device != null
? Text('Connected to ${device!.name}')
: CircularProgressIndicator();
}
}
更多关于Flutter蓝牙通信插件gatt的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter蓝牙通信插件gatt的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中进行蓝牙通信时,flutter_blue
是一个非常流行的插件,它封装了 Android 和 iOS 上的蓝牙低功耗 (BLE) API。虽然 flutter_blue
插件本身并没有直接命名为 gatt
,但它确实提供了对 GATT(Generic Attribute Profile)服务的访问,这是 BLE 通信的基础。
下面是一个使用 flutter_blue
插件进行蓝牙通信的基本示例,包括扫描设备、连接到设备、发现服务和特征值(Characteristics),以及读写特征值。
首先,确保你的 pubspec.yaml
文件中包含了 flutter_blue
依赖:
dependencies:
flutter:
sdk: flutter
flutter_blue: ^0.13.0 # 请检查最新版本号
然后,运行 flutter pub get
来获取依赖。
接下来是主要的 Dart 代码:
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Blue Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
FlutterBlue flutterBlue = FlutterBlue.instance;
BluetoothDevice? selectedDevice;
List<BluetoothService> services = [];
@override
void initState() {
super.initState();
flutterBlue.stateChanged.listen((state) {
if (state == BluetoothState.on) {
print('Bluetooth is on');
// Start scanning
flutterBlue.scan().listen((scanResult) {
// Do something with scan result
print('Device found: ${scanResult.device.name} ${scanResult.device.id}');
});
}
});
// Request location permission on Android
flutterBlue.requestLocationPermission().then((_) {
setState(() {});
// Start scanning
flutterBlue.scan().listen((scanResult) {
// Do something with scan result
print('Device found: ${scanResult.device.name} ${scanResult.device.id}');
// Connect to device (for example, on a button press)
setState(() {
selectedDevice = scanResult.device;
});
// Connect to selected device
selectedDevice!.connect().then((_) {
// Discover services
selectedDevice!.discoverServices().then((services) {
setState(() {
this.services = services;
});
// For example, print out service UUIDs
services.forEach((service) {
print('Service UUID: ${service.uuid}');
// Discover characteristics of the first service (for example)
service.characteristics.then((characteristics) {
characteristics.forEach((characteristic) {
print(' Characteristic UUID: ${characteristic.uuid}');
// Read characteristic value (for example)
characteristic.read().then((value) {
print(' Value: ${value}');
});
// Write to characteristic (for example)
// characteristic.write([0x10, 0x01]); // Example data
// Listen for characteristic value changes
characteristic.setNotifyValue(true).then((_) {
characteristic.value.listen((value) {
print(' Characteristic value changed: ${value}');
});
});
});
});
});
});
});
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Blue Demo'),
),
body: Center(
child: selectedDevice == null
? Text('No device selected.')
: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Device: ${selectedDevice!.name ?? 'Unknown'}'),
Text('Address: ${selectedDevice!.id}'),
ElevatedButton(
onPressed: () {
// Disconnect from device
selectedDevice!.disconnect();
setState(() {
selectedDevice = null;
services = [];
});
},
child: Text('Disconnect'),
),
],
),
),
);
}
}
说明:
- 初始化 FlutterBlue 实例:在
initState
方法中,我们监听蓝牙状态的变化,并在蓝牙打开时开始扫描设备。 - 扫描设备:使用
flutterBlue.scan()
方法来扫描附近的蓝牙设备。扫描到的每个设备都会触发一个事件,我们可以在这个事件中处理设备信息。 - 连接到设备:在扫描到的设备信息中,我们可以选择一个设备进行连接。这里为了简化,我们在扫描到设备时立即尝试连接(实际使用中,你可能会在用户点击某个按钮时连接设备)。
- 发现服务:连接成功后,使用
device.discoverServices()
方法来发现设备上的服务。 - 读取和写入特征值:遍历服务中的特征值,读取它们的值,或者写入新的值。还可以设置通知来监听特征值的变化。
请注意,这个示例代码为了简洁而省略了一些错误处理和用户界面的细节,比如处理连接失败、扫描停止等。在实际应用中,你需要根据具体需求来完善这些部分。