startScan method

Future<void> startScan({
  1. bool filterByService = true,
  2. int scanTimeoutSecs = 30,
})

Implementation

Future<void> startScan({
  bool filterByService = true,
  int scanTimeoutSecs = 30,
}) async {
  if (_didDispose) {
    return;
  }

  await _ensurePermissions();
  await _cancelScanOnly();

  _matchingDevice = null;
  state = const BleScanning();

  final withServices = filterByService ? _scanServices : const <Uuid>[];

  _scanTimeoutTimer = Timer(Duration(seconds: scanTimeoutSecs), () async {
    await _cancelScanOnly();
    state = const BleError();
    _scheduleReconnect();
  });

  _scanSub = _ble
      .scanForDevices(
    withServices: withServices,
    scanMode: ScanMode.lowLatency,
  )
      .listen(
    (device) {
      if (!_deviceMatcher(device)) {
        return;
      }

      _scanTimeoutTimer?.cancel();
      _matchingDevice = device;
      state = BleDeviceFound(device);

      if (_shouldConnect) {
        unawaited(_ensureAutoConnect());
      }
    },
    onError: (Object error) {
      state = BleError(error.toString());
      _scheduleReconnect();
    },
  );
}