Пример #1
0
void Kneader::continuos_program(){
	switch(mixing_step){
	case waiting2Mix:
		started_kenading=millis();
		mixing_step=firstMix;
		on();
		break;
	case firstMix:
	case secondMix:
		if(isExpired(started_kenading,kp->ki.firstMix_milli)){
			started_pause=millis();
			mixing_step=firstPause;
			off();
		}
		break;
	case firstPause:
	case secondPause:
		if(isExpired(started_pause,kp->ki.frequency_milli) ){
			started_kenading=millis();
			mixing_step=firstMix;
			on();
		}
		break;
	}
}
Пример #2
0
bool CachedResource::mustRevalidateDueToCacheHeaders(CachePolicy cachePolicy) const
{    
    ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);

    if (cachePolicy == CachePolicyRevalidate)
        return true;

    if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
        LOG(ResourceLoading, "CachedResource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
        return true;
    }

    if (cachePolicy == CachePolicyCache) {
        if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
            LOG(ResourceLoading, "CachedResource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
            return true;
        }
        return false;
    }

    // CachePolicyVerify
    if (isExpired()) {
        LOG(ResourceLoading, "CachedResource %p mustRevalidate because of isExpired()\n", this);
        return true;
    }

    return false;
}
Пример #3
0
CachedResource::RevalidationDecision CachedResource::makeRevalidationDecision(CachePolicy cachePolicy) const
{    
    switch (cachePolicy) {
    case CachePolicyHistoryBuffer:
        return RevalidationDecision::No;

    case CachePolicyReload:
    case CachePolicyRevalidate:
        return RevalidationDecision::YesDueToCachePolicy;

    case CachePolicyVerify:
        if (m_response.cacheControlContainsNoCache())
            return RevalidationDecision::YesDueToNoCache;
        // FIXME: Cache-Control:no-store should prevent storing, not reuse.
        if (m_response.cacheControlContainsNoStore())
            return RevalidationDecision::YesDueToNoStore;

        if (isExpired())
            return RevalidationDecision::YesDueToExpired;

        return RevalidationDecision::No;
    };
    ASSERT_NOT_REACHED();
    return RevalidationDecision::No;
}
Пример #4
0
 bool Timer::onRestart() {
   if(isExpired()) {
     restart();
     return true;
   }
   return false;
 }
Пример #5
0
void Kneader::run(){
	if(!active)
		return ;
	/* first check if is the first time we run*/
	if(started==0){
		/* in that case mark when the program is started*/
		started=millis();
	}
	/* check if the program is ended */
	if(kp==NULL || isExpired(kp->ki.length_seconds*1000,started) ){
		delay(2000);
		return;
	}
	switch(kp->ki.mode){

	case continuos:
		continuos_program();
		break;
	case dashed:
		dashed_program();
		break;
	case alternated:
		alternated_program();
		break;
	default:
		/* unsupported bake */
		break;
	}
}
Пример #6
0
xpcc::Timestamp
xpcc::Timeout<T>::remaining()
{
	if (isExpired())
		return 0;
	else
		return (endTime - T::now());
}
Пример #7
0
void CallbackTimer::update()
{
	// When not flagged as "just expired" yet, do it now, and call listeners
	if (isExpired() && !mJustExpired)
	{
		mJustExpired = true;
		mListeners.call(*this);
	}
}
Пример #8
0
// isValid:
//
bool Cacheable::isValid()
{
    if (isExpired())
       return false;

    if (this->m_isValidFlag == VALID)
        return true;
    else
        return false;
} // END OF MEMBER FUNCTION isValid
Пример #9
0
void Schedule::start()
{
    if (isExpired() || isActive())
        return;

/////////////////////////////////////////////
    _timer->connect(_timer, SIGNAL(timeout()), this, SLOT(timeout()));
    _timer->start(QDateTime::currentDateTime().msecsTo(_launchAt));


  //////////////////////////////////////////////
}
Lease::Lease (const Client& c)
{
    m = SharedPtr<ClientData>(c.m);
    if (   !m->fHasLease
        || (   isExpired()
            && !isInBindingPhase()))
    {
        m->fHasLease = true;
        m->fBinding = true;
        phaseStart(RTTimeMilliTS());
    }
}
sc::result StGetBackOnTrackPrepare::react(const EvProcess&) {
  if (detectedErrornousTransitions()) return transit<StGlobalRecover> ();

  //	return transit<StDrive>();
  //	return transit<StPause>();

  ChsmPlanner& planner = context<ChsmPlanner> ();

  if (isExpired(context<StGetBackOnTrack> ().map_timer)) {
    return transit<StGetBackOnTrackAStar> ();
  }
  else {
    planner.generateStopTrajectory();
    return forward_event();
  }
}
    Volatility CapFloor::impliedVolatility(Real targetValue,
                                           const Handle<YieldTermStructure>& d,
                                           Volatility guess,
                                           Real accuracy,
                                           Natural maxEvaluations,
                                           Volatility minVol,
                                           Volatility maxVol) const {
        //calculate();
        QL_REQUIRE(!isExpired(), "instrument expired");

        ImpliedVolHelper f(*this, d, targetValue);
        //Brent solver;
        NewtonSafe solver;
        solver.setMaxEvaluations(maxEvaluations);
        return solver.solve(f, accuracy, guess, minVol, maxVol);
    }
