DiameterSessionEntryList::DiameterSessionEntryList() 
{
     ACE_Time_Value tm = ACE_OS::gettimeofday();
     m_LastKnownCounter.High() = tm.sec();
     m_LastKnownCounter.Low() = tm.usec();
}
Exemplo n.º 2
0
int
run_main (int argc, ACE_TCHAR *argv[])
{
  ACE_START_TEST (ACE_TEXT ("NDDS_Timer_Test"));

  RTIClock *timer = RTIHighResolutionClock_new();

  u_int errors = 0;

  u_int iterations = 1;

  ACE_Get_Opt getoptarg (argc, argv, ACE_TEXT ("i:"));
  for (int c; (c = getoptarg ()) != -1; )
    {
      switch (c)
        {
        case 'i':
          iterations = ACE_OS::atoi (getoptarg.opt_arg ());
          break;
        }
    }

  // We don't check for errors if the interval is shorter than this
  // value because the OS has a finite resolution anyway.
  static u_int const TIMER_RESOLUTION = 10000;

  for (u_int i = 0; i < sizeof intervals / sizeof (u_int); ++i)
    {
      for (u_int j = 0; j < iterations; ++j)
        {
          ACE_Time_Value const interval (0, intervals[i]);

          RTINtpTime duration;
          time_interval (timer, interval, duration);

          unsigned long long microseconds, nanoseconds;
          int sec;
          RTINtpTime_unpackToMicrosec (sec, microseconds, duration);
          RTINtpTime_unpackToNanosec (sec, nanoseconds, duration);

          time_t const interval_usec =
            interval.sec () * ACE_ONE_SECOND_IN_USECS + interval.usec ();
          time_t const measured_usec =
            sec * ACE_ONE_SECOND_IN_USECS + microseconds;


          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("interval: %: usec, measured: %: usec %s\n"),
                      interval_usec,
                      measured_usec,
                      (intervals[i] <= TIMER_RESOLUTION
                       ? ACE_TEXT (" (interval and measured may differ)")
                       : ACE_TEXT (""))));

          if (intervals[i] > TIMER_RESOLUTION)
            {
              errors += check (interval.sec () * ACE_ONE_SECOND_IN_USECS
                               + interval.usec (),
                               sec * ACE_ONE_SECOND_IN_USECS + microseconds);
              // Don't check for error for intervals below 10 msec.
            }
          errors += check_micro_nano (microseconds, nanoseconds);
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("NDDS_Timer usec: %Q, nsec: %Q\n"),
                      microseconds,
                      nanoseconds));
        }
    }

  ACE_END_TEST;
  return errors == 0  ?  0  :  1;
}
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  if ( argc < 2 )
    ACE_ERROR_RETURN ((LM_ERROR,
                       "Usage: %s <rate> <PDU> <session> <host> <selector> [ host sel ] ...\n"
                       "\tUse 0 for default values\n",
                       argv[0]),
                      1);

  int rate = ACE_OS::atoi( argv[ 1 ]);
  rate = ( rate != 0 ) ? rate : 170000;
  int pdu_size = ACE_OS::atoi( argv[ 2 ]) * 1024;
  pdu_size = ( pdu_size != 0 ) ? pdu_size : 8192;
  int session = ACE_OS::atoi( argv[ 3 ]);
  session = ( session != 0 ) ? session : 100;

  ACE_OS::printf( "ATM_Client: rate: %d c/s, PDU: %dB, session: %d pkts\n",
    rate, pdu_size, session );

  // Record all hosts/selectors
  ACE_ATM_Addr hosts[ MAX_LEAVES ];
  int num_leaves = argc / 2 - 2;

  ACE_OS::printf( "ATM_Client: Connecting to ...\n" );
  for ( int i = 0; i < num_leaves; i++ ) {
    hosts[ i ].set( argv[ i*2 + 4 ],
                    ( argv[ i*2 + 5 ] != 0 )
                      ? ACE_OS::atoi( argv[ i*2 + 5 ]) : ACE_ATM_Addr::DEFAULT_SELECTOR );
    ACE_OS::printf( "ATM_Client: leaf: %s (%s), sel: %d\n",
                    argv[ i*2 + 4 ],
                    hosts[ i ].addr_to_string(),
                    hosts[ i ].get_selector());
  }

  // The timeout really gets ignored since FORE's drivers don't work when
  //  ioctl or fcntl calls are made on the transport id/file descriptor
  int timeout = ACE_DEFAULT_TIMEOUT;
  char buf[BUFSIZ];
  ACE_ATM_Stream atm_stream;

  char hostname[ MAXNAMELEN ];
  ACE_OS::hostname( hostname, MAXNAMELEN );
  ACE_ATM_Addr local_addr( hostname, hosts[ 0 ].get_selector());

  ACE_OS::printf( "ATM_Client: local host: %s(%s)\n",
    hostname, local_addr.addr_to_string());

  // In order to construct connections options the file handle is
  // needed.  Therefore, we need to open the ATM_Stream before we
  // construct the options.
  ACE_OS::printf( "ATM_Client: to open a stream\n" );
  if (atm_stream.open () == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "open failed"),
                      1);

  ACE_DEBUG ((LM_DEBUG,
              "ATM_Client: starting non-blocking connection\n"));

  // Initiate timed, non-blocking connection with server.
  ACE_ATM_Connector con;

  // Construct QoS options - currently FORE only supports bandwidth
  ACE_OS::printf( "ATM_Client: specify cell rate at %d c/s\n", rate );
  ACE_ATM_QoS qos;
  qos.set_rate(atm_stream.get_handle (),
               rate,
               ACE_ATM_QoS::OPT_FLAGS_CPID);

  if ( num_leaves == 1 ) {
    // Point-to-point connection
    // Not sure why but reuse_addr set to true/1 causes problems for
    // FORE/XTI/ATM - this is now handled in ACE_ATM_Connector::connect()
    ACE_OS::printf( "ATM_Client: to open a connection \n" );
    ACE_ATM_Params params = ACE_ATM_Params();
    if (con.connect (atm_stream,
                     hosts[ 0 ],
                     params,
                     qos,
                     (ACE_Time_Value *) &ACE_Time_Value::zero,
                     local_addr,
                     0,
                     0 ) == -1) {
      if (errno != EWOULDBLOCK)
	      ACE_ERROR_RETURN ((LM_ERROR,
                          "%p\n",
                          "ATM_Client: connection failed"),
                          1);

      ACE_DEBUG ((LM_DEBUG,
                    "ATM_Client: starting timed connection\n"));

      // Check if non-blocking connection is in progress, and wait up
      // to timeout seconds for it to complete.
      ACE_Time_Value tv (timeout);

      ACE_OS::printf( "ATM_Client: connection completed\n" );
      if (con.complete (atm_stream,
                        &hosts[ 0 ],
                        &tv) == -1)
		    ACE_ERROR_RETURN ((LM_ERROR,
                          "%p\n",
                          "ATM_Client: connection failed"),
                          1);
      else
		    ACE_DEBUG ((LM_DEBUG,
                   "ATM_Client: connected to %s\n",
		               hosts[ 0 ].addr_to_string()));
    }
  } else {
    // Point-to-multipoint connection
    for ( int i = 0; i < num_leaves; i++ ) {
      con.add_leaf( atm_stream,
                    hosts[ i ],
                    i,
                    NULL );

    }
  } /* if num_leaves == 1 */

  ACE_UINT16 vpi, vci;
  atm_stream.get_vpi_vci(vpi, vci);
  ACE_DEBUG ((LM_DEBUG,
              "ATM_Client: connected to VPI %d VCI %d\n",
              vpi, vci));

  // Send data to server (correctly handles "incomplete writes").

  int s_bytes;
  int total;
  int xmit = 0;
  ACE_High_Res_Timer timer;
  ACE_Time_Value elapsed;
  double real_time;
  double actual_rate;

  for ( ;; ) {
    total = 0;

    timer.start_incr();

    for ( ;; ) {
      s_bytes = atm_stream.send_n( buf, BUFSIZ, 0 );
      if ( s_bytes == -1 )
        ACE_ERROR_RETURN ((LM_ERROR,
                           "%p\n",
                           "send_n"),
                           1);

      total += s_bytes;

      if ( total >= session * pdu_size )
        break;
    }

    timer.stop_incr();
    timer.elapsed_time_incr( elapsed );
    real_time = elapsed.sec() * ACE_ONE_SECOND_IN_USECS + elapsed.usec();
    xmit += total;
    actual_rate = ( double )xmit * ( double )8 / real_time;

    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("(%t) bytes = %d, usec = %f, rate = %0.00f Mbps\n"),
                xmit,
                real_time,
                actual_rate < 0 ? 0 : actual_rate ));
  }

  // Explicitly close the connection.
  ACE_OS::printf( "ATM_Client: close connection\n" );
  if (atm_stream.close () == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "close"),
                       -1);
  return 0;
}
  void
  Consumer::handleMessage(const Miro::DevMessage * _message)
  {
    ++Connection::gotTicks_;

    if (pOdometry_) {

      const FaulController::OdometryMessage * pFaulMsg =
	static_cast<const FaulController::OdometryMessage *>(_message);

      if (pFaulMsg->wheel_ == FaulController::OdometryMessage::LEFT) {
//	cout << "L: " << pFaulMsg->ticks_;
	ticksL_ = pFaulMsg->ticks_;
	timeStampL_ = pFaulMsg->time();
      }
      else {
//	cout << "R: " << pFaulMsg->ticks_;
	ticksR_ = pFaulMsg->ticks_;
	timeStampR_ = pFaulMsg->time();
      }

      if (prevTimeStampL_+ ACE_Time_Value(0, 10000) < timeStampR_ &&
	  prevTimeStampR_+ ACE_Time_Value(0, 10000) < timeStampL_ &&
	  prevTimeStampL_ != timeStampL_ &&
	  prevTimeStampR_ != timeStampR_) {
	if (init_ == 0) {
	  double dL = -(ticksL_ - prevTicksL_) / params_->leftTicksPerMM;
	  double dR = (ticksR_ - prevTicksR_) / params_->rightTicksPerMM;

//	  cout << "dL: " << dL << " dR: " << dR << endl;

	  // reset tick counters to minimize overhead
	  //if ((pFaulMsg->lPos < 3000) or (pFaulMsg->lPos > 10000) pConnection->setPos1(0);
	  //if ((pFaulMsg->RPos < 3000) or (pFaulMsg->RPos > 10000) pConnection->setPos0(0);

	  // calculate new orientation
	  double turn = (dR - dL) / wheelBase_;
	  status_.position.heading += turn;

	  Miro::Angle::normalize(status_.position.heading);

	  double dist = (dL + dR) / 2.;
	  xPos_ += cos(status_.position.heading) * dist;
	  yPos_ += sin(status_.position.heading) * dist;

	  ACE_Time_Value timeDelta = timeStampR_ - prevTimeStampR_;

	  double deltaT = (double)timeDelta.sec() + (double)timeDelta.usec() / 1000000.;

	  // compose odometry message
	  Miro::timeA2C(timeStampR_, status_.time);

	  if (!Sparrow::Parameters::instance()->goalie) {
	    status_.position.point.x = (long) xPos_;
	    status_.position.point.y = (long) yPos_;
	  }
	  else {
	    status_.position.point.x = (long) yPos_;
	    status_.position.point.y = (long) -xPos_;
	  }
	  status_.velocity.translation = (long)(dist / deltaT);
	  status_.velocity.rotation = turn / deltaT;

	  //cout << status_.time.sec<< "  " << status_.time.usec <<endl; //(dL+dR) / 2*dtime<<  endl;

// berechnung
if (false) {
	  ACE_Time_Value dTR = timeStampR_ - prevTimeStampR_;
	  deltaTR[counter] = (double)dTR.sec() + (double)dTR.usec() / 1000000.;

	  ACE_Time_Value dTL = timeStampL_ - prevTimeStampL_;
	  deltaTL[counter] = (double)dTL.sec() + (double)dTL.usec()/ 1000000.;

	  ACE_Time_Value dTLR = (timeStampL_ > timeStampR_)?
		                timeStampL_ - timeStampR_ :
				timeStampR_ - timeStampL_;
	  deltaTLR[counter] = (double)dTLR.sec() + (double)dTLR.usec()/ 1000000.;

	  cout << "TimerOdo dTR: " << dTR << " \tdTL: " << dTL << " \tdTLR: " << dTLR << endl;

	  int i;
	  if (counter ==  0) {
	    double meanL = deltaTL[0];
	    double meanR = deltaTR[0];
	    double meanLR = deltaTLR[0];

	    for ( i = 49; i > 0; --i) {
	      meanL += deltaTL[i];
	      meanR += deltaTR[i];
	      meanLR += deltaTLR[i];
	    }

	    meanL /= 50.;
	    meanR /= 50.;
	    meanLR /= 50.;

	    double varL = 0.;
	    double varR = 0.;
	    double varLR = 0.;

	    for ( i = 49; i >= 0; --i) {
	      varL += (deltaTL[i] - meanL) * (deltaTL[i] - meanL);
	      varR += (deltaTR[i] - meanR) * (deltaTR[i] - meanR);
	      varLR += (deltaTLR[i] - meanLR) * (deltaTLR[i] - meanLR);
	    }

	    varL /= 49.;
	    varR /= 49.;
	    varLR /= 49.;

	    cout << "TimerOdo L:  mean=" << meanL << "sec \t var=" <<sqrt(varL)<< endl;
	    cout << "TimerOdo R:  mean=" << meanR << "sec \t var=" <<sqrt(varR)<< endl;
	    cout << "TimerOdo LR: mean=" << meanLR << "sec \t var=" <<sqrt(varLR)<< endl;

	    counter = 50;
	  }


	  --counter;
}
	  // save current values for next iteration
	  prevTimeStampL_ = timeStampL_;
	  prevTimeStampR_ = timeStampR_;
	  prevTicksL_ = ticksL_;
	  prevTicksR_ = ticksR_;
          
	  pOdometry_->integrateData(status_);
	  return;
	}
	else {
	  // save current values for next iteration
	  prevTimeStampL_ = timeStampL_;
	  prevTimeStampR_ = timeStampR_;
	  prevTicksL_ = ticksL_;
	  prevTicksR_ = ticksR_;

	  --init_;
	}
      }
    }
  }
