Esempio n. 1
0
ConsoleWindow *
MessageHandler::createConsoleWindow()
{
    if (! this->_consoleWindow)
        return this->_consoleWindow;

    // alloc: QSharedPointer here, plus it sets Qt::WA_DeleteOnClose
    // in its constructor.
    this->_consoleWindow = new ConsoleWindow(0);

    if (! QObject::connect(MessageHandler::p(),
                           SIGNAL(deliverMessage(QString)),
                           this->_consoleWindow,
                           SLOT(printMessage(QString))))
        qWarning() << "Could not connect console.";
    QObject::connect(this->_consoleWindow,
                     SIGNAL(destroyed(QObject*)),
                     this,
                     SLOT(notifyQObjectDestroyed(QObject*)));

    this->_consoleWindow->show();
    this->_consoleWindow->raise();
    this->_consoleWindow->activateWindow();

    foreach(QString m, this->_buffer)
        emit deliverMessage(m);

    return this->_consoleWindow;
}
Esempio n. 2
0
void
MessageHandler::message(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString message;

    message = QDateTime::currentDateTime().toString(Qt::ISODate) + " ";

    switch (type)
    {
    case QtDebugMsg:        message += "";              break;
    case QtWarningMsg:      message += "Warning:";      break;
    case QtCriticalMsg:     message += "Critical:";     break;
    case QtFatalMsg:        message += "Fatal:";        break;
    default:                message += "Message:";
    }

    message += QString(" ") + msg;
    message += QString(" (line #") + context.line + QString(" in ") + context.file + QString(")");

    emit deliverMessage(message);

    this->_buffer.enqueue(message);
    if (this->_buffer.length() > this->_bufferLength)
        this->_buffer.dequeue();

    std::cerr << message.toStdString() << std::endl;

    if (type == QtFatalMsg)
        abort();
}
 /**
  * Since certain setups have proximity responses coming from another message stream
  * Those messages should be shunted to this function and processed
  */
 virtual void processProxCallback(const ObjectReference&destination,
                                  const Sirikata::Protocol::IProxCall&callInfo,
                                  const void *optionalSerializedProxCall=NULL,
                                  size_t optionalSerializedProxCallSize=0) {
     RoutableMessage delivery;
     constructMessage(delivery,NULL,&destination,"ProxCall",callInfo,optionalSerializedProxCall,optionalSerializedProxCallSize);
     deliverMessage(destination,delivery,NULL,0);
 }