Пример #13
0
		bool Clock::isExpired(const dtn::data::Bundle &b)
		{
			if (b.timestamp == 0)
			{
				// use the AgeBlock to verify the age
				try {
					const dtn::data::AgeBlock &agebl = b.find<dtn::data::AgeBlock>();
					return (b.lifetime < agebl.getSeconds());
				} catch (const dtn::data::Bundle::NoSuchBlockFoundException&) {
					// if there is no AgeBlock this bundle is not valid
					return true;
				}
			}

			return isExpired(b.timestamp, b.lifetime);
		}
Пример #14
0
 Volatility CallableBond::impliedVolatility(
                           Real targetValue,
                           const Handle<YieldTermStructure>& discountCurve,
                           Real accuracy,
                           Size maxEvaluations,
                           Volatility minVol,
                           Volatility maxVol) const {
     calculate();
     QL_REQUIRE(!isExpired(), "instrument expired");
     Volatility guess = 0.5*(minVol + maxVol);
     blackDiscountCurve_.linkTo(*discountCurve, false);
     ImpliedVolHelper f(*this,targetValue);
     Brent solver;
     solver.setMaxEvaluations(maxEvaluations);
     return solver.solve(f, accuracy, guess, minVol, maxVol);
 }
Пример #15
0
void SubscriptionManager::checkMissedPublication(
    const Timer::TimerId id)
{
    std::lock_guard<std::recursive_mutex> subscriptionLocker(&mutex);

    if (!isExpired() && !subscription->isStopped)
    {
        JOYNR_LOG_DEBUG(logger, "Running MissedPublicationRunnable for subscription id= {}",subscriptionId);
        std::int64_t delay = 0;
        std::int64_t now = duration_cast<milliseconds>(
            system_clock::now().time_since_epoch()).count();
        std::int64_t timeSinceLastPublication = now
            - subscription->timeOfLastPublication;
        bool publicationInTime = timeSinceLastPublication < alertAfterInterval;
        if (publicationInTime)
        {
            JOYNR_LOG_TRACE(logger, "Publication in time!");
            delay = alertAfterInterval - timeSinceLastPublication;
        }
        else
        {
            JOYNR_LOG_DEBUG(logger, "Publication missed!");
            std::shared_ptr<ISubscriptionCallback> callback =
                subscription->subscriptionCaller;

            callback->onError();
            delay = alertAfterInterval
                - timeSinceLastExpectedPublication(timeSinceLastPublication);
        }
        JOYNR_LOG_DEBUG(logger, "Resceduling MissedPublicationRunnable with delay: {}",std::string::number(delay));
        subscription->missedPublicationRunnableHandle =
            subscriptionManager.missedPublicationScheduler->schedule(
                new MissedPublicationRunnable(decayTime,
                    expectedIntervalMSecs,
                    subscriptionId,
                    subscription,
                    subscriptionManager,
                    alertAfterInterval),
                delay);
    }
    else
    {
        JOYNR_LOG_DEBUG(logger, "Publication expired / interrupted. Expiring on subscription id={}",subscriptionId);
    }
}
Пример #16
0
void EntityList::update( void *updateState )
{
	Entity::update( updateState );

	if ( isExpired() )
	{
		return;
	}

	for (auto e : entities)
	{
		e->update( updateState );

		onEntityUpdated( e, updateState );
	}

	clean();
}
Пример #17
0
//Checks for expiry of all tasks in the multimap
void Storage::checkForExpiry() {

	multimap<DEADLINE, Task*>::iterator it;
	it=timedTaskMap.begin(); 
	while(it != timedTaskMap.end()){

		if(isExpired((*it).second)) {
			(*it).second->indicateExpired();
		}

		if(isToday((*it).second)) {
			(*it).second->indicateToday(true);
		} else {
			(*it).second->indicateToday(false);
		}

		it++; 
	}
}
Пример #18
0
    Volatility CdsOption::impliedVolatility(
                   Real targetValue,
                   const Handle<YieldTermStructure>& termStructure,
                   const Handle<DefaultProbabilityTermStructure>& probability,
                   Real recoveryRate,
                   Real accuracy,
                   Size maxEvaluations,
                   Volatility minVol,
                   Volatility maxVol) const {
        calculate();
        QL_REQUIRE(!isExpired(), "instrument expired");

        Volatility guess = 0.10;

        ImpliedVolHelper f(*this, probability, recoveryRate,
                           termStructure, targetValue);
        Brent solver;
        solver.setMaxEvaluations(maxEvaluations);
        return solver.solve(f, accuracy, guess, minVol, maxVol);
    }
Пример #19
0
    Volatility DoubleBarrierOption::impliedVolatility(
             Real targetValue,
             const boost::shared_ptr<GeneralizedBlackScholesProcess>& process,
             Real accuracy,
             Size maxEvaluations,
             Volatility minVol,
             Volatility maxVol) const {

        QL_REQUIRE(!isExpired(), "option expired");

        boost::shared_ptr<SimpleQuote> volQuote =
            boost::make_shared<SimpleQuote>();

        boost::shared_ptr<GeneralizedBlackScholesProcess> newProcess =
            detail::ImpliedVolatilityHelper::clone(process, volQuote);

        // engines are built-in for the time being
        boost::scoped_ptr<PricingEngine> engine;
        switch (exercise_->type()) {
          case Exercise::European:
            engine.reset(new AnalyticDoubleBarrierEngine(newProcess));
            break;
          case Exercise::American:
          case Exercise::Bermudan:
            QL_FAIL("engine not available for non-European barrier option");
            break;
          default:
            QL_FAIL("unknown exercise type");
        }

        return detail::ImpliedVolatilityHelper::calculate(*this,
                                                          *engine,
                                                          *volQuote,
                                                          targetValue,
                                                          accuracy,
                                                          maxEvaluations,
                                                          minVol, maxVol);
    }
