java - Using a Timer to break a loop -
i trying build timeout call/response ping. determine commport use in auto-connect sequence. when send call_signal byte[], expect "fu" in reply. how determine device. sscce below (sorry length, is shortened version)
import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.enumeration; import java.util.timer; import java.util.timertask; import javax.comm.commportidentifier; import javax.comm.commport; import javax.comm.portinuseexception; import javax.comm.serialport; public class pingtest { public static final long ping_timeout = 1000; // in millis public static final byte[] call_signal = {70, 68, 73, 68}; public boolean ping(commportidentifier cpi) { system.out.println("pinging " + cpi.getname()); commport port = null; inputstream input = null; outputstream output = null; //initialization test try { port = cpi.open("pingtest", 50); input = port.getinputstream(); output = port.getoutputstream(); } catch (portinuseexception ex) { if (cpi.getcurrentowner().startswith("pingtest")) { system.out.println("port owned application."); return true; } return false; } catch (exception ex) { try { port.close(); } catch (nullpointerexception e) { } system.out.println("failed initialization test."); system.err.println(ex); return false; } system.out.println("passed initialization test."); //call , response test final stop stop = new stop(); timer timer = new timer(); timer.schedule(new timertask() { @override public void run() { system.out.println("stop timer triggered."); stop.shouldstop = true; } }, ping_timeout); try { system.out.println("writing..."); output.write(call_signal); system.out.println("reading..."); boolean waitforf = true; while (!stop.shouldstop && !stop.didpass) { if (waitforf) { if ((byte) 'f' == input.read()) { waitforf = false; } } else { system.out.println('f'); if ((byte) 'u' == input.read()) { system.out.println('u'); stop.didpass = true; } else { system.out.println(); waitforf = true; } } } } catch (ioexception ex) { system.out.println("failed i/o test."); return false; } { port.close(); } if (stop.didpass) { system.out.println("successful ping."); return true; } system.out.println("failed call , response test."); return false; } public static void main(string[] args) { pingtest pinger = new pingtest(); enumeration<commportidentifier> ports = commportidentifier.getportidentifiers(); boolean trigger = true; string name = null; while (trigger && ports.hasmoreelements) { commportidentifier cpi = ports.nextelement(); name = cpi.getname(); trigger = !ping(cpi); } if (trigger) { system.out.println("found it. " + name); } else { system.out.println("not found"); } } } class stop { boolean shouldstop = false; boolean didpass = false; } my output is:
pinging com1 passed initialization test. writing... reading... stop timer triggered. and application freezes. there problem trying stop while loop timer?
your reads blocking. need use timeouts
Comments
Post a Comment