Estartar o Geomidia com classes java

1 resposta
farzac

Boa noite

Um amigo meu me psssou umas classes java porem esta dando um erro, segue as classes abaixo:

10.1.1 GPS

package dk.itu.haas.GPS;

import java.util.Vector;

/**

  • This is the abstract base-class that encapsulates the functionality of a generic GPS-unit.
    
    <em>/
    
    public abstract class GPS {
    
    /</em>* A vector containing references to the objects registered as listeners on this GPS. */
    
    protected Vector GPSlisteners;
    

    /** A vector containing references to the objects registered as listeners for waypoint-data from the GPS.*/
    protected Vector WaypointListeners;

    /** A vector containing references to the objects registered as listeners for transfers from the GPS.

    • A listener can’t be directly add to this group, but will instead be added when it registers for some
    • other data that is being transmitted in transfer-groups.
      */
      protected Vector TransferListeners;
    protected GPS() {
    
    GPSlisteners = new Vector();
    
    WaypointListeners = new Vector();
    
    TransferListeners = new Vector();		
    
    }
    
    /** Adds the specified IGPSlistener to receive data from the GPS. */
    
    public void addGPSlistener(IGPSlistener l) {
    
    // Only allow a listener to be registered once.
    
    if (GPSlisteners.contains(l))
    
    return;
    
    GPSlisteners.add(l);
      return;
    

    }
    /**

    • Adds l to the list of listeners interested in transfer-events.

    • Members of this list can’t be directly added, but have to be added through addition of

    • other listeners.
      
      */
      
      protected void addTransferListener(ITransferListener l) {
      
      // Only allow a listener to be registered once.
      
      if (TransferListeners.contains(l))
      
      return;
      
      TransferListeners.add(l);
      
      return;
      
      }
      

    /**

    • Adds l to the list of listeners interested in waypoint-data.

    • Also adds l to the list of transfer-listeners.
      */
      public void addWaypointListener(IWaypointListener l) {
      // Only allow a listener to be registered once.

      if (WaypointListeners.contains(l))
      return;

      addTransferListener(l);

      WaypointListeners.add(l);
      
      return;				
      
      }
      

    /**

    • Removes the the Waypoint-listener l from the list of Waypoint-listeners.
      */
      public void removeWaypointListener(IWaypointListener l) {
      while (WaypointListeners.removeElement(l)) {}
      return;
      }

    /**

    • Removes the the GPS-listener l from the list of GPS-listeners.
      */
      public void removeGPSListener(IGPSlistener l) {
      while (GPSlisteners.removeElement(l)) {}
      return;
      }

    /**

    • Removes the the transfer-listener l from the list of transfer-listeners.
      */
      protected void removeTransferListener(ITransferListener l) {
      while (TransferListeners.removeElement(l)) {}
      return;
      }

    /**

    • Notifies listeners of the beginning of a stream of data. Tells listeners of the number of
    • data-units in the transfer.
      */
      public void fireTransferStart(int number) {
      for (int i = 0 ; i < TransferListeners.size() ; i++) {
      ((ITransferListener) TransferListeners.elementAt(i)).transferStarted(number);
      }
      }

    /**

    • Goes through the list of Waypoint-listeners and distributes the waypoint wp.
      */
      public void fireWaypointData(IWaypoint wp) {
      for (int i = 0 ; i < WaypointListeners.size() ; i++) {
      ((IWaypointListener) WaypointListeners.elementAt(i)).waypointReceived(wp);
      }
      }

    /**

    • Notifies listeners of the end of a stream of data.
      */
      public void fireTransferComplete() {
      for (int i = 0 ; i < TransferListeners.size() ; i++) {
      ((ITransferListener) TransferListeners.elementAt(i)).transferComplete();
      }
      }

    /**

    • Goes through the list of GPSlisteners and distributes the new position data.
      */
      protected void firePositionData(IPosition pos) {
      for (int i = 0 ; i < GPSlisteners.size() ; i++) {
      ((IGPSlistener) GPSlisteners.elementAt(i)).positionReceived(pos);
      }
      }

    /**

    • Goes through the list of GPSlisteners and distributes the new date data.
      */
      protected void fireDateData(IDate dat) {
      for (int i = 0 ; i < GPSlisteners.size() ; i++) {
      ((IGPSlistener) GPSlisteners.elementAt(i)).dateReceived(dat);
      }
      }

    /**

    • Goes through the list of GPSlisteners and distributes the new time data.
      */
      protected void fireTimeData(ITime time) {
      for (int i = 0 ; i < GPSlisteners.size() ; i++) {
      ((IGPSlistener) GPSlisteners.elementAt(i)).timeReceived(time);
      }
      }

    /** Makes a request for the specified data to the GPS. Data will be returned to all listeners through the IGPSlistener-interface. */
    public abstract void requestPosition();

    /** Makes a request for the specified data to the GPS. Data will be returned to all listeners through the IGPSlistener-interface. */
    public abstract void requestTime();

    /** Makes a request for the specified data to the GPS. Data will be returned to all listeners through the IGPSlistener-interface. */
    public abstract void requestDate();

    /**

    • Requests a descriptive string from the GPS. Should be formatted for human-reading.
    • The string should be constructed by every GPS-implementation upon startup.
      */
      public abstract String getDescription();

    /**

    • Asks the GPS to transmit all the waypoints in it’s memory. The result will be returned through the WaypointListener-interface.
    • Throws a FeatureNotSupportException if it isn’t possible to do this on the GPS.
      */
      public abstract void requestWaypoints();

    /**

    • Asks the GPS to either start or stop transmitting data periodically.
    • The data will be the that which is accessible through the IGPSlistener-interface.
    • Throws a FeatureNotSupportException if it isn’t possible to do this on the GPS.
      */
      public abstract void setAutoTransmit(boolean t);

    /** Stops communication with GPS.

    • Most likely, your program won’t be able to shut down before you’ve called this method.
    • If b is set to true, the GPS will be asked to turn off.
    • If b is set to false, the GPS will remain turned on.
    • Throws a FeatureNotSupportException if b is true, but the GPS-unit doesn’t support that function.
      */
      public abstract void shutdown(boolean b);
      }

10.1.2 IGPSlistener
package dk.itu.haas.GPS;

/**

  • This interface is used to receive notification each time the GPS transmits one of the common data, ie. position, time and date.
  • The GPS does not necessarily transmit these things periodially by itself! Some GPS-units needs a request before
  • transmitting anything. Use the method GPS.setAutoTransmission(true) if you want the GPS to periodically send this data.
  • Don't perform any long calculations or big operations in these methods. They're called by a dispatching thread, and putting
  • it to too much work will slow performance on the communication with the GPS.

*/

public interface IGPSlistener {

/** Invoked when the GPS transmits time-data. <em>/

public void timeReceived(ITime t);

/</em>* Invoked when the GPS transmits date-data. <em>/

public void dateReceived(IDate d);

/</em>* Invoked when the GPS transmits position-data. */

public void positionReceived(IPosition pos);

}

10.1.3 IwaypointListener
package dk.itu.haas.GPS;

public interface IWaypointListener extends ITransferListener {

/**

* This method is called whenever a waypoint is received from the GPS.

*/

public void waypointReceived(IWaypoint wp);

}

10.1.4 ItransferListener
package dk.itu.haas.GPS;

/**

  • The methods in this interface are used whenever the GPS should transfer a series of data.
    /
    public interface ITransferListener {
    /
    *

    • This method is called when a transfer is initiated.
    • Number is the amount of data that will be transferred, ie. the amount of waypoints.
    • If it’s not possible to tell how much data that will be transferred, number will be -1.
      */
      public void transferStarted(int number);

    /**

    • This method is called when the transfer is complete.
      */
      public void transferComplete();
      }
      10.1.5 IPosition
      package dk.itu.haas.GPS;

/**

  • This interface is implemented by all packets capable of returning a position.
    /
    public interface IPosition {
    /
    *

    • This method returns the latitude of the position.
      */
      public PositionRadians getLatitude();

    /**

    • This method returns the longitude of the position.
      */
      public PositionRadians getLongitude();
      };
      10.1.6 ITime
      package dk.itu.haas.GPS;

