Flutter蓝牙通信插件ip_global_ble的使用

Flutter蓝牙通信插件ip_global_ble的使用

ip_global_ble 是一个为 Flutter 提供蓝牙扫描功能的插件。本指南将帮助你了解如何在 Flutter 应用程序中使用该插件。

使用

1. 设置 Android 权限

首先,在你的 AndroidManifest.xml 文件中添加以下权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

2. 在 main.dart 中定义全局键

main.dart 文件的顶部定义一个全局键:

final GlobalKey<_HomeScreenState> glbKey = GlobalKey<_HomeScreenState>();

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(key: glbKey), // 附加全局键,不要忘记这一步。
    );
  }
}

3. 声明回调函数

你可以通过声明回调函数来使用库:

void IP_CB_BLE_ShowScanInfo(String msg) {
  setState(() {
    msg1 = msg;
    print("IP_CB_BLE_ShowScanInfo : " + msg);
  });
}

void IP_CB_BLE_ScannedBLEList(List<clsScannedBLE> lstScannedBLE) {
  setState(() {
    print("IP_CB_BLE_ScannedBLEList : " + lstScannedBLE.length.toString());
  });
}

void IP_CB_BLE_BLEConnectInfo(String msg) {
  setState(() {
    msg1 = msg;
    print("IP_CB_BLE_BLEConnectInfo : " + msg);
  });
}

void IP_CB_BLE_WriteBLEResponse(List<clsWriteBLEResponse> objlstResponse) {
  setState(() {
    msg1 = objlstResponse.last.strOriginalRequest.toString() + " = " + objlstResponse.last.strResponse.toString();
    print("IP_CB_BLE_WriteBLEResponse : " + msg1);
  });
}

4. 调用 IP_scanBLE 方法

通过全局键调用 IP_scanBLE 方法:

IP_scanBLE(context, glbKey, "<Filter with Name>", null);

5. 连接并读写数据

连接到蓝牙设备并进行数据读写操作:

List<String> lstWrite = [];
List<clsWriteBLEResponse> lstRead = [];

clsFilterBLE objFilter = clsFilterBLE(strBLEName: 'IG', maxRssi: -100);

lstWrite.add("RSSIFROM:-100:");
lstWrite.add("RSSITO:-100:");

clsBLEConnect obj = new clsBLEConnect(
  strServiceUUID: "<ServiceUUID>",
  strCharacteristicUUID: "<CharacteristicUUID>",
  lstRequest: lstWrite,
  lstResponse: lstRead,
  flgRequestWithoutResponse: false,
  strMAC: strBLEMACAddress,
);

IP_scanBLE(context, glbKey, objFilter, obj);

6. 停止扫描

停止扫描操作:

IP_stopScanning();

事件

IP_CB_BLE_ShowScanInfo

当请求位置权限、蓝牙权限或扫描时,会触发此事件:

Requesting Location Permission
Requesting Bluetooth Permission
Scanning...
<DeviceMAC>: <DeviceName> found!
Scanning Stopped...

IP_CB_BLE_ScannedBLEList

返回已扫描到的蓝牙设备列表:

class clsScannedBLE {
  String name;
  String BLEmac;
  String WiFimac;
  int rssi;

  clsScannedBLE({
    required this.name,
    required this.BLEmac,
    required this.WiFimac,
    required this.rssi,
  });
}

List<clsScannedBLE> lstScannedBLE

IP_CB_BLE_BLEConnectInfo

当连接到蓝牙设备、发现服务或特性时,会触发此事件:

Connecting...
Discovering Services
Discovering Characteristics
Writing WOR/WR <DATA>
# Successfully - 您可以替换为 Read / Write 或其他任何内容。

IP_CB_BLE_WriteBLEResponse

读取 GATT 数据时返回响应:

class clsWriteBLEResponse {
  String strOriginalRequest;
  String strResponse;

  clsWriteBLEResponse({
    required this.strOriginalRequest,
    required this.strResponse,
  });
}

List<clsWriteBLEResponse> lstResponse = [];

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

1 回复

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


ip_global_ble 是一个用于在 Flutter 应用中实现蓝牙通信的插件。它提供了与蓝牙设备进行连接、数据交换等功能。以下是如何使用 ip_global_ble 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  ip_global_ble: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 初始化插件

在 Flutter 应用中初始化 ip_global_ble 插件:

import 'package:ip_global_ble/ip_global_ble.dart';

void main() {
  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> {
  IpGlobalBle _ble = IpGlobalBle();

  [@override](/user/override)
  void initState() {
    super.initState();
    _initializeBle();
  }

  Future<void> _initializeBle() async {
    bool isInitialized = await _ble.initialize();
    if (isInitialized) {
      print("BLE initialized successfully");
    } else {
      print("Failed to initialize BLE");
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Communication'),
      ),
      body: Center(
        child: Text('Bluetooth Screen'),
      ),
    );
  }
}

3. 扫描蓝牙设备

使用 scanForDevices 方法来扫描附近的蓝牙设备:

