How To Test for Lost Serial Port?

I am using the processing serial library. In processing I am monitoring serial data. I want to detect when a USB device which identifies on a Windows computer as a COM port is turned off and therefor the COM port goes away.

I found a method in the documentation I think should do it but no joy.
active()
Return true if this port is still active and hasn’t run into any trouble.

Below is my code.
Would like some help.

/* Trying to use Serial.active()
 *I would like to detect loss of COM port like when a USB to serial adapter is disconnected.
 *I read about the active method here:
 *https://processing.github.io/processing-javadocs/libraries/processing/serial/Serial.html
 * However I can not get it to work. I run the sketch below and disconnect the USB adatpers 
 * and do not see the message when the port is not active.
 *If I disconnect the USB adapter before running the sketch I get Runtime
*/

import processing.serial.*;
Serial myPort;    // The serial port
String inString = "Not initilized" ;  // Input string from serial port
int cr = 13;      // ASCII carrage return 

void setup() { 
size(400,200); 
//Setup Serial input
  // List all the available serial ports: 
  printArray(Serial.list());  //Change the port number for your instrument.
  myPort = new Serial(this, Serial.list()[1], 115200); //COM30. 
  myPort.bufferUntil(cr);  //ST365 data is CR delimited.
}//setup

void draw(){
  if(myPort.active() != true){
   println("You can't have that port"); 
  }  
}//draw

/*Event handlers*/
//The serial port receiver. 
void serialEvent(Serial p) { 
  inString = p.readString();
  println(inString);
}// Serial receive 

I run the code and disconnect the USB COM port and never see the expected message “You can’t have that port”
I am running Processing 3.5.3 on a Windows 7 computer.

1 Like

You can try using Serial.list to see all available ports. And just check wether one disconnects/disappears if you unplug the USB.

Hello Lexyth,

Thanks for trying to help.

I probably should have phrased my question differently. I would like help understanding why the method “myPort.active()” did not work. Perhaps I have an error of understanding or the processing library only has a stub implementation that always returns “true” or ???

I want to programmatically test if the port to which mySerial was set at creation has become inactive (USB COM port disconnected).

I took Lexyth’s advise and wrote a function to test for the lost port.
The function is called in draw so I am polling for loss of port at the draw rate.

Code:

/* Trying to use Serial.active()
 *I would like to detect loss of COM port like when a USB to serial adapter is disconnected.
 *I read about the active method here:
 *https://processing.github.io/processing-javadocs/libraries/processing/serial/Serial.html
 * However I can not get it to work. I run the sketch below and disconnect the USB adatpers 
 * and do not see the message when the port is not active.
 *If I disconnect the USB adapter before running the sketch I get Runtime
 *question asked: https://discourse.processing.org/t/how-to-test-for-lost-serial-port/15437
 *20191114 Implimented function to read port list to see if port is gone.  Remove magic number for port.
*/

import processing.serial.*;
Serial myPort;    // The serial port
String myPortName = ""; 
String inString = "Not initilized" ;  // Input string from serial port
int cr = 13;      // ASCII carrage return 
int myPortIndex = 1; //Set for your desired port.

void setup() { 
size(400,200); 
//Setup Serial input
  // List all the available serial ports: 
  printArray(Serial.list());  //Print the current port numbers and names for your computer.
  myPortName = Serial.list()[myPortIndex];
  
  myPort = new Serial(this, myPortName, 115200); //Open the indexed port. 
  myPort.bufferUntil(cr);  //ST365 data is CR delimited.
}//setup

void draw(){
  background(0);
//  if(myPort.active() != true){
  if(isPortActive(myPortName) == true){
    text("Port is: "+ myPortName, 10, 10);
  }else {
    text("Your port is gone.", 10, 10); 
  }
}//draw

/*Event handlers*/
//The serial port receiver. 
void serialEvent(Serial p) { 
  inString = p.readString();
  println(inString);
}// Serial receive 

/* Functions */
boolean isPortActive(String aPort){
  String[] m1 = match(aPort, Serial.list()[myPortIndex]);  
  if (m1 != null ){
    return (true);
  }else{
    return(false);
  } 
}//isPortActive
2 Likes

I should have written, “I want an event to tell me if the port has become inactive (USB COM port disconnected).”

I though that function was a Solution, so i didn‘t write further :sweat_smile:

Anyway, to get an Event from when a Port is disconnected is apparently not a part of the Serial library…

