/**
 *
 * @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;
}
Beispiel #2
0
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);

  }

}
Beispiel #3
0
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;
}
Beispiel #4
0
void loop() {
    // read the analog sensor:
    int sensorReading = analogRead(A0);
    // convert the data to a String to send it:
    String dataString = String(sensorReading);

    // you can append multiple readings to this String if your
    // pachube feed is set up to handle multiple values:
    int otherSensorReading = analogRead(A1);
    dataString += ",";
    dataString += String(otherSensorReading);

    // if there's incoming data from the net connection.
    // send it out the serial port.  This is for debugging
    // purposes only:
    if (client.available()) {
        char c = client.read();
        Serial.print(c);
    }

    // if there's no net connection, but there was one last time
    // through the loop, then stop the client:
    if (!client.connected() && lastConnected) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
    }

    // if you're not connected, and ten seconds have passed since
    // your last connection, then connect again and send data:
    if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
        sendData(dataString);
    }
    // store the state of the connection for next time through
    // the loop:
    lastConnected = client.connected();
}
 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);
  }
  }
Beispiel #6
0
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;
}
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;
				}
			}
		}
	}
}
Beispiel #8
0
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");
		          client.println("Content-Type: text/html");
		          client.println("Connection: close");  // the connection will be closed after completion of the response
		          client.println("Refresh: 60");  // refresh the page automatically every 60 sec
		          client.println();
		          client.println("<!DOCTYPE HTML>");
		          client.println("<html>");

#ifdef PERIPHERAL_RTCC
		          client.print("green-O-matic RTC Time : ");
		          client.println(currentTime);
#endif //PERIPHERAL_RTCC

#ifdef INTERFACE_ASK_RX
		          client.println("Most recently received 433MHz ASK Transmission : ");
#endif //INTERFACE_ASK_RX

		          client.println("</html>");
		          break;
		        }
		        if (c == '\n')
		        {
		          // you're starting a new line
		          currentLineIsBlank = true;
		        }
		        else if (c != '\r')
		        {
		          // you've gotten a character on the current line
		          currentLineIsBlank = false;
		        }
		      }
		    }
		    // give the web browser time to receive the data
		    delay(5);
		    // close the connection
		    client.stop();
		    Serial.println("client disconnected");
		  }
#endif //ETHERNET_WEBSERVER

		digitalWrite(13, LOW);

		delay (LOOP_DELAY);
	};
	return 0;
}
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();
}
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;
			}
			else if(result[0] == "analogWrite")
			{
				result[1].toCharArray(buffer, 50);
				char buffer2[50];
				result[2].toCharArray(buffer2, 50);
				analogWrite(atoi(buffer),atoi(buffer2));
				Serial.println("1");
			}
			else if(result[0] == "analogRead")
			{
				result[1].toCharArray(buffer, 50);
				Serial.println(analogRead(atoi(buffer)));

				httpValue = httpValue + analogRead(atoi(buffer));
				readCmd = true;
			}
			else if(result[0] == "continueFlow")
			{
				setConnected(false);
				Serial.println("1");
			}
			client.println("HTTP/1.1 200 OK");
			if(readCmd)
			{
				client.println(httpValue);
	    	}
	    	client.println("Connection: close");
	        client.stop();
	        delay(100);
		}
	}
	
}
Beispiel #11
0
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();
	}
}
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;
				// Finished with this client's message. Next loop() we'll see if there's more to read.
				break;
			}
		}
		return false;
	}
#endif


bool gatewayTransportAvailable()
{
	_w5100_spi_en(true);
	#if !defined(MY_IP_ADDRESS) && defined(MY_GATEWAY_W5100)
		// renew IP address using DHCP
		gatewayTransportRenewIP();
	#endif

	#ifdef MY_USE_UDP

		int packet_size = _ethernetServer.parsePacket();

		if (packet_size) {
			//debug(PSTR("UDP packet available. Size:%d\n"), packet_size);
            setIndication(INDICATION_GW_RX);
			#if defined(MY_GATEWAY_ESP8266)
				_ethernetServer.read(inputString[0].string, MY_GATEWAY_MAX_RECEIVE_LENGTH);
				inputString[0].string[packet_size] = 0;
				debug(PSTR("UDP packet received: %s\n"), inputString[0].string);
				return protocolParse(_ethernetMsg, inputString[0].string);
			#else
				_ethernetServer.read(inputString.string, MY_GATEWAY_MAX_RECEIVE_LENGTH);
				inputString.string[packet_size] = 0;
				debug(PSTR("UDP packet received: %s\n"), inputString.string);
				_w5100_spi_en(false);
				return protocolParse(_ethernetMsg, inputString.string);
			#endif
		}
	#else
		#if defined(MY_GATEWAY_ESP8266)
			// ESP8266: Go over list of clients and stop any that are no longer connected.
			// If the server has a new client connection it will be assigned to a free slot.
			bool allSlotsOccupied = true;
			for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++) {
				if (!clients[i].connected()) {
					if (clientsConnected[i]) {
						debug(PSTR("Client %d disconnected\n"), i);
						clients[i].stop();
					}
					//check if there are any new clients
					if (_ethernetServer.hasClient()) {
						clients[i] = _ethernetServer.available();
						inputString[i].idx = 0;
						debug(PSTR("Client %d connected\n"), i);
						gatewayTransportSend(buildGw(_msg, I_GATEWAY_READY).set("Gateway startup complete."));
						if (presentation)
							presentation();
					}
				}
				bool connected = clients[i].connected();
				clientsConnected[i] = connected;
				allSlotsOccupied &= connected;
			}
			if (allSlotsOccupied && _ethernetServer.hasClient()) {
				//no free/disconnected spot so reject
				debug(PSTR("No free slot available\n"));
				EthernetClient c = _ethernetServer.available();
				c.stop();
			}
				// Loop over clients connect and read available data
			for (uint8_t i = 0; i < ARRAY_SIZE(clients); i++) {
				if (_readFromClient(i)) {
                    setIndication(INDICATION_GW_RX);
					_w5100_spi_en(false);
					return true;
				}
			}
		#else
			// W5100/ENC module does not have hasClient-method. We can only serve one client at the time.
			EthernetClient newclient = _ethernetServer.available();
			// if a new client connects make sure to dispose any previous existing sockets
			if (newclient) {
				if (client != newclient) {
					client.stop();
					client = newclient;
					debug(PSTR("Eth: connect\n"));
					_w5100_spi_en(false);
					gatewayTransportSend(buildGw(_msg, I_GATEWAY_READY).set("Gateway startup complete."));
					_w5100_spi_en(true);
					if (presentation)
						presentation();
				}
			}
			if (client) {
				if (!client.connected()) {
					debug(PSTR("Eth: disconnect\n"));
					client.stop();
				} else {
					if (_readFromClient()) {
                        setIndication(INDICATION_GW_RX);
						_w5100_spi_en(false);
						return true;
					}
				}
			}
		#endif
	#endif
	_w5100_spi_en(false);
	return false;
}
Beispiel #13
0
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();
  }

}
//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
        _msDisconnecting = millis();
        Serial << _msDisconnecting << F(" disconnecting\n");
        client.stop();
        if (_ledPin >= 0) digitalWrite(_ledPin, LOW);
        _msDisconnected = millis();
        respTime = _msLastPacket - _msPutComplete;
        discTime = _msDisconnected - _msDisconnecting;
        Serial << _msDisconnected << F(" disconnected\n\n");
        GS_STATE = GS_WAIT;
        ret = DISCONNECTED;
        break;
    }
    if (ret != NO_STATUS) lastStatus = ret;
    return ret;
}
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");
      Serial.print(Start);
      Serial.print("=");
      Serial.println(C[Start]);
    #endif
    ByteArray[5] = 2; //Number of bytes after this one.
    MessageLength = 8;
    client.write(ByteArray, MessageLength);
    Writes = 1 + Writes * (Writes < 999);
    FC = MB_FC_NONE;
  } 

  //****************** Write Register ******************
  if(FC == MB_FC_WRITE_REGISTER)
  {
    Start = word(ByteArray[8],ByteArray[9]);
    R[Start] = word(ByteArray[10],ByteArray[11]);
    #ifdef MbDebug
      Serial.print(" MB_FC_WRITE_REGISTER R");
      Serial.print(Start);
      Serial.print("=");
      Serial.println(R[Start]);
    #endif
    ByteArray[5] = 6; //Number of bytes after this one.
    MessageLength = 12;
    client.write(ByteArray, MessageLength);
    Writes = 1 + Writes * (Writes < 999);
    FC = MB_FC_NONE;
  }


  //****************** Write Multiple Coils **********************
  //Function codes 15 & 16 by Martin Pettersson http://siamect.com
  if(FC == MB_FC_WRITE_MULTIPLE_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_WRITE_MULTIPLE_COILS S=");
      Serial.print(Start);
      Serial.print(" L=");
      Serial.println(CoilDataLength);
    #endif
    ByteArray[5] = ByteDataLength + 5; //Number of bytes after this one.
    for(int i = 0; i < ByteDataLength ; i++)
    {
      for(int j = 0; j < 8; j++)
      {
        C[Start + i * 8 + j] = bitRead( ByteArray[13 + i], j);
      }
    }
    MessageLength = 12;
    client.write(ByteArray, MessageLength);
    Writes = 1 + Writes * (Writes < 999);
    FC = MB_FC_NONE;
  }


  //****************** Write Multiple Registers ******************
  //Function codes 15 & 16 by Martin Pettersson http://siamect.com
  if(FC == MB_FC_WRITE_MULTIPLE_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.
    for(int i = 0; i < WordDataLength; i++)
    {
      R[Start + i] =  word(ByteArray[ 13 + i * 2],ByteArray[14 + i * 2]);
    }
    MessageLength = 12;
    client.write(ByteArray, MessageLength);
    Writes = 1 + Writes * (Writes < 999);
    FC = MB_FC_NONE;
  }

  #ifdef MbDebug
    Serial.print("Mb runs: ");
    Serial.print(Runs);
    Serial.print("  reads: ");
    Serial.print(Reads);
    Serial.print("  writes: ");
    Serial.print(Writes);
    Serial.println();
  #endif
}
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';


				Serial.println("");
				Serial.println("=>Parsing the IP address...");
				bFindIP = GetIpAddressFromDataBuffer(gDataBuffer, pos, gIPBuffer, IP_BUFFER_SIZE);
				if(bFindIP)
				{
					Serial.print("=>Success: IP address is: ");
					Serial.println(gIPBuffer);
				}
				else
				{
					Serial.println("=>Error: Fail to get the IP address.");
				}

				// Close the link every time. Otherwise, the connection can be created only on first time.
				// The following request will fail.
				client.stop();
			}
			else
			{
				Serial.println("=>Error: No http body");
			}
		}
	}

	Serial.println("");
	Serial.println("[Finish!]");
	Serial.println("");

	return bFindIP;
}
void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection:
#if defined(WIZ550io_WITH_MACADDRESS)
  if (Ethernet.begin() == 0) {
#else
  if (Ethernet.begin(mac) == 0) {
#endif  
    Serial.println("Failed to configure Ethernet using DHCP");
    // DHCP failed, so use a fixed IP address:
#if defined(WIZ550io_WITH_MACADDRESS)
    Ethernet.begin(ip, dnsip, gw,snip);
#else
    Ethernet.begin(mac, ip, dnsip, gw,snip);
#endif  
  }
}

void loop() {
  // read the analog sensor:
  int sensorReading = analogRead(A0);   
  // convert the data to a String to send it:

  String dataString = "sensor1,";
  dataString += sensorReading;

  // you can append multiple readings to this String if your
  // pachube feed is set up to handle multiple values:
  int otherSensorReading = analogRead(A1);
  dataString += "\nsensor2,";
  dataString += otherSensorReading;

  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }

  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data: 
  if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    sendData(dataString);
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}
Beispiel #18
0
void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        
        if(c == '?'){
          startRequest = true;
          noReq = false;
        }else if(c == ' '){
           startRequest = false;
        }
       
        if(startRequest){
          httpReq += c;
        }
       
        if(light){
          button = "Turn the system off.";
          action = "/?OFF";
          sense();
        }else{
          button = "Arm the system.";
          action = "/?ON";
          motionStart = "";
          measurement = "";
        }

        // 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");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          if(noReq){
            client.println();
            client.println("<!DOCTYPE HTML>");
            client.println("<html>");
            client.println("<head>");
            client.println("<link rel='stylesheet' href='//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css'><script type='text/javascript' src='http://code.jquery.com/jquery-2.1.1.min.js'></script><script type='text/javascript'>$.ajax({url: 'http://107.170.57.28/return.php', type: 'get', success: function (response){$('body').html(response)}});</script></head><body></body>");
            client.println("</head>");
            client.println("</html>");
          }else{
            client.println();
            client.print("{\"sensorLog\": \"");
            client.print(sensorLog);
            client.print(motionStart);
            client.print(measurement);
            client.print("\",\"action\": \"" + action + "\"}"); 
          }
          break;
        }

        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    
    if(httpReq == "?ON"){
       digitalWrite(7, HIGH);
       digitalWrite(3, LOW);
       sensorLog = ("Calibrating sensor <br /> Done <br /> SENSOR ACTIVE <br /> Motion Detected at: ");
       measurement = " sec";
       light = true;
     }else if(httpReq == "?OFF"){
//       digitalWrite(7, LOW);
       sensorLog = ("System turned off");
       light = false;
     }else if(httpReq == "?PLAY"){
       play();
     }
     noReq = true;
     Serial.print("HTTPReq: ");
     Serial.print(httpReq);
     httpReq = "";
    // give the web browser time to receive the data
    delay(1);
    
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}
void loop() {
 
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  int mois = analogRead(1);

  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t) || isnan(h)) {
    Serial.println("Failed to read from DHT");
  } else {
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
  }
 
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new 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");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
   client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
        
          // output the value of the DHT-11
            client.print("<div id='banner'>");
            client.print(h);
            client.print(",");
            client.print(t);
            client.print(",");
            client.print(mois);
           client.print("</div>");
           
                
         
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}
Beispiel #20
0
bool
Twitter::post_status(const char *message)
{
  char *cp;
  int i;

  timestamp = get_time();
  create_nonce();

  compute_authorization(message);

  /* Post message to twitter. */

  EthernetClient http;

  if (!http.connect(ip, port))
    {
      println(PSTR("Could not connect to server"));
      return false;
    }

  http_print(&http, PSTR("POST "));

  if (proxy)
    {
      http_print(&http, PSTR("http://"));
      http_print(&http, server);
    }

  http_print(&http, uri);
  http_println(&http, PSTR(" HTTP/1.1"));

  http_print(&http, PSTR("Host: "));
  http_print(&http, server);
  http_newline(&http);

  http_println(&http,
               PSTR("Content-Type: application/x-www-form-urlencoded"));
  http_println(&http, PSTR("Connection: close"));

  /* Authorization header. */
  http_print(&http, PSTR("Authorization: OAuth oauth_consumer_key=\""));

  url_encode_pgm(buffer, consumer_key);
  http.write(buffer);

  http_print(&http, PSTR("\",oauth_signature_method=\"HMAC-SHA1"));
  http_print(&http, PSTR("\",oauth_timestamp=\""));

  sprintf(buffer, "%ld", timestamp);
  http.write(buffer);

  http_print(&http, PSTR("\",oauth_nonce=\""));

  hex_encode(buffer, nonce, sizeof(nonce));
  http.write(buffer);

  http_print(&http, PSTR("\",oauth_version=\"1.0\",oauth_token=\""));

  if (access_token_pgm)
    url_encode_pgm(buffer, access_token.pgm);
  else
    url_encode_eeprom(buffer, access_token.eeprom);

  http.write(buffer);

  http_print(&http, PSTR("\",oauth_signature=\""));

  cp = base64_encode(buffer, signature, HASH_LENGTH);
  url_encode(cp + 1, buffer);

  http.write(cp + 1);

  http_println(&http, PSTR("\""));

  /* Encode content. */
  cp = url_encode(buffer, "status");
  *cp++ = '=';
  cp = url_encode(cp, message);

  int content_length = cp - buffer;
  sprintf(cp + 1, "%d", content_length);

  http_print(&http, PSTR("Content-Length: "));
  http.write(cp + 1);
  http_newline(&http);

  /* Header-body separator. */
  http_newline(&http);

  /* And finally content. */
  http.write(buffer);

  /* Read response status line. */
  if (!read_line(&http, buffer, buffer_len) || buffer[0] == '\0')
    {
      http.stop();
      return false;
    }

  int response_code;

  /* HTTP/1.1 200 Success */
  for (i = 0; buffer[i] && buffer[i] != ' '; i++)
    ;
  if (buffer[i])
    response_code = atoi(buffer + i + 1);
  else
    response_code = 0;

  bool success = (200 <= response_code && response_code < 300);

  if (!success)
    Serial.println(buffer);

  /* Skip header. */
  while (true)
    {
      if (!read_line(&http, buffer, buffer_len))
        {
          http.stop();
          return false;
        }

      if (buffer[0] == '\0')
        break;

      /* Update our system basetime from the response `Date'
         header. */
      process_date_header(buffer);
    }

  /* Handle content. */
  while (http.connected())
    {
      while (http.available() > 0)
        {
          uint8_t byte = http.read();

          if (!success)
            Serial.write(byte);
        }
      delay(100);
    }

  http.stop();

  if (!success)
    println(PSTR(""));

  return success;
}
Beispiel #21
0
WebClient* NetworkInterfaceWIZ5x00::processPacket () {
	WebClient *ret = NULL;

	EthernetClient client = server.available ();
	if (client) {
		DPRINT (F("New client from "));
		DPRINTLN (client.remoteIP ());

		// An http request ends with a blank line
		boolean currentLineIsBlank = true;
		ethernetBufferSize = 0;
		boolean copy = true;
		while (client.connected ()) {
			if (client.available ()) {
				char c = client.read ();
				if (copy) {
					if (ethernetBufferSize < sizeof (ethernetBuffer)) {
						ethernetBuffer[ethernetBufferSize++] = c;
					} else {
						DPRINTLN (F("Ethernet buffer overflow"));
						break;
					}
				}

				// If you've gotten to the end of the line (received a newline
				// character) and the line is blank, the http request has ended,
				if (c == '\n' && currentLineIsBlank) {
					webClient.begin (client, (char *) ethernetBuffer);
					ret = &webClient;
					break;
				}

				if (c == '\n') {
					// See if we got the URL line
					if (strncmp_P ((char *) ethernetBuffer, PSTR ("GET "), 4) == 0) {
						// Yes, ignore the rest
						ethernetBuffer[ethernetBufferSize - 1] = '\0';
						copy = false;
					} else {
						// No, start over
						ethernetBufferSize = 0;
					}

					// you're starting a new line
					currentLineIsBlank = true;
				} else if (c != '\r') {
					// you've gotten a character on the current line
					currentLineIsBlank = false;
				}
			}
		}

		// give the web browser time to receive the data
		//delay (500);

		// If we are not returning a client, close the connection
		if (!ret) {
			client.stop ();
			DPRINTLN (F("Client disconnected"));
		}
	}

	return ret;
}
Beispiel #22
0
/**
 *	Process HTTP request
 *
 *	@return EthernetClient client
 **/