DelayedJabberMessage::DelayedJabberMessage(const QString &message, int msec) :
	QTimer(),
	m_message(message) {
	
	connect(this, SIGNAL(timeout()), SLOT(deliverMessage()));
	
	start(msec);
}
void accept_loop(void* thread_args) {
	struct socket *so = (struct socket*) thread_args;
	struct socket* rsock;
	struct sockaddr sender_addr;
	int error, read;
	char msg[3];

	log_debug("Starting accept_loop");
	for (;;) {
		error = my_kern_accept(so, &rsock);
		if (error) {
			log_warn("error in my_kern_accept in accept_loop: %d", error);
			if (error == ECONNABORTED)
				goto completed;
			goto continue_listen;
		}
		log_debug("A connection accepted in accept_loop");
		bzero((char*) msg, sizeof(msg));

		//read the message 't' or 'T' or 'r'
		error = my_kern_recv(rsock, msg, 1, &read, NULL);
		if (error || read != 1) {
			log_warn("error in my_kern_recv in accept_loop(1): %d", error);
			goto continue_listen;
		}
		// exit if exit_message received
		if (strcmp(msg, MESSAGE_EXIT) == 0) {
			log_info("Received exit message: exiting");
			goto completed;
		}
		// read sender address
		error = my_kern_recv(rsock, &sender_addr, sizeof(struct sockaddr),
				&read, NULL);
		if (error || read != sizeof(struct sockaddr)) {
			log_warn("error in my_kern_recv in accept_loop(2): %d", error);
			goto continue_listen;
		}
		// process delivered message
		deliverMessage(&sender_addr, msg);

		continue_listen: //
		if (rsock != NULL) {
			soclose(rsock);
			rsock = NULL;
		}
	}
	completed: // on error
	if (error)
		log_error("Error in accept_loop [%d]\n", error);
	if (so != NULL)
		soclose(so);
	if (rsock != NULL)
		soclose(rsock);
	log_info("accept_loop exit");
	kthread_exit();
}
Esempio n. 6
0
int deliverMessageSuid(char *interface, char *message )
{

#ifdef NESSIE
	return (deliverMessage( interface, message ));
#else
	return(-1);
#endif

}
Esempio n. 7
0
int sendToVnmr(char *msge )
{
        CommPort vnmr_addr = &comm_addr[VNMR_COMM_ID];
#ifdef NESSIE
	return( deliverMessage( vnmr_addr->path, msge ) );
#else
	SendAsync2( vnmr_addr, msge );
	return( 0 );
#endif
}
Esempio n. 8
0
int main(int argc, char** argv) {
  //initialize the node
  ros::init(argc, argv, "message_delivery");

  ros::NodeHandle privateNode("~");

  privateNode.param<std::string>("location",location, /*default*/ ""); 
  privateNode.param<std::string>("message",message,"");
  privateNode.param<int32_t>("speed",speed,160);
  privateNode.param<std::string>("voice",voice,"default");
  privateNode.param<int32_t>("pitch",pitch,50);

  if (location.compare("") != 0) {
    goToLocation();
    deliverMessage();
  }
}
Esempio n. 9
0
void send_data()
{
    int i;
    int rc;

    while(1)
    {
        for(i = 0; i < num_clients; ++i)
        {
            if(client_tcp_sock > 0)
            {
                int shift=0;
                char buffer[POWER_UPDATE_SIZE];
                struct Power_Update msg;

                msg.hdr.type=1;
                msg.hdr.len=htons(4);
                msg.hdr.nodeID = htonl(100 + i);

                memcpy(buffer+shift,&msg.hdr.type,1); shift+=1;
                memcpy(buffer+shift,&msg.hdr.len,2); shift+=2;
                memcpy(buffer+shift,&msg.hdr.nodeID,4); shift+=4;

                uint16_t power = (1000*i) + (rand() % 499);
                msg.top_power = htons(power);
                memcpy(buffer+shift,&msg.top_power,sizeof(uint16_t)); shift+=2;

                power = (1000*i) + (rand() % 499) + 500;
                msg.bot_power = htons(power);
                memcpy(buffer+shift,&msg.bot_power,sizeof(uint16_t));

                //send reading
                rc = deliverMessage(buffer, POWER_UPDATE_SIZE, i);
                if(rc < 0)
                    QUIT();
            }
        }

        attempt_recieve();
    }
}
Esempio n. 10
0
int cycle(Client* c, Timer* timer)
{
    // read the socket, see what work is due
    unsigned short packet_type = readPacket(c, timer);
    
    int len = 0,
        rc = SUCCESS;

    switch (packet_type)
    {
        case CONNACK:
        case PUBACK:
        case SUBACK:
            break;
        case PUBLISH:
        {
            MQTTString topicName;
            MQTTMessage msg;
            if (MQTTDeserialize_publish((unsigned char*)&msg.dup, (int*)&msg.qos, (unsigned char*)&msg.retained, (unsigned short*)&msg.id, &topicName,
               (unsigned char**)&msg.payload, (int*)&msg.payloadlen, c->readbuf, c->readbuf_size) != 1)
                goto exit;
            deliverMessage(c, &topicName, &msg);
            if (msg.qos != QOS0)
            {
                if (msg.qos == QOS1)
                    len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id);
                else if (msg.qos == QOS2)
                    len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id);
                if (len <= 0)
                    rc = FAILURE;
                   else
                       rc = sendPacket(c, len, timer);
                if (rc == FAILURE)
                    goto exit; // there was a problem
            }
            break;
        }
        case PUBREC:
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
                rc = FAILURE;
            else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREL, 0, mypacketid)) <= 0)
                rc = FAILURE;
            else if ((rc = sendPacket(c, len, timer)) != SUCCESS) // send the PUBREL packet
                rc = FAILURE; // there was a problem
            if (rc == FAILURE)
                goto exit; // there was a problem
            break;
        }
        case PUBCOMP:
            break;
        case PINGRESP:
				{
						INFO("<--PINGRESP");
						c->ping_outstanding = 0;
						countdown(&c->ping_timer, c->keepAliveInterval);
            break;
				}
    }
    rc = keepalive(c);
