bool doubleTouchThread::checkMotionDone()
{
    if (step == 7 || (record == 0 && (step == 4 || step == 5)))
        return true;
    
    iencsL->getEncoders(encsL->data());
    Vector qL=encsL->subVector(0,6);
    armL->setAng(qL*iCub::ctrl::CTRL_DEG2RAD);
    Vector eeL = armL -> EndEffPosition();

    iencsR->getEncoders(encsR->data());
    Vector qR=encsR->subVector(0,6);
    armR->setAng(qR*iCub::ctrl::CTRL_DEG2RAD);
    Vector eeR = armR -> EndEffPosition();

    double normL = norm(eeL - oldEEL);
    double normR = norm(eeR - oldEER);
    printMessage(4,"step: %i  result: %i  normL: %g\tnormR: %g\n", step,
        (normL <= VEL_THRES * (1000.0*getPeriod())) && (normR <= VEL_THRES * (1000.0*getPeriod())), normL, normR);

    oldEEL = eeL;
    oldEER = eeR;

    if ((normL <= VEL_THRES * (1000.0*getPeriod())) && (normR <= VEL_THRES * (1000.0*getPeriod()))) {
        return true;
    }

    return false;
}
Beispiel #2
0
void CompositionDBG::recurrentNoisyChange(){ 
	for (int i=0;i<m_numPeaks; i++) copy(mpp_peak[i],mpp_peak[i]+m_numDim,mpp_prePeak[i]);
	copy(mp_height,mp_height+m_numPeaks,mp_preHeight);
	copy(mp_width,mp_width+m_numPeaks,mp_preWidth);

	double initial_angle;
	double height_range=m_maxHeight-m_minHeight;

	double noisy;
	for(int i=0;i<m_numPeaks;i++){
	    if(mp_whetherChange[i]==false) continue;
		initial_angle=(double)getPeriod()*i/m_numPeaks;

		 mp_height[i]=sinValueNoisy(m_changeType.counter,m_minHeight,m_maxHeight,height_range,initial_angle,m_noisySeverity);
	}

	initial_angle=OFEC_PI*(sin(2*OFEC_PI*(m_changeType.counter)/m_period)+1)/12.;
	noisy=m_noisySeverity*Global::msp_global->mp_normalPro->Next();
	positionStandardChange(initial_angle+noisy);

    restoreInfor();
	calculateGlobalOptima();
	 updateNumberofChanges();
	m_changeType.counter++;
}
    void handleNodeStatus(const ReceivedDataStructure<protocol::NodeStatus>& msg)
    {
        if (!needToQuery(msg.getSrcNodeID()))
        {
            return;
        }

        NodeData* data = node_map_.access(msg.getSrcNodeID());
        if (data == NULL)
        {
            trace(TraceDiscoveryNewNodeFound, msg.getSrcNodeID().get());

            data = node_map_.insert(msg.getSrcNodeID(), NodeData());
            if (data == NULL)
            {
                getNode().registerInternalFailure("NodeDiscoverer OOM");
                return;
            }
        }
        UAVCAN_ASSERT(data != NULL);

        if (msg.uptime_sec < data->last_seen_uptime)
        {
            trace(TraceDiscoveryNodeRestartDetected, msg.getSrcNodeID().get());
            data->num_get_node_info_attempts = 0;
        }
        data->last_seen_uptime = msg.uptime_sec;

        if (!isRunning())
        {
            startPeriodic(MonotonicDuration::fromMSec(TimerPollIntervalMs));
            trace(TraceDiscoveryTimerStart, getPeriod().toUSec());
        }
    }
