serial_port_win32 icon indicating copy to clipboard operation
serial_port_win32 copied to clipboard

Getting SetCommError when started again after closing the port.

Open MANOJKUMAR26 opened this issue 4 months ago • 16 comments

Hi Team, I am trying to read serial data through USB for flutter windows desktop application. The data gets read the first time properly but when I stop the port and start the reading again, I am getting setCommState error. I am using : serial_port_win32: ^1.3.0

Below is the code I am using to open the port and read the data and close the port.

late SerialPort port; void _getPortsAndClose() { port.close(); showToast( 'Readings stopped successfully', duration: Duration(seconds: 3), position: const ToastPosition(align: Alignment.topRight), backgroundColor: Colors.green ); }

void _getPortsAndOpen(Device selectedDevice) { final List<PortInfo> portInfoLists = SerialPort.getPortsWithFullMessages(); ports = SerialPort.getAvailablePorts(); String datacopy = ''; print(portInfoLists); print(ports); if (ports.isNotEmpty) {

  port = SerialPort(selectedDevice.portName,
      openNow: false,BaudRate:9600, ReadIntervalTimeout: 1, ReadTotalTimeoutConstant: 2);
  port.open();
  
  String incomingData = '';
  String completeData = '';

  // while (port.isOpened) {
  // incomingData = '';
  port.readBytesOnListen(8, (value) {
    print('check vlaue ${utf8.decode(value)}');
  // if (utf8.decode(value) != '+' && utf8.decode(value) != ',') {
  incomingData += utf8.decode(value);
  print('check incoming data ${incomingData.length}');
  if(incomingData.length > 50) {
      String trimmedData = incomingData.substring(35);
      incomingData = trimmedData;
  }
  List<String> parts = incomingData.split(',');
  final regex = RegExp(r'\+\d+(?:\.\d+)?'); // Matches numbers optionally followed by a decimal point
  List<double> extractedValues = [];
  for (var part in parts) {
    final match = regex.matchAsPrefix(part);
    if (match != null) {
      // Extract the captured group (the number) and convert to double
      extractedValues.add(double.parse(match.group(0)!.substring(1))); // Remove leading "+"
    }
  }

  if (extractedValues.length >= 2) {
    completeData = extractedValues[extractedValues.length - 2].toString();
  }
  
  setState(() {data = completeData;});
  }
  );
  }
  
  Can you help me resolve this issue please?
  Below are the attempts I did to fix the issue:
  1) Tries to set stop bits to 0 and 1, didn't help.
  2) Tried giving delay before stopping the port so that if there is any queue it can complete but that also didn't help.
  

MANOJKUMAR26 avatar Oct 13 '24 07:10 MANOJKUMAR26