Пример #1
0
int Connection::getState(int isLocal, int& cause) const
{
   cause = mConnectionStateCause;
   int state;
   if (isLocal)
      state = mLocalConnectionState;
   else
      state = mRemoteConnectionState;

   if ((mLocalConnectionState == CONNECTION_FAILED) &&
       state != mLocalConnectionState)
   {
      UtlString oldStateString, newStateString;
      getStateString(mLocalConnectionState, &oldStateString);
      getStateString(state, &newStateString);
      state = mLocalConnectionState;
   }
   else if ((mRemoteConnectionState == CONNECTION_FAILED) &&
            mRemoteConnectionState != state)
   {
      UtlString oldStateString, newStateString;
      getStateString(mRemoteConnectionState, &oldStateString);
      getStateString(state, &newStateString);
      state = mRemoteConnectionState;
   }

   return state;
}
Пример #2
0
void setState(GstState state)
{
    GstStateChangeReturn ret = gst_element_set_state(playBin, state);
    gst_element_set_state(playBin, state);

    if (ret == GST_STATE_CHANGE_SUCCESS)
    {
        printf("State = %s\n", getStateString(state));
    }
    else if (ret == GST_STATE_CHANGE_ASYNC)
    {
        GstState actualState = getState();
        if (state != actualState)
        {
            printf("Failed to set state to %s\n", getStateString(state));
            return;
        }
    }
    else if (ret == GST_STATE_CHANGE_FAILURE || ret == GST_STATE_CHANGE_NO_PREROLL)
    {
        printf("Failed to set state to %s hard failure\n", getStateString(state));
        return;
    }

    return;
}
Пример #3
0
/*@Test: test_state9_state10_transition test behavior of var1 in default and other interface */
int test_state9_state10_transition()
{
	Test_HierarchyStatemachine* machine;
	Timer dummyTimer;
	EventPool eventPool;

	/*@Desc: setup initial statemachine */
	setupStatemachine(&dummyTimer, &eventPool);

	/* get the handle only for getting the state name */
	machine = test_Hierarchy_get_handle();

	/*@Desc: check wether state is initial state (State9) */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State9") == 0);

	/*@Desc: check whether s1 is set to 2 as State 9 is in second hierarchy level */
	assert( test_Hierarchy_if_get_s1() == 2 );

	/*@Desc: run the statechart for the first time (just as dummy) */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is still in initial state (State9) */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State9") == 0);

	/*@Desc: check whether s1 is set to 2 as State 9 is in second hierarchy level */
	assert( test_Hierarchy_if_get_s1() == 2 );

	/*@Desc: raise event9 on default interface */
	test_Hierarchy_if_raise_event9();

	/*@Desc: run the statechart to trigger state change */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state10 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State10") == 0);

	/*@Desc: check whether s1 is set to 2 as State 9 is in second hierarchy level */
	assert( test_Hierarchy_if_get_s1() == 2 );

	/*@Desc: raise event10 on default interface */
	test_Hierarchy_if_raise_event10();

	/*@Desc: run the statechart to trigger state change */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state10 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State9") == 0);

	/*@Desc: check whether s1 is set to 2 as State 9 is in second hierarchy level */
	assert( test_Hierarchy_if_get_s1() == 2 );

	/*@Desc: teardown statemachine */
	teardownStatemachine(&dummyTimer, &eventPool);

	return 0;
}
Пример #4
0
int
SocketBase::doReceive(void* buffer, size_t len) throw(NetworkException)
{
    if ( state == CONNECTED )
    {
        int res = recv(sockfd, (char*) buffer, len, RECV_FLAGS);
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            if ( IS_IGNORABLE_ERROR(lastError) )
                return 0;

            if ( ! IS_DISCONECTED(lastError) ) {
                std::stringstream msg;
                msg << "Read error: " << NETSTRERROR(lastError);
                LOGGER.warning("%s", msg.str().c_str());
            }

            onDisconected();
            return 0;
        }

        if (!res) {
            LOGGER.debug("SocketBase::doReceive Disconected from server");
            onDisconected();
        }

        return res;
    }
    else
    {
        LOGGER.warning("Trying to receive on unconected socket [%s]", getStateString());
    }
    return 0;
}
Пример #5
0
int
SocketBase::doSendTo(const Address& toaddr, const void* data, size_t len) throw(NetworkException)
{
    if ( state == BOUND )
    {
        int res = sendto(sockfd, (const char*) data, len, SEND_FLAGS,
                    toaddr.getSockaddr(), toaddr.getSockaddrLen());
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            if ( ! IS_SENDTO_IGNORABLE(lastError) )
            {
                std::stringstream msg;
                msg << "Send error: " << NETSTRERROR(lastError);
                LOGGER.warning("%s", msg.str().c_str());
            }
            return 0;
        }
        return res;
    }
    else
    {
        LOGGER.warning("Trying to sendto in an unbound socket [%s]", getStateString());
    }
    return 0;
}
Пример #6
0
SOCKET
SocketBase::doAccept(Address& fromaddr) throw(NetworkException)
{
    if ( state == LISTENING )
    {
        SOCKET newsock;
        newsock= accept(sockfd, fromaddr.getSockaddr(), fromaddr.getSockaddrLenPointer());
        if ( newsock == INVALID_SOCKET )
        {
            lastError = GET_NET_ERROR();
            if ( ! IS_ACCEPT_IGNORABLE(lastError) )
            {
                std::stringstream msg;
                msg << "Accept error: " << NETSTRERROR(lastError);
                LOGGER.warning("%s", msg.str().c_str());
            }
        }
        return newsock;
    }
    else
    {
        LOGGER.warning("Trying to accept on an unlistening socket [%s]", getStateString());
    }
    return SOCKET_ERROR;
}
Пример #7
0
/**
* \brief 把TCP连接任务交给下一个任务队列,切换状态
*
*/
void zTCPTask::getNextState()
{
	//Zebra::logger->debug("zTCPTask::getNextState()");
	zTCPTask_State old_state = getState();

	switch(old_state)
	{
	case notuse:
		setState(verify);
		break;
	case verify:
		setState(sync);
		break;
	case sync:
		buffered = true;
		addToContainer();
		setState(okay);
		break;
	case okay:
		removeFromContainer();
		setState(recycle);
		break;
	case recycle:
		setState(notuse);
		break;
	}

	Zebra::logger->debug("zTCPTask::getNextState(%s:%u),%s -> %s)",getIP(),getPort(),getStateString(old_state),getStateString(getState()));
}
Пример #8
0
                    std::wstring DFASerializer::toString() {
                        if (dfa->s0 == nullptr) {
                            return L"";
                        }
                        StringBuilder *buf = new StringBuilder();
                        std::vector<DFAState*> states = dfa->getStates();
                        for (auto s : states) {
                            int n = 0;
                            n = (int)s->edges.size();
                            for (int i = 0; i < n; i++) {
                                DFAState *t = s->edges[i];
                                if (t != nullptr && t->stateNumber != INT16_MAX) {
                                    buf->append(getStateString(s));
                                    std::wstring label = getEdgeLabel(i);
                                    buf->append(L"-"); buf->append(label); buf->append(L"->"); buf->append(getStateString(t)); buf->append(L"\n");
                                }
                            }
                        }

                        std::wstring output = buf->toString();
                        if (output.length() == 0) {
                            return L"";
                        }
                        //return Utils.sortLinesInString(output);
                        return output;
                    }
