FengChendian / serial_port_win32

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

no data after closing and reopening connection #8

Closed ali80 closed 3 years ago

ali80 commented 3 years ago

Hi, Connecting works the first time and I receive data after connection, after closing connection and trying to connect again, no data is received on the new conenction

ElevatedButton(
    onPressed: () async {
      sp = SerialPort("COM9", openNow: true);
      sp.readBytesOnListen(8, (value) {
        print(value.toString());
      });
    },
    child: Text("connect")),
ElevatedButton(
    onPressed: () async {
      sp.close();
    },
    child: Text("disconnect")),
FengChendian commented 3 years ago

Because this is Singleton Pattern. sp = SerialPort("COM9", openNow: true); only using once actually. If you print sp.isOpened, you will find value is false. So don't re-create intsance. You can:

final sp = SerialPort("COM9", openNow: false);
ElevatedButton(
    onPressed: () async {
      sp.open()
      sp.readBytesOnListen(8, (value) {
        print(value.toString());
      });
    },
    child: Text("connect")),

or

ElevatedButton(
    onPressed: () async {
      sp = SerialPort("COM9", openNow: true);
      if (!sp.isOpened) {
        sp.open()
      }
      sp.readBytesOnListen(8, (value) {
        print(value.toString());
      });
    },
    child: Text("connect")),
ali80 commented 3 years ago

I used your second method and it works, thanks, but this seems weird, if I need multiple connections to multiple serial ports, you create multiple singletons for each port and then SerialPort factory uses caching to return selected port's instance?

FengChendian commented 3 years ago

I used your second method and it works, thanks, but this seems weird, if I need multiple connections to multiple serial ports, you create multiple singletons for each port and then SerialPort factory uses caching to return selected port's instance?

Yeah... It is weird. Because I found that if I don't use singleton, Hot reload will cause multiple connection problems for same COM name. The instance will not be recycled immediately. So maybe you can't re-connect COM next time if you forget to close COM.

ali80 commented 3 years ago

Interesting to know reasoning behind that, maybe add example to the docs since this kind of usage is not obvious