MAK RTIspy API Documentation for HLA Evolved
rtisimple Example Code for HLA 1516

rtiSimple1516.cxx and rtiSimpleFedAmb1516.cxx (rtiSimpleFedAmb1516.h) have the RTI calls and federate ambassador calls for the HLA 1516 version of rtisimple.

This page has the code for the following files:


rtiSimple1516.cxx

/*******************************************************************************
** Copyright (c) 2004 MaK Technologies, Inc.
** All rights reserved.
*******************************************************************************/

// 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

#pragma warning(disable: 4251)
#pragma warning(disable: 4786)
#pragma warning(disable: 4290)

#ifdef WIN32
#include <winsock2.h>
#include <process.h>

#else
#include <unistd.h>
#endif

#include <stdio.h>
#include <wchar.h>
#include <sstream>
#include <string>
#include <iostream>
#include <sstream>
#include <cstring> 
#include <cstdlib>

#include <RTI/RTI1516.h>
#include "rtiSimpleFedAmb1516.h"
#include "rtiSimpleKeyboard.h"
#include "rtiSimpleStringUtil.h"

// Handles keyboard input without blocking
keyboard input;

using namespace rti1516;
using namespace std;

// Map between strings and attribute handles
typedef std::map<std::wstring, AttributeHandle>  DtAttrNameHandleMap;

// Map between strings and parameter handles
typedef std::map<std::wstring, ParameterHandle>  DtParamNameHandleMap;


// Data shared between federate and federate ambassador
DtTalkAmbData theAmbData;

// The federate handle
FederateHandle theFederateHandle;

// The object class name
std::wstring theClassName = L"BaseEntity";

// The interaction class name
std::wstring theInterClassName = L"WeaponFire";

// The object class handle (to be retrieved from RTI).
ObjectClassHandle theClassHandle;

// The interaction class handle (to be retrieved from RTI).
InteractionClassHandle theInterClassHandle;

// The object instance handle (to be retrieved from the RTI).
ObjectInstanceHandle theObjectHandle;

// Map between strings and attribute handles
DtAttrNameHandleMap theAttrNameHandleMap;

// Map between strings and parameter handles
DtParamNameHandleMap theParamNameHandleMap;



// Create the federation execution
void createFedEx(RTIambassador & rtiAmb,
                 std::wstring const& fedName,
                 std::wstring const& fedFile)
{
   wcout << L"createFederationExecution "
         << fedName.c_str() << L" "
         << fedFile.c_str() << endl;
   try
   {
      rtiAmb.createFederationExecution(fedName, fedFile);      
   }
   catch(FederationExecutionAlreadyExists& ex)
   {
      wcout << L"Could not create Federation Execution: "
            << L"FederationExecutionAlreadyExists: "
            << ex.what().c_str() << endl;
   }
   catch(rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl
            << L"Could not create Federation Execution: " << endl;
      exit(0);
   }
   rtiAmb.evokeMultipleCallbacks(0.1, 0.2);

   wcout << L"Federation Created." << endl;
}

// Join the federation execution
void joinFedEx(
   RTIambassador & rtiAmb, MyFederateAmbassador & fedAmb,
   std::wstring const& federateType, std::wstring const& federationName)
{
   bool joined=false;
   const int maxTry  = 10;
   int numTries = 0;
   wcout << L"joinFederationExecution "
         << federateType.c_str() << L" "
         << federationName.c_str() << endl;

   while (!joined && numTries++ < maxTry)
   {
      try
      {
         theFederateHandle = rtiAmb.joinFederationExecution(federateType, federationName, fedAmb);
         joined = true;
      }
      catch(FederationExecutionDoesNotExist)
      {
         wcout << L"FederationExecutionDoesNotExist, try "
               << numTries << L" out of "
               << maxTry << endl;
         continue;
      }
      catch(rti1516::Exception& ex)
      {
         wcout << L"RTI Exception: "
               << ex.what().c_str() << endl;
         return;
      }
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }
   if (joined)
      wcout << L"Joined Federation." << endl;
   else
   {
      wcout << L"Giving up." << endl;
      rtiAmb.destroyFederationExecution(federationName);
      exit(0);
   }
}

// Resign and destroy the federation execution
void resignAndDestroy( RTIambassador & rtiAmb,
      std::wstring const& federationName)
{
   wcout << L"Resign and Destroy Federation" << endl;
   rtiAmb.resignFederationExecution(rti1516::DELETE_OBJECTS);
   rtiAmb.destroyFederationExecution(federationName);
}

// Save federation

// Query federation save status
void queryFederationSaveStatus(RTIambassador & rtiAmb)
{
   wcout << L"Query save status\n";

   rtiAmb.queryFederationSaveStatus();

   int count = 0;
   while ( count++ < 100
      && !theAmbData.myReceivedFederationSaveStatusResponse )
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedFederationSaveStatusResponse )
   {
      wcout << L"Timed out waiting for status response\n";
   }
   else
   {
      FederateHandleSaveStatusPairVector::const_iterator statusIter = theAmbData.myFederateHandleSaveStatus.begin();
      FederateHandleSaveStatusPairVector::const_iterator statusEnd = theAmbData.myFederateHandleSaveStatus.end();

      for ( ; statusIter != statusEnd; ++statusIter )
      {
         wcout << L"Status federate " << statusIter->first.toString().c_str() << L" is ";
         switch (statusIter->second)
         {
         case NO_SAVE_IN_PROGRESS:
            wcout << L"NO_SAVE_IN_PROGRESS\n";
            break;
         case FEDERATE_INSTRUCTED_TO_SAVE:
            wcout << L"FEDERATE_INSTRUCTED_TO_SAVE\n";
            break;
         case FEDERATE_SAVING:
            wcout << L"FEDERATE_SAVING\n";
            break;
         case FEDERATE_WAITING_FOR_FEDERATION_TO_SAVE:
            wcout << L"FEDERATE_WAITING_FOR_FEDERATION_TO_SAVE\n";
            break;
         default:
            wcout << L"UNKNOWN\n";
            break;
         }
      }
   }
}

// Request federation save and wait for initiate
// Return save status
bool requestFederationSave(RTIambassador & rtiAmb, std::wstring const& label)
{
   bool saveOk = true;
   int count = 0;
   // Turn the signals off
   theAmbData.myReceivedInitiateFederateSave =
      theAmbData.myReceivedFederationSaved =
      theAmbData.myReceivedFederationNotSaved =
      theAmbData.myReceivedFederationSaveStatusResponse = false;

   wcout << L"Request federation save with label " << label.c_str() << endl;

   // Request the save and wait for the signal that the save has been initiated
   // or that the federation has not saved (could be that some other federate
   // resigns during save)
   rtiAmb.requestFederationSave(label);

   while (count++ < 100
      && !theAmbData.myReceivedInitiateFederateSave
      && !theAmbData.myReceivedFederationNotSaved)
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedInitiateFederateSave )
   {
      saveOk = false;
      if ( !theAmbData.myReceivedFederationNotSaved )
      {
         wcout << L"Timed out waiting for initiate federate save\n";
         queryFederationSaveStatus(rtiAmb);
      }
   }
   return saveOk;
}