Пример #9
0
int
SocketBase::doSend(const void* data, size_t len)
{
    if ( state == CONNECTED )
    {
        int res = send(sockfd, (const char*) data, len, SEND_FLAGS);
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            if ( IS_IGNORABLE_ERROR(lastError) )
                return 0;

            if ( ! IS_DISCONECTED(lastError) ) {
                std::stringstream msg;
                msg << "Send error: " << NETSTRERROR(lastError);
                LOGGER.warning("%s", msg.str().c_str());
            }

            onDisconected();
            return 0;
        }
        return res;
    }
    else
    {
        LOGGER.warning("Trying to send to unconected socket [%s]", getStateString());
    }
    return 0;
}
Пример #10
0
void
SocketBase::setNonBlocking() throw(NetworkException)
{
    if ( state >= CREATED )
    {
        int res;
#ifdef _WIN32
        unsigned long mode = 1;
        res = ioctlsocket(sockfd, FIONBIO, &mode);
#else
        res = fcntl(sockfd, F_SETFL, O_NONBLOCK);
#endif
        if ( res == SOCKET_ERROR ) {
            lastError = GET_NET_ERROR();
    //        doClose();
            std::stringstream msg;
            msg << "Couldn't set socket to nonblocking mode: " << NETSTRERROR(lastError);
            LOGGER.warning("%s", msg.str().c_str());
        }
    }
    else
    {
        LOGGER.warning("Trying to configure uncreated socket [%s]", getStateString());
    }
}
Пример #11
0
void
FileLock::display( void ) const
{
	dprintf( D_FULLDEBUG, "fd = %d\n", m_fd );
	dprintf( D_FULLDEBUG, "blocking = %s\n", m_blocking ? "TRUE" : "FALSE" );
	dprintf( D_FULLDEBUG, "state = %s\n", getStateString( m_state ) );
}
Пример #12
0
void
SocketBase::doConnect() throw(NetworkException)
{
    if ( state == CONFIGURED )
    {
        int res = connect(sockfd, addr.getSockaddr(), addr.getSockaddrLen());
        if(res == SOCKET_ERROR)
        {
            lastError = GET_NET_ERROR();
            if ( !IS_CONNECT_INPROGRESS(lastError) )
            {
                doClose();
                std::stringstream msg;
                msg << "Couldn't connect to '" << addr.getIP() << "' port "
                    << addr.getPort() << ": " << NETSTRERROR(lastError);
                throw NetworkException(msg.str());
            }
        }
        state = CONNECTING;
        disconnectTimer.reset();
        SocketManager::addSocket(this);
    }
    else
    {
        LOGGER.warning("Trying to connect to an unconfigured socket [%s]", getStateString());
    }
}
Пример #13
0
/**
* \brief 重值连接任务状态,回收连接
*
*/
void zTCPTask::resetState()
{
	//Zebra::logger->debug("zTCPTask::resetState");
	zTCPTask_State old_state = getState();

	switch(old_state)
	{
	case notuse:
		/*
		* whj 
		* 如果sync情况下添加到okay管理器失败会出现okay状态resetState的可能性
		*/
		//case okay:
	case recycle:
		//不可能的
		Zebra::logger->fatal("zTCPTask::resetState:不可能 recycle -> recycle");
		break;
	case verify:
	case sync:
	case okay:
		//TODO 相同的处理方式
		break;
	}

	setState(recycle);
	Zebra::logger->debug("zTCPTask::resetState(%s:%u),%s -> %s)",getIP(),getPort(),getStateString(old_state),getStateString(getState()));
}
Пример #14
0
void
SocketBase::setNoDelay() throw(NetworkException)
{
    if ( state >= CONFIGURED )
    {
        SETSOCKOPT_PARAMTYPE val = 1;
        int res = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
    //        doClose();
            std::stringstream msg;
            msg << "Couldn't set TCP_NODELAY: " << NETSTRERROR(lastError);
            LOGGER.warning("%s", msg.str().c_str());
        }
    }
    else
    {
        LOGGER.warning("Trying to set nodelay on an unconfigured socket [%s]", getStateString());
    }
}
Пример #15
0
void
SocketBase::doListen() throw(NetworkException)
{
    if ( state == BOUND )
    {
        int res = listen(sockfd, 20);
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            doClose();
            std::stringstream msg;
            msg << "Couldn't listen on socket: " << NETSTRERROR(lastError);
            throw NetworkException(msg.str());
        }
        state = LISTENING;
    }
    else
    {
        LOGGER.warning("Trying to listen on an unbound socket [%s]", getStateString());
    }
}
Пример #16
0
void
SocketBase::setReuseAddr() throw(NetworkException)
{
    if ( state == CONFIGURED )
    {
        SETSOCKOPT_PARAMTYPE val = 1;
        int res = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
    //        doClose();
            std::stringstream msg;
            msg << "Couldn't set SO_REUSEADDR: " << NETSTRERROR(lastError);
            LOGGER.warning("%s", msg.str().c_str());
        }
    }
    else
    {
        LOGGER.warning("Trying to set reuse addr on an unconfigured socket [%s]", getStateString());
    }
}
Пример #17
0
UtlBoolean CpGhostConnection::transferControllerStatus(int connectionState, int cause)
{
#ifdef TEST_PRINT
    UtlString connState;
    getStateString(connectionState, &connState);
    osPrintf("CpGhostConnection::transferControllerStatus state: %s cause: %d\n",
        connState.data(), cause);
         connState.remove(0);
#endif
    setState(connectionState, CONNECTION_REMOTE, cause);
    /** SIPXTAPI: TBD **/

    // If the transfer suceeded, imediately go to UNKNOWN as
    // we will not receive notification of further state changes
    if(connectionState == CONNECTION_ESTABLISHED)
    {
        setState(CONNECTION_UNKNOWN, CONNECTION_REMOTE, CONNECTION_CAUSE_TRANSFER);
        /** SIPXTAPI: TBD **/
    }

    return(TRUE);
}
Пример #18
0
GstState getState()
{
    GstState state;
    GstState pending;
    GstStateChangeReturn ret = gst_element_get_state(playBin, &state, &pending, 10 * GST_SECOND);

    if (ret == GST_STATE_CHANGE_SUCCESS)
    {
        printf("State = %s\n", getStateString(state));
        return state;
    }
    else if (ret == GST_STATE_CHANGE_ASYNC)
    {
        printf("Query state failed, still performing change\n");
    }
    else
    {
        printf("Query state failed, hard failure\n");
    }

    return GST_STATE_NULL;
}
Пример #19
0
	/* iostreamBase interface. */