void parseScoringEvents(std::string page, std::vector<ScoringEvent> *scoringEvents, Game *game, League *league){

	/*
	For goals, we dont' want anything above the scoring summary, or below the next </table>
	*/
	std::string goals = split(page, "Scoring Summary")[1];
	goals = split(goals, "</table>")[0];

	/*
	Split by </td> to break up the periods. The first and last elements are garbage, just toss them.
	*/
	std::vector<std::string> goalVec = split(goals, "</td>");
	goalVec.erase(goalVec.begin());
	goalVec.erase(goalVec.end());

	/*
	Go through and remove the opening <td> tag now from every element, it's unnecessary.
	*/
	for(int i = 0; i < goalVec.size(); i++){
		goalVec[i] = extract(goalVec[i] + "</td>", "td");
	}


	/*
	Cycle through goals by period
	*/
	for(int i = 0; i < goalVec.size(); i+=2){

		/*
		Only if there was a goal in that period
		*/

		if(goalVec[i+1].find("(no scoring)") == std::string::npos ){

			/*
			Get the actual number for this period
			*/
			int per = getPeriod(goalVec[i]);

			/*
			If there are more than one goals in that period, split them up and process them seperately.
			If there is only one goal, process it directly.
			*/
			if(goalVec[i+1].find("<tr>") != std::string::npos){
				std::vector<std::string> firstsplit = split(goalVec[i+1], "<tr>");
				for(int n = 0; n < firstsplit.size(); n++){
					/*
					If it wasn't the first goal of the period, there will be another <td> tag on it. We can't have that, so strip it off.
					*/
					if(firstsplit[n].find("<td") != std::string::npos)
						firstsplit[n] = extract(firstsplit[n], "td");
					scoringEvents->push_back(processGoal(game, league, per, firstsplit[n]));
				}
			}else{
				scoringEvents->push_back(processGoal(game, league, per, goalVec[i+1]));
			}
		}
	}
}
void parsePenaltyEvents(std::string page, std::vector<PenaltyEvent> *penaltyEvents, Game *game, League *league){
  /*
  For Penalties, delete everything above the "Penalties" header. Once again, delete all that follows </table>.
  */
  std::string penalties = split(page, "Penalties")[1];
  penalties = split(penalties, "</table>")[0];

  /*
  Split by </td> to break up the periods. The first and last elements are garbage, just toss them.
  */
  std::vector<std::string> penVec = split(penalties, "</td>");
  penVec.erase(penVec.begin());
  penVec.erase(penVec.end());

  /*
  Go through and remove the opening <td> tag now from every element, it's unnecessary.
  */
  for(int i = 0; i < penVec.size(); i++){
    penVec[i] = extract(penVec[i] + "</td>", "td");
  }


  /*
  Cycle through penalties by period
  */
  for(int i = 0; i < penVec.size()-1; i+=2){

    /*
    Only if there was a penalty in that period
    */

    if(penVec[i+1].find("(no penalties)") == std::string::npos ){

      /*
      Get the actual number for this period
      */
      int per = getPeriod(penVec[i]);

      /*
      If there is more than one penalty in that period, split them up and process them seperately.
      If there is only one penalty process it directly.
      */
      if(penVec[i+1].find("<tr>") != std::string::npos){
        std::vector<std::string> firstsplit = split(penVec[i+1], "<tr>");
        for(int n = 0; n < firstsplit.size(); n++){
          /*
          If it wasn't the first penalty of the period, there will be another <td> tag on it. We can't have that, so strip it off.
          */
          if(firstsplit[n].find("<td") != std::string::npos)
            firstsplit[n] = extract(firstsplit[n], "td");
          penaltyEvents->push_back(processPenalty(game, league, per, firstsplit[n]));
        }
      }else{
        processPenalty(game, league, per, penVec[i+1]);
        penaltyEvents->push_back(processPenalty(game, league, per, penVec[i+1]));
      }
    }
  }
}
Beispiel #6
0
void Task::execute(void) {
	pid_t pid, wait_return;
	int wait_status;

	pid = fork();
	if (pid == -1) {
		perror("fork");
		exit(EXIT_FAILURE);
	}

	// forked task
	if (pid == 0) {

		printf( "executing time and rtspin " );
		char wcet[20];
		char period[20];
		char duration[20];
		sprintf(wcet,"%d",getExecCost());
		sprintf(period,"%d",getPeriod());
		sprintf(duration,"%d",getTestingDuration());
		
		execl( TIME_PATH, TIME_BIN,
		       "-f",
		       " \"%P\" ",
		       "-o",
		       // "cpuusagefile",
		       TS_CPU_U_F,
		       "-a",
		       RTSPIN_PATH, 
		       "-w",
		       wcet,
		       period,
		       duration,
		       (char *) NULL );

		// char wcet[20];
		// char period[20];
		// char cnt[20];
		// sprintf(wcet,"%d",10);
		// sprintf(period,"%d",100);
		// sprintf(cnt,"%d",1000);


		// execl( "./base_task","base_task",
		//        wcet,
		//        period,
		//        cnt,		       
		//        (char *) NULL );

		perror( "could not execute time or rtspin " );

		exit(EXIT_FAILURE);

	} else { 		// parent
		// Save child pid to wait for.
		setWaitReturn(pid);
	}

}
NABoolean
ComSqlTextHandle::isPeriod(const char &aChar) const
{
  if (aChar EQU getPeriod())
  {
    return TRUE;
  }
  return FALSE;
}
Beispiel #8
0
void BarForm::init(QString symbol, QString exchange, int period)
{
    symbol_ = symbol;
    exchange_ = exchange;
    period_ = period;

    this->setWindowTitle(QString("history-bar-") + symbol_ + QString("-") + getPeriod());
    on_first128_clicked();
}
::Ice::DispatchStatus
RoboCompCommonBehavior::CommonBehavior::___getPeriod(::IceInternal::Incoming& __inS, const ::Ice::Current& __current)
{
    __checkMode(::Ice::Idempotent, __current.mode);
    __inS.is()->skipEmptyEncaps();
    ::IceInternal::BasicStream* __os = __inS.os();
    ::Ice::Int __ret = getPeriod(__current);
    __os->write(__ret);
    return ::Ice::DispatchOK;
}
Beispiel #10
0
extern int
rotate(void) {
	int rotation = getRotation() + 1;
	if (rotation >= MAX_ROTATIONS)  // TODO: Should we use this to indicate the last rotation is now complete?  Maybe if agents are clearing feedback msgs anyway
		rotation = -1;
	else {
		checkVoltage();  // updates vCur_1 used in next line
		setRotation(rotation,getPeriod(),(getCumulativeDays()*24) + *P_Hour + (*P_Minute / 30),vCur_1);
	}
	return rotation;
}
Beispiel #11
0
extern int
incrementPeriod(void) {
	struct NORperiod period;
	int currentPeriod = getPeriod() + 1;
	
	period.structType = NOR_STRUCT_ID_PERIOD;
	period.period = currentPeriod;
	ptrsCounts.period = (struct NORperiod *)AppendStructToFlash(&period);

	return currentPeriod;
}
/**
  * Attempts to set the sample rate of the accelerometer to the specified value (in ms).
  *
  * @param period the requested time between samples, in milliseconds.
  *
  * @return MICROBIT_OK on success, MICROBIT_I2C_ERROR is the request fails.
  *
  * @code
  * // sample rate is now 20 ms.
  * accelerometer.setPeriod(20);
  * @endcode
  *
  * @note The requested rate may not be possible on the hardware. In this case, the
  * nearest lower rate is chosen.
  */