/**

  • This interface is implemented by all packets capable of returning the time of day.
    
    <em>/
    
    public interface ITime {
    
    /</em>* Returns the hour of the day. */
    
    public int getHours();
    

    /** Returns the minute of the hour. */
    public short getMinutes();

    /** Returns the second of the minute. */
    
    public short getSeconds();	
    
    };
    

10.1.7 IDate
package dk.itu.haas.GPS;

/**

  • This interface is implemented by all packets capable of returning a date.
    
    <em>/
    
    public interface IDate {
    
    /</em>* Returns the day of the month. */
    
    public short getDay();
    

    /** Returns the month. */
    public short getMonth();

    /** returns the year. */
    
    public int getYear();	
    
    };
    

10.1.8 IWaypoint
package dk.itu.haas.GPS;

public interface IWaypoint extends IPosition {

public String getName();

}

10.1.9 Position
package dk.itu.haas.GPS;

/**

  • This is a class meant for containing positions.
    */

public class Position implements IPosition {
private PositionRadians lat, lon;

/**
* Makes a new position. Initializes the latitude and the longitude to 0.
*/
public Position() {
	this(0,0);
}

/** 
* Initializes the Position with la as the latitude and lo as the longitude.
*/
public Position(double la, double lo) {
	lat = new PositionRadians(la);
	lon = new PositionRadians(lo);
}

/**
* Initializes the position object from an IPosition reference.
*/
public Position(IPosition pos) {
	lat = pos.getLatitude();
	lon = pos.getLongitude();
}

/**
* Sets the latitude of this position.
*/
public void setLatitude(PositionRadians l) {
	lat = l;
}

/**
* Sets the longitude of this position.
*/
public void setLongitude(PositionRadians l) {
	lon = l;
}

/**
* Returns the latitude of this position.
*/
public PositionRadians getLatitude() {
	return lat;
}

/**
* Returns the longitude of this position.
*/
public PositionRadians getLongitude() {
	return lon;
}

}

10.1.10 PositionDegrees
package dk.itu.haas.GPS;

/**

  • Class used to store degrees, usually latitude or longitude.
    */

public class PositionDegrees {
protected double value;

public PositionDegrees(double v) {
	value = v;
}

/**
* Returns the degrees part of this object, when converted to coordinates.
*/		
public int getDegrees() {
	return (int) value;	
}

/**
* Converts the degrees to Radians. 
*/
public PositionRadians convertToRadians() {
	return new PositionRadians(( value * Math.PI ) / 180.0d);
}

/**
* Returns the minutes part of this object, when converted to coordinates.
*/	
public double getMinutes() {
	double v = value;
	v -= getDegrees();
	return 60 * v; // 60 minutes in one degree.
}

}

10.1.11 PositionRadians
package dk.itu.haas.GPS;

/**

  • Class used to store radians, usually latitude or longitude.

  • Contains methods for converting to the format degress,minutes.
    
    */
    
    public class PositionRadians {
    
    private double value;
    

    /**

    • Initializes the PositionRadians-object. After the object is constructed, it can’t change is value.
      */
      public PositionRadians(double v) {
      value = v;
      }
    public double getRadians() {
    
    return value;
    
    }
    

    /**

    • Returns the degrees part of this object, when converted to coordinates.
      */
      public int getDegrees() {
      return (int) (value * (180.0d / Math.PI));
      }

    /**

    • Returns the minutes part of this object, when converted to coordinates.
      */
      public double getMinutes() {
      double v = value * (180.0d / Math.PI);
      v -= getDegrees();
      return 60 * v; // 60 minutes in one degree.
      }

    /**

    • Returns the value of this object in degrees and minutes.
      */
      public String toString() {
      return getDegrees() + “:” + getMinutes() + “”;
      }

    /**

    • Tests if the two PositionRadians contains the same value.
      */
      public boolean equals(PositionRadians p) {
      if (value == p.value)
      return true;
      else
      return false;
      }

    /**

    • Tests if this PositionRadians is greater than p.
      */
      public boolean greaterThan(PositionRadians p) {
      if (value > p.value)
      return true;
      else
      return false;
      }

    /**

    • Tests if this PositionRadians is smaller than p.
      */
    public boolean smallerThan(PositionRadians p) {
    
    if (value < p.value)
    
    return true;
    
    else
    
    return false;
    
    }	
    
    }
    

10.1.12 FeatureNotSupportedException
package dk.itu.haas.GPS;

/**

  • Thrown by methods in classes extending the GPS-class, if the implemented GPS-unit does not support the feature
  • requested in the method.
    /
    public class FeatureNotSupportedException extends RuntimeException {
    }
    10.2 dk.itu.haas.GPS.Garmin ? package
    10.2.1 GarminGPS
    package dk.itu.haas.GPS.Garmin;
    import dk.itu.haas.GPS.
    ;
    import java.io.*;
    import java.util.Vector;
public class GarminGPS extends GPS implements Runnable {

GarminInputStream input;

GarminOutputStream output;
/** A human-readable description of the GPS-unit. */ 
protected String description;

Thread listener;
/** The listening thread will be active as long as this variable remains true. */
protected boolean active; 
/** A vector containing references to all the GarminListeners. */
protected Vector GarminListeners;

/** */ 
public GarminGPS(BufferedInputStream i, BufferedOutputStream o) {
	input = new GarminInputStream(i);
	output = new GarminOutputStream(o);
	listener = new Thread(this);
	listener.start();
	active = true;
	GarminListeners = new Vector();
	
	// Request product information. 
	try {
	  output.write(GarminPacket.createBasicPacket(GarminPacket.Pid_Product_Rqst, new int[] {}));
	} catch(IOException e) {}
}


/**
* Adds the specified GarminListener to receive all packets sent from the GPS. 	
*/
public void addGarminListener(GarminListener l) {
	// Only allow a listener to be registered once.
	if (GarminListeners.contains(l))
		return;
		
	GarminListeners.add(l);
	return;
}

/**
* Removes the specified GarminListener from the list of listeners.
*/ 
public void removeGarminListener(GarminListener l) {
	while (GarminListeners.removeElement(l)) {}
	return;
}

/** 
* Goes through the list of GarminListeners and transmits p to them.
*/	
protected void fireGarminPacket(GarminPacket p) {
	for (int i = 0 ; i < GarminListeners.size() ; i++) {
		((GarminListener) GarminListeners.elementAt(i)).GarminPacketReceived(p);
	}	
}

/** This method is listening for input from the GPS. */ 
public void run() {
	GarminPacket pack = null;		

	while (active) {
		try {
			if (input.available() == 0) {
				try {
					Thread.sleep(500);
				} catch(InterruptedException e) {}
				continue;
			}
			pack = new GarminPacket(input.readPacket());				
		} catch (IOException e) {
			active = false;				
			return;
		} catch (InvalidPacketException e) {
			// Send back a NAK-packet.
			try {
			  output.write( GarminPacket.createBasicPacket(GarminPacket.Pid_Nak_Byte, new int[] {pack.getID(), 0}));
			} catch (IOException ex) {
				active = false;
				return;
			}
		}
		
		// Send back ACK-packet.
		try {
		  output.write( GarminPacket.createBasicPacket(GarminPacket.Pid_Ack_Byte, new int[] {pack.getID(), 0}));
		} catch (IOException e) {
			active = false;
		}

		fireGarminPacket(pack);
		Distribute(pack);
		
	} // End of while
}

/** This method is used to identify the type of packet received, and distribute it to the correct 
* listeners. 
*/
protected void Distribute(GarminPacket p) {		
	switch (p.getID()) {
		case GarminPacket.Pid_Position_Data :
			firePositionData(new PositionDataPacket(p));
			return;
		case GarminPacket.Pid_Date_Time_Data :
			TimeDataPacket tdp = new TimeDataPacket(p);
			fireDateData(tdp);
			fireTimeData(tdp);
			return;
		case GarminPacket.Pid_Pvt_Data :
			PVTDataPacket pvtp = new PVTDataPacket(p);		
			fireTimeData(pvtp);
			firePositionData(pvtp);
			return;				
		case GarminPacket.Pid_Records :
			fireTransferStart((new RecordsPacket(p)).getNumber());
			return;
		case GarminPacket.Pid_Wpt_Data : 
			fireWaypointData( new WaypointDataPacket(p));
			return;
		case GarminPacket.Pid_Xfer_Cmplt :
			fireTransferComplete();
			return;
		case GarminPacket.Pid_Product_Data :
			System.out.println("Product data arrived!");
			ProductDataPacket pp = new ProductDataPacket(p);
			description = pp.getDescription();
			description += "\nSoftware version: " + pp.getSWVersion();
			description += "\nProduct ID: " + pp.getProductID();
			return;
		case GarminPacket.Pid_Protocol_Array :
			description += "\nProtocols supported:\n";
			description += (new ProtocolDataPacket(p)).toString();
			return;
		default :
			return;
	}
}