sc::result StWaitForActivation::react(const EvProcess&) {
  if (detectedErrornousTransitions()) return transit<StGlobalRecover> ();
  ChsmPlanner& planner = context<ChsmPlanner> ();
  Topology* topology = planner.topology_;

  // set velocity to 0 -> park mode
  context<ChsmPlanner> ().generateStopTrajectory();

//  context<ChsmPlanner> ().vehiclecmd.beeper_on = 1;
//  context<ChsmPlanner> ().vehiclecmd.hazard_lights_on = 1;

  if (isExpired(wait_until_)) {

    // Transition: Replanning (because ego vehicle is off track)
    if (topology->isOffTrack() || moved) return transit<StReplan> ();

    // Transition: restore history
    return transit<StActiveHistory> ();

  }
  else {
    return forward_event();
  }
}
Пример #21
0
 bool Timer::onExpired() {
   if(!_has_been_expired && isExpired()) {
     return _has_been_expired = true;
   }
   return false;
 }
Пример #22
0
bool
CNameData::isExpired () const
{
  return isExpired (chainActive.Height ());
}
Пример #23
0
bool Timer::isRunning() const
{
	return mStopWatch.isRunning() && !isExpired();
}
sc::result StIntersectionTrafficLightStop::react(const EvProcess&)
{
	if (detectedErrornousTransitions()) return transit<StGlobalRecover>();

	ChsmPlanner& planner = context<ChsmPlanner>();
	IntersectionManager* isec_man = context<StIntersection>().isec_man;
	Topology* topology = context<ChsmPlanner>().topology_;
	assert(isec_man);


  // Transition: Recovery Mode
	if (isec_man->hasPrioMovement()) {
		context<StIntersection>().clearRecoveryIndicator();
	}
  if (planner.params().enable_recovery && (context<StIntersection>().checkRecovery() || isExpired(context<StIntersection>().max_wait_at_intersection))) { // measure progress in the parent state
    return transit<StIntersectionRecover>();
  }

  // Transition: Replanning (because ego vehicle is off track)
	if (topology->isOffTrack())
	  return transit<StReplan>();

	// Transition: Replanning (because route is blocked)
	if ( topology->isRouteBlocked() )
		return transit<StReplan>();

    // Transition: If traffic light switched to green while slowing down cross intersection
	if(!context<StIntersection>().isec_man->hasToStop()) {
    return transit<StIntersectionDriveInside>();
  }

	// calculate distances
	// TODO: make sure that stop line belongs to intersection
	double traffic_light_dist = topology->distToTrafficLight(isec_man->intersection(), NULL, &planner.stop_point_);
	double intersec_dist = topology->distToIntersection(isec_man->intersection());
	double mv_veh_dist, sv_veh_dist;
	planner.getVehicleDistances(sv_veh_dist, mv_veh_dist);

	// set turn signal
	planner.turn_signal_.signal = context<StIntersection>().turnDirection;

//	printf("STOP IN %f m;\t CURRENT SPEED %f\n", traffic_light_dist, currentPose().v());

  // Transition: Wait at stop line (because ego_vehicle stopped at stopline)
	if ( traffic_light_dist < TRAFFIC_LIGHT_DIST_THRESHOLD && planner.currentPose().v() < STOP_SPEED_THRESHOLD ) {
    return transit<StIntersectionTrafficLightWait>();
	}
	else if (traffic_light_dist == std::numeric_limits<double>::infinity()) {
	  std::cout << "WE RAN OVER A (NON GREEN) TRAFFIC LIGHT!!\n";
    return transit<StIntersectionDriveInside>();
	}

	// Transition: Queueing (if vehicle backed up)
	if ( traffic_light_dist < TRIGGER_DIST_TRAFFIC_LIGHT && (mv_veh_dist < traffic_light_dist || sv_veh_dist < traffic_light_dist) )
		return transit<StIntersectionQueue>();
	// Transition: To get states right if something goes wrong: leave intersection mode if we behind intersection
	if ( intersec_dist <= -0.1 ) {
		return transit<StDrive>();
	}

	// generate curvepoints
	context<StIntersection>().generateCurvepoints(traffic_light_dist, planner.params().max_speed_traffic_light_approach);
	return forward_event();
}
Пример #25
0
UtlBoolean SipSubscriptionMgr::insertDialogInfo(const SipMessage& subscribeRequest,
                                                const UtlString& resourceId,
                                                const UtlString& eventTypeKey,
                                                UtlString& subscribeDialogHandle,
                                                UtlBoolean& isNew,
                                                UtlBoolean& isSubscriptionExpired,
                                                SipMessage& subscribeResponse)
{
    isNew = FALSE;
    UtlBoolean subscriptionSucceeded = FALSE;
    UtlString dialogHandle;
    subscribeRequest.getDialogHandle(dialogHandle);
    SubscriptionServerState* state = NULL;
    int expiration = -1;
    isSubscriptionExpired = TRUE;

    // If this is an early dialog we need to make it an established dialog.
    if(SipDialog::isEarlyDialog(dialogHandle))
    {
        UtlString establishedDialogHandle;
        if(mDialogMgr.getEstablishedDialogHandleFor(dialogHandle, establishedDialogHandle))
        {
            OsSysLog::add(FAC_SIP, PRI_WARNING,
                "Incoming early SUBSCRIBE dialog: %s matches established dialog: %s",
                dialogHandle.data(), establishedDialogHandle.data());
        }

        // make up a To tag and set it
        UtlString toTag;
        CallId::getNewTag(dialogHandle.data(), toTag);

        // Get and validate the expires period
        // This potentially should be delegated to the event handler specifics
        if(!subscribeRequest.getExpiresField(&expiration))
        {
            expiration = mDefaultExpiration;
        }

        else if(expiration > mMaxExpiration)
        {
            expiration = mMaxExpiration;
        }

        // Acceptable expiration, create a subscription and dialog
        if(expiration >= mMinExpiration ||
           expiration == 0 ||
           // :WORKAROUND:  Also allow expiration == 1, to support the
           // 1-second subscriptions the pick-up agent makes because
           // current Snom phones do not respond to 0-second subscriptions.
           // See XPB-399 and ENG-319.
           expiration == 1)
        {
            // Create a dialog and subscription state even if
            // the expiration is zero as we need the dialog info
            // to route the one-time NOTIFY.  The immediately
            // expired dialog will be garbage collected.

            SipMessage* subscribeCopy = new SipMessage(subscribeRequest);
            subscribeCopy->setToFieldTag(toTag);

            // Re-get the dialog handle now that the To tag is set
            subscribeCopy->getDialogHandle(dialogHandle);

            // Create the dialog
            mDialogMgr.createDialog(*subscribeCopy, FALSE, dialogHandle);
            isNew = TRUE;

            // Create a subscription state
            state = new SubscriptionServerState();
            *((UtlString*) state) = dialogHandle;
            state->mEventTypeKey = eventTypeKey;
            state->mpLastSubscribeRequest = subscribeCopy;
            state->mResourceId = resourceId;
            subscribeCopy->getAcceptField(state->mAcceptHeaderValue);

            long now = OsDateTime::getSecsSinceEpoch();
            state->mExpirationDate = now + expiration;

            // TODO: currently the SipSubsribeServer does not handle timeout
            // events to send notifications that the subscription has ended.
            // So we do not set a timer at the end of the subscription
            state->mpExpirationTimer = NULL;

            // Create the index by resourceId and eventTypeKey key
            SubscriptionServerStateIndex* stateKey = new SubscriptionServerStateIndex;
            *((UtlString*) stateKey) = resourceId;
            stateKey->append(eventTypeKey);
            stateKey->mpState = state;

            subscribeResponse.setResponseData(subscribeCopy, 
                                              SIP_ACCEPTED_CODE,
                                              SIP_ACCEPTED_TEXT, 
                                              NULL);
            subscribeResponse.setExpiresField(expiration);
            subscribeCopy->getDialogHandle(subscribeDialogHandle);

            lock();
            mSubscriptionStatesByDialogHandle.insert(state);
            mSubscriptionStateResourceIndex.insert(stateKey);
            if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG))
            {
               UtlString requestContact;
               subscribeRequest.getContactField(0, requestContact);
               OsSysLog::add(FAC_SIP, PRI_DEBUG,
                             "SipSubscriptionMgr::insertDialogInfo insert early-dialog subscription for dialog handle '%s', key '%s', contact '%s', mExpirationDate %ld",
                             state->data(), stateKey->data(),
                             requestContact.data(), state->mExpirationDate);
            }

            // Not safe to touch these after we unlock
            stateKey = NULL;
            state = NULL;
            subscribeCopy = NULL;
            unlock();

            subscriptionSucceeded = TRUE;

            // One time subscribe?
            isSubscriptionExpired = expiration == 0;
        }
        // Expiration too small
        else
        {
            // Set expiration too small error
            subscribeResponse.setResponseData(&subscribeRequest, 
                                                SIP_TOO_BRIEF_CODE,
                                                SIP_SUB_TOO_BRIEF_TEXT);
            subscribeResponse.setMinExpiresField(mMinExpiration);
            isSubscriptionExpired = TRUE;
        }
    }

    // Not an early dialog handle -- The dialog for this message may already exist
    else
    {
        // Get and validate the expires period
        // This potentially should be delegated to the event handler specifics
        if(!subscribeRequest.getExpiresField(&expiration))
        {
            expiration = mDefaultExpiration;
        }

        else if(expiration > mMaxExpiration)
        {
            expiration = mMaxExpiration;
        }

        // Acceptable expiration, create a subscription and dialog
        if(expiration > mMinExpiration ||
           expiration == 0)
        {
            // Update the dialog state
            mDialogMgr.updateDialog(subscribeRequest, dialogHandle);

            // Get the subscription state and update that
            // TODO:  This assumes that no one reuses the same dialog
            // to subscribe to more than one event type.  mSubscriptionStatesByDialogHandle
            // will need to be changed to a HashBag and we will need to
            // search through to find a matching event type
            lock();
            state = (SubscriptionServerState*)
                mSubscriptionStatesByDialogHandle.find(&dialogHandle);
            if(state)
            {
                long now = OsDateTime::getSecsSinceEpoch();
                state->mExpirationDate = now + expiration;
                if(state->mpLastSubscribeRequest)
                {
                    delete state->mpLastSubscribeRequest;
                }
                state->mpLastSubscribeRequest = new SipMessage(subscribeRequest);
                subscribeRequest.getAcceptField(state->mAcceptHeaderValue);

                // Set the contact to the same request URI that came in
                UtlString contact;
                subscribeRequest.getRequestUri(&contact);

                // Add the angle brackets for contact
                Url url(contact);
                url.includeAngleBrackets();
                contact = url.toString();

                subscribeResponse.setResponseData(&subscribeRequest, 
                                                SIP_ACCEPTED_CODE,
                                                SIP_ACCEPTED_TEXT, 
                                                contact);
                subscribeResponse.setExpiresField(expiration);
                subscriptionSucceeded = TRUE;
                isSubscriptionExpired = FALSE;
                subscribeDialogHandle = dialogHandle;
            }

            // No state, but SUBSCRIBE had a to-tag.
            else
            {
                SipMessage* subscribeCopy = new SipMessage(subscribeRequest);
                // Create the dialog
                mDialogMgr.createDialog(*subscribeCopy, FALSE, dialogHandle);
                isNew = TRUE;

                // Create a subscription state
                state = new SubscriptionServerState();
                *((UtlString*)state) = dialogHandle;
                state->mEventTypeKey = eventTypeKey;
                state->mpLastSubscribeRequest = subscribeCopy;
                state->mResourceId = resourceId;
                subscribeCopy->getAcceptField(state->mAcceptHeaderValue);

                long now = OsDateTime::getSecsSinceEpoch();
                state->mExpirationDate = now + expiration;
                // TODO: currently the SipSubsribeServer does not handle timeout
                // events to send notifications that the subscription has ended.
                // So we do not set a timer at the end of the subscription
                state->mpExpirationTimer = NULL;

                // Create the index by resourceId and eventTypeKey key
                SubscriptionServerStateIndex* stateKey = new SubscriptionServerStateIndex;
                *((UtlString*)stateKey) = resourceId;
                stateKey->append(eventTypeKey);
                stateKey->mpState = state;
                mSubscriptionStatesByDialogHandle.insert(state);
                mSubscriptionStateResourceIndex.insert(stateKey);
                if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG))
                {
                   UtlString requestContact;
                   subscribeRequest.getContactField(0, requestContact);
                   OsSysLog::add(FAC_SIP, PRI_DEBUG,
                         "SipSubscriptionMgr::insertDialogInfo insert subscription for key '%s', contact '%s', mExpirationDate %ld",
                         stateKey->data(), requestContact.data(), state->mExpirationDate);
                }

                // Not safe to touch these after we unlock
                stateKey = NULL;
                state = NULL;
                subscribeCopy = NULL;

                // Set the contact to the same request URI that came in
                UtlString contact;
                subscribeRequest.getRequestUri(&contact);

                // Add the angle brackets for contact
                Url url(contact);
                url.includeAngleBrackets();
                contact = url.toString();

                subscribeResponse.setResponseData(&subscribeRequest, 
                                                  SIP_ACCEPTED_CODE,
                                                  SIP_ACCEPTED_TEXT, 
                                                  contact);
                subscribeResponse.setExpiresField(expiration);
                subscriptionSucceeded = TRUE;
                // Unsubscribe
                if(expiration == 0)
                {
                    isSubscriptionExpired = TRUE;
                }
                else
                {
                    isSubscriptionExpired = FALSE;
                }
                subscribeDialogHandle = dialogHandle;
            }
            unlock();
        }

        // Expiration too small
        else
        {
            // Set expiration too small error
            subscribeResponse.setResponseData(&subscribeRequest, 
                                                SIP_TOO_BRIEF_CODE,
                                                SIP_SUB_TOO_BRIEF_TEXT);
            subscribeResponse.setMinExpiresField(mMinExpiration);
            isSubscriptionExpired = isExpired(dialogHandle);
        }
    }

    return(subscriptionSucceeded);
}
Пример #26
0
void CButton::run()
{
	bitWrite(state,PREVIOUS,bitRead(state,CURRENT));
	timing[PREVIOUS] = timing[CURRENT];
	bitWrite(state,CURRENT,(digitalRead(pin) != mode));
	timing[CURRENT] = millis();
	if (bitRead(state,CURRENT) != bitRead(state,PREVIOUS)){
		bitWrite(state,CHANGED,true);
		timing[CHANGED] = timing[CURRENT];
	}else{
		bitWrite(state,CHANGED,false);
	}

	/* check if we need to reset a sequence that has been recorded
	 * and is aged.
	 * */
	if(stopCountingSequence==false){
		if(stateChanged()){
			/* check if was a transition from
			 * pressed to release
			 */

			if(!bitRead(state,PREVIOUS)){
				/* new Pressure start
				 * reset the timeout for the sequence
				 */
				timing[START_OF_SEQ] = millis();
				shortCounted=longCounted=false;
			}

		}else{
			/* status doesn't change*/
			if(isPressed()){
				if( shortCounted==false && isExpired(timing[START_OF_SEQ],shortPushMilli) ){
					/* count it only once*/
					shortPressureCount++;
					shortCounted=true;
					timing[START_OF_SEQ] = millis();
				}
				if( longCounted==false && isExpired(timing[START_OF_SEQ],longPushMilli) ){
					/* count it only once*/
					longPressureCount++;
					shortPressureCount--;
					longCounted=true;
					timing[START_OF_SEQ] = millis();
				}
				if(longCounted && isExpired(timing[START_OF_SEQ],resetSequenceMilli)){
					shortPressureCount=longPressureCount=0;
					stopCountingSequence=false;
				}

			}
		}
	}

		if(!isPressed() && (longCounted || shortCounted)){
			if(isExpired(timing[START_OF_SEQ],timeOut4SequenceMilli) && stopCountingSequence==false ){
				stopCountingSequence=true;
			}
			if(stopCountingSequence && isExpired(timing[START_OF_SEQ],expireSequenceMilli)){
				shortPressureCount=longPressureCount=0;
				stopCountingSequence=false;
			}
		}
	delay(20);

}
Пример #27
0
/** Returns true if there exists a mapping for <b>addr</b> and that mapping is
 * not expired. */
