コード例 #1
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::sendPlanesActives(int cfd){

  PlanesActives* planes = new PlanesActives;
  planes->blue = true;
  planes->red = true;
  planes->green = true;
  planes->yellow = true;

  mutex theMutex;
  theMutex.lock();
  for( map<int, Player*>::iterator it = this->players.begin(); it != this->players.end();  ++it ) {
    // if game is running and player is inactive, skip 
    if( this->running && !( it->second->isActive() ) ) continue;
    // if already a player with that color
    if( it->second->getColor() == "azul" ) {
      planes->blue = false;
    } else if( it->second->getColor() == "rojo" ) {
      planes->red = false;
    } else if( it->second->getColor() == "verde" ) {
      planes->green = false;
    } else if( it->second->getColor() == "amarillo" ) {
      planes->yellow = false;
    }
  }
  theMutex.unlock();
  Transmitter* tmt = new Transmitter( cfd, this->logger );
  if( !( tmt->sendData( planes ) ) ) {
    DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::addPlayer" );
    this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::addPlayer" );
  }

  delete planes;
  delete tmt;
}
コード例 #2
0
ファイル: curl.cpp プロジェクト: rushad/filetransfer
  size_t CurlTarget::ReadFunc(void* buffer, size_t size, size_t nmemb, void* data)
  {
    Transmitter* tr = static_cast<Transmitter*>(data);
    size_t l = tr->Transmit(buffer, size, nmemb);

    if (tr->Cancelled())
      return CURL_READFUNC_ABORT;

    return l;
  }
