I am attempting to read data through a serial port using SwingWorker. However, upon executing this code I receive no output. By adding the line
JOptionPane.showConfirmDialog(null, "Cancel", "Cancel this task?", JOptionPane.DEFAULT_OPTION);
As suggested in SwingWorker not executing doInBackGround() I only receive the outputs "Reading" /n "Done", and my getPortText method is not invoked. The IF block that is meant to display available ports also does not execute.
The fazecast SerialComm JAR can be found at http://fazecast.github.io/jSerialComm/
All help is greatly appreciated, I've been stuck on this for quite a few days!
import java.util.List;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import com.fazecast.jSerialComm.SerialPort;
public class PortWorkerCheck {
public static void main(String[] args) {
Worker worker = new Worker();
worker.execute();
}
public static void getPortText(String dir) {
System.out.println(dir);
}
static class Worker extends SwingWorker<Void, String>{
boolean portcheck = false;
SerialPort comPort[] = SerialPort.getCommPorts();
SerialPort port;
protected void done() {
System.out.println("Done");
}
@Override
protected Void doInBackground() throws Exception {
String data;
//This if block attempts to list available ports and have the user select one.
if (portcheck = false) {
int i = 1;
System.out.println("Select a port:");
for(SerialPort ports : comPort) {
System.out.println(i++ + ". " + ports.getSystemPortName());
}
Scanner s = new Scanner(System.in);
int chosenPort = s.nextInt();
port = comPort[chosenPort - 1];
portcheck = true;
if(port.openPort()) {
System.out.println("Port opened successfully");
}
port.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
}
publish("Reading");
Scanner read = new Scanner(port.getInputStream());
data = read.nextLine();
publish(data);
return null;
}
//My process should call getPortText, which should then display the received data.
@Override
protected void process(List<String> chunks) {
for(String line : chunks) {
portcheck = true;
PortWorkerCheck.getPortText(line);
}
}
}
}