Exemplo n.º 5
0
int
run_main (int argc, ACE_TCHAR *argv[])
{
  ACE_START_TEST (ACE_TEXT ("High_Res_Timer_Test"));

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("The ACE_High_Res_Timer scale factor is %u ")
              ACE_TEXT ("1/microsecond\n"),
              ACE_High_Res_Timer::global_scale_factor ()));

  u_int errors = 0;

  u_int iterations = 1;

  ACE_Get_Opt getoptarg (argc, argv, ACE_TEXT ("i:"));
  for (int c; (c = getoptarg ()) != -1; )
    {
      switch (c)
        {
        case 'i':
          iterations = ACE_OS::atoi (getoptarg.opt_arg ());
          break;
        }
    }

  // We don't check for errors if the interval is shorter than this
  // value because the OS has a finite resolution anyway.
  static u_int const TIMER_RESOLUTION = 10000;

  for (u_int i = 0; i < sizeof intervals / sizeof (u_int); ++i)
    {
      for (u_int j = 0; j < iterations; ++j)
        {
          ACE_Time_Value const interval (0, intervals[i]);
          ACE_hrtime_t nanoseconds;
          ACE_hrtime_t microseconds;
          ACE_Time_Value const measured = time_interval (interval,
                                                         nanoseconds,
                                                         microseconds);
          time_t const interval_usec =
            interval.sec () * ACE_ONE_SECOND_IN_USECS + interval.usec ();
          time_t const measured_usec =
            measured.sec () * ACE_ONE_SECOND_IN_USECS + measured.usec ();

          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("interval: %: usec, measured: %: usec %s\n"),
                      interval_usec,
                      measured_usec,
                      (intervals[i] <= TIMER_RESOLUTION
                       ? ACE_TEXT (" (interval and measured may differ)")
                       : ACE_TEXT (""))));

          if (intervals[i] > TIMER_RESOLUTION)
            {
              errors += check (interval.sec () * ACE_ONE_SECOND_IN_USECS
                               + interval.usec (),
                               measured.sec () * ACE_ONE_SECOND_IN_USECS
                               + measured.usec ());
              // Don't check for error for intervals below 10 msec.
            }
          // Check the ACE_Timer_Value-calculated microseconds against
          // the ACE_High_Res_Timer-calculated nanoseconds.
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("ACE_Time_Value usec: %:, ACE_HR nsec: %Q\n"),
                      measured_usec,
                      nanoseconds));
          // This gives problems -> should be fixed
          errors += check_micro_nano (measured.sec () * ACE_ONE_SECOND_IN_USECS
                                      + measured.usec (),
                                      nanoseconds);
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("ACE_High_Res_Timer usec: %Q, nsec: %Q\n"),
                      microseconds,
                      nanoseconds));
          // Now check the ACE_High_Res_Timer-calculated values against
          // each other.
          errors += check_micro_nano (microseconds, nanoseconds);
        }
    }

  ACE_END_TEST;
  return errors == 0  ?  0  :  1;
}
Exemplo n.º 6
0
void
Writer::start()
{
  ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) Writer::start \n")));

  try {
    OpenDDS::DCPS::DataReaderImpl* dr_servant =
      dynamic_cast<OpenDDS::DCPS::DataReaderImpl*>(reader_);

    ::Xyz::Foo foo;
    foo.x = 0.0;
    foo.y = 0.0;

    ::OpenDDS::DCPS::SequenceNumber seq;

    if (!multiple_instances_) {
      foo.key = default_key;
    }

    for (int i = 0; i < num_writes_per_thread_; ++i) {
      ++seq;

      foo.x = (float)i;
      foo.y = (float)i;

      if (multiple_instances_) {
        foo.key = i + 1;
      }

      ACE_Time_Value now = ACE_OS::gettimeofday();

      ACE_OS::printf("\"writing\" foo.x = %f foo.y = %f, foo.key = %d\n",
                     foo.x, foo.y, foo.key);
      OpenDDS::DCPS::ReceivedDataSample sample(0);

      sample.header_.message_length_ = sizeof(foo);
      sample.header_.message_id_ = OpenDDS::DCPS::SAMPLE_DATA;
      sample.header_.sequence_ = seq.getValue();

      // RepoIds are conventionally created and managed by the DCPSInfoRepo. Those
      // generated here are for the sole purpose of verifying internal behavior.
      OpenDDS::DCPS::RepoIdBuilder builder(sample.header_.publication_id_);

      builder.participantId(1);
      builder.entityKey(1);
      builder.entityKind(OpenDDS::DCPS::ENTITYKIND_OPENDDS_NIL_WRITER);

      sample.header_.source_timestamp_sec_ = static_cast<ACE_INT32>(now.sec());
      sample.header_.source_timestamp_nanosec_ = now.usec() * 1000;

      sample.sample_ = new ACE_Message_Block(sizeof(foo));

      ::OpenDDS::DCPS::Serializer ser(sample.sample_);
      ser << foo;

      dr_servant->data_received(sample);
    }
  } catch (const CORBA::Exception& ex) {
    ex._tao_print_exception("Exception caught in svc:");
  }
}
Exemplo n.º 7
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  ACE_Service_Config daemon;

  daemon.open (argv[0]);

  parse_args (argc, argv);

  if (child)
    {
      worker (n_iterations);

      ACE_OS::exit (exit_code);
    }

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t@%T) Process_Manager test.  Expect output from"
              "2 or 3 processes...\n"));

  ACE_Process_Manager::instance ()->register_handler
    (new ExitHandler ("default"));

  pid_t pid1 = respawn_self (argv[0],
                             n_iterations,
                             111);
  pid_t pid2 = respawn_self (argv[0],
                             n_iterations + 500,
                             222);

