Ejemplo n.º 1
0
/*
 * Pipeline broadcast. This protocol takes 1 turn to broadcast, the node
 * performing the broadcast sends the message to the next note, which in turn
 * transmits the message to its neighbour and so on.
 * Note that like every functions defined here, they have the type NodesFct.
 */
void PipelineBroadcast(int id, Message m){
    char* event;
    Message msg, fwd;
    int neighbor;

    // Event Rules
    while((event = getNextExternalEvent(id)) != NULL){
        printf("event received %i %s\n",id, event); 
        // Read the first event
        if(0 == strcmp(event, "broadcast")){
            neighbor = (id + 1) % getNbNodes();
            msg = initMessage("Hello\0", id, id, neighbor);
            Send(msg);
            deliver(msg,id);
        }
        free(event);
    }

    // Message Rules
    if(NULL != m){
        deliver(m, id);

        // Forward the message if need be
        neighbor = (id + 1) % getNbNodes();
        if(neighbor != m->origin){
            fwd = initMessage(m->msg, m->origin, id, neighbor);
            Send(fwd);
        }

        // Free the local message
        deleteMessage(m);
    }
}
Ejemplo n.º 2
0
/*
 * Basic broadcast. The broadcast takes N turns, all sends are done by the
 * same node (one at each turn).
 * Note that like every functions defined here, they have the type NodesFct.
 */
void BasicBroadcast(int id, Message m){
    char* event;
    Message msgOut;
    int i;

    //Events Rules
    while((event = getNextExternalEvent(id)) != NULL){
        printf("event received %d %s\n", id, event); 
        //Read the first event
        if(!strcmp(event, "broadcast")){
            //start a basic broadcast:
            //send hello to every nodes
            for(i = 0; i < getNbNodes(); i++){
                msgOut = initMessage("Hello\0", id, id, i);
                if(i != id){
                    Send(msgOut);
                } else {
                    deliver(msgOut,id);
                    deleteMessage(msgOut);
                }
            }
        }
        free(event);
    }

    //Message Rules
    if(NULL != m){
        deliver(m,id);
        deleteMessage(m);
    }
}
Ejemplo n.º 3
0
/*
 * Total Order Broadcast with good throughput.
 * Note that like every functions defined here, they have the type NodesFct.
 */
void TOBThroughputRodBroadcast(int id, Message m){
    char* event;
    Message msgOut;

    //Events Rules
    while((event = getNextExternalEvent(id)) != NULL){
        printf("Event received %d %s\n", id, event); 
        //Read the first event
        if(!strcmp(event, "broadcast")){
            if(0 == id){
                // The broadcast is your own, deliver
                msgOut = initMessage("Hello\0", id, id, id);
                deliver(msgOut, id);
                deleteMessage(msgOut);
                // Pass the message to your successor

                if(1 != getNbNodes()){
                    msgOut = initMessage("Hello\0", 0, 0, 1);
                    Send(msgOut);
                }
            } else {
                // Send the message to process 0
                msgOut = initMessage("Hello\0", id, id, 0);
                Send(msgOut);
            }
        }
        free(event);
    }

    // Message Rules
    if(NULL != m){
        if(0 == id)
            printf("0 receives a message to relay from %i\n", m->sender);

        deliver(m, id);

        // If not the last of the pipeline...
	if(id != getNbNodes() - 1){
            // Transfer the message to you successor
            msgOut = initMessage(m->msg, m->origin, id, id + 1 % getNbNodes());
            Send(msgOut);
	}

        deleteMessage(m);
    }
}
Ejemplo n.º 4
0
/*
 * Tree broadcast. This protocol needs log(NbNodes) turn to broadcast.
 * Every node sends to its succesors.
 * Note that like every functions defined here, they have the type NodesFct.
 */
void TreeBroadcast(int id, Message m){
    char* event;
    Message msgOut;
    int nTurn;

    //Events Rules
    while((event = getNextExternalEvent(id)) != NULL){
        printf("Event received %d %s\n", id, event); 
        //Read the first event
        if(!strcmp(event, "broadcast")){
            //start a tree broadcast:
            //Iniatialize the message
            for(nTurn = 0; nTurn < log2(getNbNodes()); nTurn++){
                //at the first step of the tree broadcast, we send a message
                //to our successor
                msgOut = initMessage("Hello\0", id, id, (int)(pow(2,nTurn)+id)%getNbNodes());
                Send(msgOut);
            }
            // Deliver the message localy
            msgOut = initMessage("Hello\0", id, id, id);
            deliver(msgOut,id);
            deleteMessage(msgOut);
        }
        free(event);
    }

    //Message Rules
    if(NULL != m){
        deliver(m,id);
        //at a step n, a message is sent at a distance 2^n
        //the distance is not exactly the difference between the sender and the
        //receiver id because of the mod N
        if(m->sender < m->receiv)
            nTurn=log2(m->receiv-m->sender);
        else
            nTurn=log2(getNbNodes()-m->sender+m->receiv);
        //this turn is done, let's do the others
        //now we can send all the others messages
        for(nTurn++; nTurn<log2(getNbNodes()); nTurn++){
            msgOut = initMessage(m->msg, m->origin, id, ((int)(pow(2,nTurn)+id))%getNbNodes());
            Send(msgOut);
        }
        deleteMessage(m);
    }
}
Ejemplo n.º 5
0
/*
 * Total Order Broadcast with good latency.
 * Note that like every functions defined here, they have the type NodesFct.
 */
