当前位置: 首页>>代码示例>>C++>>正文


C++ EthernetClient::available方法代码示例

本文整理汇总了C++中EthernetClient::available方法的典型用法代码示例。如果您正苦于以下问题:C++ EthernetClient::available方法的具体用法?C++ EthernetClient::available怎么用?C++ EthernetClient::available使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在EthernetClient的用法示例。


在下文中一共展示了EthernetClient::available方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: mqtt_read

/**
 *
 * @brief MQTT Paho client read interface
 *
 * @param n             pointer to the Network stucture
 * @param buffer        buffer to read into
 * @param length        number of bytes to into
 * @timeout timeout_ms  timeout
 *
 * @return Number of by bytes read
 *
 * \NOMANUAL
 */
int mqtt_read(Network* n, unsigned char* buffer, int length, int timeout_ms) {
    
    int availableBytes;
    int count;
    Timer t;
    EthernetClient* client = (EthernetClient*)n->client;
  
    InitTimer(&t);
    countdown_ms(&t, timeout_ms);
    
// try to do stuff until timer expires

   while (!(availableBytes = client->available()) && (!expired(&t)));
    
   count = (length < availableBytes) ? length : availableBytes;

    for (int i = 0; i < count; i++) {
        buffer[i] = (unsigned char)client->read();
    }
 
    return count;
}
开发者ID:Wind-River,项目名称:rocket-arduino-lite,代码行数:35,代码来源:paho-rocket.cpp

示例2: loop

void loop()
{

  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);

  }

}
开发者ID:ern0,项目名称:posixino,代码行数:22,代码来源:WebClient.cpp

示例3: ReadRequestLine

bool ReadRequestLine()
{
    _requestLine[0] = CH_NONE;
    uint8_t pos = 0;
    char prevChar = CH_NONE;
    bool isRead = false;
    
    while (_etClient.available())
    {
        isRead = true;
        // Can not read more - buffer overflow return null.
        if (pos == MAX_REQUEST_LINE_LEN - 1)
        { return false; }
        
        char c = _etClient.read();
#ifdef DEBUG
        Serial.write(c);
#endif
        // Add only chars, exclude CR LF.
        if(c != CH_CR && c != CH_LF)
        { _requestLine[pos++] = c; }
        
        // Find end line, after this start Post data.
        if(prevChar == CH_CR && c == CH_LF)
        { break; }

        prevChar = c;
    }
	
	// Add \0.
	_requestLine[pos] = CH_NONE;
    
    // Is not read - return false.
    if (!isRead)
    { return false; }
    
    return true;
}
开发者ID:nhanh0,项目名称:Arduino-1,代码行数:38,代码来源:Processing.cpp

示例4: run

 void VirtuinoEthernet_WebServer::run(){
    EthernetServer server(serverPort);  
    EthernetClient client = server.available();
  if (client) {
    char c;
   if (DEBUG) Serial.println(clientConnected);
    
    while (client.connected()) {
      if (client.available()) {
        c = client.read();
        lineBuffer.concat(c);
        if (DEBUG)  Serial.write(c);
      }
      if (c == '\n' ) {
              int pos = lineBuffer.indexOf("GET /");
              if (pos!=-1){                                   // We have a GET message
                   if (DEBUG) Serial.println("\n\r LineBuffer="+lineBuffer);
                  String responce = checkNetworkCommand(lineBuffer.substring(pos+5));
                   if (DEBUG) Serial.println("\n\r Responce="+responce);
                  delay(10);
                  client.flush();
                  client.println("HTTP/1.1 200 OK");
                  client.println("Content-Type: text/html");
                  client.println("Connection: close");
                  client.println();
                  client.println(responce);
                  lineBuffer="";
                  break;
                } // if pos
             lineBuffer="";
        } // if c=='\n'
    } // if client.available
    delay(1);
    client.stop();  // close the connection:
    if (DEBUG) Serial.println(clientDisconnected);
  }
  }
开发者ID:technologiescollege,项目名称:arduino,代码行数:37,代码来源:VirtuinoEthernet_WebServer.cpp

示例5: config_handler