#if !defined (ACE_WIN32)
  pid_t pid3 = ACE_OS::fork ();

  if (!pid3)
    {
      worker (n_iterations);
      return 999;
    }
#endif /* ACE_WIN32 */

  ACE_Process_Manager::instance ()->register_handler (new ExitHandler ("specific"),
                                                      pid2);

  if (pid1 == ACE_INVALID_PID || pid2 == ACE_INVALID_PID)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "(%P|%t) %p\n",
                       "start_n"),
                      1);

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t@%T) Test parent waiting (synchronously, "
              "up to 6 seconds) for children...\n"));

  int result =
    ACE_Process_Manager::instance ()->wait (ACE_Time_Value (6));

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t@%T) Test parent: %d processes left\n",
              result));

  if (result > 0)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t@%T) Test parent waiting (synchronously, "
                  "indefinitely) for remaining children...\n"));
      result =
        ACE_Process_Manager::instance ()->wait ();
      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t@%T) Test parent finished waiting: %d\n",
                  result));
    }

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t@%T) Test parent: try auto-reap functions\n"));

  ACE_Process_Manager::instance ()->open (ACE_Process_Manager::DEFAULT_SIZE,
                                          ACE_Reactor::instance ());

  pid1 = respawn_self (argv[0],
                       n_iterations + 200,
                       333 );
  pid2 = respawn_self (argv[0],
                       n_iterations + 500,
                       444);

#if !defined (ACE_WIN32)
  pid3 = ACE_OS::fork ();

  if (!pid3)
    {
      worker (n_iterations);
      return 888;
    }