void TOBLatencyBroadcast(int id, Message m){
    char* event;
    Message msgOut;
    int i;

    //Events Rules
    while((event = getNextExternalEvent(id)) != NULL){
        printf("Event received %d %s\n", id, event); 
        //Read the first event
        if(!strcmp(event, "broadcast")){
            if(0 == id){
                // The broadcast is your own, deliver
                msgOut = initMessage("Hello\0", id, id, id);
                deliver(msgOut, id);
                deleteMessage(msgOut);
                // Pass the message to your childs
                for(i = 1; i < getNbNodes(); i *= 2){
                    msgOut = initMessage("Hello\0", id, id, i);
                    Send(msgOut);
                }
            } else {
                // Send the message to process 0
                msgOut = initMessage("Hello\0", id, id, 0);
                Send(msgOut);
            }
        }
        free(event);
    }

    // Message Rules
    if(NULL != m){
        if(0 == id)
            printf("0 receives a message to relay from %i\n", m->sender);

        deliver(m, id);

        for(i = 2 * id + 1; i < getNbNodes(); i *= 2){
            msgOut = initMessage(m->msg, m->origin, id, i);
            Send(msgOut);
        }

        deleteMessage(m);
    }
}
Ejemplo n.º 6
0
/*
 * create an ack at the format: clk initiator ack
 * clk      : the timestamp of the message to acknowledge
 * init     : the original sender of the message to acknowledge
 * sender   : the node who send the ack
 * receiver : the node ho will receive the ack
 * returns the ack
 */
Message Ack(int clk, int init, int sender, int receiver){
    char *msgTxt;
    Message m;
    if((msgTxt=malloc(sizeof(char)*(intToStringSize+3/*ack*/)))==NULL){
        fprintf(stderr,"malloc fail at Ack\n");
        exit(EXIT_FAILURE);
    }
    sprintf(msgTxt, "%d ack", clk);
    m=initMessage(msgTxt,init,sender,receiver); 
    free(msgTxt);
    return m;
}
Ejemplo n.º 7
0
int CSocketClient::start(int nSocketType, const char* cszAddr, short nPort, int nStyle)
{
	if ( AF_UNIX == nSocketType )
	{
		setDomainSocketPath( cszAddr );
	}
	else if ( AF_INET == nSocketType )
	{
		if ( -1 == setInetSocket( cszAddr, nPort ) )
		{
			_DBG( "set INET socket address & port fail" );
			return -1;
		}
	}

	if ( -1 != createSocket( nSocketType, nStyle ) )
	{
		if ( SOCK_STREAM == nStyle )
		{
			if ( -1 == connectServer() )
			{
				socketClose();
				return -1;
			}
		}

		if ( -1 != externalEvent.m_nMsgId )
		{
			if ( -1 == initMessage( externalEvent.m_nMsgId ) )
			{
				throwException( "socket client create message id fail" );
			}
			else
			{
				threadHandler->createThread( threadMessageReceive, this );
				threadHandler->createThread( threadSocketRecvHandler, this );
			}
		}

		_DBG( "[Socket Client] Socket connect success, FD:%d", getSocketfd() );
		return getSocketfd();
	}

	return -1;
}
Ejemplo n.º 8
0
int main(void) {
	WDTCTL = WDTPW | WDTHOLD;	// Stop watchdog time
	configClocks();
	configPins();
	configTimerA0();
	configTimerA1();
	configADC10();
	initSPI();
	initMessage();

	_enable_interrupts();		// enable global interrupts

	while (1) {
		//pack our new message
		GPIOUpdate();
		currentUpdate();
		messagePackServoValues(servoValue);
	}
}
Ejemplo n.º 9
0
int respondToRequests() {
    int listener_fd = get_listener_fd();
    if (listener_fd == -1) return 1;
    int connection_fd;
    while (0 <= (connection_fd = get_connection_fd(listener_fd))) {
        struct SMJobBlessMessage messageIn, messageOut;
        if (readMessage(connection_fd, &messageIn)) break;
        initMessage(messageOut, messageIn.command);
        switch (messageIn.command) {
            case SMJobBless_Version:
                messageOut.dataSize = 3;
                messageOut.data[0] = kVersionPart1;
                messageOut.data[1] = kVersionPart2;
                messageOut.data[2] = kVersionPart3;
                break;
                
            case SMJobBless_PID: {
                int pid = getpid();
                messageOut.dataSize = sizeof(pid);
                memcpy(messageOut.data, &pid, messageOut.dataSize);
                break;
            }
            default:
                syslog(LOG_NOTICE, "Unknown command: %hhd\n", messageIn.command);
                char* message = "Unknown command!";
                messageOut.command = SMJobBless_Error;
                messageOut.dataSize = strlen(message) + 1;    // add trailing \0
                strcpy((char *) messageOut.data, message);
                break;
        }
        int count = messageSize(&messageOut);
        int written = write(connection_fd, &messageOut, count);
        if (written != count) {
            syslog(LOG_NOTICE, "tried to write %i, but wrote %i", count, written);
            break;
        }
        close(connection_fd);
    }
    close(listener_fd);
    if (0 < connection_fd) close(connection_fd);
	return connection_fd == -1 ? 0 : 1;
}
Ejemplo n.º 10
0
int CHttpServer::start(int nSocketType, const char* cszAddr, short nPort)
{
	int nMsgId;

	nMsgId = initMessage(MSG_ID);
	if (-1 == nMsgId)
	{
		throwException("socket server create message id fail");
		return -1;
	}

	threadHandler->createThread(threadMessageReceive, NULL);

	if (AF_UNIX == nSocketType)
	{
		setDomainSocketPath(cszAddr);
	}
	else if (AF_INET == nSocketType)
	{
		if (-1 == setInetSocket(cszAddr, nPort))
		{
			_DBG("set INET socket address & port fail");
			return -1;
		}
	}

	if (-1 != createSocket(nSocketType))
	{
		if (-1 != socketBind())
		{
			if (-1 != socketListen(BACKLOG))
			{
				threadHandler->createThread(threadSocketAccept, NULL);
				return 0;
			}
		}
	}

	return -1;
}
Ejemplo n.º 11
0
void TargetTracker::tracking(std::vector<TargetState> states)
{
    std::vector<TargetState>::const_iterator iter;
    TargetState tState;
    KalmanFilter *filter;
    SingleTarget *target;
    qDebug() << "测量值:";

    for (iter = states.begin(); iter != states.end(); ++iter)
    {
        tState = *iter;
        tState.state.print();

        filter = findFilter(tState.groupId, tState.targetId);
        target = findTarget(tState.groupId, tState.targetId);
        if (target == NULL) continue;
        if (filter == NULL) continue;
        if (target->getStateCount() == 0) {
            // 第一次获取目标的状态,直接保存,不做任何计算。
            target->addState(tState.state);
            filter->setState(tState.state.getData());
            continue;
        }
        //计算一步预测值
        Matrix matrix = filter->estimate();
        // 根据测量值更新预测数据
        filter->updateByMeasure(tState.state.getData());
        State s;
        s.setData(matrix);
        s.setTime(tState.time);
        target->addState(s);
    }

    //项目验收后去掉
    initMessage();

    printTargetGroups();
}
Ejemplo n.º 12
0
/*
 * Total Order Broadcast with good throughput.
 * Note that like every functions defined here, they have the type NodesFct.
 */