static boolean config_handler(TinyWebServer& web_server) 
{
	web_server.send_error_code(200);
	web_server.end_headers();

	const char* length_str = web_server.get_header_value("Content-Length");
	int length = atoi(length_str);
	uint32_t start_time = millis();
	StringParse buf;

	EthernetClient client = web_server.get_client();

	while (buf.length() < length && client.connected() && (millis() - start_time < 30000)) {
		if (!client.available()) continue;
		buf += client.readString();
	}

	ParseConfig(buf);
	IP_Config.SaveConfig();

	main_page(client, F("<font color='green'>IP Config saved</font>"));

	return true;
}
开发者ID:nanda-dash,项目名称:LDuino,代码行数:24,代码来源:plcweb.cpp

示例6: readPage

String readPage(){
	int stringPos = 0; // string index counter
	boolean startRead = false; 
    //read the page, and capture & return everything between '?' and '~'

    stringPos = 0;
    memset(inString,' ', 200); //clear inString memory

	while(true){

		if (client.available()) {
		char c = client.read();
		Serial.print(c);

			if (c == '?' ) { 			//'?' is our begining character
				startRead = true; 		//Ready to start reading the part 
			}
			else if(startRead){
				if(c != '~'){ 			//'~' is our ending character
					inString[stringPos] = c;
					stringPos ++;
				}
				else{
					//got what we needed, disconnect
					startRead = false;
					c = 0;
					client.stop();
					client.flush();
					Serial.println("end of poll disconnecting.");
          
				return inString;
				}
			}
		}
	}
}
开发者ID:bclouser,项目名称:apartmentAutomation,代码行数:36,代码来源:Apartment_Ardi.C

示例7: main