exit:
    if (rc == SUCCESS)
        rc = packet_type;
    return rc;
}
Esempio n. 11
0
int procQTask()
{
   char ProcId[EXPID_LEN];
   char ActiveId[EXPID_LEN];
   int proctype,activetype,fgbg,pid;
   long fid,ct;
   int dCode,eCode;
   int activeDcode;

   DPRINT(1,"Procproc: start procQtask()(chk processing Q)\n");
   if ( procQget(&proctype, ProcId, &fid, &ct, &dCode, &eCode) == -1)  /* nothin in Q ? */
     return(0);

   DPRINT2(1,"Procproc: got Qed Task, Done Code: %d Error Code: %d\n",dCode,eCode);
   if (activeQget(&activetype, ActiveId, &fgbg, &pid, &activeDcode ) == -1) /* no active processing */
   {
       if (ProcExpInfo.ExpInfo == NULL)
       {
 	      /* map in new processing Exp Info file */
    	      strncpy(ProcExpInfo.ExpId,ProcId,EXPID_LEN);
    	      ProcExpInfo.ExpId[EXPID_LEN-1] = '\0';
	      if (mapInExp(&ProcExpInfo) == -1)
	      {
                /* if expinfo file not there skip this processing,
                 * remove it from the process queue, and get the next
                 * queued item.
                 */
		ProcExpInfo.ExpInfo = NULL;
	        procQdelete(proctype, 1);
                procQTask();
	        return(0);
	      }
	      /* Both ProcExpInfo & ActiveExpInfo were NULL so they will be
		 the same */
	      /* memcpy((char*)&ActiveExpInfo,(char*)&ProcExpInfo,
			     sizeof(ExpInfoEntry)); */
              UpdateStatus(&ProcExpInfo);
       }
       else   /* is the present ProcExpInfo the right one */
       {
	   if( strcmp(ProcExpInfo.ExpId,ProcId) != 0)    /* NO, close one, open new */
	   {
	       mapOutExp(&ProcExpInfo);
 	       /* map in new processing Exp Info file */
    	       strncpy(ProcExpInfo.ExpId,ProcId,EXPID_LEN);
    	       ProcExpInfo.ExpId[EXPID_LEN-1] = '\0';
	       if (mapInExp(&ProcExpInfo) == -1)
	       {
                /* if expinfo file not there skip this processing,
                 * remove it from the process queue, and get the next
                 * queued item.
                 */
		ProcExpInfo.ExpInfo = NULL;
	        procQdelete(proctype, 1);
                procQTask();
                return(0);
	       }
               UpdateStatus(&ProcExpInfo);
	   }
       }
       BeginProcessing(&ProcExpInfo, proctype, fid, ct, dCode, eCode); 
   }
   else    /* There is an active processing going on */
   {
       if ( (proctype != WEXP_WAIT) && (proctype != WEXP) &&
            (proctype != WERR) )
       {
          /* Only check active queue at WEXP and WERR */
          return(0);
       }
       if (ActiveExpInfo.ExpInfo == NULL)
       {
          char vnhost[256];
          int vnport, vnpid;

 	  /* map in new processing Exp Info file */
    	  strncpy(ActiveExpInfo.ExpId,ActiveId,EXPID_LEN);
    	  ActiveExpInfo.ExpId[EXPID_LEN-1] = '\0';
	  if (mapInExp(&ActiveExpInfo) == -1)
	  {
             /* If the info file is not there, active element is done */
	     ActiveExpInfo.ExpInfo = NULL;
             activeQdelete(FG,pid);
             procQTask();
	     return(0);
	  }
          if (fgbg == BG)
          {
             vnpid = pid;
          }
          else
          {
             sscanf(ActiveExpInfo.ExpInfo->MachineID, "%s %d %d", vnhost,&vnport,&vnpid);
          }
          if (( kill(vnpid,0) == -1) && (errno == ESRCH))
          {
            /* if the process which was doing active processing is gone,
             * remove the active element
             */
            activeQdelete(FG,pid);
	    mapOutExp(&ActiveExpInfo);
	    ActiveExpInfo.ExpInfo = NULL;
            unlink(ActiveId);  /* delete exp info file */
            procQTask();
          }
          else if (fgbg == BG)
          {
            /* if the process which was doing active processing is present,
             * but in background, just let it continue
             */
	    mapOutExp(&ActiveExpInfo);
	    ActiveExpInfo.ExpInfo = NULL;
          }
          else if (recheckFG)
          {
            char msgestring[256];

            /* if the process which was doing active processing is present,
             * send another message for FGcomplt().  If it is still busy,
             * the message will be queued and an extra FGcomplt will be
             * delivered.  It will be ignored.
             */
            sprintf(msgestring,"acqsend('%d,0,','check')\n", (int)FGkey);
            deliverMessage( ActiveExpInfo.ExpInfo->MachineID, msgestring );
	    mapOutExp(&ActiveExpInfo);
	    ActiveExpInfo.ExpInfo = NULL;
            /*
             * avoid sending a lot of these messages. This gets reset to 1 whenever
             * a FG message is received.
             */
            recheckFG = 0;
          }
       }
   }
   return(0);
}
Esempio n. 12
0
/*------------------------------------------------------------------------
|
|       BeginProcessing()/1
|       Fork & Exec a child for BackGround vnmr processing
|       Send commands to Vnmr for ForeGround processing
|
|                               Author Greg Brissey 9/7/94
|
+-----------------------------------------------------------------------*/
void BeginProcessing(ExpInfoEntry* pProcExpInfo, int proctype, long fid, long ct,
                     int dCode, int eCode)
{
    char cmdstring[1024];
    char procmsge[1024];
    char msgestring[1024];
    int process2do;
    MSG_Q_ID pAutoMsgQ;

    /* we no longer pass the actual command string to Vnmr but just it's
       type, and Vnmr will read it's procpar to get the command string 
       This means for Wexp, Wnt & Wexp will need tobe concatenated
    */
    process2do =  pProcExpInfo->ExpInfo->ProcMask;
    DPRINT3(1,"BeginProcessing(): type = %d dcode: %d ecode: %d \n",
               proctype,dCode,eCode);
    switch(proctype)
    {
       case WEXP_WAIT:
       case WEXP:
	    if (pProcExpInfo->ExpInfo->GoFlag != EXEC_GO)
            {
	       process2do &= WHEN_SU_PROC;
               eCode = pProcExpInfo->ExpInfo->GoFlag;  /* type of su done */
            }
	    else
            {
	       process2do &= WHEN_GA_PROC | WHEN_EXP_PROC | WHEN_NT_PROC;
            }
	break;
       case WERR:
               if (dCode == EXP_STARTED)
	          process2do = 0;
               else
	          process2do &= WHEN_ERR_PROC;
	break;
       case WFID:
	       process2do &= (WHEN_NT_PROC | WHEN_GA_PROC);
	break;
       case WBS:
	       process2do &= WHEN_BS_PROC;
	break;
       default:
	       process2do = 0;	/* don't do any */
	break;
    }

    if (++FGkey > 1024)
	FGkey = 1L;
    DPRINT2(1,"BeginProcessing(): flags: automode= %d vpmode= %d\n",
               pProcExpInfo->ExpInfo->ExpFlags & AUTOMODE_BIT,pProcExpInfo->ExpInfo->ExpFlags & VPMODE_BIT);
/*
    sprintf(msgestring,"acqcp('exp%d','%s',%d,%d,%d,%d,%lu,%lu,%lu)\n",
			pProcExpInfo->ExpInfo->ExpNum,
			pProcExpInfo->ExpId,0,0,process2do,(int)FGkey, fid, ct);
 */
    if ( (pProcExpInfo->ExpInfo->ExpFlags & VPMODE_BIT) &&
         (pProcExpInfo->ExpInfo->ExpFlags & AUTOMODE_BIT) )
       sprintf(msgestring,"acqsend(5,'%d',0,%d,'vpa',%d,%d,%lu,%lu,'%s')\n",
                        (int)FGkey, process2do,dCode,eCode, fid, ct,
                        pProcExpInfo->ExpInfo->DataFile);
    else if (pProcExpInfo->ExpInfo->ExpFlags & VPMODE_BIT)
       sprintf(msgestring,"acqsend(5,'%d',0,%d,'vp',%d,%d,%lu,%lu,'%s')\n",
                        (int)FGkey, process2do,dCode,eCode, fid, ct,
                        pProcExpInfo->ExpInfo->DataFile);
    else
       sprintf(msgestring,"acqsend(5,'%d',%d,%d,'exp%d',%d,%d,%lu,%lu)\n",
                        (int)FGkey,pProcExpInfo->ExpInfo->ExpNum,
			process2do,pProcExpInfo->ExpInfo->ExpNum,dCode,eCode, fid, ct);
    /* ---  If FG Vnmr is in Process Exp#  & Wexp Not Processing in FG, --- */
    /*       And not in automation mode                             */
    /* ---  Then do FG processing else do it in BG                      --- */
    /*  FG is Never done for automation Experiments!  */

    if ( (strlen(pProcExpInfo->ExpInfo->MachineID) > (size_t) 1) &&
	  (verifyInterface( pProcExpInfo->ExpInfo->MachineID )) &&
         ( !(pProcExpInfo->ExpInfo->ExpFlags & AUTOMODE_BIT) ||
            ( ((pProcExpInfo->ExpInfo->ExpFlags & VPMODE_BIT) && (pProcExpInfo->ExpInfo->ExpFlags & AUTOMODE_BIT)) ) ) )
    {
 
         /* acqcp('exp#','ExpInfo',donecode,errorcode,WprocType,fid,ct) */

         DPRINT(1,"Send Vnmr(MachineId): acqsend(5,FGkey,Exp#,Process2Do,'exp#',dcode,ecode,fid,ct)\n");
         DPRINT2(1,"Send Vnmr(%s): '%s'\n",
         		pProcExpInfo->ExpInfo->MachineID,
         		msgestring);
         deliverMessage( pProcExpInfo->ExpInfo->MachineID, msgestring );

         DPRINT(1,"BeginProcessing: FG calling activeQadd\n");
	 activeQadd(pProcExpInfo->ExpId, proctype, fid, ct, FG, (int) FGkey, dCode, eCode );
	 procQdelete(proctype, 1);

    }
    else	/* ----- process in BackGround ----- */
    {

        char vnmrmode[20];
        char expnum[16];
        char fidpath[128];
        char userpath[128];
        char host[128];
        char vnmr_acqid[16];
        int ret;
        int len;
        int uid;
        int gid;

        /* Be Absolutely sure there is a Vnmr out there to RUN */
        if ( access(Vnmrpath,R_OK | X_OK) != 0)
        {
           errLogRet(ErrLogOp,debugInfo,
                 "WARNING: BG '%s' Processing for '%s' was NOT performed, \n",
                   procmsge, pProcExpInfo->ExpId);
           errLogRet(ErrLogOp,debugInfo,
                 "         '%s' not found or can not run.\n",
                   Vnmrpath);
           return;   /* don't do any more */
        }

        /*
	    Common Arguments for NORMAL or AUTOMATION Vnmr Arguments
        */
	/* below we first copy the string "acqsend('5',..." to 
	   cmdstring (why? I don't know, msgestring isn't used anymore)
	   and then set the 8th character to '6'. So the cmdstring then
	   reads as "acqsend('6',...". By the way, in acqproc the digits
	   5 and 6 are defines as FGREPLY and FGNOREPLY respectively.
	   For those that need to maintain software this may be of help.
	*/
        strcpy(cmdstring,msgestring);
        cmdstring[8] = '6';
        sprintf(userpath,"-u%s",pProcExpInfo->ExpInfo->UsrDirFile);
        sprintf(host,"-h%s",pProcExpInfo->ExpInfo->MachineID);
        sprintf(vnmr_acqid,"-i%d",pProcExpInfo->ExpInfo->ExpNum);
	sprintf(fidpath,"-d%s",pProcExpInfo->ExpInfo->DataFile);

        /* Are we in Automation Mode ? */
        if ( !(pProcExpInfo->ExpInfo->ExpFlags & AUTOMODE_BIT) )
        {
          /* back mode is used because the experiment will need to be
           * locked by the background Vnmr. The acq mode expects the
           * experiment to already be locked.
           */
          sprintf(vnmrmode,"-mback");
          sprintf(expnum,"-n%d",pProcExpInfo->ExpInfo->ExpNum);
        }
        else     /* Automation Mode */
        {
	    /* Use Exp2 & Exp3 in automation mode */
           if (proctype == WEXP)
              sprintf(expnum,"-n2");
           else
              sprintf(expnum,"-n3");

           sprintf(vnmrmode,"-mauto");

           len = strlen(fidpath);
            /* Test Auto_Pid ? */
           /* if acquisition in automode and go neither a go(nowait)  */
           /*  or Werror issue a resume to autoproc prior to processing */
           if ( (pProcExpInfo->ExpInfo->ProcWait == AU_NOWAIT) && 
		(proctype != WERR) )
           {
	     DPRINT(1,"BeginProcessing: Prior to vfork - Send Resume\n");
    	     pAutoMsgQ = openMsgQ("Autoproc");
	     if (pAutoMsgQ != NULL)
	     {
	       sendMsgQ(pAutoMsgQ, "resume", strlen("resume"), MSGQ_NORMAL,
 			WAIT_FOREVER); /* NO_WAIT */
	       closeMsgQ(pAutoMsgQ);
	     }
           }

        }
 
 
        /* save User is a static location for forked child */
	strcpy(User,pProcExpInfo->ExpInfo->UserName);
	umask4Vnmr = pProcExpInfo->ExpInfo->UserUmask;
        childpid = fork();  /* fork a child */
        DPRINT1(1,"Start BG process ----  childpid = %d\n",childpid);
        /* -----  Parent vs Child ---- */
        if (childpid == 0)
        {
	    sigset_t signalmask;

	    /* set signal mask for child ti zip */
	    sigemptyset( &signalmask );
    	    sigprocmask( SIG_SETMASK, &signalmask, NULL );

            /* change the user and group ID of the child so that VNMR
               will run with those ID's */
	    getUserUid(User, &uid, &gid);
 
            seteuid(getuid());
            freopen("/dev/null","r",stdin);
            freopen("/dev/console","a",stdout);
            freopen("/dev/console","a",stderr);
            if ( setgid(gid) )
            {
                  DPRINT(1,"BGprocess:  cannot set group ID\n");
            }
 
            if ( setuid(uid) )
            {
                  DPRINT(1,"BGprocess:  cannot set user ID\n");
            }

            /* set umask to be that requested by PSG */
            umask( umask4Vnmr );
              
            ret=execl(Vnmrpath,"Vnmr",vnmrmode,host,vnmr_acqid,expnum,userpath,fidpath,cmdstring,NULL);
            if (ret == -1)
            {
               errLogRet(ErrLogOp,debugInfo,
                 "WARNING: BG '%s' for Exp%d was NOT performed, \n",
                   proctype,pProcExpInfo->ExpInfo->ExpNum);
               errLogRet(ErrLogOp,debugInfo, "         execl on '%s' failed.\n",
                   Vnmrpath);
               return;   /* don't do any more */
            }
        }
        else     /* if (childpid != 0)  Child */
        {
            DPRINT(1,"BeginProcessing: BG calling activeQadd()\n");
	    activeQadd(pProcExpInfo->ExpId, proctype, fid, ct, BG, childpid, dCode, eCode);
	    procQdelete(proctype, 1);
        }
    }
}
/*


	success -> 
  		return packet type
  	fail->
		return FAIL

*/
int cycle(MQTTClient* c, Timer* timer)
{
	int packet_type = readPacket(c, timer);
	int len = 0;
	int rc = SUCCESS;

	if (FAILURE == packet_type) {
		packet_type = NOPACKET;
		goto exit;
	}
	printf("received %s\n", MQTTPacket_names[packet_type]);

	switch (packet_type)
	{
		case CONNACK:
		case PUBACK:
		case SUBACK:
			break;
		case PUBLISH:
		{
			MQTTString topicName;
			MQTTMessage msg;
			int intQoS;
			if (MQTTDeserialize_publish(&msg.dup, &intQoS, &msg.retained, &msg.id, &topicName,
					(unsigned char**)&msg.payload, (int*)&msg.payloadlen, c->readbuf, c->readbuf_size) != 1)
				goto exit;

			msg.qos = (enum QoS)intQoS;
			//deliverMessage(c, &topicName, &msg);

			if (msg.qos != QOS0) {
				if (msg.qos == QOS1)
					len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id);
				else if (msg.qos == QOS2)
					len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id);

				if (len <= 0)
					rc = FAILURE;
				else
					rc = sendPacket(c, len, timer);

				if (rc == FAILURE)
					goto exit; // there was a problem
			}
			deliverMessage(c, &topicName, &msg);

			break;
		}
		case PUBREC:
		{
			unsigned short mypacketid;
			unsigned char dup, type;
			if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
				rc = FAILURE;
			else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREL, 0, mypacketid)) <= 0)
				rc = FAILURE;
			else if ((rc = sendPacket(c, len, timer)) != SUCCESS) // send the PUBREL packet
				rc = FAILURE; // there was a problem
			if (rc == FAILURE)
				goto exit; // there was a problem
			break;
		}
		case PUBCOMP:
			break;
		case PINGRESP:
			c->ping_outstanding = 0;
			//c->keepAliveFailCount = 0;
			break;
		case PUBREL:
		{
			unsigned short mypacketid;
			unsigned char dup, type;
			if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
				rc = FAILURE;
			else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, PUBCOMP, 0, mypacketid)) <= 0)
				rc = FAILURE;
			else if ((rc = sendPacket(c, len, timer)) != SUCCESS) // send the PUBCOMP packet
				rc = FAILURE; // there was a problem
			if (rc == FAILURE)
				goto exit; // there was a problem
			break;
		}
	}