/** Makes a request for the specified data to the GPS. Data will be returned to all listeners through the IGPSlistener-interface. */
public void requestPosition() {
	try {
		output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Transfer_Posn));
	} catch (IOException e) {}
}
/** Makes a request for the specified data to the GPS. Data will be returned to all listeners through the IGPSlistener-interface. */
public void requestTime() {
	try {
		output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Transfer_Time));
	} catch (IOException e) {}		
}

/** Makes a request for the specified data to the GPS. Data will be returned to all listeners through the IGPSlistener-interface. */
public void requestDate() {
	try {
		output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Transfer_Time));
	} catch (IOException e) {}		
}

/** 
* Asks the GPS to transmit all the waypoints in it's memory. The result will be returned through the WaypointListener-interface. 
*/
public void requestWaypoints() {
	try {
		output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Transfer_Wpt));
	} catch (IOException e) {}
}
		
/** 
* Asks the GPS to either start or stop transmitting data periodically. <br/>
* The data will be that which is accessible through the IGPSlistener-interface. 
* Throws a FeatureNotSupportException if it isn't possible to do this on the GPS.
*/
public void setAutoTransmit(boolean t) {
	if (t) {
		try {
		output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Start_Pvt_Data));
		} catch (IOException e) {}		
	} else {
		try {
			output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Stop_Pvt_Data));
		} catch (IOException e) {}					
	}
}

/** Stops communication with GPS.<br/>
* Most likely, your program won't be able to shut down before you've called this method. 
* If b is set to true, the GPS will be asked to turn off.	
* If b is set to false, the GPS will remain turned on.
*/
public void shutdown(boolean b) {
	if (b) { 
		try {
			output.write( GarminPacket.createCommandPacket(GarminPacket.Cmnd_Turn_Off_Pwr));
		} catch (IOException e) {}
	}
	active = false;		
}

/** 
* Returns a string telling the brand of the Garmin-gps, software version and the protocols supported.
*/ 
public String getDescription() {
	return description;
}

}

10.2.2 GarminPacket

package dk.itu.haas.GPS.Garmin;

import dk.itu.haas.GPS.*;