int MicroBitAccelerometer::setPeriod(int period)
{
    int result;

    samplePeriod = period;
    result = configure();

    samplePeriod = getPeriod();
    return result;

}
Beispiel #13
0
void setReadPeriod (Sensor * sensor, uint32_t read_period) {
	uint32_t physical_period = 0;

	if (getPeriod(sensor->ID, &physical_period) != OP_OK) {
		// scrive sul log che c'è stato un accesso errato in lettura
	}

	// il controllo si deve fare solo per sensori SINCRONI
	if (physical_period > 0 && read_period < physical_period)
		sensor->read_period_ms = physical_period;
	else sensor->read_period_ms = read_period;
}
Beispiel #14
0
double RateOfChange::calculate(list<double>& pastPrices)
{
	double lastPrice = pastPrices.back();
	double priceNPeriodsAgo;
	
	list<double>::reverse_iterator it = pastPrices.rbegin();
	advance(it, getPeriod());
	priceNPeriodsAgo = *it;

	double ROC = (lastPrice - priceNPeriodsAgo) / priceNPeriodsAgo * 100;
	return ROC;
}
Beispiel #15
0
double
Project2::SawtoothSignal::getVoltageAtTime(Time t)
{
   double seconds = (double)(t.getTotalTimeAsSeconds());
   double offSet = (double)(getTimeOffset().getTotalTimeAsSeconds());
   double period = (double)(getPeriod().getTotalTimeAsSeconds());
   //Formula for calculating sawtooth voltage at time t
   //V(t) = valueOffset + min + ((t + timeOffset) * (max - min) / period) % (max - min)
   return getVoltageOffset() + getMinVoltage() +
      fmod(((seconds + offSet) *
      (getMaxVoltage() - getMinVoltage()) / period),
      (getMaxVoltage() - getMinVoltage()));
}
void DiscoveryResponder::sendResponse(string s, struct sockaddr_in *requester) {
	int bytesRecieved;
	int requesterLen = sizeof(struct sockaddr);
	
	/* sleep for a random period to prevent network saturation */
	/* from all agents replying at once. */	
	Utils::sleep(getPeriod());
		
	bytesRecieved = sendto(discoverySocket, 
						   s.c_str(), 
						   s.length()*sizeof(char), 
						   0, 
						   (struct sockaddr *)requester,
						   requesterLen); 
	if (bytesRecieved < 0) { 
	  ConsoleServer::debugMsg(1,"Response error :%s\n",strerror(errno));
	} 	
}
Beispiel #17
0
void printTableTarget(sqlite3 * db, char * sql, int id){
    int i, j;
    double seconds;
    char curentTime[20];
    values * val;
    time_t tp;

    time(&tp);
    struct tm * mytm = gmtime(&tp);

    //mytm->tm_hour += 3;
    strftime(curentTime, (size_t)20, "%Y-%m-%d %H:%M:%S", mytm);

    if(id > 0) {
        val = selectFromTable(db, sql, id);
    } else val = selectFromTable(db, sql);

    int count = val->columns * val->rows + val->columns;

    for (i = val->columns, j = 1; i < count; i++) {
        switch(j){
            case 1:
                printf("[%d]\t", atoi(val->result[i]));
                j++;
                break;

            case 2:
                seconds = getPeriod(val->result[i], curentTime);
                printf("%s\t", val->result[i]);
                printf("%d\t", secToDays(seconds));
                j++;
                break;

            case 3:
                printf("%s\n", val->result[i]);
                j = 1;
                break;
        }
    }

    freeStructValues(val);

}
Beispiel #18
0
double getTaskTime(sqlite3 * db, char * sql, int id){
    int i, j, proxy;
    double seconds = 0.0;
    
    values * val = selectFromTable(db, sql, id);
        
    int count = val->columns * val->rows + val->columns;
    
    for (i = val->columns, j = 1; i < count; i++) {
        if(j == 1) proxy = i;
        if(j == 2 && val->result[i] != NULL) {
  
            seconds += getPeriod(val->result[proxy], val->result[i]);
        }    
        if(j == val->columns) j = 1;
        else j++;
    }
    
    freeStructValues(val); 
    return seconds;
}
Beispiel #19
0
extern void getRTC(char * str) {
	unsigned long r,c,p,d,h,m,s;
	char time[RTC_STRING_LENGTH];
	
	h = (unsigned long) *P_Hour;	
	m = (unsigned long) *P_Minute;
	s = (unsigned long) *P_Second;
	if (h >23) {
		h -= 24;
		setRTC(h,m,s);
		incrementCumulativeDays();
	}
	r = (long)getRotation();
	c = (long)getPowerups();
	p = (long)getPeriod();  
	d = (long)getCumulativeDays();

	if (r >= 0)
		time[0] = r + '0';
	else
		time[0] = '_';
	time[1] = 'r';
	longToDecimalString(c,time+2,4);
	time[6] = 'c';
	if (p >= 0)
		longToDecimalString(p,time+7,3);
	else
		strcpy(time+7,(char *)"___");
	time[10] = 'p';
	longToDecimalString(d,time+11,3);
	time[14] = 'd';
	longToDecimalString(h,time+15,2);
	time[17] = 'h';
	longToDecimalString(m,time+18,2);
	time[20] = 'm';
	longToDecimalString(s,time+21,2);
	time[23] = 's';
	time[24] = 0;
	strcpy(str,time);
}
Beispiel #20
0
    void Gripper::updateHook()
    {
#if (defined OROPKG_OS_LXRT)        

        prev_pos=pos;
        pos=encoder->readSensor();
        bool stopped = false;
        time_passed = TimeService::Instance()->secondsSince(time_begin);
        
        if(time_passed>min_time.rvalue())
            stopped = (std::abs(prev_pos-pos)/getPeriod())<eps.rvalue();
#endif
        if(opening){
#if (defined OROPKG_OS_LXRT)        
            gripper_axis->drive(voltage_value.rvalue());
            if(stopped)
#endif
                {
                    opening=false;
                    opened=true;
                }
        }
        else if(closing){
#if (defined OROPKG_OS_LXRT)        
            gripper_axis->drive(-voltage_value.rvalue());
            if(stopped)
#endif
                {
                    closed=true;
                    if(!actuated_grip.rvalue())
                        closing=false;
                }
        }else{
#if (defined OROPKG_OS_LXRT)        
            gripper_axis->drive(0.0);
#endif
        }
    }