exit:

	if (FAILURE == keepalive(c)) {
		rc = FAILURE;
	}

	if (rc == SUCCESS)
		rc = packet_type;

	return rc;
}
    /**
     * Process a message that may be meant for the proximity system
     * \returns true if object was deleted
     */
    OpaqueMessageReturnValue internalProcessOpaqueProximityMessage(
                                               const ObjectReference*object,
                                               const RoutableMessageHeader& hdr,
                                               const void *serializedMessageBody,
                                               size_t serializedMessageBodySize,
                                               bool trusted) {
        try {
            RoutableMessage msg(hdr,serializedMessageBody,serializedMessageBodySize);
            MessageBundle sendState=DELIVER_TO_UNKNOWN;
            bool deliverAllMessages=true;
            int len=msg.body().message_size();
            OpaqueMessageReturnValue obj_is_deleted=OBJECT_NOT_DESTROYED;
            bool disconnection=false;
            bool registration=false;
            for (int i=0;i<len;++i) {
                if (trusted||(hdr.has_source_object()&&hdr.source_object()==ObjectReference::spaceServiceID()&&hdr.source_port()==mRegistrationPort)) {
                    if(msg.body().message_names(i)=="DelObj") {
                        disconnection=true;
                        obj_is_deleted=OBJECT_DELETED;
                    }
                    if(msg.body().message_names(i)=="RetObj") {
                        registration=true;
                        Sirikata::Protocol::RetObj ro;
                        ro.ParseFromString(msg.body().message_arguments(i));
                        newObj(ro,msg.body().message_arguments(i).data(),msg.body().message_arguments(i).size());
                    }
                }
                if (!forwardThisName(disconnection,msg.body().message_names(i))) {
                    if (len==1) return obj_is_deleted;
                    deliverAllMessages=false;
                }else {
                    if (msg.body().message_names(i)==proxCallbackName()) {
                        if (sendState==DELIVER_TO_UNKNOWN||sendState==DELIVER_TO_OBJECT)
                            sendState=DELIVER_TO_OBJECT;
                        else 
                            sendState=DELIVER_TO_BOTH;
                    }else{
                        if (sendState==DELIVER_TO_UNKNOWN||sendState==DELIVER_TO_PROX)
                            sendState=DELIVER_TO_PROX;
                        else 
                            sendState=DELIVER_TO_BOTH;
                    }
                }
            }
            if (sendState==DELIVER_TO_UNKNOWN)
                return obj_is_deleted;//no messages considered worth forwarding to the proximity system
            if (sendState==DELIVER_TO_BOTH) {
                SILOG(prox,info,"Message with recipients both proximity and object bundled into the same message: not delivering.");
                return obj_is_deleted;
            }
/* NOT SURE THIS IS NECESSARY -- do these messages already have addresses on them?*/
            DidAlterMessage alteration;
            if (sendState==DELIVER_TO_PROX) 
                alteration=addressMessage(msg,object,NULL);
            else
                alteration=addressMessage(msg,NULL,object);
            if (deliverAllMessages&&sendState==DELIVER_TO_PROX) {
                sendMessage(*object,msg,serializedMessageBody,serializedMessageBodySize);
            } else if (deliverAllMessages&&sendState==DELIVER_TO_OBJECT) {
                deliverMessage(*object,msg,serializedMessageBody,serializedMessageBodySize);
            }else {
                //some messages are not considered worth forwarding to the proximity system or there's a mishmash of destinations
                if (msg.body().message_size()<len) {
                    len=msg.body().message_size();
                }
                RoutableMessage newMsg (msg);
                newMsg.body().clear_message();
                for (int i=0;i<len;++i) {
                    if (forwardThisName(registration||disconnection,msg.body().message_names(i))) {
                        newMsg.body().add_message(msg.body().message_names(i), msg.body().message_arguments(i));
                    }
                }
                if (sendState==DELIVER_TO_OBJECT)
                    deliverMessage(*object,newMsg,NULL,0);
                if (sendState==DELIVER_TO_PROX)
                    sendMessage(*object,newMsg,NULL,0);
                
            }
            return obj_is_deleted;
        }catch(std::invalid_argument&ia) {
            SILOG(proximity,warning,"Could not parse message");
            return OBJECT_NOT_DESTROYED;
        }

    }
