Пытаюсь выполнить поиск ближайших устройств с помощью Bluetooth в трепете. 19,20,22 или даже больше устройств найдены без названий

Я пытаюсь выполнить поиск устройств, но у меня так много доступных устройств без имен. Когда я сканирую с помощью другого приложения Bluetooth, я не нахожу ни одного устройства, а может быть, одного или двух. Думаю, что-то не так в моем 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');
    }
  }
}

0
0
77
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Устройство Bluetooth LE может передавать свое имя в рекламном сообщении, но это не обязательно. Предположение о том, что каждая вещательная компания Bluetooth LE передает в рекламе имя своего устройства, неверно. Я думаю, что ваше приложение все делает правильно и что используемое вами эталонное приложение просто отфильтровывает все устройства Bluetooth LE без имен.

а нормально ли найти столько устройств?

Talal Gh 30.04.2024 13:46

@TalalGh Это зависит от вашего местоположения. Bluetooth может иметь дальность приема 50-100 метров. Просто нарисуйте вокруг себя трехмерную сферу радиусом 100 метров и посчитайте, сколько смартфонов, гарнитур, колонок, компонентов умного дома BT… расположено в этой области.

Robert 30.04.2024 13:50

@Роберт, на самом деле это имеет смысл, спасибо, ребята.

Talal Gh 30.04.2024 14:09

Другие вопросы по теме