Я пытаюсь выполнить поиск устройств, но у меня так много доступных устройств без имен. Когда я сканирую с помощью другого приложения 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');
}
}
}
Устройство Bluetooth LE может передавать свое имя в рекламном сообщении, но это не обязательно. Предположение о том, что каждая вещательная компания Bluetooth LE передает в рекламе имя своего устройства, неверно. Я думаю, что ваше приложение все делает правильно и что используемое вами эталонное приложение просто отфильтровывает все устройства Bluetooth LE без имен.
@TalalGh Это зависит от вашего местоположения. Bluetooth может иметь дальность приема 50-100 метров. Просто нарисуйте вокруг себя трехмерную сферу радиусом 100 метров и посчитайте, сколько смартфонов, гарнитур, колонок, компонентов умного дома BT… расположено в этой области.
@Роберт, на самом деле это имеет смысл, спасибо, ребята.
а нормально ли найти столько устройств?