コード例 #3
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::queryCurrentStageOffset() {
  if( this->stageData != NULL ) {  
    delete this->stageData;
    this->stageData = NULL;
  }

  for( map<int, Player*>::iterator it = this->players.begin();
      it != this->players.end(); ++it ) {
    if( it->second->isActive() ) {
      Transmitter* tmt = new Transmitter( it->first, this->logger );
      tmt->sendDataID( "SQ" );
      delete tmt;
      break;
    }
  }
}
コード例 #4
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::createPlayers() {
  map<int, Player*>::iterator it2 = this->players.begin();

  for (int i = 0; i < this->players.size(); i++) {
    // if player not active
    if( !( it2->second->isActive() ) ) {
      // send stage config
      this->sendConf(it2->first);

      // if game already started
      if( this->running ) {
	// get stage offset
	this->queryCurrentStageOffset();

	// send stage offset to player
	this->sendCurrentStageOffset( it2->first );
      }
    }
    // send other players data
    for (map<int, Player*>::iterator it = this->players.begin();
	it != this->players.end(); ++it) {
      Transmitter* tmt = new Transmitter(it2->first, this->logger);

      PlayerData* player = new PlayerData;
      strcpy(player->name, it->second->getName().c_str());
      strcpy(player->color, it->second->getColor().c_str());
      player->x = it->second->getX();
      player->y = it->second->getY();

      while (!tmt->sendData(player, "PR"));

      delete player;
      delete tmt;
    }
    // activate player
    it2->second->activate();
    it2++;
  }
}
コード例 #5
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::sendConf(int cfd){
  this->config = GameParser::parse("gameconf.xml");
  Transmitter* tmt = new Transmitter( cfd, this->logger );

  AvionConf* avion = this->config->avion;
  if( !( tmt->sendData( avion ) ) ) {
    DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send avion" );
    this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send avion" );
  }

  EscenarioConf* escenario = this->config->escenario;
  if( !( tmt->sendData( escenario ) ) ) {
    DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send escenario" );
    this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send escenario" );
  }

  vector<ElementoConf*> elementos = this->config->elementos;
  for (int var = 0; var < elementos.size(); ++var) {
    ElementoConf* elemento = elementos[var];
    if( !( tmt->sendData( elemento ) ) ) {
      DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send elementos" );
      this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send elementos" );
    }
  }

  vector<SpriteConf* > sprites = this->config->sprites;
  for (int var = 0; var < sprites.size(); ++var) {
    SpriteConf* sprite = sprites[var];
    if( !( tmt->sendData( sprite ) ) ) {
      DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send Sprites" );
      this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send Sprites" );
    }
  }

  if( !( tmt->sendEndDataConf(this->clientCount)) ) {
    DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::sendConf" );
    this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::sendConf" );
  }
  cout<<"Envio toda la Configuracion"<<endl;
  delete tmt;
}
コード例 #6
0
//------------------------------------------------------------------------------
bool USNTwoWayRange::Evaluate(bool withEvents)
{
   bool retval = false;

   if (!initialized)
      InitializeMeasurement();

   #ifdef DEBUG_RANGE_CALC
      MessageInterface::ShowMessage("Entered USNTwoWayRange::Evaluate()\n");
      MessageInterface::ShowMessage("  ParticipantCount: %d\n",
            participants.size());
   #endif

   if (withEvents == false)
   {
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("USN 2-Way Range Calculation without "
               "events\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES
         DumpParticipantStates("++++++++++++++++++++++++++++++++++++++++++++\n"
               "Evaluating USN 2-Way Range without events");
      #endif

      CalculateRangeVectorInertial();
      Rvector3 outState;

      // Set feasibility off of topocentric horizon, set by the Z value in topo
      // coords
      std::string updateAll = "All";
      UpdateRotationMatrix(currentMeasurement.epoch, updateAll);
      outState = R_o_j2k * rangeVecInertial;
      currentMeasurement.feasibilityValue = outState[2];

      #ifdef CHECK_PARTICIPANT_LOCATIONS
         MessageInterface::ShowMessage("Evaluating without events\n");
         MessageInterface::ShowMessage("Calculating USN 2-Way Range at epoch "
               "%.12lf\n", currentMeasurement.epoch);
         MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         Rvector3 bfLoc = R_o_j2k * p1Loc;
         MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s",
               participants[0]->GetName().c_str(),
               bfLoc.ToString().c_str());
         bfLoc = R_o_j2k * p2Loc;
         MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s\n",
               participants[1]->GetName().c_str(),
               bfLoc.ToString().c_str());
      #endif

      if (currentMeasurement.feasibilityValue > 0.0)
      {
         currentMeasurement.isFeasible = true;
         currentMeasurement.value[0] = rangeVecInertial.GetMagnitude();
         currentMeasurement.eventCount = 2;

         retval = true;
      }
      else
      {
         currentMeasurement.isFeasible = false;
         currentMeasurement.value[0] = 0.0;
         currentMeasurement.eventCount = 0;
      }

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("Calculating Range at epoch %.12lf\n",
               currentMeasurement.epoch);
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Range Vector:  %s\n",
               rangeVecInertial.ToString().c_str());
         MessageInterface::ShowMessage("   R(Groundstation) dot RangeVec =  %lf\n",
               currentMeasurement.feasibilityValue);
         MessageInterface::ShowMessage("   Feasibility:  %s\n",
               (currentMeasurement.isFeasible ? "true" : "false"));
         MessageInterface::ShowMessage("   Range is %.12lf\n",
               currentMeasurement.value[0]);
         MessageInterface::ShowMessage("   EventCount is %d\n",
               currentMeasurement.eventCount);
      #endif

      #ifdef SHOW_RANGE_CALC
         MessageInterface::ShowMessage("Range at epoch %.12lf is ",
               currentMeasurement.epoch);
         if (currentMeasurement.isFeasible)
            MessageInterface::ShowMessage("feasible, value = %.12lf\n",
               currentMeasurement.value[0]);
         else
            MessageInterface::ShowMessage("not feasible\n");
      #endif
   }
   else
   {
      // Calculate the corrected range measurement
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("USN 2-Way Range Calculation:\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES_WITH_EVENTS
         DumpParticipantStates("********************************************\n"
               "Evaluating USN 2-Way Range with located events");
      #endif

      // 1. Get the range from the down link
      Rvector3 r1, r2;
      r1 = downlinkLeg.GetPosition(participants[0]);
      r2 = downlinkLeg.GetPosition(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("r1 = (%f,  %f,  %f)\n", r1.Get(0), r1.Get(1), r1.Get(2));
         MessageInterface::ShowMessage("r2 = (%f,  %f,  %f)\n", r2.Get(0), r2.Get(1), r2.Get(2));
      #endif
      Rvector3 downlinkVector = r2 - r1;		// rVector = r2 - r1;
      downlinkRange = downlinkVector.GetMagnitude();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Downlink Range = r2-r1:  %.12lf km\n",
               downlinkRange);
      #endif

	   // 2. Calculate down link range rate:
      Rvector3 p1V = downlinkLeg.GetVelocity(participants[0]);
      Rvector3 p2V = downlinkLeg.GetVelocity(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("p1V = (%f,  %f,  %f)\n", p1V.Get(0), p1V.Get(1), p1V.Get(2));
         MessageInterface::ShowMessage("p2V = (%f,  %f,  %f)\n", p2V.Get(0), p2V.Get(1), p2V.Get(2));
      #endif
      // @todo Relative origin velocities need to be subtracted when the origins
      // differ; check and fix that part using r12_j2k_vel here.  It's not yet
      // incorporated because we need to handle the different epochs for the
      // bodies, and we ought to do this part in barycentric coordinates
      Rvector downRRateVec = p2V - p1V /* - r12_j2k_vel*/;
      Rvector3 rangeUnit = downlinkVector.GetUnitVector();
      downlinkRangeRate = downRRateVec * rangeUnit;
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Downlink Range Rate:  %.12lf km/s\n",
               downlinkRangeRate);
      #endif

      // 3. Get the transponder delay
      targetDelay = GetDelay(1,0);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage(
               "    USN Transponder delay for %s = %.12lf s\n",
               participants[1]->GetName().c_str(), targetDelay);
      #endif

      // 4. Get the range from the uplink
      Rvector3 r3, r4;
      r3 = uplinkLeg.GetPosition(participants[0]);
      r4 = uplinkLeg.GetPosition(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("r3 = (%f,  %f,  %f)\n", r3.Get(0), r3.Get(1), r3.Get(2));
         MessageInterface::ShowMessage("r4 = (%f,  %f,  %f)\n", r4.Get(0), r4.Get(1), r4.Get(2));
      #endif
      Rvector3 uplinkVector = r4 - r3;
      uplinkRange = uplinkVector.GetMagnitude();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Uplink Range = r4-r3:  %.12lf km\n",
               uplinkRange);
      #endif

	   // 5. Calculate up link range rate
      Rvector3 p3V = uplinkLeg.GetVelocity(participants[0]);
      Rvector3 p4V = uplinkLeg.GetVelocity(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("p3V = (%f,  %f,  %f)\n", p3V.Get(0), p3V.Get(1), p3V.Get(2));
         MessageInterface::ShowMessage("p4V = (%f,  %f,  %f)\n", p4V.Get(0), p4V.Get(1), p4V.Get(2));
      #endif
      // @todo Relative origin velocities need to be subtracted when the origins
      // differ; check and fix that part using r12_j2k_vel here.  It's not yet
      // incorporated because we need to handle the different epochs for the
      // bodies, and we ought to do this part in barycentric coordinates
      Rvector upRRateVec = p4V - p3V /* - r12_j2k_vel*/ ;
      rangeUnit = uplinkVector.GetUnitVector();
      uplinkRangeRate = upRRateVec * rangeUnit;
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Uplink Range Rate:  %.12lf km/s\n",
               uplinkRangeRate);
      #endif

      // 5.1. Target range rate: Do we need this as well?
      targetRangeRate = (downlinkRangeRate + uplinkRangeRate) / 2.0;
	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Target Range Rate:  %.12lf km/s\n",
                targetRangeRate);
		#endif
      

	   // 6. Get sensors used in USN 2-ways range
	   ObjectArray objList1;
	   ObjectArray objList2;
	   ObjectArray objList3;
	   //			objList1 := all transmitters in participantHardware list
	   //			objList2 := all receivers in participantHardware list
	   //			objList3 := all transponders in participantHardware list
	   if (participantHardware.empty()||
	   		((!participantHardware.empty())&&
	   		  participantHardware[0].empty()&&
	   		  participantHardware[1].empty()
	   		)
	   	)
	   {
	   	// DO NOT LEAVE THIS TYPE OF MESSAGE IN THE CODE WITHOUT #ifdef WRAPPERS!!!
         //MessageInterface::ShowMessage("    Ideal measurement (no hardware delay and no media correction involve):\n");
		   Real realRange = (uplinkRange + downlinkRange)/2;
		   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
				MessageInterface::ShowMessage("   Range = %.12lf km\n", realRange);
			#endif

	   	// Set value for currentMeasurement
		   currentMeasurement.value[0] = realRange;
	      currentMeasurement.isFeasible = true;

	      return true;
	   }

	   for(std::vector<Hardware*>::iterator hw = this->participantHardware[0].begin();
	   		hw != this->participantHardware[0].end(); ++hw)
	   {
	   	if ((*hw) != NULL)
	   	{
	   		if ((*hw)->GetTypeName() == "Transmitter")
	   			objList1.push_back(*hw);
	   		if ((*hw)->GetTypeName() == "Receiver")
	   			objList2.push_back(*hw);
	   	}
	   	else
	   		MessageInterface::ShowMessage(" sensor = NULL\n");
	   }

	   for(std::vector<Hardware*>::iterator hw = this->participantHardware[1].begin();
	   		hw != this->participantHardware[1].end(); ++hw)
	   {
	   	if ((*hw) != NULL)
	   	{
	   		if ((*hw)->GetTypeName() == "Transponder")
	   			objList3.push_back(*hw);
	   	}
	   	else
	   		MessageInterface::ShowMessage(" sensor = NULL\n");
	   }

	   if (objList1.size() != 1)
	   {
	   	MessageInterface::ShowMessage("The first participant does not have only 1 transmitter to send signal.\n");
	      throw new MeasurementException("The first participant does not have only 1 transmitter to send signal.\n");
	   }
	   if (objList2.size() != 1)
	   {
	   	MessageInterface::ShowMessage("The first participant does not have only 1 receiver to receive signal.\n");
	      throw new MeasurementException("The first participant does not have only 1 receiver to receive signal.\n");
	   }
	   if (objList3.size() != 1)
	   {
	   	MessageInterface::ShowMessage("The second participant does not have only 1 transponder to transpond signal.\n");
  			throw new MeasurementException("The second participant does not have only 1 transponder to transpond signal.\n");
	   }

	   Transmitter* 	gsTransmitter 	= (Transmitter*)objList1[0];
	   Receiver* 		gsReceiver 		= (Receiver*)objList2[0];
	   Transponder* 	scTransponder 	= (Transponder*)objList3[0];
	   if (gsTransmitter == NULL)
	   {
	   	MessageInterface::ShowMessage("Transmitter is NULL object.\n");
	   	throw new GmatBaseException("Transmitter is NULL object.\n");
	   }
	   if (gsReceiver == NULL)
	   {
	   	MessageInterface::ShowMessage("Receiver is NULL object.\n");
	   	throw new GmatBaseException("Receiver is NULL object.\n");
	   }
	   if (scTransponder == NULL)
	   {
	   	MessageInterface::ShowMessage("Transponder is NULL object.\n");
	   	throw new GmatBaseException("Transponder is NULL object.\n");
	   }

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   List of sensors: %s, %s, %s\n",
					gsTransmitter->GetName().c_str(), gsReceiver->GetName().c_str(),
					scTransponder->GetName().c_str());
		#endif


	   // 7. Get frequency from transmitter of ground station (participants[0])
	   Signal* uplinkSignal = gsTransmitter->GetSignal();
	   Real uplinkFreq = uplinkSignal->GetValue();

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   UpLink signal frequency = %.12lf MHz\n", uplinkFreq);
		#endif

	   // 8. Calculate media correction for uplink leg:
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("      Media correction for uplink leg\n");
      #endif
      Real roundTripTime = ((uplinkRange + downlinkRange)*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)/GmatTimeConstants::SECS_PER_DAY;
      // DO NOT LEAVE THIS TYPE OF MESSAGE IN THE CODE WITHOUT #ifdef WRAPPERS!!!
      //MessageInterface::ShowMessage("Round trip time = %.12lf\n", roundTripTime);
      RealArray uplinkCorrection = CalculateMediaCorrection(uplinkFreq, r1, r2, currentMeasurement.epoch - roundTripTime);
      Real uplinkRangeCorrection = uplinkCorrection[0]/GmatMathConstants::KM_TO_M;
      Real uplinkRealRange = uplinkRange + uplinkRangeCorrection;
		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("      Uplink range correction = %.12lf km\n",uplinkRangeCorrection);
			MessageInterface::ShowMessage("      Uplink real range = %.12lf km\n",uplinkRealRange);
		#endif

		// 9. Doppler shift the frequency from the transmitter using uplinkRangeRate:
	   Real uplinkDSFreq = (1 - uplinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*uplinkFreq;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Uplink Doppler shift frequency = %.12lf MHz\n", uplinkDSFreq);
		#endif

	   // 10.Set frequency for the input signal of transponder
	   Signal* inputSignal = scTransponder->GetSignal(0);
	   inputSignal->SetValue(uplinkDSFreq);
	   scTransponder->SetSignal(inputSignal, 0);

	   // 11. Check the transponder feasibility to receive the input signal:
	   if (scTransponder->IsFeasible(0) == false)
	   {
	   	 currentMeasurement.isFeasible = false;
	   	 currentMeasurement.value[0] = 0;
	   	 MessageInterface::ShowMessage("The transponder is unfeasible to receive uplink signal.\n");
	   	 throw new GmatBaseException("The transponder is unfeasible to receive uplink signal.\n");
	   }

	   // 12. Get frequency of transponder output signal
	   Signal* outputSignal = scTransponder->GetSignal(1);
	   Real downlinkFreq = outputSignal->GetValue();

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Downlink frequency = %.12lf Mhz\n", downlinkFreq);
		#endif

	   // 13. Doppler shift the transponder output frequency by the downlinkRangeRate:
	   Real downlinkDSFreq = (1 - downlinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*downlinkFreq;

	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Downlink Doppler shift frequency = %.12lf MHz\n", downlinkDSFreq);
		#endif

	   // 14. Set frequency on receiver
	   Signal* downlinkSignal = gsReceiver->GetSignal();
	   downlinkSignal->SetValue(downlinkDSFreq);

	   // 15. Check the receiver feasibility to receive the downlink signal
	   if (gsReceiver->IsFeasible() == false)
	   {
	   	 currentMeasurement.isFeasible = false;
	   	 currentMeasurement.value[0] = 0;
	   	 throw new MeasurementException("The receiver is unfeasible to receive downlink signal.\n");
	   }

	   // 16. Calculate media correction for downlink leg:
	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	      MessageInterface::ShowMessage("      Media correction for downlink leg\n");
	   #endif
	   RealArray downlinkCorrection = CalculateMediaCorrection(downlinkDSFreq, r3, r4, currentMeasurement.epoch);
	   Real downlinkRangeCorrection = downlinkCorrection[0]/GmatMathConstants::KM_TO_M;
	   Real downlinkRealRange = downlinkRange + downlinkRangeCorrection;
		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("      Downlink range correction = %.12lf km\n",downlinkRangeCorrection);
			MessageInterface::ShowMessage("      Downlink real range = %.12lf km\n",downlinkRealRange);
		#endif


	   // 17. Calculate uplink time and down link time: (Is it needed???)
	   uplinkTime   = uplinkRealRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
	   downlinkTime = downlinkRealRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("    Uplink time = %.12lf s\n",uplinkTime);
			MessageInterface::ShowMessage("    Downlink time = %.12lf s\n",downlinkTime);
		#endif

	   // 18. Calculate real range
	   Real realRange = uplinkRealRange + downlinkRealRange +
	   		targetDelay*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M;
	   
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Calculated real range = %.12lf km\n", realRange/2);
      #endif

	   // 19. Set value for currentMeasurement
	   currentMeasurement.value[0] = realRange / 2.0;
      currentMeasurement.isFeasible = true;


      #ifdef PRELIMINARY_DERIVATIVE_CHECK
         MessageInterface::ShowMessage("Participants:\n ");
         for (UnsignedInt i = 0; i < participants.size(); ++i)
            MessageInterface::ShowMessage("   %d: %s of type %s\n", i,
                  participants[i]->GetName().c_str(),
                  participants[i]->GetTypeName().c_str());

         Integer id = participants[1]->GetType() * 250 +
               participants[1]->GetParameterID("CartesianX");
         CalculateMeasurementDerivatives(participants[1], id);
      #endif

      retval = true;
   }

   return retval;
}
コード例 #7
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::sendData( int cfd, Evento* data ) {
  Transmitter* tmt = new Transmitter( cfd, this->logger );
  tmt->sendData( data );
}
コード例 #8
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::receiveClientData( int cfd, struct sockaddr_storage client_addr ) {
  char clientIP[ INET_ADDRSTRLEN ]; // connected client IP
  Evento* msgToRecv = new Evento;
  mutex theMutex;

  // get connected host IP in presentation format
  inet_ntop( client_addr.ss_family,
      this->getInAddr( (struct sockaddr*) (&client_addr) ), clientIP,
      sizeof clientIP);

  if( this->allowConnections ) {
    //players2.push_back(cfd);
    cout << endl << notice( "Se inicio una conexion con el host: " ) << clientIP
      << endl;
    this->logger->info( "Se inicio una conexion con el host: " + string( clientIP ) );

    if( send( cfd, "Aceptado", 8, 0 ) == -1 ) {
      this->logger->error( "Error al enviar que se acepto la conexion" );
    }

    usleep(10);
    this->sendPlanesActives( cfd);

    timeval timeout;
    timeout.tv_sec = this->MAX_UNREACHABLE_TIME;
    timeout.tv_usec = 0;
    bool receiving = true;
    int bytesReceived;
    char id[3];
    // Create transmitter for this client
    Transmitter* tmt = new Transmitter( cfd, this->logger );

    while( receiving ) {
      // seteo el timeout de recepcion de mensajes
      if( setsockopt( cfd, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof( timeout ) ) < 0 ) {
	cout << "Error sockopt" << endl;
	exit( 1 );
      }

      // Get id of next data to receive
      bytesReceived = tmt->receiveData( id, sizeof( id ));

      if( bytesReceived > 0 ) {
	string dataID( id );
	// Receive data type based on fetched dataID 
	if( dataID == "PD" ) {
	  PlayerData* data = new PlayerData;

	  if( ( bytesReceived = tmt->receiveData( data )) > 0 ) {
	    // Process received data
	    cout << "Nombre del jugador: " << string( data->name ) << endl;
	    cout << "Color del jugador: " << string( data->color ) << endl;
	    this->addPlayer( data, cfd );
	  }

	  delete data;
	} else if( dataID == "PS" ) {
	  PlayerStatus* data = new PlayerStatus;

	  if( ( bytesReceived = tmt->receiveData( data )) > 0 ) {
	    // Process received data
	    cout << "Player status: " << data->status << endl;
	    this->updatePlayerStatus( data, cfd );
	  }

	  delete data;
	} else if (dataID == "EV") {
	  Evento* e = new Evento();

	  if (( bytesReceived = tmt->receiveData(e)) > 0 ) {
	    cout << "Evento: " << e->value << endl;

	    theMutex.lock();
	    cout << endl << "FD cliente: " << notice(to_string(cfd)) << endl;

	    map<int, Evento*>* clientMsgFD = new map<int, Evento*>();
	    clientMsgFD->insert(pair<int, Evento*>(cfd, e));
	    this->eventQueue->push(clientMsgFD);
	    theMutex.unlock();
	  }

	} else if (dataID == "DP") {
	  PlayerData* data = new PlayerData;

	  if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
	    for (map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it) {
	      if ( data->name == (it->second)->getName() ){
		Player* p = it->second;
		p->setX(data->x);
		p->setY(data->y);
		//cout<< "Jugador: " << p->getName() << endl<< "Color: " << p->getColor() << endl<<"Posiciones :" << p->getX() << "    "<< p->getY()<<endl;
		break;
	      }
	    }
	  }

	  delete data;
	} else if(dataID == "CO" ){
	  cout<<"Reset cliente "<<cfd<<endl;
	  this->sendConf(cfd);
	} else if( dataID == "SD" ) {
	  StageData* data = new StageData;

	  if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
	    // Process received data
	    cout << "Current stage offset: " << data->offset << endl;
	    this->stageData = data;
	  }
	}

      }

      // Check peer disconnection or timeout
      if ( bytesReceived <= 0 ) {
	receiving = false;
	this->avisarDesconexionDeAvion(cfd);
	this->closeClient( cfd );
	if( bytesReceived == 0 ) {
	  cout << endl << warning( "El cliente " ) << clientIP
	    << warning( " se desconecto" ) << endl;
	  this->logger->warn( "El Cliente " + string( clientIP ) + " se desconecto" );
	} else {
	  DEBUG_WARN( CONNECTION_TIMEOUT );
	  this->logger->warn( CONNECTION_TIMEOUT );
	}
      }
    }

    delete tmt;
  } else {
    cout << endl << warning( "El cliente " ) << clientIP << warning( " se rechazo" ) << endl;
    this->logger->warn( "El cliente " + string(clientIP) + " se rechazo" );
    usleep( 1000000 );
    this->closeClient( cfd );
  }
}
コード例 #9
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::sendCurrentStageOffset( int clientFD ) {
  while( this->stageData == NULL );
  Transmitter* tmt = new Transmitter( clientFD, this->logger );
  tmt->sendData( this->stageData, "SD" );
  delete tmt;
}
コード例 #10
0
ファイル: Server.cpp プロジェクト: agufiuba/1942MP
void Server::addPlayer(PlayerData* data, int cfd) {
	string validName = "Y", validColor = "Y";
	mutex theMutex;
	string selectedName(data->name);
	string selectedColor(data->color);
	bool createPlayer = true;
	bool encontrePlayer = false;
	theMutex.lock();

	for (map<int, Player*>::iterator it = this->players.begin() ; it != this->players.end() ; ++it) {
		// if already a player with that name
		if (selectedName == it->second->getName()) {
			createPlayer = false;
			validName = "N";
			cout<<"Encuentro Player"<<endl;
			// if running game and player with such name is not active
			if ( this->running && !(it->second->isActive())) {
				// resume player game
				cout<<"Resume Game"<<endl;
				selectedColor = it->second->getColor();
				posicionInicialX = it->second->getX();
				posicionInicialY = it->second->getY();
				delete it->second;
				this->players.erase(it);
				createPlayer = true;
				validName = "R";
				validColor = "R";
				break;
			}
		}

		// if already a player with that color
		if (selectedColor == it->second->getColor()) {
			createPlayer = false;
			validColor = "N";
		}
	}
	theMutex.unlock();

	if (createPlayer && (this->players.size() < this->maxClientCount) ) {
		// Add new player
		cout<<"Creo Jugador"<<endl;
		Player* p = new Player(selectedName, selectedColor, posicionInicialX, posicionInicialY);
		theMutex.lock();
		this->players[cfd] = p;
		posicionInicialX += 100;
		theMutex.unlock();
	} else {
		cout<<"No creo jugador"<<endl;
		createPlayer = false;
			validName = "N";
			validColor = "N";
	}
	// Create response
	PlayerData* response = new PlayerData;
	// Fill response struct
	strcpy(response->name, validName.c_str());
	strcpy(response->color, validColor.c_str());

	cout<<"name :"<<validName<<"  .Color: "<<validColor<<endl;
	Transmitter* tmt = new Transmitter(cfd, this->logger);
	if (!(tmt->sendData(response))) {
		DEBUG_WARN("No se pude enviar respuesta a cliente. JOB: Server::addPlayer");
		this->logger->error("No se pude enviar respuesta a cliente. JOB: Server::addPlayer");
	}
	delete response;
	delete tmt;

	theMutex.lock();
	if (createPlayer && this->players.size() == this->maxClientCount) {
		cout << "send players" << endl;
		this->createPlayers();
		if( !( this->running ) ) this->running = true;
	}
	theMutex.unlock();
}
コード例 #11
0
ファイル: main.cpp プロジェクト: 0chiehchen/c45b
int main(int argc, char **argv)
{
  QString role;
  QString serPort;
  QString udpPort;
  QString remoteHost;
  QString bufferSize;
  QCoreApplication a(argc, argv);

  std::cout << "Serial port transmitter/receiver example, Copyright (c) 2010 Inbiza Systems Inc." << std::endl;
  std::cout << "Created by Inbiza Labs <*****@*****.**>" << std::endl;
  std::cout << "==========" << std::endl;
  std::cout << "Connect two networked computers with null-modem cable, run tranceiver with \"--role=transmit\" on one, and with \"--role=receive\" on ther other." << std::endl;
  std::cout << "==========" << std::endl;
  std::cout << std::endl;

  if ( !processArgs(a.arguments(), role, serPort, udpPort, remoteHost, bufferSize) )
    return 0;

  qDebug() << "Mode:" << role << ", Serial Port:" << serPort << ", Port Settings:" << "9600,8,n,1" <<
              ", Listening at port: " << udpPort << ", Testing peer at: " << remoteHost << ", Buffer size: " << (bufferSize == "*" ? "equal to data set size" : bufferSize);

  TNX::QSerialPort serialPort(serPort, "9600,8,n,1");

  TNX::CommTimeouts commTimeouts;

  commTimeouts.PosixVMIN = 1;
  commTimeouts.PosixVTIME = 0;
  commTimeouts.Win32ReadIntervalTimeout = 75;
  commTimeouts.Win32ReadTotalTimeoutConstant = 250;
  commTimeouts.Win32ReadTotalTimeoutMultiplier = 25;
  commTimeouts.Win32WriteTotalTimeoutConstant = 250;
  commTimeouts.Win32WriteTotalTimeoutMultiplier = 75;

  if ( !serialPort.setCommTimeouts(commTimeouts) )
    qWarning("Cannot set communications timeout values at port %s.", qPrintable(serPort));

  Receiver *receiver = NULL;
  Transmitter *transmitter = NULL;
  if ( 0 == role.compare("transmit", Qt::CaseInsensitive) ) {
    transmitter = new Transmitter(serialPort, remoteHost, udpPort.toInt(), &a);
    if ( !transmitter->start() ) {
      std::cout << "Cannot start transmitter. Quitting." << std::endl;
      return 0;
    }

  }
  else if ( 0 == role.compare("receive", Qt::CaseInsensitive) ) {
    receiver = new Receiver(serialPort,  remoteHost, udpPort.toInt(), QString((bufferSize == "*" ? "0" : bufferSize)).toInt(), &a);
    if ( !receiver->start() ) {
      std::cout << "Cannot start receiver. Quitting." << std::endl;
      return 0;
    }
  }
  else {
    std::cout << "Wrong role defined. Quitting." << std::endl;
    return 0;
  }

  return a.exec();
}
コード例 #12
0
int main(int argc, char* argv[])
{

  bool createFromFile = false;
  std::string create_filename = "nothing";
  bool backup = false;
  std::string backup_filename = "no_backup";
  for(int i=0;i<argc;i++)
  {
    if(strcmp("-B",argv[i]) == 0 || strcmp("-b",argv[i]) == 0)
    {
      std::cout << "make continuous backups" << std::endl;
      if(i+1 < argc)
      {
        backup_filename = std::string(argv[i+1]);
        backup = true;
      }
    }

    if(strcmp("-F",argv[i]) == 0 || strcmp("-f",argv[i]) == 0)
    {
      std::cout << "Contruct from saved data" << std::endl;
      if(i+1 < argc)
      {
        create_filename = std::string(argv[i+1]);
        createFromFile = true;
      }
    }
  }

  std::cout << "------------------------------------"<< std::endl;
  std::cout << "---------------START----------------"<< std::endl;
  std::cout << "------------------------------------"<< std::endl;

  std::cout << "Main: program started" << std::endl;

  // (1) Create a  mission and a transmitter
  Mission* mission;

  if(!createFromFile)
  {
    std::vector<std::string> missionPlan;
    for(std::string line; std::getline(std::cin,line);)
    {
      //std::cout << "READING: " << line << std::endl;
      if(line[0] != '#')
        missionPlan.push_back(line);
    }
    //std::cout << missionPlan.size() << std::endl;
    mission = new Mission(missionPlan);
  }
  else{
    mission = new Mission(create_filename);
  }

  //return 0;


  //Mission* mission = new Mission(0);

  std::cout << "\n---------starting mission-----------\n"<< std::endl;

  Transmitter* transmitter = new Transmitter(2);
  transmitter->start();

  // (2) Create the navigator, and pass the transmitter to
  double delta = 15;
  double tol = 2;//delta / 3.0;

  int delay_data = 50000;
  int delay_scanner = 500000;

  Navigator* navigator = new Navigator(transmitter,delay_data,delay_scanner,delta,tol, backup, backup_filename);

  // (3) give the navigator a mission
  navigator->setMission(mission);

  // (4) start navigator
  navigator->start();


  //navigator.abort();
  //transmitter->abort();

  delete navigator;
  delete mission;
  delete transmitter;

  std::cout << "Main: program done" << std::endl;

  std::cout << "------------------------------------"<< std::endl;
  std::cout << "----------------DONE----------------"<< std::endl;
  std::cout << "------------------------------------"<< std::endl;
}
コード例 #13
0
ファイル: DSNTwoWayRange.cpp プロジェクト: rockstorm101/GMAT
//------------------------------------------------------------------------------
bool DSNTwoWayRange::Evaluate(bool withEvents)
{
   bool retval = false;

   if (!initialized)
      InitializeMeasurement();

   #ifdef DEBUG_RANGE_CALC
      MessageInterface::ShowMessage("Entered DSNTwoWayRange::Evaluate(%s)\n",
            (withEvents ? "true" : "false"));
      MessageInterface::ShowMessage("  ParticipantCount: %d\n",
            participants.size());
   #endif

   if (withEvents == false)
   {
      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("DSN 2-Way Range Calculation without "
               "events\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES
         DumpParticipantStates("++++++++++++++++++++++++++++++++++++++++++++\n"
               "Evaluating DSN 2-Way Range without events");
      #endif

      CalculateRangeVectorInertial();
      Rvector3 outState;

      // Set feasibility off of topocentric horizon, set by the Z value in topo
      // coords
      std::string updateAll = "All";
      UpdateRotationMatrix(currentMeasurement.epoch, updateAll);
      outState = R_o_j2k * rangeVecInertial;
      currentMeasurement.feasibilityValue = outState[2];

      #ifdef CHECK_PARTICIPANT_LOCATIONS
         MessageInterface::ShowMessage("Evaluating without events\n");
         MessageInterface::ShowMessage("Calculating DSN 2-Way Range at epoch "
               "%.12lf\n", currentMeasurement.epoch);
         MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   J2K Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         Rvector3 bfLoc = R_o_j2k * p1Loc;
         MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s",
               participants[0]->GetName().c_str(),
               bfLoc.ToString().c_str());
         bfLoc = R_o_j2k * p2Loc;
         MessageInterface::ShowMessage("   BodyFixed Location of %s:  %s\n",
               participants[1]->GetName().c_str(),
               bfLoc.ToString().c_str());
      #endif

      if (currentMeasurement.feasibilityValue > 0.0)
      {
         currentMeasurement.isFeasible = true;
         currentMeasurement.value[0] = rangeVecInertial.GetMagnitude();
         currentMeasurement.eventCount = 2;

         SetHardwareDelays(false);

         retval = true;
      }
      else
      {
         currentMeasurement.isFeasible = false;
         currentMeasurement.value[0] = 0.0;
         currentMeasurement.eventCount = 0;
      }

      #ifdef DEBUG_RANGE_CALC
         MessageInterface::ShowMessage("Calculating Range at epoch %.12lf\n",
               currentMeasurement.epoch);
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[0]->GetName().c_str(),
               currentMeasurement.participantIDs[0].c_str(),
               p1Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Location of %s, id = '%s':  %s",
               participants[1]->GetName().c_str(),
               currentMeasurement.participantIDs[1].c_str(),
               p2Loc.ToString().c_str());
         MessageInterface::ShowMessage("   Range Vector:  %s\n",
               rangeVecInertial.ToString().c_str());
         MessageInterface::ShowMessage("   R(Groundstation) dot RangeVec =  %lf\n",
               currentMeasurement.feasibilityValue);
         MessageInterface::ShowMessage("   Feasibility:  %s\n",
               (currentMeasurement.isFeasible ? "true" : "false"));
         MessageInterface::ShowMessage("   Range is %.12lf\n",
               currentMeasurement.value[0]);
         MessageInterface::ShowMessage("   EventCount is %d\n",
               currentMeasurement.eventCount);
      #endif

      #ifdef SHOW_RANGE_CALC
         MessageInterface::ShowMessage("Range at epoch %.12lf is ",
               currentMeasurement.epoch);
         if (currentMeasurement.isFeasible)
            MessageInterface::ShowMessage("feasible, value = %.12lf\n",
               currentMeasurement.value[0]);
         else
            MessageInterface::ShowMessage("not feasible\n");
      #endif
   }
   else
   {
      // Calculate the corrected range measurement
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("\n\n DSN 2-Way Range Calculation:\n");
      #endif

      #ifdef VIEW_PARTICIPANT_STATES_WITH_EVENTS
         DumpParticipantStates("********************************************\n"
               "Evaluating DSN 2-Way Range with located events");
      #endif

      // 1. Get the range from the down link
      Rvector3 r1, r2;
	  Real t1, t2;
      r1 = downlinkLeg.GetPosition(participants[0]);
      r2 = downlinkLeg.GetPosition(participants[1]);
	  t1 = downlinkLeg.GetEventData((GmatBase*) participants[0]).epoch;
	  t2 = downlinkLeg.GetEventData((GmatBase*) participants[1]).epoch;
	  Rmatrix33 mt = downlinkLeg.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	     MessageInterface::ShowMessage("1. Get downlink leg range:\n");
         MessageInterface::ShowMessage("   Ground station position in FK5: r1 = (%f, %f, %f)km  at epoch = %18.12lf\n", r1.Get(0), r1.Get(1), r1.Get(2), t1);
         MessageInterface::ShowMessage("   Spacecraft position in FK5    : r2 = (%f, %f, %f)km  at epoch = %18.12lf\n", r2.Get(0), r2.Get(1), r2.Get(2), t2);
		 MessageInterface::ShowMessage("   Transformation matrix from Earth fixed coordinate system to FK5 coordinate system at epoch = %18.12lf:\n", t1);
		 MessageInterface::ShowMessage("                %18.12lf  %18.12lf  %18.12lf\n", mt(0,0), mt(0,1), mt(0,2));
		 MessageInterface::ShowMessage("                %18.12lf  %18.12lf  %18.12lf\n", mt(1,0), mt(1,1), mt(1,2));
		 MessageInterface::ShowMessage("                %18.12lf  %18.12lf  %18.12lf\n", mt(2,0), mt(2,1), mt(2,2));
      #endif
      Rvector3 downlinkVector = r2 - r1;		// rVector = r2 - r1;
      downlinkRange = downlinkVector.GetMagnitude();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Downlink Range = r2-r1:  %.12lf km\n",
               downlinkRange);
      #endif


 	   // 2. Calculate down link range rate:
      Rvector3 p1V = downlinkLeg.GetVelocity(participants[0]);
      Rvector3 p2V = downlinkLeg.GetVelocity(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	     MessageInterface::ShowMessage("2. Get downlink leg range rate:\n");
         MessageInterface::ShowMessage("   Ground station velocity in FK5: p1V = (%f, %f, %f)km/s\n", p1V.Get(0), p1V.Get(1), p1V.Get(2));
         MessageInterface::ShowMessage("   Spacecraft velocity in FK5    : p2V = (%f, %f, %f)km/s\n", p2V.Get(0), p2V.Get(1), p2V.Get(2));
      #endif
      // @todo Relative origin velocities need to be subtracted when the origins
      // differ; check and fix that part using r12_j2k_vel here.  It's not yet
      // incorporated because we need to handle the different epochs for the
      // bodies, and we ought to do this part in barycentric coordinates
      Rvector downRRateVec = p2V - p1V /* - r12_j2k_vel*/;
      Rvector3 rangeUnit = downlinkVector.GetUnitVector();
      downlinkRangeRate = downRRateVec * rangeUnit;
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Downlink Range Rate:  %.12lf km/s\n",
               downlinkRangeRate);
      #endif


      // 3. Get the range from the uplink
      Rvector3 r3, r4;
	  Real t3, t4;
      r3 = uplinkLeg.GetPosition(participants[0]);
      r4 = uplinkLeg.GetPosition(participants[1]);
	  t3 = uplinkLeg.GetEventData((GmatBase*) participants[0]).epoch;
	  t4 = uplinkLeg.GetEventData((GmatBase*) participants[1]).epoch;
	  Rmatrix33 mt1 = uplinkLeg.GetEventData((GmatBase*) participants[0]).rInertial2obj.Transpose();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	     MessageInterface::ShowMessage("3. Get uplink leg range:\n");
         MessageInterface::ShowMessage("   Spacecraft position in FK5    : r4 = (%f, %f, %f)km   at epoch = %18.12lf\n", r4.Get(0), r4.Get(1), r4.Get(2), t4);
         MessageInterface::ShowMessage("   Ground station position in FK5: r3 = (%f, %f, %f)km   at epoch = %18.12lf\n", r3.Get(0), r3.Get(1), r3.Get(2), t3);
		 MessageInterface::ShowMessage("   Transformation matrix from Earth fixed coordinate system to FK5 coordinate system at epoch = %18.12lf:\n", t3);
		 MessageInterface::ShowMessage("                %18.12lf  %18.12lf  %18.12lf\n", mt1(0,0), mt1(0,1), mt1(0,2));
		 MessageInterface::ShowMessage("                %18.12lf  %18.12lf  %18.12lf\n", mt1(1,0), mt1(1,1), mt1(1,2));
		 MessageInterface::ShowMessage("                %18.12lf  %18.12lf  %18.12lf\n", mt1(2,0), mt1(2,1), mt1(2,2));
      #endif
      Rvector3 uplinkVector = r4 - r3;
      uplinkRange = uplinkVector.GetMagnitude();
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Uplink Range = r4-r3:  %.12lf km\n",
               uplinkRange);
      #endif


   	// 4. Calculate up link range rate
      Rvector3 p3V = uplinkLeg.GetVelocity(participants[0]);
      Rvector3 p4V = uplinkLeg.GetVelocity(participants[1]);
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	     MessageInterface::ShowMessage("4. Get uplink leg range rate:\n");
         MessageInterface::ShowMessage("   Ground station velocity in FK5: p3V = (%f, %f, %f)km/s\n", p3V.Get(0), p3V.Get(1), p3V.Get(2));
         MessageInterface::ShowMessage("   Spacecraft velocity in FK5    : p4V = (%f, %f, %f)km/s\n", p4V.Get(0), p4V.Get(1), p4V.Get(2));
      #endif
      // @todo Relative origin velocities need to be subtracted when the origins
      // differ; check and fix that part using r12_j2k_vel here.  It's not yet
      // incorporated because we need to handle the different epochs for the
      // bodies, and we ought to do this part in barycentric coordinates
      Rvector upRRateVec = p4V - p3V /* - r12_j2k_vel*/ ;
      rangeUnit = uplinkVector.GetUnitVector();
      uplinkRangeRate = upRRateVec * rangeUnit;
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("   Uplink Range Rate:  %.12lf km/s\n",
               uplinkRangeRate);
      #endif

      // 4.1. Target range rate: Do we need this as well?
      targetRangeRate = (downlinkRangeRate + uplinkRangeRate) / 2.0;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   Target Range Rate:  %.12lf km/s\n",
						targetRangeRate);
		#endif


		// 5. Get sensors used in DSN 2-ways range
	   if (participantHardware.empty()||
	   		((!participantHardware.empty())&&
	   		  participantHardware[0].empty()&&
	   		  participantHardware[1].empty()
	   		)
	   	)
	   {
         // DO NOT LEAVE THIS RAW IN A SOURCE FILE!!!
	   	// MessageInterface::ShowMessage("    Ideal measurement (no hardware delay and no media correction involve):\n");

		   // Calculate uplink time and down link time: (Is it needed???)
		   uplinkTime   = uplinkRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
		   downlinkTime = downlinkRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
		   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
		      MessageInterface::ShowMessage("  Ideal measurement (no hardware delay and no media correction involve):\n");
			  MessageInterface::ShowMessage("    Uplink time = %.12lf s\n",uplinkTime);
			  MessageInterface::ShowMessage("    Downlink time = %.12lf s\n",downlinkTime);
		   #endif

		   // Calculate real range
		   Real freqFactor = GetFrequencyFactor(frequency);	// Notice that: unit of "frequency" varaibel is Hz (not MHz)
		   Real realTravelTime = uplinkTime + downlinkTime + receiveDelay + transmitDelay + targetDelay;	// unit: second
		   Real realRangeKm = 0.5 *realTravelTime * GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM/1000.0;    // unit: km
		   Real realRange = realTravelTime * freqFactor;													// unit: no unit

		   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
		      MessageInterface::ShowMessage("   Frequency = %.12lf MHz (This value is set to the default value in PhysicalMeasurement class due to no hardware used.)\n", frequency/1.0e6);
			  MessageInterface::ShowMessage("   Frequency factor = %.12lf MHz\n", freqFactor/1.0e6);
	          MessageInterface::ShowMessage("   Range in km = %.12lf km\n", realRangeKm);
			  MessageInterface::ShowMessage("   uplinkRange = %lfkm   downlinkRange = %lfkm\n", uplinkRange, downlinkRange);
			  MessageInterface::ShowMessage("   receiveDelay = %lfm   transmitDelay = %lfm   targetDelay = %lfm\n", receiveDelay*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM, transmitDelay*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM, targetDelay*GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM);
	          MessageInterface::ShowMessage("   Range = %.12lf (It has no unit)\n", realRange);
	       #endif

	      // Set value for currentMeasurement
		   currentMeasurement.value[0] = realRange;
	      currentMeasurement.isFeasible = true;

	      return true;
	   }

		ObjectArray objList1;
		ObjectArray objList2;
		ObjectArray objList3;
		//			objList1 := all transmitters in participantHardware list
		//			objList2 := all receivers in participantHardware list
		//			objList3 := all transponders in participantHardware list
		for(std::vector<Hardware*>::iterator hw = this->participantHardware[0].begin();
		  		hw != this->participantHardware[0].end(); ++hw)
		{
		 	if ((*hw) != NULL)
		  	{
		  		if ((*hw)->GetTypeName() == "Transmitter")
		  			objList1.push_back(*hw);
		  		if ((*hw)->GetTypeName() == "Receiver")
		  			objList2.push_back(*hw);
		  	}
		  	else
		  		MessageInterface::ShowMessage(" sensor = NULL\n");
		}

		for(std::vector<Hardware*>::iterator hw = this->participantHardware[1].begin();
		  		hw != this->participantHardware[1].end(); ++hw)
		{
		  	if ((*hw) != NULL)
		  	{
		  		if ((*hw)->GetTypeName() == "Transponder")
		  			objList3.push_back(*hw);
		  	}
		  	else
		  		MessageInterface::ShowMessage(" sensor = NULL\n");
		}

		if (objList1.size() != 1)
		{
		  	MessageInterface::ShowMessage("The first participant does not have only 1 transmitter to send signal.\n");
		   throw new MeasurementException("The first participant does not have only 1 transmitter to send signal.\n");
		}
		if (objList2.size() != 1)
		{
		 	MessageInterface::ShowMessage("The first participant does not have only 1 receiver to receive signal.\n");
		   throw new MeasurementException("The first participant does not have only 1 receiver to receive signal.\n");
		}
		if (objList3.size() != 1)
		{
		  	MessageInterface::ShowMessage("The second participant does not have only 1 transponder to transpond signal.\n");
		  	throw new MeasurementException("The second participant does not have only 1 transponder to transpond signal.\n");
		}

	   Transmitter* 	gsTransmitter 	= (Transmitter*)objList1[0];
	   Receiver* 		gsReceiver 		= (Receiver*)objList2[0];
	   Transponder* 	scTransponder 	= (Transponder*)objList3[0];
	   if (gsTransmitter == NULL)
	   {
	   	MessageInterface::ShowMessage("Transmitter is NULL object.\n");
	   	throw new GmatBaseException("Transmitter is NULL object.\n");
	   }
	   if (gsReceiver == NULL)
	   {
	   	MessageInterface::ShowMessage("Receiver is NULL object.\n");
	   	throw new GmatBaseException("Receiver is NULL object.\n");
	   }
	   if (scTransponder == NULL)
	   {
	   	MessageInterface::ShowMessage("Transponder is NULL object.\n");
	   	throw new GmatBaseException("Transponder is NULL object.\n");
	   }

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	        MessageInterface::ShowMessage("5. Sensors, delays, and signals:\n");
			MessageInterface::ShowMessage("   List of sensors: %s, %s, %s\n",
				gsTransmitter->GetName().c_str(), gsReceiver->GetName().c_str(),
				scTransponder->GetName().c_str());
		#endif


		// 6. Get transmitter, receiver, and transponder delays:
		transmitDelay = gsTransmitter->GetDelay();
		receiveDelay = gsReceiver->GetDelay();
		targetDelay = scTransponder->GetDelay();

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   Transmitter delay = %le s\n", gsTransmitter->GetDelay());
			MessageInterface::ShowMessage("   Receiver delay = %le s\n", gsReceiver->GetDelay());
			MessageInterface::ShowMessage("   Transponder delay = %le s\n", scTransponder->GetDelay());
		#endif


		// 7. Get frequency from transmitter of ground station (participants[0])
		Signal* uplinkSignal = gsTransmitter->GetSignal();
		Real uplinkFreq = uplinkSignal->GetValue();


        // 8. Calculate media correction for uplink leg:
        #ifdef DEBUG_RANGE_CALC_WITH_EVENTS   
           MessageInterface::ShowMessage("6. Media correction for uplink leg\n");
		   MessageInterface::ShowMessage("   UpLink signal frequency = %.12lf MHz\n", uplinkFreq);
        #endif
        Real roundTripTime = ((uplinkRange + downlinkRange)*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)/GmatTimeConstants::SECS_PER_DAY;
        RealArray uplinkCorrection = CalculateMediaCorrection(uplinkFreq, r1, r2, currentMeasurement.epoch - roundTripTime);
        Real uplinkRangeCorrection = uplinkCorrection[0]/GmatMathConstants::KM_TO_M;
        Real uplinkRealRange = uplinkRange + uplinkRangeCorrection;
		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   Uplink range correction = %.12lf km\n",uplinkRangeCorrection);
			MessageInterface::ShowMessage("   Uplink real range = %.12lf km\n",uplinkRealRange);
		#endif


		// 9. Doppler shift the frequency from the transmitter using uplinkRangeRate:
	   Real uplinkDSFreq = (1 - uplinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*uplinkFreq;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	        MessageInterface::ShowMessage("7. Transponder input and output frequencies\n");
			MessageInterface::ShowMessage("   Uplink Doppler shift frequency = %.12lf MHz\n", uplinkDSFreq);
		#endif


	   // 10.Set frequency for the input signal of transponder
	   Signal* inputSignal = scTransponder->GetSignal(0);
	   inputSignal->SetValue(uplinkDSFreq);
	   scTransponder->SetSignal(inputSignal, 0);


	   // 11. Check the transponder feasibility to receive the input signal:
	   if (scTransponder->IsFeasible(0) == false)
	   {
	   	 currentMeasurement.isFeasible = false;
	   	 currentMeasurement.value[0] = 0;
	   	 MessageInterface::ShowMessage("The transponder is unfeasible to receive uplink signal.\n");
	   	 throw new GmatBaseException("The transponder is unfeasible to receive uplink signal.\n");
	   }


	   // 12. Get frequency of transponder output signal
	   Signal* outputSignal = scTransponder->GetSignal(1);
	   Real downlinkFreq = outputSignal->GetValue();

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("  Downlink frequency = %.12lf Mhz\n", downlinkFreq);
		#endif


	   // 13. Doppler shift the transponder output frequency by the downlinkRangeRate:
	   Real downlinkDSFreq = (1 - downlinkRangeRate*GmatMathConstants::KM_TO_M/GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM)*downlinkFreq;

	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("  Downlink Doppler shift frequency = %.12lf MHz\n", downlinkDSFreq);
		#endif


	   // 14. Set frequency on receiver
	   Signal* downlinkSignal = gsReceiver->GetSignal();
	   downlinkSignal->SetValue(downlinkDSFreq);


	   // 15. Check the receiver feasibility to receive the downlink signal
	   if (gsReceiver->IsFeasible() == false)
	   {
	   	 currentMeasurement.isFeasible = false;
	   	 currentMeasurement.value[0] = 0;
		 MessageInterface::ShowMessage("The receiver is unfeasible to receive downlink signal.\n");
	   	 throw new MeasurementException("The receiver is unfeasible to receive downlink signal.\n");
	   }


	   // 16. Calculate media correction for downlink leg:
      #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
         MessageInterface::ShowMessage("8. Media correction for downlink leg\n");
      #endif
	   RealArray downlinkCorrection = CalculateMediaCorrection(downlinkDSFreq, r3, r4, currentMeasurement.epoch);
	   Real downlinkRangeCorrection = downlinkCorrection[0]/GmatMathConstants::KM_TO_M;
	   Real downlinkRealRange = downlinkRange + downlinkRangeCorrection;
		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
			MessageInterface::ShowMessage("   Downlink range correction = %.12lf km\n",downlinkRangeCorrection);
			MessageInterface::ShowMessage("   Downlink real range = %.12lf km\n",downlinkRealRange);
		#endif

	   // 17. Calculate uplink time and down link time: (Is it needed???)
	   uplinkTime   = uplinkRealRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;
	   downlinkTime = downlinkRealRange*GmatMathConstants::KM_TO_M / GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM;

		#ifdef DEBUG_RANGE_CALC_WITH_EVENTS
	        MessageInterface::ShowMessage("9. Travel time:\n");
			MessageInterface::ShowMessage("   Uplink time = %.12lf s\n",uplinkTime);
			MessageInterface::ShowMessage("   Downlink time = %.12lf s\n",downlinkTime);
		#endif


	   // 18. Calculate real range
		//	   Real realRange = ((upRange + downRange) /
		//            (GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM / GmatMathConstants::KM_TO_M) +
		//            receiveDelay + transmitDelay + targetDelay) * freqFactor;

	   // Real freqFactor = GetFrequencyFactor(frequency);
	   Real freqFactor = GetFrequencyFactor(uplinkFreq*1.0e6);		// Notice that: unit of "uplinkFreq" is MHz (not Hz)
  	   Real realTravelTime = uplinkTime + downlinkTime + receiveDelay + transmitDelay + targetDelay;    // unit: second
	   Real realRangeKm = 0.5*realTravelTime * GmatPhysicalConstants::SPEED_OF_LIGHT_VACUUM/1000.0;		// unit: km
       Real realRange = realTravelTime * freqFactor;													// unit: no unit

	   #ifdef DEBUG_RANGE_CALC_WITH_EVENTS
		  MessageInterface::ShowMessage("   Frequency factor = %.12lf MHz\n", freqFactor/1.0e6);
		  MessageInterface::ShowMessage("   Calculated real range in km = %.12lf km\n", realRangeKm);
          MessageInterface::ShowMessage("   Calculated real range = %.12lf (It has no unit)\n", realRange);
       #endif



	   // 19. Set value for currentMeasurement
//	   currentMeasurement.value[0] = realRange;
      currentMeasurement.value[0] = realRangeKm;
      currentMeasurement.isFeasible = true;

      retval = true;
   }

   return retval;
}
コード例 #14
0
ファイル: Scanner.cpp プロジェクト: openwns/ofdmaphy
void
Scanner::Receiver::positionChanged()
{
    ofdmaphy::receiver::Receiver::positionChanged();

    if(transmissions.empty())
        return;

    wns::Position currentPosition = getStation()->getAntenna()->getPosition();

    assure(margin >= wns::Ratio::from_dB(0.0), "Margin must be >= 0 dB");

    wns::Ratio nullMargin = wns::Ratio::from_dB(0);
    wns::Ratio maxSINR = wns::Ratio::from_dB(-250);
    wns::Power maxRxPwr = wns::Power::from_dBm(-250);
    wns::Ratio minPathloss = wns::Ratio::from_dB(300);
    double assocdistance = 0.0;

    std::multimap<wns::Ratio, rise::TransmissionObjectPtr> sinrSortedTransmissions;                                    

	for (TOList::const_iterator itr = transmissions.begin();
		 itr != transmissions.end();
		 ++itr)
	{
		Transmitter<Sender>* transmitter = 
			dynamic_cast<Transmitter<Sender>*>((*itr)->getTransmitter());

        wns::Position bsPosition = transmitter->getAntenna()->getPosition();
        double distance = (bsPosition - currentPosition).abs();
		wns::Power txp    = (*itr)->getTxPower();
		wns::Power rxp    = this->getRxPower(*itr);
		wns::Power interf = this->getInterference(*itr);
		wns::Ratio sinr   = rxp / interf;
        wns::Ratio pathloss = this->getQuasiStaticPathLoss((*itr), wns::service::phy::ofdma::PatternPtr());
        pathloss += wns::Ratio::from_dB(2.0);

        if(margin > nullMargin)
            sinrSortedTransmissions.insert(std::pair<wns::Ratio, rise::TransmissionObjectPtr>(sinr, *itr));

        maxSINR = std::max(maxSINR, sinr);
        maxRxPwr = std::max(maxRxPwr, rxp);
        if (pathloss < minPathloss)
        {
            minPathloss = pathloss;
            assocdistance = distance;
        }

		bsID = transmitter->getStation()->getStationId();

		MESSAGE_BEGIN(NORMAL, logger, m, "Measured ");

		std::string msName = scanner->getMyNode()->getName();
		std::string bsName = transmitter->getStation()->getMyNode()->getName();

        m << bsName << "(bsId=" << bsID << ") by " << msName << "(msId=" << scanner->getStationId() << "):\n"
		  << "TxPower: " << txp.get_dBm() << "\n"
		  << "RxPower: " << rxp.get_dBm() << "\n"
		  << "Interference+Noise: " << interf.get_dBm() << "\n"
		  << "SINR:" << sinr.get_dB() << "\n";
		MESSAGE_END();

		rxpContextCollector->put(rxp.get_dBm());
		sinrContextCollector->put(sinr.get_dB());
        pathlossContextCollector->put(-1 * pathloss.get_dB());
	}

    if(margin > nullMargin)
    {
        wns::Ratio marginSINR = maxSINR - margin;

        std::multimap<wns::Ratio, rise::TransmissionObjectPtr>::iterator it_bound;

        it_bound = sinrSortedTransmissions.lower_bound(marginSINR);
        assure(it_bound != sinrSortedTransmissions.end(), "Maximum SINR not in sorted SINR container");
        
        std::vector<rise::TransmissionObjectPtr> candidates;
        
        std::multimap<wns::Ratio, rise::TransmissionObjectPtr>::iterator it;
        for(it = it_bound; it != sinrSortedTransmissions.end(); it++)
            candidates.push_back(it->second);

        wns::distribution::DiscreteUniform rng(0, candidates.size() - 1);
        rise::TransmissionObjectPtr serving =  candidates[rng()];

		wns::Power rxp    = this->getRxPower(serving);
		wns::Power interf = this->getInterference(serving);
		wns::Ratio sinr   = rxp / interf;

        maxRxpContextCollector->put(rxp.get_dBm());
        maxSINRContextCollector->put(sinr.get_dB());
        minPathlossContextCollector->put(-1 * this->getQuasiStaticPathLoss((serving), 
            wns::service::phy::ofdma::PatternPtr()).get_dB());

		Transmitter<Sender>* transmitter = 
			dynamic_cast<Transmitter<Sender>*>((serving)->getTransmitter());
        wns::Position bsPosition = transmitter->getAntenna()->getPosition();
        distanceContextCollector->put((bsPosition - currentPosition).abs());

		MESSAGE_BEGIN(NORMAL, logger, m, "Selected " << transmitter->getStation()->getMyNode()->getName());
		m << "Number of candidates: " << candidates.size() << "\n"
		  << "SINR:" << sinr.get_dB() << "\n";
		MESSAGE_END();
    }
    else
    {
        maxRxpContextCollector->put(maxRxPwr.get_dBm());
        maxSINRContextCollector->put(maxSINR.get_dB());
        minPathlossContextCollector->put(-1 * minPathloss.get_dB());
        distanceContextCollector->put(assocdistance);
    }
}