Beispiel #21
0
void SmoothADC::dbgInfo()			// needs SCI initialized in sketch setup
{
	#ifdef DEBUG
	String		dbgInfo = "";
	uint8_t		c;
	
	dbgInfo += "!> ";
	dbgInfo += "Pin A";
	dbgInfo += (getPin() - A0);
	dbgInfo += ",\tRate: ";
	dbgInfo += getPeriod();
	dbgInfo += "ms";
	Serial.println(dbgInfo);
	dbgInfo.remove(0);
	dbgInfo += "!> ";
	dbgInfo += "Tab :\t";
	for (c = 0 ; c < DEF_NB_ACQ ; c++)
	{
		dbgInfo += ADCChannel.ADCTab[c];
		dbgInfo += "\t";
	}
	Serial.println(dbgInfo);
	#endif
}
Beispiel #22
0
double TaskRec::getObstacle2PressPeriod() {
	obstacle2PressPeriod = getPeriod(pressTime, disappearTime);
	return obstacle2PressPeriod;
}
Beispiel #23
0
double Task::getUtilization() {
  return (double)((double)(getExecCost())
		  /(double)(getPeriod()));
}
Beispiel #24
0
int main(int argc, char* argv[]) {
	int i = 0;	// indice usato per i cicli for
	int n = 0;	// variabile per il numero di sensori
	xQueueHandle queue[NUM_PRIORITIES];
	Sync_Init sync_sensor;

	initNode();

	initSensors();

//	initNetwork();		funzione fornita dal livello rete

	if ( join(getID()) == 0) { 	// supponendo sia questa la firma
		// scrive nel log che si e' verificato un errore di autenticazione
		while(1);
	}

	for (i = 0; i < NUM_PRIORITIES; i++)
		queue[i] = xQueueCreate(MAX_QUEUE_LENGTH, sizeof(Message));

	if (xTaskCreate(asyncRequestManage,// nome della funzione
					"Gestione richieste asincrone",
					configMINIMAL_STACK_SIZE,
					queue(1), // parametri della funzione: queue(1)
					3) != pdTRUE) {
		// scrive nel log che si `e verificato un errore di gestione della memoria
		while(1);
	}

	n = getNumSensors();

	for (i = 0; i < n; i++) {

		if (getPeriod(getSensorID(i)) > 0) {

			sync_sensor.ID = getSensorID(i);
			sync_sensor.period = getPeriod(getSensorID(i));

			if (xTaskCreate(syncSensorManage,// nome della funzione
							"Task di gestione di un sensore sincrono ",
							configMINIMAL_STACK_SIZE,
							(void *)&sync_sensor, // parametri della funzione
							2) != pdTRUE) {
				// scrive nel log che si `e verificato un errore di gestione della memoria
				while(1);
			}

		}
	}

	if (xTaskCreate(sendOverNetwork,// nome della funzione
					"Task per l'invio dei messaggi",
					configMINIMAL_STACK_SIZE,
					(void *)queue, // parametri della funzione
					1) != pdTRUE) {
		// scrive nel log che si `e verificato un errore di gestione della memoria
		while(1);
	}

	vTaskStartScheduler();

	while (1);
}
PRL_RESULT CDspVmAutoTaskManagerBase::tryToRegisterVm(const SmartPtr<CVmConfiguration>& pVmConfig,
													  const QString& qsVmDirUuid,
													  int iRecommendedNextTime)
{
	if ( ! pVmConfig )
		return PRL_ERR_FAILURE;

	CVmIdent vmIdent = MakeVmIdent(pVmConfig->getVmIdentification()->getVmUuid(), qsVmDirUuid);

	// Fake client (calling at starting dispatcher from Init())
	SmartPtr<CDspClient> pClient( new CDspClient(IOSender::Handle()) );
	pClient->getAuthHelper().AuthUserBySelfProcessOwner();
	pClient->setVmDirectoryUuid(vmIdent.second);

	PRL_RESULT res = prepareRegistration( vmIdent, pClient );
	if ( PRL_FAILED( res ) )
		return res;

	if ( !isEnabled( pVmConfig, false ) )
		return unregisterVm(vmIdent);

// Check period
	int iPeriod;
	res = getPeriod( pVmConfig, iPeriod );
	if ( PRL_FAILED( res ) )
		return res;

// Register VM and start timer
	{
		QMutexLocker locker(&m_lockVmIdents);

		if (m_mapVmIdents.contains(vmIdent))
		{
			TimerInfo timerInfo = m_mapVmIdents.value(vmIdent);

			if ( timerInfo.bAutoTask )
			{
				int iOldPeriod = timerInfo.iPeriod;
				if (iOldPeriod && iOldPeriod != iPeriod)
				{
					emit killVmTimerSignal(timerInfo.iTimerId);

					m_mapVmIdents.remove(vmIdent);
				}
				else
				{
					return PRL_ERR_SUCCESS;
				}
			}
		}
	}

// Check timestamp

	QDateTime dtNow = QDateTime::currentDateTime();

	QDateTime dtTimestamp;
	{
		CDspLockedPointer<QSettings> pQSettings = CDspService::instance()->getQSettings();

		QString qsGroup = getSettingsGroupKey(vmIdent);
		pQSettings->beginGroup(qsGroup);

		QString qsKeyTimeStamp = getSettingsKeyTimestamp();
		dtTimestamp = pQSettings->value(qsKeyTimeStamp, QVariant(dtNow)).toDateTime();

		if ( ! pQSettings->contains(qsKeyTimeStamp) )
			pQSettings->setValue(qsKeyTimeStamp, QVariant(dtNow));

		pQSettings->endGroup();
	}

	int iOriginalPeriod = iPeriod;

	int iSkippedInterval = dtTimestamp.secsTo( dtNow );
	if ( iSkippedInterval > 0 )
	{
		iPeriod = (iSkippedInterval > iPeriod ? 0 : iPeriod - iSkippedInterval);
	}
	if ( iRecommendedNextTime )
		iPeriod = qMin(iPeriod, iRecommendedNextTime);

	WRITE_TRACE( DBG_FATAL, "%s manager: register VM %s with period %d (%d)",
				getManagerName(), QSTR2UTF8( pVmConfig->getVmIdentification()->getVmName() ),
				iPeriod, iOriginalPeriod );
	emit startVmTimerSignal(vmIdent, iPeriod, iOriginalPeriod);

	return PRL_ERR_SUCCESS;
}
    int hrpExecutionContext::svc(void)
    {
        if (open_iob() == FALSE){
            std::cerr << "open_iob: failed to open" << std::endl;
            return 0;
        } 
        if (lock_iob() == FALSE){
            std::cerr << "failed to lock iob" << std::endl;
            close_iob();
            return 0;
        }
#ifndef OPENRTM_VERSION_TRUNK
        long period_nsec = (m_period.sec()*1e9+m_period.usec()*1e3);
        double period_sec = period_nsec/1e9;
#else
        coil::TimeValue period(getPeriod());
        double period_sec = (double)period;
        long period_nsec = period_sec*1e9;
#endif
	    int nsubstep = number_of_substeps();
        set_signal_period(period_nsec/nsubstep);
        std::cout << "period = " << get_signal_period()*nsubstep/1e6
                  << "[ms], priority = " << m_priority << std::endl;
        struct timeval debug_tv1, debug_tv2, debug_tv3, debug_tv4, debug_tv5;
        int loop = 0;
        int debug_count = 5000.0/(get_signal_period()*nsubstep/1e6); // Loop count for debug print. Once per 5000.0 [ms].

        if (!enterRT()){
            unlock_iob();
            close_iob();
            return 0;
        }
        do{
            loop++;
            if (loop % debug_count == 0 && ENABLE_DEBUG_PRINT) gettimeofday(&debug_tv1, NULL);
            if (!waitForNextPeriod()){
                unlock_iob();
                close_iob();
                return 0;
            }
            struct timeval tv;
            gettimeofday(&tv, NULL);
            if (m_profile.count > 0){
#define DELTA_SEC(start, end) (end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1e6)
                double dt = DELTA_SEC(m_tv, tv);
                if (dt > m_profile.max_period) m_profile.max_period = dt;
                if (dt < m_profile.min_period) m_profile.min_period = dt;
                m_profile.avg_period = (m_profile.avg_period*m_profile.count + dt)/(m_profile.count+1);
            }
            m_profile.count++;
            m_tv = tv;
            if (loop % debug_count == 0 && ENABLE_DEBUG_PRINT) gettimeofday(&debug_tv2, NULL);

#ifndef OPENRTM_VERSION_TRUNK
            invoke_worker iw;
            struct timeval tbegin, tend;
	        std::vector<double> processes(m_comps.size());
            gettimeofday(&tbegin, NULL);
            for (unsigned int i=0; i< m_comps.size(); i++){
                iw(m_comps[i]);
                gettimeofday(&tend, NULL);
                double dt = DELTA_SEC(tbegin, tend);
                processes[i] = dt;
                tbegin = tend;
            }
#else
            struct timeval tbegin, tend;
            const RTCList& list = getComponentList();
            std::vector<double> processes(list.length());
            gettimeofday(&tbegin, NULL);
            for (unsigned int i=0; i< list.length(); i++){
                RTC_impl::RTObjectStateMachine* rtobj = m_worker.findComponent(list[i]);
                rtobj->workerDo(); 
                gettimeofday(&tend, NULL);
                double dt = DELTA_SEC(tbegin, tend);
                processes[i] = dt;
                tbegin = tend;
            }
#endif
            if (loop % debug_count == 0 && ENABLE_DEBUG_PRINT &&
                rtc_names.size() == processes.size()) {
              printRTCProcessingTime(processes);
            }
            if (loop % debug_count == 0 && ENABLE_DEBUG_PRINT) gettimeofday(&debug_tv3, NULL);

            gettimeofday(&tv, NULL);
            double dt = DELTA_SEC(m_tv, tv);
            if (dt > m_profile.max_process) m_profile.max_process = dt;
	    if (m_profile.profiles.length() != processes.size()){
	        m_profile.profiles.length(processes.size());
		for (unsigned int i=0; i<m_profile.profiles.length(); i++){
		    m_profile.profiles[i].count = 0;
		    m_profile.profiles[i].avg_process = 0;
		    m_profile.profiles[i].max_process = 0;
		}
	    }
	    for (unsigned int i=0; i<m_profile.profiles.length(); i++){
#ifndef OPENRTM_VERSION_TRUNK
                LifeCycleState lcs = get_component_state(m_comps[i]._ref);
#else
                RTC_impl::RTObjectStateMachine* rtobj = m_worker.findComponent(list[i]);
                LifeCycleState lcs = rtobj->getState();
#endif
                OpenHRP::ExecutionProfileService::ComponentProfile &prof 
                    = m_profile.profiles[i];
                double dt = processes[i];
                if (lcs == ACTIVE_STATE){
                    prof.avg_process = (prof.avg_process*prof.count + dt)/(++prof.count);
                }
	        if (prof.max_process < dt) prof.max_process = dt;
	    }
            if (dt > period_sec*nsubstep){
  	        m_profile.timeover++; 
#ifdef NDEBUG
                fprintf(stderr, "[hrpEC][%d.%6.6d] Timeover: processing time = %4.2f[ms]\n",
                        tv.tv_sec, tv.tv_usec, dt*1e3);
                // Update rtc_names only when rtcs length change.
                if (processes.size() != rtc_names.size()){
                    rtc_names.clear();
                    for (unsigned int i=0; i< processes.size(); i++){
                        RTC::RTObject_var rtc = RTC::RTObject::_narrow(m_comps[i]._ref);
                        rtc_names.push_back(std::string(rtc->get_component_profile()->instance_name));
                    }
                }
                printRTCProcessingTime(processes);
#endif
            }

#ifndef OPENRTM_VERSION_TRUNK
            if (loop % debug_count == 0 && ENABLE_DEBUG_PRINT) {
              gettimeofday(&debug_tv4, NULL);
              fprintf(stderr, "[hrpEC] Processing time breakdown : waitForNextPeriod %f[ms], warker (onExecute) %f[ms], ExecutionProfile %f[ms], time from prev cicle %f[ms]\n",
                      DELTA_SEC(debug_tv1, debug_tv2)*1e3,
                      DELTA_SEC(debug_tv2, debug_tv3)*1e3,
                      DELTA_SEC(debug_tv3, debug_tv4)*1e3,
                      DELTA_SEC(debug_tv5, debug_tv1)*1e3);
            }
            if (loop % debug_count == (debug_count-1) && ENABLE_DEBUG_PRINT) gettimeofday(&debug_tv5, NULL);
        } while (m_running);
#else
        } while (isRunning());
