Skip to content
Snippets Groups Projects
Commit 3ab37360 authored by Schutt, Thomas (Capt)'s avatar Schutt, Thomas (Capt)
Browse files

Schutt and Fetterolf project, pre final revisions.

parent 5a53822e
No related branches found
No related tags found
No related merge requests found
Showing
with 278138 additions and 753 deletions
......@@ -17,7 +17,7 @@ import java.util.Scanner;
*/
public class SchuttPDUSaverListener
{
private final static String DEFAULT_OUTPUTDIR = "pduLog";
private final static String DEFAULT_OUTPUTDIR = "src//MV3500Cohort2019JulySeptember//projects//SchuttFetterolf//pduLog";
private final static String MCAST_ADDR = "239.1.2.3";
private final static int DIS_PORT = 3002;
......
// THIS CODE IS FOR REFERENCE ONLY IN THIS DIRECTORY.
// TO ACCESS FULL FUNCTIONALITY DOWNLOAD THE DIS7 PROJECT FROM GITLAB
// https://github.com/open-dis/open-dis7-java
///**
// * Copyright (c) 2008-2019, MOVES Institute, Naval Postgraduate School. All rights reserved.
// * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html
// */
//package edu.nps.moves.dis7;
//
///**
// * This is a test class (which can also be run through its main() method) which tests round-tripping of pdus, i.e.,
// * creating a pdu instance in java, serializing it and sending over the network as a stream of bytes, at the same time
// * reading them back from the net. It also uses the pdu logger in the Player class to save the received pdus to disk.
// *
// * Two tests for pdu equivalency are performed:
// * 1. Sent vs. received
// * 2. Sent vs. persisted
// *
// * @author Mike Bailey, jmbailey@edu.nps.edu
// * @version $Id$
// */
//import com.google.common.io.Files;
//import edu.nps.moves.dis7.enumerations.Country;
//import edu.nps.moves.dis7.enumerations.DISPDUType;
//import edu.nps.moves.dis7.util.DisThreadedNetIF;
//import edu.nps.moves.dis7.util.PduFactory;
//import edu.nps.moves.dis7.util.playerrecorder.Player;
//import edu.nps.moves.dis7.util.playerrecorder.Recorder;
//import java.io.File;
//import java.util.HashMap;
//import java.util.concurrent.Semaphore;
//import org.junit.jupiter.api.*;
//import static org.junit.jupiter.api.Assertions.*;
//
//@DisplayName("All Pdu Round Trip Test")
//
//public class AllPduRoundTripTest
//{
// private PduFactory fact;
//
// @BeforeAll
// public static void beforeAllTests()
// {
// System.out.println("AllPduRoundTripTest");
// }
//
// @AfterAll
// public static void afterAllTests()
// {
// }
//
// @BeforeEach
// public void setUp()
// {
// }
//
// @AfterEach
// public void tearDown()
// {
// }
//
// @Test
// public void testRoundTripAllPdus()
// {
// Throwable ex = null;
// try {
// setupReceiver();
// setupRecorder();
//
// fact = new PduFactory(Country.PHILIPPINES_PHL, (byte) 11, (byte) 22, (short) 33, true);
//
// sendOne(fact.makeAcknowledgePdu());
// sendOne(fact.makeAcknowledgeReliablePdu());
// sendOne(fact.makeActionRequestPdu());
// sendOne(fact.makeActionRequestReliablePdu());
// sendOne(fact.makeActionResponsePdu());
// sendOne(fact.makeActionResponseReliablePdu());
// sendOne(fact.makeAggregateStatePdu());
// sendOne(fact.makeAppearancePdu());
// sendOne(fact.makeArealObjectStatePdu());
// sendOne(fact.makeArticulatedPartsPdu());
// sendOne(fact.makeAttributePdu());
// sendOne(fact.makeCollisionElasticPdu());
// sendOne(fact.makeCollisionPdu());
// sendOne(fact.makeCommentPdu());
// sendOne(fact.makeCommentReliablePdu());
// sendOne(fact.makeCreateEntityPdu());
// sendOne(fact.makeCreateEntityReliablePdu());
// sendOne(fact.makeDataPdu());
// sendOne(fact.makeDataQueryPdu());
// sendOne(fact.makeDataQueryReliablePdu());
// sendOne(fact.makeDataReliablePdu());
// sendOne(fact.makeDesignatorPdu());
// sendOne(fact.makeDetonationPdu());
// sendOne(fact.makeDirectedEnergyFirePdu());
// sendOne(fact.makeElectronicEmissionsPdu());
// sendOne(fact.makeEntityDamageStatusPdu());
// sendOne(fact.makeEntityStatePdu());
// sendOne(fact.makeEntityStateUpdatePdu());
// sendOne(fact.makeEnvironmentalProcessPdu());
// sendOne(fact.makeEventReportPdu());
// sendOne(fact.makeEventReportReliablePdu());
// sendOne(fact.makeFirePdu());
// sendOne(fact.makeGriddedDataPdu());
// sendOne(fact.makeIffPdu());
// sendOne(fact.makeInformationOperationsReportPdu());
// sendOne(fact.makeInformationOperationsActionPdu());
// sendOne(fact.makeIntercomControlPdu());
// sendOne(fact.makeIntercomSignalPdu());
// sendOne(fact.makeIsGroupOfPdu());
// sendOne(fact.makeIsPartOfPdu());
// sendOne(fact.makeLEDetonationPdu());
// sendOne(fact.makeLEFirePdu());
// sendOne(fact.makeLinearObjectStatePdu());
// sendOne(fact.makeMinefieldDataPdu());
// sendOne(fact.makeMinefieldQueryPdu());
// sendOne(fact.makeMinefieldResponseNackPdu());
// sendOne(fact.makeMinefieldStatePdu());
// sendOne(fact.makePointObjectStatePdu());
// sendOne(fact.makeReceiverPdu());
// sendOne(fact.makeRecordQueryReliablePdu());
// sendOne(fact.makeRecordReliablePdu());
// sendOne(fact.makeRemoveEntityPdu());
// sendOne(fact.makeRemoveEntityReliablePdu());
// sendOne(fact.makeRepairCompletePdu());
// sendOne(fact.makeRepairResponsePdu());
// sendOne(fact.makeResupplyCancelPdu());
// sendOne(fact.makeResupplyOfferPdu());
// sendOne(fact.makeResupplyReceivedPdu());
// sendOne(fact.makeSeesPdu());
// sendOne(fact.makeServiceRequestPdu());
// sendOne(fact.makeSetDataPdu());
// sendOne(fact.makeSetDataReliablePdu());
// sendOne(fact.makeSetRecordReliablePdu());
// sendOne(fact.makeSignalPdu());
// sendOne(fact.makeStartResumePdu());
// sendOne(fact.makeStartResumeReliablePdu());
// sendOne(fact.makeStopFreezePdu());
// sendOne(fact.makeStopFreezeReliablePdu());
// sendOne(fact.makeTransferOwnershipPdu());
// sendOne(fact.makeTransmitterPdu());
// sendOne(fact.makeTspiPdu());
// sendOne(fact.makeUnderwaterAcousticPdu());
//
// sleep(1000L);
//
// assertTrue(pduReceivedMap.size() == pduSentMap.size(),"No pdus, or not all sent pdus, received");
//
// shutDownReceiver();
// shutDownRecorder();
//
// testForEquals();
//
// Semaphore mutex = new Semaphore(1);
// getAllFromRecorder(mutex);
// mutex.acquire(); // wait until above method is done
//
// testRecorderForEquals();
// }
// catch (Throwable t) {
// ex = t;
// System.out.println(t.getLocalizedMessage());
// t.printStackTrace();
// }
//
// assertNull(ex, "Exception should be null if successful creation of all objects");
// }
//
// private File recorderDirectory;
// private HashMap<DISPDUType, Pdu> pduSentMap = new HashMap<>();
// private HashMap<DISPDUType, Pdu> pduReceivedMap = new HashMap<>();
// private HashMap<DISPDUType, Pdu> pduReadMap = new HashMap<>();
//
// DisThreadedNetIF disnetworking;
// Recorder recorder;
//
// private void setupReceiver()
// {
// disnetworking = new DisThreadedNetIF();
// disnetworking.addListener(pdu -> {
// pduReceivedMap.put(pdu.getPduType(), pdu);
// });
// }
//
// private void shutDownReceiver()
// {
// disnetworking.kill();
// }
//
// private void sendOne(Pdu pdu)
// {
// pduSentMap.put(pdu.getPduType(), pdu);
// disnetworking.send(pdu);
// }
//
// private void setupRecorder() throws Exception
// {
// recorderDirectory = Files.createTempDir();
// recorder = new Recorder(recorderDirectory.getAbsolutePath(), disnetworking.getMcastGroup(), disnetworking.getDisPort());
// System.out.println("Recorder log at " + recorderDirectory.getAbsolutePath());
// }
//
// private void shutDownRecorder() throws Exception
// {
// recorder.end();
// }
//
// private void testForEquals() throws Exception
// {
// assertEquals(pduSentMap.size(), pduReceivedMap.size(), "Different number of pdus received than sent");
//
// pduSentMap.keySet().forEach(typ -> assertTrue(pduSentMap.get(typ).equals(pduReceivedMap.get(typ)), "Sent and received pdus not identical"));
// }
//
// private void getAllFromRecorder(Semaphore sem) throws Exception
// {
// sem.acquire();
// Player player = new Player(disnetworking.getMcastGroup(), disnetworking.getDisPort(), recorderDirectory.toPath());
// player.sendToNet(false);
// player.addRawListener(ba -> {
// if (ba != null) {
// Pdu pdu = fact.createPdu(ba);
// pduReadMap.put(pdu.getPduType(), pdu);
// }
// else {
// player.end();
// sem.release();
// }
// });
//
// player.startResume();
// }
//
// private void testRecorderForEquals() throws Exception
// {
// assertEquals(pduSentMap.size(), pduReadMap.size(), "Different number of pdus sent than read");
//
// pduSentMap.keySet().forEach(typ -> assertTrue(pduSentMap.get(typ).equals(pduReadMap.get(typ)), "Sent and read pdus not identical"));
// }
//
////@formatter:off
// private void sleep(long ms)
// {
// try {Thread.sleep(ms);}catch (InterruptedException ex) {}
// }
////@formatter:on
//
// public static void main(String[] args)
// {
// new AllPduRoundTripTest().testRoundTripAllPdus();
// }
//}
// THIS CODE IS FOR REFERENCE ONLY IN THIS DIRECTORY.
// TO ACCESS FULL FUNCTIONALITY DOWNLOAD THE DIS7 PROJECT FROM GITLAB
// https://github.com/open-dis/open-dis7-java
///**
// * Copyright (c) 2008-2019, MOVES Institute, Naval Postgraduate School. All rights reserved.
// * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html
// */
//package edu.nps.moves.dis7;
//
//import edu.nps.moves.dis7.enumerations.VariableRecordType;
//import edu.nps.moves.dis7.util.DisNetworking;
//import edu.nps.moves.dis7.util.PduFactory;
//import java.io.IOException;
//import org.junit.jupiter.api.*;
//import static org.junit.jupiter.api.Assertions.*;
//
//@DisplayName("Comment Pdus Test")
//public class CommentPdusTest
//{
// @BeforeAll
// public static void setUpClass()
// {
// System.out.println("CommentPdusTest");
// }
//
// @AfterAll
// public static void tearDownClass()
// {
// }
//
// @BeforeEach
// public void setUp()
// {
// }
//
// @AfterEach
// public void tearDown()
// {
// }
//
// private Pdu receivedPdu;
//
// @Test
// public void testRoundTrip()
// {
// PduFactory factory = new PduFactory();
// setUpReceiver();
//
// testOne(factory.makeCommentPdu());
// testOne(factory.makeCommentPdu("123_test_string"));
// testOne(factory.makeCommentPdu(VariableRecordType.MODEL_TYPE, "456_test with type = modeltype"));
// testOne(factory.makeCommentPdu("xyz first message","mno second message", "jkl third message"));
//
// testOne(factory.makeCommentReliablePdu());
// testOne(factory.makeCommentReliablePdu("789_test_string"));
// testOne(factory.makeCommentReliablePdu(VariableRecordType.ACLS_AIRCRAFT_REPORT, "abc_test with type = acls_aircraft_report"));
// testOne(factory.makeCommentReliablePdu("xyz R first message","mno R second message", "jkl R third message"));
// }
//
// private void testOne(Pdu pdu)
// {
// sendPdu(pdu); // will wait a while
// assertTrue(receivedPdu != null, "No response from network receive");
// assertTrue(compare(pdu,receivedPdu),"Comparison failed");
// receivedPdu = null;
// }
//
// private void sendPdu(Pdu pdu)
// {
// try {
// Thread.sleep(250l); // make sure receiver is listening
// DisNetworking disnet = new DisNetworking();
// disnet.sendPdu(pdu);
//
// Thread.sleep(1000l);
// }
// catch (Exception ex) {
// System.err.println("Error sending Multicast: " + ex.getLocalizedMessage());
// System.exit(1);
// }
// }
//
// private boolean compare(Pdu pdu1, Pdu pdu2)
// {
// return pdu1.equals(pdu2);
// }
//
// private void setUpReceiver()
// {
// Thread rcvThread = new Thread(() -> {
// try {
// while(true) {
// receivedPdu = new DisNetworking().receivePdu(); // blocks
// }
// }
// catch (IOException ex) {
// System.err.println("Error receiving Multicast: " + ex.getLocalizedMessage());
// System.exit(1);
// }
// });
//
// rcvThread.setPriority(Thread.NORM_PRIORITY);
// rcvThread.setDaemon(true);
// rcvThread.start();
// }
//
// public static void main(String[] args)
// {
// new CommentPdusTest().testRoundTrip();
// }
//}
\ No newline at end of file
This diff is collapsed.
/**
* Copyright (c) 2008-2019, MOVES Institute, Naval Postgraduate School. All rights reserved.
* This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html
*/
package MV3500Cohort2019JulySeptember.projects.SchuttFetterolf;
import edu.nps.moves.dis7.util.playerrecorder.Recorder;
import java.io.IOException;
import java.util.Scanner;
/**
* PduSaver.java created on Aug 21, 2019
* MOVES Institute Naval Postgraduate School, Monterey, CA, USA www.nps.edu
*
* @author Mike Bailey, jmbailey@nps.edu
* @version $Id$
*/
public class PduListenerSaver
{
private final static String DEFAULT_OUTPUTDIR = "pduLog";
private final static String MCAST_ADDR = "239.1.2.3";
private final static int DIS_PORT = 3000;
private enum mystate
{
RUNNING,
PAUSED;
}
public static void main(String[] args)
{
String outDir = DEFAULT_OUTPUTDIR;
String mcast = MCAST_ADDR;
int port = DIS_PORT;
System.out.println("DisExamplesOpenDis7.PduListenerSaver started...");
switch (args.length) {
case 0:
break;
case 1:
outDir = args[0];
break;
case 3:
outDir = args[0];
mcast = args[1];
port = Integer.parseInt(args[2]);
break;
default:
System.err.println("Usage: PduListener() or PduListener(\"outputdir\") or PduListener(\"outputdir\",\"multicast address\", ipPort");
System.exit(1);
}
System.out.println("Beginning pdu save to directory " + outDir);
try {
Recorder recorder = new Recorder(outDir, mcast, port);
recorder.startResume();
mystate state = mystate.RUNNING;
System.out.println("* recorder.startResume(), state=RUNNING, recording in progress...");
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Warning: you must quit when complete, otherwise recorded PDUs are lost!");
System.out.println("Type p/enter to pause, r/enter to resume, q/enter to stop recording, save and quit");
String line = scan.nextLine();
if (line.equalsIgnoreCase("p") && state == mystate.RUNNING) {
recorder.stopPause();
state = mystate.PAUSED;
System.out.println("* recorder.stopPause(), state=PAUSED, recording paused...");
}
else if (line.equalsIgnoreCase("r") && state == mystate.PAUSED) {
recorder.startResume();
state = mystate.RUNNING;
System.out.println("* recorder.startResume(), state=RUNNING, recording in progress...");
}
else if (line.equalsIgnoreCase("q")) {
recorder.end();
System.out.println("* recorder.end(), recording complete.");
break;
}
}
System.out.println("Ending pdu save to "+recorder.getLogFile());
}
catch (IOException ex) {
System.err.println("*** Exception: " + ex.getClass().getSimpleName() + ": " + ex.getLocalizedMessage());
}
}
}
package MV3500Cohort2019JulySeptember.projects.SchuttFetterolf;
import java.io.*;
import java.net.*;
import java.util.*;
import edu.nps.moves.dis7.*;
import edu.nps.moves.dis7.enumerations.*;
import edu.nps.moves.dis7.util.CoordinateConversions;
/**
* This is an example that sends many/most types of PDUs. Useful for testing standards
* compliance or getting a full set of PDUs. It also writes the generated PDUs to an XML file.
* Adapted from OpenDIS library example package edu.nps.moves.examples
*
* @author DMcG
* @version $Id:$
*/
public class S_F_FiringUnit
{
public static final int NUMBER_TO_SEND = 5; // 5000
/**
* Default multicast group address we send on.
*/
public static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3";
/**
* Default multicast port used, matches Wireshark DIS capture default
*/
public static final int DEFAULT_MULTICAST_PORT = 3000;
public enum NetworkMode {
UNICAST, MULTICAST, BROADCAST
};
/**
* Possible system properties, passed in via -Dattr=val networkMode:
* unicast, broadcast, multicast destinationIp: where to send the packet. If
* in multicast mode, this can be multicast. To determine broadcast
* destination IP, use an online broadcast address calculator, for example
* http://www.remotemonitoringsystems.ca/broadcast.php If in multicast mode,
* a join() will be done on the multicast address. port: port used for both
* source and destination.
*
* @param args
*/
public static void main(String args[]) {
System.out.println("Firing Unit started...");
// Default settings. These are used if no system properties are set.
// If system properties are passed in, these are overridden later.
NetworkMode networkMode = NetworkMode.BROADCAST;
InetAddress address = null; // must be initialized, even if null
int port = DEFAULT_MULTICAST_PORT;
MulticastSocket socket = null; // must be initialized to avoid later error, even if null;
EntityStatePdu espdu = new EntityStatePdu();
DisTime disTime = new DisTime();
// Firing Unit Location
double latitude = 36.350100;
double longitude = -121.451000;
try {
address = InetAddress.getByName(DEFAULT_MULTICAST_ADDRESS);
} 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 socket to send information
try {
if (portString != null) // Update port we send to, if provided
{
port = Integer.parseInt(portString);
}
socket = new MulticastSocket(port);
// Where we send packets to, the destination IP address
if (destinationIpString != null) {
address = InetAddress.getByName(destinationIpString);
}
// Type of transport: unicast, broadcast, or multicast
if (networkModeString != null) {
if (networkModeString.equalsIgnoreCase("unicast")) {
networkMode = NetworkMode.UNICAST;
} else if (networkModeString.equalsIgnoreCase("broadcast")) {
networkMode = NetworkMode.BROADCAST;
} else if (networkModeString.equalsIgnoreCase("multicast")) {
networkMode = NetworkMode.MULTICAST;
if (!address.isMulticastAddress()) {
throw new RuntimeException("*** Error: sending to multicast address, but destination address " + address.toString() + "is not multicast");
}
socket.joinGroup(address);
}
} // end networkModeString
} catch (IOException | RuntimeException e) {
System.out.println("Unable to initialize network correctly, exiting.");
System.out.println(e);
System.exit(-1); // outta here
}
// 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((byte) 1); //(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(); // initialize, reset, override
// TODO check: 0 is apparently not a valid site number, per DIS specification
entityID.setSiteID((short) 1); // TODO utility method to allow int values
entityID.setApplicationID((short) 2);
entityID.setEntityID((short) 3);
espdu.setEntityID(entityID);
// 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.
// New way using entity jar(s)
espdu.setEntityType(new edu.nps.moves.dis7.entities.usa.platform.land.M119105_mmlightHowitzer());
// Manual way:
/*
EntityType entityType = espdu.getEntityType();
entityType.setEntityKind(EntityKind.PLATFORM); //(short) 1); // Platform (vs lifeform, munition, sensor, etc.)
entityType.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); //225); // USA
entityType.setDomain(Domain.inst(PlatformDomain.LAND)); // Land (vs air, surface, subsurface, space)
entityType.setCategory((byte) 1); // Tank
entityType.setSubCategory((byte) 1); // M1 Abrams
entityType.setSpecific((byte) 3); // M1A2 Abrams
*/
Set<InetAddress> broadcastAddresses;
try // Loop through sending N ESPDUs
{
System.out.println("Sending " + NUMBER_TO_SEND + " sets of packets:"); // + address.toString()
for (int index = 0; index < NUMBER_TO_SEND; index++) {
// DIS time is a pain in the uh, neck. 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) (index));
longitude = longitude + (direction * 0.00006);
double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(latitude, longitude, 1.0);
Vector3Double location = espdu.getEntityLocation();
location.setX(disCoordinates[0]);
location.setY(disCoordinates[1]);
location.setZ(disCoordinates[2]);
System.out.println("===============");
System.out.println("Create new PDUs");
System.out.println(" latitude, longitude: [" + latitude + ", " + longitude + "]");
System.out.println(" coordinate conversion: [" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2] + "]");
location = espdu.getEntityLocation();
System.out.println("Espdu #" + index + " entityID=[" + entityID.getSiteID() + "," + entityID.getApplicationID() + "," + entityID.getEntityID() + "]");
double c[] = {location.getX(), location.getY(), location.getZ()};
double lla[] = CoordinateConversions.xyzToLatLonDegrees(c);
// System.out.println(" DIS entityLocation: [" + location.getX() + "," + location.getY() + "," + location.getZ() + "]");
String debugString = " Location (latitude/longitude/altitude): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]";
// System.out.println(debugString);
// 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);
DatagramPacket packet;
// The byte array here is the packet in DIS format. We put that into a
// datagram and send it.
espdu.marshal(dos);
byte[] espduArray = baos.toByteArray();
FirePdu firePdu = new FirePdu();
firePdu.setLocationInWorldCoordinates(espdu.getEntityLocation());
byte[] fireArray = firePdu.marshal();
broadcastAddresses = getBroadcastAddresses();
Iterator iterator = broadcastAddresses.iterator();
while (iterator.hasNext()) {
InetAddress broadcast = (InetAddress) iterator.next();
if (espduArray.length > 0) {
System.out.println("Sending espdu datagram packet to " + broadcast);
packet = new DatagramPacket(espduArray, espduArray.length, broadcast, port);
socket.send(packet);
}
// TODO experiment with these! 8)
if (fireArray.length > 0) {
System.out.println("Sending fire datagram packet to " + broadcast);
packet = new DatagramPacket(fireArray, fireArray.length, broadcast, port); // alternate
socket.send(packet);
}
}
// Send every 1 second within loop. Otherwise all this will be all over in a fraction of a second.
Thread.sleep(1000); // msec
}
} catch (Exception e) {
System.out.println("Problem with DisExamplesOpenDis7.EspduSender, see exception trace:");
System.out.println(e);
}
System.out.println("===============");
System.out.println("DisExamplesOpenDis7.EspduSender complete.");
}
/**
* 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, etc.) 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--e.g. 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 iterator = anInterface.getInterfaceAddresses().iterator();
while (iterator.hasNext()) {
InterfaceAddress anAddress = (InterfaceAddress) iterator.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) {
System.out.println("Problem with DisExamplesOpenDis7.EspduSender.getBroadcastAddresses(), see exception trace:");
System.out.println(e);
}
return broadcastAddresses;
}
}
package MV3500Cohort2019JulySeptember.projects.SchuttFetterolf;
import java.io.*;
import java.net.*;
import java.util.*;
import edu.nps.moves.dis7.*;
import edu.nps.moves.dis7.enumerations.*;
import edu.nps.moves.dis7.util.CoordinateConversions;
/**
* This is an example that sends many/most types of PDUs. Useful for testing standards
* compliance or getting a full set of PDUs. It also writes the generated PDUs to an XML file.
* Adapted from OpenDIS library example package edu.nps.moves.examples
*
* @author DMcG
* @version $Id:$
*/
public class S_F_RequestingUnit
{
public static final int NUMBER_TO_SEND = 5; // 5000
/**
* Default multicast group address we send on.
*/
public static final String DEFAULT_MULTICAST_ADDRESS = "239.1.2.3";
/**
* Default multicast port used, matches Wireshark DIS capture default
*/
public static final int DEFAULT_MULTICAST_PORT = 3000;
public enum NetworkMode {
UNICAST, MULTICAST, BROADCAST
};
/**
* Possible system properties, passed in via -Dattr=val networkMode:
* unicast, broadcast, multicast destinationIp: where to send the packet. If
* in multicast mode, this can be multicast. To determine broadcast
* destination IP, use an online broadcast address calculator, for example
* http://www.remotemonitoringsystems.ca/broadcast.php If in multicast mode,
* a join() will be done on the multicast address. port: port used for both
* source and destination.
*
* @param args
*/
public static void main(String args[]) {
System.out.println("Requesting Unit started...");
// Default settings. These are used if no system properties are set.
// If system properties are passed in, these are overridden later.
NetworkMode networkMode = NetworkMode.BROADCAST;
InetAddress address = null; // must be initialized, even if null
int port = DEFAULT_MULTICAST_PORT;
MulticastSocket socket = null; // must be initialized to avoid later error, even if null;
EntityStatePdu espdu = new EntityStatePdu();
DisTime disTime = new DisTime();
// Requesting Unit Location
double latitude = 36.372000;
double longitude = -121.503200;
// Target Location
double tarLat = 36.371600;
double tarLon = -121.150300;
EventReportPdu actionReq = new edu.nps.moves.dis7.EventReportPdu();
actionReq.setEventType(EventReportEventType.REQUEST_FOR_INDIRECT_FIRE_OR_CAS_MISSION);
try {
address = InetAddress.getByName(DEFAULT_MULTICAST_ADDRESS);
} 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 socket to send information
try {
if (portString != null) // Update port we send to, if provided
{
port = Integer.parseInt(portString);
}
socket = new MulticastSocket(port);
// Where we send packets to, the destination IP address
if (destinationIpString != null) {
address = InetAddress.getByName(destinationIpString);
}
// Type of transport: unicast, broadcast, or multicast
if (networkModeString != null) {
if (networkModeString.equalsIgnoreCase("unicast")) {
networkMode = NetworkMode.UNICAST;
} else if (networkModeString.equalsIgnoreCase("broadcast")) {
networkMode = NetworkMode.BROADCAST;
} else if (networkModeString.equalsIgnoreCase("multicast")) {
networkMode = NetworkMode.MULTICAST;
if (!address.isMulticastAddress()) {
throw new RuntimeException("*** Error: sending to multicast address, but destination address " + address.toString() + "is not multicast");
}
socket.joinGroup(address);
}
} // end networkModeString
} catch (IOException | RuntimeException e) {
System.out.println("Unable to initialize network correctly, exiting.");
System.out.println(e);
System.exit(-1); // outta here
}
// 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((byte) 1); //(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(); // initialize, reset, override
// TODO check: 0 is apparently not a valid site number, per DIS specification
entityID.setSiteID((short) 1); // TODO utility method to allow int values
entityID.setApplicationID((short) 2);
entityID.setEntityID((short) 3);
espdu.setEntityID(entityID);
// 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.
// New way using entity jar(s)
espdu.setEntityType(new edu.nps.moves.dis7.entities.usa.platform.land.M1A2());
// Manual way:
/*
EntityType entityType = espdu.getEntityType();
entityType.setEntityKind(EntityKind.PLATFORM); //(short) 1); // Platform (vs lifeform, munition, sensor, etc.)
entityType.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); //225); // USA
entityType.setDomain(Domain.inst(PlatformDomain.LAND)); // Land (vs air, surface, subsurface, space)
entityType.setCategory((byte) 1); // Tank
entityType.setSubCategory((byte) 1); // M1 Abrams
entityType.setSpecific((byte) 3); // M1A2 Abrams
*/
Set<InetAddress> broadcastAddresses;
try // Loop through sending N ESPDUs
{
System.out.println("Sending " + NUMBER_TO_SEND + " sets of packets:"); // + address.toString()
for (int index = 0; index < NUMBER_TO_SEND; index++) {
// DIS time is a pain in the uh, neck. 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) (index));
longitude = longitude + (direction * 0.00006);
double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(latitude, longitude, 1.0);
Vector3Double location = espdu.getEntityLocation();
location.setX(disCoordinates[0]);
location.setY(disCoordinates[1]);
location.setZ(disCoordinates[2]);
System.out.println("===============");
System.out.println("Create new PDUs");
System.out.println(" latitude, longitude: [" + latitude + ", " + longitude + "]");
System.out.println(" coordinate conversion: [" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2] + "]");
location = espdu.getEntityLocation();
System.out.println("Espdu #" + index + " entityID=[" + entityID.getSiteID() + "," + entityID.getApplicationID() + "," + entityID.getEntityID() + "]");
double c[] = {location.getX(), location.getY(), location.getZ()};
double lla[] = CoordinateConversions.xyzToLatLonDegrees(c);
// System.out.println(" DIS entityLocation: [" + location.getX() + "," + location.getY() + "," + location.getZ() + "]");
String debugString = " Location (latitude/longitude/altitude): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]";
// System.out.println(debugString);
// 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);
DatagramPacket packet;
// The byte array here is the packet in DIS format. We put that into a
// datagram and send it.
espdu.marshal(dos);
byte[] espduArray = baos.toByteArray();
FirePdu firePdu = new FirePdu();
firePdu.setLocationInWorldCoordinates(espdu.getEntityLocation());
byte[] fireArray = firePdu.marshal();
broadcastAddresses = getBroadcastAddresses();
Iterator iterator = broadcastAddresses.iterator();
while (iterator.hasNext()) {
InetAddress broadcast = (InetAddress) iterator.next();
if (espduArray.length > 0) {
System.out.println("Sending espdu datagram packet to " + broadcast);
packet = new DatagramPacket(espduArray, espduArray.length, broadcast, port);
socket.send(packet);
}
// TODO experiment with these! 8)
if (fireArray.length > 0) {
System.out.println("Sending fire datagram packet to " + broadcast);
packet = new DatagramPacket(fireArray, fireArray.length, broadcast, port); // alternate
socket.send(packet);
}
}
// Send every 1 second within loop. Otherwise all this will be all over in a fraction of a second.
Thread.sleep(1000); // msec
}
} catch (Exception e) {
System.out.println("Problem with DisExamplesOpenDis7.EspduSender, see exception trace:");
System.out.println(e);
}
System.out.println("===============");
System.out.println("DisExamplesOpenDis7.EspduSender complete.");
}
/**
* 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, etc.) 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--e.g. 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 iterator = anInterface.getInterfaceAddresses().iterator();
while (iterator.hasNext()) {
InterfaceAddress anAddress = (InterfaceAddress) iterator.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) {
System.out.println("Problem with DisExamplesOpenDis7.EspduSender.getBroadcastAddresses(), see exception trace:");
System.out.println(e);
}
return broadcastAddresses;
}
}
!End!End of DIS capture file, Pdusave2.dislog.
......@@ -4,44 +4,42 @@ import java.io.IOException;
import java.net.*;
/**
* A server example that creates and dispaches a new thread to handle
* multiple connections one after another, running in parallel.
*
* A server example that creates and dispaches a new thread to handle multiple
* connections one after another, running in parallel.
*
* @author Don McGregor
* @author Don Brutzman
* @author MV3500 class
*/
public class TcpExample4DispatchServer {
public static void main(String[] args) // execution starts here
{
try
{
try {
ServerSocket serverSocket = new ServerSocket(2317);
int connectionCount = 0; // state variable
System.out.println("TcpExample4DispatchServer ready to accept socket connections...");
while(true) // infinite loop
int connectionCount = 0; // state variable
System.out.println("TcpExample4DispatchServer ready to accept socket connections...");
while (true) // infinite loop
{
Socket clientConnection = serverSocket.accept(); // block until connected
connectionCount++; // unblocked, got another connection
System.out.println("=============================================================");
System.out.println("TcpExample4DispatchServer.handlerThread invocation for connection #" + connectionCount + "...");
connectionCount++; // unblocked, got another connection
System.out.println("=============================================================");
System.out.println("TcpExample4DispatchServer.handlerThread invocation for connection #" + connectionCount + "...");
TcpExample4HandlerThread handlerThread = new TcpExample4HandlerThread(clientConnection);
handlerThread.start(); // invokes the run() method in that object
System.out.println("TcpExample4DispatchServer.handlerThread is launched, awaiting another connection...");
}
}
catch(IOException e)
{
System.out.println("TcpExample4DispatchServer.handlerThread is launched, awaiting another connection...");
}
} catch (IOException e) {
System.out.println("Problem with TcpExample4DispatchServer networking:"); // describe what is happening
System.out.println("Error: " + e);
// Provide more helpful information to user if exception occurs due to running twice at one time
if (e instanceof java.net.BindException)
if (e instanceof java.net.BindException) {
System.out.println("*** Be sure to stop any other running instances of programs using this port!");
}
}
System.out.println("=============================================================");
System.out.println("=============================================================");
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment