
package lejos.pc.tools;
import lejos.pc.comm.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.io.*;

/**
 * Downloads  data from the RConsole running on a MXT <br>
 * Uses USB by default, or Bluetooth  if selected from buttons.
 * If using Bluetooth, you can get a quicker connection entering the name or address 
 * of you NXT.<br>
 * Do NOT click "connect" unless the NXT displays the correct "Console" message.
 * status field shows messages 
 * @author Roger Glassey 6.1.2008
 *
 * 
 */
public class ConsoleViewer extends JFrame implements ActionListener
{
   private JButton startButton = new JButton("Connect");
   private JToggleButton usbButton = new JToggleButton("USE BlueTooth");
   private TextField statusField = new TextField(20);
   private TextField nameField = new TextField(12);
   private String _nxt = "NXT"; 
   private boolean _useUSB = true;
   private InputStream is = null;
   private DataInputStream dataIn = null;
   private OutputStream os = null;
   private Connector con;
   private boolean _connected = false;

   /**
    * screen area to hold the downloaded data
    */
   private TextArea theLog;


   /**
    * Constructor builds GUI
    */
   public ConsoleViewer() 
   {		
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setTitle("View RConsole output from NXT");
      setSize(500,600);
      JPanel p1 = new JPanel();  //holds  button and text field
      p1.add(usbButton);
      usbButton.addActionListener(this);
      p1.add(new JLabel("name or address"));
      p1.add(nameField);
      startButton.addActionListener(this);
      JPanel p2 = new JPanel();//  holds label and text field
//      p2.add(usbButton);
//      usbButton.addActionListener(this);
      p2.add(startButton);
      p2.add(new JLabel("  Status:"));
      p2.add(statusField);
      JPanel panel = new JPanel();  // North area of the frame
      panel.setLayout(new GridLayout(2,1));
      panel.add(p1);
      panel.add(p2);;
      add(panel,BorderLayout.NORTH);
      theLog = new TextArea(40,40); // Center area of the frame
      getContentPane().add(theLog,BorderLayout.CENTER);
      statusField.setText("using USB");
      Reader reader = new Reader();
      reader.start();
   }
   /**
    * Required by action listener; only action is generated by the get Length button
    */	
   public void actionPerformed(ActionEvent e)
   {
      if(e.getSource()== startButton)
      {
         _nxt = nameField.getText();
         startDownload();
      }
      if(e.getSource()==usbButton)
      {
         _useUSB = !_useUSB;
         if(_useUSB){
            setMessage("using USB");
         }
         else setMessage("using Bluetooth");          
      }
   }
   /**
    * Initialize the display Frame <br>
    */		
   public static void main(String[] args)
   {
      ConsoleViewer frame = new ConsoleViewer();
      frame.setVisible(true);
   } 

   private void connect()
   {
      _nxt = nameField.getText(); 
      setMessage("Connecting");
      con = new Connector();
      if (! con.connectTo(_nxt,_useUSB)) System.exit(1);
      is = con.getInputStream();
      _connected = true;
   }
   private void startDownload()
   {  
      if(!_connected)connect();        
      os = con.getOutputStream();
      // the NXT is waiting for an incoming byte before it starts transmitting 
      try  // handshake
      {     
         byte [] hello = new byte [] {'C', 'O', 'N'};
         os.write(hello);
         os.flush();       
      } catch(IOException e) {System.out.println(e+" write "); }
      _connected = true;
      setMessage("ready for data");
   }

   private class Reader extends Thread
   {
      public  void run()
      {     
         while(true)
         {
            if(_connected)
            {
               try
               {  
                  int input;
                  while ((input = is.read()) >= 0) 
                  {   
                     theLog.append(""+(char)input);
                  } 
                  is.close();
               }
               catch(IOException e) 
               {
                  System.out.println( "read error"); 
               }
            } 
            Thread.yield();
         }
      }
   }
   /**
    *messages generated by  PCcomSerial show in the status Field
    */
   public void  setMessage(String s){ statusField.setText(s);}
}

