示例#1
0
void NearFieldTagCommandRequest::CommandComplete(TInt aError)
{
    BEGIN
    iRequestIssued = EFalse;
    ProcessResponse(HandlePassiveCommand(aError));
    END
}
示例#2
0
int CallHome()
{
	int length  = -1;
	char  Xml[102400]  = {0};
	char  RequestData[102400] = {0};
	char  AuthenticationData[200] = {0};
	char  CallHomeData[200] = {0};
	char *Pdata[1] = {0};
	sprintf(CallHomeData,"%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s","22222","12345678","","","","","","","","","","","","","","","","","","","","","","","");
	 Pdata[0] = CallHomeData;
	 GetHash(Pdata,1,AuthenticationData);
	sprintf(RequestData,"T[]=%s",CallHomeData);
	
	PostRequest("tams/tams/devinterface/callhome.php",RequestData,AuthenticationData,Xml);
	length = strlen(Xml);
	if(length >0)
	{
		//Response Successfull
		return ProcessResponse(Xml);
	}else
	{
		ErrorReceipt LocalErrorReceipt;
		LocalErrorReceipt.ErrorCode = -1;
		strncpy(LocalErrorReceipt.ErrorMessage,"Connection Failure",sizeof(LocalErrorReceipt.ErrorMessage)-1);
		strncpy(LocalErrorReceipt.FunctionName,"CALLHOME",sizeof(LocalErrorReceipt.FunctionName)-1);
		PrintErrorReceipt(LocalErrorReceipt);
		return -1;
	}
}
示例#3
0
void CProtocolCDT::ProcessRespond(QByteArray data_)
{
    m_bufferReceive.AppendData(data_.data(),data_.count());
    QByteArray array((char *)m_bufferReceive.GetBuffer(0),m_bufferReceive.GetInfoSize());
    qDebug()<<"array.toHex()"<<array.toHex();
    if (m_bufferReceive.GetInfoSize() < MinFrameLength)
        return ;

    for(int nStart=0; nStart<=m_bufferReceive.GetInfoSize() - MinFrameLength; ++nStart)
    {
        int nFrameLength = IsAFrame(m_bufferReceive.GetBuffer(nStart),m_bufferReceive.GetInfoSize()-nStart);
        if(nFrameLength)
        {
            m_CDTResponse.SetData(m_bufferReceive.GetBuffer(nStart),nFrameLength);
            m_bufferReceive.Fifo(nStart+nFrameLength);
            ProcessResponse(m_CDTResponse);
            nStart=-1;//重新再来
        }
    }
    if(m_bufferReceive.GetInfoSize()>MAX_FRAME)
    {
        m_bufferReceive.SetInfoSize(0);
//        Q_ASSERT(false);
    }
}
示例#4
0
			void Run() override {
				try {
					std::unique_ptr<CURL, CURLEasyDeleter> cHandle{curl_easy_init()};
					if (cHandle) {
						size_t (*curlWriteCallback)(void *, size_t, size_t, ServerListQuery *) = [](
						  void *ptr, size_t size, size_t nmemb, ServerListQuery *self) -> size_t {
							size_t numBytes = size * nmemb;
							self->buffer.append(reinterpret_cast<char *>(ptr), numBytes);
							return numBytes;
						};
						curl_easy_setopt(cHandle.get(), CURLOPT_USERAGENT, OpenSpades_VER_STR);
						curl_easy_setopt(cHandle.get(), CURLOPT_URL, cl_serverListUrl.CString());
						curl_easy_setopt(cHandle.get(), CURLOPT_WRITEFUNCTION, curlWriteCallback);
						curl_easy_setopt(cHandle.get(), CURLOPT_WRITEDATA, this);
						if (0 == curl_easy_perform(cHandle.get())) {
							ProcessResponse();
						} else {
							SPRaise("HTTP request error.");
						}
					} else {
						SPRaise("Failed to create cURL object.");
					}
				} catch (std::exception &ex) {
					std::unique_ptr<MainScreenServerList> lst{new MainScreenServerList()};
					lst->message = ex.what();
					ReturnResult(std::move(lst));
				} catch (...) {
					std::unique_ptr<MainScreenServerList> lst{new MainScreenServerList()};
					lst->message = "Unknown error.";
					ReturnResult(std::move(lst));
				}
			}