// Wait for federation saved
// Return save status
bool waitForFederationSaved(RTIambassador & rtiAmb)
{
   bool saveOk = true;
   int count = 0;

   // Wait until the RTI signals that the entire federation completed the save

   while ( count++ < 100
      && !theAmbData.myReceivedFederationNotSaved
      && !theAmbData.myReceivedFederationSaved )
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedFederationSaved )
   {
      saveOk = false;
      if ( !theAmbData.myReceivedFederationNotSaved )
      {
         wcout << L"Timed out waiting for federation saved\n";
         queryFederationSaveStatus(rtiAmb);
      }
   }
   return saveOk;
}

// Perform save federation
// Return save status
bool saveFederation(RTIambassador & rtiAmb, std::wstring const& label, bool performRequest)
{
   bool saveOk = true;
   int count = 0;

   try
   {
      if ( performRequest )
      {
         saveOk = requestFederationSave(rtiAmb, label);
      }

      if ( theAmbData.myReceivedInitiateFederateSave )
      {
         // At this point, the save has been initiated
         // and the federate cannot invoke any other calls except
         // to complete the save (or resign). It signals to the RTI that
         // it will begin saving its own local state

         wcout << L"Federate save begun\n";
         rtiAmb.federateSaveBegun();

         // Here the federate would save its own state including any context
         // information relating to the RTI
         // (i.e. what classes are published and subscribed
         // object instance handles for registered and discovered objects, etc.

         // Once the federate saves is own data, it signals to the RTI that its
         // save is complete.
         wcout << L"Federate save complete\n";
         rtiAmb.federateSaveComplete();

         // Wait until the RTI signals that the entire federation completed the save
         saveOk = waitForFederationSaved(rtiAmb);
      }
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: " << ex.what().c_str() << endl;
      wcout << L"Could not  save federation " << label.c_str() << endl;
      saveOk = false;
   }
   catch(exception& stdEx)
   {
      wcout << L"Standard exception: " << stdEx.what() << endl;
      wcout << L"Could not  save federation " << label.c_str() << endl;
      saveOk = false;
   }
   catch(...)
   {
      wcout << L"Unknown exception\n";
      wcout << L"Could not  save federation " << label.c_str() << endl;
      saveOk = false;
   }

   // Turn the signals off
   theAmbData.myReceivedInitiateFederateSave =
      theAmbData.myReceivedFederationSaved =
      theAmbData.myReceivedFederationNotSaved =
      theAmbData.myReceivedFederationSaveStatusResponse = false;

   return saveOk;
}

// Restore federation

// Query restore status
void queryRestoreStatus(RTIambassador & rtiAmb)
{
   // Check the status
   rtiAmb.queryFederationRestoreStatus();

   int count = 0;
   while ( count++ < 100
      && !theAmbData.myReceivedFederationRestoreStatusResponse )
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedFederationRestoreStatusResponse )
   {
      wcout << L"Timed out waiting for restore status\n";
   }
   else
   {
      FederateHandleRestoreStatusPairVector::const_iterator statusIter = theAmbData.myFederateHandleRestoreStatus.begin();
      FederateHandleRestoreStatusPairVector::const_iterator statusEnd = theAmbData.myFederateHandleRestoreStatus.end();

      for ( ; statusIter != statusEnd; ++statusIter )
      {
         wcout << L"Status federate " << statusIter->first.toString().c_str() << L" is ";
         switch (statusIter->second)
         {
         case NO_RESTORE_IN_PROGRESS:
            wcout << L"NO_RESTORE_IN_PROGRESS\n";
            break;
         case FEDERATE_RESTORE_REQUEST_PENDING:
            wcout << L"FEDERATE_RESTORE_REQUEST_PENDING\n";
            break;
         case FEDERATE_WAITING_FOR_RESTORE_TO_BEGIN:
            wcout << L"FEDERATE_WAITING_FOR_RESTORE_TO_BEGIN\n";
            break;
         case FEDERATE_PREPARED_TO_RESTORE:
            wcout << L"FEDERATE_PREPARED_TO_RESTORE\n";
            break;
         case FEDERATE_RESTORING:
            wcout << L"FEDERATE_RESTORING\n";
            break;
         case FEDERATE_WAITING_FOR_FEDERATION_TO_RESTORE:
            wcout << L"FEDERATE_WAITING_FOR_FEDERATION_TO_RESTORE\n";
            break;
         default:
            wcout << L"UNKNOWN\n";
            break;
         }
      }
   }
}

// Request the restore and wait for the response.
// Return request status
bool requestFederationRestore(RTIambassador & rtiAmb, std::wstring const& label)
{
   int count = 0;
   bool restoreOk = true;

   wcout << L"Request federation restore with label " << label.c_str() << endl;

   // Turn the signals off
   theAmbData.myReceivedRequestFederationRestoreSucceeded =
      theAmbData.myReceivedRequestFederationRestoreFailed =
      theAmbData.myReceivedFederationRestoreBegun =
      theAmbData.myReceivedInitiateFederateRestore =
      theAmbData.myReceivedFederationRestored =
      theAmbData.myReceivedFederationNotRestored =
      theAmbData.myReceivedFederationRestoreStatusResponse = false;
   theAmbData.myFederateHandleRestoreStatus.clear();

   rtiAmb.requestFederationRestore(label);
   while (count++ < 100
      && !theAmbData.myReceivedRequestFederationRestoreSucceeded
      && !theAmbData.myReceivedRequestFederationRestoreFailed)
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedRequestFederationRestoreSucceeded )
   {
      restoreOk = false;
      if ( !theAmbData.myReceivedRequestFederationRestoreFailed )
      {
         wcout << L"Timed out waiting for request federation restore succeeded.\n";
         queryRestoreStatus(rtiAmb);
      }
   }
   return restoreOk;
}

// Wait for restore begun
// Return begun status
bool waitForRestoreBegun(RTIambassador & rtiAmb)
{
   bool restoreOk = true;
   // Wait for the restore begun

   wcout << L"Wait for restore begun\n";
   int count = 0;
   while (count++ < 100
      && !theAmbData.myReceivedFederationRestoreBegun
      && !theAmbData.myReceivedFederationNotRestored)
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedFederationRestoreBegun )
   {
      restoreOk = false;
      if (!theAmbData.myReceivedFederationNotRestored)
      {
         wcout << L"Timed out waiting for federation restore begun.\n";
         queryRestoreStatus(rtiAmb);
      }
   }
   return restoreOk;
}

// Wait for initiate restore
// Return initiate status
bool waitForInitiateRestore(RTIambassador & rtiAmb)
{
   bool restoreOk = true;

   // Wait for the initiate restore

   wcout << L"Wait for initiate restore\n";

   int count = 0;
   while (count++ < 100
      && !theAmbData.myReceivedInitiateFederateRestore
      && !theAmbData.myReceivedFederationNotRestored)
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( theAmbData.myReceivedFederationNotRestored )
   {
      restoreOk = false;
   }
   else if ( !theAmbData.myReceivedInitiateFederateRestore )
   {
      restoreOk = false;
      wcout << L"Timed out waiting for initiate federate restore.\n";
      queryRestoreStatus(rtiAmb);
   }
   else if ( theAmbData.myRestoreFederateHandle != theFederateHandle )
   {
      // In general, a federate must be able to restore any saved state of
      // a federate of the same type. Even if a federate submits
      // a unique federate type string during join, the current federate
      // and object handles may not match those being restored.
      // This simplistic federate implementation cannot handle the case where
      // the federate and object handles are different.
      wcout << L"Restore initiated with handle " << theAmbData.myRestoreFederateHandle.toString().c_str()
         << L" does not match current handle " << theFederateHandle.toString().c_str() << endl;
      wcout << L"Unable to complete restore\n";

      restoreOk = false;

      // Will revert to state before restore was begun
      rtiAmb.federateRestoreNotComplete();

      count = 0;
      while ( count++ < 100
         && !theAmbData.myReceivedFederationNotRestored )
      {
         rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
      }

      if ( !theAmbData.myReceivedFederationNotRestored )
      {
         wcout << L"Timed out waiting for federation not restored.\n";
         queryRestoreStatus(rtiAmb);
      }
   }

   return restoreOk;
}