Esempio n. 15
0
int cycle(Client* c, Timer* timer)
{
    // read the socket, see what work is due
    int read_status;
    unsigned short packet_type;
    read_status = readPacket(c, timer);
    packet_type = (unsigned short )read_status;

    if(read_status == SOCKET_CLOSED)
    {
    	MQTTReConnect(c);
    	goto exit;
    }
    int len = 0,
        rc = SUCCESS;
    switch (packet_type)
    {
        case CONNACK:
        {
			{
				unsigned char connack_rc = 255;
				char sessionPresent = 0;
				if (MQTTDeserialize_connack((unsigned char*)&sessionPresent, &connack_rc, c->readbuf, c->readbuf_size) == 1)
				{
					c->isconnected = 1;
					//开cloud灯
					system(SET_LIGHT_CLOUD);

					log_printf(LOG_NOTICE, "[MqttConnected]: recv connack\n");
					//subtopics and pubtopics init
					sprintf(&subtopics[0][0], "%s%s", SUBTOPIC_PRE1, gateway_info.did);
					sprintf(&subtopics[1][0], "%s%s", SUBTOPIC_PRE2, gateway_info.productkey);
					sprintf(&subtopics[2][0], "%s%s/#", SUBTOPIC_PRE3, gateway_info.did);

					sprintf(&pubtopics[0][0], "%s%s", PUBTOPIC_PRE1, gateway_info.did);
					sprintf(&pubtopics[1][0], "%s%s", PUBTOPIC_PRE2, gateway_info.did);
					sprintf(&pubtopics[2][0], "%s%s/#", PUBTOPIC_PRE3, gateway_info.did);

					rc = MQTTSubscribe(c, subtopics[c->suborder], 0, mh[c->suborder]); //for test
					log_printf(LOG_NOTICE, "Subscribing to %s\n", subtopics[c->suborder]);
					c->suborder++;
				}
			}
        }
        	break;
        case PUBACK:
        	break;
        case SUBACK:
        {
			int count = 0, grantedQoS = -1;
			unsigned short mypacketid;
			if (MQTTDeserialize_suback(&mypacketid, 1, &count, &grantedQoS, c->readbuf, c->readbuf_size) == 1)
				rc = grantedQoS; // 0, 1, 2 or 0x80
			if (rc != 0x80)
			{
				if(c->suborder <subscribe_over)
				{
					rc = MQTTSubscribe(c, subtopics[c->suborder], 0, mh[c->suborder]);
					log_printf(LOG_NOTICE, "Subscribing to %s\n",subtopics[c->suborder]);
					c->suborder++;
				}

//				int i;
//				for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i)
//				{
//					if (c->messageHandlers[i].topicFilter == 0)
//					{
//						c->messageHandlers[i].topicFilter = mytopics[i];
//						c->messageHandlers[i].fp = mh[i];
//						rc = 0;
//						break;
//					}
//				}
			}
			else
			{
				log_printf(LOG_ERROR, "SUCACK FAILED\n");
				//TODO: error handle
			}
        }
        	break;
        case PUBLISH:
        {
            if(c->suborder != subscribe_over)
            {
            	log_printf(LOG_ERROR, "[REC_MSG] rece publish msg but subcribe not over\n");
            	//TODO: error
            }
            MQTTString topicName = MQTTString_initializer;
            MQTTMessage msg;
            if (MQTTDeserialize_publish((unsigned char*)&msg.dup, (int*)&msg.qos, (unsigned char*)&msg.retained, (unsigned short*)&msg.id, &topicName,
               (unsigned char**)&msg.payload, (int*)&msg.payloadlen, c->readbuf, c->readbuf_size) != 1)
                goto exit;
            deliverMessage(c, &topicName, &msg);
//            MQTTPublish(c, "applerespond", &msg); //add by yaly for test
            if (msg.qos != QOS0)
            {
                if (msg.qos == QOS1)
                    len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id);
                else if (msg.qos == QOS2)
                    len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id);
                if (len <= 0)
                    rc = FAILURE;
                   else
                       rc = sendPacket_ev(c, len);
                if (rc == FAILURE)
                    goto exit;
            }
        }
        	break;
        case PUBREC:
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
                rc = FAILURE;
            else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREL, 0, mypacketid)) <= 0)
                rc = FAILURE;
            else if ((rc = sendPacket_ev(c, len)) != SUCCESS) // send the PUBREL packet
                rc = FAILURE;
            if (rc == FAILURE)
                goto exit;
            break;
        }
        break;
        case PUBCOMP:
            break;
        case PINGRESP:
        	log_printf(LOG_NOTICE, "[MqttPingResp]\n");
            c->ping_outstanding = 0;
            break;
    }
