![]() |
MAK RTIspy API Documentation for HLA 1516
|
simpleTime13.cxx and simpleTimeFedAmb13.cxx (simpleTimeFedAmb13.h) have the RTI calls and federate ambassador calls for the HLA 1.3 version of simpleTime.
This page has the code for the following files:
/******************************************************************************* ** Copyright (c) 2004 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTime13.cxx,v $ $Revision: 1.5 $ $State: Exp $ *******************************************************************************/ // A simple federate that updates an object with attributes whose values // are the name of the attribute. Objects from other simple federates // are discovered and reflected. The string values are byte encoded to allow // compatibility between 1.3 and 1516 #ifdef WIN32 #pragma warning(disable: 4251) #pragma warning(disable: 4786) #pragma warning(disable: 4290) #include <winsock2.h> #include <process.h> #else #include <unistd.h> #include <stdlib.h> #include <sched.h> #include <netdb.h> #endif #include <stdio.h> #include <iostream> #include <map> #include <set> #include <string> #include <sstream> #include <iterator> #include "RTI.hh" #include "fedtime.hh" #include "simpleTimeFedAmb13.h" #include "simpleTimeKeyboard.h" #include "simpleTimeStringUtil.h" using namespace std; bool parseCmdLine( int argc, char* argv[] ); // Handles keyboard input without blocking keyboard input; // Data shared between federate and federate ambassador DtTalkAmbData theAmbData; // The object class name string theClassName = "BaseEntity"; // The interaction class name string fireInteractionName = "WeaponFire"; string detonateInteractionName = "MunitionDetonation"; // The object class handle (to be retrieved from RTI). RTI::ObjectClassHandle theClassHandle; // The interaction class handles (to be retrieved from RTI). RTI::InteractionClassHandle fireInteractionHandle; RTI::InteractionClassHandle detonateInteractionHandle; // The object instance handle (to be retrieved from the RTI). RTI::ObjectHandle theObjectHandle; // This federation of simple objects has a single master object, (determined by command line arguments) // The master federate will keep the other federates from entering their main loop of execution until // all of numFederates have joined. bool Master(false); // numFederates is the number of federates (including the master) that the master should wait to join the // federation before it allows any federate to enter its main loop. // This variable is only used by the master federate. int numFederates(0); // dedicatedMachine indicates that this federate will be as greedy as possible with the processor. // this is helpful for users who have two federates on separate machines and want them to time-step // as quickly as possible. // If each federate is not on a dedicated machine, this may actually slow federates. bool dedicatedMachine(false); // unManaged Federate will allow you to see the operation of a time regulating and constrained federate // when the federate does not wait for the "begin" synchronization before executing. bool unManagedFederate(false); // sleepTime (indicated in milliseconds, defaults to 850ms), is the time that a federate will sleep between // iterations of the main loop. This value is invalidated if (above) dedicatedMachine is set. // 850 ms is selected to allow the user to see the time advances progressing at a very slow pace. // There is no need to set this to a value > 50ms or so other than allowing the user to watch the text scroll. int sleepTime(850); // the name of the fed file this federate will use. Can be overridden with cmd line parameter fedFile string fedFileName("MAKsimpletime.fed"); // the name of the federation we'll create. string federationName("MAKsimpletime"); // The name of the initialization synchronization point that the master and other federates use to establish a // synchronized starting point for the federation. string initSyncPointLabel("begin"); // Create the federation execution void createFedEx(RTI::RTIambassador & rtiAmb, string const& fedName, string const& fedFile) { std::cout << "createFederationExecution " << fedName.c_str() << " " << fedFile.c_str() << endl; try { rtiAmb.createFederationExecution(fedName.c_str(), fedFile.c_str()); } catch(RTI::FederationExecutionAlreadyExists& ex) { std::cout << "Could not create Federation Execution: " << "FederationExecutionAlreadyExists: " << ex._name << " " << ex._reason << endl; } catch(RTI::Exception& ex) { std::cout << "Could not create Federation Execution: " << endl << "RTI Exception: " << ex._name << " " << ex._reason << endl; exit(0); } rtiAmb.tick(0.1, 0.2); std::cout << "Federation Created" << endl; } // Join the federation execution void joinFedEx( RTI::RTIambassador & rtiAmb, MyFederateAmbassador* fedAmb, string const& federateType) { bool joined=false; const int maxTry = 10; int numTries = 0; std::cout << "joinFederationExecution " << federateType.c_str() << " " << federationName.c_str() << endl; while (!joined && numTries++ < maxTry) { try { rtiAmb.joinFederationExecution(federateType.c_str(), federationName.c_str(), fedAmb); joined = true; } catch(RTI::FederationExecutionDoesNotExist) { std::cout << "FederationExecutionDoesNotExist, try " << numTries << "out of " << maxTry << endl; continue; } catch(RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl; return; } rtiAmb.tick(0.1, 0.2); } if (joined) std::cout << "Joined Federation." << endl; else { std::cout << "Giving up." << endl; rtiAmb.destroyFederationExecution(federationName.c_str()); exit(0); } } // Resign and destroy the federation execution void resignAndDestroy( RTI::RTIambassador & rtiAmb ) { rtiAmb.resignFederationExecution(RTI::DELETE_OBJECTS); rtiAmb.destroyFederationExecution(federationName.c_str()); } // Publish and subscribe the object class attributes. // Register an object instance of the class. bool publishSubscribeAndRegisterObject(RTI::RTIambassador & rtiAmb) { // Declare the attributes that we will be publishing. theAmbData.ourAttrs.insert(string("AccelerationVector")); theAmbData.ourAttrs.insert(string("DeadReckoningAlgorithm")); theAmbData.ourAttrs.insert(string("Orientation")); theAmbData.ourAttrs.insert(string("WorldLocation")); theAmbData.ourAttrs.insert(string("VelocityVector")); theAmbData.ourAttrs.insert(string("DamageState")); // Get the object class handle try { theClassHandle = rtiAmb.getObjectClassHandle(theClassName.c_str()); theAmbData.objectClassMap[theClassHandle] = theClassName; } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not get object class handle: " << theClassName.c_str() << endl; return false; } // Construct an attribute handle set string attrName; RTI::AttributeHandleSet* hSet = RTI::AttributeHandleSetFactory::create(theAmbData.ourAttrs.size()); // Create an appropriately sized Attribute Handle Value Pair Set theAmbData.attrValues = RTI::AttributeSetFactory::create(theAmbData.ourAttrs.size()); set<string>::iterator attributeSetIterator = theAmbData.ourAttrs.begin(); set<string>::iterator attributeSetEnd = theAmbData.ourAttrs.end(); string currentAttribute(""); RTI::AttributeHandle retrievedHandle; for ( ; attributeSetIterator != attributeSetEnd; ++attributeSetIterator ) { currentAttribute = *attributeSetIterator; try{ retrievedHandle = rtiAmb.getAttributeHandle(currentAttribute.c_str(), theClassHandle); } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not get attribute handle " << attrName.c_str() << endl; return false; } // Populate the AttributeHandleSet hSet->add(retrievedHandle); // Populate the attribute handle value pair set with the // values containing the attribute names // Attribute values will be just the name of the attribute. theAmbData.attrValues->add(retrievedHandle, currentAttribute.c_str(), currentAttribute.length()+1); theAmbData.theAttrNameHandleMap.insert( std::make_pair( currentAttribute, retrievedHandle)); } // Publish and subscribe int cnt=0; try { rtiAmb.publishObjectClass(theClassHandle, *hSet); rtiAmb.tick(0.1, 0.2); cnt=1; rtiAmb.subscribeObjectClassAttributes(theClassHandle, *hSet); rtiAmb.tick(0.1, 0.2); } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not " << (cnt ? "publish" : "subscribe") << endl; delete hSet; return false; } string objectName("Talk"); // Register the object instance try { unsigned int objId = abs(getpid()); stringstream pid; pid << objId; objectName += pid.str(); theObjectHandle = rtiAmb.registerObjectInstance(theClassHandle, objectName.c_str()); // Add name-handle to map theAmbData.objectInstanceMap[theObjectHandle] = rtiAmb.getObjectInstanceName(theObjectHandle); rtiAmb.tick(0.1, 0.2); } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not Register Object " << objectName.c_str() << " with class " << theClassName.c_str() << endl; delete hSet; return false; } std::cout << "Registered object " << objectName.c_str() << " with class name " << theClassName.c_str() << endl; delete hSet; return true; } // Publish and Subscribe to an interaction class bool publishAndSubscribeInteraction(RTI::RTIambassador & rtiAmb) { theAmbData.ourParms.insert("EventIdentifier"); theAmbData.ourParms.insert("FiringLocation"); theAmbData.ourParms.insert("FiringObjectIdentifier"); theAmbData.ourParms.insert("MunitionObjectIdentifier"); theAmbData.ourParms.insert("TargetObjectIdentifier"); // Get the interaction class handle try { fireInteractionHandle = rtiAmb.getInteractionClassHandle(fireInteractionName.c_str()); theAmbData.interactionClassMap[fireInteractionHandle] = fireInteractionName; detonateInteractionHandle = rtiAmb.getInteractionClassHandle( detonateInteractionName.c_str()); theAmbData.interactionClassMap[detonateInteractionHandle] = detonateInteractionName; } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not get interaction class handle: " << theClassName.c_str() << endl; return false; } // Construct a parameter handle value pair set with the // values containing the parameter names theAmbData.paramValues = RTI::ParameterSetFactory::create(theAmbData.ourParms.size()); // Get the parameter handles and construct the name-handle map string paramName; set<string>::const_iterator parameterIter = theAmbData.ourParms.begin(); set<string>::const_iterator parameterEnd = theAmbData.ourParms.end(); RTI::ParameterHandle retrievedHandle; for ( ; parameterIter != parameterEnd; ++parameterIter ) { paramName = *parameterIter; try { retrievedHandle = rtiAmb.getParameterHandle(paramName.c_str(), fireInteractionHandle); } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not get parameter handle " << paramName.c_str() << endl; return false; } // Parameter values will be just the name of the attribute. theAmbData.paramValues->add(retrievedHandle, paramName.c_str(), paramName.length()+1); theAmbData.theParamNameHandleMap.insert( std::make_pair( paramName, retrievedHandle)); } // Publish and subscribe int cnt=0; try { rtiAmb.publishInteractionClass(fireInteractionHandle); rtiAmb.tick(0.1, 0.2); rtiAmb.publishInteractionClass(detonateInteractionHandle); rtiAmb.tick(0.1, 0.2); cnt=1; rtiAmb.subscribeInteractionClass(fireInteractionHandle); rtiAmb.tick(0.1, 0.2); rtiAmb.subscribeInteractionClass(detonateInteractionHandle); rtiAmb.tick(0.1, 0.2); } catch (RTI::Exception& ex) { std::cout << "RTI Exception: " << ex._name << " " << ex._reason << endl << "Could not " << (cnt ? "publish" : "subscribe") << " to interaction." << endl; return false; } std::cout << "Subscribed to interaction class: " << fireInteractionName.c_str() << " with handle: " << fireInteractionHandle << endl << " and interaction class " << detonateInteractionName.c_str() << " with handle: " << detonateInteractionHandle << endl; return true; } // This function will exit the program after resigning the federation. void cleanUpProgram(RTI::RTIambassador& rtiAmb) { try { if ( theAmbData.isRegulating ) { rtiAmb.disableTimeRegulation(); } // Resign and destroy federation resignAndDestroy(rtiAmb); } catch (RTI::Exception& ex) { std::cout << "RTI Exception (during exit): " << ex._name << " " << ex._reason << endl; } #ifdef WIN32 WSACleanup(); #endif exit(0); } // This is a simple function to output a FedTime object. // Helpful for debugging and general diagnostics. void printOutFedTime(RTI::FedTime* time) { char* buff = new char[time->getPrintableLength()]; time->getPrintableString(buff); std::cout << atof(buff) ; delete [] buff; } // platform independent sleep function. void sleepFunction() { // On a dedicated machine we do not sleep, making this function a nop if ( ! dedicatedMachine ) { #ifdef WIN32 Sleep(sleepTime); #else usleep(sleepTime * 1000); #endif } } // platform independent sleep, for a predetermined small time. (10 ms) void minimalSleepFunction() { #ifdef WIN32 Sleep(10); #else usleep(10 * 1000); #endif } // simply yields the current thread independent of the platform void yieldFunction() { // On a dedicated machine we do not yield the processor, making this function a nop if ( ! dedicatedMachine ) { #ifdef _WIN32 Sleep( 0 ); #elif __solaris__ yield(); #else sched_yield(); #endif } } // This function causes the federate to become time constrained and regulating. // If the user presses q while the federate is waiting for the callback from the RTI // making it time constrained, the federate will quit. void becomeConstrainedAndRegulating(RTI::RTIambassador& rtiAmb, RTI::FedTime* currentTime, RTI::FedTime* lookAhead ) { try { rtiAmb.enableTimeRegulation((*currentTime), (*lookAhead)); std::cout << "Waiting to become Time Regulating \n"; rtiAmb.tick(.1, 1); while ( ! theAmbData.isRegulating ) { std::cout << "."; if (input.keybrdTick() < 0) { cleanUpProgram(rtiAmb); } minimalSleepFunction(); rtiAmb.tick(.1, 1); } std::cout << endl; rtiAmb.enableTimeConstrained(); std::cout << "Waiting to become Time Constrained \n"; rtiAmb.tick(.1, 1); while ( ! theAmbData.isConstrained ) { std::cout << "."; if (input.keybrdTick() < 0 ) { cleanUpProgram(rtiAmb); } rtiAmb.tick(.1, 1); if ( ! theAmbData.isConstrained ) { yieldFunction(); } } std::cout << endl; } catch (RTI::Exception& ) { std::cout << " unable to become regulating and constrained\n" << " Exiting ...\n"; cleanUpProgram(rtiAmb); } } // This function will not exit until numFederates (as indicated to the master // of this federation execution) have been made known to the master federate. // The master then waits to have discovered numFederates - 1, // (i.e. all federates but itself), then accomplished by the master registering // a sync point. From this point the master behaves exactly as the other federates. // The non-master federates wait for the announceSyncPoint callback, indicating that // the master federate has discovered all necessary federates. They each non-master federate // will call synchPointAchieved, indicating to the RTI that they are prepared to start. // Then both master and non-master simply wait for the RTI federationSynchronized callback. //Note: An alternative to waiting for object discovery callbacks to indicate a joined federate // is to use MOM interactions. The master can subscribe to a MOM interaction and have a joined // federate send that interaction prior to entering the synchronizeFederation function. void synchronizeFederation(RTI::RTIambassador& rtiAmb) { if ( theAmbData.isMaster ) { std::string synchPointTag(""); int maximumSize(256); char* hostName = new char[maximumSize]; if ( -1 == gethostname(hostName, maximumSize) ) { unsigned int objId = abs(getpid()); std::stringstream pid; pid.str(std::string("")); pid << "unknownHostName" << "_" << objId; synchPointTag = pid.str(); } else { unsigned int objId = abs(getpid()); std::stringstream pid; pid.str(std::string("")); pid << hostName << "_" << objId; synchPointTag = pid.str(); } delete hostName; // Wait until other federates have joined. rtiAmb.tick(0.1, 0.2); std::cout << " Master waiting for all federates to Join.\n"; while ( theAmbData.otherFederatesReady < (theAmbData.numFederates - 1) ) { if (input.keybrdTick() < 0 ) { cleanUpProgram(rtiAmb); } yieldFunction(); rtiAmb.tick(0.1, 0.2); } // Now that all required federates have joined, register a sync point. std::cout << " Master federate has discovered the required number of other federates.\n\n"; rtiAmb.registerFederationSynchronizationPoint(initSyncPointLabel.c_str(), synchPointTag.c_str()); rtiAmb.tick(0.1, 0.2); while ( !theAmbData.registerFailed && !theAmbData.registerSucceeded ) { if (input.keybrdTick() < 0 ) { cleanUpProgram(rtiAmb); } yieldFunction(); rtiAmb.tick(0.1, 0.2); } if ( theAmbData.registerFailed ) { std::cout << " We failed to register synch point " << initSyncPointLabel << std::endl << " with tag " << synchPointTag << std::endl; cleanUpProgram(rtiAmb); } std::cout << "Master successfully registered\n"; } else { rtiAmb.tick(0.1, 0.2); std::cout << " Ordinary federate is waiting for synchPoint message\n"; while ( ! theAmbData.announceSyncReceived ) { if (input.keybrdTick() < 0 ) { cleanUpProgram(rtiAmb); } yieldFunction(); rtiAmb.tick(0.1, 0.2); } std::cout << "sync Point message received\n"; } // At this time, any kind of federate announces to the RTI that they have reached their // synchronization. try { rtiAmb.synchronizationPointAchieved(initSyncPointLabel.c_str()); } catch (RTI::Exception& ) { std::cout << " Synch point achieved failed\n" << " Exiting....\n"; cleanUpProgram(rtiAmb); } //Then they will wait for the RTI to announce to all federates that all federates are synchronized. rtiAmb.tick(0.1, 0.2); while ( !theAmbData.federationIsSynchronized ) { if (input.keybrdTick() < 0 ) { cleanUpProgram(rtiAmb); } minimalSleepFunction(); rtiAmb.tick(0.1, 0.2); } } int main(int argc, char** argv) { std::cout << "MAK simpleTime version 1.3" << std::endl; try { // Federate and Federation info string federateType("simpletime13"); if (argc > 1) { if (!parseCmdLine(argc, argv)) { exit(0); } } // RTI and Federate Ambassadors RTI::RTIambassador rtiAmb; MyFederateAmbassador fedAmb(theAmbData); // Create the federation createFedEx(rtiAmb, federationName, fedFileName); // Join the federation joinFedEx(rtiAmb, &fedAmb, federateType); #ifdef WIN32 WSADATA data; WSAStartup(MAKEWORD(1,1), &data); #endif rtiAmb.tick(0.1, 0.2); long count=0; RTI::FedTime* currentTime = RTI::FedTimeFactory::makeZero(); RTI::FedTime* lookAhead = new RTIfedTime(1.0); RTI::FedTime* currentRTITime = RTI::FedTimeFactory::makeZero(); RTI::FedTime* oneTimeStep = new RTIfedTime(5.0); //Become Time managed and regulating in this federation. becomeConstrainedAndRegulating(rtiAmb, currentTime, lookAhead); (*currentTime) += (*oneTimeStep); // Publish, subscribe and register and object if (!publishSubscribeAndRegisterObject(rtiAmb)) { resignAndDestroy(rtiAmb); return 0; } // By using synchronization points, ensure that all expected federates // have joined prior to commencing. This function requires that // other federates have registered an object as it utilizes discovery // callbacks to count the number of federates that have joined as yet. if ( !unManagedFederate ) { synchronizeFederation(rtiAmb); } // Publish and subscribe to the required interaction if (!publishAndSubscribeInteraction(rtiAmb)) { resignAndDestroy(rtiAmb); return 0; } // This is the main loop of the application. In it, the federate ticks the RTI, updates // its published attributes and if indicated, fires and detonates, this continues // until this federate has been detonated. while ( !theAmbData.timeManagedObject.isDetonated() ) { std::cout << "===================================================================\n"; std::cout << " Fedtime ("; printOutFedTime(currentRTITime); std::cout << "), Lookahead ("; printOutFedTime(lookAhead); std::cout << ") and wallclock time ("; printOutFedTime(currentTime); std::cout << ") " << std::endl; std::cout << endl; stringstream ss; ss << "1.3-" << count++; string tag(ss.str()); theAmbData.timeManagedObject.tick(); theAmbData.timeManagedObject.incPosition(); try{ // Update the object rtiAmb.updateAttributeValues( theObjectHandle, *(theAmbData.attrValues), (*currentTime), tag.c_str()); rtiAmb.tick(0.1, 0.5); // Send the interaction if appropriate. if ( theAmbData.timeManagedObject.shouldDetonate() ) { string munitionString = "MunitionObjectIdentifier"; // Find the Parameter Handle that the RTI associated with this Parameter Name. RTI::ParameterHandle munitionHandle = theAmbData.theParamNameHandleMap.find(munitionString)->second; // By adding a munitions parameter with nothing for the data, we communicate that this // interaction is a munitions interaction. theAmbData.paramValues->remove( munitionHandle ); theAmbData.paramValues->add(munitionHandle, "\0", 1); rtiAmb.sendInteraction( detonateInteractionHandle, *theAmbData.paramValues, (*currentTime), tag.c_str() ); // Restore the munitions parameter data. theAmbData.paramValues->remove( munitionHandle ); theAmbData.paramValues->add(munitionHandle, munitionString.c_str(), munitionString.length() + 1); } if ( theAmbData.timeManagedObject.shouldFire() ) { string fireString = "FiringObjectIdentifier"; // Find the Parameter Handle that the RTI associated with the Fire Parameter. RTI::ParameterHandle fireHandle = theAmbData.theParamNameHandleMap.find(fireString)->second; // By replacing the existing fire parameter with one thas has null data, we indicate // that this interaction is a fire interation. theAmbData.paramValues->remove(fireHandle); theAmbData.paramValues->add(fireHandle, "\0", 1); rtiAmb.sendInteraction( fireInteractionHandle, *theAmbData.paramValues, (*currentTime), tag.c_str() ); // Restore the fire parameter's data. theAmbData.paramValues->remove(fireHandle); theAmbData.paramValues->add(fireHandle, fireString.c_str(), fireString.length() + 1); } } catch(RTI::InvalidFederationTime& ex) { std::cout << " caught an Invalid Federation Time !!\n"; std::cout << ex._name << " " << ex._reason << endl; // A federate can easily rectify a difference in current time with the RTI's time. // This federate is synchronized before it advances time, this should never be reached. cleanUpProgram(rtiAmb); } int kb(0); try { if ( theAmbData.isRegulating ) { (*currentRTITime) += (*oneTimeStep); (*currentTime) += (*oneTimeStep); rtiAmb.timeAdvanceRequest(*currentRTITime); theAmbData.timeAdvanced = false; rtiAmb.tick(0.1, 0.2); while ( ! theAmbData.timeAdvanced ) { kb = input.keybrdTick(); if (kb < 0) { break; } else if ( kb == 1 ) { theAmbData.timeManagedObject.firePressed(); std::cout << "**********Firing at Fed Time " ; printOutFedTime(currentRTITime); std::cout << "*************\n"; } else if ( !theAmbData.timeAdvanced ) { yieldFunction(); rtiAmb.tick(0.1, 0.2); } } } } catch( RTI::Exception& ex ) { std::cout << "RTI Exception" << endl << ex._name << " " << ex._reason << endl << " Could not advance time" << endl; } rtiAmb.tick(0.1, 0.2); if ( kb == 0 ) { kb = input.keybrdTick(); } if ( kb < 0 ) { break; } else if ( kb == 1 ) { theAmbData.timeManagedObject.firePressed(); std::cout << "**********Firing at Fed Time " ; printOutFedTime(currentRTITime); std::cout << "*************\n"; } std::cout << "===================================================================\n\n"; sleepFunction(); } delete oneTimeStep; delete lookAhead; delete currentTime; delete currentRTITime; delete theAmbData.paramValues; delete theAmbData.attrValues; if ( theAmbData.isRegulating ) { rtiAmb.disableTimeRegulation(); } // Resign and destroy federation resignAndDestroy(rtiAmb); } catch (RTI::Exception& ex) { std::cout << "RTI Exception (main loop): " << ex._name << " " << ex._reason << endl; } #ifdef WIN32 WSACleanup(); #endif return 0; } bool parseCmdLine( int argc, char* argv[] ) { // Process commandline linput. vector < std::string > cmdArgs; copy( argv + 1, argv + argc, back_inserter(cmdArgs)); vector<std::string>::const_iterator cur = cmdArgs.begin(); vector<std::string>::const_iterator last = cmdArgs.end(); while ( cur != last ) { vector<std::string>::const_iterator next = cur + 1; if ( *cur == "-h" ) { std::cerr << usage(); return false; } else if ( *cur == "-fedFile" ) { if ( !convert<string>(*cur, *next, fedFileName )) { std::cerr << usage(); return false; } ++cur; } else if (*cur == "-m" ) { if ( !convert<int> (*cur, *next, theAmbData.numFederates)) { std::cerr << usage(); return false; } theAmbData.isMaster = true; ++cur; } else if ( *cur == "-phaseLine" ) { int phaseLine(0); if ( !convert<int>(*cur, *next, phaseLine)) { std::cerr << usage(); return false; } theAmbData.timeManagedObject.setPhaseLine(phaseLine); ++cur; } else if ( *cur == "-sleepTime" ) { if ( !convert<int> (*cur, *next, sleepTime )) { std::cerr << usage(); return false; } ++cur; } else if ( *cur == "-dedicated" ) { dedicatedMachine = true; } else if ( *cur == "-unManaged" ) { unManagedFederate = true; } else { std::cerr<< usage(); return false; } ++cur; } return true; }
/******************************************************************************* ** Copyright (c) 2004 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeFedAmb13.cxx,v $ $Revision: 1.3 $ $State: Exp $ *******************************************************************************/ #ifdef WIN32 #pragma warning(disable: 4786) #pragma warning(disable: 4290) #else #include <stdio.h> #endif #include <cstdlib> #include <iostream> #include "simpleTimeFedAmb13.h" #include "simpleTimeTimeManagedEntity.h" using namespace std; DtTalkAmbData::DtTalkAmbData() : isConstrained(false), isRegulating(false), timeAdvanced(false), otherFederatesReady(0), isMaster(false), numFederates(0), registerSucceeded(false), registerFailed(false), announceSyncReceived(false), federationIsSynchronized(false) { } DtTalkAmbData::~DtTalkAmbData() { } MyFederateAmbassador::MyFederateAmbassador(DtTalkAmbData & data) : NullFederateAmbassador(), myData(data) { } MyFederateAmbassador::~MyFederateAmbassador() throw (RTI::FederateInternalError) { } void MyFederateAmbassador::discoverObjectInstance ( RTI::ObjectHandle theObject, RTI::ObjectClassHandle theObjectClass, const char* theObjectName) throw ( RTI::CouldNotDiscover, RTI::ObjectClassNotKnown, RTI::FederateInternalError) { // This is an over simplification of the initialization of a federation. // In our case we simply wait until there are the requisite # of known federates // before starting. ++myData.otherFederatesReady; if ( myData.isMaster) { std::cout << " Master federate is aware of " << myData.otherFederatesReady + 1 << " federates, including itself\n"; } // Now that we've discovered an object we should request an Attribute // update for all of the attributes that we're subscribed for. // Construct an attribute handle set RTI::AttributeHandleSet* hSet = RTI::AttributeHandleSetFactory::create(myData.ourParms.size()); for (DtAttrNameHandleMap::iterator iter = myData.theAttrNameHandleMap.begin(); iter != myData.theAttrNameHandleMap.end(); iter++) { hSet->add(iter->second); } // In order to avoid making RTI calls from within an RTI callback, // we'll add this attrRequest to a shared Object, allowing the // call to be made from outside this callback. myData.updateRequestMap.insert(make_pair(theObject,hSet)); delete hSet; myData.objectInstanceMap[theObject] = theObjectName; } // To keep callbacks expedient and simple, we simply save all pertinent information // from this reflect in our timeManagedObject, allowing the main thread of execution // to process the update when it chooses. // The same can be said of the other reflectAttributeValues calls void MyFederateAmbassador::reflectAttributeValues ( RTI::ObjectHandle theObject, const RTI::AttributeHandleValuePairSet& theAttributes, const RTI::FedTime& theTime, const char *theTag, RTI::EventRetractionHandle theHandle) throw ( RTI::ObjectNotKnown, RTI::AttributeNotKnown, RTI::FederateOwnsAttributes, RTI::InvalidFederationTime, RTI::FederateInternalError) { myData.timeManagedObject.addAttrUpdateEvent(new attributeUpdateEvent( theAttributes, theTime, theTag, theHandle)); } void MyFederateAmbassador::reflectAttributeValues ( RTI::ObjectHandle theObject, const RTI::AttributeHandleValuePairSet& theAttributes, const char *theTag) throw ( RTI::ObjectNotKnown, RTI::AttributeNotKnown, RTI::FederateOwnsAttributes, RTI::FederateInternalError) { myData.timeManagedObject.addAttrUpdateEvent(new attributeUpdateEvent( theAttributes, theTag )); } // Similar to the reflectAttributeValues implementations, here we do some minimal // interpretation of the received Interaction (whether it is a fire or detonation // interaction), and add the interaction event to our timeManagedObject, allowing // the main thread of execution to process it as appropriate. void MyFederateAmbassador::receiveInteraction ( RTI::InteractionClassHandle theInteraction, const RTI::ParameterHandleValuePairSet& theParameters, const RTI::FedTime& theTime, const char *theTag, RTI::EventRetractionHandle theHandle) throw ( RTI::InteractionClassNotKnown, RTI::InteractionParameterNotKnown, RTI::InvalidFederationTime, RTI::FederateInternalError) { interactionEvent::interaction_type interactionType(interactionEvent::Unknown); string munitionString("MunitionObjectIdentifier"); string fireString("FiringObjectIdentifier"); RTI::ParameterHandle munitionHandle = myData.theParamNameHandleMap.find(munitionString)->second; RTI::ParameterHandle fireHandle = myData.theParamNameHandleMap.find(fireString)->second; for ( unsigned int i(0); (interactionType == interactionEvent::Unknown) && i < theParameters.size(); ++i ) { if ( theParameters.getHandle(i) == munitionHandle ) { RTI::ULong length = theParameters.getValueLength(i); if ( length == 1 ) { interactionType = interactionEvent::DetonationType; } } if ( theParameters.getHandle(i) == fireHandle ) { RTI::ULong length = theParameters.getValueLength(i); if ( length == 1 ) { interactionType = interactionEvent::FireType; } } } myData.timeManagedObject.addInteractionEvent(new interactionEvent ( theInteraction, theParameters, theTime, theTag, interactionType )); } void MyFederateAmbassador::receiveInteraction ( RTI::InteractionClassHandle theInteraction, const RTI::ParameterHandleValuePairSet& theParameters, const char *theTag) throw ( RTI::InteractionClassNotKnown, RTI::InteractionParameterNotKnown, RTI::FederateInternalError) { myData.timeManagedObject.addInteractionEvent( new interactionEvent( theInteraction, theParameters, theTag) ); } // remove the object instance from our map of object instances. void MyFederateAmbassador::removeObjectInstance ( RTI::ObjectHandle theObject, const RTI::FedTime& theTime, const char *theTag, RTI::EventRetractionHandle theHandle) throw ( RTI::ObjectNotKnown, RTI::InvalidFederationTime, RTI::FederateInternalError) { if ( myData.objectInstanceMap.find(theObject) != myData.objectInstanceMap.end()) myData.objectInstanceMap.erase(theObject); myData.timeManagedObject.reset(); } void MyFederateAmbassador::removeObjectInstance ( RTI::ObjectHandle theObject, const char *theTag) throw ( RTI::ObjectNotKnown, RTI::FederateInternalError) { if ( myData.objectInstanceMap.find(theObject) != myData.objectInstanceMap.end()) myData.objectInstanceMap.erase(theObject); myData.timeManagedObject.reset(); } // A request was made for an attribute update from this update, add the request // to our updateRequestMap. void MyFederateAmbassador::provideAttributeValueUpdate ( RTI::ObjectHandle theObject, const RTI::AttributeHandleSet& theAttributes) throw ( RTI::ObjectNotKnown, RTI::AttributeNotKnown, RTI::AttributeNotOwned, RTI::FederateInternalError) { RTI::AttributeHandleSet* hSet = RTI::AttributeHandleSetFactory::create(myData.ourAttrs.size()); for (DtAttrNameHandleMap::iterator iter = myData.theAttrNameHandleMap.begin(); iter != myData.theAttrNameHandleMap.end(); iter++) { hSet->add(iter->second); } myData.updateRequestMap.insert( make_pair( theObject, hSet) ); delete hSet; } // Alert the user and set the isRegulating flag of our shared Object. void MyFederateAmbassador::timeRegulationEnabled ( const RTI::FedTime& theFederateTime) // supplied C4 throw ( RTI::InvalidFederationTime, RTI::EnableTimeRegulationWasNotPending, RTI::FederateInternalError) { std::cout << " This federate is now able to Regulate time\n"; myData.isRegulating = true; } // Alert the user and set the isConstrained flag of our shared Object. void MyFederateAmbassador::timeConstrainedEnabled ( const RTI::FedTime& theFederateTime) throw ( RTI::InvalidFederationTime, RTI::EnableTimeConstrainedWasNotPending, RTI::FederateInternalError) { std::cout << " This federate is now time Constrained\n"; myData.isConstrained = true; } // Alert the user and set the timeAdvanced flag of our shared Object. void MyFederateAmbassador::timeAdvanceGrant ( const RTI::FedTime& theTime) // supplied C4 throw ( RTI::InvalidFederationTime, RTI::TimeAdvanceWasNotInProgress, RTI::FederateInternalError) { int length = theTime.getPrintableLength(); char* buff = new char[length + 1]; const_cast<RTI::FedTime&>(theTime).getPrintableString(buff); std::cout << " Federate Time has been advanced to " << atof(buff) << endl; delete [] buff; myData.timeAdvanced = true; } // set the registerSucceeded flag of our shared object. void MyFederateAmbassador::synchronizationPointRegistrationSucceeded ( const char *label) // supplied C4) throw ( RTI::FederateInternalError) { myData.registerSucceeded = true; } // set the registerFailed flag of our shared Object. void MyFederateAmbassador::synchronizationPointRegistrationFailed ( const char *label) throw ( RTI::FederateInternalError) { myData.registerFailed = true; } // We received a callback from the RTI announcing a synchronization point. void MyFederateAmbassador::announceSynchronizationPoint ( const char *label, // supplied C4 const char *tag) // supplied C4 throw ( RTI::FederateInternalError) { myData.announceSyncReceived = true; std::cout << "Announce Sync Received for label " << label << " and tag " << tag << endl; } // A previous synchronization point has been achieved by all involved federates. void MyFederateAmbassador::federationSynchronized ( const char *label) // supplied C4) throw ( RTI::FederateInternalError) { myData.federationIsSynchronized = true; std::cout << " My Federation has been synchronized.\n"; }
/******************************************************************************* * Adapted from "Beginning Linux Programming", from Wrox Press -- www.wrox.com *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeKeyboard.cxx,v $ $Revision: 1.1 $ $State: Exp $ *******************************************************************************/ #include "simpleTimeKeyboard.h" #ifdef WIN32 #include <conio.h> #else #include <unistd.h> #endif #include <iostream> keyboard::keyboard() { #ifndef WIN32 tcgetattr(0,&initial_settings); new_settings = initial_settings; new_settings.c_lflag &= ~ICANON; new_settings.c_lflag &= ~ECHO; new_settings.c_lflag &= ~ISIG; new_settings.c_cc[VMIN] = 1; new_settings.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &new_settings); peek_character=-1; #endif } keyboard::~keyboard() { #ifndef WIN32 tcsetattr(0, TCSANOW, &initial_settings); #endif } int keyboard::kbhit() { #ifdef WIN32 return _kbhit(); #else unsigned char ch; int nread; if (peek_character != -1) return 1; new_settings.c_cc[VMIN]=0; tcsetattr(0, TCSANOW, &new_settings); nread = read(0,&ch,1); new_settings.c_cc[VMIN]=1; tcsetattr(0, TCSANOW, &new_settings); if (nread == 1) { peek_character = ch; return 1; } return 0; #endif } int keyboard::getkey() { char ch; #ifdef WIN32 ch = _getch(); #else if (peek_character != -1) { ch = peek_character; peek_character = -1; } else read(0,&ch,1); #endif return ch; } int keyboard::keybrdTick() { char key = ' '; if (!kbhit()) return 0; key = getkey(); while (key != 'q' && key != 'Q' && kbhit()) key = getkey(); if ( key == 'q' || key == 'Q' ) { return -1; } else if ( key == 32 ) { return 1; } else { return 0; } }
/******************************************************************************* ** Copyright (c) 2006 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeAttribute13.cxx,v $ $Revision: 1.2 $ $State: Exp $ *******************************************************************************/ #ifdef WIN32 #pragma warning(disable: 4251) #pragma warning(disable: 4786) #pragma warning(disable: 4290) #endif #include "simpleTimeAttribute13.h" // A simple container class for an attributeUpdate event // Construct an attributeUpdateEvent, store pertinent information from the reflect callback. attributeUpdateEvent::attributeUpdateEvent( const RTI::AttributeHandleValuePairSet& ahvps, const RTI::FedTime& fedTime, const char* tag, RTI::EventRetractionHandle theRetractionHandle ) : myTag(tag), myRetractionHandle(theRetractionHandle) { for ( long unsigned int i(0); i < ahvps.size(); ++i ) { RTI::ULong len = ahvps.getValueLength(i); myAhvps.insert(std::make_pair( ahvps.getHandle(i), std::string( ahvps.getValuePointer(i,len)))); } int length = fedTime.getPrintableLength(); char* buff = new char[length + 1]; const_cast<RTI::FedTime&>(fedTime).getPrintableString(buff); myFedTime = std::string(buff); delete [] buff; } // Construct an attributeEvent from a non-Time Managed reflectAttributeUpdates callback. attributeUpdateEvent::attributeUpdateEvent( const RTI::AttributeHandleValuePairSet& ahvps, const char* tag ) : myTag(tag) { for ( long unsigned int i(0); i < ahvps.size(); ++i ) { RTI::ULong len = ahvps.getValueLength(i); myAhvps.insert(std::make_pair( ahvps.getHandle(i), std::string( ahvps.getValuePointer(i,len)))); } myFedTime = std::string("no Time Given"); } attributeUpdateEvent::~attributeUpdateEvent() { } const std::map<unsigned long, std::string>& attributeUpdateEvent::getAhvps() { return myAhvps; } const std::string& attributeUpdateEvent::getFedTime() { return myFedTime; } const std::string& attributeUpdateEvent::getTag() { return myTag; } RTI::EventRetractionHandle attributeUpdateEvent::getRetractionHandle() { return myRetractionHandle; }
/******************************************************************************* ** Copyright (c) 2006 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeInteraction13.cxx,v $ $Revision: 1.2 $ $State: Exp $ *******************************************************************************/ #ifdef WIN32 #pragma warning(disable: 4251) #pragma warning(disable: 4786) #pragma warning(disable: 4290) #endif #include "simpleTimeInteraction13.h" // Construct an interactionEvent, store pertinent information from the callback. interactionEvent::interactionEvent( RTI::InteractionClassHandle theHandle, const RTI::ParameterHandleValuePairSet& phvps, const RTI::FedTime& fedTime, const char* tag, interaction_type theInteractionType) : myHandle(theHandle), myTag(tag), myInteractionType(theInteractionType) { for ( long unsigned int i(0); i < phvps.size(); ++i ) { RTI::ULong len = phvps.getValueLength(i); myPhvps.insert(std::make_pair( phvps.getHandle(i), std::string( phvps.getValuePointer(i,len)))); } int length = fedTime.getPrintableLength(); char* buff = new char[length + 1]; const_cast<RTI::FedTime&>(fedTime).getPrintableString(buff); myFedTime = std::string(buff); delete [] buff; } // Construct an interactionEvent from a non-Time Managed callback. interactionEvent::interactionEvent( RTI::InteractionClassHandle theHandle, const RTI::ParameterHandleValuePairSet& phvps, const char* tag, interaction_type theInteractionType) : myHandle(theHandle), myTag(tag), myFedTime(""), myInteractionType(theInteractionType) { for ( long unsigned int i(0); i < phvps.size(); ++i ) { RTI::ULong len = phvps.getValueLength(i); myPhvps.insert(std::make_pair( phvps.getHandle(i), std::string( phvps.getValuePointer(i,len)))); } } interactionEvent::~interactionEvent() { } RTI::InteractionClassHandle interactionEvent::getHandle() { return myHandle; } const std::string& interactionEvent::getFedTime() { return myFedTime; } const std::string& interactionEvent::getTag() { return myTag; } int interactionEvent::getTypeOfInteraction() { return myInteractionType; } bool interactionEvent::isFireInteraction() { return myInteractionType == FireType; } bool interactionEvent::isDetonateInteraction() { return myInteractionType == DetonationType; } requestUnit::requestUnit( RTI::ObjectHandle handle, const RTI::AttributeHandleSet& attrHandSet ) : myHandle(handle), myAttrHandleSet(attrHandSet) {} requestUnit::~requestUnit() {} const RTI::AttributeHandleSet& requestUnit::getAttrHandSet() { return myAttrHandleSet; } const RTI::ObjectHandle requestUnit::getHandle() { return myHandle; }
/******************************************************************************* ** Copyright (c) 2006 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeTimeManagedEntity.cxx,v $ $Revision: 1.3 $ $State: Exp $ *******************************************************************************/ #ifdef WIN32 #pragma warning(disable: 4251) #pragma warning(disable: 4786) #pragma warning(disable: 4290) #endif // A simple object that dictates the behavior of an advancing entity. #include "simpleTimeTimeManagedEntity.h" #include <assert.h> #include <iostream> timeManagedEntity::timeManagedEntity() : myFirePressed(false), myPosition(0), myVelocity(0), myPhysicalState(Alive), myState(Initial), myPhaseLine(150) { } timeManagedEntity::~timeManagedEntity() { while ( attrUpdateWaiting() ) { delete getNextAttrUpdateEvent(); } while ( interactionWaiting() ) { delete getNextInteractionEvent(); } } bool timeManagedEntity::attrUpdateWaiting() { return myAttrUpdateQueue.size() > 0; } bool timeManagedEntity::interactionWaiting() { return myInteractionQueue.size() > 0; } interactionEvent* timeManagedEntity::getNextInteractionEvent() { interactionEvent* retVal = myInteractionQueue.front(); myInteractionQueue.pop(); return retVal; } attributeUpdateEvent* timeManagedEntity::getNextAttrUpdateEvent() { attributeUpdateEvent* retVal = myAttrUpdateQueue.front(); myAttrUpdateQueue.pop(); return retVal; } void timeManagedEntity::addInteractionEvent(interactionEvent* eventToAdd) { myInteractionQueue.push(eventToAdd); } void timeManagedEntity::addAttrUpdateEvent(attributeUpdateEvent* eventToAdd) { myAttrUpdateQueue.push(eventToAdd); } bool timeManagedEntity::shouldFire() { return (myState == Firing ); } void timeManagedEntity::reset() { myState = Initial; myPhysicalState = Alive; myFirePressed = false; } bool timeManagedEntity::shouldDetonate() { return (myState == SendDetonate ); } bool timeManagedEntity::isFiredUpon() { return ( myPhysicalState >= FiredUpon ); } bool timeManagedEntity::isDetonated() { return ( myPhysicalState >= Damaged ); } void timeManagedEntity::setPhaseLine(int phaseLine) { myPhaseLine = phaseLine; } void timeManagedEntity::processEvents() { if ( isDetonated() ) { std::cout << "XXX DEAD XXX\n"; while ( interactionWaiting() ) { delete getNextInteractionEvent(); } while ( attrUpdateWaiting() ) { delete getNextAttrUpdateEvent(); } } else { while ( interactionWaiting() ) { interactionEvent* receivedInteraction = getNextInteractionEvent(); std::string fedTime = receivedInteraction->getFedTime(); std::string tag = receivedInteraction->getTag(); if ( receivedInteraction->getTypeOfInteraction() == interactionEvent::FireType && myPhysicalState < FiredUpon ) { std::cout << " received Fire interaction (" << tag << ") at time " << fedTime.c_str() << " \n" ; myPhysicalState = FiredUpon; } if ( receivedInteraction->getTypeOfInteraction() == interactionEvent::DetonationType && myPhysicalState < Damaged ) { std::cout << " received Detonation interaction (" << tag << ") at time " << fedTime.c_str() << " \n" ; myPhysicalState = Damaged; } delete receivedInteraction; } while ( attrUpdateWaiting() ) { attributeUpdateEvent* receivedAttrUpdate = getNextAttrUpdateEvent(); std::string fedTime = receivedAttrUpdate->getFedTime(); std::string tag = receivedAttrUpdate->getTag(); std::cout << " received attribute update (" << tag << ") at time " << fedTime.c_str() << " \n" ; delete receivedAttrUpdate; } } } void timeManagedEntity::incPosition() { ++myPosition; } void timeManagedEntity::firePressed() { myFirePressed = true; } void timeManagedEntity::tick() { if ( !isDetonated()) { processEvents(); switch ( myState ) { case Initial : if ( myFirePressed || myPosition >= myPhaseLine ) { myState = Firing; } break; case Firing : myState = SendDetonate; break; case SendDetonate : myState = Firing; break; } } else { myState = Idle; myPhysicalState = Dead; } }
/******************************************************************************* ** Copyright (c) 2004 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeFedAmb13.h,v $ $Revision: 1.2 $ $State: Exp $ *******************************************************************************/ #pragma warning(disable: 4786) #pragma warning(disable: 4290) #include "NullFederateAmbassador.hh" #include <map> #include <set> #include <string> #include "simpleTimeTimeManagedEntity.h" // Map between strings and attribute handles typedef std::map<std::string, RTI::AttributeHandle> DtAttrNameHandleMap; typedef std::map<std::string, RTI::ParameterHandle> DtParamNameHandleMap; class DtTalkAmbData{ public : DtTalkAmbData(); ~DtTalkAmbData(); public: std::map<RTI::ObjectClassHandle, std::string> objectClassMap; std::map<RTI::ObjectHandle, std::string> objectInstanceMap; std::map<RTI::InteractionClassHandle, std::string> interactionClassMap; std::map<RTI::ObjectHandle, RTI::AttributeHandleSet*> updateRequestMap; // Map between strings and attribute handles DtAttrNameHandleMap theAttrNameHandleMap; // Map between strings and attribute handles DtParamNameHandleMap theParamNameHandleMap; // The set of Attributes that this federate's published objects will contain. std::set <std::string> ourAttrs; // The set of Parameters that this federate's published interactions will contain. std::set <std::string> ourParms; // This federation of simple objects has a single master object, (determined by command line arguments) // The master federate will keep the other federates from entering their main loop of execution until // all of numFederates have joined. bool isMaster; // numFederates is the number of federates (including the master) that the master should wait to join the // federation before it allows any federate to enter its main loop. // This variable is only used by the master federate. int numFederates; RTI::AttributeHandleValuePairSet* attrValues; RTI::ParameterHandleValuePairSet* paramValues; bool isConstrained; bool isRegulating; bool timeAdvanced; int otherFederatesReady; bool registerFailed; bool registerSucceeded; bool announceSyncReceived; bool federationIsSynchronized; timeManagedEntity timeManagedObject; }; class MyFederateAmbassador : public NullFederateAmbassador { public: MyFederateAmbassador(DtTalkAmbData & data); virtual ~MyFederateAmbassador() throw (RTI::FederateInternalError); // Object Management Services // virtual void discoverObjectInstance ( RTI::ObjectHandle theObject, // supplied C1 RTI::ObjectClassHandle theObjectClass, // supplied C1 const char* theObjectName) // supplied C4 throw ( RTI::CouldNotDiscover, RTI::ObjectClassNotKnown, RTI::FederateInternalError); virtual void reflectAttributeValues ( RTI::ObjectHandle theObject, // supplied C1 const RTI::AttributeHandleValuePairSet& theAttributes, // supplied C4 const RTI::FedTime& theTime, // supplied C1 const char *theTag, // supplied C4 RTI::EventRetractionHandle theHandle) // supplied C1 throw ( RTI::ObjectNotKnown, RTI::AttributeNotKnown, RTI::FederateOwnsAttributes, RTI::InvalidFederationTime, RTI::FederateInternalError); virtual void reflectAttributeValues ( RTI::ObjectHandle theObject, // supplied C1 const RTI::AttributeHandleValuePairSet& theAttributes, // supplied C4 const char *theTag) // supplied C4 throw ( RTI::ObjectNotKnown, RTI::AttributeNotKnown, RTI::FederateOwnsAttributes, RTI::FederateInternalError); // 4.6 virtual void receiveInteraction ( RTI::InteractionClassHandle theInteraction, // supplied C1 const RTI::ParameterHandleValuePairSet& theParameters, // supplied C4 const RTI::FedTime& theTime, // supplied C4 const char *theTag, // supplied C4 RTI::EventRetractionHandle theHandle) // supplied C1 throw ( RTI::InteractionClassNotKnown, RTI::InteractionParameterNotKnown, RTI::InvalidFederationTime, RTI::FederateInternalError); virtual void receiveInteraction ( RTI::InteractionClassHandle theInteraction, // supplied C1 const RTI::ParameterHandleValuePairSet& theParameters, // supplied C4 const char *theTag) // supplied C4 throw ( RTI::InteractionClassNotKnown, RTI::InteractionParameterNotKnown, RTI::FederateInternalError); virtual void removeObjectInstance ( RTI::ObjectHandle theObject, // supplied C1 const RTI::FedTime& theTime, // supplied C4 const char *theTag, // supplied C4 RTI::EventRetractionHandle theHandle) // supplied C1 throw ( RTI::ObjectNotKnown, RTI::InvalidFederationTime, RTI::FederateInternalError); virtual void removeObjectInstance ( RTI::ObjectHandle theObject, // supplied C1 const char *theTag) // supplied C4 throw ( RTI::ObjectNotKnown, RTI::FederateInternalError); virtual void provideAttributeValueUpdate ( RTI::ObjectHandle theObject, const RTI::AttributeHandleSet& theAttributes) throw ( RTI::ObjectNotKnown, RTI::AttributeNotKnown, RTI::AttributeNotOwned, RTI::FederateInternalError); virtual void timeRegulationEnabled ( const RTI::FedTime& theFederateTime) // supplied C4 throw ( RTI::InvalidFederationTime, RTI::EnableTimeRegulationWasNotPending, RTI::FederateInternalError); virtual void timeConstrainedEnabled ( const RTI::FedTime& theFederateTime) // supplied C4 throw ( RTI::InvalidFederationTime, RTI::EnableTimeConstrainedWasNotPending, RTI::FederateInternalError); virtual void timeAdvanceGrant ( const RTI::FedTime& theTime) // supplied C4 throw ( RTI::InvalidFederationTime, RTI::TimeAdvanceWasNotInProgress, RTI::FederateInternalError); virtual void synchronizationPointRegistrationSucceeded ( const char *label) // supplied C4) throw ( RTI::FederateInternalError); virtual void synchronizationPointRegistrationFailed ( const char *label) // supplied C4) throw ( RTI::FederateInternalError); virtual void announceSynchronizationPoint ( const char *label, // supplied C4 const char *tag) // supplied C4 throw ( RTI::FederateInternalError); virtual void federationSynchronized ( const char *label) // supplied C4) throw ( RTI::FederateInternalError); public: DtTalkAmbData & myData; };
/******************************************************************************* * Adapted from "Beginning Linux Programming", from Wrox Press -- www.wrox.com *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeKeyboard.h,v $ $Revision: 1.1 $ $State: Exp $ *******************************************************************************/ // Utility to allow keyboard input without blocking #ifndef MYKBHIT_H_ #define MYKBHIT_H_ #ifndef WIN32 #include <termios.h> #endif class keyboard { public: keyboard(); ~keyboard(); // Returns 1 if keyboard input is ready; otherwise, 0 int kbhit(); // Returns character from keyboard if avaialable; otherwise, 0 int keybrdTick(); protected: // Return character from keyboard input int getkey(); private: #ifndef WIN32 struct termios initial_settings, new_settings; int peek_character; #endif }; #endif
/******************************************************************************* ** Copyright (c) 2006 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeTimeManagedEntity.h,v $ $Revision: 1.3 $ $State: Exp $ *******************************************************************************/ #ifndef _TIMEMANAGEDOBJECTDEFINITION_ #define _TIMEMANAGEDOBJECTDEFINITION_ // A simple object that dictates the behavior of an advancing entity. #ifdef DtIFSPEC1516 #include "simpleTimeAttribute1516.h" #include "simpleTimeInteraction1516.h" #elif defined(DtIFSPEC1516E) #include "simpleTimeAttribute1516e.h" #include "simpleTimeInteraction1516e.h" #else #ifdef DtIFSPEC13DLC #include "simpleTimeAttribute13dlc.h" #include "simpleTimeInteraction13dlc.h" #else #include "simpleTimeAttribute13.h" #include "simpleTimeInteraction13.h" #endif #endif #include <queue> class timeManagedEntity { public: enum entity_state{ Alive = 0, FiredUpon = 1, Damaged = 2, Dead = 3 }; enum active_state{ Initial = 0, Firing = 1, SendDetonate = 3, Idle = 5}; // constructor and destructor for timeManagedEntity timeManagedEntity(); ~timeManagedEntity(); // Peek at our queue's of attributes and Interaction to see if there // is an event waiting to be processed. bool attrUpdateWaiting(); bool interactionWaiting(); // retreive an event from one of the event queue's attributeUpdateEvent* getNextAttrUpdateEvent(); interactionEvent* getNextInteractionEvent(); // add an event to our event queue. void addAttrUpdateEvent(attributeUpdateEvent*); void addInteractionEvent(interactionEvent*); // access this timeManagedEntity's state. bool shouldFire(); bool shouldDetonate(); bool isFiredUpon(); bool isDetonated(); // Change this timeManagedEntity's state. void setPhaseLine(int phaseLine); void incPosition(); void firePressed(); void reset(); // Sets myState to the correct Value. void tick(); private: void sendFire(); void sendDetonate(); void processEvents(); private: bool myFirePressed; unsigned int myPosition; unsigned int myVelocity; // myPhaseLine acts as a boundary for this federate. When the position of the timeManagedEntity is past // the myPhaseLine, the timeManagedEntity will start firing on other federates. unsigned int myPhaseLine; entity_state myPhysicalState; active_state myState; std::queue< attributeUpdateEvent* > myAttrUpdateQueue; std::queue< interactionEvent* > myInteractionQueue; }; #endif
/******************************************************************************* ** Copyright (c) 2004 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeStringUtil.h,v $ $Revision: 1.2 $ $State: Exp $ *******************************************************************************/ #ifndef stringUtil_H_ #define stringUtil_H_ #include <string> #include <sstream> #include <iomanip> #include <iostream> using namespace std; // Convert narrow C string to wide string inline wstring DtToWString(const char * in_val) { wstring temp; while (*in_val != '\0') temp += *in_val++; return temp; } // Convert narrow string to wide string inline string DtToString(const wstring &in_val) { string temp; wstring::const_iterator b = in_val.begin(); const wstring::const_iterator e = in_val.end(); while (b != e) { temp += static_cast<char>(*b); ++b; } return temp; } inline string usage() { ostringstream ostr; ostr << "Usage: simpletime13/1516(d) [-fedFile fedFileName][-m #Federates][-phaseLine #][-sleepTime s][-dedicated][-unManaged]" << endl << endl << setw( 20 ) << " -fedFile " << " Specify the Fed file name \n" << setw ( 24 ) << " " << "Default : MAKsimple.xml/fed. \n" << setw( 20 ) << " -m " << " Specify whether this federate is the master and if so, how many \n" << setw( 24 ) << " " << "total federates it should wait for. \n" << setw( 20 ) << " -phaseLine " << " Specify the boundary, which when this federate\n" << setw( 24 ) << " " << "crosses it, it starts firing.\n" << setw( 24 ) << " " << " Default is 75 units. \n" << setw( 20 ) << " -sleepTime " << " Specify the time in ms to sleep between iterations of the main loop. \n" << setw( 24 ) << " " << " Default is 850 ms. \n" << setw( 20 ) << " -dedicated " << " Specify whether this federate is on a machine dedicated to running\n" << setw( 24 ) << " " << " this federate. Invalidates all sleeps and yields.\n" << setw( 20 ) << " -unManaged " << " Specify whether this federate will respect the synchronization step\n" << setw( 24 ) << " " << " before time advancing.\n" << endl; return ostr.str(); } template< class T > bool convert( const string& param, const string& value, T& dest ) { istringstream convert( value ); convert >> dest; if ( convert.fail() ) { std::cout << "Bad Parameter Value\n" << "Param: " << param << "\tValue: " << value << endl; return false; } return true; } #endif
/******************************************************************************* ** Copyright (c) 2006 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeAttribute13.h,v $ $Revision: 1.1 $ $State: Exp $ *******************************************************************************/ #ifndef _ATTRIBUTE13DEFINITION_ #define _ATTRIBUTE13DEFINITION_ // A simple container class for an attribute update event. #include <map> #include <string> #include "RTI.hh" // An attributeUpdateEvent object encapsulates the contents of a // reflectattributeupdates callback. Note, that not all contents of the // callback are stored, only those required for our specific application. // That information can then be stored and later retrieved to be processed. class attributeUpdateEvent { public: attributeUpdateEvent( const RTI::AttributeHandleValuePairSet& pvhps, const RTI::FedTime& fedTime, const char* tag, RTI::EventRetractionHandle theRetractionHandle ); attributeUpdateEvent( const RTI::AttributeHandleValuePairSet& phvps, const char* tag ); ~attributeUpdateEvent(); RTI::ObjectHandle getHandle(); const std::map<unsigned long, std::string>& getAhvps(); const std::string& getFedTime(); const std::string& getTag(); RTI::EventRetractionHandle getRetractionHandle(); private: RTI::ObjectHandle myHandle; std::map<unsigned long, std::string> myAhvps; std::string myFedTime; std::string myTag; RTI::EventRetractionHandle myRetractionHandle; }; #endif // #define _ATTRIBUTE13DEFINITION_
/******************************************************************************* ** Copyright (c) 2006 MaK Technologies, Inc. ** All rights reserved. *******************************************************************************/ /******************************************************************************* ** $RCSfile: simpleTimeInteraction13.h,v $ $Revision: 1.1 $ $State: Exp $ *******************************************************************************/ #ifndef _INTERACTIONDEFINITION_ #define _INTERACTIONDEFINITION_ // A simple container class for an interaction event #include <map> #include <string> #include "RTI.hh" // An interactionEvent object encapsulates the contents of a // receiveInteraction callback. Note, that not all contents of the // callback are stored, only those required for our specific application. // That information can then be stored and later retrieved to be processed. class interactionEvent { public: enum interaction_type{ Unknown, FireType, DetonationType }; interactionEvent(RTI::InteractionClassHandle theHandle, const RTI::ParameterHandleValuePairSet& pvhps, const RTI::FedTime& fedTime, const char* tag, interaction_type theInteractionType = Unknown ); // Constructor for an interaction with no reported FedTime. interactionEvent(RTI::InteractionClassHandle theHandle, const RTI::ParameterHandleValuePairSet& pvhps, const char* tag, interaction_type theInteractionType = Unknown ); ~interactionEvent(); RTI::InteractionClassHandle getHandle(); // const std::map<unsigned long, std::string>& getPhvps(); bool isFireInteraction(); bool isDetonateInteraction(); const std::string& getFedTime(); const std::string& getTag(); RTI::EventRetractionHandle getRetractionHandle(); int getTypeOfInteraction(); private: RTI::InteractionClassHandle myHandle; std::map<unsigned long, std::string> myPhvps; std::string myFedTime; std::string myTag; int myInteractionType; }; class requestUnit { public: requestUnit( RTI::ObjectHandle, const RTI::AttributeHandleSet& attrHandSet ); ~requestUnit(); const RTI::AttributeHandleSet& getAttrHandSet(); const RTI::ObjectHandle getHandle(); private: const RTI::AttributeHandleSet& myAttrHandleSet; RTI::ObjectHandle myHandle; }; #endif