FengChendian / serial_port_win32

A flutter SerialPort library using win32 API.
BSD 3-Clause "New" or "Revised" License
30 stars 8 forks source link

Not able to re-open a closed port #18

Closed Ssercon closed 2 years ago

Ssercon commented 2 years ago

I have the package working pretty solidly for reading out data from a serial port. However when I try to re-open a port after closing it I am not able to do so and the SerialPort() function does not throw any exceptions.

I use this to connect to a serial port:

    try {
      port = SerialPort(dropdownvalue, openNow: true, ByteSize: 8);
    } on Exception catch (_) {
      print("can't open port, exiting...");
      return;
    }

The first time it works like a charm. Then I disconnect the port by calling:

opened_port.closeOnListen(
      onListen: () => print(opened_port.isOpened),
    )
      ..onError((err) {
        print(err);
      })
      ..onDone(() {
        print("${opened_port.portName} is closed");
        print(opened_port.isOpened);
      });

The port is closed properly because I am able to open it with other software but when I try to connect to it again with SerialPort() it doesn't fail but the COM port is not opened. Not sure if this is a bug in the close function or that I am missing something. Help would be appriciated, thanks!

FengChendian commented 2 years ago

Do you mean you use port = SerialPort(dropdownvalue, openNow: true, ByteSize: 8); to connect again?

I think the bug is due to Singleton mode. The last SerialPort hasn't been recycled by dart VM. So you re-create the same instance as the last. That means you fetch an old instance from the cache rather than init a new class. The old instance doesn't run the init method and using parameters that you have edited.

Maybe using open() method to force open can resolve this problem.

Ssercon commented 2 years ago

I can confirm that switching the first code snippet to:

      try {
      port = SerialPort(dropdownvalue, openNow: false, ByteSize: 8);
      port.open();
    } on Exception catch (_) {
      print("can't open port, exiting...");
      return;
    }

And thus using port.open() instead of opening the port during initalisation fixes the problem. Closing the issue, thanks!