//    keepalive(c); //modify by yanly
exit:
    if (rc == SUCCESS)
        rc = packet_type;
    return rc;
}
Esempio n. 16
0
int cycle( Client* c, Timer* timer )
{
    // read the socket, see what work is due
    unsigned short packet_type = readPacket( c, timer );
    int len = 0;
    int rc = MQTT_SUCCESS;

    WPRINT_APP_INFO( ("Packet Type %d\n", packet_type) );

    switch ( packet_type )
    {
        case CONNACK:
        case PUBACK:
        case SUBACK:
            break;
        case PUBLISH:
        {
            MQTTString topicName;
            MQTTMessage msg;

            if ( MQTTDeserialize_publish( (unsigned char*) &msg.dup, (int*) &msg.qos, (unsigned char*) &msg.retained, (unsigned short*) &msg.id, &topicName, (unsigned char**) &msg.payload, (int*) &msg.payloadlen, c->readbuf, c->readbuf_size ) != 1 )
            {
                goto exit;
            }

            deliverMessage( c, &topicName, &msg );
            if ( msg.qos != QOS0 )
            {
                if ( msg.qos == QOS1 )
                {
                    len = MQTTSerialize_ack( c->buf, c->buf_size, PUBACK, 0, msg.id );
                }
                else if ( msg.qos == QOS2 )
                {
                    len = MQTTSerialize_ack( c->buf, c->buf_size, PUBREC, 0, msg.id );
                }
                if ( len <= 0 )
                {
                    rc = MQTT_FAILURE;
                }
                else
                {
                    rc = sendPacket( c, len, timer );
                }

                if ( rc == MQTT_FAILURE )
                {
                    goto exit;
                    // there was a problem
                }
            }
            break;
        }
        case PUBREC:
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            if ( MQTTDeserialize_ack( &type, &dup, &mypacketid, c->readbuf, c->readbuf_size ) != 1 )
            {
                rc = MQTT_FAILURE;
            }
            else if ( ( len = MQTTSerialize_ack( c->buf, c->buf_size, PUBREL, 0, mypacketid ) ) <= 0 )
            {
                rc = MQTT_FAILURE;
            }
            else if ( ( rc = sendPacket( c, len, timer ) ) != MQTT_SUCCESS ) // send the PUBREL packet
            {
                rc = MQTT_FAILURE; // there was a problem
            }

            if ( rc == MQTT_FAILURE )
            {
                goto exit;
                // there was a problem
            }

            break;
        }
        case PUBCOMP:
            break;
        case PINGRESP:
            c->ping_outstanding = 0;
            break;
    }

    keepalive( c );

    exit: if ( rc == MQTT_SUCCESS )
    {
        rc = packet_type;
    }

    return rc;
}
Esempio n. 17
0
int cycle(MQTTClient* c, Timer* timer)
{
    Timer t;
    platform_timer_init(&t);

    int len = 0, packet_type, rc = MQTT_SUCCESS;

    // read the socket, see what work is due
    if ((packet_type = readPacket(c, timer)) == MQTT_CONNECTION_LOST)
	{
		rc = MQTT_CONNECTION_LOST;
		goto exit;
	}
    
    switch (packet_type)
    {
        case CONNACK:
        case PUBACK:
        case SUBACK:
            break;
        case PUBLISH:
        {
            MQTTString topicName;
            MQTTMessage msg = {0};
            int intQoS;
            if (MQTTDeserialize_publish(&msg.dup, &intQoS, &msg.retained, &msg.id, &topicName,
               (unsigned char**)&msg.payload, &msg.payloadlen, c->readbuf, c->readbuf_size) != 1)
                goto exit;
            msg.qos = (enum QoS)intQoS;
            deliverMessage(c, &topicName, &msg);
            if (msg.qos != QOS0)
            {
                if (msg.qos == QOS1)
                    len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id);
                else if (msg.qos == QOS2)
                    len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id);
                if (len <= 0)
                    rc = MQTT_FAILURE;
                else
                {
                    platform_timer_countdown(&t, c->command_timeout_ms);
                    rc = sendPacket(c, len, &t);
                }
                if (rc == MQTT_FAILURE)
                    goto exit; // there was a problem
            }
            break;
        }
        case PUBREC:
        {
            unsigned short mypacketid;
            unsigned char dup, type;
            platform_timer_countdown(&t, c->command_timeout_ms);
            if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1)
                rc = MQTT_FAILURE;
            else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREL, 0, mypacketid)) <= 0)
                rc = MQTT_FAILURE;
            else if ((rc = sendPacket(c, len, &t)) != MQTT_SUCCESS) // send the PUBREL packet
                rc = MQTT_FAILURE; // there was a problem
            if (rc == MQTT_FAILURE)
                goto exit; // there was a problem
            break;
        }
        case PUBCOMP:
            break;
        case PINGRESP:
            c->ping_outstanding = 0;
            platform_printf("received ping response\n");
            break;
    }

    keepalive(c);

    if (c->ping_outstanding && platform_timer_isexpired(&c->pingresp_timer))
    {
        c->ping_outstanding = 0;
		platform_printf("ping response was not received within keepalive timeout of %d\n", 
                c->keepAliveInterval);
        rc = MQTT_CONNECTION_LOST;
    }