// Wait for federation (not) restored
// Return restore status
bool waitForFederationRestored(RTIambassador & rtiAmb)
{
   bool restoreOk = true;
   // Wait until the RTI signals that the entire federation completed the restore

   wcout << L"Wait for federation restored\n";
   int count = 0;
   while ( count++ < 100
      && !theAmbData.myReceivedFederationRestored
      && !theAmbData.myReceivedFederationNotRestored )
   {
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }

   if ( !theAmbData.myReceivedFederationRestored )
   {
      restoreOk = false;
      if ( !theAmbData.myReceivedFederationNotRestored )
      {
         wcout << L"Timed out waiting for federation restored.\n";
         queryRestoreStatus(rtiAmb);
      }
   }
   return restoreOk;
}

// Perform restore federation
// Return restore status
bool restoreFederation(RTIambassador & rtiAmb, std::wstring const& label, bool performRequest)
{
   bool restoreOk = true;
   int count = 0;

   theAmbData.myReceivedFederationNotRestored = false;

   try
   {
      if ( performRequest )
      {
         if ( requestFederationRestore(rtiAmb, label) )
         {
            restoreOk = waitForRestoreBegun(rtiAmb);
         }
      }

      if ( theAmbData.myReceivedFederationRestoreBegun )
      {
         // At this point, the restore has begun
         // and the federate cannot invoke any other calls except
         // to complete the restore (or resign). It waits for the
         // initiate restore to begin restoring its local state.

         if ( restoreOk = waitForInitiateRestore(rtiAmb) )
         {
            // Here the federate would restore its own state including any context
            // information relating to the RTI
            // (i.e. what classes are published and subscribed
            // object instance handles for registered and discovered objects, etc.

            // Once the federate restores its own data, it signals to the RTI that its
            // restore is complete.
            wcout << L"Federate restore complete\n";
            rtiAmb.federateRestoreComplete();
            // If the federate was unable to restore its state, it would respond with
            // federateRestoreNotComplete();

            // Now wait for remaining federation to be restored
            restoreOk = waitForFederationRestored(rtiAmb);
         }
      }
   }
   catch (rti1516::FederateInternalError& ex)
   {
      wcout << L"RTI Exception: " << ex.what().c_str() << endl;
      wcout << L"Could not restore federation " << label.c_str() << endl;
      restoreOk = false;
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: " << ex.what().c_str() << endl;
      wcout << L"Could not restore federation " << label.c_str() << endl;
      restoreOk = false;
   }
   catch(exception& stdEx)
   {
      wcout << L"Standard exception: " << stdEx.what() << endl;
      wcout << L"Could not restore federation " << label.c_str() << endl;
      restoreOk = false;
   }
   catch(...)
   {
      wcout << L"Unknown exception\n";
      wcout << L"Could not restore federation " << label.c_str() << endl;
      restoreOk = false;
   }

   // Turn the signals off
   theAmbData.myReceivedRequestFederationRestoreSucceeded =
      theAmbData.myReceivedRequestFederationRestoreFailed =
      theAmbData.myReceivedFederationRestoreBegun =
      theAmbData.myReceivedInitiateFederateRestore =
      theAmbData.myReceivedFederationRestored =
      theAmbData.myReceivedFederationNotRestored =
      theAmbData.myReceivedFederationRestoreStatusResponse = false;
      theAmbData.myFederateHandleRestoreStatus.clear();

   return restoreOk;
}


// Publish and subscribe the object class attributes.
// Register an object instance of the class.
bool publishSubscribeAndRegisterObject(RTIambassador & rtiAmb)
{
   AttributeHandleSet hSet;
   // Get the object class handle
   try
   {  
      theClassHandle = rtiAmb.getObjectClassHandle(theClassName);     
      theAmbData.objectClassMap[theClassHandle] = theClassName;
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not get object class handle: "
            << theClassName.c_str() << endl;
      return false;
   }

   // Get the attribute handles and construct the name-handle map and
   // attribute set
   std::wstring attrName;
   try
   {
      attrName  = L"AccelerationVector";
      theAttrNameHandleMap[attrName] = 
            rtiAmb.getAttributeHandle(theClassHandle, attrName);
      hSet.insert(theAttrNameHandleMap[attrName]);
      attrName  = L"VelocityVector";
      theAttrNameHandleMap[attrName] = 
            rtiAmb.getAttributeHandle(theClassHandle, attrName);
      hSet.insert(theAttrNameHandleMap[attrName]);
      attrName  = L"Orientation";
      theAttrNameHandleMap[attrName] = 
            rtiAmb.getAttributeHandle(theClassHandle, attrName);
      hSet.insert(theAttrNameHandleMap[attrName]);
      attrName  = L"DeadReckoningAlgorithm";
      theAttrNameHandleMap[attrName] = 
            rtiAmb.getAttributeHandle(theClassHandle, attrName);
      hSet.insert(theAttrNameHandleMap[attrName]);
      attrName  = L"WorldLocation";
      theAttrNameHandleMap[attrName] = 
            rtiAmb.getAttributeHandle(theClassHandle, attrName);
      hSet.insert(theAttrNameHandleMap[attrName]);
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not get attribute handle "
            << attrName.c_str() << endl;
      return false;
   }

    // Publish and subscribe
   int cnt=0;
   try
   {
      rtiAmb.publishObjectClassAttributes(theClassHandle, hSet);
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
      cnt=1;
      rtiAmb.subscribeObjectClassAttributes(theClassHandle, hSet);
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not "
            << (cnt ? L"subscribe" : L"publish") << endl;
      return false;
   }

   std::wstring objectName(L"Talk");

   // Reserve object name and register the object instance
   try
   {
      unsigned int objId = abs(getpid());
      std::wstringstream pid;
      pid << objId;
      objectName += pid.str();
      theAmbData.myNameReservationReturned = 
      theAmbData.myNameReservationSucceeded = false;
      rtiAmb.reserveObjectInstanceName(objectName);
      int count = 0;
      while (count++ < 100 && !theAmbData.myNameReservationReturned)
      {
         rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
      }

      if (count < 100)
      {
         theObjectHandle = rtiAmb.registerObjectInstance(theClassHandle,
               objectName);
         //theObjectHandle = rtiAmb.registerObjectInstance(theClassHandle);

         // Add name-handle to map
         theAmbData.objectInstanceMap[theObjectHandle] =
            rtiAmb.getObjectInstanceName(theObjectHandle);
      }
      else
      {
         wcout << L"Failed waiting for reserve object name "
               << objectName.c_str() << endl;
         return false;
      }
      rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not  Register Object "
            << objectName.c_str()
            << L" with class "
            << theClassName.c_str() << endl;
      return false;
   }

   wcout << L"Registered object "
         << objectName.c_str()
         << L" with class name "
         << theClassName.c_str() << endl;
   return true;
}

