From e7b0ef1f5ab06f6e514c84c8a0875f4c1acab1eb Mon Sep 17 00:00:00 2001
From: Chris Angelopoulos <>
Date: Tue, 6 Mar 2018 15:30:35 -0800
Subject: [PATCH] Angelopoulos Assignment 3 complete

---
 .../homework3/Angel_OpenDisEspduSender.java   | 341 ++++++++++++++++++
 .../homework3/AngelopoulosREADME.md           |  34 ++
 .../homework3/Angelopoulos_dispackets.disbin  | Bin 0 -> 7488 bytes
 .../Angelopoulos_dispackets.disbin.disbinidx  | Bin 0 -> 1196 bytes
 4 files changed, 375 insertions(+)
 create mode 100644 projects/Assignments/homework3/Angel_OpenDisEspduSender.java
 create mode 100644 projects/Assignments/homework3/AngelopoulosREADME.md
 create mode 100644 projects/Assignments/homework3/Angelopoulos_dispackets.disbin
 create mode 100644 projects/Assignments/homework3/Angelopoulos_dispackets.disbin.disbinidx

diff --git a/projects/Assignments/homework3/Angel_OpenDisEspduSender.java b/projects/Assignments/homework3/Angel_OpenDisEspduSender.java
new file mode 100644
index 0000000000..100647dc12
--- /dev/null
+++ b/projects/Assignments/homework3/Angel_OpenDisEspduSender.java
@@ -0,0 +1,341 @@
+//package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+
+import edu.nps.moves.dis.*;
+import edu.nps.moves.disutil.CoordinateConversions;
+import edu.nps.moves.disutil.DisTime;
+
+/**
+ * Creates and sends ESPDUs in IEEE binary format. 
+ *
+ * @author DMcG
+ */
+public class Angel_OpenDisEspduSender 
+{
+    public static final int NUMBER_TO_SEND = 5000;
+
+    public enum NetworkMode{UNICAST, MULTICAST, BROADCAST};
+
+    /** Default multicast group address we send on */
+    public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3";
+   
+    /** Default port we send on */
+    public static final int    DIS_DESTINATION_PORT = 3000;
+    
+/** Possible system properties, passed in via -Dattr=val
+     * networkMode: unicast, broadcast, multicast
+     * destinationIp: where to send the packet. If in multicast mode, this can be multicast.
+     *                To determine broadcast destination IP, use an online broadcast address
+     *                calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php
+     *                If in multicast mode, a join() will be done on the multicast address.
+     * port: port used for both source and destination.
+     * @param args 
+     */
+public static void main(String args[])
+{
+    /** an entity state pdu */
+    EntityStatePdu espdu = new EntityStatePdu();
+    MulticastSocket socket = null; // must be initialized, even if null
+    DisTime disTime = DisTime.getInstance(); // TODO explain
+    int alternator = -1;
+    
+    // ICBM coordinates for my office
+    double lat = 36.595517; 
+    double lon = -121.877000;
+    
+    // Default settings. These are used if no system properties are set. 
+    // If system properties are passed in, these are over ridden.
+    int port = DIS_DESTINATION_PORT;
+    NetworkMode mode = NetworkMode.BROADCAST;
+    InetAddress destinationIp = null; // must be initialized, even if null
+    
+    try
+    {
+        destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP);
+    }
+    catch(UnknownHostException e)
+    {
+        System.out.println(e + " Cannot create multicast address");
+        System.exit(0);
+    }
+    
+    // All system properties, passed in on the command line via -Dattribute=value
+    Properties systemProperties = System.getProperties();
+    
+    // IP address we send to
+    String destinationIpString = systemProperties.getProperty("destinationIp");
+    
+    // Port we send to, and local port we open the socket on
+    String portString = systemProperties.getProperty("port");
+    
+    // Network mode: unicast, multicast, broadcast
+    String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast
+        
+    // Set up a socket to send information
+    try
+    {
+        // Port we send to
+        if(portString != null)
+            port = Integer.parseInt(portString);
+        
+        socket = new MulticastSocket(port);
+        
+        // Where we send packets to, the destination IP address
+        if(destinationIpString != null)
+        {
+            destinationIp = InetAddress.getByName(destinationIpString);
+        }
+
+        // Type of transport: unicast, broadcast, or multicast
+		// TODO convert to String constants
+        if(networkModeString != null)
+        {
+            if(networkModeString.equalsIgnoreCase("unicast"))
+                mode = NetworkMode.UNICAST;
+            else if(networkModeString.equalsIgnoreCase("broadcast"))
+                mode = NetworkMode.BROADCAST;
+            else if(networkModeString.equalsIgnoreCase("multicast"))
+            {
+                mode = NetworkMode.MULTICAST;
+                if(!destinationIp.isMulticastAddress())
+                {
+                    throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast");
+                }
+                
+                socket.joinGroup(destinationIp);
+            }
+        } // end networkModeString
+    }
+    catch(IOException | RuntimeException e)
+    {
+        System.out.println("Unable to initialize networking. Exiting.");
+        System.out.println(e);
+        System.exit(-1);
+    }
+    
+    // Initialize values in the Entity State PDU object. The exercise ID is 
+    // a way to differentiate between different virtual worlds on one network.
+    // Note that some values (such as the PDU type and PDU family) are set
+    // automatically when you create the ESPDU.
+    espdu.setExerciseID((short)1);
+    
+    // The EID is the unique identifier for objects in the world. This 
+    // EID should match up with the ID for the object specified in the 
+    // VMRL/x3d/virtual world.
+    EntityID entityID = espdu.getEntityID();
+    entityID.setSite(1);  // 0 is apparently not a valid site number, per the spec
+    entityID.setApplication(1); 
+    entityID.setEntity(2); 
+    
+    // Set the entity type. SISO has a big list of enumerations, so that by
+    // specifying various numbers we can say this is an M1A2 American tank,
+    // the USS Enterprise, and so on. We'll make this a tank. There is a 
+    // separate project elsehwhere in this project that implements DIS 
+    // enumerations in C++ and Java, but to keep things simple we just use
+    // numbers here.
+    EntityType entityType = espdu.getEntityType();
+    entityType.setEntityKind((short)1);      // Platform (vs lifeform, munition, sensor, etc.)
+    entityType.setCountry(225);              // USA
+    entityType.setDomain((short)2);          // AIR (vs air, surface, subsurface, space)
+    entityType.setCategory((short)2);        // Fighter/Attack
+    entityType.setSubcategory((short)2);     // M1 Abrams
+    entityType.setSpec((short)3);            // M1A2 Abrams
+    
+
+    Set<InetAddress> broadcastAddresses;
+    // Loop through sending N ESPDUs
+    try
+    {
+        System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString());
+            double disCoordinates1[] = CoordinateConversions.getXYZfromLatLonDegrees(36.593731, -121.882534, 1.0);
+            double disCoordinates2[] = CoordinateConversions.getXYZfromLatLonDegrees(36.594548, -121.882651, 1.0);
+            double disCoordinates3[] = CoordinateConversions.getXYZfromLatLonDegrees(36.596826, -121.882694, 1.0);
+            double disCoordinates4[] = CoordinateConversions.getXYZfromLatLonDegrees(36.598394, -121.883188, 1.0);
+            double disCoordinates5[] = CoordinateConversions.getXYZfromLatLonDegrees(36.599927, -121.883510, 1.0);
+            double disCoordinates6[] = CoordinateConversions.getXYZfromLatLonDegrees(36.599979, -121.887286, 1.0);
+            double disCoordinates7[] = CoordinateConversions.getXYZfromLatLonDegrees(36.598170, -121.887715, 1.0);
+            double disCoordinates8[] = CoordinateConversions.getXYZfromLatLonDegrees(36.596826, -121.888895, 1.0);
+            double disCoordinates9[] = CoordinateConversions.getXYZfromLatLonDegrees(36.595121, -121.889239, 1.0);
+            double disCoordinates10[] = CoordinateConversions.getXYZfromLatLonDegrees(36.594415,-121.885934, 1.0);
+            
+        double[][] disCoords = {disCoordinates1, disCoordinates2, disCoordinates3, disCoordinates4,
+            disCoordinates5, disCoordinates6, disCoordinates7, disCoordinates8, disCoordinates8, 
+            disCoordinates10};
+  
+        for(int idx = 0; idx < NUMBER_TO_SEND; idx++)
+        {
+            // DIS time is a pain in the ass. DIS time units are 2^31-1 units per
+            // hour, and time is set to DIS time units from the top of the hour. 
+            // This means that if you start sending just before the top of the hour
+            // the time units can roll over to zero as you are sending. The receivers
+            // (escpecially homegrown ones) are often not able to detect rollover
+            // and may start discarding packets as dupes or out of order. We use
+            // an NPS timestamp here, hundredths of a second since the start of the
+            // year. The DIS standard for time is often ignored in the wild; I've seen
+            // people use Unix time (seconds since 1970) and more. Or you can
+            // just stuff idx into the timestamp field to get something that is monotonically
+            // increasing.
+            
+            // Note that timestamp is used to detect duplicate and out of order packets. 
+            // That means if you DON'T change the timestamp, many implementations will simply
+            // discard subsequent packets that have an identical timestamp. Also, if they
+            // receive a PDU with an timestamp lower than the last one they received, they
+            // may discard it as an earlier, out-of-order PDU. So it is a good idea to
+            // update the timestamp on ALL packets sent.
+            
+
+            // An alterative approach: actually follow the standard. It's a crazy concept,
+            // but it might just work.
+            int timestamp = disTime.getDisAbsoluteTimestamp();
+            espdu.setTimestamp(timestamp);
+            
+            // Set the position of the entity in the world. DIS uses a cartesian 
+            // coordinate system with the origin at the center of the earth, the x
+            // axis out at the equator and prime meridian, y out at the equator and
+            // 90 deg east, and z up and out the north pole. To place an object on
+            // the earth's surface you also need a model for the shape of the earth
+            // (it's not a sphere.) All the fancy math necessary to do this is in
+            // the SEDRIS SRM package. There are also some one-off formulas for 
+            // doing conversions from, for example, lat/lon/altitude to DIS coordinates.
+            // Here we use those one-off formulas.
+
+            // Modify the position of the object. This will send the object a little
+            // due east by adding some to the longitude every iteration. Since we
+            // are on the Pacific coast, this sends the object east. Assume we are
+            // at zero altitude. In other worlds you'd use DTED to determine the
+            // local ground altitude at that lat/lon, or you'd just use ground clamping.
+            // The x and y values will change, but the z value should not.
+            
+            //lon = lon + (double)((double)idx / 100000.0);
+            //System.out.println("lla=" + lat + "," + lon + ", 0.0");
+
+
+            //double direction = Math.pow((double)(-1.0), (double)(idx));
+            //lon = lon + (direction * 0.00006);
+            //System.out.println(lon);
+            
+
+
+            Vector3Double location = espdu.getEntityLocation();
+            int res = idx/2 % 10;
+            location.setX(disCoords[res][0]);
+            location.setY(disCoords[res][1]);
+            location.setZ(disCoords[res][2]);
+            //System.out.println("lat, lon:" + lat + ", " + lon);
+            //System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]);
+
+            // Optionally, we can do some rotation of the entity
+            /*
+            Orientation orientation = espdu.getEntityOrientation();
+            float psi = orientation.getPsi();
+            psi = psi + idx;
+            orientation.setPsi(psi);
+            orientation.setTheta((float)(orientation.getTheta() + idx /2.0));
+             */
+            
+            // You can set other ESPDU values here, such as the velocity, acceleration,
+            // and so on.
+
+            // Marshal out the espdu object to a byte array, then send a datagram
+            // packet with that data in it.
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            DataOutputStream dos = new DataOutputStream(baos);
+            espdu.marshal(dos);
+
+            
+            //FirePdu fire = new FirePdu();
+            //byte[] fireArray = fire.marshal();
+            
+            // The byte array here is the packet in DIS format. We put that into a 
+            // datagram and send it.
+            byte[] data = baos.toByteArray();
+
+            broadcastAddresses = getBroadcastAddresses();
+            Iterator it = broadcastAddresses.iterator();
+            while(it.hasNext())
+            {
+               InetAddress broadcast = (InetAddress)it.next();
+               System.out.println("Sending broadcast datagram packet to " + broadcast);
+               DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000);
+               socket.send(packet);
+			   // TODO experiment with these!  8)
+               //packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate
+               socket.send(packet);
+            }
+            
+            // Send every 1 sec. Otherwise this will be all over in a fraction of a second.
+            Thread.sleep(3000);
+
+            location = espdu.getEntityLocation();
+            
+            System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]");
+            System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]");
+            double c[] = {location.getX(), location.getY(), location.getZ()};
+            double lla[] = CoordinateConversions.xyzToLatLonDegrees(c);
+//            System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]");
+
+        }
+    }
+    catch(IOException | InterruptedException e)
+    {
+        System.out.println(e);
+    }
+        
+}
+
+ /**
+    * A number of sites get all snippy about using 255.255.255.255 for a broadcast
+    * address; it trips their security software and they kick you off their 
+    * network. (Comcast, NPS.) This determines the broadcast address for all
+    * connected interfaces, based on the IP and subnet mask. If you have
+    * a dual-homed host it will return a broadcast address for both. If you have
+    * some VMs running on your host this will pick up the addresses for those
+    * as well--eg running VMWare on your laptop with a local IP this will
+    * also pick up a 192.168 address assigned to the VM by the host OS.
+    * 
+    * @return set of all broadcast addresses
+    */
+   public static Set<InetAddress> getBroadcastAddresses()
+   {
+       Set<InetAddress> broadcastAddresses = new HashSet<>();
+       Enumeration interfaces;
+       
+       try
+       {
+           interfaces = NetworkInterface.getNetworkInterfaces();
+           
+           while(interfaces.hasMoreElements())
+           {
+               NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement();
+               
+               if(anInterface.isUp())
+               {
+                   Iterator it = anInterface.getInterfaceAddresses().iterator();
+                   while(it.hasNext())
+                   {
+                       InterfaceAddress anAddress = (InterfaceAddress)it.next();
+                       if((anAddress == null || anAddress.getAddress().isLinkLocalAddress()))
+                           continue;
+                       
+                       //System.out.println("Getting broadcast address for " + anAddress);
+                       InetAddress broadcastAddress = anAddress.getBroadcast();
+                       if(broadcastAddress != null)
+                          broadcastAddresses.add(broadcastAddress);
+                   }
+               }
+           }
+           
+       }
+       catch(SocketException e)
+       {
+           e.printStackTrace();
+           System.out.println(e);
+       }
+       
+       return broadcastAddresses;   
+   }
+
+}
diff --git a/projects/Assignments/homework3/AngelopoulosREADME.md b/projects/Assignments/homework3/AngelopoulosREADME.md
new file mode 100644
index 0000000000..bf6e056dcf
--- /dev/null
+++ b/projects/Assignments/homework3/AngelopoulosREADME.md
@@ -0,0 +1,34 @@
+## Homework Assignment 3 Checklist
+
+1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads
+
+1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java
+
+1. [x] Otherwise just inspect files of interest from
+   [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples)
+
+1. [x] Copy README.md and create YournameREADME.md documentation file...
+
+1. [x] Plan a track of interest, described in YournameREADME.md documentation file...
+
+The armor (Enhanced Ground Combat Vehicle) travels from intersection of Freemont and 68, down Camino Aguajito,
+left on Del Monte Ave, Left on Camino El Estero, and finally a left on Fremont to the beginning.  The travel movement is 
+roughly 1/3 of a mile every 24 seconds.  It might be a bit fast....but its ARMY/MARINE Strong!
+
+1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java
+
+1. [x] Modify your example file to produce track PDUs (and be cool)
+
+1. [x] Generate PDUs...
+
+1. [x] Test PDU reading using Wireshark...
+
+Some examples of PDUs within WireShark
+
+111	32.870689	172.20.144.243	172.20.159.255	DIS	186	PDUType: 1 	 Entity State, Platform, Air, (1:1:2)
+110	32.870603	172.20.144.243	172.20.159.255	DIS	186	PDUType: 1 	 Entity State, Platform, Air, (1:1:2)
+97	29.761150	172.20.144.243	172.20.159.255	DIS	186	PDUType: 1 	 Entity State, Platform, Air, (1:1:2)
+
+1. [x] Record PDU file using X3D-Edit...
+
+1. [x] Playback PDU file using X3D-Edit...
diff --git a/projects/Assignments/homework3/Angelopoulos_dispackets.disbin b/projects/Assignments/homework3/Angelopoulos_dispackets.disbin
new file mode 100644
index 0000000000000000000000000000000000000000..75f5caf1ddc7fed9a2c5ac6d83bc52d1e4fa1337
GIT binary patch
literal 7488
zcmZQ$WMo_=zi}zU1O^5MMj&JYQcMgFnV6V?0+`^S%Sz^#3!a4?447TM=CF2=qtDII
znR?r9VX7oggl*J4cmr-whEMn|%|VrZM%{xm4T00oU<;oKixP=XKP!HTw%wKimOoh+
zR}^domOqvM@)DhJdYD8BaQKY62WO}a%J4a99Y3hj&!~Iwr=LL<KC7AJ-ja}hF280i
z{Q@k1yaJcUaRSSq`xU#VZpP_h5+y+SYt%is18q=-k2O>Eph`cZ?!lRW!0BhOg-`M9
zN)pn~Y0pb`uYl!`Ug?9$+Z=svsRkbW3F^I31%Sh6)IB)Ea!`iPn&$O`D*cSQ2Y>n*
zY~k}X-Ij#(vu6*Bj2E!{5mjLAp9w5~GH3hw3*q!Ii4x%aHR>Lmp*9%9XN??#^<YXr
zqwc|(d>BCKXV8UD*yEGLr=OMH&i|F84hGD6e%vKxGO+x~e&fOP61R^@lL3d%sC#e*
z+Mo=d{^Q|;D*cSQ2Y>n*Y~gbv<v$7Or&?#xgj2xs=Z|dVwJE^zM>;&>hdNFVlPCes
NU!(598ES(qd;n<bJVpQj

literal 0
HcmV?d00001

diff --git a/projects/Assignments/homework3/Angelopoulos_dispackets.disbin.disbinidx b/projects/Assignments/homework3/Angelopoulos_dispackets.disbin.disbinidx
new file mode 100644
index 0000000000000000000000000000000000000000..159aa2e788491aa6a444ff345031cbd29ecc337c
GIT binary patch
literal 1196
zcmZY8K}b_^90%~Xx4pg1<+hxwR)WvzA&}uPlpwUxlAs`mfd^;XL>A`7fd{Ye=m@t*
zTi`)*V+W0-9)hwiF*<aMtwRpGH1#kjib2rL=>Pu>e0}j<etbXwAAkP;-=AkSnS}G7
zW<6t#R^{FmRt+{O#J0o;vQBItECGul&hNhXuCronBG!lx%D;fk3F7)TFGjbyMSK`v
z1-7UxnwDplKLbl{;#vDJa-q#TX<%!RI2P+euCOQuo|XH7<p}Yb%F2HSlp8FHfy`4s
zuq{QL{eh#hGZn<<rgIv)?HY06&o|%>g}C_DjjR)w?oR<bLM)n#(U-WlqelFA@fCDm
zND#-88^|r<c)Sa^Q)ST-z4QJBu#+Fm5)IdHAs2}6M*af3g2WS_aNe#8W67J<8>|{H
z?~V}Xq)}wvC3*858Q_blHs`m1`7H#gs_cA3)`<N#9s+xmHdk*V>%{#Jegk)hShS{<
z56_Wn#C{)+%A08O8xM4QTf_rJ{zDp<zofD#hv$Dz0$+9$C*O`C7l@zaz5`zg5-&K`
zkt>`}$5xuaz6kO7>wCxz;@d+h;Hx~!r=ht=z}Hw3Z2OJq9<oM!v|9%5QHYP1@ELk^
K;*&s}cmD&$Q<%;G

literal 0
HcmV?d00001

-- 
GitLab