openReader method

Future<bool> openReader(
  1. void handler(
    1. dynamic data
    )
)

Implementation

Future<bool> openReader(void Function(dynamic data) handler) async {
  log("open handler1");
  _intendedOpen = true;
  _mode = _HandlerMode.readOnly;

  if (_inner.isOpen) {
    portStatus.value = PortStatus.open;
    return true;
  }

  _setConnecting();
  portStatus.value = PortStatus.opening;
  _log('[PORT][$portName] Opening...');

  if (!_inner.openRead()) {
    portStatus.value = PortStatus.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(handler, 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;
  savedHandler = handler;
  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;
}