exit:
	if (rc == MQTT_SUCCESS)
		rc = packet_type;

	return rc;
}
Esempio n. 18
0
int cycle(MQTTClient *c, Timer *timer)
{
    int len = 0,
        rc = SUCCESS;

    int packet_type = readPacket(c, timer);     /* read the socket, see what work is due */

    switch (packet_type) {
    default:
        /* no more data to read, unrecoverable. Or read packet fails due to unexpected network error */
        rc = packet_type;
        goto exit;

    case 0: /* timed out reading packet */
        break;

    case CONNACK:
    case PUBACK:
    case SUBACK:
    case UNSUBACK:
        break;

    case PUBLISH: {
        MQTTString topicName;
        MQTTMessage msg;
        int intQoS;
        msg.payloadlen = 0; /* this is a size_t, but deserialize publish sets this as int */

        if (MQTTDeserialize_publish(&msg.dup, &intQoS, &msg.retained, &msg.id, &topicName,
                                    (unsigned char **)&msg.payload, (int *)&msg.payloadlen, c->readbuf, c->readbuf_size) != 1) {
            goto exit;
        }

        msg.qos = (enum QoS)intQoS;
        deliverMessage(c, &topicName, &msg);

        if (msg.qos != QOS0) {
            if (msg.qos == QOS1) {
                len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id);
            } else if (msg.qos == QOS2) {
                len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id);
            }

            if (len <= 0) {
                rc = FAILURE;
            } else {
                rc = sendPacket(c, len, timer);
            }

            if (rc == FAILURE) {
                goto exit;    // there was a problem
            }
        }

        break;
    }

    case PUBREC:
    case PUBREL: {
        unsigned short mypacketid;
        unsigned char dup, type;

        if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1) {
            rc = FAILURE;
        } else if ((len = MQTTSerialize_ack(c->buf, c->buf_size,
                                            (packet_type == PUBREC) ? PUBREL : PUBCOMP, 0, mypacketid)) <= 0) {
            rc = FAILURE;
        } else if ((rc = sendPacket(c, len, timer)) != SUCCESS) { // send the PUBREL packet
            rc = FAILURE;    // there was a problem
        }

        if (rc == FAILURE) {
            goto exit;    // there was a problem
        }

        break;
    }

    case PUBCOMP:
        break;

    case PINGRESP:
        c->ping_outstanding = 0;
        break;
    }

    if (keepalive(c) != SUCCESS) {
        //check only keepalive FAILURE status so that previous FAILURE status can be considered as FAULT
        rc = FAILURE;
    }

exit:

    if (rc == SUCCESS) {
        rc = packet_type;
    } else if (c->isconnected) {
        MQTTCloseSession(c);
    }

    return rc;
}