FengChendian / serial_port_win32

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

Port is now availabel when open and readBytesOnListen bug #15

Closed yong5354 closed 2 years ago

yong5354 commented 2 years ago

The following are the two problems I met when using:

  1. Open port number that is greater than COM9, the open function will return INVALID_HANDLE_VALUE and the error is "COMXX is not available". see this https://support.microsoft.com/en-us/topic/howto-specify-serial-ports-larger-than-com9-db9078a5-b7b6-bf00-240f-f749ebfd913e. so i change the _portNameUtf16 value from TEXT(portName) to TEXT("\\\\.\\$portName") and solve this problem.
  2. The value in readBytesOnListen callback will change randomly. This problem is cause because the value in readBytesOnListen callback is cast from a pointer "lpBuffer" that has been free, here is the code i modify:
    -uint8list = lpBuffer.cast<Uint8>().asTypedList(_bytesRead.value);
    +var u8l = lpBuffer.cast<Uint8>().asTypedList(_bytesRead.value); 
    +uint8list = Uint8List.fromList(u8l); //return the copy instead of the direct cast
    free(lpBuffer);

    I'm not sure if this is the correct solution, please point it out if I'm wrong, thanks again for sharing

FengChendian commented 2 years ago
  1. Yeah, I didn't implement method to open port number greater than COM9. I will add it later.
  2. I think you are right. I was always confused about random wrong [255,...255] data.It seems like that the problem was solved by your method.

    /// [_read] is a fundamental read function/
    Future<Uint8List> _read(int bytesSize) async {
    final lpBuffer = calloc<Uint16>(bytesSize);
    Uint8List uint8list;
    
    try {
      readOnBeforeFunction();
      ReadFile(handler!, lpBuffer, bytesSize, _bytesRead, _over);
    } finally {
      /// Uint16 need to be casted for real Uint8 data
      var u8l = lpBuffer.cast<Uint8>().asTypedList(_bytesRead.value);
      uint8list = Uint8List.fromList(u8l);
      free(lpBuffer);
    }
    
    return uint8list;
    }