Page 249 - The Unofficial Guide to Lego Mindstorms Robots
P. 249

238


                  sendReturn();
             }
              catch (InterruptedException ie) { System.out.println(ie) ; }
              catch (DownloadException de) {
              System.out.println();
                System.out.println("Line " + n + ":");
                System.out.println(" " + de.getMessage());
             }
              catch (IOException ioe) { System.out.println(ioe); }

              // Regardless of what happened, try to clean up.
             try {
              mPortListener.stop();
              mFileIn.close();
              mOut.close();
              mPort.close();
             }
              catch (IOException ioe) {}
             System.exit(0);
           }

            protected void sendReturn() throws IOException, InterruptedException {
             mOut.write('\r');
             mOut.flush();
             Thread.sleep(kCharSleep);
              // Wait for response, or time out.
              long savedTime = System.currentTimeMillis();
              boolean trucking = true;
              while (trucking) {
                if (mPortListener.isComplete()) trucking = false;
                long currentTime = System.currentTimeMillis();
                if (currentTime - savedTime > kTimeOut) trucking = false;
              Thread.sleep(20);
             }
           }

            public class PortListener
              implements Runnable {
              private Thread mThread;
              private BufferedReader mIn;
              private boolean mComplete = false;
              private boolean mError = false;
              private String mLastLine;

              public PortListener (Reader in) {
                mIn = new BufferedReader(in);
                mThread = new Thread(this);
              mThread.start();
             }

              public void run() {
              String line;
              try {
                  while((line = mIn.readLine()) != null) {
   244   245   246   247   248   249   250   251   252   253   254