void NearFieldTagNdefRequest::WriteComplete(TInt aError)
{
    BEGIN
    iRequestIssued = EFalse;
    ProcessResponse(aError);
    END
}
示例#6
0
bool Client::GetPostResult(Value& result)
{
    log_trace();
    gettimeofday( &startTime_, 0 );
    result.SetInvalid();

    if (responseProcessed_)
    {
        PreserveReceiveBuffer();
        ResetTransaction();
    }

    if (socket_.IsConnected(0) &&
        ReadHeader(result) &&
        ReadResponse(result))
    {
        switch (ProcessResponse(result))
        {
            case ProcessResponseSuccess       : return true;
            case ProcessResponseErrorKeepOpen : return false;
        }
    }

    Reset();
    return false;
}
示例#7
0
static Err CookieRequestResponseProcessorCommon(AppContext* appContext, void* context, const char* responseBegin, const char* responseEnd, const char*& wordOut)
{
    ResponseParsingResult   result;
    Err error=ProcessResponse(appContext, responseBegin, responseEnd, 
        responseCookie|responseMessage|responseErrorMessage, result);
    if (error)
        return error;

    if (responseCookie==result)
    {
        Assert(HasCookie(appContext->prefs));
        if (context)
        {
            ExtensibleBuffer* wordBuffer=static_cast<ExtensibleBuffer*>(context);
            const char*       word=ebufGetDataPointer(wordBuffer);
            Assert(word);
            wordOut=word;
        }
        else
            wordOut=NULL;
    }
    else if (responseMessage==result || responseErrorMessage==result)
    {
        appContext->mainFormContent=mainFormShowsMessage;
        appContext->firstDispLine=0;
        // if we didn't get cookie, we need to notify the caller that he
        // can't proceed. We do that by returning an error
        // TODO: figure out some better error?
        error = 1;
    }
    else 
        Assert(false);
    return error;
}
示例#8
0
int DNSClient::getHostByName(const char* aHostname, IPAddress& aResult)
{
    int ret =0;

    // See if it's a numeric IP address
    if (inet_aton(aHostname, aResult))
    {
        // It is, our work here is done
        return 1;
    }

    // Check we've got a valid DNS server to use
    if (iDNSServer == INADDR_NONE)
    {
        return INVALID_SERVER;
    }
    
	
    // Find a socket to use
    if (iUdp.begin(localPort))
    {
        // Try up to three times
        int retries = 0;
        while ((retries < 3) && (ret <= 0))
        {
            // Send DNS request
            ret = iUdp.beginPacket(iDNSServer, DNS_PORT);
            if (ret != 0)
            {
                // Now output the request data
                ret = BuildRequest(aHostname);
                if (ret != 0)
                {
                    // And finally send the request
                    ret = iUdp.endPacket();
                    if (ret != 0)
                    {
                        // Now wait for a response
                        int wait_retries = 0;
                        ret = TIMED_OUT;
                        while ((wait_retries < 3) && (ret == TIMED_OUT))
                        {
                            ret = ProcessResponse(aResult);
                            wait_retries++;
                        }
                    }
                }
            }
            retries++;
        }

        // We're done with the socket now
        iUdp.stop();
    }

    return ret;
}
示例#9
0
/** 
 * Function: QueryIndices
 * ----------------------
 * Standard query loop that allows the user to specify a single search term, and
 * then proceeds (via ProcessResponse) to list up to 10 articles (sorted by relevance)
 * that contain that word.
 */
static void QueryIndices(void* userData)
{
  char response[1024];
  while (true) {
    printf("Please enter a single query term that might be in our set of indices [enter to quit]: ");
    fgets(response, sizeof(response), stdin);
    response[strlen(response) - 1] = '\0';
    if (strcasecmp(response, "") == 0) break;
    ProcessResponse(response,userData);
  }
}
/** 
 * Function: QueryIndices
 * ----------------------
 * Standard query loop that allows the user to specify a single search term, and
 * then proceeds (via ProcessResponse) to list up to 10 articles (sorted by relevance)
 * that contain that word.
 */