And as for getting one yourself… it probably requires you to get it from the System directly, which is very annoying…(struggeled a lot to get an Event from the System and still failed after days…).

But maybe someone Else is more experienced with that…

As for getting an Event, you could just continuisly check if the Port changes and then trigger an Event yourself. That‘s a lot easier :sweat_smile:

You could just add a method in the Code you posted above, that is called when the isPortActive method returns false.

void portDeactivated () {
//put the Code you want executed in this case here. 
}
1 Like

Here is the Processing Serial.active() implementation:

which looks like it is a getter for a property on this JSSC SerialPort object:

Hey there,

I’m sure this post has been solved by now, but I just wanted to show my implementation from April, 2020.

String[] lastComList = *Serial.list() polled in setup()*;
...
String[] tempList = Serial.list();
    if (!Arrays.equals(lastComList, tempList)) { //Compare
        lastComList = tempList;
        comList.setItems(lastComList, 0);
    }

Of course, this only tests if you lost any serial port(s), not a particular one, though you could go further into the if statement once its triggered to determine which port was lost (I dont need that for my application)

Happy coding!

2 Likes

Hello legohead 259,
im new may you can send the whole code so I can use it in my project.
Thx very mutch

does this work for other people? i have tried and it seems that if the port has been open at anypoint while the program was running, and it gets disconnected, the port name still shows up in the serial.List … its like only if you restart the program will that serial port disapear… im having so much trouble getting processing to tell me if the serial port has been lost.

Hello,

This is a simple test to confirm that the Serial.list() is updated when I connect\disconnect my Arduino:

import processing.serial.*;
Serial myPort;

void setup()
  { 
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[2], 9600);
  }
  
void draw()
  { }
  
void keyPressed()
  {
  printArray(Serial.list());
  println(); 
  }

It works on my W10 PC with an Arduino MEGA 2560 R3.
I did not look at any of the topic examples.

This still needs more exploration…

:)

1 Like

I have found in the past that if an application e.g. Processing has a COM port open while the Arduino is repowered the connection does not work. To recover the situation I have to stop the Processing sketch (or maybe myPort.stop), repower the Arduino and wait a moment. Then restart the Processing sketch.

1 Like

when does Serial.list() gets updated ?
For me following code in loop always prints com ports even if I remove the cable.

printArray(Serial.list());

And following code in loop is also printing true even if I remove the cable.

 println(serialPort.active());

Please help.

Hi @Ghostsss, One way of getting things confused is to have something using the port, and you pull the cable out. If at this point you plug the usb in, it may look like you have a com port (in device manager) but it won’t work. The only way to restore normal working is to have the usb disconnected, and no program (or Ard Serial Monitor) using the port. Now plug it in, wait for the dee-ding noise, start again.

Another confusion is that the cheap Chinese Arduini, with the CH340 chip, you get a different com port number from different usb sockets.

1 Like

Thanks for the explanation.

What I want to do is if I pull the cable, I want to give an notification in the processing program that com port is no longer active. For example in following code, I want to print “Error in com Port” whenever I pull the cable when com Port is active. But currently nothing is getting printed.

Please help.

import processing.serial.*;

Serial myPort;

void setup(){
  myPort = new Serial(this, Serial.list()[0], 9600);
}

void draw(){
  serialPortCheck();
  serialReadData();
}

void serialPortCheck(){
  if(myPort.active()==false){
    println("Error in com Port");
  }
}

void serialReadData(){
  if(myPort.available()>0){
    println(myPort.readString());
  }
}

I managed to get it to work. (based on info from previous comments)

Here is the code for anyone to refer in future.

import processing.serial.*;

Serial myPort;
String currentPort;

void setup(){
  myPort = new Serial(this, Serial.list()[1], 9600);
  currentPort=Serial.list()[1]; // Save current port
}

void draw(){
  if(serialPortCheck()==true){
    println("com port found");
  }else{
    println("com port lost");
  }
  serialReadData();
}

boolean serialPortCheck(){
  boolean connected = false;
  String[] str = Serial.list(); // Get the current list of available ports
  for(int i=0; i<str.length; i++){
    //println("com:"+currentPort+"    str[i]:"+str[i]);
    if(currentPort.equals(str[i])==true){ //check if currentPort is still in the list of comPorts
      connected=true;   // com port found so still connected                   
      break;
    }
  }  
  return connected;
}

void serialReadData(){
  if(myPort.available()>0){
    println(myPort.readString());
  }
}