open method

Future<bool> open()

Try opening the port with the configured mode.

Implementation

Future<bool> open() async {
  if (_port.isOpen) return true;

  if (!SerialPort.availablePorts.contains(config.portName)) {
    return false;
  }

  final ok = _port.openReadWrite();
  if (!ok) return false;

  final cfg = SerialPortConfig()
    ..baudRate = config.baudRate
    ..bits = config.dataBits
    ..parity = config.parity
    ..stopBits = config.stopBits
    ..setFlowControl(config.flowControl);
  _port.config = cfg;
  // NOTE: flutter_libserialport does not expose manual DTR/RTS toggling.
  // Use flow control in SerialPortConfig instead (none / rtsCts / dtrDsr).


  final parser = FrameParser();

  // reader.stream.listen((Uint8List chunk) {
  //   final msgs = parser.feed(chunk);
  //   for (final msg in msgs) {
  //     final text = String.fromCharCodes(msg);
  //     print('Received frame: "$text" (hex: ${msg.map((b)=>b.toRadixString(16)).join(" ")})');
  //
  //     // Here call your onReceived / stream event
  //     onReceived(DataReceive(text: text, bytes: msg));
  //   }
  // });
  // Start reader
  _reader = SerialPortReader(_port);
  _reader!.stream.listen(
    _onBytes,
    onError: (e, st) {
      // bubble up as an empty receive (or log)
    },
  );

  // Start pin polling (lib doesn’t expose pin change events)
  _pinPoll?.cancel();
  _pinPoll = Timer.periodic(const Duration(milliseconds: 250), (_) => _pollPins());

  return true;
}