void TOBThroughputBroadcast(int id, Message m){

    PipelineAckData_t data;
    int argSize, ackOrigin;
    char *event, *eventArg, *msgTxt;
    Message mOut;
    NumberedMessage NumMsg, temp;

    if((data=(PipelineAckData_t)getData(id))==NULL){
        //Initialization

        if((data=malloc(sizeof(struct _PipleineAckData_t)))==NULL){
            fprintf(stderr,"malloc fail at TOBThroughputBroadcast\n");
            exit(EXIT_FAILURE);
        }

        data->clock=0;
        data->next=(id+1)%getNbNodes();
        //        data->pred=(id==0)?getNbNodes()-1:id-1;
        data->pending=newSortedList(NumberedMsgComp);
        setData(id,data);
    }

    if(m==NULL){
        // Event Rules
        if((event = getNextExternalEvent(id)) != NULL){
            printf("event received %i %s\n",id, event); 
            // Read the first event
            if(event==strstr(event, "broadcast")){
                //there is an event : increment the clock
                data->clock++;
                //event is someting like broadcast <string>
                if((eventArg=malloc(sizeof(char)*maxArgSize))==NULL){
                    fprintf(stderr,"malloc fail at TOBThroughputBroadcast\n");
                    exit(EXIT_FAILURE);
                }
                if(1>sscanf(event, "broadcast %s", eventArg)){
                    sscanf("hello","%s",eventArg);
                }
                //eventArg is either the string to broadcast, or "hello"
                argSize=strlen(eventArg);
                if((msgTxt=malloc((intToStringSize+1+argSize)*sizeof(char)))==NULL){
                    fprintf(stderr,"malloc fail at TOBThroughputBroadcast\n");
                    exit(EXIT_FAILURE);
                }
                sprintf(msgTxt, "%d ",data->clock);
                strncat(msgTxt, eventArg, argSize); 
                //Now the message text have the format: clk <arg>
                if((NumMsg=malloc(sizeof(struct _NumberedMessage)))==NULL){
                    fprintf(stderr,"malloc fail at TOBThroughputBroadcast\n");
                    exit(EXIT_FAILURE);
                }
                NumMsg->clk=data->clock;
                //waiting for 1 ack
                //creating the actual message
                NumMsg->m=initMessage(msgTxt,id,id,data->next);
                free(msgTxt);
                NumMsg->origin=id;
                if(data->next==id){
                    //we are the only process of the system
                    deliver(NumMsg->m,id);
                    free(NumMsg->m->msg);
                    free(NumMsg->m);
                    free(NumMsg);
                }else{
                    //and send it
                    Send(copyMessage(NumMsg->m));
                    //Finally store the numbered msg in the pending list
                    AddSorted(NumMsg,data->pending);
                }
            }
            free(event);
        }

    }else{
        // Message Rules
        if((NumMsg=malloc(sizeof(struct _NumberedMessage)))==NULL){
            fprintf(stderr,"malloc fail at TOBThroughputBroadcast\n");
            exit(EXIT_FAILURE);
        }

        //this is a new message at the format:
        //clock <text> where text is either ack or the text of the
        //message
        //We have to parse the clock of the broadcast
        extractInt(m->msg, &(NumMsg->clk));
        NumMsg->origin=m->origin;
        //don't forget to update the clock
        data->clock=MAX(NumMsg->clk,data->clock)+1;

        if(strstr(m->msg,"ack")==NULL){
            printf("%s received by %d from %d but not delivered yet\n", m->msg, id, m->sender);
            //m is an actual message
            NumMsg->m=m;
            if(m->origin!=data->next){
                //We need to forward the message
                mOut=initMessage(m->msg,m->origin,id,data->next);
                Send(mOut);
                AddSorted(NumMsg,data->pending);
            }else{
                AddSorted(NumMsg,data->pending);
                //we deliver all the older messages
                mOut=NULL;
                while((temp=getFirst(data->pending))!=NULL && NumMsg!=NULL && NumberedMsgComp(temp,NumMsg)<=0){
                    //we remove the message from the pending list
                    RemoveFirst(data->pending);
                    if(!NumberedMsgComp(temp,NumMsg)){
                        //to ensure we stop after that
                        NumMsg=NULL;
                    }
                    //prepare an ack
                    if(temp->origin!=id){
                        if(mOut!=NULL){
                            free(mOut);
                        }
                        mOut=Ack(temp->clk,temp->origin,id,data->next);
                    }
                    //deliver
                    deliver(temp->m,id);
                    //we can free the message
                    free(temp->m->msg);
                    free(temp->m);
                    free(temp);
                }
                //if we have managed to deliver a message
                //we acknowleged the older message delvered
                if(mOut){
                    Send(mOut);
                }
            }

        }else{
            //this is an ack
            printf("%s received by %d from %d origin %d\n", m->msg, id, m->sender, m->origin);
            //we deliver all the older messages
            mOut=NULL;
            while((temp=getFirst(data->pending))!=NULL && NumMsg!=NULL && NumberedMsgComp(temp,NumMsg)<=0){
                //we remove the message from the pending list
                RemoveFirst(data->pending);
                //prepare an ack
                ackOrigin=((temp->origin+getNbNodes()-1)%getNbNodes());
                if(ackOrigin!=data->next){
                    if(mOut!=NULL){
                        free(mOut);
                    }
                    mOut=Ack(temp->clk,temp->origin,id,data->next);
                }
                //deliver
                deliver(temp->m,id);
                //we can free the message
                free(temp->m->msg);
                free(temp->m);
                free(temp);
            }
            //if we have managed to deliver a message
            //we acknowleged the older message delvered
            ackOrigin=((NumMsg->origin+getNbNodes()-1)%getNbNodes());
            if(mOut){
                Send(mOut);
            }else if(Size(data->pending)==0 && ackOrigin!=data->next){
                //we haven't be able to deliver a message because our pending
                //list is empty, but the message may be blocked in someon else
                //queue so we forward the ack
                Send(Ack(NumMsg->clk,NumMsg->origin,id,data->next));
            }
            // Free the local message
            free(m->msg);
            free(m);
        }
    }

}
Ejemplo n.º 13
0
ServerModule_Chargen::ServerModule_Chargen()
{
    initMessage();
    transferredBytes_ = 0;
}
Ejemplo n.º 14
0
int main(int argc, char* argv[])
{
    /* INITIALISATIONS DES BIBLIOTHEQUES : IMG, SDL, TTF */
    IMG_Init(IMG_INIT_PNG);
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    Message msgs[NOMBRE_MESSAGES];
    initMessage(msgs);

    SDL_Surface *ecran = SDL_SetVideoMode(LARGEUR, HAUTEUR, BPP, SDL_HWSURFACE | SDL_DOUBLEBUF);

    /* Titre */
    SDL_WM_SetCaption("Duck Hunt", NULL);

    /* Icone */
    SDL_WM_SetIcon(SDL_LoadBMP("sprites/icon.bmp"), NULL);

    /* Initialisation des variables en rapport avec le temps */
    Time temps;
    initTime(temps);
    srand((unsigned)time(NULL));

    int modeJeu = 0;    // Le mode de jeu.
    int modeMenu = 1;   // Détermine la page du menu à afficher.

    Partie partie;
    partie.score = 0;
    partie.niveau = 0;
    Sprites sprites;
    Chien chien;

    Boutons boutons;
    initBouton(boutons);

    chargerImages(sprites, chien, boutons, "classique");
    boutons.bouton[BOUTON_THEME_CLASSIQUE].actif = true;

    Uint8 *keystate = SDL_GetKeyState(NULL);
    SourisEvent sourisEvent;
    initSourisEvent(sourisEvent);

    initFichiers();

    SDL_ShowCursor(SDL_DISABLE);

    menu(ecran, sprites, boutons, modeMenu, modeJeu, sourisEvent, temps, msgs, partie, chien);
    while (modeJeu != 0)
    {
        if (modeMenu != 0)
        {
            menu(ecran, sprites, boutons, modeMenu, modeJeu, sourisEvent, temps, msgs, partie, chien);
        }
        temps.currentTime = SDL_GetTicks();
        partie.alreadyShot = partie.alreadyGetEvent = partie.alreadyClic = false;
        for (int i = 0 ; i < sprites.canardActifs ; i++)
        {
            shoot(sourisEvent, sprites.canard[i], partie, temps, modeJeu);
            if ((temps.currentTime >= sprites.canard[i].vitesseTime + sprites.canard[i].vitesse))
            {
                mouvementsCanard(sprites.canard[i]);
                detectionBordsCanard(sprites.canard[i], partie, i);
                changementDirection(sprites.canard[i]);
                if(sprites.canard[i].etat == TOUCHED)
                {
                    touched(sprites.canard[i], temps);
                }
                sprites.canard[i].vitesseTime = temps.currentTime;
            }
            if (temps.currentTime >= sprites.canard[i].vitesseAnimationTime + sprites.canard[i].vitesseAnimation)
            {
                switchSpriteCanard(sprites.canard[i]);
                sprites.canard[i].vitesseAnimationTime = temps.currentTime;
            }
        }
        if(partie.shots <= 0)
        {
            for(int i = 0 ; i < sprites.canardActifs ; i++)
            {
                canardSurvivant(sprites, partie, i);
            }
        }
        if (temps.currentTime >= chien.vitesseAnimationTime + chien.vitesseAnimation)
        {
            switchSpriteChien(chien, partie);
            controlesChien(chien, partie, sprites);
            ramasserCanard(chien, partie, sprites);

            chien.vitesseAnimationTime = temps.currentTime;
            ramasserCanard(chien, partie, sprites);
        }
        if(partie.relancer)
        {
            relancerPartie(partie, sprites);
        }
        if(partie.round >= 5)
        {
            if(finPartie(partie))
            {
                if (testHighScore("scoresClassic", partie))
                {
                    modeMenu = 8;
                }
                else
                {
                    modeMenu = 9;
                }
            }
            else
            {
                partie.round = 0;
                partie.niveau ++;
                initPartie(partie, sprites.canardActifs);
                partie.jeu = true;
                for (int i=0; i<sprites.canardActifs; i++)
                {
                    initCanard(sprites.canard[i], partie);
                }
                initTableau(partie.tableauChasse, sprites);
                modeMenu = 6;
            }
        }
        if (keystate[SDLK_ESCAPE])
        {
            modeMenu = 5;
        }
        if (temps.currentTime >= temps.timeFps + temps.fpsTime)
        {
            genererRendu(ecran, sprites, sourisEvent, partie, chien, msgs);
            SDL_Flip(ecran);
            temps.timeFps = temps.currentTime;
        }

        SDL_Delay(1);
    }
    libererImages(sprites, chien, boutons);
    SDL_Quit();
    IMG_Quit();
    TTF_Quit();
    return EXIT_SUCCESS;
}
Ejemplo n.º 15
0
Win32Error::Win32Error(unsigned int errorCode)
:	mErrorCode(errorCode)
{
	initMessage(0);
}
Ejemplo n.º 16
0
Win32Error::Win32Error()
:	mErrorCode(GetLastError())
{
	initMessage(0);
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
	char line[MAXLINE], message[MAXLINE+1];
	int n, pid;
	struct sockaddr_in proxy_addr;
	int maxfdp1;
	int s;
	fd_set read_fds;
	
	struct __message msg = {0x0, };
	struct __message resp = {0x0, };
	
	if(argc < 3)
	{
		printf("usage1 : %s [proxy_ip#] [proxy_port#]\n", argv[0]);
		printf("usage2 : %s [proxy_ip#] [proxy_port#] [monitoring_mode#] [monitoring_interval#]\n", argv[0]);
		exit(0);
	}	//if(argc
	else if(argc >= 5)
	{
		g_monMode = atoi(argv[3]);
		g_monInterval = atoi(argv[4]);
		
		if(argc >= 6)
		{
			strncpy(g_strLogName, argv[5], strlen(argv[5]));
			
			if(argc == 7)
			{
				g_iLogCount = atoi(argv[6]);
			}
		}
		else
		{
			strncpy(g_strLogName, CLIENT_LOG_NAME, strlen(CLIENT_LOG_NAME));
		}
	}
	/*
	fLog = fopen(g_strLogName, "w");
	printf("fLog=%d\n", fLog);
	fprintf(fLog, "Hello Minjin\n");
	fprintf(fLog, "Hello Minjin!!!\n");
	fclose(fLog);
	*/
	if( (s=socket(PF_INET, SOCK_STREAM, 0)) < 0 )
	{
		printf("client : socket failed!\n");
		exit(0);
	}	//if( (s=socket
	
	
	bzero((char *)&proxy_addr, sizeof(struct sockaddr_in));
	proxy_addr.sin_family = AF_INET;
	proxy_addr.sin_addr.s_addr = inet_addr(argv[1]);
	proxy_addr.sin_port = htons(atoi(argv[2]));
	
	if(connect(s, (struct sockaddr *)&proxy_addr, sizeof(struct sockaddr_in)) < 0)
	{
		printf("client : connect failed!\n");
		exit(0);
	}
	else
	{
		printf("client : connected server!\n");
	}	//if(connect(
	
	maxfdp1 = s + 1;
	FD_ZERO(&read_fds);
	
	memset(&msg, 0x0, sizeof(struct __message));
	srand(time(NULL));
	msg.owner = random()%10000;
	printf("CLIEND:owner=%d\n", msg.owner);
	
//#if !ENABLE_REPEATE
	if(g_monMode == RESOURCE_CMD_REGISTER)
	{
		initMessage(&msg);
		msg.cmd = RESOURCE_CMD_REGISTER;
		msg.req_dur = g_monInterval;
		if(send(s, &msg, sizeof(struct __message), 0) < 0)
		{
			printf("client : send failed!\n");
		}	//if(send(
	}
//#endif	//#if 0

	while(1)
	{
		FD_SET(0, &read_fds);
		FD_SET(s, &read_fds);

//#if ENABLE_REPEATE	
		if(g_monMode == RESOURCE_CMD_GET)
		{
			initMessage(&msg);
			msg.cmd = RESOURCE_CMD_GET;
			
			if(send(s, &msg, sizeof(struct __message), 0) < 0)
			{
				printf("client : send failed!\n");
			}	//if(send(
		}
//#endif			
		
		if(select(maxfdp1, &read_fds, (fd_set *)0, (fd_set *)0, (struct timeval *)0) < 0)
		{
			printf("client : select failed\n");
			exit(0);
		}//if(select
		
		if(FD_ISSET(s, &read_fds))
		{
			int size;
			if((size = recv(s, &resp, sizeof(struct __message), 0)) > 0)
			{
				handleMessage(resp);
			} //if((size
		}	//if(FD_ISSET(
		
		if(g_monMode == RESOURCE_CMD_GET)
		{
			//usleep(g_monInterval*1000);
			struct timeval timeSched;
			struct timeval timeB;
			struct timeval timeNow;
			
			timeB.tv_sec = g_monInterval/1000;
			timeB.tv_usec = 	(g_monInterval%1000)*1000;
			
			addTimeValue(&timeSched, msg.client_started, timeB);
//printf("timeSched:%ld.%06ld\n", timeSched.tv_sec, timeSched.tv_usec);			
			while(1)
			{
				usleep(1000);
				gettimeofday(&timeNow, NULL);
				if(isBiggerThan(timeNow, timeSched)) break;
			}
		}
	}	//while(1)
	
	//fclose(fLog);
	
	return 0;
}	//int main(
CESDDevice::CESDDevice() : m_hDevice(0), m_hSyncDevice(0), m_iDeviceId(-1), m_uiBaudRate(0), m_uiQueueSize(128), m_uiTimeOut(3)		// ESD C331
{
	initMessage("CESDDevice", g_iDebugLevel, g_bDebug, g_bDebugFile);
}
Ejemplo n.º 19
0
Win32Error::Win32Error(const char *baseMessage)
:	mErrorCode(GetLastError())
{
	initMessage(baseMessage);
}
Ejemplo n.º 20
0
Archivo: recv.cpp Proyecto: hunanhd/vns
void receiveMessages ()
{

  cleanBuffers ();

  do
    {

      if (! atLeastOneActiveThread ())
        {
          waitMessage ();
        }

      int src, tag;

      while (probeMessage (src, tag))
        {
          receiveMessage (src, tag);
          initMessage ();

          switch (tag)
            {

            case RUNNER_STOP_TAG:
              unpackTerminationOfRunner ();
              break;

            case SYNCHRONIZE_REQ_TAG:
              unpackSynchronRequest ();
              break;

            case SYNCHRONIZED_TAG:
            {
              RUNNER_ID runner_id;
              unpack (runner_id);

              COOP_ID coop_id;
              unpack (coop_id);

              getCooperative (coop_id) -> notifySynchronized ();
              break;
            }

            case COOP_TAG:
              COOP_ID coop_id;
              unpack (coop_id);
              getCooperative (coop_id) -> unpack ();
              getCooperative (coop_id) -> notifyReceiving ();
              break;

            case SCHED_REQUEST_TAG:
              unpackResourceRequest ();
              break;

            case SCHED_RESULT_TAG:
            {
              /* Unpacking the resource */
              SERVICE_ID serv_id;
              unpack (serv_id);
              Service * serv = getService (serv_id);
              int dest;
              unpack (dest);
              WORKER_ID worker_id;
              unpack (worker_id);

              /* Going back ... */
              initMessage ();
              pack (worker_id);
              pack (serv_id);
              serv -> packData ();
              serv -> notifySendingData ();
              sendMessage (dest, TASK_DATA_TAG);
              break;
            }

            case TASK_DATA_TAG:
            {
              WORKER_ID worker_id;
              unpack (worker_id);
              Worker * worker = getWorker (worker_id);
              worker -> setSource (src);
              worker -> unpackData ();
              worker -> wakeUp ();

              break;
            }

            case TASK_RESULT_TAG:
            {
              SERVICE_ID serv_id;
              unpack (serv_id);
              Service * serv = getService (serv_id);
              serv -> unpackResult ();
              break;
            }

            case TASK_DONE_TAG:
              unpackTaskDone ();
              break;

            default:
              ;
            };
        }

    }
  while ( ! atLeastOneActiveThread () && atLeastOneActiveRunner () /*&& ! allResourcesFree ()*/ );
}
Ejemplo n.º 21
0
Win32Error::Win32Error(const char *baseMessage, unsigned int errorCode)
:	mErrorCode(errorCode)
{
	initMessage(baseMessage);
}
Ejemplo n.º 22
0
// Collisions
void checkCollisions(void) {

	// Laser->asteroid collisions
	int li;
	for (li=0; li<MAXSHOTS; li++) {
		object *l = LAZORZ+li;
	
		// If shot is inactive, skip
		if (!(l->state & LAZER_ACTIVE)) continue;
		int a;
		// Else check all asteroids for a collision
		for (a = 0; a < MAXASTEROIDS; a++) {
			// Get distance vector from laser to asteroid centre
			vector dv = subVec(&(l->pos), &((asteroids+a)->pos));

			if (asteroids[a].state & ASTEROID_ACTIVE // Asteroid active?
			 && lengthVec(&dv) < asteroids[a].radius //Laser close enough?
			 && pointPolygonCollide(asteroids+a, &(l->pos))) {//Collision?

				// Kill asteroid and deactivate laser shot
				initGib(asteroidGibs[a], asteroids+a, GIB_ACTIVE);
				killAsteroid(asteroids+a);
				l->state &= !LAZER_ACTIVE;
				break;			
			}		
		}
	}
	
	// // Missile->asteroid collisions
	// if (missile.state & MISSILE_ACTIVE) {
		
		// int si;
		// // Check eack vertex of the ship for a collision
		// for (si=0; si<missile.size; si++) {

			// int a;
			// // Get world coordinate of ship vertex
			// vector sv = localToWorld(missile.verts+si, &missile);

			// // Check all asteroids for collision
			// for (a = 0; a < MAXASTEROIDS; a++) {

				// // Skip if asteroid is not active (destroyed)
				// if (!(asteroids[a].state & ASTEROID_ACTIVE)) continue;

				// // Get distance vector
				// vector dv = subVec( &sv, &((asteroids+a)->pos));
				// if (lengthVec(&dv) < asteroids[a].radius //Close enough?
				 // && pointPolygonCollide(asteroids+a, &sv)) {//Collision?

					// // Kill asteroid and ship, display lose message
					// killAsteroid(asteroids+a);
				// //	initGib(shipGibs, &ship, GIB_ACTIVE);
					// initGib(asteroidGibs[a], asteroids+a, GIB_ACTIVE);
				// //	initMessage();
					// missile.state &= !MISSILE_ACTIVE;				
					// break;			
				// }		
			// }
		// }
	// }

	// Ship->asteroid collisions
	int si;
	object *ship;
	for ( si = 0; si < MAXSHIPS; si++ ) {
		ship = ships+si;

		if ( !(ship->state & ( SHIP_DED | SHIP_INACTIVE)) ) {
			
			int si;
			// Check eack vertex of the ship for a collision
			for (si=0; si<ship->size; si++) {

				int a;
				// Get world coordinate of ship vertex
				vector sv = localToWorld(ship->verts+si, ship);

				// Check all asteroids for collision
				for (a = 0; a < MAXASTEROIDS; a++) {

					// Skip if asteroid is not active (destroyed)
					if (!(asteroids[a].state & ASTEROID_ACTIVE)) continue;

					// Get distance vector
					vector dv = subVec( &sv, &((asteroids+a)->pos));
					if (lengthVec(&dv) < asteroids[a].radius //Close enough?
					 && pointPolygonCollide(asteroids+a, &sv)) {//Collision?

						// Kill asteroid and ship, display lose message
						killAsteroid(asteroids+a);
						initGib(shipGibs+si*ship->size, ship, GIB_ACTIVE);
						initGib(asteroidGibs[a], asteroids+a, GIB_ACTIVE);
						initMessage();
						ship->state += SHIP_DED;				
						break;			
					}		
				}
			}
		}
	}
}
Ejemplo n.º 23
0
int CSocketServer::start(int nSocketType, const char* cszAddr, short nPort, int nStyle)
{
	int nMsgId = -1;

	if(-1 != externalEvent.m_nMsgId)
	{
		nMsgId = initMessage(externalEvent.m_nMsgId, "CSocketServer");
	}
	else
	{
		nMsgId = initMessage(m_nInternalFilter, "CSocketServer");
	}

	if(-1 == nMsgId)
	{
		_log("[CSocketServer] Init Message Queue Fail");
		return -1;
	}

	if(0 != munRunThreadId)
	{
		threadHandler->threadCancel(munRunThreadId);
		threadHandler->threadJoin(munRunThreadId);
		munRunThreadId = 0;
	}

	threadHandler->createThread(threadServerMessageReceive, this);

	if( AF_UNIX == nSocketType)
	{
		setDomainSocketPath(cszAddr);
	}
	else if( AF_INET == nSocketType)
	{
		if(-1 == setInetSocket(cszAddr, nPort))
		{
			_log("set INET socket address & port fail");
			return -1;
		}
	}

	if(-1 != createSocket(nSocketType, nStyle))
	{
		if(-1 != socketBind())
		{
			if( SOCK_STREAM == nStyle)
			{
				if(-1 == socketListen( BACKLOG))
				{
					perror("socket listen");
					socketClose();
					return -1;
				}

				threadHandler->createThread(threadServerSocketAccept, this);
			}
			else if( SOCK_DGRAM == nStyle)
			{
				if(udpClientData)
					delete udpClientData;
				udpClientData = new CDataHandler<struct sockaddr_in>;
				dataHandler(getSocketfd());
			}
			return 0;
		}
		else
		{
			socketClose();
		}
	}

	return -1;
}
Ejemplo n.º 24
0
int CSocketServer::start(int nSocketType, const char* cszAddr, short nPort, int nStyle)
{
	int nMsgId = -1;

	if (-1 != externalEvent.m_nMsgId)
	{
		nMsgId = initMessage(externalEvent.m_nMsgId);
	}
	else
	{
		nMsgId = initMessage(m_nInternalFilter);
	}

	if (-1 == nMsgId)
	{
		throwException("socket server create message id fail");
		return -1;
	}

	threadHandler->createThread(threadSocketMessageReceive, this);

	if (AF_UNIX == nSocketType)
	{
		setDomainSocketPath(cszAddr);
	}
	else if (AF_INET == nSocketType)
	{
		if (-1 == setInetSocket(cszAddr, nPort))
		{
			_DBG("set INET socket address & port fail");
			return -1;
		}
	}

	if (-1 != createSocket(nSocketType, nStyle))
	{
		if (-1 != socketBind())
		{
			if (SOCK_STREAM == nStyle)
			{
				if (-1 == socketListen(BACKLOG))
				{
					perror("socket listen");
					socketClose();
					return -1;
				}

				threadHandler->createThread(threadSocketAccept, this);
			}
			else if (SOCK_DGRAM == nStyle)
			{
				if (udpClientData)
					delete udpClientData;
				udpClientData = new CDataHandler<struct sockaddr_in>;
				clientHandler(getSocketfd());
			}
			return 0;
		}
		else
		{
			socketClose();
		}
	}

	return -1;
}
Ejemplo n.º 25
0
bool stageTwoInitialise(void)
{
	int i;

	debug(LOG_WZ, "== stageTwoInitalise ==");

	// make sure we clear on loading; this a bad hack to fix a bug when
	// loading a savegame where we are building a lassat
	for (i = 0; i < MAX_PLAYERS; i++)
	{
		setLasSatExists(false, i);
	}

	if(bMultiPlayer)
	{
		if (!multiTemplateSetup())
		{
			return false;
		}
	}

	if (!dispInitialise())		/* Initialise the display system */
	{
		return false;
	}

	if(!initMiscImds())			/* Set up the explosions */
	{
		iV_ShutDown();
		debug( LOG_FATAL, "Can't find all the explosions graphics?" );
		abort();
		return false;
	}

	if (!cmdDroidInit())
	{
		return false;
	}

   	/* Shift the interface initialisation here temporarily so that it
   		can pick up the stats after they have been loaded */

	if (!intInitialise())
	{
		return false;
	}

	if (!initMessage())			/* Initialise the message heaps */
	{
		return false;
	}

	if (!gwInitialise())
	{
		return false;
	}

	// keymappings
	keyClearMappings();
	keyInitMappings(false);

	// Set the default uncoloured cursor here, since it looks slightly
	// better for menus and such.
	wzSetCursor(CURSOR_DEFAULT);

	SetFormAudioIDs(ID_SOUND_WINDOWOPEN,ID_SOUND_WINDOWCLOSE);

	// Setup game queues.
	// Don't ask why this doesn't go in stage three. In fact, don't even ask me what stage one/two/three is supposed to mean, it seems about as descriptive as stage doStuff, stage doMoreStuff and stage doEvenMoreStuff...
	debug(LOG_MAIN, "Init game queues, I am %d.", selectedPlayer);
	sendQueuedDroidInfo();  // Discard any pending orders which could later get flushed into the game queue.
	for (i = 0; i < MAX_PLAYERS; ++i)
	{
		NETinitQueue(NETgameQueue(i));

		if (!myResponsibility(i))
		{
			NETsetNoSendOverNetwork(NETgameQueue(i));
		}
	}

	debug(LOG_MAIN, "stageTwoInitialise: done");

	return true;
}
Ejemplo n.º 26
0
namespace defaultpipeline_test
{

int initMessage(){
    /// Install the backtrace so that we have more information in case of test segfault.
    BackTrace::autodump() ;
    return 0;
}

int messageInited = initMessage();

class TestDefaultPipeLine : public Sofa_test<> {
public:
    void checkDefaultPipelineWithNoAttributes();
    void checkDefaultPipelineWithMissingIntersection();
    int checkDefaultPipelineWithMonkeyValueForDepth(int value);
};

void TestDefaultPipeLine::checkDefaultPipelineWithNoAttributes()
{
    EXPECT_MSG_NOEMIT(Warning) ;
    EXPECT_MSG_NOEMIT(Error) ;

    std::stringstream scene ;
    scene << "<?xml version='1.0'?>                                                          \n"
             "<Node 	name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
             "  <DefaultPipeline name='pipeline'/>                                           \n"
             "  <DiscreteIntersection name='interaction'/>                                    \n"
             "</Node>                                                                        \n" ;

    Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene",
                                                      scene.str().c_str(),
                                                      scene.str().size()) ;
    ASSERT_NE(root.get(), nullptr) ;
    root->init(ExecParams::defaultInstance()) ;