/**
  • A class that encapsulates the basic functionality of a packet.
    
    */
    
    public class GarminPacket {
    
    // L000 values. (Names taken from protocol specification.)
    
    public static final int Pid_Ack_Byte = 6;
    
    public static final int Pid_Nak_Byte = 21;
    
    public static final int Pid_Protocol_Array = 253;
    
    public static final int Pid_Product_Rqst = 254;
    
    public static final int Pid_Product_Data = 255;
    
    // L001 values.
    
    public static final int Pid_Command_Data = 10;
    
    public static final int Pid_Xfer_Cmplt = 12;
    
    public static final int Pid_Date_Time_Data = 14;	
    
    public static final int Pid_Position_Data = 17;
    
    public static final int Pid_Records = 27;
    
    public static final int Pid_Wpt_Data = 35;
    
    public static final int Pid_Pvt_Data = 51;
    
    // A010 - Device Command Protocol.
    
    /** Abort current transfer. <em>/
    
    public static final int Cmnd_Abort_Transfer = 0;
    
    /</em>* Transfer almanac. <em>/
    
    public static final int Cmnd_Transfer_Alm 	= 1;	
    
    /</em>* Transfer position. <em>/
    
    public static final int Cmnd_Transfer_Posn 	= 2;
    
    /</em>* Transfer proximity waypoints. <em>/
    
    public static final int Cmnd_Transfer_Prx 	= 3;
    
    /</em>* Transfer routes. <em>/
    
    public static final int Cmnd_Transfer_Rte	= 4;
    
    /</em>* Transfer time. <em>/
    
    public static final int Cmnd_Transfer_Time 	= 5;	
    
    /</em>* Transfer track log. <em>/
    
    public static final int Cmnd_Transfer_Trk	= 6;
    
    /</em>* Transfer waypoints. <em>/
    
    public static final int Cmnd_Transfer_Wpt	= 7;
    
    /</em>* Turn off power. <em>/
    
    public static final int Cmnd_Turn_Off_Pwr 	= 8;	
    
    /</em>* Start transmitting PVT (Position, velocity, time) Data. <em>/
    
    public static final int Cmnd_Start_Pvt_Data = 49;
    
    /</em>* Stop transmitting PVT (Position, velocity, time) Data. */
    
    public static final int Cmnd_Stop_Pvt_Data	= 50;
    

    // Packet Boundaries.
    /**

    • Data link escape. Packet boundary.
      /
      public static final int DLE = 16;
      /
      *
    • End of text. Packet boundary.
      */
      public static final int ETX = 3;

    /**

    • The packet in byte-form.
    • It is required that the array-length is trimmed to the size of the packet.
      */
      protected int[] packet;

    /**

    • Creates a new GarminPacket with the contents of p.
    • Throws InvalidPacketException if packet is malformed.
      */
      public GarminPacket(int[] p){
      this(p, false);
      }

    /**

    • Creates a new GarminPacket with the contents of p.
    • if calcChecksum is true, the packet will have it’s checksum recalculated.
    • Throws InvalidPacketException if packet is malformed.
      */

    public GarminPacket(int[] p, boolean calcChecksum) {
    packet = (int[]) p.clone();

    if (calcChecksum) {
      	packet[packet.length - 3] = calcChecksum();
      }
      
      if (isLegal() != -1) {
      	System.out.println("Error in byte: " + isLegal());
      	throw (new InvalidPacketException(p, isLegal()));
      }
    

    }

    /**

    • Calculates the checksum for the packet.

    • Does not insert it into the correct position of the int[] packet array.

    • The method assumes that the packet is a valid Garmin-packet with all values containing their final

    • values.
      
      */	
      
      public int calcChecksum() {
      
      int sum = 0;
      
      for (int i = 1 ; i <= packet.length - 4 ; i++) {
      
      sum += packet[i];		
      
      }
      
      sum = sum % 256;
      
      sum = sum ^ 255;						
      
      sum += 1;
      
      return sum;	
      
      }
      

    /**

    • Returns the ID (ie. type) of the packet.
      */
      public int getID() {
      return packet[1];
      }

    /**

    • Returns the amount of bytes in the data-field of this packet.
      */
      public int getDataLength() {
      return packet[2];
      }

    /**

    • Returns the packet-byte at position i.
      */
      protected int getByte(int i) {
      return packet[i];
      }

    /**

    • Returns the packet in it’s original byte-form.

    • Note: The array returned is a clone of the array contained in the class.
    • Changing the values in the array will not affect the contents of the class.
      */
      protected int[] getPacket() {
      return (int[]) packet.clone();
      }

    /**

    • Returns the length of the entire packet in bytes.
      */
      protected int getLength() {
      return packet.length;
      }

    /**

    • Method that reads a Garmin-word in the packet and returns it as an int.
    • This method can be used to read both int and word from a Garmin-packet.
      */
      protected int readWord(int packet_index) {
      int sum = packet[packet_index++];
      sum += packet[packet_index++] << 8;
      return sum;
      }

    /**

    • Method that reads a Garmin-long in the packet and returns it as an int.
      
      */ 	
      
      protected int readLong(int packet_index) {
      
      int res = packet[packet_index++];
      
      res += packet[packet_index++] << 8;
      
      res += packet[packet_index++] << 16;
      
      res += packet[packet_index++] << 24;
      

      return res;
      }

    /**

    • Method that reads a null-terminated string.
      
      */
      
      protected String readNullTerminatedString(int packet_index) {
      
      StringBuffer res = new StringBuffer(20);
      
      while ((packet[packet_index] != 0) && (packet_index != packet.length )) {
      
      res.append( (char) packet[packet_index++]);
      
      }
      
      return res.toString();
      
      }
      

    /**

    • Method that translates a packet-id into a human-readable string.
      */
      public static String idToString(int id) {
      switch (id) {
      case Pid_Ack_Byte :
      return “Acknowledge packet”;
      case Pid_Command_Data :
      return “Command packet”;
      case Pid_Date_Time_Data :
      return “Date and time data”;
      case Pid_Nak_Byte :
      return “Not acknowledged packet”;
      case Pid_Product_Data :
      return “Product data.”;
      case Pid_Product_Rqst :
      return “Product request”;
      case Pid_Protocol_Array :
      return “Protocol array packet”;
      case Pid_Position_Data :
      return “position data”;
      case Pid_Pvt_Data :
      return “PVT data”;
      case Pid_Records :
      return “Start of record transfer”;
      case Pid_Wpt_Data :
      return “waypoint data”;
      default :
      return “unknown data”;
      }
      }

    /**

    • Debug-method.
    • Returns a String-representation of the bytes in the packet.
      */
      public String getRawPacket() {
      StringBuffer s = new StringBuffer();
      for (int i = 0 ; i < packet.length ; i++)
      s.append(" " + packet[i]);
      return s.toString();
      }

    /**

    • This is a factory-method capable of creating instances the commandpackets from A010. (Device Command Protocol 1)
    • returns null if it can’t make a packet from the argument supplied.

    • type can be one of the following constants:
    • Cmnd_Turn_Off_Pwr
    • Cmnd_Transfer_Posn
    • Cmnd_Transfer_Time
    • Cmnd_Abort_Transfer
    • Cmnd_Transfer_Alm
    • Cmnd_Transfer_Prx
    • Cmnd_Transfer_Rte
    • Cmnd_Transfer_Trk
    • Cmnd_Transfer_Wpt
    • Cmnd_Start_Pvt_Data
    • Cmnd_Stop_Pvt_Data
*/

public static GarminPacket createCommandPacket(int type) {

switch (type) {

case Cmnd_Turn_Off_Pwr :

case Cmnd_Transfer_Posn:

case Cmnd_Transfer_Time:

case Cmnd_Abort_Transfer :

case Cmnd_Transfer_Alm :

case Cmnd_Transfer_Prx :

case Cmnd_Transfer_Rte :

case Cmnd_Transfer_Trk :

case Cmnd_Transfer_Wpt :

case Cmnd_Start_Pvt_Data :

case Cmnd_Stop_Pvt_Data	:

return new GarminPacket(new int[] {DLE, Pid_Command_Data, 2, type,0 , 0, DLE, ETX}, true);

default :			

return null;

}

}

/**

  • This method is capable of making the data-packets from L000 (basic link protocol).

  • type can be one of the following constants:
  • Pid_Ack_Byte
  • Pid_Nak_Byte
  • Pid_Protocol_Array
  • Pid_Product_Rqst
  • Pid_Product_Data
  • The argument data is an array of int that will be put in the data-field of the packet.
    */
    public static GarminPacket createBasicPacket(int type, int[] data) {
    switch (type) {
    case Pid_Ack_Byte :
    case Pid_Nak_Byte :
    case Pid_Protocol_Array :
    case Pid_Product_Rqst:
    case Pid_Product_Data :
    int[] packet = new int[data.length + 6];
    packet[0] = DLE; packet[1] = type;
    packet[2] = data.length;
    System.arraycopy(data, 0, packet, 3, data.length);
    packet[packet.length - 3] = 0;
    packet[packet.length - 2] = DLE;
    packet[packet.length - 1] = ETX;
    return new GarminPacket(packet, true);
    default :
    return null;
    }
    }
  • /**

    • Checks if the packet is valid with regards to header, footer,data-field-length and checksum.

    • Returns the index of the illegal byte. If packet is ok, -1 is returned.
      
      */
      
      public int isLegal() {
      
      if (packet[0] != DLE)
      
      return 0;
      

      int size = packet[2];

      if (size + 6 != packet.length)
      return 2;

      if ( packet[packet.length - 3] != calcChecksum() )
      return packet.length - 3;

      if ( packet[packet.length - 2] != DLE )
      return packet.length - 2;

      if ( packet[packet.length - 1] != ETX )
      return packet.length - 1;

      return -1;
      }

    /**

    • Method that reads a Garmin-byte in the packet and returns it as a short.
      */
      protected short readByte(int packet_index) {
      return (short) packet[packet_index];
      }

    /**

    • Method that reads a Garmin-double in the packet and returns it as a double.
      
      */
      
      protected double readDouble(int packet_index) {								
      
      long res = 0;
      
      res += ( (long) packet[packet_index++] );
      
      res += ( (long) packet[packet_index++] ) << 8;
      
      res += ( (long) packet[packet_index++] ) << 16;
      
      res += ( (long) packet[packet_index++] ) << 24;
      
      res += ( (long) packet[packet_index++] ) << 32;
      
      res += ( (long) packet[packet_index++] ) << 40;
      
      res += ( (long) packet[packet_index++] ) << 48;
      
      res += ( (long) packet[packet_index++] ) << 56;
      

      return Double.longBitsToDouble(res);
      }

    /**

    • Returns a human-readable string with information to the packet’s contents.
      */
    public String toString() {
    
    return "GarminPacket containing " + idToString(getID());
    
    }
    

    /**

    • Method that reads a Garmin-float in the packet and returns it as a float.
      
      */	
      
      protected float readFloat(int packet_index) {
      
      int res = 0;
      
      res += packet[packet_index++];
      
      res += packet[packet_index++] << 8;
      
      res += packet[packet_index++] << 16;
      
      res += packet[packet_index++] << 24;
      

      return Float.intBitsToFloat(res);
      }

    }

    10.2.3 PositionDataPacket

    package dk.itu.haas.GPS.Garmin;

    import dk.itu.haas.GPS.*;

    public class PositionDataPacket extends GarminPacket implements IPosition{
    private PositionRadians lat, lon;

    /**
    * Treats the packet p as a packet containing position-data.
    * Throws PacketNotRecognizedException if p is not a position-data-packet.
    * Throws InvalidPacketException if the packet contains too little data.
    */
    public PositionDataPacket(int[] p) {
    	super(p);
    	if (getID() != Pid_Position_Data) {
    		throw(new PacketNotRecognizedException(Pid_Position_Data, getID()));
    	}
    	
    	if (getDataLength() != 16) {
    		throw(new InvalidPacketException(packet, 2));
    	}
    	
    	lat = new PositionRadians(readDouble(3));
    	lon = new PositionRadians(readDouble(11));
    }	
    
    /** 
    * This method is a copy-constructor allowing to "upgrade" a GarminPacket to a PositionPacket.
    * Throws PacketNotRecognizedException if p is not a position-data-packet.
    */	
    public PositionDataPacket(GarminPacket p) {
    	this( p.packet );		
    }
    
    /**
    * This method returns the latitude of the position.
    */
    public PositionRadians getLatitude() {
    	return lat;
    }
    
    /**
    * This method returns the longitude of the position.
    */
    public PositionRadians getLongitude() {
    	return lon;
    }
    
    /**
    * Returns a String containing the position in a human-readable format.
    */
    public String toString() {
    	StringBuffer res = new StringBuffer();
    	res.append("\nPosition:");
    	res.append("\nLatitude: " + lat.toString());
    	res.append("\nLongitude: " + lon.toString());		
    	return res.toString();
    }
    

    }

    10.2.4 PVTDataPacket
    
    package dk.itu.haas.GPS.Garmin;
    
    import dk.itu.haas.GPS.*;
    
    /**
    
    • This class encapsulates the PVT (Position, velocity and time) packet.
    • After receiving a Cmnd_Start_Pvt-packet, the GPS will continually transmit
    • packets of the PVT-type.
      */

    public class PVTDataPacket extends GarminPacket implements IPosition, ITime {

    protected float alt; 			// Altitude
    protected float epe; 			// Estimated position error
    protected float eph; 			// Horizontal epe
    protected float epv; 			// Vertical epe
    protected int fix;			 	// Position fix
    protected double  tow;		 	// Time of week (seconds).
    protected PositionRadians lat;	// Latitude
    protected PositionRadians lon; 	// Longitude
    protected float veast; 		 	// Velocity east.
    protected float vnorth;		 	// Velocity north.
    protected float vup;			// Velocity up.
    protected float msl_hght;		// 
    protected int leap_scnds;		// Time difference between GPS and GMT (UTC)
    protected long wn_days;		 	// Week number days. 
    
    /**
    * Treats the packet p as a packet containing PVT-data.
    * Throws PacketNotRecognizedException if p is not a PVT-packet.
    * Throws InvalidPacketException if the packet contains too little data.
    */	
    public PVTDataPacket(int[] p) {
    	super(p);
    	
    	if (getID() != Pid_Pvt_Data) {
    		throw(new PacketNotRecognizedException(Pid_Pvt_Data, getID()));
    	}
    	
    	if (getDataLength() != 64) {
    		throw(new InvalidPacketException(packet, 2));
    	}
    			
    	alt = readFloat(3);
    	epe = readFloat(7);
    	eph = readFloat(11);
    	epv = readFloat(15);
    	fix = readWord(19);
    	tow = readDouble(21);
    	lat = new PositionRadians( readDouble(29));
    	lon = new PositionRadians( readDouble(37));
    	veast = readFloat(45);
    	vnorth = readFloat(49);
    	vup = readFloat(53);
    	msl_hght = readFloat(57);
    	leap_scnds = readWord(61);
    	wn_days = readLong(63);
    }
    
    /** 
    * This method is a copy-constructor allowing to "upgrade" a GarminPacket to a PVTDataPacket.
    * Throws PacketNotRecognizedException if p is not a PVT-data-packet.
    */	
    public PVTDataPacket(GarminPacket p) {
    	this( p.packet );		
    }
    
    
    /** Returns the hour of the day. */
    public int getHours() {
    	int hour = (int) tow;
    	hour = hour % (24 * 60 * 60); // Remove all preceding days.
    	hour = hour / 3600;
    	return hour;
    }
    
    /** Returns the minute of the hour. */
    public short getMinutes() {
    	int minute = (int) tow;
    	minute = minute % (24 * 60 * 60); // Remove all preceding days.
    	minute = minute / 60;
    	minute = minute % 60;
    	return (short) minute;
    }
    
    /** Returns the second of the minute. */
    public short getSeconds() {
    	return (short) (tow % 60);
    }	
    
    /**
    * This method returns the latitude of the position.
    */
    public PositionRadians getLatitude() {
    	return lat;
    }
    
    /**
    * This method returns the longitude of the position.
    */
    public PositionRadians getLongitude() {
    	return lon;
    }
    

    }

    10.2.5 TimeDataPacket
    package dk.itu.haas.GPS.Garmin;

    import dk.itu.haas.GPS.*;

    /**

    • This class encapsulates the information of a Garmin-Date-Time-packet.
      */
    public class TimeDataPacket extends GarminPacket implements ITime, IDate{
    
    /** Month (1-12) <em>/
    
    protected short month; 	
    
    /</em>* Day (1-31) <em>/
    
    protected short day;
    
    /</em>* Year. <em>/
    
    protected int year;
    
    /</em>* Hour of the day. <em>/
    
    protected int hour;
    
    /</em>* Minute of the hour. <em>/
    
    protected short minute;
    
    /</em>* Second of the minute. */
    
    protected short second;
    
    /**
    * Treats the packet p as a packet containing Time-data.
    * Throws PacketNotRecognizedException if p is not a Time-packet.
    * Throws InvalidPacketException if the packet contains too little data.
    */	
    public TimeDataPacket (int[] p) {
    	super(p);
    	
    	if (getID() != Pid_Date_Time_Data) {
    		throw(new PacketNotRecognizedException(Pid_Date_Time_Data, getID()));
    	}		
    	
    	if (getDataLength() != 8) {
    		throw(new InvalidPacketException(packet, 2));
    	}
    	
    	month = readByte(3);
    	day = readByte(4);
    	year = readWord(5);
    	hour = readWord(7);
    	minute = readByte(9);
    	second = readByte(10);
    }
    
    /**
    * Treats the packet p as a packet containing Time-data.
    * Throws PacketNotRecognizedException if p is not a Time-packet.
    * Throws InvalidPacketException if the packet contains too little data.
    */	
    public TimeDataPacket (GarminPacket p) {
    	this(p.packet);
    }
    
    /** Returns the day of the month. */
    public short getDay() {
    	return day;
    }
    
    /** Returns the month. */
    public short getMonth() {
    	return month;
    }
    
    /** returns the year. */
    public int getYear() {
    	return year;
    }
    
    /** Returns the hour of the day. */
    public int getHours() {
    	return hour;
    }
    
    /** Returns the minute of the hour. */
    public short getMinutes() {
    	return minute;
    }
    
    /** Returns the second of the minute.*/
    public short getSeconds() {
    	return second;
    }
    
    /**
    * Returns the value of this packet in a human-readable format.
    */
    public String toString() {
    	StringBuffer res = new StringBuffer();
    	if (hour < 10)
    		res.append("0");
    	res.append(hour +":");
    	if (minute < 10)
    		res.append("0");
    	res.append(minute +":");
    	if (second < 10)
    		res.append("0");			
    	res.append(second + " on ");
    	res.append(day + "/");
    	res.append(month + "-" + year);
    	return res.toString();
    }
    

    }

    10.2.6 WaypointDataPacket
    package dk.itu.haas.GPS.Garmin;

    import dk.itu.haas.GPS.*;

    /**

    • This class encapsulates a Waypoint-packet. The Garmin-protocol contains a huge amount of different

    • Waypoint-Packet specifications. Only the one labelled D108 is implemented so far.
      /
      public class WaypointDataPacket extends GarminPacket implements IWaypoint{
      /
      *

      • Holds information about which waypoint-format this Garmin-unit uses. The default is 108.
        */
        protected static int datatypeversion = 108;
      /** Class of waypoint. <em>/
      
      protected short wpt_class;
      
      /</em>* Color of waypoint when displayed on the GPS.<em>/
      
      protected short color;
      
      /** Display options.</em>/
      
      protected short dspl;
      
      /** Attributes. <em>/
      
      protected short attr;
      
      /</em>* Waypoint symbol. <em>/
      
      protected int smbl;
      
      /</em>* Subclass of waypoint <em>/
      
      protected short[] subclass;
      
      /</em>* Latitude of waypoint. <em>/
      
      protected PositionDegrees lat;
      
      /</em>* Longitude of waypoint. <em>/
      
      protected PositionDegrees lon;
      
      /</em>* Altitude. <em>/
      
      protected float alt;
      
      /</em>* Depth. <em>/
      
      protected float depth;
      
      /</em>* Proximity distance in meters. <em>/
      
      protected float dist;
      
      /</em>* State.<em>/
      
      protected char[] state;
      
      /** Country code.</em>/
      
      protected char[] cc;
      
      /** Waypoint name. <em>/
      
      protected String name;
      
      /</em>* Waypoint comment. <em>/
      
      protected String comment;
      
      /</em>* facility name. <em>/
      
      protected String facility;
      
      /</em>* City name. <em>/
      
      protected String city;
      
      /</em>* Address number <em>/
      
      protected String address;
      
      /</em>* Intersecting road label.*/
      
      protected String cross_road;
      

      /**

      • Throws a PacketNotRecognizedException if the Waypoint-dataformat is not implemented.
        */

      public WaypointDataPacket(int[] p) {
      super§;

      if (getID() != Pid_Wpt_Data) {			
        	throw(new PacketNotRecognizedException(Pid_Wpt_Data, getID()));
        }		
        
        switch (datatypeversion) {
        	case 108 :
        		initD108();
        		break;
        	default :
        		System.out.println("Waypoint-type " + datatypeversion + " not supported.");
        		throw(new PacketNotRecognizedException(Pid_Wpt_Data, getID()));
        }
      

      }

      public WaypointDataPacket(GarminPacket p) {
      
      this( (int[]) p.packet.clone() );
      
      }
      

      /**

      • Configures this packet as a D108 (Waypoint).
        */
        private void initD108() {
        long l;
        l = readLong(27);
        // Calculate from semicircles to degrees.
        lat = new PositionDegrees( (l * 180) / Math.pow(2.0d, 31.0d) );
        l = readLong(31);
        lon = new PositionDegrees( (l * 180) / Math.pow(2.0d, 31.0d) );
        name = readNullTerminatedString(49);
        }

      /**

      • Sets which version of the packet that this class should treat.

      • Note: Setting this value will affect all instances of the class.
        */
        public static void setDatatypeVersion(int v) {
        datatypeversion = v;
        }

      /**

      • This method returns the latitude of the waypoint.
        */
        public PositionRadians getLatitude() {
        return lat.convertToRadians();
        }

      /**

      • This method returns the longitude of the waypoint.
        */
        public PositionRadians getLongitude() {
        return lon.convertToRadians();
        }

      /**

      • This method returns the name of the waypoint.
        */
        public String getName() {
        return name;
        }
        }

    10.2.7 ProductDataPacket

    package dk.itu.haas.GPS.Garmin;

    public class ProductDataPacket extends GarminPacket {	
    
    /** Product-ID of GPS. <em>/
    
    protected int productID;
    
    /</em>* Software version in GPS.*/
    
    protected int SWversion;
    
    /** Description of GPS as given by GPS. */
    
    protected String productDesc;
    
    /**
    * Treats the packet p as a packet containing product-data.
    * Throws PacketNotRecognizedException if p is not a product-data-packet.
    */
    public ProductDataPacket(int[] p) {
    	super(p);
    	if (getID() != Pid_Product_Data) {
    		throw(new PacketNotRecognizedException(Pid_Product_Data, getID()));
    	}		
    	
    	productID = readWord(3);
    	SWversion = readWord(5);
    	productDesc = readNullTerminatedString(7);
    }
    
    /** 
    * This method is a copy-constructor allowing to "upgrade" a GarminPacket to a ProductDataPacket.
    * Throws PacketNotRecognizedException if p is not a product-data-packet.
    */	
    public ProductDataPacket(GarminPacket p) {
    	this( p.packet );		
    }
    
    
    /** Returns the product ID of the GPS.*/
    public int getProductID() {
    	return productID;		
    }
    
    /** Returns the version of the software in the GPS. */
    public int getSWVersion() {
    	return SWversion;
    }
    
    /** Returns the supplied description of the GPS. */ 
    public String getDescription() {
    	return productDesc;
    }	
    /** Returns a human-readable version of this packet. */
    public String toString() {
    	StringBuffer res = new StringBuffer();
    	res.append(productDesc + '\n');
    	res.append("Product ID: " + productID);
    	res.append("\nSoftware version: " + SWversion);
    	return res.toString();
    }
    

    }
    package dk.itu.haas.GPS.Garmin;

    10.2.8 ProtocolDataPacket
    public class ProtocolDataPacket extends GarminPacket {

    protected char[] tags;
    protected int[]  data;
    
    /**
    * Treats the packet p as a packet containing data about which protocols the GPS support.
    * Throws PacketNotRecognizedException if p is not a product-data-packet.
    */		
    public ProtocolDataPacket(int[] p) {
    	super(p);
    	if (getID() != Pid_Protocol_Array) {
    		throw(new PacketNotRecognizedException(Pid_Protocol_Array, getID()));
    	}		
    	
    	if (getDataLength() % 3 != 0) {
    		throw(new InvalidPacketException(packet, 2));				
    	}
    	
    	tags = new char[getDataLength() / 3];
    	data = new int[getDataLength() / 3];
    	
    	int packet_index = 3;
    	int array_index = 0;
    	while (packet_index != getDataLength() + 3) {
    		tags[array_index] = (char) readByte(packet_index++);
    		data[array_index] = readWord(packet_index);
    		packet_index += 2;
    		array_index++;
    	}		
    }
    
    public ProtocolDataPacket(GarminPacket p) {
    	this(p.packet);
    }
    
    /**
    * This method will return the exact version of a protocol.
    * If the protocol is not supported by the GPS, the method returns -1.
    */ 
    public int getVersion(char tag, int protocol) {
    	for (int i = 0 ; i < tags.length ; i++) {
    		if (tags[i] == tag) {
    			if ( data[i] / protocol == 1)
    				return data[i];
    		}
    	}
    	return -1;
    }
    
    public String toString() {
    	StringBuffer res = new StringBuffer();
    	res.append("Tag:\tData:\n");
    	for (int i = 0 ; i < tags.length ; i++) {
    		res.append(tags[i] + "\t" + data[i] + '\n');
    	}
    	return res.toString();
    }
    

    }

    10.2.9 RecordsPacket
    package dk.itu.haas.GPS.Garmin;

    /**

    • This packet is transmitted between devices before a large transfer of data-units, ie. a transfer of waypoints.
    <em>/
    
    public class RecordsPacket extends GarminPacket {
    
    /</em>* The number of records to come, that this packet announces. */
    
    protected int number;
    
    public RecordsPacket(int[] p) {
    	super(p);
    	
    	if (getID() != Pid_Records) {
    		throw(new PacketNotRecognizedException(Pid_Records, getID()));
    	}
    	
    	if (getDataLength() != 2) {
    		throw(new InvalidPacketException(packet, 2));
    	}
    	
    	number = readWord(3);		
    }
    
    public RecordsPacket(GarminPacket p) {
    	this(p.packet);
    }
    
    /** Returns the number of records that this packet announces. */
    public int getNumber() {
    	return number;
    }
    

    }

    10.2.10 GarminInputStream

    package dk.itu.haas.GPS.Garmin;
    import java.io.*;

    /**

    • This class provides the functionality of automatically removing the double DLEs from the GPS-inputstream.

    • The double-DLEs can be found in the size-,data-, and checksum-fields.

    • The only method providing the filtering-functionality is read().
      /
      public class GarminInputStream extends FilterInputStream {
      /

      • Last value read.
        */
        private int prev;

      /**

      • Takes the stream to the GPS-unit as an argument.
        */
        public GarminInputStream(InputStream i) {
        super(i);
        in = i;
        prev = 0;
        }

      /**

      • Reads a packet from the stream.

      • Note: Method assumes that it’s called between packets, ie. when the first byte of a packet is the

      • next in the stream. If this condition is met, the method will leave the stream in the same state.
        
        */	
        
        public int[] readPacket() throws InvalidPacketException, IOException {
        
        int c;
        
        int[] packet;
        
        int id, size;
        
        c = read();
        
        if (c != GarminPacket.DLE) {
        
        throw (new InvalidPacketException( new int[] { GarminPacket.DLE }, 0));
        
        }
        
        id = read();
        
        size = read();
        
        packet = new int[size + 6];
        
        packet[0] = GarminPacket.DLE;
        
        packet[1] = id;
        
        packet[2] = size;
        
        for (int i = 0 ; i < size + 3 ; i++)
        
        packet[3 + i] = read();
        
        if (packet[packet.length - 2] != GarminPacket.DLE) {
        
        throw (new InvalidPacketException(packet, packet.length - 2));
        
        }
        
        if (packet[packet.length - 1] != GarminPacket.ETX) {
        
        throw (new InvalidPacketException(packet, packet.length - 1));
        
        }
        
        return packet;
        
        }
        

      /**

      • Returns the next byte from the stream. Makes sure to remove DLE stuffing.
        */
        public int read() throws IOException{
        int c = in.read();
        if ( prev == 16 && c == 16)
        return prev = in.read();
        else
        return prev = c;
        }
        }

    10.2.11 GarminOutputStream

    package dk.itu.haas.GPS.Garmin;
    import java.io.*;

    /**

    • This class take care of adding DLE-stuffing to all packets sent to the GPS.
    • NOTE: Only the method write(GarminPacket) performs addition of DLE-stuffing. The remaining
    • methods write directly to the GPS without format-control.
      */
    public class GarminOutputStream extends FilterOutputStream {	
    
    public GarminOutputStream(OutputStream o) {
    
    super(o);
    
    }
    
    public synchronized void write (GarminPacket packet) throws IOException, InvalidPacketException {
    	if (packet.isLegal() != -1) {			
    		throw (new InvalidPacketException(packet.getPacket(), packet.isLegal()));
    	}
    	write(packet.getByte(0));
    	write(packet.getByte(1));
    	
    	int c;
    	// Iterate through size-field, data-field and checksum-field. Add stuffing where necessary.
    	for (int i = 0 ; i < packet.getByte(2) + 2 ; i++) {
    		c = packet.getByte(i + 2);			
    		write(c);
    		if (c == GarminPacket.DLE)
    			write(c);			
    	}
    	
    	write(GarminPacket.DLE);
    	write(GarminPacket.ETX);		
    	flush();
    }
    
    }
    
    10.2.12 GarminListener
    
    package dk.itu.haas.GPS.Garmin;
    

    /**
    This interface should be implemented by classes that are interested in getting all the Garmin-packets
    transmitted by a Garmin-GPS. Listener’s will receive all packets including ACKs and NAKs. Only exception
    are malformed packets.
    */

    public interface GarminListener {
    
    /** This method will be called for each packet received from the GPS. */
    
    public void GarminPacketReceived(GarminPacket p);
    
    }
    

    10.2.13 InvalidPacketException
    package dk.itu.haas.GPS.Garmin;

    /**

    • This method is thrown from the constructors of the packet-classes, whenever the int[]-array is not formatted according to the Garmin-packet-specs.
      */
      public class InvalidPacketException extends RuntimeException {

      private int[] packet;
      private int index;

      /**

      • Creates an InvalidPacketException. pack is a reference to the byte-array that caused the exception.
      • i is the index of the byte that was in error.
        */
        public InvalidPacketException(int[] pack, int i) {
        packet = pack;
        index = i;
        }

      /**

      • Returns the packet that caused the exception to be thrown.
      • Note: The return-value is a reference to the original array. Changes will likely propagate
      • to other parts of the program.
        */
        public int[] getPacket() {
        return packet;
        }

      /**

      */

      /**

      • Returns the index of the first erroneously configured byte.
        */
        public int getIndex() {
        return index;
        }

      /**

      • Returns a formatted string showing which byte is wrong.
        */
        public String toString() {
        StringBuffer res = new StringBuffer();
        res.append("\nByte\tvalue\n");
        for (int i = 0 ; i < packet.length ; i++) {
        res.append(" " + i+"\t"+packet[i]);
        if (i == index)
        res.append(" <- Erroneous");
        res.append(’\n’);
        }
        return res.toString();
        }
        }

    10.2.14 PacketNotRecognizedException

    package dk.itu.haas.GPS.Garmin;

    /**

    • This exception is thrown whenever a method expects one type of packet, but receives another.

    • An example is if a PositionDataPacket is initialized with the byte-array containing time-data.

    • This exception is a runtime exception because it’s assumed that there will in most cases be type-checking

    • of packets.
      */
      public class PacketNotRecognizedException extends RuntimeException {

      /**

      • expected is the type of packet that the method was expecting. actual is the type of the packet that
      • it received.
        */
        public PacketNotRecognizedException(int expected, int actual) {
        super( “\nPacket initialization error:\n” + "Expected: " +
        GarminPacket.idToString(expected) + ‘\n’ +
        "received: " + GarminPacket.idToString(actual) + ‘\n’);
        }
        }
        10.2.15 UnknownPacketException
        package dk.itu.haas.GPS.Garmin;

    public class UnknownPacketException extends Exception {

    }

    10.3 dk.itu.haas.GPS.services ? package
    
    10.3.1 AreaAlarm
    
    package dk.itu.haas.GPS.services;
    
    import dk.itu.haas.GPS.*;
    
    import java.util.Vector;
    

    /**

    • This class implements an AreaAlarm-service. The class allows the user to specify two positions, which

    • will be used as opposite corners in a rectangular area. Whenever the GPS enters or exits the area all

    • listeners are notified through the IAlarmListener-interface.
      
      */
      
      public class AreaAlarm implements IGPSlistener {
      
      private GPS gps;
      
      // The positions defining the rectangle to be used.
      
      private PositionRadians bottom_longitude,
      
      top_longitude,
      
      left_latitude,
      
      right_latitude;
      

      private Vector alarmListeners;
      private boolean inside;

      public AreaAlarm(GPS g, Position p1, Position p2) {		
      
      gps = g;
      
      gps.setAutoTransmit(true);
      
      gps.addGPSlistener(this);
      
      alarmListeners = new Vector();
        
        PositionRadians l1, l2;
        l1 = p1.getLatitude();
        l2 = p2.getLatitude();
        if (l1.equals(l2))
        	throw (new RuntimeException("No area. Latitude of point 1 equals latitude of point 2."));
        	
        if (l1.greaterThan(l2)) {
        	right_latitude = l1;
        	left_latitude = l2;
        } else {
        	right_latitude = l2;
        	left_latitude = l1;
        }
      
        l1 = p1.getLongitude();
        l2 = p2.getLongitude();
        if (l1.equals(l2))
        	throw (new RuntimeException("No area. Longitude of point 1 equals longitude of point 2."));
        
        if (l1.greaterThan(l2)) {
        	top_longitude = l1;
        	bottom_longitude = l2;
        } else {
        	top_longitude = l2;
        	bottom_longitude = l1;
        }
      

      }

      /**

      • Adds l to the list of listeners interested in receiving notification when the GPS enters or exits the area.
        
        */
        
        public void addAlarmListener(IAlarmListener l) {
        
        // Only allow a listener to be registered once.		
        
        if (alarmListeners.contains(l))
        
        return;
        
        alarmListeners.add(l);
        
        return;						
        
        }
        

      /**

      • Removes the the Alarm-listener l from the list of Waypoint-listeners.
        */
        public void removeAlarmListener(IAlarmListener l) {
        while (alarmListeners.removeElement(l)) {}
        }

      /**

      • This method propagates the information that the gps has exited the area to all listeners.
        */
        protected void fireOutside() {
        for (int i = 0 ; i < alarmListeners.size() ; i++) {
        ((IAlarmListener) alarmListeners.elementAt(i)).exitedAlarm();
        }
        }

      /**

      • This method propagates the information that the gps has entered the area to all listeners.
        */
        protected void fireInside() {
        for (int i = 0 ; i < alarmListeners.size() ; i++) {
        ((IAlarmListener) alarmListeners.elementAt(i)).enteredAlarm();
        }
        }

      public void timeReceived(ITime t) {}

      public void dateReceived(IDate d) {}

      public void positionReceived(IPosition pos) {
      
      System.out.println(Areaalarm: Received pos. Analyzing!);
      
      if (inside == false) {			
      
      if ( 	(pos.getLatitude().greaterThan(left_latitude)) &&
      
      (pos.getLatitude().smallerThan(right_latitude)) &&
      
      (pos.getLongitude().greaterThan(bottom_longitude)) &&
      
      (pos.getLongitude().smallerThan(top_longitude))) {
      
      inside = true;
      
      fireInside();				
      
      }
      
      } else {
      
      if (   !((pos.getLatitude().greaterThan(left_latitude)) &&
      
      (pos.getLatitude().smallerThan(right_latitude)) &&
      
      (pos.getLongitude().greaterThan(bottom_longitude)) &&
      
      (pos.getLongitude().smallerThan(top_longitude)))) {
      
      inside = false;
      
      fireOutside();
      
      }
      
      }		
      
      }
      
      }
      

    10.3.2 IAlarmListener

    package dk.itu.haas.GPS.services;

    /**

    • This interface allows a class to listen on an AreaAlarm.
      /
      public interface IAlarmListener {
      /
      *

      • This method is called by the AreaAlarm when the GPS exists the area.
        */
        public void exitedAlarm();

      /**

      • This method is called by the AreaAlarm when the GPS enters the area.
        */
        public void enteredAlarm();
        }

    10.4 dk.itu.haas.GPS.examples ? package
    10.4.1 ConnectionTest

    package dk.itu.haas.GPS.examples;
    
    import dk.itu.haas.GPS.<em>;
    
    import dk.itu.haas.GPS.Garmin.</em>;
    
    import javax.comm.<em>;
    
    import java.util.Enumeration;
    
    import java.util.Vector;
    
    import <a href="http://java.io">java.io</a>.</em>;
    

    /**

    • A simple test-program that queries the GPS for a description of itself.
    • A good way to initially test the connection to the GPS.
    • Attempts to turn off the GPS after retrieving the description.
      */
    class ConnectionTest {
    
    /** The communication port being used. */
    
    String portname;
    
    BufferedReader inuser;
    
    GPS gps;
    
    CommPort port;
    
    BufferedInputStream input;
    
    BufferedOutputStream output;
    
    public static void main(String args[]) {
    	new ConnectionTest();
    }
    
    public ConnectionTest() {
    	inuser = new BufferedReader(new InputStreamReader(System.in));
    	String portname = ListPorts();
    	String gpsbrand = ListGPS();
    	
    	try {
    		port = CommPortIdentifier.getPortIdentifier(port).open("ConnectionTest", 3000);
    	} catch (NoSuchPortException e) {
    		System.out.println("Port not found!");
    		return;
    	} catch (PortInUseException e) {
    		System.out.println("Port already in use by " + e.currentOwner);
    		return;
    	}
    	
    	try {
    		input = new BufferedInputStream(port.getInputStream());
    		output = new BufferedOutputStream(port.getOutputStream());			
    	} catch (IOException e) {
    		System.out.println("Error opening port " + portname);
    		return;
    	}
    	if (gpsbrand.equals("GARMIN") ) {
    		gps = new GarminGPS(input, output);
    	}
    	try {
    		Thread.sleep(1500);
    	} catch (InterruptedException e) {}
    	
    	System.out.println("Connected to GPS:");		
    	System.out.println( gps.getDescription());
    	gps.shutdown(false);
    }
    
    /** 
    * Ok. Ridiculous method, but I'm hoping that more GPS-types will be added later.
    * Lists the types of GPS that are available and lets the user pick one. 
    */		
    private String ListGPS() {
    	int index = -1;
    	while (index == -1) {
    		System.out.println("\nAvailable GPS-types:");
    		System.out.println(" 1. Garmin");
    		System.out.print("Select GPS: ");
    		String input = readFromUser();
    		
    		try {
    			index = Integer.parseInt(input);
    		} catch (NumberFormatException e) {
    			index = -1;
    			continue;			
    		}
    		
    		if (index != 1) {
    			index = -1;
    			continue;
    		}
    	}
    	switch (index) {
    		case 1 :
    			return "GARMIN";
    		default :
    			return "unknown";
    	}
    }	
    
    private String ListPorts() {
    	Vector names = null;
    	int index = -1;		
    	while (index == -1) {
    		int j = 1;
    		names = new Vector();
    		System.out.println("Available ports: ");
    		CommPortIdentifier c;
    		for (Enumeration i = CommPortIdentifier.getPortIdentifiers() ; i.hasMoreElements() ;) {
    			c = (CommPortIdentifier) i.nextElement();
    			System.out.print(j++ +". " + c.getName());
    			names.add(c.getName());
    			if (c.getPortType() == CommPortIdentifier.PORT_SERIAL)
    				System.out.print("\t SERIAL\n");
    			if (c.getPortType() == CommPortIdentifier.PORT_PARALLEL)
    				System.out.print("\t PARALLEL\n");			
    		}
    		System.out.print("Select port: ");
    		String input = readFromUser();
    		
    		try {
    			index = Integer.parseInt(input);
    		} catch (NumberFormatException e) {
    				index = -1;
    				continue;			
    		}
    		
    		if ( (index < 1) || (index  >= names.size()) ) {				
    			index = -1;
    			continue;				
    		}
    	}
    	
    	return names.elementAt(index - 1).toString();
    }
    
    public String readFromUser() {
    	try {
    		return inuser.readLine();
    	} catch (IOException e) {
    		return "";
    	}			
    }
    

    }

    10.4.2 AreaAlarmDemo

    package dk.itu.haas.GPS.examples;
    
    import dk.itu.haas.GPS.<em>;
    
    import dk.itu.haas.GPS.services.</em>;
    
    import dk.itu.haas.GPS.Garmin.<em>;
    
    import javax.swing.</em>;
    
    import java.awt.event.<em>;
    
    import java.awt.</em>;
    
    import <a href="http://java.io">java.io</a>.<em>;
    
    import javax.comm.</em>;
    
    public class AreaAlarmDemo extends JFrame implements ActionListener, IGPSlistener, IAlarmListener {
    
    GPS gps;		
    
    AreaAlarm alarm;
    
    Position pos1 = null, pos2 = null;
    
    IPosition current = null;	
    
    JLabel indicator;
    
    JButton mark1;
    
    JButton mark2;
    
    BufferedInputStream input;
    
    BufferedOutputStream output;
    
    public static void main(String args[]) {
    	new AreaAlarmDemo();
    }
    
    public void actionPerformed(ActionEvent e) {
    	if ( (e.getActionCommand().equals("mark1")) && (current != null)) {
    		mark1.setEnabled(false);
    		pos1 = new Position(current);
    		current = null;
    	}
    	
    	if ( (e.getActionCommand().equals("mark2")) && (current != null)) {
    		mark2.setEnabled(false);
    		pos2 = new Position(current);
    		current = null;			
    	}
    	
    	if ( (pos1 != null) && (pos2 != null) ) {
    		indicator.setText("Not inside area.");
    		alarm = new AreaAlarm(gps, pos1, pos2);
    		alarm.addAlarmListener(this);
    		gps.removeGPSListener(this);
    	}
    }
    	
    
    public void exitedAlarm() {
    	indicator.setText("Not inside area.");
    }
    
    public void enteredAlarm() {
    	indicator.setText("Inside area.");
    }
    
    public AreaAlarmDemo() {		
    	super("AreaAlarm-demonstration");
    	CommPort port;
    	
    	try {
    		port = CommPortIdentifier.getPortIdentifier("COM1").open("AreaAlarmDemo", 3000);
    	} catch (NoSuchPortException e) {
    		System.out.println("COM1 not found!");
    		return;
    	} catch (PortInUseException e) {
    		System.out.println("Port already in use by " + e.currentOwner);
    		return;
    	}
    	
    	try {
    		input = new BufferedInputStream(port.getInputStream());
    		output = new BufferedOutputStream(port.getOutputStream());			
    	} catch (IOException e) {
    		System.out.println("Error opening COM1");
    		return;
    	}		
    			
    	gps = new GarminGPS(input, output);
    	gps.setAutoTransmit(true);
    	gps.addGPSlistener(this);
    	
    	
    	indicator = new JLabel("Nothing recorded yet.", JLabel.CENTER);
    	getContentPane().setLayout(new BorderLayout());
    	
    	mark1 = new JButton("Mark position 1");
    	mark1.setActionCommand("mark1");
    	mark1.addActionListener(this);
    	mark2 = new JButton("Mark position 2");
    	mark2.setActionCommand("mark2");
    	mark2.addActionListener(this);
    	
    	
    	getContentPane().add(mark1, BorderLayout.NORTH);
    	getContentPane().add(mark2, BorderLayout.SOUTH);
    	getContentPane().add(indicator, BorderLayout.CENTER);
    			
    	setDefaultCloseOperation(EXIT_ON_CLOSE);
    	setSize(320,200);
    	setLocationRelativeTo(null);				
    	show();
    	
    	System.out.println(gps.getDescription());
    }		
    	
    public void timeReceived(ITime t) {}
    public void dateReceived(IDate d) {}
    
    public void positionReceived(IPosition pos) {
    	System.out.println("Received!");
    	current = pos;
    }
    

    }

    Bem, mas o motivo desse artigo que meu amigo passou seria para que eu consiga estartar o Geomidia e e posicionar no local que eu passar como parametro.

    Alguem sabe o problema das classes que esta descrito acima ou uma solução para que eu consiga trabalhar com geomidia

    Espero que alguem possa me ajudar.

    Abraços a todos.

    1 Resposta

    jmoreira

    Cara, fica meio difícil analisar 2200 linhas de códigos.
    Você praticamente plotou seu software inteiro aqui… :smiley:

    Tente centralizar o problema em poucas linhas (não mais que 10) e forneça mais informação a respeito das bibliotecas que você está utilizando e como utilizando.
    Valeu!

    Criado 25 de março de 2008
    Ultima resposta 30 de mar. de 2008
    Respostas 1
    Participantes 2