scan static method

Scans for devices.

Implementation

static Stream<BrilliantScannedDevice> scan() async* {
  try {
    _log.info("Starting to scan for devices");

    await FlutterBluePlus.startScan(
      withServices: [
        _serviceUUID,
        Guid('fe59'),
      ],
      continuousUpdates: true,
      removeIfGone: const Duration(seconds: 2),
    );
  } catch (error) {
    _log.warning("Scanning failed. $error");
    throw BrilliantBluetoothException(error.toString());
  }

  yield* FlutterBluePlus.scanResults
      .where((results) => results.isNotEmpty)
      // TODO filter by name: "Frame", "Frame Update", "Monocle" & "DFUTarg"
      .map((results) {
    ScanResult nearestDevice = results[0];
    for (int i = 0; i < results.length; i++) {
      if (results[i].rssi > nearestDevice.rssi) {
        nearestDevice = results[i];
      }
    }

    _log.fine(
        "Found ${nearestDevice.device.advName} rssi: ${nearestDevice.rssi}");

    return BrilliantScannedDevice(
      device: nearestDevice.device,
      rssi: nearestDevice.rssi,
    );
  });
}