    BaseObject* clp = root->getObject("pipeline") ;
    ASSERT_NE(clp, nullptr) ;

    clearSceneGraph();
}

void TestDefaultPipeLine::checkDefaultPipelineWithMissingIntersection()
{
    EXPECT_MSG_EMIT(Warning) ;
    EXPECT_MSG_NOEMIT(Error) ;


    std::stringstream scene ;
    scene << "<?xml version='1.0'?>                                                          \n"
             "<Node 	name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
             "  <DefaultPipeline name='pipeline'/>                                           \n"
             "</Node>                                                                        \n" ;

    Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene",
                                                      scene.str().c_str(),
                                                      scene.str().size()) ;
    ASSERT_NE(root.get(), nullptr) ;
    root->init(ExecParams::defaultInstance()) ;

    BaseObject* clp = root->getObject("pipeline") ;
    ASSERT_NE(clp, nullptr) ;

    clearSceneGraph();
}

int TestDefaultPipeLine::checkDefaultPipelineWithMonkeyValueForDepth(int dvalue)
{
    std::stringstream scene ;
    scene << "<?xml version='1.0'?>                                                          \n"
             "<Node 	name='Root' gravity='0 -9.81 0' time='0' animate='0' >               \n"
             "  <DefaultPipeline name='pipeline' depth='"<< dvalue <<"'/>                     \n"
             "  <DiscreteIntersection name='interaction'/>                                    \n"
             "</Node>                                                                        \n" ;

    Node::SPtr root = SceneLoaderXML::loadFromMemory ("testscene",
                                                      scene.str().c_str(),
                                                      scene.str().size()) ;
    //EXPECT_NE( (root.get()), NULL) ;
    root->init(ExecParams::defaultInstance()) ;

    DefaultPipeline* clp = dynamic_cast<DefaultPipeline*>(root->getObject("pipeline")) ;
    //ASSERT_NE( (clp), nullptr) ;

    int rv = clp->d_depth.getValue() ;

    clearSceneGraph();
    return rv;
}