EthernetClient uHTTP::available(){
    EthernetClient client;

    memset(__uri, 0, sizeof(__uri));
    memset(__query, 0, sizeof(__query));
    memset(__body, 0, sizeof(__body));
    memset(&__head, 0, sizeof(__head));

    if(client = EthernetServer::available()){
        uint8_t cursor = 0, cr = 0;
        char buffer[uHTTP_BUFFER_SIZE] = {0};
        bool sub = false;

        enum state_t {METHOD, URI, QUERY, PROTO, KEY, VALUE, BODY};
        state_t state = METHOD;

        enum header_t {START, AUTHORIZATION, CONTENT_TYPE, CONTENT_LENGTH, ORIGIN};
        header_t header = START;

		while(client.connected() && client.available()){
      		char c = client.read();

      		(c == '\r' || c == '\n') ? cr++ : cr = 0;
      		
      		switch(state){
      			case METHOD:
            		if(c == ' '){
              			if(strncmp_P(buffer, PSTR("OP"), 2) == 0) __method = uHTTP_METHOD_OPTIONS;
              			else if(strncmp_P(buffer, PSTR("HE"), 2) == 0) __method = uHTTP_METHOD_HEAD;
              			else if(strncmp_P(buffer, PSTR("PO"), 2) == 0) __method = uHTTP_METHOD_POST;
              			else if(strncmp_P(buffer, PSTR("PU"), 2) == 0) __method = uHTTP_METHOD_PUT;
              			else if(strncmp_P(buffer, PSTR("PA"), 2) == 0) __method = uHTTP_METHOD_PATCH;
              			else if(strncmp_P(buffer, PSTR("DE"), 2) == 0) __method = uHTTP_METHOD_DELETE;
              			else if(strncmp_P(buffer, PSTR("TR"), 2) == 0) __method = uHTTP_METHOD_TRACE;
              			else if(strncmp_P(buffer, PSTR("CO"), 2) == 0) __method = uHTTP_METHOD_CONNECT;
              			else __method = uHTTP_METHOD_GET;
              			state = URI; 
              			cursor = 0; 
            		}else if(cursor < uHTTP_METHOD_SIZE - 1){
            			buffer[cursor++] = c; 
            			buffer[cursor] = '\0'; 
            		}
            		break;
            	case URI:
            		if(c == ' '){
            			state = PROTO;
            			cursor = 0;
            		}else if(c == '?'){
            			state = QUERY;
            			cursor = 0;
            		}else if(cursor < uHTTP_URI_SIZE - 1){
            			__uri[cursor++] = c;
            			__uri[cursor] = '\0';
            		}
            		break;
            	case QUERY:
            		if(c == ' '){
            			state = PROTO;
            			cursor = 0;
            		}else if(cursor < uHTTP_QUERY_SIZE - 1){
            			__query[cursor++] = c;
            			__query[cursor] = '\0';
            		}
            		break;
            	case PROTO:
            		if(cr == 2){ state = KEY; cursor = 0; }
            		break;
            	case KEY:
            		if (cr == 4){ state = BODY; cursor = 0; }
            		else if(c == ' '){ state = VALUE; cursor = 0; }
            		else if(c != ':' && cursor < uHTTP_BUFFER_SIZE){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
            		break;
            	case VALUE:
            		if(cr == 2){
            			switch(header){
                			case AUTHORIZATION:
                  				strncpy(__head.auth, buffer, uHTTP_AUTH_SIZE);
                  				break;
                			case CONTENT_TYPE:
                				strncpy(__head.type, buffer, uHTTP_TYPE_SIZE);
                  				break;
                			case ORIGIN:
                  				strncpy(__head.orig, buffer, uHTTP_ORIG_SIZE);
                  				break;
                  			case CONTENT_LENGTH:
                  				__head.length = atoi(buffer);
                  				break;
                  			break;
              			}
            			state = KEY; header = START; cursor = 0; sub = false;
            		}else if(c != '\r' && c!= '\n'){
            			if(header == START){
                			if(strncmp_P(buffer, PSTR("Auth"), 4) == 0) header = AUTHORIZATION;
                			else if(strncmp_P(buffer, PSTR("Content-T"), 9) == 0) header = CONTENT_TYPE;
                			else if(strncmp_P(buffer, PSTR("Content-L"), 9) == 0) header = CONTENT_LENGTH;
              			}

              			// Fill buffer
              			if(cursor < uHTTP_BUFFER_SIZE - 1){
                			switch(header){
                  				case AUTHORIZATION:
                    				if(sub){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
                    				else if(c == ' ') sub = true;
                    				break;
                  				case CONTENT_TYPE:
                  				case CONTENT_LENGTH:
                    				buffer[cursor++] = c; buffer[cursor] = '\0';
                    				break;
                			}
              			}
            		}
            		break;
            	case BODY:
            		if(cr == 2 || __head.length == 0) client.flush();
            		else if(cursor < uHTTP_BODY_SIZE - 1){ __body[cursor++] = c; __body[cursor] = '\0'; }
            		break;
      		}
      	}
	}
	return client;
}
void pachube_in_out(){

	if (minute() < last_connect) last_connect = minute();

	if (request_pause){
		if ((minute() - last_connect) > interval){
			ready_to_update = true;
			reading_pachube = false;
			request_pause = false;
			found_status_200 = false;
			found_session_id = false;
			found_CSV = false;

			Serial.print("Ready to connect: ");
			Serial.println(minute());
			Serial.print("interval: ");
			Serial.println(interval);
		}
	}

	if (ready_to_update){
		Serial.println("Connecting...");
		if (localClient.connect(remoteServer, 80) > 0) {

			// here we assign comma-separated values to 'data', which will update Pachube datastreams
			// we use all the analog-in values, but could of course use anything else millis(), digital
			// inputs, etc. . i also like to keep track of successful and failed connection
			// attempts, sometimes useful for determining whether there are major problems.

			sprintf(pachube_data,"%d,%d,%d-%d-%d %d:%d:%d",analogRead(0),analogRead(1), year(),month(),day(),hour(),minute(),second());
			content_length = strlen(pachube_data);

			Serial.print("GET request to retrieve: ");
			Serial.println(pachube_data);

			localClient.print("GET /api/");
			localClient.print(REMOTE_FEED_ID);
			localClient.print(".csv HTTP/1.1\nHost: pachube.com\nX-PachubeApiKey: ");
			localClient.print(PACHUBE_API_KEY);
			localClient.print("\nUser-Agent: Arduino (Pachube In Out v1.1)");
			localClient.println("\n");

			//Serial.println("finished GET now PUT, to update");

			localClient.print("PUT /api/");
			localClient.print(SHARE_FEED_ID);
			localClient.print(".csv HTTP/1.1\nHost: pachube.com\nX-PachubeApiKey: ");
			localClient.print(PACHUBE_API_KEY);

			localClient.print("\nUser-Agent: Arduino (Pachube In Out v1.1)");
			localClient.print("\nContent-Type: text/csv\nContent-Length: ");
			localClient.print(content_length);
			localClient.print("\nConnection: close\n\n");
			localClient.print(pachube_data);

			localClient.print("\n");

			ready_to_update = false;
			reading_pachube = true;
			request_pause = false;
			interval = UPDATE_INTERVAL;

			// Serial.print("finished PUT: ");
			// Serial.println(millis());

		} 
		else {
			Serial.print("connection failed!");
			Serial.print(++failures);
			found_status_200 = false;
			found_session_id = false;
			found_CSV = false;
			ready_to_update = false;
			reading_pachube = false;
			request_pause = true;
			last_connect = minute();
			interval = RESET_INTERVAL;
			setupEthernet();
		}
	}

	while (reading_pachube){
		while (localClient.available()) {
			checkForResponse();
		} 

		if (!localClient.connected()) {
			disconnect_pachube();
		}
	} 
}
Beispiel #24
0
unsigned char EthernetSup::available() 
{
  unsigned char ret = 0;
  
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
  {
    boolean currentLineIsBlank = true;
    boolean isReferer = false;
    while (client.connected()) 
    {
      if (client.available()) 
      {
        char c = client.read();

        if (!isReferer)
        {
          findButtonId(client, c);
          findDimmerValue(client, c);
          isReferer = checkReferer(client, c);
        }

        if (c == '\n' && currentLineIsBlank) 
        {
          // send a standard http response header
          printP(client, http200);
          printP(client, contenttype);
          printP(client, connkeep);  
          printP(client, doctype);

          // Verificando o tipo de botao
          if (buttonIdx != -1)
          {
            if (buttonType[buttonIdx] == ONOFF_BUTTON)
            {
              buttonState[buttonIdx] = (buttonState[buttonIdx] ? 0 : 1);
            }
            else if (buttonType[buttonIdx] == DIMMER_BUTTON)
            {
              if (dimmerDirection[buttonIdx] == 1)
              {
                if (dimmerValue[buttonIdx] + dimmerStep[buttonIdx] < 255)
                  dimmerValue[buttonIdx] += dimmerStep[buttonIdx];
                else
                  dimmerValue[buttonIdx] = 255;
              }
              else if (dimmerDirection[buttonIdx] == 2)
              {
                if (dimmerValue[buttonIdx] - dimmerStep[buttonIdx] > 0)
                  dimmerValue[buttonIdx] -= dimmerStep[buttonIdx];
                else
                  dimmerValue[buttonIdx] = 0;
              }
            }
          }
          
          printP(client, head_ini);
          printP(client, stylesheet);
          printP(client, head_fim);
          printP(client, div_ini);
          
          for (int i = 0; i < MAX_BUTTONS; i++)
          {
            if (buttonType[i] != -1)
            {
              if (buttonType[i] == DIMMER_BUTTON)
              {
                printP(client, dimmer_ini1);
                client.print(buttonText[i]);

                // converting to percent
                int val1 = map(dimmerValue[i], 0, 255, 0, 100);
                client.print(val1, DEC);
                client.print("%");

                printP(client, dimmer_ini2);

                // link do dimmer UP
                printP(client, btnid);
                client.print(buttonId[i], DEC);
                printP(client, dimmerdown);
                printP(client, dimmer_mid11); 
                printP(client, colorgreen);
                printP(client, dimmer_mid12);
                printP(client, dimmer_space);
                printP(client, dimmer_space);
                client.print("-");
                printP(client, dimmer_space);
                printP(client, dimmer_space);
                printP(client, dimmer_mid2); 

                // link do dimmer DOWN
                printP(client, btnid);
                client.print(buttonId[i], DEC);
                printP(client, dimmerup);
                printP(client, dimmer_mid21);
                printP(client, colorgreen);
                printP(client, dimmer_mid22);
                printP(client, dimmer_space);
                printP(client, dimmer_space);
                client.print("+");
                printP(client, dimmer_space);
                printP(client, dimmer_space);
                printP(client, dimmer_fim); 
              }
              else
              {
                printP(client, button_ini);

                // link do botao
                printP(client, btnid);
                client.print(buttonId[i], DEC);
                printP(client, button_mid1);
                
                // cor do botao
                if (buttonState[i] == 1)
                {
                  printP(client, colorred);
                }
                else
                {
                  printP(client, colorblue);
                }
                printP(client, button_mid2);

                // texto do botao
                client.print(buttonText[i]);
                printP(client, button_fim);  
              }
            }
          }
          printP(client, div_fim);
          
          ret = 1;
          break;
        }

      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  }
  
  return ret;
}
Beispiel #25
0
int http_client::request(byte server[], unsigned short port, const char* url, const char* method, const char* data)
{
    // clear out any old response that may be hanging around
    if (response != NULL)
    {
        free(response);
        response = NULL;
        content_length = 0;
    }

    // validate/parse the url
    size_t len = strlen(url);
    char* host = (char*) malloc(len); // allocate string for host
    if (host == NULL)
        return OUT_OF_MEMORY;
    char* path = (char*) malloc(len); // allocate string for path
    if (path == NULL)
    {
        free(host);
        return OUT_OF_MEMORY;
    }
    int ret = parse_url(url, host, path);
    if (ret != SUCCESS)
    {
        free(host);
        free(path);
        return ret;
    }
    
    // make the connection
        EthernetClient client;
    if (!client.connect(server, port))
    {
        free(host);
        free(path);
        return CONNECTION_FAILED;
    }
    
    // default method is GET
    if (method == NULL)
        method = "GET";
    
    // send up our request
    char header_buffer[1024];
    sprintf(header_buffer, "%s %s HTTP/1.0", method, path); // don't even think about 1.1
    client.println(header_buffer);
    Serial.println(header_buffer);
    sprintf(header_buffer, "Host: %s", host);
    client.println(header_buffer);
    Serial.println(header_buffer);
    sprintf(header_buffer, "User-Agent: %s", USER_AGENT);
    client.println(header_buffer);
    Serial.println(header_buffer);
    if (data != NULL)
    {
        sprintf(header_buffer, "Content-Length: %d", strlen(data));
        client.println(header_buffer);
        Serial.println(header_buffer);
    }

    // send up any additional headers

    // end of headers
    client.println();

    // send up data, if we have any
    if (data != NULL)
        client.print(data);
    
    // now get the response
    char* p = header_buffer;
    bool in_headers = true;
    content_length = 0;
    while (client.available())
    {
        char c = client.read();
        if (in_headers)
        {
            // header end in CRLF, so we'll ignore CR and process the line on LF
            if (c == '\r')
            {
                // ignore and wait for linefeed
            }
            else if (c == '\n')
            {
                // terminate the string and see if we have a header or the body is starting
                *p = 0;
                if (strlen(header_buffer) == 0)
                {
                    // if this is an empty line, we've reached the end of the headers
                    in_headers = false;
                    
                    // set our pointer to the response buffer, which should have been allocated already
                    p = response;
                }
                else
                {
                    // this is a header, certain ones are interesting to us
                    Serial.println(header_buffer);

                    // convert header name to lower case for comparison
                    char* ph = header_buffer;
                    while (*ph && *ph != ':')
                        *ph = tolower(*ph);
                    if (strstr(header_buffer, "content-length:") != NULL)
                    {
                        content_length = atoi(ph + 2);
                        response = (char*) malloc(content_length);
                    }
                }

                // reset the pointer for the next header
                p = header_buffer;
            }
            else
            {
                // otherwise, this is just part of a header string, append it
                *p++ = c;
            }
        }
        else
        {
            // everything else gets appended to the response body
            *p++ = c;
        }
    }

    // we're done, close the connection
    client.stop();
    
    // clean up
    free(host);
    free(path);

    return SUCCESS;
}
Beispiel #26
0
void ModbusTCP::run(void){

  int16_t i, iStart, iQty;
  int16_t iTXLen = 0;       // response packet length
  uint8_t *ptr, iFC = MB_FC_NONE, iEC = MB_EC_NONE;
  //  
  // Initialize and check for a request from a MODBUS master
  //
#ifdef MB_ETHERNET
  EthernetClient clientrequest = mb_server.available();
#endif
#ifdef MB_CC3000
  Adafruit_CC3000_ClientRef clientrequest = mb_server.available();
#endif
#ifdef ARDUINO_AMEBA
  if (!clientrequest.connected()) {
    clientrequest = mb_server.available();
  }
#endif

#ifdef MODBUSTCP_PCN001_USE_WIFI
  if(clientrequest.available()) {
    int len = clientrequest.read(mb_adu, sizeof(mb_adu));
    if (len > 0) {
      iFC = mb_adu[MB_TCP_FUNC];
    }
  } else {
    delay(10);
  }

#else
  if(clientrequest.available()) {
    //
    // Retrieve request
    //
    for (i = 0 ; clientrequest.available() ; i++) 
      mb_adu[i] = clientrequest.read();
#ifdef MB_DEBUG   
    printMB("RX: ", word(mb_adu[MB_TCP_LEN],mb_adu[MB_TCP_LEN+1])+6);  
#endif    
    //
    // Unpack the function code
    //
    iFC = mb_adu[MB_TCP_FUNC];
  }
#endif // end of #ifdef ARDUINO_AMEBA
  //
  // Handle request
  //
  switch(iFC) {
  case MB_FC_NONE:
    break;
  case MB_FC_READ_REGISTERS: 
    //
    // 03 (0x03) Read Holding Registers
    //
    // modpoll -m tcp -t 4:float -r 40001 -c 1 -1 192.168.x.x
    //
    //     [TransID] [ProtID-] [Length-] [Un] [FC] [Start--] [Qty----] 
    // RX: 0x00 0x01 0x00 0x00 0x00 0x06 0x01 0x03 0x9C 0x40 0x00 0x02 
    //
    //     [TransID] [ProtID-] [Length-] [Un] [FC] [Bc] [float------------] 
    // TX: 0x00 0x01 0x00 0x00 0x00 0x07 0x01 0x03 0x04 0x20 0x00 0x47 0xF1
    //
    // 123456.0 = 0x00 0x20 0xF1 0x47 (IEEE 754)
    //
    // Unpack the start and length
    //
    ptr = mb_adu + MB_TCP_DATA;
    iStart = word(*ptr++, *ptr++) - 40000;
    iQty = 2*word(*ptr++, *ptr);
    //
    // check for valid register addresses     
    //
    if (iStart < 0 || (iStart + iQty/2 - 1) > MB_REGISTERS_MAX) {
      iEC = MB_EC_ILLEGAL_DATA_ADDRESS;
      break;
    }
    //
    // Write data length
    //
    ptr = mb_adu + MB_TCP_DATA;
    *ptr++ = iQty;
    //
    // Write data
    //
    for (i = 0 ; i < iQty/2 ; i++) {
      *ptr++ = highByte(mb_reg[iStart + i]);
      *ptr++ =  lowByte(mb_reg[iStart + i]);
    }
    iTXLen = iQty + 9;
    break;

  case MB_FC_WRITE_REGISTER:
    //
    // 06 (0x06) Write register 
    //
    ptr = mb_adu + MB_TCP_DATA;   
    iStart = word(*ptr++, *ptr++) - 40000;
    //
    // check for valid register addresses     
    //   
    if (iStart < 0 || (iStart - 1) > MB_REGISTERS_MAX) {
      iEC = MB_EC_ILLEGAL_DATA_ADDRESS;
      break;
    }      
    // Unpack and store data
    //
    mb_reg[iStart] = word(*ptr++, *ptr);
    //
    // Build a response 
    //
    iTXLen = 12;             
    break;

  case MB_FC_WRITE_MULTIPLE_REGISTERS: 
    //
    // 16 (0x10) Write Multiple registers
    //
    // modpoll -m tcp -t 4:float -r 40001 -c 1 -1 192.168.x.x 123456.0
    //
    //     [TransID] [ProtID-] [Length-] [Un] [FC] [Start--] [Qty----] [Bc] [float------------] 
    // RX: 0x00 0x01 0x00 0x00 0x00 0x0B 0x01 0x10 0x9C 0x40 0x00 0x02 0x04 0x20 0x00 0x47 0xF1
    //
    // 123456.0 = 0x00 0x20 0xF1 0x47 (IEEE 754)
    //
    // Unpack the start and length
    //
    ptr = mb_adu + MB_TCP_DATA;   
    iStart = word(*ptr++, *ptr++) - 40000;
    iQty = 2*word(*ptr++, *ptr);      
    //
    // check for valid register addresses     
    //   
    if (iStart < 0 || (iStart + iQty/2 - 1) > MB_REGISTERS_MAX) {
      iEC = MB_EC_ILLEGAL_DATA_ADDRESS;
      break;
    }
    //
    // Unpack and store data
    //
    ptr = mb_adu + MB_TCP_DATA+5;
    // todo: check for valid length
    for (i = 0 ; i < iQty/2 ; i++) {
      mb_reg[iStart + i] = word(*ptr++, *ptr++);
    }
    //
    // Build a response 
    //
    iTXLen = 12;
    break;

  default:
    iEC = MB_EC_ILLEGAL_FUNCTION;
    break;    
  }
  //
  // Build exception response if necessary because we were too
  // lazy to do it earlier. Other responses should already be
  // built.
  //
  if (iEC) {
    ptr = mb_adu + MB_TCP_FUNC;
    *ptr = *ptr++ | 0x80;        // flag the function code
    *ptr = iEC;                  // write the exception code
    iTXLen = 9;
  }
  //
  // If there's a response, transmit it
  //
  if (iFC) {
    ptr = mb_adu + MB_TCP_LEN;    // write the header length
    *ptr++ = 0x00;
    *ptr = iTXLen - MB_TCP_UID;  
    clientrequest.write(mb_adu, iTXLen); // send it        
#ifdef MB_DEBUG   
    printMB("TX: ", word(mb_adu[MB_TCP_LEN], mb_adu[MB_TCP_LEN+1]) + MB_TCP_UID);  
#endif                                                
  }
}
void runExternalCommandsPersistent(EthernetServer* _server, systemState* _state) 
{
	// local variables
	int i, buffer_ptr;
	int room, radiatorState, automaticMode;
	float temperature;
	int commandError = 0;
	
	
	EthernetClient client = _server->available(); // is non-blocking
	if(client.available() > 2)
	{
		#ifdef DEBUG
		Serial.println("Connection established");
		Serial.print("Available: ");
		Serial.println(client.available());
		#endif
		
		char buffer[32];
		
		// read command field
		if( readParam(buffer, 3, client) < 0 ) {commandError = 1; goto errorHandler;}
		
		// switch case on commands
		if(strcmp(buffer, "STM") == 0) // set temperature
		{
			#ifdef DEBUG
			Serial.println("Set temperature command received");
			#endif
			
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);
			
			// read second param: temperature (format xx.y)
			if( readParam(buffer, 4, client) < 0 ) {commandError = 1; goto errorHandler;}
			temperature = atof(buffer);
			
			_state->desiredTemp[room] = temperature;
			
			client.write((unsigned char*)"STM", 3);
			client.write((unsigned char*)"OOK", 3);
		}
		else if(strcmp(buffer, "RTM") == 0) // read temperature
		{
			#ifdef DEBUG
			Serial.println("Read temperature command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			
			room = atoi(buffer);
			
			temperature = _state->actualTemp[room];
			//buffer_ptr = sprintf(buffer, "%4.1f", temperature);
			ttoa(buffer, temperature);
			
			client.write((unsigned char*)"RTM", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 4);
		}
		else if(strcmp(buffer, "SRD") == 0) // set radiator
		{
			#ifdef DEBUG
			Serial.println("Set radiator command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);
			
			// read second param: radiator state (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			radiatorState = atoi(buffer);
			
			_state->radiatorState[room] = radiatorState;
			digitalWrite(radiatorPinByRoom(room), (radiatorState == 1) ? LOW : HIGH);
			
			// set zone valve
			int someoneIsOn = 0;
			for(room = 0; room < 6; room++) 
			{
				if(_state->radiatorState[room] == ON) someoneIsOn = 1;
			}
			digitalWrite(ZONE_VALVE_NO1, someoneIsOn ? LOW : HIGH);
			
			client.write((unsigned char*)"SRD", 3);
			client.write((unsigned char*)"OOK", 3);
		}
		else if(strcmp(buffer, "RRD") == 0) // read radiator
		{
			#ifdef DEBUG
			Serial.println("Read radiator command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);

			radiatorState = _state->radiatorState[room];
			sprintf(buffer, "%d", radiatorState);
			
			client.write((unsigned char*)"RRD", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 1);
		}
		else if(strcmp(buffer, "SAM") == 0) // set automatic mode
		{
			#ifdef DEBUG
			Serial.println("Set automatic mode command received");
			#endif
			// read second param: radiator state (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			automaticMode = atoi(buffer);
			
			_state->automaticMode = automaticMode;
			
			client.write((unsigned char*)"SAM", 3);
			client.write((unsigned char*)"OOK", 3);
		}
		else if(strcmp(buffer, "RAM") == 0) // read automatic mode
		{
			#ifdef DEBUG
			Serial.println("Read automatic mode command received");
			#endif
			automaticMode = _state->automaticMode;
			
			sprintf(buffer, "%d", automaticMode);
			
			client.write((unsigned char*)"RAM", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 1);
		}
		else if(strcmp(buffer, "RDT") == 0) // read desired temperature
		{
			#ifdef DEBUG
			Serial.println("Read desired temperature command received");
			#endif
			// read fisrt param: room number (one digit)
			if( readParam(buffer, 1, client) < 0 ) {commandError = 1; goto errorHandler;}
			room = atoi(buffer);
			
			temperature = _state->desiredTemp[room];
			//buffer_ptr = sprintf(buffer, "%4.1f", temperature);
			ttoa(buffer, temperature);
			
			client.write((unsigned char*)"RDT", 3);
			client.write((unsigned char*)"OOK", 3);
			client.write((unsigned char*)buffer, 4);
		}
		else if(strcmp(buffer, "CLS") == 0) // Close connection
		{
			#ifdef DEBUG
			Serial.println("Close connection command received");
			#endif
			
			client.write((unsigned char*)"CLS", 3);
			client.write((unsigned char*)"OOK", 3);
			
			client.flush(); // NEW to verify ---> it seems not working
			delay(2000);
			while(client.connected())
			{
				client.stop();
				delay(2000);
			}
		}
		else
		{
			#ifdef DEBUG
			Serial.print("Invalid command received: ");
			Serial.print(buffer[0]);
			Serial.print(buffer[1]);
			Serial.print(buffer[2]);
			Serial.println();
			#endif
			client.write((unsigned char*)"ERR", 3);
			client.write((unsigned char*)"INV", 3);
		}
		
		// =============================================
		errorHandler:
		if(commandError)
		{
			
			#ifdef DEBUG
			Serial.print("Invalid command received: ");
			Serial.print(buffer[0]);
			Serial.print(buffer[1]);
			Serial.print(buffer[2]);
			Serial.println();
			#endif
			client.write((unsigned char*)"ERR", 3);
			client.write((unsigned char*)"GEN", 3);
		}
		// =============================================
	}
	
}
Beispiel #28
0
// ---------------------------------------------------------------------------
// --- Main loop update ------------------------------------------------------
// ---------------------------------------------------------------------------
void PLabFileServer::update() {
	// Main loop.
	// Check if we have any new connections
	EthernetClient client = available();
	if (client) {
		if (out) {
			out->println();
			// Buffer is initially considered empty
			strcpy_P(bigBuf, plabRequest);
			out->println(bigBuf);
			out->println();
		}

		if (filter) {
			filter->start();
		}

		// We should now start parsing our request
		RequestState_t state = REQ_START;
		RequestMethod_t method = METH_NOT_SUPPORTED;
		int indexTracker = 0;
		// While we still have an open connection to the client
		while (client.connected()) {
			if (client.available()) {
				char c = client.read();
				if (out) {
					out->write(c);
				}
				state = reqStateTransition(state, c, indexTracker, method);
			}
			// By default we assume we have answered.
			bool answered = true;
			// Configuring answer, if we have any yet.
			switch (state) {
			case REQ_MESSAGE_BODY:
				if (out) {
					out->println();
					// Safe to overwrite buffer: it should not contain anything
					strcpy_P(bigBuf, plabResponse);
					out->println(bigBuf);
					out->println();
				}
				// GET and HEAD discard request body in this server
				// Currently this (HEAD and GET) covers every possibility.
				if (method == METH_HEAD || method == METH_GET) {
					if (userControlledResponse) {
						if (filter)
							filter->writeResponse(client);
					}
					else {
						// The exact same header
						strcpy_P(bigBuf, plabHeaderHttp);
						if (filter)
							filter->filterResponseHeader(bigBuf, client);
						cPrint(bigBuf, client);
						strcpy_P(bigBuf, plab200OK);
						if (filter)
							filter->filterResponseHeader(bigBuf, client);
						cPrintln(bigBuf, client);
						if (internalMIMEIndex >= 0) {
							strcpy_P(bigBuf, plabContentType);
							if (filter)
								filter->filterResponseHeader(bigBuf, client);
							cPrint(bigBuf, client);
							strcpy_P(bigBuf, (char*)pgm_read_word(&(plabMIMETypeTable[internalMIMEIndex])));
							if (filter)
								filter->filterResponseHeader(bigBuf, client);
							cPrintln(bigBuf, client);
						}
						strcpy_P(bigBuf, plabConnectionClose);
						if (filter)
							filter->filterResponseHeader(bigBuf, client);
						cPrintln(bigBuf, client);
						// TODO Additional user defined header fields
						cPrintln("", client);	// HEADER stop
						if (method == METH_GET) {
							// Rediricting file location
							if (filter)
								filter->redirectReplyFile(sdFile);
#ifdef PLAB_DEBUG
							if (out)
								out->println("GET response");
#endif // PLAB_DEBUG
							// ONLY get has message body
							// TODO User defined body write
							if (sdFile) {
								while (sdFile.available()) {
									char c = sdFile.read();
									if (filter) {
										if (filter->filterResponse(c, client))
											cWrite(c, client);
									}
									else
										cWrite(c, client);
								}
								sdFile.close();
							}
#ifdef PLAB_DEBUG
							else if (out)
								out->println("File not open!");
#endif // PLAB_DEBUG
						}
					}
				}
				break;

				// TODO Better error treatment
			case BAD_REQ_400:
				printDefaultError(400, client);
				break;
			case NOT_FOUND_404:
				printDefaultError(404, client);
				break;
			case METHOD_NOT_ALLOWED_405:
				printDefaultError(405, client);
				break;
			case REQUEST_URI_TOO_LONG_414:
				printDefaultError(414, client);
				break;
			case INTERNAL_SERVER_ERROR_500:
				printDefaultError(500, client);
				break;
			case NOT_IMPLEMENTED_501:
				printDefaultError(501, client);
				break;
			case HTTP_VERSION_NOT_SUPPORTED_505:
				printDefaultError(505, client);
				break;

			default:
				// No other state (as of yet) produces an answer
				answered = false;
			}

			// Clean, if need be
			if (answered) {
				if (sdFile) {
					sdFile.close();
				}

				// Client should have some time to process answer
				delay(1);

				client.stop();
				client.flush();
			}
		}
		if (filter)
			filter->end();
	}
}
Beispiel #29
0
void loop()
{
  switch (rs485State)
  {
    case Rs485Loopback:
      serialReadString();
      serialWriteString();
      break;

    case Rs485RxTest:
      if (TIMER_COUNT_1S < timerCounter)
      {
        Serial.write("~!EloHello$75~");
        timerCounter = 0;
      }
      break;

    case Rs485TxTest:
      serialReadString();
      break;

    default:
      break;
  }

  // Create a client connection
  EthernetClient client = server.available();
  if (client)
  {
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
         }

         //if HTTP request has ended
         if (c == '\n')
         {
           //controls the Arduino if you press the buttons
           if (readString.indexOf("?button485Loopback") >0)        changeRs485Mode(Rs485Loopback);
           else if (readString.indexOf("?button485RxTest") >0)     changeRs485Mode(Rs485RxTest);
           else if (readString.indexOf("?button485TxTest") >0)     changeRs485Mode(Rs485TxTest);

           //clearing string for next read
           readString="";

           client.println("HTTP/1.1 200 OK"); //send new page
           client.println("Content-Type: text/html");
           client.println("Refresh: 5");  // refresh the page automatically every 5 sec
           client.println();
           client.println("<HTML>");
           client.println("<HEAD>");
           refreshSection(client);
           client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
           client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
           client.println("<link rel='stylesheet' type='text/css' href='http://randomnerdtutorials.com/ethernetcss.css' />");
           client.println("<TITLE>RS-485 - RET tester</TITLE>");
           client.println("</HEAD>");
           client.println("<BODY>");
           client.println("<H1>RS-485 - RET tester</H1>");
           client.println("<hr />");
           client.println("<br />");
           client.println("<H2>RS-485 mode</H2>");
           client.println("<a href=\"/?button485Loopback\"\">1. RS-485 Loopback</a>");
           client.println("<a href=\"/?button485RxTest\"\">2. RS-485 RX Test</a>");
           client.println("<a href=\"/?button485TxTest\"\">3. RS-485 TX Test</a>");
           client.println("<br />");
           client.println("<H2>RET Status</H2>");
           // DC Voltage section
           // RS485 section
           client.print("<a style=\"background-color:#4DB257\">RS-485 mode: ");  //
           client.print(rs485State);
           client.println("</a> <br />");
           client.println("<br />");
           // Last 10 received messages section
           client.print("<H2>Last ");
           client.print(MSG_BUFFER_SIZE);
           client.println(" received messages</H2>");

           char counter = msgBuffer.counter;
           for(char i = 0; i < MSG_BUFFER_SIZE; ++i)
           {
             client.print(msgBuffer.readString[counter]);
             client.println("<br />");
             if (--counter < 0) counter = MSG_BUFFER_SIZE-1;
           }

           client.println("<br />");
           client.println("</BODY>");
           client.println("</HTML>");

           delay(1);
           //stopping client
           client.stop();
         }
       }
    }
  }
}
// The loop function is called in an endless loop
void loop() {



	// if there's incoming data from the net connection.
	// send it out the serial port. This is for debugging
	// purposes only:
	if (client.available()) {
		char c = client.read();
		Serial.print(c);
	}

	// if there's no net connection, but there was one last time
	// through the loop, then stop the client:
	if (!client.connected() && wasConnected) {
		Serial.println();
		Serial.println("disconnecting.");
		client.stop();
		wasConnected = false;
	}

	if (PowerSerial::solar.count < 0) {
		int waitTime = millis() - lastupdate;
		if (waitTime > 30000) {
			String jsonResult = PowerSerial::solar.jsonResult;
			Serial.println("transmit Every 30 seconds");
			lastupdate = millis();

			lmillis = tmillis; //timing to determine amount of time since last call
			tmillis = millis();

			delay(1000);
			if (!client.connected()) {
				Serial.println(jsonResult);
				// if there's a successful connection:
				Serial.println("!client.connected() --> 1");

//				DNSClient dns;
//				IPAddress remote_addr;
//				dns.begin(Ethernet.dnsServerIP());
//				int ret = dns.getHostByName(serverName, remote_addr);
//				  if (ret == 1) {
//				    Serial.println(serverName);
//				    Serial.println(remote_addr);
//				  } else {
//					    Serial.println("Fail !!!");
//				  }


				if (client.connect(serverName, 80)) {
					delay(1000);
					Serial.println("!client.connect() --> 2");
					wasConnected = true;
					Serial.println("connecting...");
					// send the HTTP PUT request:
					String str = "GET ";
						str.concat(input);
    					str.concat(apikey);
						str.concat(inputJson);
						str.concat(jsonResult);
						str.concat(" HTTP/1.0");

					client.println(str);
					client.println("Host: emoncms.org");
					client.println("User-Agent: arduino-ethernet");
					client.println("Connection: close");
					client.println();
					client.flush();
					Serial.println(str);
					Serial.println("Respons:");
					Serial.println(client.readString());
					PowerSerial::solar.count = 0;
				} else {
					delay(1000);
					// if you couldn't make a connection:
					Serial.println("connection failed");
					Serial.println();
					Serial.println("disconnecting.");
					client.stop();
				}

			}
		} else {
//			Serial.print("Still waiting: ");
//			Serial.println(waitTime);
		}
	} else {
		Serial.println("Powerserial has no result .... waiting: ");
	}

	if (PowerSerial::solar.count >= 0){
		PowerSerial::parse();
	}

}