Future<void> _scanForDevices() async {
  List<BluetoothDevice> devices = await _ble.scanForDevices();
  for (var device in devices) {
    print("Device: ${device.name}, ID: ${device.id}");
  }
}

4. 连接蓝牙设备

使用 connectToDevice 方法来连接特定的蓝牙设备:

Future<void> _connectToDevice(String deviceId) async {
  bool isConnected = await _ble.connectToDevice(deviceId);
  if (isConnected) {
    print("Connected to device: $deviceId");
  } else {
    print("Failed to connect to device: $deviceId");
  }
}

5. 发送和接收数据

使用 sendDatareceiveData 方法来发送和接收数据:

Future<void> _sendData(String deviceId, String data) async {
  await _ble.sendData(deviceId, data);
  print("Data sent: $data");
}

Future<void> _receiveData(String deviceId) async {
  String data = await _ble.receiveData(deviceId);
  print("Data received: $data");
}

6. 断开连接

使用 disconnectFromDevice 方法来断开与蓝牙设备的连接:

Future<void> _disconnectFromDevice(String deviceId) async {
  await _ble.disconnectFromDevice(deviceId);
  print("Disconnected from device: $deviceId");
}

7. 处理权限

在 Android 和 iOS 上,蓝牙通信需要特定的权限。确保在 AndroidManifest.xmlInfo.plist 中添加必要的权限声明。

Android

AndroidManifest.xml 中添加以下权限:

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

iOS

Info.plist 中添加以下权限:

<key>NSBluetoothAlwaysUsageDescription</key>
<string>We need access to Bluetooth to connect to devices.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need access to Bluetooth to connect to devices.</string>

8. 处理蓝牙状态

你可以监听蓝牙状态的变化,并在状态改变时做出相应的处理:

_ble.onBluetoothStateChanged.listen((state) {
  print("Bluetooth state changed: $state");
});

9. 处理设备连接状态

你可以监听设备连接状态的变化,并在状态改变时做出相应的处理:

_ble.onDeviceConnectionStateChanged.listen((state) {
  print("Device connection state changed: $state");
});

10. 错误处理

在处理蓝牙通信时,可能会遇到各种错误。确保在代码中处理这些错误:

try {
  await _ble.connectToDevice(deviceId);
} catch (e) {
  print("Error connecting to device: $e");
}

11. 完整示例

以下是一个完整的示例,展示了如何使用 ip_global_ble 插件进行蓝牙通信:

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

void main() {
  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> {
  IpGlobalBle _ble = IpGlobalBle();
  List<BluetoothDevice> _devices = [];
  String? _connectedDeviceId;

  [@override](/user/override)
  void initState() {
    super.initState();
    _initializeBle();
  }

  Future<void> _initializeBle() async {
    bool isInitialized = await _ble.initialize();
    if (isInitialized) {
      print("BLE initialized successfully");
      _scanForDevices();
    } else {
      print("Failed to initialize BLE");
    }
  }

  Future<void> _scanForDevices() async {
    _devices = await _ble.scanForDevices();
    setState(() {});
  }

  Future<void> _connectToDevice(String deviceId) async {
    bool isConnected = await _ble.connectToDevice(deviceId);
    if (isConnected) {
      print("Connected to device: $deviceId");
      setState(() {
        _connectedDeviceId = deviceId;
      });
    } else {
      print("Failed to connect to device: $deviceId");
    }
  }

  Future<void> _sendData(String data) async {
    if (_connectedDeviceId != null) {
      await _ble.sendData(_connectedDeviceId!, data);
      print("Data sent: $data");
    } else {
      print("No device connected");
    }
  }

  Future<void> _receiveData() async {
    if (_connectedDeviceId != null) {
      String data = await _ble.receiveData(_connectedDeviceId!);
      print("Data received: $data");
    } else {
      print("No device connected");
    }
  }

  Future<void> _disconnectFromDevice() async {
    if (_connectedDeviceId != null) {
      await _ble.disconnectFromDevice(_connectedDeviceId!);
      print("Disconnected from device: $_connectedDeviceId");
      setState(() {
        _connectedDeviceId = null;
      });
    } else {
      print("No device connected");
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bluetooth Communication'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _devices.length,
              itemBuilder: (context, index) {
                var device = _devices[index];
                return ListTile(
                  title: Text(device.name),
                  subtitle: Text(device.id),
                  onTap: () => _connectToDevice(device.id),
                );
              },
            ),
          ),
          if (_connectedDeviceId != null)
            Column(
              children: [
                ElevatedButton(
                  onPressed: () => _sendData("Hello, Bluetooth!"),
                  child: Text("Send Data"),
                ),
                ElevatedButton(
                  onPressed: _receiveData,
                  child: Text("Receive Data"),
                ),
                ElevatedButton(
                  onPressed: _disconnectFromDevice,
                  child: Text("Disconnect"),
                ),
              ],
            ),
        ],
      ),
    );
  }
}
回到顶部