Solved

GPP Java Program

Posted on 2004-10-24
1,836 Views
Last Modified: 2012-06-27
Hi people, i am a newbie in this things of Java.
I have one program, which i pretend to modify, but first i need to know how it works. Well, i know what he does, but i dont know how is structured, like variables, classes etc etc etc. So, what i want is if someone can comment all the next code. To have and idea how to work it out after. Thanks a lot.


import java.io.*;
import java.util.*;
import javax.comm.*;

public class GpsReader implements SerialPortEventListener {


   private InputStream        inputStream;
   private SerialPort         sPort;

   private int                bcount = 0;

   static OutputStreamWriter  outW = null;
   static CommPortIdentifier  portId;
   static Enumeration         portList;

   public static final String FILENAME = "NMEA.txt";
   public static final String PORTNAME = "COM5";
   public static final int    BAUDRATE = 4800;
   public static final int    TIMEOUT  = 2000;    

   public static void main(String[] args) {

      GpsReader g = new GpsReader();
      g.mymain();              
   }

   void mymain(){

       try {
          outW = new OutputStreamWriter(
                 new FileOutputStream (FILENAME));
       }
       catch (IOException e) {
          System.err.println("Ficheiro de escrita não aberto\n" + e.toString());
          System.exit(1);
       }

        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(PORTNAME)) {


        try   {sPort = (SerialPort) portId.open("GarApp", TIMEOUT);}
        catch (PortInUseException e) {}

        try   {inputStream = sPort.getInputStream();}
        catch (IOException e) {}

     try   {sPort.addEventListener(this);}
        catch (TooManyListenersException e) {}

        sPort.notifyOnDataAvailable(true);
        try {
           sPort.setSerialPortParams(BAUDRATE,
                          SerialPort.DATABITS_8,
                          SerialPort.STOPBITS_1,
                          SerialPort.PARITY_NONE);
           }
        catch (UnsupportedCommOperationException e) {}
                }
            }
        }

   }

   public void serialEvent(SerialPortEvent event) {

      int  newData = 0;
      char mybyte;

      switch(event.getEventType()) {
         case SerialPortEvent.BI:            
         case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;

      case SerialPortEvent.DATA_AVAILABLE:
            while(newData != -1) {
               try {
                  newData = inputStream.read();
               if (newData == -1) {break;}
                  mybyte = (char)newData;
                  outW.write(mybyte);
                  bcount = bcount + 1;
                  if(mybyte == '$') {System.out.print("\r"+bcount+" bytes");}
               } catch(IOException ex) {
                  System.err.println(ex);
                  return;
               }
            }
            break;
      }
   }
}
0
Question by:psiubest
    2 Comments
     
    LVL 12

    Accepted Solution

    by:
    Here's the code with some comments and references to online documentation. Ask if you need specific info on some constructs. In order to really understand this, you'll have to read the documentation of the classes used. I would think that this code is still "work in progress"; it will do what's required but needs further work.


    HTH, J


    /* make names available, avoid full qualification: http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html#70209 */
    import java.io.*;
    import java.util.*;
    import javax.comm.*;

    /* class to copy GPS info from serial port into file */
    public class GpsReader implements SerialPortEventListener {


       private InputStream        inputStream; /* http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputStream.html */
       private SerialPort         sPort; /* http://java.sun.com/products/javacomm/javadocs/javax/comm/SerialPort.html */

       private int                bcount = 0; /* byte count */

       static OutputStreamWriter  outW = null; /* class to write an output file: http://java.sun.com/j2se/1.5.0/docs/api/java/io/OutputStreamWriter.html */
       static CommPortIdentifier  portId; /* which serial port to use: http://java.sun.com/products/javacomm/javadocs/javax/comm/CommPortIdentifier.html */
       static Enumeration         portList; /* list of all available serial ports */

       public static final String FILENAME = "NMEA.txt";  // file to write output to; full path would be better
       public static final String PORTNAME = "COM5";  // which serial port to use; probably an USB serial device
       public static final int    BAUDRATE = 4800;  // baud rate - NMEA standard
       public static final int    TIMEOUT  = 2000;  //

       /* main program: Create a new GPSReader object and run its mymain method */
       public static void main(String[] args) {

          GpsReader g = new GpsReader();
          g.mymain();              
       }

       /* mymain method - main method of GPSReader class */
       void mymain(){

           /* create/open output file FILENAME = NMEA.TXT */
           try {
              outW = new OutputStreamWriter(
                     new FileOutputStream (FILENAME));
           }
           /* if this fails, issue an error message and exit with error code 1 */
           catch (IOException e) {
              System.err.println("Ficheiro de escrita não aberto\n" + e.toString());
              System.exit(1);
           }

            // find all available communication ports and copy them to port list */
            portList = CommPortIdentifier.getPortIdentifiers();

            // iterate through all ports and check whether it's a serial port
            while (portList.hasMoreElements())
            {
                portId = (CommPortIdentifier) portList.nextElement();
                // if it's a serial port, check whether it's the port specified as PORTNAME (COM5:)
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(PORTNAME)) {

            // yes, it's our port; try to open it and assign name "GarApp"
            try   {sPort = (SerialPort) portId.open("GarApp", TIMEOUT);}
            // no further error handling
            catch (PortInUseException e) {}

            // make the port available as stream to easy further processing
            try   {inputStream = sPort.getInputStream();}
            catch (IOException e) {}

         // assign an event handler - in this case, the SerialEvent method further down.
         // check http://java.sun.com/products/javacomm/javadocs/javax/comm/SerialPortEvent.html
         try   {sPort.addEventListener(this);}
            catch (TooManyListenersException e) {}

            // we're interested only if there's new data available
            sPort.notifyOnDataAvailable(true);
            /* a number of events is not handled, including error events and protocol handling events. This should really be done for
                production quality code.
            */

            // set comm parameters
            try {
               sPort.setSerialPortParams(BAUDRATE,
                              SerialPort.DATABITS_8,
                              SerialPort.STOPBITS_1,
                              SerialPort.PARITY_NONE);
               }
            catch (UnsupportedCommOperationException e) {}
                    }
                }
            }
       // we're done initializing; the event handler will process all data coming from the serial port.
       }

       /* process all serial port events. In this case, write the received data to the NMEA.TXT file. */
       /* Check out http://java.sun.com/products/javacomm/javadocs/javax/comm/SerialPortEvent.html for all events */
       public void serialEvent(SerialPortEvent event) {

          int  newData = 0;
          char mybyte;

          /* a number of events is not handled, including error events and protocol handling events. This should really be done for
              production quality code.
          */

          // we're not interested in BREAK signals or if the output buffer is empty. Code probably isn't necessary since these
          switch(event.getEventType()) {
             case SerialPortEvent.BI:            
             case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;

          // more interesting: if there's new data available
          case SerialPortEvent.DATA_AVAILABLE:
                // while there's more data avilable on the serial port
                while(newData != -1) {

                   // read one byte from the InputStream associated with the serial port
                   try {
                      newData = inputStream.read();

                   // stop if there's no more data
                   if (newData == -1) {break;}
                      // translate into a byte
                      mybyte = (char)newData;

                       // write to file
                      outW.write(mybyte);

                      bcount = bcount + 1;

                      // if the byte is a dollar sign, issue a progress message to the console; for debugging only
                      if(mybyte == '$') {System.out.print("\r"+bcount+" bytes");}

                   // if something goes wrong, issue an error message and exit
                   } catch(IOException ex) {
                      System.err.println(ex);
                      return;
                   }
                }
                break;
          }
       }
    }
    0
     
    LVL 12

    Expert Comment

    by:fulscher
    Btw - just as a side remark: The code indendation looks completely wrong here in EE, but it's fine when you copy/paste the code into an editor.
    J

    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Lean Six Sigma Project Manager Certification

    There are many schools of thought around successful project management, but few as highly regarded as the Six Sigma and Lean methods. With 37 hours of learning, this training will explain concrete processes for increasing efficiency and limiting wasted time and effort.

    I feel like more and more people want to know how to programmatically convert addresses into geospatial locations. So in this article, I will show you how you can do it with Bing Maps. I'm going to use PowerShell, which is a nice scripting language,…
    Introduction This article is designed to assist GIS (Geographic Information System) and GPS (Global Positioning System) developers using ESRI ArcGIS and other spatial information management systems.   For the uninitiated the concept of projectio…
    This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
    This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…

    856 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now