// Publish and Subscribe to an interaction class
bool publishAndSubscribeInteraction(RTIambassador & rtiAmb)
{
   // Get the interaction class handle
   try
   {  
      theInterClassHandle = rtiAmb.getInteractionClassHandle(theInterClassName.c_str());
      theAmbData.interactionClassMap[theInterClassHandle] = theInterClassName;
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not get interaction class handle: "
            << theInterClassName.c_str() << endl;
      return false;
   }

   // Get the parameter handles and construct the name-handle map
   std::wstring paramName;
   try
   {
      paramName  = L"EventIdentifier";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"FireControlSolutionRange";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"FireMissionIndex";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"FiringLocation";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"FiringObjectIdentifier";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"FuseType";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"InitialVelocityVector";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"MunitionObjectIdentifier";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"MunitionType";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"QuantityFired";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"RateOfFire";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"TargetObjectIdentifier";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
      paramName  = L"WarheadType";
      theParamNameHandleMap[paramName] = 
            rtiAmb.getParameterHandle(theInterClassHandle, paramName);
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not get parameter handle "
            << paramName.c_str() << endl;
      return false;
   }

    // Publish and subscribe
   int cnt=0;
   try
   {
   rtiAmb.publishInteractionClass(theInterClassHandle);
   rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   cnt=1;
   rtiAmb.subscribeInteractionClass(theInterClassHandle);
   rtiAmb.evokeMultipleCallbacks(0.1, 0.2);
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception: "
            << ex.what().c_str() << endl;
      wcout << L"Could not "
            << (cnt ? L"publish" : L"subscribe")
            << L" to interaction class." << endl;
      return false;
   }

   wcout  << L"Subscribed to interaction class: "
          << theInterClassName.c_str()
          << L" with handle: "
          <<  theInterClassHandle.toString() << endl;
   return true;
}


int main(int argc, char** argv)
{
   std::cout << "MAK rtiSimple version 1516" << std::endl;


   RTIambassador* rtiAmb = 0;

   try
   {
      // Federate and Federation info
      std::vector< std::wstring > args;
      std::wstring federationName(L"MAKsimple");
      std::wstring federationFile(L"MAKsimple.xml");
      std::wstring federateType(L"rtisimple1516");

      if (argc > 1)
      {
         if (strcmp(argv[1], "-h") == 0)
         {
            wcout << L"Usage: rtisimple1516 [federtionName] [federationFile] [federateType]" << endl;
            wcout << L"default values: "
                  << L"\"" << federationName.c_str() << L"\" "
                  << L"\"" << federationFile.c_str() <<  L"\" "
                  << L"\"" << federateType.c_str() <<  L"\" " << endl;
            return 0;
         }
         federationName = DtToWString(argv[1]);
      }

      if (argc > 2)
      {
         federationFile = DtToWString(argv[2]);
      }

      if (argc > 3)
      {
         federateType = DtToWString(argv[3]);
      }

      wcout << L"Using " << RTIname().c_str() << L" " << RTIversion().c_str() << L"\n";

      
      theAmbData.myNameReservationReturned =
         theAmbData.myNameReservationSucceeded =
         theAmbData.myReceivedInitiateFederateSave =
         theAmbData.myReceivedFederationSaved =
         theAmbData.myReceivedFederationNotSaved =
         theAmbData.myReceivedFederationSaveStatusResponse =
         theAmbData.myReceivedRequestFederationRestoreSucceeded =
         theAmbData.myReceivedRequestFederationRestoreFailed =
         theAmbData.myReceivedFederationRestoreBegun =
         theAmbData.myReceivedInitiateFederateRestore =
         theAmbData.myReceivedFederationRestored =
         theAmbData.myReceivedFederationNotRestored =
         theAmbData.myReceivedFederationRestoreStatusResponse = false;


      // RTI and Federate Ambassadors
      RTIambassadorFactory* rtiAmbFactory = new RTIambassadorFactory();
      std::auto_ptr < RTIambassador > rtiAmbAP =
         rtiAmbFactory->createRTIambassador(args);
      rtiAmb = rtiAmbAP.release();
      MyFederateAmbassador fedAmb(theAmbData);


#ifdef WIN32
      WSADATA data;
      WSAStartup(MAKEWORD(1,1), &data);
#endif
      rtiAmb->evokeCallback(0.0);

      AttributeHandleValueMap attrValues;
      ParameterHandleValueMap paramValues;

      long count=0;
      bool doConnect = true;
      bool connected = false;
      while (1)
      {
         if (doConnect)
         {
            doConnect = false;

            // Create the federation
            createFedEx(*rtiAmb, federationName, federationFile);

            // Join the federation
            joinFedEx(*rtiAmb, fedAmb, federateType, federationName);

            // Publish, subscribe and register and object
            if (!publishSubscribeAndRegisterObject(*rtiAmb))
            {
               resignAndDestroy(*rtiAmb, federationName);
               if (rtiAmb != 0)
               {
                  delete rtiAmb;
                  rtiAmb = 0;
               }
               return 0;
            }

            // Publish and subscribe to the required interaction
            if (!publishAndSubscribeInteraction(*rtiAmb))
            {
               resignAndDestroy(*rtiAmb, federationName);
               if (rtiAmb != 0)
               {
                  delete rtiAmb;
                  rtiAmb = 0;
               }
               return 0;
            }

            // Construct an attribute handle value pair set with the
            // values containing the attribute names
            attrValues.clear();

            for (DtAttrNameHandleMap::iterator iter = theAttrNameHandleMap.begin();
               iter != theAttrNameHandleMap.end();
               iter++)
            {
               // Attribute values will be just the name of the attribute.
               // Format is narrow string representation of attribute name to remain
               // compatible with 1.3 simple federate
               std::string temp = DtToString(iter->first);
               attrValues[iter->second].setData(temp.c_str(), temp.length()+1);
            }


            // Construct a parameter handle value pair set with the
            // values containing the parameter names
            paramValues.clear();

            for (DtParamNameHandleMap::iterator iter2 = theParamNameHandleMap.begin();
               iter2 != theParamNameHandleMap.end();
               iter2++)
            {
               // Parameter values will be just the name of the attribute.
               // Format is narrow string representation of parameter name to remain
               // compatible with 1.3 simple federate
               std::string temp = DtToString(iter2->first);
               paramValues[iter2->second].setData(temp.c_str(), temp.length()+1);
            }
            connected = true;
         }
         else if (connected)
         {
            std::stringstream ss;
            ss << "1516-" << count++;
            std::string tag(ss.str());
            // Tag format is narrow string representation compatible
            // with 1.3 simple federate

            // Update the object
            rtiAmb->updateAttributeValues(
               theObjectHandle,
               attrValues,
               VariableLengthData(tag.c_str(), tag.size()+1));

            // Send an interaction every few passes
            if ( count % 5 == 0 )
            {
               wcout << L"Sending interaction..." << endl;
               rtiAmb->sendInteraction(
                  theInterClassHandle,
                  paramValues,
                  VariableLengthData(tag.c_str(), tag.size()+1));
            }

            rtiAmb->evokeMultipleCallbacks(0.1, 0.5);

            if ( theAmbData.myReceivedInitiateFederateSave )
            {
               // Perform a save operation
               if ( !saveFederation(*rtiAmb, theAmbData.mySaveLabel, false) )
               {
                  // Save failed
                  break;
               }
            }

            if ( theAmbData.myReceivedFederationRestoreBegun )
            {
               // Perform a restore operation
               if ( !restoreFederation(*rtiAmb, theAmbData.myRestoreLabel, false) )
               {
                  // Restore failed
                  break;
               }
            }
         }

         int key = input.keybrdTick();
         if (key  < 0)
         {
            break;
         }
         else if ('c' == key || 'C' == key )
         {
            doConnect = !connected;
         }
         else if ('d' == key || 'D' == key )
         {
            if (connected)
            {
               try
               {
                  resignAndDestroy(*rtiAmb, federationName);
                  connected = false;
               }
               catch(rti1516::Exception& ex)
               {
                  wcout << L"RTI Exception: "
                     << ex.what().c_str() << endl;
               }
            }
         }
         else if ('s' == key || 'S' == key )
         {
            if (connected)
            {
               // Initiate a save operation
               const wstring saveLabel(L"rtiSimpleSave");
               if ( !saveFederation(*rtiAmb, saveLabel, true) )
               {
                  // Save failed
                  break;
               }
            }
         }
         else if ('r' == key || 'R' == key )
         {
            if (connected)
            {
               // Initiate a restore operation
               const wstring savedLabel(L"rtiSimpleSave");
               if ( !restoreFederation(*rtiAmb, savedLabel, true) )
               {
                  // Restore failed
                  break;
               }
            }
         }
         
#ifdef WIN32
         Sleep(2000);
#else
         sleep(2);
#endif
      }

      if (connected)
      {
         // Resign and destroy federation
         resignAndDestroy(*rtiAmb, federationName);
      }
   }
   catch (rti1516::Exception& ex)
   {
      wcout << L"RTI Exception (main loop): "
            << ex.what().c_str() << endl;
   }

   if (rtiAmb != 0)
   {
      delete rtiAmb;
      rtiAmb = 0;
   }

#ifdef WIN32
   WSACleanup();
#endif

   return 0;
}

