diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java index 6dec6bd38359a650e7f4ba646a09f6a8dd6b4361..674acbcea5fbc1afb5e2d12a775876fde97a0bf3 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java @@ -1,343 +1,351 @@ package MV3500Cohort2018JanuaryMarch.homework3; -//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.*; // OpenDIS version 4 -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 command-line arguments - */ -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; - } - -} +//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.*; // OpenDIS version 4 +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; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + 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 command-line arguments + */ +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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java index f6171dd562946fc04e294c3e52301c55e3218720..cfab01793ab677ba867de7b7322a34b7d766bf53 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java @@ -1,366 +1,374 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class BlankenbekerOpenDisEspduSender -{ - - 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"; - - public static final ArrayList <Float[]> track = new ArrayList<>(); - - /** 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 command-line arguments - */ -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.MULTICAST; - 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)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // M1 Abrams - entityType.setSpec((short)3); // M1A2 Abrams - - - Set<InetAddress> broadcastAddresses; - // Loop through sending N ESPDUs - try - { - - Float[] TrackCoor1 = new Float [2]; - TrackCoor1[0] = 36.59135f; - TrackCoor1[1] = -121.88051f; - track.add(TrackCoor1); - Float[] TrackCoor2 = new Float [2]; - TrackCoor2[0] = 36.59487f; - TrackCoor2[1] = -121.86739f; - track.add(TrackCoor2); - Float[] TrackCoor3 = new Float [2]; - TrackCoor3[0] = 36.63259f; - TrackCoor3[1] = -121.66926f; - track.add(TrackCoor3); - Float[] TrackCoor4 = new Float [2]; - TrackCoor4[0] = 36.64481f; - TrackCoor4[1] = -121.61162f; - track.add(TrackCoor4); - Float[] TrackCoor5 = new Float [2]; - TrackCoor5[0] = 35.64239f; - TrackCoor5[1] = -120.68503f; - track.add(TrackCoor5); - Float[] TrackCoor6 = new Float [2]; - TrackCoor6[0] = 35.61577f; - TrackCoor6[1] = -119.65283f; - track.add(TrackCoor6); - Float[] TrackCoor7 = new Float [2]; - TrackCoor7[0] = 34.76589f; - TrackCoor7[1] = -118.79854f; - track.add(TrackCoor7); - Float[] TrackCoor8 = new Float [2]; - TrackCoor8[0] = 34.77651f; - TrackCoor8[1] = -118.17049f; - track.add(TrackCoor8); - Float[] TrackCoor9 = new Float [2]; - TrackCoor9[0] = 34.5806f; - TrackCoor9[1] = -118.1334f; - track.add(TrackCoor9); - -// System.out.println("********" + String.valueOf(track_coordinates[0]) ); -// System.out.println("********" + track_coordinates.get(5)[1]); - System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); - 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"); - - Float lat = track.get(idx)[0]; - Float lon = track.get(idx)[1]; - - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class BlankenbekerOpenDisEspduSender +{ + + public static final int NUMBER_TO_SEND = 5000; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + public static final ArrayList <Float[]> track = new ArrayList<>(); + + /** 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 command-line arguments + */ +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.MULTICAST; + 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)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.59135f; + TrackCoor1[1] = -121.88051f; + track.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.59487f; + TrackCoor2[1] = -121.86739f; + track.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.63259f; + TrackCoor3[1] = -121.66926f; + track.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.64481f; + TrackCoor4[1] = -121.61162f; + track.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 35.64239f; + TrackCoor5[1] = -120.68503f; + track.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 35.61577f; + TrackCoor6[1] = -119.65283f; + track.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 34.76589f; + TrackCoor7[1] = -118.79854f; + track.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 34.77651f; + TrackCoor8[1] = -118.17049f; + track.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 34.5806f; + TrackCoor9[1] = -118.1334f; + track.add(TrackCoor9); + +// System.out.println("********" + String.valueOf(track_coordinates[0]) ); +// System.out.println("********" + track_coordinates.get(5)[1]); + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + 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"); + + Float lat = track.get(idx)[0]; + Float lon = track.get(idx)[1]; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java index b0a5973d4b9ff30f275cb388d68115cc8d819182..e5919470b2d09b6e54436817fa7b751dc436f2a5 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java @@ -1,326 +1,334 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class ConardSnellOpenDisEspduSender -{ - 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 command-line arguments - */ -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)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // 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()); - 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 = Math.cos(idx)*20; - lat = Math.sin(idx)*20; -// lon = lon + (direction * 0.00006); -// System.out.println(lon); - - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class ConardSnellOpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + 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 command-line arguments + */ +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)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // 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()); + 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 = Math.cos(idx)*20; + lat = Math.sin(idx)*20; +// lon = lon + (direction * 0.00006); +// System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java index 455674db916051dd908b0f1e5829eaea1980b007..0857a42f7ba7283d360e006384cd2816376fcb2f 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java @@ -1,325 +1,333 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class Hanley_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 command-line arguments - */ -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(224); // UK - entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // M1 Abrams - entityType.setSpec((short)4); // M1A1 w/ mine roller - - - Set<InetAddress> broadcastAddresses; - // Loop through sending N ESPDUs - try - { - System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); - 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.00008); - lat = lat + (direction * 0.00008); - System.out.println(lon); - - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Hanley_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + 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 command-line arguments + */ +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(224); // UK + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)4); // M1A1 w/ mine roller + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + 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.00008); + lat = lat + (direction * 0.00008); + System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java index a2c39578ee49f7a527712772fc1ed2ed2875a390..5235b1563a73c7b53051e808f8d7b8ae6a190693 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java @@ -1,387 +1,395 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class Landas_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; - - public static final ArrayList <Float[]> track_coordinates = new ArrayList<>(); - -/** 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 command-line arguments - */ -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)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)20); // Maintenance equipment trailer(20) - entityType.setSpec((short)3); // M1A2 Abrams - - - Set<InetAddress> broadcastAddresses; - // Loop through sending N ESPDUs - try - { - -// Point point = new Point(); -// point.setX(1.5f); -// point.setY(1.9f); -// -// List<Point> track_coordinates = new ArrayList<Point>(); -// track_coordinates.add(point); -// System.out.println("********" + track_coordinates); - -// ArrayList <Float[]> track_coordinates = new ArrayList<>(); - - Float[] TrackCoor1 = new Float [2]; - TrackCoor1[0] = 36.585657f; - TrackCoor1[1] = -121.879920f; - track_coordinates.add(TrackCoor1); - Float[] TrackCoor2 = new Float [2]; - TrackCoor2[0] = 36.584853f; - TrackCoor2[1] = -121.880024f; - track_coordinates.add(TrackCoor2); - Float[] TrackCoor3 = new Float [2]; - TrackCoor3[0] = 36.583500f; - TrackCoor3[1] = -121.879615f; - track_coordinates.add(TrackCoor3); - Float[] TrackCoor4 = new Float [2]; - TrackCoor4[0] = 36.586307f; - TrackCoor4[1] = -121.874582f; - track_coordinates.add(TrackCoor4); - Float[] TrackCoor5 = new Float [2]; - TrackCoor5[0] = 36.588670f; - TrackCoor5[1] = -121.877928f; - track_coordinates.add(TrackCoor5); - Float[] TrackCoor6 = new Float [2]; - TrackCoor6[0] = 36.591124f; - TrackCoor6[1] = -121.880074f; - track_coordinates.add(TrackCoor6); - Float[] TrackCoor7 = new Float [2]; - TrackCoor7[0] = 36.592827f; - TrackCoor7[1] = -121.877149f; - track_coordinates.add(TrackCoor7); - Float[] TrackCoor8 = new Float [2]; - TrackCoor8[0] = 36.594051f; - TrackCoor8[1] = -121.877452f; - track_coordinates.add(TrackCoor8); - Float[] TrackCoor9 = new Float [2]; - TrackCoor9[0] = 36.594245f; - TrackCoor9[1] = -121.876477f; - track_coordinates.add(TrackCoor9); - Float[] TrackCoor10 = new Float [2]; - TrackCoor10[0] = 36.595230f; - TrackCoor10[1] = -121.877537f; - track_coordinates.add(TrackCoor10); -// System.out.println("********" + String.valueOf(track_coordinates[0]) ); -// System.out.println("********" + track_coordinates.get(5)[1]); - - - -// System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); -// for(int idx = 0; idx < NUMBER_TO_SEND; idx++) - for(int idx = 0; idx < 10; idx++) - { - System.out.println("Sending ESPDU packet " + idx + " to " + destinationIp.toString()); - // 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"); - Float lat = track_coordinates.get(idx)[0]; - Float lon = track_coordinates.get(idx)[1]; - -// double direction = Math.pow((double)(-1.0), (double)(idx)); -// lon = lon + (direction * 0.00006); - - -// System.out.println(lon); - - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Landas_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + 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; + + public static final ArrayList <Float[]> track_coordinates = new ArrayList<>(); + +/** 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 command-line arguments + */ +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)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)20); // Maintenance equipment trailer(20) + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + +// Point point = new Point(); +// point.setX(1.5f); +// point.setY(1.9f); +// +// List<Point> track_coordinates = new ArrayList<Point>(); +// track_coordinates.add(point); +// System.out.println("********" + track_coordinates); + +// ArrayList <Float[]> track_coordinates = new ArrayList<>(); + + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.585657f; + TrackCoor1[1] = -121.879920f; + track_coordinates.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.584853f; + TrackCoor2[1] = -121.880024f; + track_coordinates.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.583500f; + TrackCoor3[1] = -121.879615f; + track_coordinates.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.586307f; + TrackCoor4[1] = -121.874582f; + track_coordinates.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 36.588670f; + TrackCoor5[1] = -121.877928f; + track_coordinates.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 36.591124f; + TrackCoor6[1] = -121.880074f; + track_coordinates.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 36.592827f; + TrackCoor7[1] = -121.877149f; + track_coordinates.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 36.594051f; + TrackCoor8[1] = -121.877452f; + track_coordinates.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 36.594245f; + TrackCoor9[1] = -121.876477f; + track_coordinates.add(TrackCoor9); + Float[] TrackCoor10 = new Float [2]; + TrackCoor10[0] = 36.595230f; + TrackCoor10[1] = -121.877537f; + track_coordinates.add(TrackCoor10); +// System.out.println("********" + String.valueOf(track_coordinates[0]) ); +// System.out.println("********" + track_coordinates.get(5)[1]); + + + +// System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); +// for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + for(int idx = 0; idx < 10; idx++) + { + System.out.println("Sending ESPDU packet " + idx + " to " + destinationIp.toString()); + // 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"); + Float lat = track_coordinates.get(idx)[0]; + Float lon = track_coordinates.get(idx)[1]; + +// double direction = Math.pow((double)(-1.0), (double)(idx)); +// lon = lon + (direction * 0.00006); + + +// System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java index 8db3d7cd7969fc9ad0bb585f9f9415dac785fef2..1f808475bc2985981ba3c41bcffc4e866e12d071 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java @@ -1,365 +1,373 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class 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"; - - public static final ArrayList <Float[]> track = new ArrayList<>(); - - /** 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 command-line arguments - */ -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)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // M1 Abrams - entityType.setSpec((short)3); // M1A2 Abrams - - - Set<InetAddress> broadcastAddresses; - // Loop through sending N ESPDUs - try - { - - Float[] TrackCoor1 = new Float [2]; - TrackCoor1[0] = 36.59135f; - TrackCoor1[1] = -121.88051f; - track.add(TrackCoor1); - Float[] TrackCoor2 = new Float [2]; - TrackCoor2[0] = 36.59487f; - TrackCoor2[1] = -121.86739f; - track.add(TrackCoor2); - Float[] TrackCoor3 = new Float [2]; - TrackCoor3[0] = 36.63259f; - TrackCoor3[1] = -121.66926f; - track.add(TrackCoor3); - Float[] TrackCoor4 = new Float [2]; - TrackCoor4[0] = 36.64481f; - TrackCoor4[1] = -121.61162f; - track.add(TrackCoor4); - Float[] TrackCoor5 = new Float [2]; - TrackCoor5[0] = 35.64239f; - TrackCoor5[1] = -120.68503f; - track.add(TrackCoor5); - Float[] TrackCoor6 = new Float [2]; - TrackCoor6[0] = 35.61577f; - TrackCoor6[1] = -119.65283f; - track.add(TrackCoor6); - Float[] TrackCoor7 = new Float [2]; - TrackCoor7[0] = 34.76589f; - TrackCoor7[1] = -118.79854f; - track.add(TrackCoor7); - Float[] TrackCoor8 = new Float [2]; - TrackCoor8[0] = 34.77651f; - TrackCoor8[1] = -118.17049f; - track.add(TrackCoor8); - Float[] TrackCoor9 = new Float [2]; - TrackCoor9[0] = 34.5806f; - TrackCoor9[1] = -118.1334f; - track.add(TrackCoor9); - -// System.out.println("********" + String.valueOf(track_coordinates[0]) ); -// System.out.println("********" + track_coordinates.get(5)[1]); - System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); - 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"); - - Float lat = track.get(idx)[0]; - Float lon = track.get(idx)[1]; - - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[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 firePdu = new FirePdu(); - byte[] fireArray = firePdu.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 iteratorBroadcastAddresses = broadcastAddresses.iterator(); - while(iteratorBroadcastAddresses.hasNext()) - { - InetAddress broadcastAddress = (InetAddress)iteratorBroadcastAddresses.next(); - System.out.println("Sending broadcast datagram packet to " + broadcastAddress); - DatagramPacket packet = new DatagramPacket(data, data.length, broadcastAddress, 3000); - socket.send(packet); - // TODO experiment with these! 8) - packet = new DatagramPacket(fireArray, fireArray.length, broadcastAddress, 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; // skip to next iterator value - - //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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + public static final ArrayList <Float[]> track = new ArrayList<>(); + + /** 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 command-line arguments + */ +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)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.59135f; + TrackCoor1[1] = -121.88051f; + track.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.59487f; + TrackCoor2[1] = -121.86739f; + track.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.63259f; + TrackCoor3[1] = -121.66926f; + track.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.64481f; + TrackCoor4[1] = -121.61162f; + track.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 35.64239f; + TrackCoor5[1] = -120.68503f; + track.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 35.61577f; + TrackCoor6[1] = -119.65283f; + track.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 34.76589f; + TrackCoor7[1] = -118.79854f; + track.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 34.77651f; + TrackCoor8[1] = -118.17049f; + track.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 34.5806f; + TrackCoor9[1] = -118.1334f; + track.add(TrackCoor9); + +// System.out.println("********" + String.valueOf(track_coordinates[0]) ); +// System.out.println("********" + track_coordinates.get(5)[1]); + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + 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"); + + Float lat = track.get(idx)[0]; + Float lon = track.get(idx)[1]; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[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 firePdu = new FirePdu(); + byte[] fireArray = firePdu.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 iteratorBroadcastAddresses = broadcastAddresses.iterator(); + while(iteratorBroadcastAddresses.hasNext()) + { + InetAddress broadcastAddress = (InetAddress)iteratorBroadcastAddresses.next(); + System.out.println("Sending broadcast datagram packet to " + broadcastAddress); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcastAddress, 3000); + socket.send(packet); + // TODO experiment with these! 8) + packet = new DatagramPacket(fireArray, fireArray.length, broadcastAddress, 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; // skip to next iterator value + + //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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java index 3f8d30eb5cd4eda9b98eb16a7b6f76e5bfab20b5..c583e0f4eec158f9dfb214354df8f65255104ec2 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java @@ -1,299 +1,307 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class Sasala_OpenDisEspduSender1 -{ - 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 command-line arguments - */ -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 radians = 0; - - // 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)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // 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()); - 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. - - radians = (radians + (Math.PI/6)) % (2*Math.PI); - - Vector3Double location = espdu.getEntityLocation(); - location.setX(Math.cos(radians)*1000); - location.setY(Math.sin(radians)*1000); - location.setZ(250); - - // Optionally, we can do some rotation of the entity - - Orientation orientation = espdu.getEntityOrientation(); - orientation.setTheta((float)(radians + (Math.PI/2))%(float)(Math.PI *2)); - - // 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() + "]"); - System.out.println(" Orientation: " + orientation.getTheta()); - //System.out.println(" Location (lat/lon/alt): [" + lat + ", " + 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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Sasala_OpenDisEspduSender1 +{ + public static final int NUMBER_TO_SEND = 5000; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + 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 command-line arguments + */ +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 radians = 0; + + // 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)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // 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()); + 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. + + radians = (radians + (Math.PI/6)) % (2*Math.PI); + + Vector3Double location = espdu.getEntityLocation(); + location.setX(Math.cos(radians)*1000); + location.setY(Math.sin(radians)*1000); + location.setZ(250); + + // Optionally, we can do some rotation of the entity + + Orientation orientation = espdu.getEntityOrientation(); + orientation.setTheta((float)(radians + (Math.PI/2))%(float)(Math.PI *2)); + + // 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() + "]"); + System.out.println(" Orientation: " + orientation.getTheta()); + //System.out.println(" Location (lat/lon/alt): [" + lat + ", " + 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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java index 0adc83480016be4e7358692ba746befb99b606d9..f3a80329ee7447cbadb904b0916adc61476101f4 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java @@ -1,371 +1,379 @@ package MV3500Cohort2018JanuaryMarch.homework3; -// 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.*; // OpenDIS version 4 -import edu.nps.moves.disutil.CoordinateConversions; -import edu.nps.moves.disutil.DisTime; - -/** - * Creates and sends ESPDUs in IEEE binary format. - * - * @author DMcG - */ -public class Tackett_Assignment3_OpenDisEspduSender -{ - public static final int NUMBER_TO_SEND = 10; - - 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; - - public static final ArrayList <Float[]> track_coordinates = new ArrayList<>(); - -/** 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 command-line arguments - */ -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; - - // Lat/Lon coordinates -// double lat = 36.616366; -// double lon = -121.913065; - - // 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)1); // Land (vs air, surface, subsurface, space) - entityType.setCategory((short)1); // Tank - entityType.setSubcategory((short)1); // M1 Abrams - entityType.setSpec((short)3); // M1A2 Abrams - - - Set<InetAddress> broadcastAddresses; - // Loop through sending N ESPDUs - try - { - Float[] TrackCoor1 = new Float [2]; - TrackCoor1[0] = 36.585657f; - TrackCoor1[1] = -121.879920f; - track_coordinates.add(TrackCoor1); - Float[] TrackCoor2 = new Float [2]; - TrackCoor2[0] = 36.584853f; - TrackCoor2[1] = -121.880024f; - track_coordinates.add(TrackCoor2); - Float[] TrackCoor3 = new Float [2]; - TrackCoor3[0] = 36.583500f; - TrackCoor3[1] = -121.879615f; - track_coordinates.add(TrackCoor3); - Float[] TrackCoor4 = new Float [2]; - TrackCoor4[0] = 36.586307f; - TrackCoor4[1] = -121.874582f; - track_coordinates.add(TrackCoor4); - Float[] TrackCoor5 = new Float [2]; - TrackCoor5[0] = 36.588670f; - TrackCoor5[1] = -121.877928f; - track_coordinates.add(TrackCoor5); - Float[] TrackCoor6 = new Float [2]; - TrackCoor6[0] = 36.591124f; - TrackCoor6[1] = -121.880074f; - track_coordinates.add(TrackCoor6); - Float[] TrackCoor7 = new Float [2]; - TrackCoor7[0] = 36.592827f; - TrackCoor7[1] = -121.877149f; - track_coordinates.add(TrackCoor7); - Float[] TrackCoor8 = new Float [2]; - TrackCoor8[0] = 36.594051f; - TrackCoor8[1] = -121.877452f; - track_coordinates.add(TrackCoor8); - Float[] TrackCoor9 = new Float [2]; - TrackCoor9[0] = 36.594245f; - TrackCoor9[1] = -121.876477f; - track_coordinates.add(TrackCoor9); - Float[] TrackCoor10 = new Float [2]; - TrackCoor10[0] = 36.595230f; - TrackCoor10[1] = -121.877537f; - track_coordinates.add(TrackCoor10); - - //System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); - for(int idx = 0; idx < NUMBER_TO_SEND; idx++) - { - System.out.println("Sending espdu packet" + idx + " to " + destinationIp.toString()); - // 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); - - Float lat = track_coordinates.get(idx)[0]; - Float lon = track_coordinates.get(idx)[1]; - - double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); - Vector3Double location = espdu.getEntityLocation(); - location.setX(disCoordinates[0]); - location.setY(disCoordinates[1]); - location.setZ(disCoordinates[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; - } - -} +// 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.*; // OpenDIS version 4 +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Tackett_Assignment3_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 10; + + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + 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; + + public static final ArrayList <Float[]> track_coordinates = new ArrayList<>(); + +/** 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 command-line arguments + */ +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; + + // Lat/Lon coordinates +// double lat = 36.616366; +// double lon = -121.913065; + + // 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)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.585657f; + TrackCoor1[1] = -121.879920f; + track_coordinates.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.584853f; + TrackCoor2[1] = -121.880024f; + track_coordinates.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.583500f; + TrackCoor3[1] = -121.879615f; + track_coordinates.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.586307f; + TrackCoor4[1] = -121.874582f; + track_coordinates.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 36.588670f; + TrackCoor5[1] = -121.877928f; + track_coordinates.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 36.591124f; + TrackCoor6[1] = -121.880074f; + track_coordinates.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 36.592827f; + TrackCoor7[1] = -121.877149f; + track_coordinates.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 36.594051f; + TrackCoor8[1] = -121.877452f; + track_coordinates.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 36.594245f; + TrackCoor9[1] = -121.876477f; + track_coordinates.add(TrackCoor9); + Float[] TrackCoor10 = new Float [2]; + TrackCoor10[0] = 36.595230f; + TrackCoor10[1] = -121.877537f; + track_coordinates.add(TrackCoor10); + + //System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + System.out.println("Sending espdu packet" + idx + " to " + destinationIp.toString()); + // 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); + + Float lat = track_coordinates.get(idx)[0]; + Float lon = track_coordinates.get(idx)[1]; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[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/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java index 9be3ee502f72a5a0bea32e33ec28620a71f08eda..bc635f11ab087c913066097771d86ec4ed869721 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java @@ -22,7 +22,15 @@ public class YamashitaDeMouraOpenDisEspduSender { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** Default multicast group address we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java index 517d24d313605f28ef491b32b1a3e32495c0b532..0e9f0d0772414bc8bb11e6e4c81a4fd3261faec5 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java @@ -19,7 +19,15 @@ public class AngelBlankEspduSenderA { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** default multicast group we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.4"; diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java index 937790154dca98c355af6a586586ae6d68156152..c8b184b3686251387d78ff38a68e4957a050de07 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java @@ -18,7 +18,15 @@ import edu.nps.moves.disutil.DisTime; public class AngelBlankEspduSenderB { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** default multicast group we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; /** Port we send on */ diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java index 1314bb186b33ee406a80695c1e27e4da52c3dc9e..f7e4756f1d5685458dacd6de33daefd2b94dd92e 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java @@ -20,7 +20,15 @@ import edu.nps.moves.disutil.DisTime; public class AngelBlankEspduTCPReceiverASenderB { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** default multicast group we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; public static final int MAX_PDU_SIZE = 8192; diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java index fab25f7119a92be8e4bc05b6f4fb33017c29cad9..1aaa3de18adcd3e48f071e46463d7d766860291c 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java @@ -19,7 +19,15 @@ public class AngelBlankEspduTCPReceiverBSenderA { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; public static final int MAX_PDU_SIZE = 8192; /** default multicast group we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.4"; diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/Hanley/HanleyOpenDisEspduSenderFP.java b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/Hanley/HanleyOpenDisEspduSenderFP.java index 9b31f8a3355063f3afc32f9ba456ca07d58f14f7..688199cd26c8a5a63524909d93e2a85ff3f9e705 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/Hanley/HanleyOpenDisEspduSenderFP.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/Hanley/HanleyOpenDisEspduSenderFP.java @@ -28,7 +28,15 @@ public class HanleyOpenDisEspduSenderFP { //public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** Default multicast group address we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; diff --git a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java index d38a0c90e7e34edb74f098eef91cc6442489adae..2ee59198cd39b01f18a4681efffd3920a2d2e221 100644 --- a/assignments/src/MV3500Cohort2018JanuaryMarch/projects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java +++ b/assignments/src/MV3500Cohort2018JanuaryMarch/projects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java @@ -37,7 +37,15 @@ public class CSVreaderOpenDisEspduSenderFP public static final int RECEIVING_PORT = 1415; public static final String DESTINATION_HOST = "localhost"; - public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** Default multicast group address we send on */ public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; diff --git a/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduRequestingUnit.java b/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduRequestingUnit.java index 7a9330cc91b0f7efce3c340485243c53923de518..56c899357447ecb48e232f2fc586d8f5ecb3898c 100644 --- a/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduRequestingUnit.java +++ b/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduRequestingUnit.java @@ -19,9 +19,15 @@ public class C_T_EspduRequestingUnit { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST - }; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; public static final int MAX_PDU_SIZE = 8192; diff --git a/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduSupplyerUnit.java b/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduSupplyerUnit.java index e5d9dffc9ef6f54ac61c642389ae7fd6e8a14f47..e0df5d66cbd0d37877ec437b189d0c65f7ab0672 100644 --- a/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduSupplyerUnit.java +++ b/assignments/src/MV3500Cohort2018JulySeptember/projects/CainThomersonFinal/C_T_EspduSupplyerUnit.java @@ -21,9 +21,15 @@ public class C_T_EspduSupplyerUnit { public static final int NUMBER_TO_SEND = 5000; - public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST - }; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; public static final int MAX_PDU_SIZE = 8192; diff --git a/assignments/src/MV3500Cohort2019JulySeptember/homework4/Brennenstuhl/BrennenstuhlEspduSender.java b/assignments/src/MV3500Cohort2019JulySeptember/homework4/Brennenstuhl/BrennenstuhlEspduSender.java index b8feae689d51a936dc38e87edfba315fd694aabb..3523e189825bbc6f4c533d99e6ac093a612a5863 100644 --- a/assignments/src/MV3500Cohort2019JulySeptember/homework4/Brennenstuhl/BrennenstuhlEspduSender.java +++ b/assignments/src/MV3500Cohort2019JulySeptember/homework4/Brennenstuhl/BrennenstuhlEspduSender.java @@ -32,8 +32,14 @@ public class BrennenstuhlEspduSender */ public static final int DEFAULT_MULTICAST_PORT = 3000; + /** Type of network connection */ public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST }; /** diff --git a/assignments/src/MV3500Cohort2019JulySeptember/homework4/Schutt/SchuttESPDUSender.java b/assignments/src/MV3500Cohort2019JulySeptember/homework4/Schutt/SchuttESPDUSender.java index d332eed0443baab5630141d33f20297eb0f2323d..c84558a28f586f269d91fbf8783899430091a92d 100644 --- a/assignments/src/MV3500Cohort2019JulySeptember/homework4/Schutt/SchuttESPDUSender.java +++ b/assignments/src/MV3500Cohort2019JulySeptember/homework4/Schutt/SchuttESPDUSender.java @@ -38,9 +38,15 @@ public class SchuttESPDUSender { */ public static final int DEFAULT_MULTICAST_PORT = 3002; - public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST - }; + /** Type of network connection */ + public enum NetworkMode { + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST + }; /** * Possible system properties, passed in via -Dattr=val networkMode: diff --git a/assignments/src/MV3500Cohort2019JulySeptember/homework4/Yurkovich/Yurk_EspduSender.java b/assignments/src/MV3500Cohort2019JulySeptember/homework4/Yurkovich/Yurk_EspduSender.java index 11af1378435251a29987cd0c913870f4296cb8d7..257f567ba59e4d9420577aa1ac8927592862d479 100644 --- a/assignments/src/MV3500Cohort2019JulySeptember/homework4/Yurkovich/Yurk_EspduSender.java +++ b/assignments/src/MV3500Cohort2019JulySeptember/homework4/Yurkovich/Yurk_EspduSender.java @@ -28,8 +28,14 @@ public class Yurk_EspduSender */ public static final int DEFAULT_MULTICAST_PORT = 3000; + /** Type of network connection */ public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST }; /** diff --git a/assignments/src/MV3500Cohort2020JulySeptember/homework4/Britt/EspduSender.java b/assignments/src/MV3500Cohort2020JulySeptember/homework4/Britt/EspduSender.java index 714cc23e6358a46c4ce03b7c231d221d950d8f0a..fe1de553dfd148c75a8e355e80aa8524d33c974d 100644 --- a/assignments/src/MV3500Cohort2020JulySeptember/homework4/Britt/EspduSender.java +++ b/assignments/src/MV3500Cohort2020JulySeptember/homework4/Britt/EspduSender.java @@ -35,9 +35,15 @@ public class EspduSender * Default multicast port used, matches Wireshark DIS capture default */ public static final int DEFAULT_MULTICAST_PORT = 3000; - + + /** Type of network connection */ public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST }; /** diff --git a/examples/src/OpenDis4Examples/EspduReceiver.java b/examples/src/OpenDis4Examples/EspduReceiver.java index 4f9be5581246fbffcc3d0f3bd018d6822fdc693d..4783ef6437959963f376bdf9dc6109664e155685 100644 --- a/examples/src/OpenDis4Examples/EspduReceiver.java +++ b/examples/src/OpenDis4Examples/EspduReceiver.java @@ -22,10 +22,12 @@ public class EspduReceiver */ private static final int MAX_PDU_SIZE = 8192; - /** Default multicast group address we send on. */ + /** Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ private static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3"; - /** Default multicast port used, matches Wireshark DIS capture default */ + /** Default multicast port used, matches Wireshark DIS capture default + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ private static final int DEFAULT_MULTICAST_PORT = 3000; /** diff --git a/examples/src/OpenDis4Examples/EspduSender.java b/examples/src/OpenDis4Examples/EspduSender.java index c4a472c130c0cd0b3759507e69804d817b48d064..d5a95c03ac678efbe86a83e0bdda89e6be5f0151 100644 --- a/examples/src/OpenDis4Examples/EspduSender.java +++ b/examples/src/OpenDis4Examples/EspduSender.java @@ -16,10 +16,18 @@ import edu.nps.moves.disutil.DisTime; */ public class EspduSender { + /** Defining number of packets to send is superior to infinite loops + * which have possible hazard of unstoppably sending packets as a zombie process */ public static final int NUMBER_TO_SEND = 5000; + /** Type of network connection */ public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST }; /** @@ -29,6 +37,7 @@ public class EspduSender { /** * Default multicast port used, matches Wireshark DIS capture default + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = 3000; diff --git a/examples/src/OpenDis4Examples/PduReceiver.java b/examples/src/OpenDis4Examples/PduReceiver.java index 1014866879ac8ac34302f9d336d6beb0fbd05468..10075dc020ed5c097b57e963c698d173a1e4e66a 100644 --- a/examples/src/OpenDis4Examples/PduReceiver.java +++ b/examples/src/OpenDis4Examples/PduReceiver.java @@ -8,6 +8,7 @@ import edu.nps.moves.dis.*; import edu.nps.moves.disutil.PduFactory; import java.io.IOException; +/** Listen for IEEE DIS Protocol Data Units (PDUs) */ public class PduReceiver { private static final int MULTICAST_PORT = 3000; diff --git a/examples/src/OpenDis4Examples/PduSender.java b/examples/src/OpenDis4Examples/PduSender.java index f8be22550487343b808a08eb102945c2721f95a9..eac0ae10ee8113939d6c9cc263b22db241eb5ca8 100644 --- a/examples/src/OpenDis4Examples/PduSender.java +++ b/examples/src/OpenDis4Examples/PduSender.java @@ -18,15 +18,20 @@ import edu.nps.moves.examples.ClassNameComparator; */ public class PduSender { - /** Default multicast group address we send on. */ + /** Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ private static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3"; - /** Default multicast port used, matches Wireshark DIS capture default */ + /** Default multicast port used, matches Wireshark DIS capture default + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ private static final int DEFAULT_MULTICAST_PORT = 3000; private int port; InetAddress multicastAddress; + /** Object constructor + * @param port port of interest + * @param multicast address of interest */ public PduSender(int port, String multicast) { try { @@ -42,6 +47,7 @@ public class PduSender } } + /** Begin operations */ public void run() { System.out.println("OpenDis4Examples.PduSender started..."); diff --git a/examples/src/OpenDis7Examples/AllPduReceiver.java b/examples/src/OpenDis7Examples/AllPduReceiver.java index e1a4b39af41b136be84680ab905b1cf219709cb3..80b54da677f4fc641916488eca6a7aaca411a092 100644 --- a/examples/src/OpenDis7Examples/AllPduReceiver.java +++ b/examples/src/OpenDis7Examples/AllPduReceiver.java @@ -8,10 +8,14 @@ import edu.nps.moves.dis7.enumerations.*; import edu.nps.moves.dis7.utilities.PduFactory; import java.util.ArrayList; +/** Listen to all kinds of PDUs and report them */ public class AllPduReceiver { + /** @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String DEFAULT_MULTICAST_ADDRESS = AllPduSender.DEFAULT_MULTICAST_ADDRESS; + /** @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = AllPduSender.DEFAULT_MULTICAST_PORT; + /** TODO whether to use Fast ESPDU */ public static final boolean USE_FAST_ESPDU = false; /** diff --git a/examples/src/OpenDis7Examples/AllPduSender.java b/examples/src/OpenDis7Examples/AllPduSender.java index 47dd38024b60cb5e6b4c0eaebd7145cb81d58b1c..867fdc5eaf4d297793a88c4238636508943b5839 100755 --- a/examples/src/OpenDis7Examples/AllPduSender.java +++ b/examples/src/OpenDis7Examples/AllPduSender.java @@ -17,10 +17,12 @@ import edu.nps.moves.dis7.enumerations.*; */ public class AllPduSender { - /** Default multicast group address we send on. */ + /** Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3"; // PduRecorder "225.4.5.6"; // - /** Default multicast port used, matches Wireshark DIS capture default */ + /** Default multicast port used, matches Wireshark DIS capture default + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = 3000; /** Duration in milliseconds, set to 0 to avoid pausing between PDU sends */ @@ -32,6 +34,9 @@ public class AllPduSender private static InetAddress multicastAddress; private static int port; + /** Object constructor + * @param newMulticastAddress address of interest + * @param newMulticastPort port of interest */ public AllPduSender(String newMulticastAddress, int newMulticastPort) { this.port = DEFAULT_MULTICAST_PORT; try @@ -48,6 +53,8 @@ public class AllPduSender } } + /** Begin operations + * @return number of PDUs received, -1 if exception occurs */ @SuppressWarnings("SleepWhileInLoop") public int run() { diff --git a/examples/src/OpenDis7Examples/EspduReceiver.java b/examples/src/OpenDis7Examples/EspduReceiver.java index ec55541a94be1c6026b6315b35965a4fdab0b6e0..0bd1413c36d1bf84c083ea8a2c2f54301e63e06f 100755 --- a/examples/src/OpenDis7Examples/EspduReceiver.java +++ b/examples/src/OpenDis7Examples/EspduReceiver.java @@ -21,10 +21,12 @@ public class EspduReceiver */ private static final int MAX_PDU_SIZE = 8192; - /** Default multicast group address we send on. */ + /** Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String DEFAULT_MULTICAST_ADDRESS = EspduSender.DEFAULT_MULTICAST_ADDRESS; - /** Default multicast port used, matches Wireshark DIS capture default */ + /** Default multicast port used, matches Wireshark DIS capture default + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = EspduSender.DEFAULT_MULTICAST_PORT; /** diff --git a/examples/src/OpenDis7Examples/EspduSender.java b/examples/src/OpenDis7Examples/EspduSender.java index ee0cc276cb42246dbc6a82a300010b6794db34a7..67d743a2c11fafc6e0e170a6dc763ca1da4346ea 100644 --- a/examples/src/OpenDis7Examples/EspduSender.java +++ b/examples/src/OpenDis7Examples/EspduSender.java @@ -27,16 +27,22 @@ public class EspduSender /** * Default multicast group address we send on. - */ + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3"; /** * Default multicast port used, matches Wireshark DIS capture default - */ + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = 3000; - + + /** Type of network connection */ public enum NetworkMode { - UNICAST, MULTICAST, BROADCAST + /** @see <a href="https://en.wikipedia.org/wiki/Unicast">https://en.wikipedia.org/wiki/Unicast</a> */ + UNICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Multicast">https://en.wikipedia.org/wiki/Multicast</a> */ + MULTICAST, + /** @see <a href="https://en.wikipedia.org/wiki/Broadcasting_(networking)">https://en.wikipedia.org/wiki/Broadcasting_(networking)</a> */ + BROADCAST }; /** diff --git a/examples/src/OpenDis7Examples/ExampleSimulationProgram.java b/examples/src/OpenDis7Examples/ExampleSimulationProgram.java index 19263d3685b695a5b6d5f3bfd4623f74fb06543b..1bac574dcf255dbd85997f177c9e96358c7a1458 100644 --- a/examples/src/OpenDis7Examples/ExampleSimulationProgram.java +++ b/examples/src/OpenDis7Examples/ExampleSimulationProgram.java @@ -16,6 +16,7 @@ import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; +/** The purpose of this program is to provide an easily modifiable example simulation program. */ public class ExampleSimulationProgram { // class variables diff --git a/examples/src/OpenDis7Examples/PduListenerSaver.java b/examples/src/OpenDis7Examples/PduListenerSaver.java index 422bb6305493a416b2fcdc89b93b43f80aa70014..c8bbedc15a14db2b032deb007d8dd1d5258a3987 100644 --- a/examples/src/OpenDis7Examples/PduListenerSaver.java +++ b/examples/src/OpenDis7Examples/PduListenerSaver.java @@ -21,7 +21,11 @@ import java.util.Scanner; public class PduListenerSaver { private final static String DEFAULT_OUTPUT_DIRECTORY = "pduLog"; + /** + * Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String DEFAULT_MULTICAST_ADDRESS = AllPduSender.DEFAULT_MULTICAST_ADDRESS; + /** @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = AllPduSender.DEFAULT_MULTICAST_PORT; private enum mystate diff --git a/examples/src/OpenDis7Examples/PduReaderPlayer.java b/examples/src/OpenDis7Examples/PduReaderPlayer.java index 5707b732d08f82fa9853d7b87c24e83965b28b5e..4fe2c57cad241f4d91e3321274987d7e7fc5a58b 100644 --- a/examples/src/OpenDis7Examples/PduReaderPlayer.java +++ b/examples/src/OpenDis7Examples/PduReaderPlayer.java @@ -22,7 +22,10 @@ import java.util.Scanner; public class PduReaderPlayer { private final static String DEFAULT_OUTPUT_DIRECTORY = "pduLog"; + /** Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String DEFAULT_MULTICAST_ADDRESS = AllPduSender.DEFAULT_MULTICAST_ADDRESS; + /** @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DEFAULT_MULTICAST_PORT = AllPduSender.DEFAULT_MULTICAST_PORT; private enum mystate diff --git a/examples/src/TcpExamples/TcpExample3Client.java b/examples/src/TcpExamples/TcpExample3Client.java index 48d46c3f2bfed71903c733b98583901dc7a8c2e9..bc7baabc400a93d84490993dca579e1bbefe274b 100644 --- a/examples/src/TcpExamples/TcpExample3Client.java +++ b/examples/src/TcpExamples/TcpExample3Client.java @@ -16,7 +16,9 @@ import java.net.*; */ public class TcpExample3Client { - // IPv6 String constant for localhost address, similarly IPv4 127.0.0.1 + /** IPv6 String constant for localhost address, similarly IPv4 127.0.0.1 + * @see <a href="https://en.wikipedia.org/wiki/localhost">https://en.wikipedia.org/wiki/localhost</a> + * @see <a href="https://en.wikipedia.org/wiki/IPv6_address">https://en.wikipedia.org/wiki/IPv6_address</a> */ public final static String LOCALHOST = "0:0:0:0:0:0:0:1"; /** diff --git a/examples/src/UdpMulticastExamples/MulticastSender.java b/examples/src/UdpMulticastExamples/MulticastSender.java index 28820bebd8d9e2cb83334a2e24c9196638b9e25d..9a1f4a7141c1b9a34e1ac02570f92cd2e47b4726 100644 --- a/examples/src/UdpMulticastExamples/MulticastSender.java +++ b/examples/src/UdpMulticastExamples/MulticastSender.java @@ -17,10 +17,13 @@ import java.util.logging.Logger; public class MulticastSender { // reserved range for all IPv4 multicast: 224.0.0.0 through 239.255.255.255 - // https://en.wikipedia.org/wiki/Multicast_address // https://www.iana.org/assignments/multicast-addresses/multicast-addresses.xhtml + /** Default multicast group address we send on. + * @see <a href="https://en.wikipedia.org/wiki/Multicast_address">https://en.wikipedia.org/wiki/Multicast_address</a> */ public static final String MULTICAST_ADDRESS = "239.1.2.15"; // within reserved multicast address range + /** Default multicast port used, matches Wireshark DIS capture default + * @see <a href="https://en.wikipedia.org/wiki/Port_(computer_networking)">https://en.wikipedia.org/wiki/Port_(computer_networking)</a> */ public static final int DESTINATION_PORT = 1718; /** Time to live: how many router-decrement levels can be crossed */ @@ -29,6 +32,8 @@ public class MulticastSender { /** How many packets to send prior to termination */ public static final int LOOPSIZE = 20; // 20000 + /** Receiving this message causes termination + * @see <a href="https://en.wikipedia.org/wiki/Sentinel_value">https://en.wikipedia.org/wiki/Sentinel_value</a> */ public static final String QUIT_SENTINEL = "QUIT QUIT QUIT!"; private static NetworkInterface ni;