Where I work, we solved a similar issue by having our emulator not spoof a COM port at all. Here's how you can do it:
- Define an interface for talking with your COM port, something like IUsbCommService
- Implement your real COM-communcation service, using the standard Java Comm API
- For your emulator, simply kick of a thread that spits out the same sort of data you can expect from your USB device at regular intervals.
- Use your IOC framework of choice (e.g., Spring) to wire up either the emulator or the real service.
- As long as you hide your implementation logic appropriately, and as long as you code to your interface, your service-consumer code won't care whether it's talking to the real USB device or to the emulator.
For example:
import yourpackage.InaccessibleDeviceException;
import yourpackage.NoDataAvailableException;
public interface IUsbProviderService {
public void initDevice() throws InaccessibleDeviceException;
public UsbData getUsbData()
throws InaccessibleDeviceException, NoDataAvailableException;
}
// The real service
import javax.comm.SerialPort; //....and the rest of the java comm API
public class UsbService implements IUsbProviderService {
.
.
.
}
// The emulator
public class UsbServiceEmulator implements IUsbProviderService {
private Thread listenerThread;
private static final Long WAITTIMEMS = 10L;
private String usbData;
public UsbServiceEmulator(long maxWaitTime) throws InaccessibleDeviceException{
initialize();
boolean success = false;
long slept = 0;
while (!success && slept < maxWaitTime) {
Thread.sleep(WAITTIMEMS);
slept += WAITTIMEMS;
}
}
private void initialize() throws InaccessibleDeviceException{
listenerThread = new Thread();
listenerThread.start();
}
private class UsbRunner implements Runnable {
private String[] lines = {"Data line 1", "Data line 2", "Data line 3"};
public void run() {
int line = 0;
while(true) {
serialEvent(lines[line]);
if(line == 3) {
line = 0;
} else {
line++;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
//handle the error
}
}
private void serialEvent(String line) {
if(/*you have detected you have enough data */) {
synchronized(this) {
usbData = parser.getUsbData();
}
}
}
}
Hope this helps!