rtiSimpleFedAmb1516.cxx

/*******************************************************************************
** Copyright (c) 2010 MaK Technologies, Inc.
** All rights reserved.
*******************************************************************************/

#pragma warning(disable: 4251)
#pragma warning(disable: 4786)
#pragma warning(disable: 4290)

#include <iostream>
#include "rtiSimpleFedAmb1516.h"
#include "rtiSimpleStringUtil.h"

using namespace std;

void printAttrValues(AttributeHandleValueMap const& attrVals)
{
   AttributeHandleValueMap::const_iterator iter;

   for (iter = attrVals.begin(); iter != attrVals.end(); iter++)
   {
      wcout << iter->first.toString().c_str() << L" "
            << DtToWString((char*)iter->second.data()).c_str() << endl;
   }
}

void printParamValues(ParameterHandleValueMap const& paramVals)
{
   ParameterHandleValueMap::const_iterator iter;

   for (iter = paramVals.begin(); iter != paramVals.end(); iter++)
   {
      wcout << iter->first.toString().c_str() << L" "
            << DtToWString((char*)iter->second.data()).c_str() << endl;
   }
}

MyFederateAmbassador::MyFederateAmbassador(DtTalkAmbData & data) :
   NullFederateAmbassador(), myData(data) {}

MyFederateAmbassador::~MyFederateAmbassador()
   throw () {}


void MyFederateAmbassador::initiateFederateSave(std::wstring const & label)
   throw (UnableToPerformSave,   FederateInternalError)
{
   wcout << L"initiateFederateSave: " << label.c_str() << endl;
   myData.myReceivedInitiateFederateSave = true;
   myData.mySaveLabel = label;
}

void MyFederateAmbassador::federationSaved() throw (FederateInternalError)
{
   wcout << L"federationSaved " << endl;
   myData.myReceivedFederationSaved = true;
}

void MyFederateAmbassador::federationNotSaved(SaveFailureReason theSaveFailureReason)
   throw (FederateInternalError)
{
   wcout << L"federationNotSaved: ";
   switch (theSaveFailureReason)
   {
   case RTI_UNABLE_TO_SAVE:
      wcout << L"RTI_UNABLE_TO_SAVE\n";
      break;
   case FEDERATE_REPORTED_FAILURE_DURING_SAVE:
      wcout << L"FEDERATE_REPORTED_FAILURE_DURING_SAVE\n";
      break;
   case FEDERATE_RESIGNED_DURING_SAVE:
      wcout << L"FEDERATE_RESIGNED_DURING_SAVE\n";
      break;
   case RTI_DETECTED_FAILURE_DURING_SAVE:
      wcout << L"RTI_DETECTED_FAILURE_DURING_SAVE\n";
      break;
   case SAVE_TIME_CANNOT_BE_HONORED:
      wcout << L"SAVE_TIME_CANNOT_BE_HONORED\n";
      break;
   default:
      wcout << L"UNKNOWN\n";
      break;
   }
   myData.mySaveFailureReason = theSaveFailureReason;
   myData.myReceivedFederationNotSaved = true;
}

void MyFederateAmbassador::federationSaveStatusResponse(FederateHandleSaveStatusPairVector const & theFederateStatusVector)
      throw (FederateInternalError)
{
   wcout << L"federationSaveStatusResponse" << endl;
   myData.myReceivedFederationSaveStatusResponse = true;
   myData.myFederateHandleSaveStatus = theFederateStatusVector;
}


void MyFederateAmbassador::requestFederationRestoreSucceeded(std::wstring const & label)
      throw (FederateInternalError)
{
   wcout << L"requestFederationRestoreSucceeded " << label.c_str() << endl;
   myData.myReceivedRequestFederationRestoreSucceeded = true;
   myData.myRestoreLabel = label;
}

void MyFederateAmbassador::requestFederationRestoreFailed(std::wstring const & label)
      throw (FederateInternalError)
{
   wcout << L"requestFederationRestoreFailed " << label.c_str() << endl;
   myData.myReceivedRequestFederationRestoreFailed = true;
   myData.myRestoreLabel = label;
}

void MyFederateAmbassador::federationRestoreBegun()
      throw (FederateInternalError)
{
   wcout << L"federationRestoreBegun" << endl;
   myData.myReceivedFederationRestoreBegun = true;
}

void MyFederateAmbassador::initiateFederateRestore(
      std::wstring const & label,
      FederateHandle handle)
      throw (SpecifiedSaveLabelDoesNotExist,
             CouldNotInitiateRestore,
             FederateInternalError)
{
   wcout << L"initiateFederateRestore " << label.c_str()
      << L" " << handle.toString().c_str() << endl;
   myData.myReceivedInitiateFederateRestore = true;
   myData.myRestoreLabel = label;
   myData.myRestoreFederateHandle = handle;
}

void MyFederateAmbassador::federationRestored()
      throw (FederateInternalError)
{
   wcout << L"federationRestored" << endl;
   myData.myReceivedFederationRestored = true;
}

void MyFederateAmbassador::federationNotRestored(RestoreFailureReason theRestoreFailureReason)
      throw (FederateInternalError)
{
   wcout << L"federationNotRestored: ";
   switch (theRestoreFailureReason)
   {
   case RTI_UNABLE_TO_RESTORE:
      wcout << L"RTI_UNABLE_TO_RESTORE\n";
      break;
   case FEDERATE_REPORTED_FAILURE_DURING_RESTORE:
      wcout << L"FEDERATE_REPORTED_FAILURE_DURING_RESTORE\n";
      break;
   case FEDERATE_RESIGNED_DURING_RESTORE:
      wcout << L"FEDERATE_RESIGNED_DURING_RESTORE\n";
      break;
   case RTI_DETECTED_FAILURE_DURING_RESTORE:
      wcout << L"RTI_DETECTED_FAILURE_DURING_RESTORE\n";
      break;
   default:
      wcout << L"Unknown reason\n";
      break;
   }
   myData.myReceivedFederationNotRestored = true;
   myData.myRestoreFailureReason = theRestoreFailureReason;
}

