startScanning method

Future<void> startScanning()

Start scanning for BLE devices.

Starts the scanning process and sets a timer to stop the scanning process if no new devices are found.

Implementation

Future<void> startScanning() async {
  if (state.status != BluetoothAdapterState.on ||
      (state is BleDeviceScanning &&
          (state as BleDeviceScanning).scanIsInProgress)) {
    return;
  }

  if (_scanTimer != null) {
    return;
  }

  emit(const BleDeviceScanning(
    discoveredDevices: [],
    scanIsInProgress: true,
  ));

  /* clear cached RSSI values */
  _rssis.clear();

  /* instead of subscribing to the raw results, generate a sorted list of devices */
  _scanSubs = FlutterBluePlus.scanResults
      /* ignore redundant and empty scan results */
      .distinct(
          (previous, current) => (previous == current) || current.isEmpty)
      /* convert the scan results to a list of devices, storing the RSSI values */
      .map(
    (results) {
      final devices = results.map(
        (r) {
          _rssis[r.device] = r.rssi;
          return r.device;
        },
      ).toList();
      /* sort the devices by name */
      devices.addAll(mockDevices);
      devices.sort((d1, d2) => d1.platformName.compareTo(d2.platformName));
      return devices;
    },
  ).listen(
    /* update the state with the sorted list of devices */
    (devices) => emit(BleDeviceScanning(
      discoveredDevices: devices,
      scanIsInProgress: true,
    )),
  );

  FlutterBluePlus.isScanning
      .firstWhere((isScanning) => !isScanning)
      .then((_) {
    FlutterBluePlus.startScan(
      withServices: [gkServiceUuid],
      continuousUpdates: true,
      timeout: const Duration(seconds: 10),
      removeIfGone: const Duration(seconds: 5),
    );
  });

  int previousDeviceCount = 0;
  _scanTimer = Timer.periodic(const Duration(seconds: 5), (timer) async {
    if (state is! BleDeviceScanning) return;

    final devices = (state as BleDeviceScanning).discoveredDevices;

    if (devices.length > previousDeviceCount) {
      previousDeviceCount = devices.length;
    } else {
      await stopScanning();
    }
  });

  logger.info("Scanning started");
}