尝试在 flutter 中使用蓝牙扫描附近的设备。找到 19、20、22 甚至更多没有名称的设备

问题描述 投票:0回答:1

我正在尝试扫描设备,但我得到了很多可用的设备,但上面没有名称。当我使用另一个蓝牙应用程序进行扫描时,我没有找到任何设备,或者可能只有一两个。所以我猜我的 dart 代码有问题,我似乎无法弄清楚。所以请帮忙

这是我的 bluetoothManager 类,任何帮助将不胜感激。谢谢

import 'dart:async';

import 'package:flutter_blue/flutter_blue.dart';

class BluetoothManager {
  final FlutterBlue _flutterBlue = FlutterBlue.instance;
  bool isConnected = false;
  BluetoothDevice? connectedDevice;
  late StreamSubscription<List<ScanResult>> _scanSubscription;

  Future<Stream<BluetoothState>> getBluetoothState() async {
    return _flutterBlue.state;
  }

  Future<List<BluetoothDevice>> scanForDevices() async {
    List<BluetoothDevice> devices = [];

    try {
      devices.clear();

      // Start scanning for devices
      await _flutterBlue.startScan(timeout: const Duration(seconds: 10));

      // Listen for discovered devices and handle the subscription
      _scanSubscription = _flutterBlue.scanResults.listen((results) {
        for (ScanResult result in results) {
          if (!devices.contains(result.device)) {
            devices.add(result.device);
            print('Discovered device: ${result.device.name}');
          }
        }
      }, onError: (error) {
        print('Error in scanResults stream: $error');
      }, onDone: () {
        print('Scan completed');
      });

      // Wait for the scan to complete
      await Future.delayed(Duration(seconds: 10));

      // Stop scanning for devices
      await _flutterBlue.stopScan();
    } catch (error) {
      print('Error scanning for devices: $error');
    } finally {
      // Cancel the subscription after scan completion or error
      _scanSubscription.cancel();
    }

    return devices;
  }

  Future<void> connectToDevice(BluetoothDevice device) async {
    try {
      // Check if the device is already connected
      if (isConnected && connectedDevice == device) {
        print('Device is already connected');
        return;
      }

      // Disconnect from any previously connected device
      if (isConnected && connectedDevice != null) {
        await connectedDevice!.disconnect();
        isConnected = false;
      }

      // Connect to the new device
      await device.connect();
      connectedDevice = device;
      isConnected = true;
      print('Connected to device: ${device.name ?? 'Unknown'}');
    } catch (error) {
      print('Error connecting to device: $error');
    }
  }

  void sendCommand(String command) {
    if (isConnected && connectedDevice != null) {
      // Replace this with your logic to send data to the connected device
      print('Sending command: $command');
    } else {
      print('No device connected');
    }
  }
}

android flutter dart bluetooth bluetooth-lowenergy
1个回答
0
投票

蓝牙 LE 设备可以在广告消息中传输其名称,但并非必须如此。每个蓝牙 LE 广播公司在广告中传输其设备名称的假设是不正确的。我认为您的应用程序所做的一切都是正确的,并且您正在使用的参考应用程序只是过滤掉所有没有名称的蓝牙 LE 设备。

© www.soinside.com 2019 - 2024. All rights reserved.