void MyFederateAmbassador::federationRestoreStatusResponse(
      FederateHandleRestoreStatusPairVector const& theFederateStatusVector)
      throw (FederateInternalError)
{
   wcout << L"federationRestoreStatusResponse" << endl;
   myData.myReceivedFederationRestoreStatusResponse = true;
   myData.myFederateHandleRestoreStatus = theFederateStatusVector;
}


void MyFederateAmbassador::objectInstanceNameReservationSucceeded(
   std::wstring const & theObjectInstanceName)
   throw (
      UnknownName,
      FederateInternalError)
{
   //wcout << L"objectInstanceNameReservationSucceeded: "
    //     << theObjectInstanceName.c_str() << endl;
   myData.myNameReservationReturned = 
   myData.myNameReservationSucceeded = true;
}

void MyFederateAmbassador::objectInstanceNameReservationFailed(
   std::wstring const & theObjectInstanceName)
   throw (
      UnknownName,
      FederateInternalError)
{
   wcout << L"objectInstanceNameReservationFailed: "
         << theObjectInstanceName.c_str() << endl;
   myData.myNameReservationReturned = true;
   myData.myNameReservationSucceeded = false;
}

void MyFederateAmbassador::discoverObjectInstance (
   ObjectInstanceHandle theObject,
   ObjectClassHandle theObjectClass,
   std::wstring const & theObjectInstanceName)
   throw (
      CouldNotDiscover,
      ObjectClassNotKnown,
      FederateInternalError)
{
   wcout << L"discoverObjectInstance: "
         << theObjectInstanceName.c_str() << L"("
         << theObject.toString().c_str() << L") of class "
         << myData.objectClassMap[theObjectClass].c_str() << L"( "
         << theObjectClass.toString().c_str() << L")" << endl;\
   myData.objectInstanceMap[theObject] = theObjectInstanceName;
}

void MyFederateAmbassador::reflectAttributeValues (
   ObjectInstanceHandle theObject,
   AttributeHandleValueMap const & theAttributeValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType)
   throw (
      ObjectInstanceNotKnown,
      AttributeNotRecognized,
      AttributeNotSubscribed,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"reflectAttributeValues h v u o p: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << L"#attributes: " << theAttributeValues.size() << endl;

   printAttrValues(theAttributeValues);
}

void MyFederateAmbassador::reflectAttributeValues (
   ObjectInstanceHandle theObject,
   AttributeHandleValueMap const & theAttributeValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   RegionHandleSet const & theSentRegionHandleSet)
   throw (
      ObjectInstanceNotKnown,
      AttributeNotRecognized,
      AttributeNotSubscribed,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"reflectAttributeValues h v u o p r: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << L"#regions: " << theSentRegionHandleSet.size() << L" "
         << L"#attributes: " << theAttributeValues.size() << endl;

   printAttrValues(theAttributeValues);
}

void MyFederateAmbassador::reflectAttributeValues (
   ObjectInstanceHandle theObject,
   AttributeHandleValueMap const & theAttributeValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder)
   throw (
      ObjectInstanceNotKnown,
      AttributeNotRecognized,
      AttributeNotSubscribed,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"reflectAttributeValues h v u o p t o: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString().c_str() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << L"#attributes: " << theAttributeValues.size() << endl;

   printAttrValues(theAttributeValues);
}

void MyFederateAmbassador::reflectAttributeValues (
   ObjectInstanceHandle theObject,
   AttributeHandleValueMap const & theAttributeValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   RegionHandleSet const & theSentRegionHandleSet)
   throw (
      ObjectInstanceNotKnown,
      AttributeNotRecognized,
      AttributeNotSubscribed,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"reflectAttributeValues h v u o p t o r: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString().c_str() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << L"#regions: " << theSentRegionHandleSet.size() << L" "
         << L"#attributes: " << theAttributeValues.size() << endl;

   printAttrValues(theAttributeValues);
}

void MyFederateAmbassador::reflectAttributeValues (
   ObjectInstanceHandle theObject,
   AttributeHandleValueMap const & theAttributeValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   MessageRetractionHandle theHandle)
   throw (
      ObjectInstanceNotKnown,
      AttributeNotRecognized,
      AttributeNotSubscribed,
      InvalidLogicalTime,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"reflectAttributeValues h v u o p t o m: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString().c_str() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << theHandle.toString().c_str() << L" "
         << L"#attributes: " << theAttributeValues.size() << endl;

   printAttrValues(theAttributeValues);
}

void MyFederateAmbassador::reflectAttributeValues (
   ObjectInstanceHandle theObject,
   AttributeHandleValueMap const & theAttributeValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   MessageRetractionHandle theHandle,
   RegionHandleSet const & theSentRegionHandleSet)
   throw (
      ObjectInstanceNotKnown,
      AttributeNotRecognized,
      AttributeNotSubscribed,
      InvalidLogicalTime,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"reflectAttributeValues h v u o p t o m r: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString().c_str() << L" "
         << theHandle.toString().c_str() << L" "
         << L"#regions: " << theSentRegionHandleSet.size() << L" "
         << L"#attributes: " << theAttributeValues.size() << endl;

   printAttrValues(theAttributeValues);
}


// 6.9
void MyFederateAmbassador::receiveInteraction(
   InteractionClassHandle theInteraction,
   ParameterHandleValueMap const & theParameterValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType)
   throw (InteractionClassNotRecognized,
          InteractionParameterNotRecognized,
          InteractionClassNotSubscribed,
          FederateInternalError)
{
    const char* tag = theUserSuppliedTag.size() ?
       (const char*)theUserSuppliedTag.data() : "";

   wcout << L"receiveInteraction: "
         << theInteraction.toString() << L" "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << L"#parameters: " << theParameterValues.size() << endl;

   printParamValues(theParameterValues);
}


void MyFederateAmbassador::receiveInteraction(
   InteractionClassHandle theInteraction,
   ParameterHandleValueMap const & theParameterValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   RegionHandleSet const & theSentRegionHandleSet)
   throw (InteractionClassNotRecognized,
          InteractionParameterNotRecognized,
          InteractionClassNotSubscribed,
          FederateInternalError)
{
    const char* tag = theUserSuppliedTag.size() ?
       (const char*)theUserSuppliedTag.data() : "";

   wcout << L"receiveInteraction: "
         << theInteraction.toString() << L" "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << L"#regions: " << theSentRegionHandleSet.size() << L" "
         << L"#parameters: " << theParameterValues.size() << endl;

   printParamValues(theParameterValues);
}




void MyFederateAmbassador::receiveInteraction(
   InteractionClassHandle theInteraction,
   ParameterHandleValueMap const & theParameterValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder)
   throw (InteractionClassNotRecognized,
          InteractionParameterNotRecognized,
          InteractionClassNotSubscribed,
          FederateInternalError)
{
    const char* tag = theUserSuppliedTag.size() ?
       (const char*)theUserSuppliedTag.data() : "";

   wcout << L"receiveInteraction: "
         << theInteraction.toString() << L" "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << L"#parameters: " << theParameterValues.size() << endl;

   printParamValues(theParameterValues);
}