/*virtual*/ ostream &
_TDL_SpawnStatementData::printObject (
				   ostream    & theOstream,
				   const char * theIndentString /*=""*/ ) const
{
  char  subIndentString [ iostreamBase::MAXIMUM_INDENT ];
  iostreamBase::createSubIndentString ( subIndentString, theIndentString );

  theOstream << theIndentString << "-Begin- _TDL_SpawnStatementData  "
	     << ((void *)this)  << endl

	     << theIndentString
	     << " Associated with: " << ((void *) & (getSpawnStatement()) )
	     << "  ( \"" << getName() << "\" )" << endl

	     << theIndentString << " State..........: \""
	     << getStateString() << "\"  (" << int4(getState()) << ")" << endl

	     << theIndentString << " handleRef......: "
	     << ((void *)  ( getNodeHandle() . operator*() )) << endl

	     << theIndentString << " SpawnStatementTreeNodes:" << endl;

	/* Do this manually here to avoid an endless loop. */
  for ( _TDL_Snode * node  = getSpawnStatementTreeNodeSlist() . getFirstNode();
	             node != (_TDL_Snode *) NULL;
	             node  = node -> getNextNode()
       )
  {
    theOstream << theIndentString << "   _TDL_SpawnStatementTreeNode:  "
	       << ((void *) node)  << endl;
  }

  theOstream << theIndentString << "--End-- _TDL_SpawnStatementData  "
	     << ((void *)this)  << endl;

  return theOstream;
}
Пример #20
0
void
SocketBase::bindSocketTo(const Address& toaddr) throw(NetworkException)
{
    if ( state == CONFIGURED )
    {
        int res = bind(sockfd, toaddr.getSockaddr(), toaddr.getSockaddrLen());
        if(res == SOCKET_ERROR) {
            lastError = GET_NET_ERROR();
            doClose();
            std::stringstream msg;
            msg << "Couldn't bind socket to address '"
                << toaddr.getIP() << "' port " << toaddr.getPort()
                << ": " << NETSTRERROR(lastError);
            throw NetworkException(msg.str());
        }
        SocketManager::addSocket(this);
        state = BOUND;
    }
    else
    {
        LOGGER.warning("Trying to bind to a socket != CONFIGURED [%s]", getStateString());
    }
}
Пример #21
0
void
SocketBase::create () throw(NetworkException)
{
    if ( state == RESOLVED )
    {
        sockfd = socket(PF_INET, addr.socktype, addr.protocol);

        LOGGER.debug("SocketBase:: Create [%s:%d] socket", (addr.socktype == SOCK_STREAM)?"tcp":"udp",sockfd);

        if(sockfd == INVALID_SOCKET)
        {
            lastError = GET_NET_ERROR();
            std::stringstream msg;
            msg << "Couldn't create socket: " << NETSTRERROR(lastError);
            throw NetworkException(msg.str());
        }
        state = CREATED;
    }
    else
    {
        LOGGER.warning("Trying to recreate a socket [%s]", getStateString());
    }
}
Пример #22
0
/*@Test: initialJumpToState3 test, if the initial state in state2 is activated */
int initialJumpToState3()
{
	Test_DeepHistoryStatemachine* machine;
	Timer dummyTimer;
	EventPool eventPool;
	Test_DeepHistoryIf* iface;

	/*@Desc: setup initial statemachine */
	setupStatemachine(&dummyTimer, &eventPool);

	/* get the handle only for getting the state name */
	machine = test_DeepHistory_get_handle();

	iface = test_DeepHistoryStatemachine_get_iface();

	/*@Desc: check the initial state at position 0 to be State1 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine,0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine,0)), "State1") == 0);

	test_DeepHistory_if_raise_event1(iface);

	test_DeepHistoryStatemachine_runCycle();

	/*@Desc: check the initial state at position 1 to be no State */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine,0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine,0)), "State3") == 0);

	test_DeepHistory_if_raise_event2(iface);

	test_DeepHistoryStatemachine_runCycle();

	/*@Desc: check the initial state at position 2 to be no State */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine,0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine,0)), "State1") == 0);


	/*@Desc: teardown statemachine */
	teardownStatemachine(&dummyTimer, &eventPool);

	return 0;
}
Пример #23
0
// Update input to the screen 
void LightScreen::updateInput(KeyHandler* mKeyH, MouseHandler* mMouseH){
	UIScreen::updateInput(mKeyH, mMouseH);

	// Update UI Based on state 
	if (screenShown)
	{
		// Update move state
		if (state == LSTATE_MOVE){
			if (subState == SMOVE_START){
				// Check for click and make sure not clicking on menu 
				if (mMouseH->isLeftDown() && !mMouseH->wasLeftDown()
					&& mMouseH->getX() > menuWidth)
				{
					x1 = clampX(mMouseH->getX());
					y1 = clampY(mMouseH->getY());

					// Check if clicking box
					Box* b = bHand->contains(x1, y1);
					if (b != NULL){
						moveBox = b;
						subState = SMOVE_BOX;
						lTitle->setText(getStateString());
						return;
					}
				}
			}
			else if (subState == SMOVE_BOX){
				// Check for release 
				if (!mMouseH->isLeftDown()){
					moveBox = NULL;
					subState = SMOVE_START;
					lTitle->setText(getStateString());
					return;
				}

				// Get distance change 
				x2 = clampX(mMouseH->getX()) - x1;
				y2 = clampY(mMouseH->getY()) - y1;

				// Check if valid 
				bool validMove = true;
				if (!validX(moveBox->getX() + x2) ||
					!validX(moveBox->getX() + moveBox->getWidth() + x2) ||
					!validY(moveBox->getY() + y2) ||
					!validY(moveBox->getY() + moveBox->getHeight() + y2))
					validMove = false;
				
				// Move if valid 
				if (validMove){
					moveBox->setLocation(moveBox->getX() + x2, moveBox->getY() + y2);
					lMap.invalidate();
				}

				// Set old location 
				x1 = clampX(mMouseH->getX());
				y1 = clampY(mMouseH->getY());

				return;
			}
		}
		// Update add state 
		else if (state == LSTATE_ADD){
			if (subState == SADD_START){
				// Check for click and make sure not clicking on menu 
				if (mMouseH->isLeftDown() && !mMouseH->wasLeftDown() 
					&& mMouseH->getX() > menuWidth)
				{
					x1 = x2 = clampX(mMouseH->getX());
					y1 = y2 = clampY(mMouseH->getY());
					subState = SADD_DRAG;
					lTitle->setText(getStateString());
				}
			}
			else if (subState == SADD_DRAG){
				x2 = clampX(mMouseH->getX());
				y2 = clampY(mMouseH->getY());

				// Check for release 
				if (!mMouseH->isLeftDown() && mMouseH->wasLeftDown())
				{
					addBox(std::min(x1,x2), std::min(y1,y2), abs(x1-x2), abs(y1-y2));
					subState = SADD_START;
					lTitle->setText(getStateString());
				}
			} 
		}
		// Update remove state 
		else if (state == LSTATE_REMOVE){
			if (mMouseH->isLeftDown() && !mMouseH->wasLeftDown()){
				removeBox(bHand->contains(mMouseH->getX(), mMouseH->getY()));
			}
		}
		// Update set light
		else if (state == LSTATE_SETLIGHT){
			if (mMouseH->isLeftDown() && mMouseH->getX() > menuWidth){
				lMap.setLightLoc(
					clampX(mMouseH->getX()), clampY(mMouseH->getY()));
			}
		}

		// Swap screen states
		bMove->updateInput(mKeyH, mMouseH);
		if (bMove->wasClicked()){
			state = LSTATE_MOVE;
			subState = SMOVE_START;
			lTitle->setText(getStateString());
		}
		bAdd->updateInput(mKeyH, mMouseH);
		if (bAdd->wasClicked()){
			state = LSTATE_ADD;
			subState = SADD_START;
			lTitle->setText(getStateString());
		}
		bRemove->updateInput(mKeyH, mMouseH);
		if (bRemove->wasClicked()){
			state = LSTATE_REMOVE;
			lTitle->setText(getStateString());
		}
		bSetLight->updateInput(mKeyH, mMouseH);
		if (bSetLight->wasClicked()){
			state = LSTATE_SETLIGHT;
			lTitle->setText(getStateString());
		}
		
		// Check for clear boxes
		bClear->updateInput(mKeyH, mMouseH);
		if (bClear->wasClicked()){
			bHand->clear();
			lMap.clear();

			// Readd corners 
			lMap.addPoint(&tlC);
			lMap.addPoint(&trC);
			lMap.addPoint(&blC);
			lMap.addPoint(&brC);
		}

		// Check for show light
		cbShowLight->updateInput(mKeyH, mMouseH);
		drawLight = cbShowLight->Checked();

		// Update light size
		vsLightSize->updateInput(mKeyH, mMouseH);
		if (abs(vsLightSize->getValue() - lMap.getLightSize()) > 0.000001f){
			lMap.setLightSize(vsLightSize->getValue());
			if (state != LSTATE_CHANGE_LIGHT_SIZE){
				state = LSTATE_CHANGE_LIGHT_SIZE;
				lTitle->setText(getStateString());
			}
		}

		// Update ray count
		vsRayCount->updateInput(mKeyH, mMouseH);
		if (abs((int)vsRayCount->getValue() - lMap.getRayCount()) > 0.000001f){
			lMap.setRayCount((int)vsRayCount->getValue());
			lRayCount->setText(std::string("Ray Count: ") + toString(lMap.getRayCount()));
			if (state != LSTATE_CHANGE_LIGHT_SIZE){
				state = LSTATE_CHANGE_LIGHT_SIZE;
				lTitle->setText(getStateString());
			}
		}

		// Update darkness 
		vsDarkness->updateInput(mKeyH, mMouseH);
		if (abs(vsDarkness->getValue() - lightDarkness) > 0.000001f){
			lightDarkness = vsDarkness->getValue();
			if (state != LSTATE_DARKNESS){
				state = LSTATE_DARKNESS;
				lTitle->setText(getStateString());
			}
		}

		// Update checkboxes
		cbMethod1->updateInput(mKeyH, mMouseH);
		if (cbMethod1->CheckChanged()){
			cbMethod2->setChecked(!cbMethod1->Checked());
			lMap.setMethod1(cbMethod1->Checked());
			lMap.invalidate();
		}
		cbMethod2->updateInput(mKeyH, mMouseH);
		if (cbMethod2->CheckChanged()){
			cbMethod1->setChecked(!cbMethod2->Checked());
			lMap.setMethod1(!cbMethod2->Checked());
			lMap.invalidate();
		}

		// Check for hide screen
		bHide->updateInput(mKeyH, mMouseH);
		if (bHide->wasClicked()) hide();
	}
	else {
		// Check for show screen
		bShow->updateInput(mKeyH, mMouseH);
		if (bShow->wasClicked()) show();
	}
}
Пример #24
0
/*
 * Given the potential for things to mess up here,
 * lets add a little extra error checking...
 */