int main(void)
{
	/// setup
	init();
	setup();

	/// loop control
	for(frame=0; ; ++frame)
	{
		digitalWrite(13, HIGH);

		status.reset();

	    String new_msg = "Loop #";
	    new_msg.concat(frame);

#ifdef PERIPHERAL_RTCC
	    /// check time
		if (status.VALID == status.time_valid)
		{
			GetDatetimeString(rtc.now());
		}

/* 		TODO: port RTC.chipPresent() functionality over to RTClib
	    if ( RTC.read(tm) )
	    {
	    	status.time_valid = status.VALID;
	    }
	    else
	    {
	       if ( RTC.chipPresent() )
	       {
	    	  status.time_valid = status.INVALID;
	 	      Serial.println("The DS1307 is stopped.  Please set the RTC time.");
	 	      Serial.println();
	       }
	       else
	       {
	    	 status.time_valid = status.UNINSTALLED;
	         Serial.println("DS1307 read error!  Please check the circuitry.");
	         Serial.println();
	       }
	     }
*/
#endif

	    /// Check interfaces for received messages
	    // Serial, direct to the Command Line Interface (CLI)
		if(Serial.available() > 0)
		{
			char 	buff_console [8];
			for(uint8_t len_console = 0x00; Serial.available() > 0; len_console++)
			{
				buff_console[len_console] = Serial.read();
				CLI(buff_console, len_console);
			}
		}

#ifdef INTERFACE_ASK_RX
	    // RF (1-wire ASK, aka VirtualWire), print to console
		uint8_t  buff_rf   [VW_MAX_MESSAGE_LEN];
		uint8_t  len_rf  =  VW_MAX_MESSAGE_LEN;
		if(vw_get_message(buff_rf, &len_rf))
		{
#ifdef PERIPHERAL_RTCC
			// Prefix received messages with current date-time on console
			if (status.VALID == status.time_valid)
			{
				Serial.print(currentTime);
			    Serial.write(" | ");
			}
#endif //PERIPHERAL_RTCC
			Serial.print("RF Received :  ");
			for(uint8_t i = 0; i < len_rf; i++)
			{
				Serial.print((char)buff_rf[i]);
			}
			Serial.println();
		}
#endif //INTERFACE_ASK_RX

#ifdef ETHERNET_WEBSERVER
		  EthernetClient client = server.available();
		  if (client) {
		    Serial.println("new http client");
		    // an http request ends with a blank line
		    boolean currentLineIsBlank = true;
		    while (client.connected())
		    {
		      if (client.available())
		      {
		        char c = client.read();
		        Serial.write(c);
		        // if you've gotten to the end of the line (received a newline
		        // character) and the line is blank, the http request has ended,
		        // so you can send a reply
		        if (c == '\n' && currentLineIsBlank)
		        {
		          // send a standard http response header
		          client.println("HTTP/1.1 200 OK");
//.........这里部分代码省略.........
开发者ID:mechatrocity,项目名称:greenOmatic,代码行数:101,代码来源:main1.cpp

示例8: api_call_http

void api_call_http(byte amsg_server[], char body[]) {

	char path[ 30 ];
	char host[ 30 ];
	strcpy_P(path, msg_server_path);
	strcpy_P(host, msg_server_host);

	EthernetClient client;


	if (!client) {
		Serial.println("Ethernet client not available!");
		return;
	}

	Serial.print("HTTP opening connection to ");
	Serial.println(host);
	/*
	if (!ether.dnsLookup(website))
		  Serial.println("DNS failed");
	else
		  Serial.println("DNS resolution done");
	ether.printIp("SRV IP:\t", ether.hisip);
	*/

	if (!client.connect(amsg_server, pgm_read_word(&msg_server_port))) {
		Serial.println("HTTP failed");
		return;
	}

	char d;
	//TODO: add serial number, hash message, JSON
	String postbuf = body;
	String netbuf = "POST ";
	netbuf += path;
	netbuf += " HTTP/1.0\nHost: ";
	netbuf += host;
	netbuf += "\nContent-Type: application/x-www-form-urlencoded\nContent-length:";
	netbuf += postbuf.length();
	netbuf += "\nConnection: close\n\n";
	netbuf += postbuf;
  //compile error on arduino 1.6.2
  //it's just a memory optimization
	//postbuf = NULL;

	Serial.println("HTTP connected");
	Serial.print(netbuf);

	char sockbuf[ netbuf.length() +1];
	netbuf.toCharArray(sockbuf, netbuf.length()+1);
	client.write(sockbuf);
	delay(300);
	while(client.connected()) {
		while(client.available())   {
			d = client.read();
			if (d == '\n')
				Serial.print("\r\n");
			else
				Serial.print(d);
		}
	}
	client.stop();
	Serial.println();
}
开发者ID:markkimsal,项目名称:homesecurity,代码行数:64,代码来源:api_call_http.cpp

示例9: progMode

void ArduinoConnectEthernet::progMode(EthernetServer server)
{
	setConnected(true);
	while(isConnected() == true)
	{
		EthernetClient client = server.available();
	    if (client) 
	    {
	        boolean currentLineIsBlank = true;
	        input = "";
	        while (client.connected()) 
	        {
	            if (client.available()) 
	            {
	                char c = client.read();
	                if(reading && c == ' ') reading = false;
	                if(c == '?') 
	                {
	                    reading = true;
	                }

	                if(reading)
	                {
	                	//opt
	                	//Serial.println(c);
	                    if (c!='?') 
	                    {
	                        input += c;
	                    }
	                }

	                if(c == '\n' && currentLineIsBlank)  
	                {
	                    break;
	                }

	                if (c == '\n') 
	                {
	                    currentLineIsBlank = true;
	                }
	                else if (c != '\r') 
	                {
	                    currentLineIsBlank = false;
	                }
	            }
	        }
	        memset(buffer,'\0',sizeof(buffer));
	        String httpValue = "arduinoValue: ";
	        bool readCmd = false;
	        parseRequest(input);
	        if(result[0] == "pinMode")
			{
				if(result[2] == "0")
				{
					result[1].toCharArray(buffer, 50);
					pinMode(atoi(buffer), INPUT);
					Serial.println(result[0] + " " + result[1] + " " + result[2]);
				}
				else if(result[2] == "1")
				{
					result[1].toCharArray(buffer, 50);
					pinMode(atoi(buffer), OUTPUT);
					Serial.println("1");
				}
				else if(result[2] == "2")
				{
					result[1].toCharArray(buffer, 50);
					pinMode(atoi(buffer), INPUT_PULLUP);
					Serial.println("1");
				}
			}
			else if(result[0] == "digitalWrite")
			{
				if(result[2] == "0")
				{
					result[1].toCharArray(buffer, 50);
					digitalWrite(atoi(buffer), LOW);
					Serial.println("lw");
				}
				else if(result[2] == "1")
				{
					result[1].toCharArray(buffer, 50);
					digitalWrite(atoi(buffer), HIGH);
					Serial.println("hi");
				}
			}
			else if(result[0] == "digitalRead")
			{
				result[1].toCharArray(buffer, 50);
				Serial.println(digitalRead(atoi(buffer)));
				if(digitalRead(atoi(buffer)))
				{
					httpValue = httpValue + "HIGH";
				}
				else
				{
					httpValue = httpValue + "LOW";
				}
				readCmd = true;
			}
//.........这里部分代码省略.........
开发者ID:mpaleo,项目名称:arconet-arduino,代码行数:101,代码来源:ArduinoConnectEthernet.cpp

示例10: networkManage

void networkManage() {
	uint16_t size;

	if (sendClient.available()) {
//		int size = sendClient.read((uint8_t *) buf2, BUFFER_SIZE);
		size = readHttpFrame(sendClient);
#ifdef HMAC
		if (!isTimeReady()) {
			uint16_t endPos = strstrpos_P((char *) buf, DOUBLE_ENDL);
			receiveTime((char *) &buf[endPos + 4]);
		}
#endif
	}

#ifdef HMAC
	if (!isTimeReady() && sendClient.status() == SnSR::CLOSED && (lastFailTime == 0 || millis() - lastFailTime > dateFailRetryWait)) {
		if (sendClient.connect(NotifyDstIp, notifyDstPort)) {
			int len = clientBuildTimeQuery((char *) buf);
			sendClient.write(buf, len);
		} else {
			lastFailTime = millis();
			sendClient.stop();
		}
	}
#endif

	if (!sendClient.connected()) {
		sendClient.stop();
	}

	if (notification != 0 && sendClient.status() == SnSR::CLOSED) {
		// there is a notif and we are not handling another one
		if (lastFailTime == 0 || millis() - lastFailTime > notifFailRetryWait) {
			if (sendClient.connect(NotifyDstIp, notifyDstPort)) {
				int len = clientBuildNextQuery((char *) buf);
				sendClient.write(buf, len);
			} else {
				lastFailTime = millis();
				sendClient.stop();
			}
		}
	}

	EthernetClient client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                size = readHttpFrame(client);

                if (size > 0) {
                    buf[size] = 0;
                    size = handleWebRequest((char *) buf, 0, size);
                    buf[size] = 0;
                    client.println((const char *) buf);
                }

                delay(1);
                client.stop();
            }
        }
    }
	if (needReboot) {
		resetFunc();
	}
}
开发者ID:housecream,项目名称:restmcu,代码行数:65,代码来源:network-w5100.cpp

示例11: gatewayTransportSend

bool gatewayTransportSend(MyMessage &message)
{
	bool ret = true;
	char *_ethernetMsg = protocolFormat(message);

    setIndication(INDICATION_GW_TX);

	_w5100_spi_en(true);
	#if defined(MY_CONTROLLER_IP_ADDRESS)
		#if defined(MY_USE_UDP)
			_ethernetServer.beginPacket(_ethernetControllerIP, MY_PORT);
			_ethernetServer.write(_ethernetMsg, strlen(_ethernetMsg));
			// returns 1 if the packet was sent successfully
			ret = _ethernetServer.endPacket();
		#else
			EthernetClient client;
			#if defined(MY_CONTROLLER_URL_ADDRESS)
	                	if (client.connected() || client.connect(MY_CONTROLLER_URL_ADDRESS, MY_PORT)) {
	        	#else
	                	if (client.connected() || client.connect(_ethernetControllerIP, MY_PORT)) {
	        	#endif
	                	client.write(_ethernetMsg, strlen(_ethernetMsg));
	                }
	                else {
	                	// connecting to the server failed!
	                	ret = false;
	                }
		#endif
	#else
		// Send message to connected clients
		#if defined(MY_GATEWAY_ESP8266)
			for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++)
			{
				if (clients[i] && clients[i].connected())
				{
					clients[i].write((uint8_t*)_ethernetMsg, strlen(_ethernetMsg));
				}
			}
		#else
			_ethernetServer.write(_ethernetMsg);
		#endif
	#endif
	_w5100_spi_en(false);
	return ret;

}


#if defined(MY_GATEWAY_ESP8266)
	bool _readFromClient(uint8_t i) {
		while (clients[i].connected() && clients[i].available()) {
			char inChar = clients[i].read();
			if (inputString[i].idx < MY_GATEWAY_MAX_RECEIVE_LENGTH - 1) {
				// if newline then command is complete
				if (inChar == '\n' || inChar == '\r') {
					// Add string terminator and prepare for the next message
					inputString[i].string[inputString[i].idx] = 0;
					debug(PSTR("Client %d: %s\n"), i, inputString[i].string);
					inputString[i].idx = 0;
					if (protocolParse(_ethernetMsg, inputString[i].string)) {
						return true;
					}

				} else {
					// add it to the inputString:
					inputString[i].string[inputString[i].idx++] = inChar;
				}
			} else {
				// Incoming message too long. Throw away
				debug(PSTR("Client %d: Message too long\n"), i);
				inputString[i].idx = 0;
				// Finished with this client's message. Next loop() we'll see if there's more to read.
				break;
			}
		}
		return false;
	}
#else
	bool _readFromClient() {
		while (client.connected() && client.available()) {
			char inChar = client.read();
			if (inputString.idx < MY_GATEWAY_MAX_RECEIVE_LENGTH - 1) {
				// if newline then command is complete
				if (inChar == '\n' || inChar == '\r') {
					// Add string terminator and prepare for the next message
					inputString.string[inputString.idx] = 0;
					debug(PSTR("Eth: %s\n"), inputString.string);
					inputString.idx = 0;
					if (protocolParse(_ethernetMsg, inputString.string)) {
						return true;
					}

				} else {
					// add it to the inputString:
					inputString.string[inputString.idx++] = inChar;
				}
			} else {
				// Incoming message too long. Throw away
				debug(PSTR("Eth: Message too long\n"));
				inputString.idx = 0;
//.........这里部分代码省略.........
开发者ID:Clio75,项目名称:MySensors,代码行数:101,代码来源:MyGatewayTransportEthernet.cpp

示例12: tcpConnection

void tcpConnection()
{ 
  if(client)
  {
    static boolean hello = false;
    
    if(client.connected())
    {
      
      if(client.available())
      {
        if(!hello)
        {
          Serial.println("client present");
          client.println("Hello!");
          hello = true;
        }
        else
        {
          char s = client.read();
          
          if(!(s == 13 || s == 10))
          {
            stringbuilder += s;
          }
          
          if(s == '\n' && stringbuilder != "")
          {
            Serial.println(stringbuilder);
            Serial.println(Contains(stringbuilder, ","));
            if(Contains(stringbuilder, ","))
            {
              int id = stringbuilder.substring(IndexOf(stringbuilder, ",")).toInt();
              client.println(id);
              stringbuilder = RemoveFirst(stringbuilder, id + ",");
              client.println(stringbuilder);
              int cyc = stringbuilder.substring(IndexOf(stringbuilder, ",")).toInt();
              client.println(id);
              stringbuilder = RemoveFirst(stringbuilder, id + ",");
              client.println(stringbuilder);
              int inter = stringbuilder.substring(0).toInt();

              createTask(id, cyc, inter);
              client.print("Created task(");
              client.print(id);
              client.print(",");
              client.print(cyc);
              client.print(",");
              client.print(inter);
              client.println(")");
            }
            else
            {
              if(stringbuilder.toInt() >= 0)
              {
                tone(SPK, stringbuilder.toInt(), 200);
              }
            }

            stringbuilder = "";
          }
        }
      }
    }
    else
    {
      Serial.println("client disconnected");
      client.stop();
      hello = false;
    }
  }
  else
  {
    client = server.available();
  }

}
开发者ID:Nuk3R4z0r,项目名称:K-A,代码行数:77,代码来源:Server.cpp

示例13: run

//GroveStreams state machine
ethernetStatus_t GroveStreams::run(void)
{
    ethernetStatus_t ret = NO_STATUS;
    const char httpOKText[] = "HTTP/1.1 200 OK";
    static char statusBuf[sizeof(httpOKText)];

    if ( nError >= MAX_ERROR )
    {
        Serial << millis() << F(" too many network errors\n");
        mcuReset();
    }

    switch (GS_STATE)
    {
    case GS_WAIT:    //wait for next send
        break;

    case GS_SEND:
        if ( _xmit() == PUT_COMPLETE )
        {
            _msLastPacket = millis();    //initialize receive timeout
            GS_STATE = GS_RECV;
            ret = PUT_COMPLETE;
        }
        else
        {
            GS_STATE = GS_WAIT;
            ++connFail;
            ++nError;
            ret = CONNECT_FAILED;
        }
        break;

    case GS_RECV:
        {
            boolean haveStatus = false;

            if(client.connected())
            {
                uint16_t nChar = client.available();
                if (nChar > 0)
                {
                    _msLastPacket = millis();
                    Serial << _msLastPacket << F(" received packet, len=") << nChar << endl;
                    char* b = statusBuf;
                    for (uint16_t i = 0; i < nChar; i++)
                    {
                        char ch = client.read();
                        Serial << _BYTE(ch);
                        if ( !haveStatus && i < sizeof(statusBuf) )
                        {
                            if ( ch == '\r' || i == sizeof(statusBuf) - 1 )
                            {
                                haveStatus = true;
                                *b++ = 0;
                                if (strncmp(statusBuf, httpOKText, sizeof(httpOKText)) == 0)
                                {
                                    ++httpOK;
                                    nError = 0;
                                    ret = HTTP_OK;
                                }
                                else
                                {
                                    ++httpOther;
                                    ++nError;
                                    ret = HTTP_OTHER;
                                    Serial << endl << endl << millis() << F(" HTTP STATUS: ") << statusBuf << endl;
                                }
                            }
                            else
                            {
                                *b++ = ch;
                            }
                        }
                    }
                }
                //if too much time has elapsed since the last packet, time out and close the connection from this end
                else if (millis() - _msLastPacket >= RECEIVE_TIMEOUT)
                {
                    _msLastPacket = millis();
                    Serial << endl << _msLastPacket << F(" Recv timeout\n");
                    client.stop();
                    if (_ledPin >= 0) digitalWrite(_ledPin, LOW);
                    GS_STATE = GS_DISCONNECT;
                    ++recvTimeout;
                    ++nError;
                    ret = TIMEOUT;
                }
            }
            else
            {
                GS_STATE = GS_DISCONNECT;
                ret = DISCONNECTING;
            }
            break;
        }

    case GS_DISCONNECT:
        // close client end
//.........这里部分代码省略.........
开发者ID:JChristensen,项目名称:GroveStreams,代码行数:101,代码来源:GroveStreams.cpp

示例14: Run

void Mudbus::Run()
{  
  Runs = 1 + Runs * (Runs < 999);

  //****************** Read from socket ****************
 
  EthernetClient client = MbServer.available();
  if(client.available())
  {
    Reads = 1 + Reads * (Reads < 999);
    int i = 0;
    while(client.available())
    {
      ByteArray[i] = client.read();
      i++;
    }
    SetFC(ByteArray[7]);  //Byte 7 of request is FC
    if(!Active)
    {
      Active = true;
      PreviousActivityTime = millis();
      #ifdef MbDebug
        Serial.println("Mb active");
      #endif
    }
  }
  if(millis() > (PreviousActivityTime + 60000))
  {
    if(Active)
    {
      Active = false;
      #ifdef MbDebug
        Serial.println("Mb not active");
      #endif
    }
  }

  int Start, WordDataLength, ByteDataLength, CoilDataLength, MessageLength;

  //****************** Read Coils **********************
  if(FC == MB_FC_READ_COILS)
  {
    Start = word(ByteArray[8],ByteArray[9]);
    CoilDataLength = word(ByteArray[10],ByteArray[11]);
    ByteDataLength = CoilDataLength / 8;
    if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++;      
    CoilDataLength = ByteDataLength * 8;
    #ifdef MbDebug
      Serial.print(" MB_FC_READ_COILS S=");
      Serial.print(Start);
      Serial.print(" L=");
      Serial.println(CoilDataLength);
    #endif
    ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
    ByteArray[8] = ByteDataLength;     //Number of bytes after this one (or number of bytes of data).
    for(int i = 0; i < ByteDataLength ; i++)
    {
      for(int j = 0; j < 8; j++)
      {
        bitWrite(ByteArray[9 + i], j, C[Start + i * 8 + j]);
      }
    }
    MessageLength = ByteDataLength + 9;
    client.write(ByteArray, MessageLength);
    Writes = 1 + Writes * (Writes < 999);
    FC = MB_FC_NONE;
  }

  //****************** Read Registers ******************
  if(FC == MB_FC_READ_REGISTERS)
  {
    Start = word(ByteArray[8],ByteArray[9]);
    WordDataLength = word(ByteArray[10],ByteArray[11]);
    ByteDataLength = WordDataLength * 2;
    #ifdef MbDebug
      Serial.print(" MB_FC_READ_REGISTERS S=");
      Serial.print(Start);
      Serial.print(" L=");
      Serial.println(WordDataLength);
    #endif
    ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
    ByteArray[8] = ByteDataLength;     //Number of bytes after this one (or number of bytes of data).
    for(int i = 0; i < WordDataLength; i++)
    {
      ByteArray[ 9 + i * 2] = highByte(R[Start + i]);
      ByteArray[10 + i * 2] =  lowByte(R[Start + i]);
    }
    MessageLength = ByteDataLength + 9;
    client.write(ByteArray, MessageLength);
    Writes = 1 + Writes * (Writes < 999);
    FC = MB_FC_NONE;
  }

  //****************** Write Coil **********************
  if(FC == MB_FC_WRITE_COIL)
  {
    Start = word(ByteArray[8],ByteArray[9]);
    C[Start] = word(ByteArray[10],ByteArray[11]) > 0;
    #ifdef MbDebug
      Serial.print(" MB_FC_WRITE_COIL C");
//.........这里部分代码省略.........
开发者ID:formacionconarduino,项目名称:gestion-alarmas-mantenimiento,代码行数:101,代码来源:Mudbus.cpp

示例15: GetIPAddressData

bool GetIPAddressData()
{
	bool bFindIP = false;

	Serial.println("**************[IP]Begin send request**********************");
	Serial.println("=>Connecting...");
	bool bFail = false;
	// If you get a connection, report back via serial:
	if (client.connect(serverName, 80) > 0) {
		/*
		GET /n09230945.asp HTTP/1.1
		Host:automation.whatismyip.com
		Accept: *//*
		
		*/
		Serial.println("=>Connected");
		// Make a HTTP request:
		client.println("GET /n09230945.asp HTTP/1.1");
		client.println("Host:automation.whatismyip.com");
		client.println("Accept: */*");
		//client.println("Connection: close");
		client.println();
	} 
	else {
		// If you didn't get a connection to the server:
		Serial.println("=>Error: Connection failed. Initialize Ethernet Again.");

		InitializeEthernet();

		bFail = true;
	}

	if(!bFail)
	{
		Serial.println("");
		Serial.println("=>Waiting for response...");

		for(int i = 0; i < 5; i++)
		{
			if(client.available())
				break;

			delay(200); // Wait for the server. 200ms
		}

		bool bHasData = client.available();
		if (bHasData)
			Serial.println("=>Output received data");
		else
			Serial.println("=>Error: Nothing received.(Timeout)");

		if(bHasData)
		{
			/* The received data is like
			HTTP/1.1 200 OK
			Date: Sun, 14 Aug 2011 10:05:57 GMT
			Server: Microsoft-IIS/6.0
			X-Powered-By: ASP.NET
			Content-Length: 14
			Content-Type: text/html
			Set-Cookie: ASPSESSIONIDCQTCQDBB=KCDOBALDODNOIPGMIHCHDIDE; path=/
			Cache-control: private

			58.38.54.125
			*/

			bool bHttpBodyBegin = false;
			while(client.available())
			{
				int length = getline(client, gDataBuffer, DATA_BUFFER_SIZE);
				Serial.print(gDataBuffer);

				if(length == 2) // This is empty. It means the http header is finished. Next is http body.
				{
					bHttpBodyBegin = true;
					break;
				}
			}

			if(bHttpBodyBegin)
			{
				Serial.println("=>Begin to get http body...");
				// Read the http body
				int pos = 0;
				while (client.available()) 
				{
					if(pos >= (DATA_BUFFER_SIZE - 1))
					{
						Serial.println();
						Serial.println("Warning: The received data is too long. Discard the redundant data.");
						break;
					}

					char c = client.read();
					gDataBuffer[pos] = c;
					pos++;
					Serial.print(c);
				}
				gDataBuffer[pos] = '\0';

//.........这里部分代码省略.........
开发者ID:JeffreyZksun,项目名称:easyrobot2,代码行数:101,代码来源:GetExternalIPFromWimi.cpp


注:本文中的EthernetClient::available方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。