#endif /* ACE_WIN32 */

  ExitHandler *main_thread_work = 0;
  ACE_NEW_RETURN (main_thread_work,
                  ExitHandler ("main thread worker"),
                  1);

  ACE_Reactor::instance ()->schedule_timer (main_thread_work,
                                            0,
                                            ACE_Time_Value (2),
                                            ACE_Time_Value (1, 500000));
  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t@%T) Test parent: expect several Processes "
              "to be auto-detected over the next 30 seconds.\n"
              "The main thread will do some other work, too.\n" ));

  ACE_Time_Value briefly (30);

  result = ACE_Reactor::run_event_loop (briefly);

  ACE_DEBUG ((LM_DEBUG,
              "(%P|%t@%T) Test parent: finished (%d) %d.%d.  Close"
              "Process_Manager...\n",
              result,
              briefly.sec (),
              briefly.usec ()));

  ACE_Process_Manager::instance ()->close ();

  return 0;
}
Exemplo n.º 8
0
int
Client::svc (void)
{
  try
    {
      Octet_Seq octetSeq(SIZE_BLOCK);
      Char_Seq charSeq(SIZE_BLOCK);
      ACE_High_Res_Timer timer;
      ACE_OS::printf("Start sending %d Msgs...\n",this->niterations_);

      charSeq.length(SIZE_BLOCK);
      octetSeq.length(SIZE_BLOCK);

      // This sets up the connector, so that we do not incur
      // the overhead on the first call in the loop.
      server_->sendCharSeq (charSeq);

      timer.start ();

      ACE_UINT32 client_count = 0;
      for (ACE_UINT32 i = 0; i < this->niterations_; ++i)
        {
          client_count++;

          server_->sendCharSeq (charSeq);

          //server_->sendOctetSeq (octetSeq);

          //ACE_DEBUG ((LM_DEBUG, "."));
        }
      timer.stop ();

      ACE_Time_Value measured;
      timer.elapsed_time (measured);

      //ACE_DEBUG ((LM_DEBUG, "...finished\n"));

      time_t dur = measured.sec () * 1000000 + measured.usec ();
      if (dur == 0 || this->niterations_ == 0)
        ACE_DEBUG ((LM_DEBUG, "Time not measurable, calculation skipped\n"));
      else
      {
        ACE_DEBUG ((LM_DEBUG,
                    "Time for %u Msgs: %u usec\n",
                    this->niterations_,
                    dur));

        ACE_DEBUG ((LM_DEBUG, "Time for 1 Msg: %u usec, %u calls/sec\n",
                    dur / this->niterations_,
                    1000000 / (dur / this->niterations_)));
      }

      for (int c = 0; c < 10; ++c)
        server_->shutdown ();

    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("MT_Client: exception raised");
    }
  return 0;
}
Exemplo n.º 9
0
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  int n = 100;
  int low = 64;
  int hi = 4096;
  int s = 4;
  int quiet = 0;

  ACE_Get_Opt get_opt (argc, argv, ACE_TEXT("dn:l:h:s:q"));
  int opt;

  while ((opt = get_opt ()) != EOF)
    {
      switch (opt)
        {
        case 'd':
          TAO_debug_level++;
          break;
        case 'n':
          n = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 'l':
          low = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 'h':
          hi = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 's':
          s = ACE_OS::atoi (get_opt.opt_arg ());
          break;
        case 'q':
          quiet = 1;
          break;
        case '?':
        default:
          ACE_DEBUG ((LM_DEBUG,
                      "Usage: %s "
                      "-d debug"
                      "-l low "
                      "-h high "
                      "-s step "
                      "-n n "
                      "\n"
                      "Writes and then reads longs to a CDR stream "
                      "starting from <low> up to <high> incrementing "
                      "by <step>, at each step run <n> iterations to "
                      "average."
                      "\n",
                      argv[0]));
          return -1;
        }
    }

  for (int x = low; x <= hi; x += s)
    {
      ACE_High_Res_Timer writing;
      ACE_High_Res_Timer reading;
      if (TAO_debug_level > 0)
        ACE_DEBUG ((LM_DEBUG, "\nx= %d\n", x));

      for (int i = 0; i < n; ++i)
        {
          writing.start_incr ();
          TAO_OutputCDR output;

          if (test_write (output, x) != 0)
            {
              return 1;
            }
          writing.stop_incr ();

          reading.start_incr ();
          TAO_InputCDR input (output);
          if (test_read (input, x) != 0)
            {
              return 1;
            }
          reading.stop_incr ();
        }
      double m = n * x;

      ACE_Time_Value wtv;
      writing.elapsed_time_incr (wtv);
      ACE_hrtime_t wusecs = wtv.sec ();
      wusecs *= static_cast<ACE_UINT32> (ACE_ONE_SECOND_IN_USECS);
      wusecs += wtv.usec ();

      ACE_Time_Value rtv;
      reading.elapsed_time_incr (rtv);
      ACE_hrtime_t rusecs = rtv.sec ();
      rusecs *= static_cast<ACE_UINT32> (ACE_ONE_SECOND_IN_USECS);
      rusecs += rtv.usec ();

      double write_average = ACE_HRTIME_CONVERSION(wusecs) / m;
      double read_average = ACE_HRTIME_CONVERSION(rusecs) / m;
      if (!quiet)
        ACE_OS::printf ("AVE: %d %f %f\n",
                        x, write_average, read_average);
    }
  return 0;
}
Exemplo n.º 10
0
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
  ACE_Time_Value timeout (ACE_DEFAULT_TIMEOUT);

  //unsigned char selector = ACE_ATM_Addr::DEFAULT_SELECTOR;
  //int selector_specified = 0;

  if (argc > 2)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "Usage: %s [selector]\n",
                       argv[0]),
                      1);

  // Create a server address.
  ACE_ATM_Addr addr;
  //if (selector_specified)
  unsigned char selector = ( argc == 2 ) ? ACE_OS::atoi( argv[ 1 ]) : ACE_ATM_Addr::DEFAULT_SELECTOR;
  addr.set_selector( selector );
  ACE_OS::printf( "ATM_Server: selector changed to %d\n", addr.get_selector());


  // Create a server, reuse the addr.
  ACE_ATM_Acceptor  peer_acceptor;
  ACE_ATM_Params    params;

  // Not sure why but reuse_addr set to true/1 causes problems for
  // FORE/XTI/ATM - this is now handled in ACE_ATM_Acceptor::open()

  ACE_HANDLE ret = peer_acceptor.open (addr, 5, params);
  if ( ret == ACE_INVALID_HANDLE )
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%p\n",
                       "open"),
                      -1);

  ACE_ATM_Stream new_stream;
  ACE_ATM_Addr local_addr;

  local_addr.set_selector( selector );
  peer_acceptor.get_local_addr( local_addr );

  ACE_DEBUG ((LM_DEBUG,
              "starting server at address %s\n",
              local_addr.addr_to_string ()));

  // Performs the iterative server activities
  char buf[BUFSIZ];
  ACE_High_Res_Timer timer;
  int total;
  ACE_Time_Value tv;
  double real_time;
  double actual_rate;

  for (;;)
  {
    // Create a new ACE_ATM_Stream endpoint (note automatic restart
    // if errno == EINTR).
    ACE_OS::printf( "ATM_Server: expecting clients\n" );

    if (peer_acceptor.accept (new_stream,
                              &addr,
                              &timeout) == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  "%p\n",
                  "accept"));
      continue;
    }

    ACE_OS::printf( "ATM_Server: got a connection\n" );

    ACE_UINT16 vpi, vci;
    vpi = vci = 0;
    // This has problem on PMP connections on NT
    //new_stream.get_vpi_vci(vpi, vci);
    ACE_DEBUG ((LM_DEBUG,
                "connected to VPI %d VCI %d\n",
                vpi, vci));

    ACE_OS::printf( "ATM_Server: connection accepted\n" );

    ACE_DEBUG ((LM_DEBUG,
                "client %s connected\n",
                addr.addr_to_string ()));
    ACE_DEBUG ((LM_DEBUG,
                "client %s connected to host\n",
                new_stream.get_peer_name ()));

    // Read data from client (terminate on error).

    int recvd = 0;

    for ( ;; )
    {
      total = 0;
      timer.start_incr();

      for (int r_bytes;
           (r_bytes = new_stream.recv (buf, sizeof buf, 0)) > 0; )
        {
//        ACE_OS::printf( "ATM_Server: received %dB\n", r_bytes );

//        if (ACE_OS::write (ACE_STDOUT,
//                           buf,
//                           r_bytes) != r_bytes)
//          ACE_ERROR ((LM_ERROR,
//                      "%p\n",
//                      "ACE::send_n"));
          total += r_bytes;

          if ( total > 10000000 )
            break;
        }

      timer.stop_incr();
      timer.elapsed_time_incr( tv );
      real_time = tv.sec() * ACE_ONE_SECOND_IN_USECS + tv.usec();
      recvd += total;
      actual_rate = ( double )recvd * ( double )8 / real_time;

      ACE_DEBUG ((LM_DEBUG,
                 ACE_TEXT ("(%t) bytes = %d, usec = %f, rate = %0.00f Mbps\n"),
                 recvd,
                 real_time,
                 actual_rate < 0 ? 0 : actual_rate ));
    }

    // Close new endpoint (listening endpoint stays open).
    if (new_stream.close () == -1)
      ACE_ERROR ((LM_ERROR,
                  "%p\n",
                  "close"));
  }

  /* NOTREACHED */
  return 0;
}
Exemplo n.º 11
0
int
Timer_Helper::handle_timeout (const ACE_Time_Value &,
                              const void *)
{
  int no_of_servers = 0;
  CORBA::ULongLong sum = 0;

  // The following are used to keep a track of the inaccuracy
  // in synchronization.
  CORBA::ULongLong lowest_time = ACE_UINT64_LITERAL (0xFFFFFFFFFFFFFFFF);
  CORBA::ULongLong highest_time  = 0;

  try
    {
      IORS::TYPE* value;
      for (IORS::ITERATOR server_iterator (this->clerk_->server_);
           server_iterator.next (value) != 0;
           server_iterator.advance ())
        {
          // This is a remote call.
          CosTime::UTO_var UTO_server =
            (*value)->universal_time ();

          if (TAO_debug_level > 0)
            ORBSVCS_DEBUG ((LM_DEBUG,
                        "\nTime = %Q\nInaccuracy = %Q\nTimeDiff = %d\nstruct.time = %Q\n"
                        "struct.inacclo = %d\nstruct.inacchi = %d\nstruct.Tdf = %d\n",
                        UTO_server->time (),
                        UTO_server->inaccuracy (),
                        UTO_server->tdf (),
                        (UTO_server->utc_time ()).time,
                        (UTO_server->utc_time ()).inacclo,
                        (UTO_server->utc_time ()).inacchi,
                        (UTO_server->utc_time ()).tdf));

          CORBA::ULongLong curr_server_time =
            UTO_server->time ();

          sum += curr_server_time;

          ++no_of_servers;

          // Set the highest time to the largest time seen so far.
          if (curr_server_time > highest_time)
            highest_time = curr_server_time;

          // Set the lowest time to the smallest time seen so far.
          if (curr_server_time < lowest_time)
            lowest_time = curr_server_time;

        }

      if (TAO_debug_level > 0)
        ORBSVCS_DEBUG ((LM_DEBUG,
                    "\nUpdated time from %d servers in the network",
                    no_of_servers));

      // Return the average of the times retrieved from the various
      // servers.
      clerk_->time_ = sum / no_of_servers ;

      // Set the Time Displacement Factor. The TZ environment variable is
      // read to set the time zone. We convert the timezone value from seconds
      // to minutes.

      ACE_OS::tzset ();
      long arg = ACE_OS::timezone () / 60;
      CORBA::Short goodarg = static_cast<CORBA::Short> (arg);
      clerk_->time_displacement_factor (goodarg);

      // Set the inaccuracy.
      if (highest_time > lowest_time)
        clerk_->inaccuracy (highest_time - lowest_time);
      else
        clerk_->inaccuracy (0);

      const ACE_Time_Value timeofday = ACE_OS::gettimeofday ();

      // Record the current time in a timestamp to know when global
      // updation of time was done.
      clerk_->update_timestamp_ =
        static_cast<CORBA::ULongLong> (timeofday.sec ()) *
        static_cast<ACE_UINT32> (10000000) +
        static_cast<CORBA::ULongLong> (timeofday.usec () * 10);
    }
  catch (const CORBA::Exception& ex)
    {
      if (TAO_debug_level > 0)
        ex._tao_print_exception ("Exception in handle_timeout()\n");

      return -1;
    }

  return 0;
}
  // reads incoming packets from the canBus connection and stores the values
  // in the local (class internal) variables.
  void
  Consumer::handleMessage(const Miro::DevMessage * _message)
  {
    const Can::Message& message = *((Can::Message*)_message);
    int versNr, versSub;

    connection->boardReply = 1;

    Can::Parameters *CanParams = new Can::Parameters();

    CanId msgID = message.id();

    if (CanParams->module == "pcan")
       msgID = (msgID | 0x80000000);

    switch (msgID) {

      // Motor Messages

    case CAN_R_MOTOR_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE, 
	       "Consumer::receiveThread:  received message: MOTOR_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "MOTOR_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "MOTOR_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(motorAliveMutex);
      motorAliveCond.broadcast();
      break;
    }

    case CAN_R_GET_ACCELS: 
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "Consumer::receiveThread:  received message: GET_ACCELS");

      // Odometry Messages
    case CAN_R_GET_POS:
      if (pOdometry_) {
	// get data
	xPos_ = message.shortData(0);
	yPos_ = message.shortData(2);
	phi_ = ticks2rad(message.shortData(4));

	// the goalie is special
	if (params_->goalie) {
	  std::swap(xPos_, yPos_);
	  yPos_ *= -1;

	  xPos_ += (short)(125 * cos(phi_) + 85 *  sin(phi_));
	  yPos_ += (short)(125 * sin(phi_) - 85 *  cos(phi_));

	}

	double dx = (short)(xPos_ - xPrev_);
	double dy = (short)(yPos_ - yPrev_);

	x_ += dx;
	y_ += dy;
	double dPhi = phi_ - phiPrev_;

	xPrev_ = xPos_;
	yPrev_ = yPos_;
	phiPrev_ = phi_;

	// fill motion status data struct
	double deltaT = 1000. / (double) (params_->odometryPulse.msec());
	Miro::timeA2C(message.time(), status_.time);
	status_.position.point.x = x_ * params_->transFactor;
	status_.position.point.y = y_ * params_->transFactor;
	status_.position.heading = phi_;
	status_.velocity.translation = (long) rint(sqrt(dx * dx + dy * dy) * deltaT);
	status_.velocity.rotation = dPhi * deltaT;

	pOdometry_->integrateData(status_);
	break;
      }

    case 0x82820201: { // DISTANCE LR
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE, 
		    "Consumer::receiveThread:  received message: DISTANCE LR "
		    << message.shortData(0) << "  "
		    << message.shortData(2));

      Miro::Guard guard(distanceLRMutex);
      distanceL = message.shortData(0);
      distanceR = message.shortData(2);
      distanceLRCond.broadcast();
      break;
    }

    case CAN_R_ODO_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE, 
	       "Consumer::receiveThread:  received message: ODO_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "ODO_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "ODO_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(odoAliveMutex);
      odoAliveCond.broadcast();
      break;
    }
      // Port Messages

    case CAN_R_READ_PORTS: { // DIGITAL
      MIRO_DBG(SPARROW, LL_PRATTLE,
	       "Consumer::receiveThread:  received message: DIGITAL ");

      Miro::Guard guard(digitalMutex);
      for (int i = 1; i >= 0; --i) {
	if ( ((message.byteData(1) ^ digital[1]) & (0x01 << i)) && pButtons_) {
	  ACE_Time_Value t = ACE_OS::gettimeofday();
	  ButtonStatusIDL * pEvent = new ButtonStatusIDL();
	  pEvent->time.usec = t.usec();
	  pEvent->time.sec = t.sec();
	  pEvent->number = i;
	  pEvent->event = (message.byteData(1) & (0x01 << i))?
	    Miro::Button::ON_RELEASE : Miro::Button::ON_PRESS;
	  pButtons_->pushEvent(pEvent);
	}
      }

      for (int i = 7; i >= 0; --i) {
	digital[i] = message.byteData(i);
      }

      digitalCond.broadcast();
      break;
    }

    case CAN_R_READ_ANALOG: {
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "Consumer::receiveThread:  received message: ANALOG "
		    << message.shortData(0) << "  "
		    << message.shortData(2));

      Miro::Guard guard(analogMutex);
      analog[message.shortData(0)]= message.shortData(2);
      analogCond.broadcast();
      break;
    }

    case CAN_R_PORTS_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE, 
	       "Consumer::receiveThread:  received message: PORTS_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "PORTS_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "PORTS_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(portsAliveMutex);
      portsAliveCond.broadcast();
      break;
    }

      // Stall Messages

    case CAN_R_STALL:
      connection->stallTimerStart();
      if (pStall_)
	pStall_->pushEvent();
      break;

    case CAN_R_STALL_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE,
	       "Consumer::receiveThread:  received message: STALL_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "STALL_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "STALL_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(stallAliveMutex);
      stallAliveCond.broadcast();
      break;
    }

      // Kicker Messages

    case CAN_R_KICK_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE,
	       "Consumer::receiveThread:  received message: KICK_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "KICK_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "KICK_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(kickerAliveMutex);
      kickerAliveCond.broadcast();
      break;
    }

      // Servo Messages

    case CAN_R_SERVO_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE, 
	       "Consumer::receiveThread:  received message: SERVO_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "SERVO_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "SERVO_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(servoAliveMutex);
      servoAliveCond.broadcast();
      break;
    }

      // Infrared Messages:

    case CAN_R_IR_GET_CONT:
      MIRO_DBG(SPARROW, LL_PRATTLE,
	       "Consumer::receiveThread: receiveThread message: IR_CONT");

      if (pIR_) {
	Sparrow::Parameters * param = Sparrow::Parameters::instance(); //uli
	long calRange;
	Miro::RangeGroupEventIDL * data = new Miro::RangeGroupEventIDL();
	Miro::timeA2C(message.time(), data->time);
	data->group = 0;
	data->range.length(8);
	for (int i = 7; i >= 0; --i)  {
	  if (message.charData(i) != -1) {

	    calRange = ((int)message.charData(i) * 10 - param->irScaling[i].offset);
	    calRange = calRange - param->irScaling[i].minDistance;
	    calRange = (long) (calRange * param->irScaling[i].scaling);
	    calRange = calRange + param->irScaling[i].minDistance ;
	    if ((calRange < param->irScaling[i].minDistance) ||
		(calRange > param->irScaling[i].maxDistance)) {
	      calRange = -1;
	    }
	  }
	  else {
	    calRange = -1;
	  }
	  data->range[i] = calRange;
	}
	pIR_->integrateData(data);
      }
      break;

    case CAN_R_IR_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE,
	       "Consumer::receiveThread:  received message: IR_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "IR_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "IR_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(irAliveMutex);
      irAliveCond.broadcast();
      break;
    }
      // Debug Messages

    case CAN_R_DBG_PRINT:
      for (int k = 0; k < std::min(message.length(), 8); ++k)
	//if (message.canMessage()->d[k] != 0)
	//  cout << message.canMessage()->d[k] << flush;
      break;

    case CAN_R_DBG_ALIVE: {
      MIRO_DBG(SPARROW, LL_PRATTLE,
	       "Consumer::receiveThread:  received message: DBG_ALIVE");

      versSub = message.shortData(0);
      versNr = versSub >> 4;
      versSub = versSub & 0x0F; // versNr loeschen mit AND 00001111
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "DBG_ALIVE_VERSION: "<< versNr << "." << versSub);
      MIRO_DBG_OSTR(SPARROW, LL_PRATTLE,
		    "DBG_TIME_STAMP (sec): " << message.shortData(2));
      Miro::Guard guard(dbgAliveMutex);
      dbgAliveCond.broadcast();
      break;
    }

    default:
      MIRO_LOG_OSTR(LL_ERROR, 
		    "SparrowConsumer: Unhandled can bus message: " << message);
    }
  }