status_t
_TDL_SpawnStatementData::verifyDistributedCorrectly() const
{
  status_t       returnValue       = SUCCESS;
  _TDL_OnAgent * onAgentConstraint = findOnAgentConstraint();

  if ( getState() != _TDL_SpawnStatementData::NOT_ALLOCATED )
  {
    if ( getNodeHandle() . isNull() )
    {
      TDL::getLogStream()
	<< "[_TDL_SpawnStatementData:verifyDistributedCorrectly]  "
	<< "Internal Error:  "
	<< "State=\"" << getStateString()
	<< "\", but TCM_Task_Tree_Ref is NULL."
	<< endl;
      returnValue = FAILURE;
    }
    else
    {
      if (    _TDL_DO_CHECK_IF_TASK_DISTRIBUTED ( getNodeHandle() )
	   != ( onAgentConstraint != (_TDL_OnAgent *) NULL )     )
      {
	TDL::getLogStream()
	  << endl << endl << endl
	  << "[_TDL_SpawnStatementData:isDistributed]  "
	  << "URGENT INTERNAL ERROR:  "
	  << "SpawnState = \"" << getStateString()
	  << "\".   findOnAgentConstraintConst() = \""
	  << ( ( onAgentConstraint == (_TDL_OnAgent *) NULL )
	      ? "null/NON-distributed" : "NOT-null/DISTRIBUTED")
	  << "\".   TCM_IsDistributedNode(getNodeHandle) = \""
	  << ( (_TDL_DO_CHECK_IF_TASK_DISTRIBUTED (getNodeHandle()) == TRUE)
	      ? "TRUE" : "FALSE")
	  << "\".  These last two should be matching up.  They are not.  "
	  << "PLEASE REPORT THIS BUG!!!"
	  << endl << endl << endl;
	returnValue = FAILURE;
      }
    } /* IF ( getNodeHandle() . isNull() ) ...  ELSE ... */

    if ( onAgentConstraint != getCachedOnAgentConstraint() )
    {
      TDL::getLogStream()
	<< endl << endl << endl
	<< "[_TDL_SpawnStatementData:isDistributed]  "
	<< "URGENT INTERNAL ERROR:  "
	<< "spawnState = \"" << getStateString()
	<< "\".   findOnAgentConstraintConst() = \""
	<< ( ( onAgentConstraint ==  (_TDL_OnAgent *) NULL )
	    ? "NULL"
	    : onAgentConstraint -> getAgentName() )

	<< "\".   getCachedOnAgentConstraint() = \""
	<< ( ( getCachedOnAgentConstraint() ==  (_TDL_OnAgent *) NULL )
	    ? "NULL"
	    : getCachedOnAgentConstraint() -> getAgentName() )

	<< "\".  These last two should be the same.  They are not.  "
	<< "PLEASE REPORT THIS BUG!!!"
	<< endl << endl << endl;
      returnValue = FAILURE;
    }
  } /* if ( getState() != _TDL_SpawnStatementData::NOT_ALLOCATED ) */

  return returnValue;

} /* status_t _TDL_SpawnStatementData::verifyDistributedCorrectly() const */
Пример #25
0
size_t
SocketBase::doReceiveFrom(Address& fromaddr, void* buffer, size_t len) throw(NetworkException)
{
    if ( state == BOUND || state == CONNECTED )
    {
        int res = recvfrom(sockfd, (char*) buffer, len, RECV_FLAGS,
                fromaddr.getSockaddr(), fromaddr.getSockaddrLenPointer());
        if ( res == SOCKET_ERROR )
        {
            lastError = GET_NET_ERROR();
            if ( ! IS_RECVFROM_IGNORABLE(lastError) )
            {
                std::stringstream msg;
                msg << "ReceiveFrom error: " << NETSTRERROR(lastError);
                LOGGER.warning("%s", msg.str().c_str());
            }

            return 0;
        }
        return res;
    }
    else
    {
        LOGGER.warning("Trying to receivefrom on an not bound or conected socket [%s]", getStateString());
    }
    return 0;
}
Пример #26
0
/*@Test: test_traverse_to_State8_back_with_event16_transition tests whether transition to state8 and back to state10 works correct */
int test_traverse_to_State8_back_with_event16_transition()
{
	Test_HierarchyStatemachine* machine;
	Timer dummyTimer;
	EventPool eventPool;

	/*@Desc: setup initial statemachine */
	setupStatemachine(&dummyTimer, &eventPool);

	/* get the handle only for getting the state name */
	machine = test_Hierarchy_get_handle();

	/*@Desc: check wether state is initial state (State9) */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State9") == 0);

	/*@Desc: check whether s1 is set to 2 as State 9 is in second hierarchy level */
	assert( test_Hierarchy_if_get_s1() == 2 );

	/*@Desc: raise event1 on default interface */
	test_Hierarchy_if_raise_event1();

	/*@Desc: run the statechart cycle */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state3 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State3") == 0);

	/*@Desc: raise event2 on default interface */
	test_Hierarchy_if_raise_event2();

	/*@Desc: run the statechart cycle */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state5 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State5") == 0);

	/*@Desc: raise event3 on default interface */
	test_Hierarchy_if_raise_event3();

	/*@Desc: run the statechart cycle */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state7 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State7") == 0);

	/*@Desc: raise event4 on default interface */
	test_Hierarchy_if_raise_event4();

	/*@Desc: run the statechart cycle */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state8 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State8") == 0);

	/*@Desc: check whether s2 is set to 3 as State 7 is in 4th hierarchy level */
	assert( test_Hierarchy_if_get_s2() == 4 );

	/*@Desc: check whether s1 is set to 0 as State 1 has been left */
	printf( " s1 = %d\n", test_Hierarchy_if_get_s1());
	assert( test_Hierarchy_if_get_s1() == 0 );

	/*@Desc: raise event16 on default interface */
	test_Hierarchy_if_raise_event16();

	/*@Desc: run the statechart for the first time (just as dummy) */
	test_HierarchyStatemachine_runCycle();

	/*@Desc: check wether state is changed  to state10 */
	printf("%s\n", getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)));
	assert( strcmp(getStateString(statemachineBase_getState((StatemachineBase*)machine, 0)), "State10") == 0);

	/*@Desc: check whether s2 is set to 2 as State 3 is in second hierarchy level */
	printf( " s2 = %d\n", test_Hierarchy_if_get_s2());
	assert( test_Hierarchy_if_get_s2() == 0 );

	/*@Desc: check whether s1 is set to 0 as State 1 has been left */
	printf( " s1 = %d\n", test_Hierarchy_if_get_s1());
	assert( test_Hierarchy_if_get_s1() == 2 );


	/*@Desc: teardown statemachine */
	teardownStatemachine(&dummyTimer, &eventPool);

	return 0;
}
Пример #27
0
void Connection::setState(int newState, int isLocal, int newCause, int termState)
{
   UtlString oldStateString;
   UtlString newStateString;
   int currentState = isLocal ? mLocalConnectionState : mRemoteConnectionState;
   getStateString(currentState, &oldStateString);
   getStateString(newState, &newStateString);

   int metaEventId = 0;
   int metaEventType = PtEvent::META_EVENT_NONE;
   int numCalls = 0;
   const UtlString* metaEventCallIds = NULL;
   if (mpCall)
   {
      mpCall->getMetaEvent(metaEventId, metaEventType, numCalls,
                           &metaEventCallIds);
   }

   UtlString callId;
   if (mpCall) {
      mpCall->getCallId(callId);
   }
   if (callId.isNull())
      callId="null";

   UtlString strCallName;
   if (mpCall) {
      strCallName = mpCall->getName();
   }
   if (strCallName.isNull())
   {
      strCallName="null";
   }

   if (!isStateTransitionAllowed(newState, currentState))
   {
      // Under some conditions, "invalid" state changes are allowed.
      if (!(!isLocal && metaEventId > 0
            && (metaEventType == PtEvent::META_CALL_TRANSFERRING
                || metaEventType == PtEvent::META_CALL_REPLACING)))
      {
         if (newState == currentState)
         {
            Os::Logger::instance().log(FAC_CP, PRI_DEBUG,
                          "Connection::setState: "
                          "Questionable connection state change - isLocal %d, for call "
                          "'%s' with callid '%s' from %s to %s, cause %d",
                          isLocal, strCallName.data(), callId.data(),
                          oldStateString.data(), newStateString.data(), newCause);
         }
         else
         {
            Os::Logger::instance().log(FAC_CP, PRI_ERR,
                          "Connection::setState: "
                          "Invalid connection state change - isLocal %d, for call "
                          "'%s' with callid '%s' from %s to %s, cause %d",
                          isLocal, strCallName.data(), callId.data(),
                          oldStateString.data(), newStateString.data(), newCause);
         }
         return;
      }
   }

   UtlBoolean bPostStateChange = FALSE;

   if (newState != currentState ||
       newCause != CONNECTION_CAUSE_NORMAL ||
       (newState == currentState &&
           newState == CONNECTION_ALERTING &&
           (0 == isLocal)))
   {
      if (isLocal && newState == CONNECTION_DISCONNECTED)
      {
         if ((   mpCall->canDisconnectConnection(this)
              || newCause == CONNECTION_CAUSE_CANCELLED)
             && metaEventType != PtEvent::META_CALL_TRANSFERRING
             && metaEventType != PtEvent::META_CALL_REPLACING)
         {
            bPostStateChange = TRUE;
         }
      }
      else
      {
         bPostStateChange = TRUE;
      }
   }

   Os::Logger::instance().log(FAC_CP, PRI_DEBUG,
                 "Connection::setState "
                 "Call %s %s state isLocal %d\n"
                 "change\n"
                 "from %s to\n"
                 "\t %s\n"
                 "cause=%d\n"
                 "post change to upper layer %d",
            strCallName.data(),
            callId.data(),
            isLocal,
            oldStateString.data(),
            newStateString.data(),
            newCause,
            bPostStateChange);

   if (bPostStateChange)
   {
      mConnectionStateCause = newCause;
      mTerminalConnState = termState == -1 ? terminalConnectionState(newState) : termState;

      if (isLocal)
      {
         mLocalConnectionState = newState;
      }
      else
      {
         mRemoteConnectionState = newState;
      }

      postTaoListenerMessage(newState, newCause, isLocal);
   }
}
Пример #28
0
		addToContainer();
		setState(okay);
		break;
	case okay:
		removeFromContainer();
		setState(recycle);
		break;
	case recycle:
		if (terminate == TM_service_close)
			recycleConn();
		setState(close);
		final();
		break;
	}

	Zebra::logger->debug("zTCPClientTask::getNextState(%s,%u,%s -> %s)",ip.c_str(),port,getStateString(old_state),getStateString(getState()));
}