bool
AddressMap::isMapped(const QString &addr) const
{
  return (contains(addr) && !isExpired(value(addr)));
}
Пример #28
0
UtlBoolean SipSubscriptionMgr::updateDialogInfo(const SipMessage& subscribeRequest,
                                                UtlString& resourceId,
                                                UtlString& eventTypeKey,
                                                UtlString& eventType,
                                                UtlString& subscribeDialogHandle,
                                                UtlBoolean& isNew,
                                                UtlBoolean& isSubscriptionExpired,
                                                SipMessage& subscribeResponse,
                                                SipSubscribeServerEventHandler& handler)
{
    isNew = FALSE;
    UtlBoolean subscriptionSucceeded = FALSE;
    UtlString dialogHandle;
    subscribeRequest.getDialogHandle(dialogHandle);
    SubscriptionServerState* state = NULL;
    int expiration = -1;
    isSubscriptionExpired = TRUE;
    
    // Double check the sanity of the class attributes
    
    if(mMaxExpiration < mMinExpiration)
    {
        // This is an error case. Switch the values so that we do not
        // run into any negative expiration times.
        int tmp = mMaxExpiration;
        mMaxExpiration = mMinExpiration;
        mMinExpiration = tmp;
        
        OsSysLog::add(FAC_SIP, PRI_WARNING,
            "Swapping values as mMinExpiration => %d is greater than mMaxExpiration => %d",
            mMinExpiration, mMaxExpiration);
    }
    
    if(mMaxExpiration < mDefaultExpiration)
    {
        // This is an error case. Switch the values so that we do not
        // run into any negative expiration times.
        int tmp = mMaxExpiration;
        mMaxExpiration = mDefaultExpiration;
        mDefaultExpiration = tmp;
        
        OsSysLog::add(FAC_SIP, PRI_WARNING,
            "Swapping values as mDefaultExpiration => %d is greater than mMaxExpiration => %d",
            mDefaultExpiration, mMaxExpiration);
    }
    
    // Set the expires period randomly
    int spreadFloor = mMinExpiration*2;
    if(!subscribeRequest.getExpiresField(&expiration))
    {
        // no expires field
        // spread it between the default expiration and max allowed expiration
        expiration = (  (rand() % (mMaxExpiration - mDefaultExpiration))
                       + mDefaultExpiration);
    }
    else if ( expiration >= mMaxExpiration )
    {
        if (mMaxExpiration > spreadFloor)
        {
            // - spread it between the spreadFloor and the max allowed expiration
            expiration = (  (rand() % (mMaxExpiration - spreadFloor))
                           + spreadFloor);
        }
        else
        {                
            // Max Expiration is smaller than the spreadFloor, hence
            // spread it between the min and the max allowed expiration
            expiration = (  (rand() % (mMaxExpiration - mMinExpiration))
                           + mMinExpiration);
        }
    }
    else if ( expiration > spreadFloor )
    {
        // a normal (long) expiration
        // - spread it between the spreadFloor and the longest they asked for
        expiration = (  (rand() % (expiration - spreadFloor))
                       + spreadFloor);
    }
    else if ( expiration > mMinExpiration )
    {
        // a short but greater than minimum expiration
        // - spread it between the min and the longest they asked for
        expiration = (  (rand() % (expiration - mMinExpiration))
                       + mMinExpiration);
    }
    // Cases where the expiration is less than the min value is handled below.

    // If this is an early dialog we need to make it an established dialog.
    if(SipDialog::isEarlyDialog(dialogHandle))
    {
        UtlString establishedDialogHandle;
        if(mDialogMgr.getEstablishedDialogHandleFor(dialogHandle, establishedDialogHandle))
        {
            OsSysLog::add(FAC_SIP, PRI_WARNING,
                "Incoming early SUBSCRIBE dialog: %s matches established dialog: %s",
                dialogHandle.data(), establishedDialogHandle.data());
        }

        // make up a To tag and set it
        UtlString toTag;
        CallId::getNewTag(dialogHandle.data(), toTag);

        // Acceptable expiration, create a subscription and dialog
        if(expiration >= mMinExpiration ||
           expiration == 0 ||
           // :WORKAROUND:  Also allow expiration == 1, to support the
           // 1-second subscriptions the pick-up agent makes because
           // current Snom phones do not respond to 0-second subscriptions.
           // See XPB-399 and ENG-319.
           expiration == 1)
        {
            // Call the event-specific function to determine the resource ID
            // and event type for this SUBSCRIBE.
            handler.getKeys(subscribeRequest,
                            resourceId,
                            eventTypeKey,
                            eventType);

            // Create a dialog and subscription state even if
            // the expiration is zero as we need the dialog info
            // to route the one-time NOTIFY.  The immediately
            // expired dialog will be garbage collected.

            SipMessage* subscribeCopy = new SipMessage(subscribeRequest);
            subscribeCopy->setToFieldTag(toTag);

            // Re-get the dialog handle now that the To tag is set
            subscribeCopy->getDialogHandle(dialogHandle);

            // Create the dialog
            mDialogMgr.createDialog(*subscribeCopy, FALSE, dialogHandle);
            isNew = TRUE;

            // Create a subscription state
            state = new SubscriptionServerState();
            *((UtlString*) state) = dialogHandle;
            state->mEventTypeKey = eventTypeKey;
            state->mpLastSubscribeRequest = subscribeCopy;
            state->mResourceId = resourceId;
            subscribeCopy->getAcceptField(state->mAcceptHeaderValue);

            long now = OsDateTime::getSecsSinceEpoch();
            state->mExpirationDate = now + expiration;

            // TODO: currently the SipSubsribeServer does not handle timeout
            // events to send notifications that the subscription has ended.
            // So we do not set a timer at the end of the subscription
            state->mpExpirationTimer = NULL;

            // Create the index by resourceId and eventTypeKey key
            SubscriptionServerStateIndex* stateKey = new SubscriptionServerStateIndex;
            *((UtlString*) stateKey) = resourceId;
            stateKey->append(eventTypeKey);
            stateKey->mpState = state;

            subscribeResponse.setResponseData(subscribeCopy, 
                                              SIP_ACCEPTED_CODE,
                                              SIP_ACCEPTED_TEXT, 
                                              NULL);
            subscribeResponse.setExpiresField(expiration);
            subscribeCopy->getDialogHandle(subscribeDialogHandle);

            lock();
            mSubscriptionStatesByDialogHandle.insert(state);
            mSubscriptionStateResourceIndex.insert(stateKey);
	    if (OsSysLog::willLog(FAC_SIP, PRI_DEBUG))
	    {
	       UtlString requestContact;
	       subscribeRequest.getContactField(0, requestContact);
	       OsSysLog::add(FAC_SIP, PRI_DEBUG,
			     "SipSubscriptionMgr::updateDialogInfo insert early-dialog subscription for dialog handle '%s', key '%s', contact '%s', mExpirationDate %ld",
			     state->data(), stateKey->data(),
                             requestContact.data(), state->mExpirationDate);
            }

            // Not safe to touch these after we unlock
            stateKey = NULL;
            state = NULL;
            subscribeCopy = NULL;
            unlock();

            subscriptionSucceeded = TRUE;

            // One time subscribe?
            isSubscriptionExpired = expiration == 0;
        }
        // Expiration too small
        else
        {
            // Set expiration too small error
            subscribeResponse.setResponseData(&subscribeRequest, 
                                                SIP_TOO_BRIEF_CODE,
                                                SIP_SUB_TOO_BRIEF_TEXT);
            subscribeResponse.setMinExpiresField(mMinExpiration);
            isSubscriptionExpired = TRUE;
        }
    }

    // Not an early dialog handle -- The dialog for this message should already exist
    else
    {
        // Acceptable expiration, create a subscription and dialog
        if(expiration > mMinExpiration ||
           expiration == 0)
        {
            // Update the dialog state
            mDialogMgr.updateDialog(subscribeRequest, dialogHandle);

            // Get the subscription state and update that
            // TODO:  This assumes that no one reuses the same dialog
            // to subscribe to more than one event type.  mSubscriptionStatesByDialogHandle
            // will need to be changed to a HashBag and we will need to
            // search through to find a matching event type
            lock();
            state = (SubscriptionServerState*)
                mSubscriptionStatesByDialogHandle.find(&dialogHandle);
            if(state)
            {
                // Update the expiration time.
                long now = OsDateTime::getSecsSinceEpoch();
                state->mExpirationDate = now + expiration;
                // Record this SUBSCRIBE as the latest SUBSCRIBE request.
                if(state->mpLastSubscribeRequest)
                {
                    delete state->mpLastSubscribeRequest;
                }
                state->mpLastSubscribeRequest = new SipMessage(subscribeRequest);
                subscribeRequest.getAcceptField(state->mAcceptHeaderValue);

                // Set our Contact to the same request URI that came in
                UtlString contact;
                subscribeRequest.getRequestUri(&contact);

                // Add the angle brackets to Contact, since it is a name-addr.
                Url url(contact);
                url.includeAngleBrackets();
                contact = url.toString();

                subscribeResponse.setResponseData(&subscribeRequest, 
                                                SIP_ACCEPTED_CODE,
                                                SIP_ACCEPTED_TEXT, 
                                                contact);
                subscribeResponse.setExpiresField(expiration);
                subscriptionSucceeded = TRUE;
                isSubscriptionExpired = FALSE;
                subscribeDialogHandle = dialogHandle;

                // Set the resource information so our caller can generate a NOTIFY.
                resourceId = state->mResourceId;
                eventTypeKey = state->mEventTypeKey;
                // Unfortuantely, we don't record the eventType separately.
                eventType = state->mEventTypeKey;
            }

            // No state, but SUBSCRIBE had a to-tag.
            else
            {
               // Unknown subscription.
               subscribeResponse.setResponseData(&subscribeRequest, 
                                                 SIP_BAD_SUBSCRIPTION_CODE,
                                                 SIP_BAD_SUBSCRIPTION_TEXT);
            }
            unlock();
        }

        // Expiration too small
        else
        {
            // Set expiration too small error
            subscribeResponse.setResponseData(&subscribeRequest, 
                                                SIP_TOO_BRIEF_CODE,
                                                SIP_SUB_TOO_BRIEF_TEXT);
            subscribeResponse.setMinExpiresField(mMinExpiration);
            isSubscriptionExpired = isExpired(dialogHandle);
        }
    }

    return(subscriptionSucceeded);
}
Пример #29
0
void PUParticleSystem3D::processParticle( ParticlePool &pool, bool &firstActiveParticle, bool &firstParticle, float elapsedTime )
{
    PUParticle3D *particle = static_cast<PUParticle3D *>(pool.getFirst());
    //Mat4 ltow = getNodeToWorldTransform();
    //Vec3 scl;
    //Quaternion rot;
    //ltow.decompose(&scl, &rot, nullptr);
    while (particle){

        if (!isExpired(particle, elapsedTime)){
            particle->process(elapsedTime);

            //if (_emitter && _emitter->isEnabled())
            //    _emitter->updateEmitter(particle, elapsedTime);

            for (auto it : _emitters) {
                if (it->isEnabled() && !it->isMarkedForEmission()){
                    (static_cast<PUEmitter*>(it))->updateEmitter(particle, elapsedTime);
                }
            }

            for (auto& it : _affectors) {
                if (it->isEnabled()){
                    (static_cast<PUAffector*>(it))->process(particle, elapsedTime, firstActiveParticle);
                }
            }

            if (_render)
                static_cast<PURender *>(_render)->updateRender(particle, elapsedTime, firstActiveParticle);

            if (_isEnabled && particle->particleType != PUParticle3D::PT_VISUAL){
                if (particle->particleType == PUParticle3D::PT_EMITTER){
                    auto emitter = static_cast<PUEmitter *>(particle->particleEntityPtr);
                    emitter->setLocalPosition(particle->position);
                    executeEmitParticles(emitter, emitter->calculateRequestedParticles(elapsedTime), elapsedTime);
                }else if (particle->particleType == PUParticle3D::PT_TECHNIQUE){
                    auto system = static_cast<PUParticleSystem3D *>(particle->particleEntityPtr);
                    system->setPosition3D(particle->position);
                    system->setRotationQuat(particle->orientation);
                    //system->setScaleX(scl.x);system->setScaleY(scl.y);system->setScaleZ(scl.z);
                    system->forceUpdate(elapsedTime);
                }
            }

            firstActiveParticle = false;
            // Keep latest position
            particle->latestPosition = particle->position;

            //if (_maxVelocitySet && particle->calculateVelocity() > _maxVelocity)
            //{
            //    particle->direction *= (_maxVelocity / particle->direction.length());
            //}

            //// Update the position with the direction.
            //particle->position += (particle->direction * _particleSystemScaleVelocity * elapsedTime);
            //particle->positionInWorld = particle->position;
            //particle->orientationInWorld = particle->orientation;
            //particle->widthInWorld = particle->width;
            //particle->heightInWorld = particle->height;
            //particle->depthInWorld = particle->depth;

            //bool keepLocal = _keepLocal;
            //PUParticleSystem3D *parent = dynamic_cast<PUParticleSystem3D *>(getParent());
            //if (parent) keepLocal = keepLocal || parent->isKeepLocal();

            //if (keepLocal){
            //    ltow.transformPoint(particle->positionInWorld, &particle->positionInWorld);
            //    Vec3 ori;
            //    ltow.transformVector(Vec3(particle->orientation.x, particle->orientation.y, particle->orientation.z), &ori);
            //    particle->orientationInWorld.x = ori.x; particle->orientationInWorld.y = ori.y; particle->orientationInWorld.z = ori.z;
            //    particle->widthInWorld = scl.x * particle->width;
            //    particle->heightInWorld = scl.y * particle->height;
            //    particle->depthInWorld = scl.z * particle->depth;
            //}
            processMotion(particle, elapsedTime, firstActiveParticle);
        }
        else{
            initParticleForExpiration(particle, elapsedTime);
            pool.lockLatestData();
        }

        for (auto it : _observers){
            if (it->isEnabled()){
                it->updateObserver(particle, elapsedTime, firstParticle);
            }
        }

        if (particle->hasEventFlags(PUParticle3D::PEF_EXPIRED))
        {
            particle->setEventFlags(0);
            particle->addEventFlags(PUParticle3D::PEF_EXPIRED);
        }
        else
        {
            particle->setEventFlags(0);
        }

        particle->timeToLive -= elapsedTime;
        firstParticle = false;
        particle = static_cast<PUParticle3D *>(pool.getNext());
    }
}
Пример #30
0
/** Returns the address to which <b>addr</b> is currently mapped. If there is
 * no mapping for <b>addr</b> (or the mapping is expired), then an empty
 * string is returned. */
QString
AddressMap::mappedTo(const QString &addr) const
{
  AddressMapEntry entry = value(addr);
  return (isExpired(entry) ? QString() : entry.first);
}