TEST_F(TestDefaultPipeLine, checkDefaultPipelineWithNoAttributes)
{
    this->checkDefaultPipelineWithNoAttributes();
}

TEST_F(TestDefaultPipeLine, checkDefaultPipelineWithMissingIntersection)
{
    this->checkDefaultPipelineWithMissingIntersection();
}

TEST_F(TestDefaultPipeLine, checkDefaultPipelineWithMonkeyValueForDepth_OpenIssue)
{
    std::vector<std::pair<int, bool>> testvalues = {
        std::make_pair(-1, false),
        std::make_pair( 0, true),
        std::make_pair( 2, true),
        std::make_pair(10, true),
        std::make_pair(1000, true)
    };

    for(auto is : testvalues){
        EXPECT_MSG_NOEMIT(Error) ;

        if(is.second){
            EXPECT_MSG_NOEMIT(Warning) ;

            // Check the returned value.
            if(this->checkDefaultPipelineWithMonkeyValueForDepth(is.first)!=is.first){
                ADD_FAILURE() << "User provided depth parameter value '" << is.first << "' has been un-expectedly overriden." ;
            }
        }else{
            EXPECT_MSG_EMIT(Warning) ;

            // Check the default value.
            if(this->checkDefaultPipelineWithMonkeyValueForDepth(is.first)!=6){
                ADD_FAILURE() << "User provided invalid depth parameter value '" << is.first << "' have not been replaced with the default value = 6." ;
            }
        }
    }
}

} // defaultpipeline_test