/**
* \brief 重值连接任务状态,回收连接
*
*/
void zTCPClientTask::resetState()
{
	//Zebra::logger->debug("zTCPClientTask::resetState");
	ConnState old_state = getState();

	lifeTime.now();
	setState(close);
	final();
Пример #29
0
// Initialize screen
void LightScreen::init(float screen_width, float screen_height){
	UIScreen::init(screen_width, screen_height);

	this->screen_width = screen_width;
	this->screen_height = screen_height;

	// Create title 
	lTitle = new UILabel(getStateString());
	lTitle->setLocation(menuWidth + 10.0f, 10.0f);
	lTitle->setTextSize(25.0f);
	lTitle->setColor(.058f,.828f,.941f,1.0f);
	lTitle->setupHide(HT_VERTICAL,lTitle->getY()-40.0f,.2f,true);
	lTitle->setHidden();
	// Create screen show button 
	bShow = new UIButton(10.0f,screen_height-45.0f,100.0f,35.0f, std::string("Show"));
	bShow->setupHide(HT_VERTICAL,bShow->getY()+40.0f,.2f,true);
	bShow->setHidden();
	// Create screen hide button 
	bHide = new UIButton(10.0f,screen_height-45.0f,100.0f,35.0f, std::string("Hide"));
	bHide->setupHide(HT_VERTICAL,bHide->getY()-40.0f,.2f,true);
	bHide->setHidden();
	// Create Move button 
	bMove = new UIButton(10.0f,10.0f,100.0f,35.0f, std::string("Move"));
	bMove->setupHide(HT_HOROZONTAL,bMove->getX()-150.0f,.2f,true);
	bMove->setHidden();
	// Create move light button 
	bSetLight = new UIButton(10.0f,50.0f,100.0f,35.0f, std::string("Set Light"));
	bSetLight->setupHide(HT_HOROZONTAL,bSetLight->getX()-150.0f,.2f,true);
	bSetLight->setHidden();
	// Create add button 
	bAdd = new UIButton(10.0f,90.0f,100.0f,35.0f, std::string("Add"));
	bAdd->setupHide(HT_HOROZONTAL,bAdd->getX()-150.0f,.2f,true);
	bAdd->setHidden();
	// Create remove button 
	bRemove = new UIButton(10.0f,130.0f,100.0f,35.0f, std::string("Remove"));
	bRemove->setupHide(HT_HOROZONTAL,bRemove->getX()-150.0f,.2f,true);
	bRemove->setHidden();
	// Create clear button 
	bClear = new UIButton(10.0f,170.0f,100.0f,35.0f, std::string("Clear"));
	bClear->setupHide(HT_HOROZONTAL,bClear->getX()-150.0f,.2f,true);
	bClear->setHidden();
	// Create show light checkbox 
	cbShowLight = new UICheckbox(10.0f, 210.0f,24.0f,24.0f,std::string("Show Light"));
	cbShowLight->setupHide(HT_HOROZONTAL,cbShowLight->getX()-150.0f,.2f,true);
	cbShowLight->setHidden();
	cbShowLight->setTextColor(.8f,.8f,.8f);
	// Create light size label
	lLightSize = new UILabel(std::string("Light Size"));
	lLightSize->setLocation(14.0f, 240.0f);
	lLightSize->setTextSize(16.0f);
	lLightSize->setColor(.8f,.8f,.8f,1.0f);
	lLightSize->setupHide(HT_HOROZONTAL,lLightSize->getX()-150.0f,.2f,true);
	// Create light size value slider
	vsLightSize = new UIValueSlider();
	vsLightSize->setLocation(10.0f, 260.0f);
	vsLightSize->setMinValue(0.0f);
	vsLightSize->setMaxValue(2000.0f);
	vsLightSize->setValue(500.0f);
	vsLightSize->setupHide(HT_HOROZONTAL, vsLightSize->getX() - 150.0f, .2f, true);
	// Create darkness label 
	lDarkness = new UILabel(std::string("Darkness"));
	lDarkness->setLocation(vsLightSize->getX() + 4.0f, vsLightSize->getY() + 30.0f);
	lDarkness->setTextSize(16.0f);
	lDarkness->setColor(.8f,.8f,.8f,1.0f);
	lDarkness->setupHide(HT_HOROZONTAL,lDarkness->getX()-150.0f,.2f,true);
	// Create darkness value slider 
	vsDarkness = new UIValueSlider();
	vsDarkness->setLocation(lDarkness->getX() - 4.0f, lDarkness->getY() + 20.0f);
	vsDarkness->setMinValue(0.0f);
	vsDarkness->setMaxValue(1.0f);
	vsDarkness->setValue(lightDarkness);
	vsDarkness->setupHide(HT_HOROZONTAL, vsDarkness->getX() - 150.0f, .2f, true);
	
	// Make method boxes 
	method1Box.reset(1.0f, vsDarkness->getY() + 30.0f, menuWidth-2.0f, 77.0f);
	method2Box.reset(1.0f, method1Box.getY() + method1Box.getHeight() + 10.0f, menuWidth-2.0f, 35.0f);

	// Method 1 Checkbox 
	cbMethod1 = new UICheckbox(method1Box.getX(), method1Box.getY() + 5.0f,
		24.0f,24.0f,std::string("Use Method 1"));
	cbMethod1->setupHide(HT_HOROZONTAL,cbMethod1->getX()-150.0f,.2f,true);
	cbMethod1->setTextColor(.8f,.8f,.8f);
	cbMethod1->setChecked(true);

	// Create ray count label 
	lRayCount = new UILabel(std::string("Ray Count: 180"));
	lRayCount->setLocation(cbMethod1->getX() + 12.0f, cbMethod1->getY() + 30.0f);
	lRayCount->setTextSize(16.0f);
	lRayCount->setColor(.8f,.8f,.8f,1.0f);
	lRayCount->setupHide(HT_HOROZONTAL,lRayCount->getX()-150.0f,.2f,true);
	// Create ray count value slider 
	vsRayCount = new UIValueSlider();
	vsRayCount->setLocation(lRayCount->getX() - 4.0f, lRayCount->getY() + 20.0f);
	vsRayCount->setMinValue(5.0f);
	vsRayCount->setMaxValue(300.0f);
	vsRayCount->setValue(180.0f);
	vsRayCount->setupHide(HT_HOROZONTAL, vsRayCount->getX() - 150.0f, .2f, true);
	
	// Method 2 Checkbox 
	cbMethod2 = new UICheckbox(method2Box.getX(), method2Box.getY() + 5.0f,
		24.0f,24.0f,std::string("Use Method 2"));
	cbMethod2->setupHide(HT_HOROZONTAL,cbMethod2->getX()-150.0f,.2f,true);
	cbMethod2->setTextColor(.8f,.8f,.8f);
	cbMethod2->setChecked(false);
	
	lLightSize->setHidden();
	vsLightSize->setHidden();
	lRayCount->setHidden();
	vsRayCount->setHidden();
	lDarkness->setHidden();
	vsDarkness->setHidden();
	cbMethod1->setHidden();
	cbMethod2->setHidden();

	// Add corners
	tlC.setLocation(0.0f,0.0f);
	trC.setLocation(screen_width, 0.0f);
	blC.setLocation(0.0f, screen_height);
	brC.setLocation(screen_width, screen_height);
	lMap.addPoint(&tlC);
	lMap.addPoint(&trC);
	lMap.addPoint(&blC);
	lMap.addPoint(&brC);

	lMap.bHand = bHand;
}
Пример #30
0
bool
FileLock::obtain( LOCK_TYPE t )
{
	int counter = 0; 
#if !defined(WIN32)
	start: 
#endif	
// lock_file uses lseeks in order to lock the first 4 bytes of the file on NT
// It DOES properly reset the lseek version of the file position, but that is
// not the same (in some very inconsistent and weird ways) as the fseek one,
// so if the user has given us a FILE *, we need to make sure we don't ruin
// their current position.  The lesson here is don't use fseeks and lseeks
// interchangeably...
	int		status = -1;
	int saved_errno = -1;

	if ( m_use_kernel_mutex == -1 ) {
		m_use_kernel_mutex = param_boolean_int("FILE_LOCK_VIA_MUTEX", TRUE);
	}

		// If we have the path, we can try to lock via a mutex.  
	if ( m_path && m_use_kernel_mutex ) {
		status = lockViaMutex(t);
	}

		// We cannot lock via a mutex, or we tried and failed.
		// Try via filesystem lock.
	if ( status < 0) {
		long lPosBeforeLock = 0;
		if (m_fp) // if the user has a FILE * as well as an fd
		{
			// save their FILE*-based current position
			lPosBeforeLock = ftell(m_fp); 
		}
		
			// We're seeing sporadic test suite failures where a daemon
			// takes more than 10 seconds to write to the user log.
			// This will help narrow down where the delay is coming from.
		time_t before = time(NULL);
		status = lock_file( m_fd, t, m_blocking );
		saved_errno = errno;
		time_t after = time(NULL);
		if ( (after - before) > 5 ) {
			dprintf( D_FULLDEBUG,
					 "FileLock::obtain(%d): lock_file() took %ld seconds\n",
					 t, (after-before) );
		}
		
		if (m_fp)
		{
			// restore their FILE*-position
			fseek(m_fp, lPosBeforeLock, SEEK_SET); 	
		}

#ifndef WIN32		
			// if we deal with our own fd and are not unlocking
		if (m_delete == 1 && t != UN_LOCK){
			struct stat si; 
			fstat(m_fd, &si);
				// no more hard links ... it was deleted while we were waiting
				// in that case we need to reopen and restart
			if ( si.st_nlink < 1 ){
				release();
				close(m_fd);
				bool initResult;
				if (m_orig_path != NULL && strcmp(m_path, m_orig_path) != 0)
					initResult = initLockFile(false);
				else 
					initResult = initLockFile(true);
				if (!initResult) {
					dprintf(D_FULLDEBUG, "Lock file (%s) cannot be reopened \n", m_path);
					if (m_orig_path) {
						dprintf(D_FULLDEBUG, "Opening and locking the actual log file (%s) since lock file cannot be accessed! \n", m_orig_path);
						m_fd = safe_open_wrapper_follow(m_orig_path, O_CREAT | O_RDWR , 0644);
					} 
				}
				
				if (m_fd < 0) {
					dprintf(D_FULLDEBUG, "Opening the log file %s to lock failed. \n", m_path);
				}
				++counter;
					// let's retry at most 5 times
				if (counter < 6) {
					goto start;
				}
				else 
					status = -1;
			}		
		}
#endif		
	}

	if( status == 0 ) {
		m_state = t;
	}
	if ( status != 0 ) {
		dprintf( D_ALWAYS, "FileLock::obtain(%d) failed - errno %d (%s)\n",
	                t, saved_errno, strerror(saved_errno) );
	}
	else {
		UtcTime	now( true );
		dprintf( D_FULLDEBUG,
				 "FileLock::obtain(%d) - @%.6f lock on %s now %s\n",
				 t, now.combined(), m_path, getStateString(t) );
	}
	return status == 0;
}