Exemplo n.º 1
0
void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();

  // we get a request
  if (client) {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done) {
      while (client.available () > 0 && !done) {
        done = processIncomingByte (client.read ());
      }
    }  // end of while client connected

    // get ROV status values as json string
    String rovStatus = getRovStatus();

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/json"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(rovStatus);

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop
Exemplo n.º 2
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
    boolean currentLineIsBlank = true;
    while (client.connected()) 
    {
      if (client.available()) 
      {
        char c = client.read();
        Serial.write(c);

        //*******************233333333333333333333333333333333333333333333*******
        // 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: textml");
          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 each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
          client.println("<ml>");
          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 disconnected");
  }
}
Exemplo n.º 3
0
void loopServer() {
	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;
					//Serial.print(c);
				}

				//if HTTP request has ended
				if (c == '\n') {

					///////////////
					Serial.print(readString); //print to serial monitor for debuging

					//now output HTML data header
					client.println(F("HTTP/1.1 200 OK")); //send new page on browser request
					client.println(F("Content-Type: text/html"));
					client.println();

					client.println(F("Ok"));

					delay(1);
					//stopping client
					client.stop();

					if (readString.indexOf("R1=1") > 0){
						soldoRelays[0]->On();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R1=1");
					}
					if (readString.indexOf("R2=1") > 0){
						soldoRelays[1]->On();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R2=1");
					}
					if (readString.indexOf("R1=0") > 0){
						soldoRelays[0]->Off();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R1=0");
					}
					if (readString.indexOf("R2=0") > 0){
						soldoRelays[1]->Off();
//						Serial.println(">>>>>>>>>>>>");
//						Serial.println("R2=0");
					}
					readString="";

				}
			}
		}
	}
}
Exemplo n.º 4
0
void loop() {
    client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                if (client.find("GET /")) {

                    //INICIAR CRONOMETRAGEM
                    if (client.find("setCron=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            iniciarCronometragem();
                        }
                    }

                    //RETORNA O TEMPO DESDE O INICIO
                    if (client.find("getCron=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            getCronometragem();
                        }
                    }

                    //RETORNA TEMPERATURA
                    if (client.find("getTemp=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            getTemperature();
                        }
                    }

                    //RETORNA HUMIDADE
                    if (client.find("getHum=")) {
                        int charReaded = client.read();
                        if(charReaded == 49) {
                            getHumidity();
                        }
                    }

                }
            }
            Serial.println();
            break;
        }
        client.println(" HTTP/1.1 200 OK ");
    }
    // give the web browser time to receive the data
    delay(1);
    client.stop();
}
Exemplo n.º 5
0
void loop()
{
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // 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();

          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(analogRead(analogChannel));
            client.println("<br />");
          }
          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();
  }
}
Exemplo n.º 6
0
void loop()
{
	Bootloader::poll();
	EthernetClient client = server.available();
	if (client)
	{
		Comm comm(&client);
		comm.send( F("time"), millis() );

		CommClient cc = comm.available();
		if (cc)
		{
			//TODO
		}

		delay(100);

	}
}
void loop() {

  client = server.available();

  if (client) {
    client.println("Toggling MODEM POWER");
    Serial.println("Toggling MODEM Power");

  if (ACTIVATED == false) {
    client.println(" PIN 13 -> HIGH ");
    digitalWrite( powerPIN , HIGH ); // TURN POWERTAIL ON 
    ACTIVATED = true;
  }
  else {
    client.println(" PIN 13 -> LOW");
    digitalWrite( powerPIN, LOW ); // TURN POWERTAIL OFF
    ACTIVATED = false;
  }
      
    client.stop();
  }

  switch ( Ethernet.maintain() ) {

    case 1:
      Serial.println("Error: renewed fail");
      break;
    case 2:
      Serial.println("Renewed success");
      break;
    case 3:
      Serial.println("Error: rebind fail");
      break;
    case 4:
      Serial.println("Rebind success");
      break;
    default:
      break;

  }
  
}
Exemplo n.º 8
0
void loop() {
  // wait for a new client:
  EthernetClient client = server.available();

  // when the client sends the first byte, say hello:
  if (client) {
    if (!gotAMessage) {
      Serial.println("We have a new client");
      client.println("Hello, client!"); 
      gotAMessage = true;
    }

    // read the bytes incoming from the client:
    char thisChar = client.read();
    // echo the bytes back to the client:
    server.write(thisChar);
    // echo the bytes to the server as well:
    Serial.print(thisChar);
  }
}
Exemplo n.º 9
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;
}
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);
		}
	}
	
}
Exemplo n.º 11
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();
  }

}
Exemplo n.º 12
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");
  }
}
Exemplo n.º 13
0
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");
  }
}
Exemplo n.º 14
0
void NetworkConnectionClass::run()
{
  client = server.available();
  while (client.connected()) {
    switch (state) {
      case IDLE:
        state = SEND_DATA;
        return;
      case RECV_DATA:
        getConfigData();
        for (LinkedList<SensorData*>::Iterator it = sensorData->begin(); it != sensorData->end(); it++) {
          if ((*it)->code == 12) {
            LightClass *temp = new LightClass();
            temp->init((*it)->pin);
            (*it)->dev = (SensorClass*)temp;
          }
          else if ((*it)->code == 0) {
            LedClass *d1 = new LedClass();
            d1->init((*it)->pin);
            (*it)->dev = (SensorClass*)d1;
          }
          else if ((*it)->code == 1) {
            MotorClass *d2 = new MotorClass();
            d2->init((*it)->pin);
            (*it)->dev = (SensorClass*)d2;
          }
          else if ((*it)->code == 2) {
            Serial.println("Street created");
            StreetLightClass *d3 = new StreetLightClass();
            d3->init((*it)->pin);
            (*it)->dev = (SensorClass*)d3;
          }
        }
        state = SEND_DATA;
        break;
      case SEND_DATA:
        unsigned long currentMillis = millis();

        if (currentMillis - previousMillis > interval) {
          previousMillis = currentMillis;

          for (LinkedList<SensorData*>::Iterator it = sensorData->begin(); it != sensorData->end(); it++) {
            // Check just sensors, not devices. Devices have code 0.
            if ((*it)->code != 0 && (*it)->code != 1 && (*it)->code != 2) {
              float dataValue;
              if ((*it)->code == 12) {
                dataValue = (*it)->dev->getValue("");
              }
              float newValueMax = (*it)->oldValue + (*it)->treshold;
              float newValueMin = (*it)->oldValue - (*it)->treshold;
              // Check if the sensor has exceeded threshold, send data and update oldValue of sensor
              //if (dataValue <= newValueMin || dataValue >= newValueMax) {
              sendData((*it)->name, String((int)dataValue));
              (*it)->oldValue = dataValue;
              //Serial.println((*it)->name);
              //Serial.println(dataValue);
              //}
            }
          }
        }

        checkForUpdate();

        state = SEND_DATA;
        break;
    }
  }
}
Exemplo n.º 15
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;
}
Exemplo n.º 16
0
void loop() {
	// try to get client
	EthernetClient client = server.available();
	String getStr;
	
	if (client) {
		digitalWrite(greLed,HIGH);
		boolean currentLineIsBlank = true;
		boolean indice = false;
		while (client.connected()) {
			if (client.available()) {	// client data available to read
				char c = client.read();	// read 1 byte (character) from client
				// filter GET request
				// GET /index.html HTTP/1.1
				if (c == 'G') {
					c = client.read();
					if (c == 'E') {
						c = client.read();
						if (c == 'T') {
							Serial.print("GET=");
							c = client.read(); // space
							while (true) {
								c = client.read();
								if (c == ' ') {
									break;
								}
								//Serial.println(c);
								getRequest[getIndi] = c;
								getIndi++;
							}
							Serial.print(getRequest);
							Serial.println("@");
						}
					}
				}
				if (c == '\n' && currentLineIsBlank) {
					// convert to string and clear char array
					String getStr(getRequest);
					Clear();

					// if check
					// first page
					if (getStr == "/" || getStr == "/index.html") {
						indice = true;
					}

					// ajax GET info
					else if (getStr.startsWith("/Set?")) {
						indice = true;
						int getRequestStart = getStr.indexOf('?' );
						int getRequestFirst = getStr.indexOf('=' );
						int getRequestFinal = getStr.indexOf('/',2);
						int getRequestDuall = getStr.indexOf('&' );	// 2 GET
						if (getRequestDuall>0) {	// /index.html?X=20&Y=30
							int getRequestSecon = getStr.indexOf('=', getRequestFirst+1);
							String inputFirst_1 = getStr.substring(getRequestStart+1, getRequestFirst);	// X
							String valueFirst_1 = getStr.substring(getRequestFirst+1, getRequestDuall);	// 20
							String inputFirst_2 = getStr.substring(getRequestDuall+1, getRequestSecon);	// Y
							String valueFirst_2 = getStr.substring(getRequestSecon+1, getRequestFinal);	// 30
							if (inputFirst_1 == "X") {
								Update('X',valueFirst_1.toInt());
								Update('Y',valueFirst_2.toInt());
							}
							// reverse
							else if (inputFirst_1 == "Y") {
								Update('Y',valueFirst_1.toInt());
								Update('X',valueFirst_2.toInt());
							}
						}
						else {						// /index.html?Y=50 or X=50
							String inputFirst = getStr.substring(getRequestStart+1, getRequestFirst);	// Y
							String valueFirst = getStr.substring(getRequestFirst+1, getRequestFinal);	// 50
							if (inputFirst == "X") {
								Update('X',valueFirst.toInt());
							}
							else if (inputFirst == "Y") {
								Update('Y',valueFirst.toInt());
							}
						}
					}

					//ajax SAVE info
					else if (getStr.startsWith("/Save/")) {
						digitalWrite(redLed,HIGH);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						Serial.println("SAVE");
						Serial.println("");
						SD.remove(LOG);
						dataFile = SD.open(LOG, FILE_WRITE);
						if(dataFile) {				// X=123-Y=45-
							dataFile.print("X=");
							dataFile.print(X);
							dataFile.print("-Y=");
							dataFile.print(Y);
							dataFile.print("-");
							dataFile.close();
						}
						digitalWrite(redLed,LOW);
					}

					//ajax RESET info
					else if (getStr.startsWith("/Reset/")) {
						digitalWrite(redLed,HIGH);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						Serial.println("RESET");
						Serial.println("");
						delay(1);
						servoX.detach();
						servoY.detach();
						digitalWrite(redLed,LOW);
						digitalWrite(resetPin, LOW);
					}
					// ajax SET info
					else if (getStr.startsWith("/Coordinate/")) {
						digitalWrite(redLed,HIGH);
						GetValue();
						double temp = analogRead(thermRes);
						int phot = analogRead(photoRes);
						client.println("HTTP/1.1 200 OK");
						client.println("Connection: close");
						client.println();
						// JSON
						client.print("{\"coordinate\":{\"X\":");
						client.print(X);
						client.print(",\"Y\":");
						client.print(Y);
						client.print("},\"temp\":");
						client.print(GetTemp(temp),1);
						client.print(",\"light\":");
						client.print(phot);
						client.print(",\"network\":\"");
						client.print(Ethernet.localIP());
						client.print("\",\"file\":[");
						for (int i=0; i<HTTP_FILE; i++) {
							File dFile = SD.open(GET[i]);
							if (dFile) {
								if(i>0) {
									client.print(",");
								}
								client.print("{");
								client.print("\"name\":\"");
								client.print(GET[i]);
								client.print("\",\"size\":");
								client.print(dFile.size());
								client.print("}");
							}
						}
						client.println("]}");
						digitalWrite(redLed,LOW);
					}

					// print other file
					else {
						for(int i=1; i<HTTP_FILE; i++) {
							if (getStr == TYP[0][i]) {
								webFile = SD.open(GET[i]);
								if (webFile) {
									client.println("HTTP/1.1 200 OK");
									client.println(TYP[1][i]);
									if(TYP[2][i] == "1") {
										client.println("Content-Encoding: gzip");
									}
									client.print("Content-Length: ");
									client.println(webFile.size());
									client.println("Cache-Control: max-age=302400, public");
									client.println("Connection: close");
									client.println();
								}
								break;
							}
						}
					}
					// endif check

					// print index.html
					if (indice) {
						webFile = SD.open(GET[0]);
						if (webFile) {
							client.println("HTTP/1.1 200 OK");
							client.println(TYP[1][0]);
							client.print("Content-Length: ");
							client.println(webFile.size());
							client.println("Connection: close");
							client.println();
						}
					}
					// read file and write into web client
					if (webFile) {
						while(webFile.available()) {
							client.write(webFile.read());
						}
						webFile.close();
					}
					
					break;
				}

				if (c == '\n') {
					// last character on line of received text. Starting new line with next character read
					currentLineIsBlank = true;
				} 
				else if (c != '\r') {
					// you've gotten a character on the current line
					currentLineIsBlank = false;
				}
			}
		}
		//delay(1);		// give the web browser time to receive the data
		client.stop();	// close the connection
		digitalWrite(greLed,LOW);
	}
}