void MyFederateAmbassador::receiveInteraction(
   InteractionClassHandle theInteraction,
   ParameterHandleValueMap const & theParameterValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   RegionHandleSet const & theSentRegionHandleSet)
   throw (InteractionClassNotRecognized,
          InteractionParameterNotRecognized,
          InteractionClassNotSubscribed,
          FederateInternalError)
{
    const char* tag = theUserSuppliedTag.size() ?
       (const char*)theUserSuppliedTag.data() : "";

   wcout << L"receiveInteraction: "
         << theInteraction.toString() << L" "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << L"#regions: " << theSentRegionHandleSet.size() << L" "
         << L"#parameters: " << theParameterValues.size() << endl;

   printParamValues(theParameterValues);
}




void MyFederateAmbassador::receiveInteraction(
   InteractionClassHandle theInteraction,
   ParameterHandleValueMap const & theParameterValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   MessageRetractionHandle theHandle)
   throw (InteractionClassNotRecognized,
          InteractionParameterNotRecognized,
          InteractionClassNotSubscribed,
          InvalidLogicalTime,
          FederateInternalError)
{
    const char* tag = theUserSuppliedTag.size() ?
       (const char*)theUserSuppliedTag.data() : "";

   wcout << L"receiveInteraction: "
         << theInteraction.toString() << L" "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << (theType == RELIABLE ? L"RELIABLE " : L"BEST_EFFORT ")
         << theTime.toString() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << theHandle.toString() << L" "
         << L"#parameters: " << theParameterValues.size() << endl;

   printParamValues(theParameterValues);
}




void MyFederateAmbassador::receiveInteraction(
   InteractionClassHandle theInteraction,
   ParameterHandleValueMap const & theParameterValues,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   TransportationType theType,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   MessageRetractionHandle theHandle,
   RegionHandleSet const & theSentRegionHandleSet)
   throw (InteractionClassNotRecognized,
          InteractionParameterNotRecognized,
          InteractionClassNotSubscribed,
          InvalidLogicalTime,
          FederateInternalError) {}


void MyFederateAmbassador::removeObjectInstance(
   ObjectInstanceHandle theObject,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder)
   throw (
      ObjectInstanceNotKnown,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"removeObjectInstance: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ") << endl;
}

void MyFederateAmbassador::removeObjectInstance(
   ObjectInstanceHandle theObject,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   LogicalTime const & theTime,
   OrderType receivedOrder)
   throw (
      ObjectInstanceNotKnown,
      FederateInternalError)
{
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"removeObjectInstance: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << theTime.toString().c_str() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ") << endl;
}

 void MyFederateAmbassador::removeObjectInstance(
   ObjectInstanceHandle theObject,
   VariableLengthData const & theUserSuppliedTag,
   OrderType sentOrder,
   LogicalTime const & theTime,
   OrderType receivedOrder,
   MessageRetractionHandle theHandle)
   throw (
      ObjectInstanceNotKnown,
      InvalidLogicalTime,
      FederateInternalError)
 {
   const char* tag = theUserSuppliedTag.size()
      ? (const char*)theUserSuppliedTag.data() : "";

   wcout << L"removeObjectInstance: "
         << myData.objectInstanceMap[theObject].c_str() << L"("
         << theObject.toString().c_str() << L") "
         << DtToWString(tag)  << L" "
         << (sentOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << theTime.toString().c_str() << L" "
         << (receivedOrder == RECEIVE ? L"RECEIVE " : L"TIMESTAMP ")
         << theHandle.toString().c_str()  << endl;
}



rtiSimpleKeyboard.cxx

/*******************************************************************************
* Adapted from "Beginning Linux Programming", from Wrox Press -- www.wrox.com
*******************************************************************************/

#include "rtiSimpleKeyboard.h"

#ifdef WIN32
#include <conio.h>
#else
#include <unistd.h>
#endif

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();
   return (key == 'q' || key == 'Q') ? -1 : key;
}


rtiSimpleFedAmb1516.h

/*******************************************************************************
** Copyright (c) 2010 MaK Technologies, Inc.
** All rights reserved.
*******************************************************************************/

#ifndef MyFederateAmbassador_H_
#define MyFederateAmbassador_H_

#pragma warning(disable: 4251)
#pragma warning(disable: 4786)
#pragma warning(disable: 4290)

#include <RTI/RTI1516.h>
#include <RTI/NullFederateAmbassador.h>
#include <string>
#include <map>

using namespace rti1516;

class DtTalkAmbData
{
public:
   bool myNameReservationReturned;
   bool myNameReservationSucceeded;
   bool myReceivedInitiateFederateSave;
   bool myReceivedFederationSaved;
   bool myReceivedFederationNotSaved;
   bool myReceivedFederationSaveStatusResponse;
   std::wstring mySaveLabel;
   SaveFailureReason mySaveFailureReason;
   FederateHandleSaveStatusPairVector myFederateHandleSaveStatus;

   bool myReceivedRequestFederationRestoreSucceeded;
   bool myReceivedRequestFederationRestoreFailed;
   bool myReceivedFederationRestoreBegun;
   bool myReceivedInitiateFederateRestore;
   bool myReceivedFederationRestored;
   bool myReceivedFederationNotRestored;
   bool myReceivedFederationRestoreStatusResponse;
   std::wstring myRestoreLabel;
   FederateHandle myRestoreFederateHandle;
   RestoreFailureReason myRestoreFailureReason;
   FederateHandleRestoreStatusPairVector myFederateHandleRestoreStatus;

   std::map<ObjectClassHandle, std::wstring> objectClassMap;
   std::map<ObjectInstanceHandle, std::wstring> objectInstanceMap;
   std::map<InteractionClassHandle, std::wstring> interactionClassMap;
};

class MyFederateAmbassador : public NullFederateAmbassador
{
public:

   MyFederateAmbassador(DtTalkAmbData & data);

   virtual ~MyFederateAmbassador() 
     throw ();

   virtual  void initiateFederateSave(
      std::wstring const & label)
      throw (UnableToPerformSave,   FederateInternalError);

   virtual  void federationSaved()
      throw (FederateInternalError);

   virtual void federationNotSaved(SaveFailureReason theSaveFailureReason)
      throw (FederateInternalError);

   virtual void federationSaveStatusResponse(
      FederateHandleSaveStatusPairVector const & theFederateStatusVector)
      throw (FederateInternalError);


    // 4.19
    virtual void requestFederationRestoreSucceeded(std::wstring const & label)
      throw (FederateInternalError);

    virtual void requestFederationRestoreFailed(std::wstring const & label)
      throw (FederateInternalError);

    // 4.20
    virtual void federationRestoreBegun()
      throw (FederateInternalError);

    // 4.21
    virtual void initiateFederateRestore(
      std::wstring const & label,
      FederateHandle handle)
      throw (SpecifiedSaveLabelDoesNotExist,
             CouldNotInitiateRestore,
             FederateInternalError);

    // 4.23
    virtual void federationRestored()
      throw (FederateInternalError);

    virtual void federationNotRestored(RestoreFailureReason theRestoreFailureReason)
      throw (FederateInternalError);

