open method

Future<bool> open({
  1. required String source,
})

Implementation

Future<bool> open({required String source}) async {
  // log("open handler1");
  _intendedOpen = true;
  _mode = _HandlerMode.readWrite;
  log("called open already open from $source");
  if (_inner.isOpen) {


    portStatus.value = PortStatus.open;
    return true;
  }

  _setConnecting();
  portStatus.value = PortStatus.opening;
  _log('[PORT][$portName] Opening...');
  if (!_inner.openReadWrite()) {
    portStatus.value = PortStatus.error;
    log("called open error");
    _log('[PORT][$portName] Failed to open.');
    return false;
  }
  _log('[PORT][$portName] Opened.');


  try {
    final c = SerialPortConfig()
      ..baudRate = config.baudRate
      ..bits     = config.dataBits
      ..parity   = config.parity
      ..stopBits = config.stopBits
      ..setFlowControl(config.flowControl);
    _inner.config = c;
    _log('[PORT][$portName] Config applied.');
  } catch (e) {
    _log('[PORT][$portName] Config error: $e');
    try { _inner.close(); } catch (_) {}
    portStatus.value = PortStatus.error;
    _setOffline();
    return false;
  }
  log("open handler2");

  _reader = SerialPortReader(_inner);
  _sub ??= _reader!.stream.listen(_onBytes, onError: (err, st) {
    _log('[PORT][$portName] Read error: $err');
    _internalClose(keepIntent: true);
  }, onDone: () {
    _log('[PORT][$portName] Reader closed.');
    if (!_inner.isOpen) {
      portStatus.value = PortStatus.closed;
      _setOffline();
    }
  });

  log("open handler3");

  portStatus.value = PortStatus.open;

  if (!_bootstrapped) {
    _log('[PORT][$portName] Bootstrapping...');
    await _runBootstrap();
    _bootstrapped = true;
    await _pollOnce();
  }
  _pollTimer ??=
      Timer.periodic(const Duration(seconds: 5), (_) => _pollOnce());

  final (cts, dsr) = _readCtsDsr(_inner);
  _lastCts = cts;
  _lastDsr = dsr;

  log("open handler4");

  _pinPollTimer = Timer.periodic(pinPollInterval, (_) async {
    if (!_inner.isOpen) return;

    final (newCts, newDsr) = _readCtsDsr(_inner);

    if (newCts == _lastCts && newDsr == _lastDsr) return;

    _lastCts = newCts;
    _lastDsr = newDsr;

    await Future<void>.delayed(const Duration(milliseconds: 500));

    _handlePinChanged(
      ctsHolding: newCts,
      dsrHolding: newDsr,
      occurred: DateTime.now(),
    );

  });

  return true;
}