static void QueryIndices(hashset * stopWords, hashset* wordHash, 
			 hashset* articlesSeen)
{
  char response[1024];
  while (true) {
    printf("Please enter a single query term [enter to quit]: ");
    fgets(response, sizeof(response), stdin);
    response[strlen(response) - 1] = '\0';
    if (strcasecmp(response, "") == 0) break;

    ProcessResponse(response, stopWords,wordHash, articlesSeen);
  }
}
示例#11
0
LRESULT CAppWindow::OnWaveConnectionState(WAVE_CONNECTION_STATE nState, LPARAM lParam)
{
	CHECK_ENUM(nState, WCS_MAX);

	switch (nState)
	{
	case WCS_RECEIVED:
		ProcessResponse((CWaveResponse *)lParam);
		return 0;

	default:
		return OnLoginStateChanged(nState, (WAVE_LOGIN_ERROR)lParam);
	}
}
示例#12
0
void NearFieldTagCommandRequest::ProcessTimeout()
{
    if (iWait)
    {
        if (iWait->IsStarted())
        {
            if (iRequestIssued)
            {
                iOperator.DoCancelSendCommand();
                iRequestIssued = EFalse;
            }
            ProcessResponse(HandlePassiveCommand(KErrTimedOut));
        }
    }
}
示例#13
0
void mtsComponentViewer::Run(void)
{
    if (!UDrawPipeConnected) {
       ConnectToUDrawGraph();
       if (UDrawPipeConnected) {
           CMN_LOG_CLASS_INIT_VERBOSE << "Run: Sending all info" << std::endl;
           // Should flush all events before calling SendAllInfo
           SendAllInfo();
       }
    }
    ProcessQueuedCommands();
    ProcessQueuedEvents();
    if (UDrawPipeConnected)
        ProcessResponse();
}
void NearFieldTagNdefRequest::ProcessTimeout()
{
    if (iWait)
    {
        if (iWait->IsStarted())
        {
            if (iRequestIssued)
            {
                iOperator.DoCancelNdefAccess();
                iRequestIssued = EFalse;
            }
            ProcessResponse(KErrTimedOut);
        }
    }
}
示例#15
0
static void QueryIndices(rssDatabase *db)
{
  char response[1024];
  while (true) {
    printf("Please enter a single query term that might be in our set of indices [enter to quit]: ");
    fgets(response, sizeof(response), stdin);
    response[strlen(response) - 1] = '\0';
    if (strcasecmp(response, "") == 0) break;
    ProcessResponse(db, response);
  }
  
  HashSetDispose(&db->indices);
  VectorDispose(&db->previouslySeenArticles); 
  HashSetDispose(&db->stopWords);
}
示例#16
0
void Harlond::socketReadyReadData()
{
  char data[1500];
  int n;
  while((n=bt_socket->readBlock(data,1500))>0) {
    for(int i=0;i<n;i++) {
      if(data[i]=='!') {
	ProcessResponse(bt_recv_buffer);
	bt_recv_buffer="";
      }
      else {
	bt_recv_buffer+=data[i];
      }
    }
  }
}
示例#17
0
static void QueryIndices(rssData *allData)
{
  char response[1024];
  while (true) {
    printf("Please enter a single query term that might be in our set of indices [enter to quit]: ");
    fgets(response, sizeof(response), stdin);
    response[strlen(response) - 1] = '\0';
    if (strcasecmp(response, "") == 0) break;
    ProcessResponse(response, allData);
  }

  // free the memory when we're finished 
  HashSetDispose(&allData->indices); 
  HashSetDispose(&allData->stopwords); 
  VectorDispose(&allData->explored); 

}
NS_IMETHODIMP
OperationStreamListener::OnStopRequest(nsIRequest *aRequest,
                                       nsISupports *aContext,
                                       nsresult aStatusCode)
{
    PRUint32 status, rv;
    nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(aContext);

    LOG(("OperationStreamListener::OnStopRequest() entered"));

    rv = channel ? channel->GetResponseStatus(&status) : NS_ERROR_UNEXPECTED;

    if (NS_FAILED(rv))
        return SignalCompletion(rv);

    if (status != 207)
        return SignalCompletion(status);

    // ZZZ Check content-length against mBody.Length()

    // Now we parse!
    nsCOMPtr<nsIDOMNodeList> responseList;
    PRUint32 length;
    rv = NS_WD_GetDocAndResponseListFromBuffer(mBody, getter_AddRefs(mXMLDoc),
                                               getter_AddRefs(responseList),
                                               &length);
    NS_ENSURE_SUCCESS(rv, SignalCompletion(rv));

    LOG(("found %d responses", length));
    
    for (PRUint32 i = 0; i < length; i++) {
        nsCOMPtr<nsIDOMNode> responseNode;
        rv = responseList->Item(i, getter_AddRefs(responseNode));
        NS_ENSURE_SUCCESS(rv, SignalCompletion(rv));

        nsCOMPtr<nsIDOMElement> responseElt =
            do_QueryInterface(responseNode, &rv);
        NS_ENSURE_SUCCESS(rv, SignalCompletion(rv));
    
        rv = ProcessResponse(responseElt);
        NS_ENSURE_SUCCESS(rv, SignalCompletion(rv));
    }

    SignalCompletion(status);
    return NS_OK;
}
示例#19
0
bool mtsComponentViewer::ConnectToUDrawGraph(void)
{
    // Try to connect to UDrawGraph
    std::vector<std::string> arguments;
    arguments.push_back("-pipe");
    UDrawPipeConnected = UDrawPipe.Open("uDrawGraph", arguments, "rw");
    // wait for initial OK
    if (UDrawPipeConnected) {
        WaitingForResponse = true;
        UDrawResponse = "";
        // Create reader thread.
        ReaderThread.Create<mtsComponentViewer, int>(this, &mtsComponentViewer::ReadFromUDrawGraph, 0);
        // Wait for initial OK
        for (int i = 0; (i < 100) && (UDrawResponse == ""); i++)
            osaSleep(0.01);
        ProcessResponse();
        if (WaitingForResponse) {
            CMN_LOG_CLASS_RUN_ERROR << "ConnectToUDrawGraph: Failed to receive response" << std::endl;
        }

        /// Now initialize the system
        WriteString(UDrawPipe, "window(title(\"CISST Component Viewer\"))\n");
        WriteString(UDrawPipe, "app_menu(create_menus([menu_entry(\"redraw\", \"Redraw graph\"), "
#if CISST_MTS_HAS_ICE
                                                      "menu_entry(\"showproxies\", \"Show proxies\"), "
                                                      "menu_entry(\"hideproxies\", \"Hide proxies\"), "
#endif
                                                      "blank, "
                                                      "menu_entry(\"connectStart\", \"Connect Start...\"), "
                                                      "menu_entry(\"connectFinish\", \"Connect Finish\"), "
                                                      "menu_entry(\"connectCancel\", \"Connect Cancel\")]))\n");
        // Activate menu items (context-sensitive)
        ActivateMenuItems();

        // Default node rules (nr) could be removed -- not currently used
        WriteString(UDrawPipe, "visual(new_rules([er(\"CONNECTION\", [m([menu_entry(\"disconnect\", \"Disconnect\")])]), "
                                                 "nr(\"USER\", [m([menu_entry(\"start\", \"Start\"), "
                                                                  "menu_entry(\"stop\", \"Stop\")])])]))\n");
        WriteString(UDrawPipe, "drag_and_drop(dragging_on)\n");
        // Following is an example of how to create a TCL/TK window; in this case, a window with a single button "Connect"
        // that returns the message "connectPressed".
        // WriteString(UDrawPipe, "tcl(eval(\"button .b -text Connect -command {uDrawGraph tcl_answer connectPressed} ; pack .b\"))\n"); 
        CMN_LOG_CLASS_INIT_VERBOSE << "Connected to UDraw(Graph)" << std::endl;
    }
    return UDrawPipeConnected;
}
示例#20
0
void CRplNodeRsp::Process()
{
    if (m_rDevMsg->m_unSize < (int) sizeof(struct QueryHdr))
    {
        NLOG_ERR("[RplNodeRsp::Process]: invalid response size=%d, expected=%d at least",
                 m_rDevMsg->m_unSize, sizeof(struct QueryHdr));
        return;
    }

    if (QH_IS_EVENT((struct QueryHdr *) m_rDevMsg->m_pucData))
    {
        ProcessPublish();
    }
    else
    {
        ProcessResponse();
    }
}
void CVersionChecker::OnRun()
{
	CString strRequest;
	
	BuildRequest( strRequest );
	
	BOOL bRequest = UndertakeRequest( strRequest );
	
	if ( bRequest )
	{
		ProcessResponse();
		m_pResponse.RemoveAll();
	}
	else
	{
		SetNextCheck( VERSIONCHECKER_FREQUENCY );
	}
}
示例#22
0
static Err RecentLookupsResponseProcessor(AppContext* appContext, void* context, const char* responseBegin, const char* responseEnd)
{
    ResponseParsingResult result;
    Err error=ProcessResponse(appContext, responseBegin, responseEnd, 
        responseWordsList|responseMessage|responseErrorMessage, result);
    if (!error) 
    {
        if (responseWordsList==result)
            FrmPopupForm(formWordsList);
        else if (responseMessage==result || responseErrorMessage==result)
        {
            appContext->mainFormContent=mainFormShowsMessage;
            appContext->firstDispLine=0;
        }
        else
            Assert(false);
    }        
    return error;
}
示例#23
0
bool Client::Call(const char* method, Value& params, Value& result)
{
    log_trace();
    gettimeofday( &startTime_, 0 );
    result.SetInvalid();

    PreserveReceiveBuffer();
    ResetTransaction();

    if (Connect() &&
        GenerateRequest(method, params) &&
        GenerateHeader())
    {
        if (!WriteRequest(result))
        {
            // retry the connection
            Close();
            if (!Connect() ||
                !WriteRequest(result))
            {
                Reset();
                return false;
            }
        }
        // continue with the processing
        if (ReadHeader(result) &&
            ReadResponse(result))
        {
            switch (ProcessResponse(result))
            {
                case ProcessResponseSuccess       : return true;
                case ProcessResponseErrorKeepOpen : return false;
                default                           : ; // continue processing
            }
        }
    }
    Reset();
    return false;
}
示例#24
0
static Err WordLookupResponseProcessor(AppContext* appContext, void* context, const char* responseBegin, const char* responseEnd)
{
    ResponseParsingResult result;
    Err error=ProcessResponse(appContext, responseBegin, responseEnd, 
        responseDefinition|responseMessage|responseErrorMessage|responseWordsList|responseRegistrationFailed, result);
    if (error)
    {
#ifdef DEBUG
        LogStrN(appContext, responseBegin, (long) (responseEnd-responseBegin) );
#endif
        return error;
    }

    switch (result)
    {
        case responseDefinition:
            appContext->mainFormContent=mainFormShowsDefinition;
            appContext->firstDispLine=0;
            break;
            
        case responseMessage:
        case responseErrorMessage:
            appContext->mainFormContent=mainFormShowsMessage;
            appContext->firstDispLine=0;
            break;
            
        case responseWordsList:
            FrmPopupForm(formWordsList);
            break;

        case responseRegistrationFailed:
            SendEvtWithType(evtRegistrationFailed);
            break;
            
        default:
            Assert(false);
    }
    return error;
}
示例#25
0
IMasterTask::ResponseResult IMasterTask::OnResponse(const APDUResponseHeader& response, const openpal::RSlice& objects, openpal::MonotonicTimestamp now)
{
	auto result = ProcessResponse(response, objects);

	switch (result)
	{
	case(ResponseResult::ERROR_BAD_RESPONSE) :
		this->state = this->OnTaskComplete(TaskCompletion::FAILURE_BAD_RESPONSE, now);
		this->NotifyResult(TaskCompletion::FAILURE_BAD_RESPONSE);
		break;
	case(ResponseResult::ERROR_INTERNAL_FAILURE) :
		this->state = this->OnTaskComplete(TaskCompletion::FAILURE_INTERNAL_ERROR, now);
		this->NotifyResult(TaskCompletion::FAILURE_INTERNAL_ERROR);
		break;
	case(ResponseResult::OK_FINAL) :
		this->state = this->OnTaskComplete(TaskCompletion::SUCCESS, now);
		this->NotifyResult(TaskCompletion::SUCCESS);
		break;
	default:
		break;
	}

	return result;
}
示例#26
0
RsslRet UPAConsumer::ReadFromChannel(RsslChannel* chnl)
{
   RsslError		error;
   RsslBuffer *msgBuf=0;
   RsslRet	readret;

   int maxReadTime = (pingTimeoutClient_*1000)/2;
   if (chnl->socketId != -1 && chnl->state == RSSL_CH_STATE_ACTIVE)
   {

	int32_t start = utils::time::GetMilliCount();
      readret = 1;

	  // keep reading 'til nothing left or we have used half the ping interval
	  // we put int he second condition in order that when the input rate is high we still get the opportunity to send pings and other outgoing data

      while (readret > 0 || utils::time::GetMilliSpan(start) > maxReadTime )  
      {

         if ((msgBuf = rsslRead(chnl,&readret,&error)) != 0)
         {
            if (ProcessResponse(chnl, msgBuf) == RSSL_RET_SUCCESS)	
            {
               /* set flag for server message received */
               receivedServerMsg_ = RSSL_TRUE;
            }
            else
            {
               // this will trigger a reconnection so process response needs to be circumspect about return value
               return RSSL_RET_FAILURE;
            }
         }
         else
         {
            switch (readret)
            {
            case RSSL_RET_CONGESTION_DETECTED:
            case RSSL_RET_SLOW_READER:
            case RSSL_RET_PACKET_GAP_DETECTED:
               {
                  if (chnl->state != RSSL_CH_STATE_CLOSED)
                  {
                     // disconnectOnGaps must be false.  Connection is not closed 
                     t42log_error("Read Error: %s <%d>\n", error.text, readret);
                     break;
                  }
                  // if channel is closed, we want to fall through to force a reconnect
               }
            case RSSL_RET_FAILURE:
               {
                  t42log_warn("channelInactive fd=%d <%s>\n",
                     chnl->socketId,error.text);
                  RecoverConnection();
               }
               break;
            case RSSL_RET_READ_FD_CHANGE:
               {
                  t42log_info("rsslRead() FD Change - Old FD: %d New FD: %d\n", chnl->oldSocketId, chnl->socketId);
                  FD_CLR(chnl->oldSocketId, &readfds_);
                  FD_CLR(chnl->oldSocketId, &exceptfds_);
                  FD_SET(chnl->socketId, &readfds_);
                  FD_SET(chnl->socketId, &exceptfds_);
               }
               break;
            case RSSL_RET_READ_PING: 
               {
                  //set flag for server message received 
                  receivedServerMsg_ = RSSL_TRUE;
               }
               break;
            default:
               if (readret < 0 && readret != RSSL_RET_READ_WOULD_BLOCK)
               {
                  t42log_error("Read Error: %s <%d>\n", error.text, readret);

               }
               break;
            }
         }
      }
   }
   else if (chnl->state == RSSL_CH_STATE_CLOSED)
   {
      t42log_warn("Channel fd=%d Closed.\n", chnl->socketId);
      RecoverConnection();
   }

   return RSSL_RET_SUCCESS;
}
示例#27
0
ServerPanel::ServerPanel(QObject* cParent) : QObject(cParent), mOk(true) {
    // Load the configuration
    this->mConfig = new QSettings(":/ServerPanel.ini", QSettings::IniFormat);
    // Setup the databae
    this->mDbc    = QSqlDatabase::addDatabase("QSQLITE");
    // Set the database
    this->mDbc.setDatabaseName("/Users/trbrown/Documents/ServerPanel/ServerPanelClient/ServerPanelClient.sp");
    // Try to open the database
    if (!this->mDbc.open()) {
        // Dispatch a message
        this->DispatchMessageBox(this->mDbc.lastError().text(), Error);
    }
    // Create the client
    this->mClient = new QTcpSocket(this);
    // Setup the connectors
    this->connect(this->mClient, SIGNAL(connected()),                         this, SLOT(TransferData()));
    this->connect(this->mClient, SIGNAL(disconnected()),                      this, SLOT(ProcessResponse()));
    this->connect(this->mClient, SIGNAL(readyRead()),                         this, SLOT(ReadResponse()));
    this->connect(this->mClient, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SocketError(QAbstractSocket::SocketError)));
}
示例#28
0
int WiFlyRNXV::CheckUART()
{
	if(uart.available()){
		
		Serial.println("UDP command received..");
		
		char* buffer;
		char chResponse;
		int  bufpos = 0;
		
		while(uart.available()){
			
			// Read uart buffer
			chResponse = uart.read();
			Serial.print(chResponse);
			
			// Check for matching responses
			if (chResponse == KEYWORD_FRONT_DELIMITER)
			{
				Serial.println("Found start of response phrase.");
				
				// Reset the memory buffer
				buffer = (char*) malloc(RESPONSE_BUFFER_SIZE);
				memset (buffer, '\0', RESPONSE_BUFFER_SIZE-1);
				buffer[bufpos] = chResponse;
				bufpos++;
				
				// Fill memory buffer
				bool timeout = false;
				unsigned long startTime = millis();
				while(uart.available() && chResponse != KEYWORD_END_DELIMITER && !timeout)
				{
					chResponse = uart.read();
					Serial.print(chResponse);
					if(bufpos < RESPONSE_BUFFER_SIZE-1)
					{
						buffer[bufpos] = chResponse;
						bufpos++;
					}
					else
					{
						Serial.println("buffer overflow");
						bufpos=0;
					}
					if ((millis()-startTime) > TIMEOUT_TIME)
					timeout = true;
				}
				buffer[bufpos] = '\0'; // end of buffer
				
				// Flush uart buffer
				Serial.println("");
				uart.flush();
				
				return ProcessResponse(buffer);
			}
		}
	}
	
	// Nothing on UART
	else return -1;
}
void QProcessResponseThread::ParseResponseData( QByteArray &byData )
{
    ProcessResponse( byData );
}
示例#30
0
/*----------------------------------------------------------------------
|   PLT_HttpServerSocketTask::DoRun
+---------------------------------------------------------------------*/
void
PLT_SsdpSearchTask::DoRun()
{
    NPT_HttpResponse*      response = NULL;
    PLT_HttpClient         client;
    NPT_Timeout            timeout = 30;
    NPT_HttpRequestContext context;

    do {
        // get the address of the server
        NPT_IpAddress server_address;
        NPT_CHECK_LABEL_SEVERE(server_address.ResolveName(
                                   m_Request->GetUrl().GetHost(), 
                                   timeout), 
                               done);
        NPT_SocketAddress address(server_address, 
                                  m_Request->GetUrl().GetPort());

        // send 2 requests in a row
        NPT_OutputStreamReference output_stream(
            new PLT_OutputDatagramStream(m_Socket, 
                                         4096, 
                                         &address));
        NPT_CHECK_LABEL_SEVERE(client.SendRequest(
                                   output_stream, 
                                   *m_Request), 
                               done);
        NPT_CHECK_LABEL_SEVERE(client.SendRequest(
                                   output_stream, 
                                   *m_Request), 
                               done);
        output_stream = NULL;

        // keep track of when we sent the request
        NPT_TimeStamp last_send;
        NPT_System::GetCurrentTimeStamp(last_send);

        while (!IsAborting(0)) {
            // read response
            PLT_InputDatagramStreamReference input_stream(
                new PLT_InputDatagramStream(m_Socket));

            NPT_InputStreamReference stream = input_stream;
            NPT_Result res = client.WaitForResponse(stream, 
                                                    *m_Request, 
                                                    context, 
                                                    response);
            // callback to process response
            if (NPT_SUCCEEDED(res)) {
                // get source info    
                NPT_SocketInfo info;
                input_stream->GetInfo(info);

                context.SetLocalAddress(info.local_address);
                context.SetRemoteAddress(info.remote_address);

                // process response
                ProcessResponse(NPT_SUCCESS, m_Request, context, response);
                delete response;
                response = NULL;
            } else if (res != NPT_ERROR_TIMEOUT) {
                NPT_LOG_WARNING_1("PLT_SsdpSearchTask got an error (%d) waiting for response", res);
            }

            input_stream = NULL;

            // check if it's time to resend request
            NPT_TimeStamp now;
            NPT_System::GetCurrentTimeStamp(now);
            if (now >= last_send + (long)m_Timeout/1000)
                break;
        }
    } while (!IsAborting(0) && m_Repeat);

done:
    return;
}