    // 4.25
    virtual void federationRestoreStatusResponse(
      FederateHandleRestoreStatusPairVector  const & 
      theFederateStatusVector)
      throw (FederateInternalError);

    // 6.3
    virtual
    void
    objectInstanceNameReservationSucceeded(std::wstring const &
                                           theObjectInstanceName)
      throw (UnknownName,
             FederateInternalError);

    virtual
    void
    objectInstanceNameReservationFailed(std::wstring const &
                                        theObjectInstanceName)
      throw (UnknownName,
             FederateInternalError);

    // 6.5
   virtual void discoverObjectInstance (
      ObjectInstanceHandle theObject,
      ObjectClassHandle theObjectClass,
      std::wstring const & theObjectInstanceName)
      throw (
         CouldNotDiscover,
         ObjectClassNotKnown,
         FederateInternalError);

    // 6.7
    virtual
    void
    reflectAttributeValues
    (ObjectInstanceHandle theObject,
     AttributeHandleValueMap const & theAttributeValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType)
      throw (ObjectInstanceNotKnown,
             AttributeNotRecognized,
             AttributeNotSubscribed,
             FederateInternalError);

    virtual
    void
    reflectAttributeValues
    (ObjectInstanceHandle theObject,
     AttributeHandleValueMap const & theAttributeValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     RegionHandleSet const & theSentRegionHandleSet)
      throw (ObjectInstanceNotKnown,
             AttributeNotRecognized,
             AttributeNotSubscribed,
             FederateInternalError);

    virtual
    void
    reflectAttributeValues
    (ObjectInstanceHandle theObject,
     AttributeHandleValueMap const & theAttributeValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder)
      throw (ObjectInstanceNotKnown,
             AttributeNotRecognized,
             AttributeNotSubscribed,
             FederateInternalError);
  
    virtual
    void
    reflectAttributeValues
    (ObjectInstanceHandle theObject,
     AttributeHandleValueMap const & theAttributeValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder,
     RegionHandleSet const & theSentRegionHandleSet)
      throw (ObjectInstanceNotKnown,
             AttributeNotRecognized,
             AttributeNotSubscribed,
             FederateInternalError);
  
    virtual
    void
    reflectAttributeValues
    (ObjectInstanceHandle theObject,
     AttributeHandleValueMap const & theAttributeValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder,
     MessageRetractionHandle theHandle)
      throw (ObjectInstanceNotKnown,
             AttributeNotRecognized,
             AttributeNotSubscribed,
             InvalidLogicalTime,
             FederateInternalError);

    virtual
    void
    reflectAttributeValues
    (ObjectInstanceHandle theObject,
     AttributeHandleValueMap const & theAttributeValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder,
     MessageRetractionHandle theHandle,
     RegionHandleSet const & theSentRegionHandleSet)
      throw (ObjectInstanceNotKnown,
             AttributeNotRecognized,
             AttributeNotSubscribed,
             InvalidLogicalTime,
             FederateInternalError);


    // 6.9
    virtual
    void
    receiveInteraction
    (InteractionClassHandle theInteraction,
     ParameterHandleValueMap const & theParameterValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType)
      throw (InteractionClassNotRecognized,
             InteractionParameterNotRecognized,
             InteractionClassNotSubscribed,
             FederateInternalError);

    virtual
    void
    receiveInteraction
    (InteractionClassHandle theInteraction,
     ParameterHandleValueMap const & theParameterValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     RegionHandleSet const & theSentRegionHandleSet)
      throw (InteractionClassNotRecognized,
             InteractionParameterNotRecognized,
             InteractionClassNotSubscribed,
             FederateInternalError);

    virtual
    void
    receiveInteraction
    (InteractionClassHandle theInteraction,
     ParameterHandleValueMap const & theParameterValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder)
      throw (InteractionClassNotRecognized,
             InteractionParameterNotRecognized,
             InteractionClassNotSubscribed,
             FederateInternalError);

    virtual
    void
    receiveInteraction
    (InteractionClassHandle theInteraction,
     ParameterHandleValueMap const & theParameterValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder,
     RegionHandleSet const & theSentRegionHandleSet)
      throw (InteractionClassNotRecognized,
             InteractionParameterNotRecognized,
             InteractionClassNotSubscribed,
             FederateInternalError);

    virtual
    void
    receiveInteraction
    (InteractionClassHandle theInteraction,
     ParameterHandleValueMap const & theParameterValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder,
     MessageRetractionHandle theHandle)
      throw (InteractionClassNotRecognized,
             InteractionParameterNotRecognized,
             InteractionClassNotSubscribed,
             InvalidLogicalTime,
             FederateInternalError);

    virtual
    void
    receiveInteraction
    (InteractionClassHandle theInteraction,
     ParameterHandleValueMap const & theParameterValues,
     VariableLengthData const & theUserSuppliedTag,
     OrderType sentOrder,
     TransportationType theType,
     LogicalTime const & theTime,
     OrderType receivedOrder,
     MessageRetractionHandle theHandle,
     RegionHandleSet const & theSentRegionHandleSet)
      throw (InteractionClassNotRecognized,
             InteractionParameterNotRecognized,
             InteractionClassNotSubscribed,
             InvalidLogicalTime,
             FederateInternalError);


    // 6.11
    virtual
    void
    removeObjectInstance(ObjectInstanceHandle theObject,
                         VariableLengthData const & theUserSuppliedTag,
                         OrderType sentOrder)
      throw (ObjectInstanceNotKnown,
             FederateInternalError);

    virtual
    void
    removeObjectInstance(ObjectInstanceHandle theObject,
                         VariableLengthData const & theUserSuppliedTag,
                         OrderType sentOrder,
                         LogicalTime const & theTime,
                         OrderType receivedOrder)
      throw (ObjectInstanceNotKnown,
             FederateInternalError);

    virtual
    void
    removeObjectInstance(ObjectInstanceHandle theObject,
                         VariableLengthData const & theUserSuppliedTag,
                         OrderType sentOrder,
                         LogicalTime const & theTime,
                         OrderType receivedOrder,
                         MessageRetractionHandle theHandle)
      throw (ObjectInstanceNotKnown,
             InvalidLogicalTime,
             FederateInternalError);

public:
   DtTalkAmbData & myData;
};

#endif

rtiSimpleKeyboard.h

/*******************************************************************************
* Adapted from "Beginning Linux Programming", from Wrox Press -- www.wrox.com
*******************************************************************************/

// 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

rtiSimpleStringUtil.h

/*******************************************************************************
** Copyright (c) 2010 MaK Technologies, Inc.
** All rights reserved.
*******************************************************************************/

#ifndef stringUtil_H_
#define stringUtil_H_

#include <string>
#include <sstream>

// Convert narrow C string to wide string
inline std::wstring DtToWString(const char * in_val)
{
   std::wstring temp;
   while (*in_val != '\0')
   temp += *in_val++;
   return temp;
}

// Convert narrow string to wide string
inline std::string DtToString(const std::wstring &in_val)
{
   std::string temp;
   std::wstring::const_iterator b = in_val.begin();
   const std::wstring::const_iterator e = in_val.end();
   while (b != e)
   {
      temp += static_cast<char>(*b);
      ++b;
   }
   return temp;
}

#endif


Document ID: Generated on Thu Jun 14 14:15:04 EDT 2012 from SVN revision 116116
Copyright © 2005-2012 VT MÄK Inc. All Rights Reserved (www.mak.com)