Beispiel #1
0
bool ReadFromRetQueue(const string &szQueue, char *pBuffer, int &nRetSize, string szIDCUser = "******",
                       string szAddr = "localhost")
{
    bool bRet = false;
    static const string szDynLabel = "DYNPARAM";
    static const string szEnd   = "DYNEND";

    MQRECORD mrd = PopMessage(szQueue, 2000, szIDCUser, szAddr);
	if(mrd != INVALID_VALUE)
	{
        string szLabel("");
        svutil::TTime ct;
	    unsigned int len = 0;
	    if(GetMessageData(mrd, szLabel, ct, NULL, len))
	    {
            if(szLabel == szDynLabel)
            {
                if(pBuffer && len <= static_cast<unsigned int>(nRetSize))
                {
                    if(!::GetMessageData(mrd, szLabel, ct, pBuffer, len))
                    {
                        memset(pBuffer, 0, nRetSize);
                    }
                    else
                    {
                        nRetSize = len;
                        bRet = true;
                    }
                }
            }
            else if(szLabel == szEnd)
            {
                bRet = true;
            }
        }
    }
    return bRet;
}
Beispiel #2
0
bool MonitorThread::RunInProcess(int iLen,string dllname,string funname)
{
	if(m_Monitor==NULL)
		throw MSException("Monitor is empty in RunInProcess function");

#ifdef WIN32

	DWORD dw=::GetCurrentThreadId();
	char queuename[256]={0};
	sprintf(queuename,"SiteView_RunMonitor_%d",dw);
	::CreateQueue(queuename,2);
	::ClearQueueMessage(queuename);

	ProcessMonitorData pdata;
	pdata.m_data=m_InBuf.getbuffer();
	pdata.m_datalen=iLen;
	pdata.m_dllname=dllname;
	pdata.m_funname=funname;
    
	int len=pdata.GetRawDataSize();
	if(len<=RETBUFCOUNT)
	{
		if(!pdata.GetRawData(m_RetBuf,len))
			throw MSException("Get data failed in RunInProcess function");
		if(!::PushMessage(queuename,"InData",m_RetBuf,len))
			throw MSException("PushMessage failed in RunInProcess function");
	}else
	{
		svutil::buffer ibuf;
		if(!ibuf.checksize(len))
			throw MSException("Malloc memmory failed in RunInProcess function");

		if(!pdata.GetRawData(ibuf,len))
			throw MSException("Get data failed2 in RunInProcess function");
	}
	char strCommandLine[1024]={0};
	sprintf(strCommandLine,"%s\\fcgi-bin\\MonitorSchedule.exe -e %s",(char *)g_strRootPath,queuename);
//	sprintf(strCommandLine,"\"%s\\fcgi-bin\\MonitorSchedule.exe\"",(char *)g_strRootPath);
	PROCESS_INFORMATION pi;
	ZeroMemory( &pi, sizeof(PROCESS_INFORMATION) );
	STARTUPINFO si;
	ZeroMemory( &si, sizeof(STARTUPINFO) );
	si.cb=sizeof(STARTUPINFO);

	char strDir[256]={0};
	sprintf(strDir,"%s\\fcgi-bin\\",(char *)g_strRootPath);
	printf("CommandLine :%s\n",strCommandLine);
	printf("dir :%s\n",strDir);

	if(!::CreateProcess(NULL,
		strCommandLine,
		NULL,
		NULL,
		FALSE,
		/*CREATE_NO_WINDOW*/CREATE_NEW_CONSOLE,
		NULL,
		strDir,
		&si,&pi))
	{
		
		DWORD dw=GetLastError();
		printf("error:%d\n",dw);
		::DeleteQueue(queuename);

		throw MSException("Create process failed in RunInProcess function");
	}

   ::WaitForSingleObject(pi.hProcess,INFINITE);

   MQRECORD mrd=::PopMessage(queuename);
   if(mrd==INVALID_VALUE)
   {
		::DeleteQueue(queuename);
	   throw MSException("Receive messgae failed in RunInProcess function");
   }

   string label="";
   unsigned int blen=0;
   svutil::TTime rt;
   if(!GetMessageData(mrd,label,rt,NULL,blen))
   {
	   ::CloseMQRecord(mrd);
		::DeleteQueue(queuename);
	   throw MSException("GetMessageData failed in RunInProcess function");
   }

   if(label.compare("SiteView_Return")!=0)
   {
	   ::CloseMQRecord(mrd);
		::DeleteQueue(queuename);
	   throw MSException("Return data error in RunInProcess function");
   }

   if(blen>RETBUFCOUNT)
   {
	   ::CloseMQRecord(mrd);
		::DeleteQueue(queuename);
	   throw MSException("Return data too big in RunInProcess function");
   }

   if(!GetMessageData(mrd,label,rt,m_RetBuf,blen))
   {
	   ::CloseMQRecord(mrd);
		::DeleteQueue(queuename);
	   throw MSException("GetMessageData failed2 in RunInProcess function");
   }
   ::CloseMQRecord(mrd);
   ::DeleteQueue(queuename);


#endif

	return true;
}
Beispiel #3
0
/****************************************************************************
 Function
    RunLobbyistSM

 Parameters
   ES_Event : the event to process

 Returns
   ES_Event, ES_NO_EVENT if no error ES_ERROR otherwise

 Description
   Deals with the high level state transitions of the Lobbyist state machine.
****************************************************************************/
ES_Event RunLobbyistSM( ES_Event ThisEvent )
{
  ES_Event ReturnEvent;
  ReturnEvent.EventType = ES_NO_EVENT; // assume no errors

  switch ( CurrentState )
  {
    case InitPState :       // If current state is initial Psedudo State
        if ( ThisEvent.EventType == ES_INIT ) // only respond to ES_Init
        {
            //Prep the timer hardware.
						printf("Init Steering \r\n");
						InitSteering();					// Initialize the steering systems
						printf("Init Packets \r\n");					
						InitPackets(); 					// Initialize packet array
						printf("Init XBee \r\n");
            InitXBee(); 						// Initialize the comms
						printf("Init Lift Fan \r\n");
						InitLiftFan();					// Initialize the lift fan
            //Initialize the DMC.
            CurrentState = WaitingForPair;
        }
    break;

    case WaitingForPair :
      switch ( ThisEvent.EventType )
      {
        //If the event is a pair request, change state to pairing and wait for the key.
        case MESSAGE_RECEIVED:
					// Read incoming message
					message = GetMessageData();
					// Check that message is a pair request and that it's meant for us
					if(*message == PAIR_REQUEST_HEADER && CheckLobbyistNumber() && GetApiIdentifier() == INCOMING_PACKET_API_IDENTIFIER){  // Ensure that this is not a Tx success receive
						printf("\r\n Current Message Size: %d ", GetMessageDataSize());
						// If we passed the checks, we're now paired. Start timers.
						printf("\n\r\nPair request received in unpaired state.");
						ES_Timer_InitTimer(UNPAIR_TIMER, UNPAIR_TIME); //Start the 45s timer
						ES_Timer_InitTimer(PAIR_FAIL_TIMER, ONE_SEC); //Start the 1s timer
						
						
						TurnOnLiftFan();     					//Start the lift fan
						//Update DMC
						
						// Recognize our new pac daddy
						pairedAddress = GetSenderAddress() ;
						// Send an ACK back to the sender
						TransmitStatusPacket(PAIRED); 
						// Set the pair time
						PairTimeLeft = 45;
						CurrentState = PairedAwaitEncryptionKey;
				}
        break;
        default :
            ; 
      }
    break;

    case PairedAwaitEncryptionKey:
      switch(ThisEvent.EventType){
        case MESSAGE_RECEIVED:
					// Check sender and message
					message = GetMessageData();
					uint16_t sender = GetSenderAddress() ;
					if(sender == pairedAddress && *message == KEY_SEND_HEADER){
						printf("\n\r\nKey received in pairing state.");
						//Save the key 
						SetKey((message+1)); // Make sure to +1 to start after header byte
						
						ES_Timer_InitTimer(PAIR_FAIL_TIMER, ONE_SEC); //Restart the 1s timer
						TransmitStatusPacket(PAIRED); //transmit status with the pairing bit set.
						CurrentState = PairedAwaitControl;
						printf("\r\n In paired await control");
				}
        break;
        case ES_TIMEOUT: // if there is a timeout on the 1s timer
					printf("\n\r\n1s timeout in pairing - moving to awaiting pair.");
					TurnOffLiftFan(); 										//Turn off the lift fan
					//Update DMC to avaiable for pairing
					ES_Timer_StopTimer(UNPAIR_TIMER); 		//Disable the 45s pairing timer
					ES_Timer_StopTimer(PAIR_FAIL_TIMER); 	//Disable the 1s transmit timeout timer
					TransmitStatusPacket(UNPAIRED); 			//Transmit status with the pairing bit cleared.
					CurrentState = WaitingForPair;
        break;
      }
    break;

    case PairedAwaitControl:
      switch(ThisEvent.EventType){
        case MESSAGE_RECEIVED:
					// See who sent the message
					uint16_t sender = GetSenderAddress() ;
					if(sender == pairedAddress){  // Only attempt decrypt if from sender
						message = DecryptMessage(GetMessageData(),GetMessageDataSize());
						RotateCipher();
	//					printf("\r\n Rotating Key");
						if(*message == CNTRL_REQUEST_HEADER){
							//printf("\n\r\nCommand received in the paired state.");
							ES_Timer_InitTimer(PAIR_FAIL_TIMER, ONE_SEC); //Restart the control command timer.
							ExecuteControl(); //Execute the control command.
							TransmitStatusPacket(PAIRED);// ACK YAY. Transmit the status with pairing bit set.
						} else {
							printf("\n\r Not a valid control packet received, Header: %d", *message);
						}
				}
        break;

        case ES_TIMEOUT: //Either the 1s or 45s timer
				case MANUAL_UNPAIR: // Or if the pair is manual
				case DECRYPT_FAIL:  // Or if the decryption failed
          if(ThisEvent.EventParam == UNPAIR_TIMER){
						// Keep track of how long is left on UNPAIR_TIMER
              PairTimeLeft--;
              printf("\n\r\nTime until unpair: %ds", PairTimeLeft);
						// If timer has run for 45 s
              if(PairTimeLeft == 0){    
                CurrentState = WaitingForPair;
								TurnOffLiftFan(); 										//Turn off the lift fan
								UpdateSteering(OFF,OFF);							//Turn off the propulsion fans
								//Update DMC to avaiable for pairing
								ES_Timer_StopTimer(UNPAIR_TIMER); 		//Disable the 45s pairing timer
								ES_Timer_StopTimer(PAIR_FAIL_TIMER); 	//Disable the 1s transmit timeout timer
                printf("\n\r\nUnpairing.");
						// If timer is not at 0, reinitialize the timer again for 1s to keep counting
              }else{
								 ES_Timer_InitTimer(UNPAIR_TIMER, UNPAIR_TIME); //Start the 45s timer
							}								
						} else {  
							// If we have an event NOT on the 45s timer, unpair
								printf("\n\r\nTimeout in the paired state. Moving to waiting for pair \r\n");
								TurnOffLiftFan(); 										//Turn off the lift fan
								UpdateSteering(OFF,OFF);							//Turn off the propulsion fans
								//Update DMC to avaiable for pairing
								ES_Timer_StopTimer(UNPAIR_TIMER); 		//Disable the 45s pairing timer
								ES_Timer_StopTimer(PAIR_FAIL_TIMER); 	//Disable the 1s transmit timeout timer
								if(ThisEvent.EventType == DECRYPT_FAIL){	// If this event came from a decryption failure 		//// WEHERE DOES THIS COME FROM?
									TransmitStatusPacket(DECRYPT_FAILURE);	// Transmit status with the decryption fail bit set
								} else {
									TransmitStatusPacket(UNPAIRED); 				//Transmit status with the pairing bit cleared.
								}
								CurrentState = WaitingForPair;
              }

        break;
      }

    break;

  default :
    break;
  }

  return ReturnEvent;
}