getNearestFrame static method

Future<BrilliantDevice> getNearestFrame()

Gets the nearest Frame device.

Implementation

static Future<BrilliantDevice> getNearestFrame() async {
  await FlutterBluePlus.stopScan();
  //await FlutterBluePlus.startScan();
  await FlutterBluePlus.startScan(withServices: [_serviceUUID]);

  final Completer<List<ScanResult>> completer = Completer();
  final subscription = FlutterBluePlus.scanResults.listen((results) {
    if (results.isNotEmpty) {
      final filteredList = results
          .where((d) =>
              d.advertisementData.serviceUuids.contains(_serviceUUID) &&
              _allowedDeviceNames.any((name) => d.advertisementData.advName.startsWith(name)))
          .toList();
      if (filteredList.isNotEmpty) {
        completer.complete(filteredList);
      }
    }
  });

  final devices = await completer.future;
  await subscription.cancel();
  FlutterBluePlus.stopScan();

  devices.sort((a, b) => b.rssi.compareTo(a.rssi));

  if (devices.isEmpty) {
    throw const BrilliantBluetoothException("No Frame devices found");
  }

  final device = BrilliantScannedDevice(
    device: devices.first.device,
    rssi: devices.first.rssi,
  );

  return connect(device);
}