Exemplo n.º 13
0
int run_domain_test ()
{
  ::DDS::ReturnCode_t ret;

  // create participant
  ::DDS::DomainParticipant_var new_dp
    = dpf->create_participant(MY_DOMAIN,
                              PARTICIPANT_QOS_DEFAULT,
                              ::DDS::DomainParticipantListener::_nil (),
                              ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  TEST_CHECK (! CORBA::is_nil (new_dp.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(! CORBA::is_nil (new_dp.in ()))")
    ACE_TEXT("\n")
  ));

  ::DDS::DomainId_t domain_id
    = new_dp->get_domain_id ();

  TEST_CHECK (domain_id == MY_DOMAIN);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(domain_id == MY_DOMAIN)")
    ACE_TEXT("\n")
  ));

  MyTypeSupport_var fts (new MyTypeSupportImpl);

  if (::DDS::RETCODE_OK != fts->register_type(new_dp.in (), MY_TYPE))
    {
      ACE_ERROR ((LM_ERROR,
      ACE_TEXT ("Failed to register the FooTypeSupport.")));
      return 1;
    }

  // lookup existent participant
  ::DDS::DomainParticipant_var looked_dp
    = dpf->lookup_participant(MY_DOMAIN);

  OpenDDS::DCPS::DomainParticipantImpl* new_dp_servant
    = dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(new_dp.in());

  OpenDDS::DCPS::DomainParticipantImpl* looked_dp_servant
    = dynamic_cast<OpenDDS::DCPS::DomainParticipantImpl*>(looked_dp.in ());

  TEST_CHECK (looked_dp_servant == new_dp_servant);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(looked_dp_servant == new_dp_servant)")
    ACE_TEXT("\n")
  ));

  // create topic
  ::DDS::Topic_var new_topic
    = new_dp->create_topic(MY_TOPIC,
                           MY_TYPE,
                           TOPIC_QOS_DEFAULT,
                           ::DDS::TopicListener::_nil (),
                           ::OpenDDS::DCPS::DEFAULT_STATUS_MASK);

  OpenDDS::DCPS::TopicImpl* new_topic_servant
    = dynamic_cast<OpenDDS::DCPS::TopicImpl*>(new_topic.in ());

  ::DDS::Duration_t timeout;
  timeout.sec = static_cast<long>(find_topic_timeout.sec ());
  timeout.nanosec = find_topic_timeout.usec ();

  // find existent topic
  ::DDS::Topic_var found_topic
    = new_dp->find_topic(MY_TOPIC, timeout);

  ::OpenDDS::DCPS::TopicImpl* found_topic_servant
    = dynamic_cast<OpenDDS::DCPS::TopicImpl*>
    (found_topic.in ());

  TEST_CHECK (new_topic_servant == found_topic_servant);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(new_topic_servant == found_topic_servant)")
    ACE_TEXT("\n")
  ));

  // find existent topicdescription
  ::DDS::TopicDescription_var found_topicdescription
    = new_dp->lookup_topicdescription(MY_TOPIC);

  TEST_CHECK (! CORBA::is_nil (found_topicdescription.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(! CORBA::is_nil (found_topicdescription.in ()))")
    ACE_TEXT("\n")
  ));

  // widen the topicdescription to topic
  ::DDS::Topic_var widened_topic
    = ::DDS::Topic::_narrow(found_topicdescription.in ());

  TEST_CHECK (! CORBA::is_nil (widened_topic.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(! CORBA::is_nil (widened_topic.in ()))")
    ACE_TEXT("\n")
  ));

  ACE_ERROR((LM_ERROR,
    "We expect to see an error message from delete_participant\n"));
  ret = dpf->delete_participant(new_dp.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_PRECONDITION_NOT_MET);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_PRECONDITION_NOT_MET)")
    ACE_TEXT("\n")
  ));

  // delete existent topic first time
  ret = new_dp->delete_topic(found_topic.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_OK);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_OK)")
    ACE_TEXT("\n")
  ));

  // delete existent topic second time
  ret = new_dp->delete_topic(new_topic.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_OK);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_OK)")
    ACE_TEXT("\n")
  ));

  // an extra delete existent topic
  ACE_ERROR((LM_ERROR,
    "We expect to see an error message from delete_topic\n"));
  ret = new_dp->delete_topic(new_topic.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_ERROR);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_ERROR)")
    ACE_TEXT("\n")
  ));

  // Look up the topicdescription after the topic is deleted will
  // return nil.
  found_topicdescription
    = new_dp->lookup_topicdescription(MY_TOPIC);

  TEST_CHECK (CORBA::is_nil(found_topicdescription.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(CORBA::is_nil(found_topicdescription.in ()))")
    ACE_TEXT("\n")
  ));

  // find a non-existent topic - return nil
  ACE_High_Res_Timer timer;
  ACE_Time_Value elapsedTime(0, 0);
  timer.start ();
  found_topic = new_dp->find_topic(OTHER_TOPIC, timeout);
  timer.stop();
  timer.elapsed_time(elapsedTime);
  ACE_Time_Value tenMillis (0, 10000);
  elapsedTime += tenMillis;
  // some systems can be short by up to 10 milliseconds
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(CORBA::is_nil(found_topic.in ()) && elapsedTime.msec() >= find_topic_timeout.msec())")
    ACE_TEXT("\n")
  ));

  // delete the existent participant
  ret = dpf->delete_participant(new_dp.in ());

  TEST_CHECK (ret == ::DDS::RETCODE_OK);
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(ret == ::DDS::RETCODE_OK)")
    ACE_TEXT("\n")
  ));

  // lookup the participant after it's deleted - return nil
  looked_dp = dpf->lookup_participant(MY_DOMAIN);

  TEST_CHECK (CORBA::is_nil(looked_dp.in ()));
  ACE_DEBUG((LM_DEBUG,
    ACE_TEXT("(%P|%t) run_domain_test: ")
    ACE_TEXT("(CORBA::is_nil(looked_dp.in ()))")
    ACE_TEXT("\n")
  ));

  return 0;
}
Exemplo n.º 14
0
Arquivo: RTP.cpp Projeto: asdlei00/ACE
int
TAO_AV_RTP_Object::send_frame (const iovec *iov,
                               int iovcnt,
                               TAO_AV_frame_info *frame_info)
{
  int result = -1;
  RTP_Packet *rtp_packet = 0;
  ACE_UINT32 csrc_count = 0;  // Assume for now no mixers/translators
  ACE_UINT32 *csrc_list = 0;

  if (this->connection_gone_)
    {
      errno = ECONNRESET;
      return -1;
    }

  if (frame_info != 0)
    {
      if (frame_info->format != this->format_)
        ORBSVCS_DEBUG ((LM_DEBUG,
                    "TAO_AV_RTP_Object::send_frame - error: format type mismatch"));
      this->sequence_num_ = static_cast<ACE_UINT16> (frame_info->sequence_num);
      if (frame_info->ssrc != 0)
        this->ssrc_ = frame_info->ssrc;

      TAO_AV_RTCP_Object *rtcp_prot_obj = dynamic_cast<TAO_AV_RTCP_Object*> (this->control_object_);
      // set the ssrc on the control object so the RTCP traffic can be matched
      // to the RTP traffic
      rtcp_prot_obj->ssrc(this->ssrc_);
      ACE_UINT16 data_size = static_cast<ACE_UINT16> (iov[0].iov_len);

      ACE_NEW_RETURN (rtp_packet,
                      RTP_Packet (0,                            // padding
                                  frame_info->boundary_marker,  // marker
                                  static_cast<unsigned char> (this->format_),                // payload type
                                  frame_info->sequence_num,     // sequence num
                                  frame_info->timestamp,        // time stamp
                                  this->ssrc_,                  // ssrc
                                  static_cast<unsigned char> (csrc_count),                   // csrc count
                                  csrc_list,                    // csrc list
                                  (char *)iov[0].iov_base,      // data
                                  data_size),                   // data size
                                  -1);

      frame_info->sequence_num ++;
    }
  else
    {
      // TODO: For periodic RTP packets (constant rate), the RFC suggests
      //       increasing the clock by the number of samples each frame rather
      //       than relying on the system time

      // The RFC specifies at least one timestamp unit per sample as well as a
      //  random offset.  It used to be in milliseconds so I left it that way
      //  for non-audio streams.

      unsigned int samples_per_sec;
      double samples_per_usec;

      switch (this->format_)
      {
        case RTP_PT_PCMU:
        case RTP_PT_CELP:
        case RTP_PT_G721:
        case RTP_PT_GSM:
        case RTP_PT_DVI:
        case RTP_PT_LPC:
        case RTP_PT_PCMA:
        case RTP_PT_G722:
          samples_per_sec = 8000;
          break;
        case RTP_PT_L16_STEREO:
        case RTP_PT_L16_MONO:
          samples_per_sec = 44100;
          break;
        default:
          samples_per_sec = 1000000;
      };

      samples_per_usec = samples_per_sec/1000000.0;

      ACE_Time_Value now = ACE_OS::gettimeofday();

      ACE_UINT32 ts = (ACE_UINT32)
                      (now.sec () * samples_per_sec +
                       ((double)now.usec () * samples_per_usec) +
                       this->timestamp_offset_);
      ACE_UINT16 data_size = static_cast<ACE_UINT16> (iov[0].iov_len);

      ACE_NEW_RETURN (rtp_packet,
                      RTP_Packet (0,                            // padding
                                  0,                            // marker
                                  static_cast<unsigned char> (this->format_),                // payload type
                                  this->sequence_num_,          // sequence num
                                  ts,                           // time stamp
                                  this->ssrc_,                  // ssrc
                                  static_cast<unsigned char> (csrc_count),                   // csrc count
                                  csrc_list,                    // csrc list
                                  (char *)iov[0].iov_base,      // data
                                  data_size),                   // data size
                                  -1);

      this->sequence_num_ ++;
    }

  char *data_ptr;
  ACE_UINT16 data_length;
  rtp_packet->get_packet_data (&data_ptr, data_length);

  iovec send_iov[ACE_IOV_MAX];
  send_iov [0].iov_base = data_ptr;
  send_iov [0].iov_len  = data_length;
  for (int i=1;i<iovcnt; i++)
    send_iov [i] = iov [i];
  result = this->transport_->send (send_iov, iovcnt);

  delete rtp_packet;

  if (result < 0)
    ORBSVCS_ERROR_RETURN ((LM_ERROR,"TAO_AV_RTP::send_frame failed\n"),result);

  return 0;
}
Exemplo n.º 15
0
static int
run_test (int disable_notify_pipe,
          const ACE_Time_Value &tv)
{
  // Create special reactors with the appropriate flags enabled.

  ACE_Select_Reactor *reactor_impl = 0;
  if (disable_notify_pipe)
    ACE_NEW_RETURN (reactor_impl,
                    ACE_Select_Reactor (0, 0, 1),
                    -1);
  else
    ACE_NEW_RETURN (reactor_impl,
                    ACE_Select_Reactor,
                    -1);

  ACE_Reactor *reactor;
  ACE_NEW_RETURN (reactor,
                  ACE_Reactor (reactor_impl, 1),    // Delete implementation
                  -1);

  // Make sure this stuff gets cleaned up when this function exits.
  auto_ptr<ACE_Reactor> r (reactor);

  // Set the Singleton Reactor.
  ACE_Reactor *orig_reactor = ACE_Reactor::instance (reactor);
  ACE_TEST_ASSERT (ACE_LOG_MSG->op_status () != -1);
  ACE_TEST_ASSERT (ACE_Reactor::instance () == reactor);

  Supplier_Task task (disable_notify_pipe,
                      tv);
  ACE_TEST_ASSERT (ACE_LOG_MSG->op_status () != -1);

  int result;

  result = task.open ();
  ACE_TEST_ASSERT (result != -1);

  if (tv.sec () == LONG_TIMEOUT)
    // Sleep for a while so that the <ACE_Reactor>'s notification
    // buffers will fill up!
    ACE_OS::sleep (tv);

  int shutdown = 0;

  // Run the event loop that handles the <handle_output> and
  // <handle_exception> notifications.
  for (int iteration = 1;
       shutdown == 0;
       iteration++)
    {
      ACE_Time_Value timeout (tv);

      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("(%t) starting handle_events() on iteration %d")
                  ACE_TEXT (" with time-out = %d seconds\n"),
                  iteration,
                  timeout.sec ()));

      // Use a timeout to inform the Reactor when to shutdown.
      switch (ACE_Reactor::instance ()->handle_events (timeout))
        {
        case -1:
          if (! disable_notify_pipe)
            ACE_ERROR ((LM_ERROR,
                        ACE_TEXT ("(%t) %p\n"),
                        ACE_TEXT ("reactor")));
          shutdown = 1;
          break;
          /* NOTREACHED */
        case 0:
          ACE_DEBUG ((LM_DEBUG,
                      ACE_TEXT ("(%t) handle_events timed out\n")));
          shutdown = 1;
          break;
          /* NOTREACHED */
        default:
          break;
          /* NOTREACHED */
        }
    }

  if (tv.sec () == LONG_TIMEOUT)
    {
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("(%t) releasing supplier task thread\n")));
      task.release ();
    }
  ACE_Reactor::instance (orig_reactor);
  return 0;
}
Exemplo n.º 16
0
inline RtecScheduler::Period_t time_val_to_period (const ACE_Time_Value &tv)
{
  //100s of nanoseconds
  return static_cast<RtecScheduler::Period_t> (tv.sec () * 1000000 + tv.usec ())*10;
}
Exemplo n.º 17
0
  bool
  XML_Saver::open(const ACE_TString & base_name, size_t backup_count)
  {
    this->base_name_ = base_name;
    this->backup_count_ = backup_count;
    if (base_name ==  ACE_TEXT("cout"))
    {
      this->output_ = stdout;
      this->close_out_ = false;
    }
    else if (base_name ==  ACE_TEXT("cerr"))
    {
      this->output_ = stderr;
      this->close_out_ = false;
    }
    else
    {
      ACE_TString file_name = base_name;
      file_name += ACE_TEXT(".new");

      this->output_ = ACE_OS::fopen (file_name.c_str(), ACE_TEXT("wb"));
      if (this->output_) {
        this->close_out_ = true;
      } else {
        ORBSVCS_ERROR ((LM_ERROR,
          ACE_TEXT ("(%P|%t) XML_Saver unable to open %s\n"),
            base_name.c_str()));
      }
    }
    if (this->output_ != 0)
    {
      FILE * const out = this->output_;

      ACE_OS::fprintf (out, "<?xml version=\"1.0\"?>\n");

      try
      {
        bool changed = true;
        NVPList attrs;

        ACE_Time_Value const now = ACE_High_Res_Timer::gettimeofday();

        ACE_UINT64 nowus = now.usec();
        static const ACE_UINT64 USECSPERSEC = 1000 * 1000;
        ACE_UINT64 const tmpus = now.sec();
        nowus += tmpus * USECSPERSEC;

        ACE_TCHAR nowusstr[128];
        ACE_OS::sprintf(nowusstr, ACE_UINT64_FORMAT_SPECIFIER, nowus);

        attrs.push_back(NVP("version", "1.0"));
        if (this->timestamp_)
        {
          attrs.push_back(NVP("timestamp", ACE_TEXT_ALWAYS_CHAR(nowusstr)));
        }
        this->begin_object(0, "notification_service", attrs, changed);
      }
      catch (const CORBA::Exception& ex)
      {
        ex._tao_print_exception (
          ACE_TEXT (
            "(%P|%t) XML_Saver Unknown exception\n"));
        if (this->close_out_ && this->output_ != 0)
          {
            (void) ACE_OS::fclose (this->output_);
          }

        this->output_ = 0;
      }
    }
    return this->output_ != 0;
  }