Beispiel #27
0
void Channel::frameDraw( const eq::uint128_t& frameID )
{
    if( stopRendering( ))
        return;

    _initJitter();
    if( _isDone( ))
        return;

    Window* window = static_cast< Window* >( getWindow( ));
    VertexBufferState& state = window->getState();
    const Model* oldModel = _model;
    const Model* model = _getModel();

    if( oldModel != model )
        state.setFrustumCulling( false ); // create all display lists/VBOs

    if( model )
        _updateNearFar( model->getBoundingSphere( ));

    eq::Channel::frameDraw( frameID ); // Setup OpenGL state

    glLightfv( GL_LIGHT0, GL_POSITION, lightPosition );
    glLightfv( GL_LIGHT0, GL_AMBIENT,  lightAmbient  );
    glLightfv( GL_LIGHT0, GL_DIFFUSE,  lightDiffuse  );
    glLightfv( GL_LIGHT0, GL_SPECULAR, lightSpecular );

    glMaterialfv( GL_FRONT, GL_AMBIENT,   materialAmbient );
    glMaterialfv( GL_FRONT, GL_DIFFUSE,   materialDiffuse );
    glMaterialfv( GL_FRONT, GL_SPECULAR,  materialSpecular );
    glMateriali(  GL_FRONT, GL_SHININESS, materialShininess );

    const FrameData& frameData = _getFrameData();
    glPolygonMode( GL_FRONT_AND_BACK,
                   frameData.useWireframe() ? GL_LINE : GL_FILL );

    const eq::Vector3f& position = frameData.getCameraPosition();

    glMultMatrixf( frameData.getCameraRotation().array );
    glTranslatef( position.x(), position.y(), position.z() );
    glMultMatrixf( frameData.getModelRotation().array );

    if( frameData.getColorMode() == COLOR_DEMO )
    {
        const eq::Vector3ub color = getUniqueColor();
        glColor3ub( color.r(), color.g(), color.b() );
    }
    else
        glColor3f( .75f, .75f, .75f );

    if( model )
        _drawModel( model );
    else
    {
        glNormal3f( 0.f, -1.f, 0.f );
        glBegin( GL_TRIANGLE_STRIP );
            glVertex3f(  .25f, 0.f,  .25f );
            glVertex3f( -.25f, 0.f,  .25f );
            glVertex3f(  .25f, 0.f, -.25f );
            glVertex3f( -.25f, 0.f, -.25f );
        glEnd();
    }

    state.setFrustumCulling( true );
    Accum& accum = _accum[ lunchbox::getIndexOfLastBit( getEye()) ];
    accum.stepsDone = LB_MAX( accum.stepsDone,
                              getSubPixel().size * getPeriod( ));
    accum.transfer = true;
}
Beispiel #28
0
static NOINLINE uint32_t measureAudioPeriod(uint8_t periods) // in 2Mhz ticks
{
	uint32_t res=0;
	
	// display / start maintainting CVs
	
	for(int8_t i=0;i<25;++i) // lower this and eg. filter tuning starts behaving badly
		whileTuning();
			
	// prepare flip flop
	
	ff_state=0;
	ff_step=0;
	ffMask(FF_P|FF_CL,FF_D|CNTR_EN);
	
	// prepare 8253
	
	getPeriod();
	
	// flip flop stuff (CF sevice manual section 2-16)
		
	while(periods)
	{
		// init

		ffMask(CNTR_EN,0);

		ffMask(FF_D,FF_P);
		ffWaitStatus(0);

		ffMask(FF_P,FF_CL);
		ffWaitStatus(1);

		// start
		
		ffMask(FF_CL,0);
		ffWaitCounter(0);

		ffMask(0,FF_CL);
		ffMask(FF_CL,0);
		ffWaitCounter(1);
		
		// reset

		ffMask(0,CNTR_EN|FF_D);
		
		// get result / display / ...
		
		--periods;

		res+=getPeriod();

		whileTuning();

		// detect untunable osc		
		
		if (ff_timeoutCount>=STATUS_TIMEOUT_MAX_FAILURES)
		{
			res=UINT32_MAX;
			break;
		}
	}
	
	return res;
}
Beispiel #29
0
double TaskRec::getVisiblePeriod() {
	visiblePeriod = getPeriod(disappearTime, moveBegTime);
	return visiblePeriod;
}
Beispiel #30
0
double TaskRec::getTotalPeriod() {
	totalPeriod = getPeriod(pressTime, moveBegTime);
	return totalPeriod;
}