Example #1
0
void loop() {
  // NETWORKING
  // TODO FIGURE OUT WHETHRE THIS IS BLOCKING
  WiFiClient client = server.available();
  if (!client) return; // TODO CONTINUE LOOPING
  
  int timeout = COMM_TIMEOUT; // TODO LESS BUSY WAIT?
  logMsg("New client");
  while(!client.available() && --timeout>0) {
    delay(1);
  }
  if (timeout <= 0) {
    logMsg("TIMEOUT");
    client.flush();
    return;
  }
  
  // GET MSG
  // TODO FIGURE OUT WHY DOESN'T WORK DIRECTLY
  String str = client.readStringUntil(0);  
  client.flush();
  logMsg(String("Got message [") + str + "]");
  
  // SEND REPLY
  client.print(processRequest(str).toString());
  delay(1);
  logMsg("Client disonnected");
}
Example #2
0
String Iotfy_getdata(int no_of_bytes, int timeout)
{
  int ctr=0;
  int pt=millis()/1000;
  String data="";
  data.reserve(no_of_bytes);
  while(1)
  {
    if(client.available())
    {
      char c=client.read();
      data+=c;
      Serial.print(c);
      ctr++;
      if(ctr==no_of_bytes)
        break;
    }      
    else
    {
      if(millis()/1000-pt>timeout)
      {
        pt=millis()/1000;
        break;    
      } 
    }
  }
  Serial.println("calling disconnect");
  client.flush();
  client.stop();
     
  return data;
}
Example #3
0
void transmitTele()
{
  Serial.println("tele"); 
  
  while(!alreadyConnectedTele)
  {
    //attempt to save a client connecting to the server
    teleClient = teleServer.available();
    
    //if a client is connected, begin communication
    if (teleClient) {
      if (!alreadyConnectedTele) {
        // clead out the input buffer:
        teleClient.flush();
        Serial.println("We have a new client");
        alreadyConnectedTele = true;
        
      }
    }
  }
  
    for(int i = 0; i < 20; i++)
    {
      if (teleClient.available() > 0) {
        // read the bytes incoming from the client:
        char thisChar = teleClient.read();
        // echo the bytes back to the client:
        
        if(thisChar == '1')
          teleServer.println(curSpeedKn * KNOTS_TO_MPS);
          
        if(thisChar == '2')  
          teleServer.println(pollPing());
          
        if(thisChar == '3')
          teleServer.println(distToTar());
          
        if(thisChar == '4')
          teleServer.println(curLat);
        
        if(thisChar == '5')
          teleServer.println(curLon);
        
        if(thisChar == '6')
          teleServer.println(curHead);
        
        
        // echo the bytes to the server as well:
        Serial.println(thisChar);
      }
    }
    
    
    
  
}
Example #4
0
void APServer(){
    WiFiClient client = server.available();  // Check if a client has connected
    if (!client) {
        return;
    }
    Serial.println("");
    Serial.println("New client");

    // Wait for data from client to become available
    while (client.connected() && !client.available()) {
      delay(1);
    }
    
    // Read the first line of HTTP request
    String req = client.readStringUntil('\r');
    Serial.println(req);
    String s;
    String gsid;
    String gpwd;
    //if the form has been submitted
    if(req.indexOf("ssid")!=-1){
      //TODO Make this a POST request
      //I'm basically hoping they're being nice
      int x = req.indexOf("ssid")+5;
      gsid = req.substring(x,req.indexOf("&",x));
      x = req.indexOf("pwd")+4;
      gpwd = req.substring(x,req.indexOf(" ",x));
      s = gsid;
      saveWifiConfig(gsid,gpwd);
      Serial.print("Restarting");
      client.print("Thanks! Restarting to new configuration");
      client.flush();
      ESP.restart();
    }
    else{
    s =  "<h1>Welcome to your ESP</h1><form action='/' method='get'><table><tr><td>SSID</td><td><input type='text' name='ssid'></td></tr><tr><td>Password</td><td><input type='text' name='pwd'></td><tr><td /><td><input type='submit' value='Submit'></td></tr></form>";
    client.print(s);
    }
    client.flush();
    delay(1);
    //Serial.println("Client disonnected");
}
Example #5
0
void waitForTarget()
{
  //define a client object to connect to the server
  WiFiClient mainClient;
  
  //wait for a client to connect to the server
  while(!alreadyConnectedMain)
  {
    //attempt to save a client connecting to the server
    mainClient = mainServer.available();
    
    //if a client is connected, begin communication
    if (mainClient) {
      if (!alreadyConnectedMain) {
        // clead out the input buffer:
        mainClient.flush();
        Serial.println("We have a new client");
        debugServer.println("We have a new client");
        mainClient.println("Hello, client!");
        alreadyConnectedMain = true;
        
      }
    }
    
    delay(100);
    
    delay(100);
  }
  Serial.println("writing");
  debugClient.println("writing");
  
  //mainServer.println("ready");
  delay(1000);
  
  //Strings to read in latitude and longitude from the client
  char lat[50] = "";
  char lon[50] = "";
  
  int ind = 0;
  
  //Wait for input to be on the buffer
  while(!mainClient.available());
  
  char destNum = '0';
  
  while(!(destNum == '1' || destNum == '2' || destNum == '3'))
  {
    destNum = mainClient.read();
    Serial.println(destNum);
  }
  
  if(destNum == '1')
  {
    tarLat = LAT1;
    tarLon = LON1;
  }
  if(destNum == '2')
  {
    tarLat = LAT2;
    tarLon = LON2;
  }
  if(destNum == '3')
  {
    tarLat = LAT3;
    tarLon = LON3;
  }
  
  /*
  //Read in characters from the input buffer until a new line character is reached
  //this will be the latitude
  while(mainClient.available())
    {
      char c = mainClient.read();
      lat[ind] = c;
      
      if(c == '\n')
      {
        lat[ind] = NULL;
        break;
      }
      
      ind++; 
    }
  
  ind = 0;
  
  //Read in characters from the input buffer until a new line character is reached
  //this will be the longitude
  while(mainClient.available())
    {
      char c = mainClient.read();
      lon[ind] = c;
      
      if(c == '\n')
      {
        lon[ind] = NULL;
        break;
      }
      
      ind++; 
    }
  
  mainClient.stop();
  
  //convert from a string to a float
  tarLat = strtof(lat, NULL);
  tarLon = strtof(lon, NULL);
  
  //digitalWrite(LED1, LOW);
  
  //tarLat = atof(lat);
  //tarLon = atof(lon);*/  
  
  Serial.print("Lat: ");
  Serial.print(lat);
  Serial.print(" ");
  Serial.println(tarLat, 6);
  Serial.print("Lon: ");
  Serial.print(lon);
  Serial.print(" ");
  Serial.println(tarLon, 6);
  
  debugClient.print("Lat: ");
  debugClient.print(lat);
  debugClient.print(" ");
  debugClient.println(tarLat, 6);
  debugClient.print("Lon: ");
  debugClient.print(lon);
  debugClient.print(" ");
  debugClient.println(tarLon, 6);
  
  //Erick's
  //tarLat = 28.504906f;
  //tarLon = -81.457456f;
  
  //apt
  //tarLat = 28.582183f;
  //tarLon = -81.202770f;
  
  //apt 2
  //tarLat = 28.582373f;
  //tarLon = -81.202996f;
  
  //curLat = 28.628811f;
  //curLon = -81.199479f;
  
  //mem mall
  //tarLat = 28.603710f;
  //tarLon = -81.199371f;
  
  //matt's
  //tarLat = 28.628391;
  //tarLon = -81.200013;
}
int WiFiManager::serverLoop()
{
    // Check for any mDNS queries and send responses
    mdns.update();
    String s;

    WiFiClient client = server_s.available();
    if (!client) {
        return(WM_WAIT);
    }

    DEBUG_PRINT("New client");
    
    // Wait for data from client to become available
    while(client.connected() && !client.available()){
        delay(1);
    }
    
    // Read the first line of HTTP request
    String req = client.readStringUntil('\r');
    
    // First line of HTTP request looks like "GET /path HTTP/1.1"
    // Retrieve the "/path" part by finding the spaces
    int addr_start = req.indexOf(' ');
    int addr_end = req.indexOf(' ', addr_start + 1);
    if (addr_start == -1 || addr_end == -1) {
        DEBUG_PRINT("Invalid request: ");
        DEBUG_PRINT(req);
        return(WM_WAIT);
    }
    req = req.substring(addr_start + 1, addr_end);
    DEBUG_PRINT("Request: ");
    DEBUG_PRINT(req);
    client.flush();

    if (req == "/")
    {
        s = HTTP_200;
        String head = HTTP_HEAD;
        head.replace("{v}", "Config ESP");
        s += head;
        s += HTTP_SCRIPT;
        s += HTTP_STYLE;
        s += HTTP_HEAD_END;

        int n = WiFi.scanNetworks();
        DEBUG_PRINT("scan done");
        if (n == 0) {
            DEBUG_PRINT("no networks found");
            s += "<div>No networks found. Refresh to scan again.</div>";
        }
        else {
            for (int i = 0; i < n; ++i)
            {
                DEBUG_PRINT(WiFi.SSID(i));
                DEBUG_PRINT(WiFi.RSSI(i));
                String item = HTTP_ITEM;
                item.replace("{v}", WiFi.SSID(i));
                s += item;
                delay(10);
            }
        }
        
        s += HTTP_FORM;
        s += HTTP_END;
        
        DEBUG_PRINT("Sending config page");
    }
    else if ( req.startsWith("/s") ) {
        String qssid;
        qssid = urldecode(req.substring(8,req.indexOf('&')).c_str());
        DEBUG_PRINT(qssid);
        DEBUG_PRINT("");
        req = req.substring( req.indexOf('&') + 1);
        String qpass;
        qpass = urldecode(req.substring(req.lastIndexOf('=')+1).c_str());

        setEEPROMString(0, 32, qssid);
        setEEPROMString(32, 64, qpass);

        EEPROM.commit();

        s = HTTP_200;
        String head = HTTP_HEAD;
        head.replace("{v}", "Saved config");
        s += HTTP_STYLE;
        s += HTTP_HEAD_END;
        s += "saved to eeprom...<br/>resetting in 10 seconds";
        s += HTTP_END;
        client.print(s);
        client.flush();

        DEBUG_PRINT("Saved WiFiConfig...restarting.");
        return WM_DONE;
    }
    else
    {
        s = HTTP_404;
        DEBUG_PRINT("Sending 404");
    }
    
    client.print(s);
    DEBUG_PRINT("Done with client");
    return(WM_WAIT);
}
Example #7
0
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');
  //reset header value
  for (int i = 0; i < _headerKeysCount; ++i) {
    _currentHeaders[i].value =String();
   }

  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG_ESP_HTTP_SERVER
    DEBUG_OUTPUT.print("Invalid request: ");
    DEBUG_OUTPUT.println(req);
#endif
    return false;
  }

  String methodStr = req.substring(0, addr_start);
  String url = req.substring(addr_start + 1, addr_end);
  String versionEnd = req.substring(addr_end + 8);
  _currentVersion = atoi(versionEnd.c_str());
  String searchStr = "";
  int hasSearch = url.indexOf('?');
  if (hasSearch != -1){
    searchStr = urlDecode(url.substring(hasSearch + 1));
    url = url.substring(0, hasSearch);
  }
  _currentUri = url;
  _chunked = false;

  HTTPMethod method = HTTP_GET;
  if (methodStr == "POST") {
    method = HTTP_POST;
  } else if (methodStr == "DELETE") {
    method = HTTP_DELETE;
  } else if (methodStr == "OPTIONS") {
    method = HTTP_OPTIONS;
  } else if (methodStr == "PUT") {
    method = HTTP_PUT;
  } else if (methodStr == "PATCH") {
    method = HTTP_PATCH;
  }
  _currentMethod = method;

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("method: ");
  DEBUG_OUTPUT.print(methodStr);
  DEBUG_OUTPUT.print(" url: ");
  DEBUG_OUTPUT.print(url);
  DEBUG_OUTPUT.print(" search: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  //attach handler
  RequestHandler* handler;
  for (handler = _firstHandler; handler; handler = handler->next()) {
    if (handler->canHandle(_currentMethod, _currentUri))
      break;
  }
  _currentHandler = handler;

  String formData;
  // below is needed only when POST type request
  if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
    String boundaryStr;
    String headerName;
    String headerValue;
    bool isForm = false;
    bool isEncoded = false;
    uint32_t contentLength = 0;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 1);
      headerValue.trim();
       _collectHeader(headerName.c_str(),headerValue.c_str());

      #ifdef DEBUG_ESP_HTTP_SERVER
      DEBUG_OUTPUT.print("headerName: ");
      DEBUG_OUTPUT.println(headerName);
      DEBUG_OUTPUT.print("headerValue: ");
      DEBUG_OUTPUT.println(headerValue);
      #endif

      if (headerName == "Content-Type"){
        if (headerValue.startsWith("text/plain")){
          isForm = false;
        } else if (headerValue.startsWith("application/x-www-form-urlencoded")){
          isForm = false;
          isEncoded = true;
        } else if (headerValue.startsWith("multipart/")){
          boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
          isForm = true;
        }
      } else if (headerName == "Content-Length"){
        contentLength = headerValue.toInt();
      } else if (headerName == "Host"){
        _hostHeader = headerValue;
      }
    }

    if (!isForm){
      size_t plainLength;
      char* plainBuf = readBytesWithTimeout(client, contentLength, plainLength, HTTP_MAX_POST_WAIT);
      if (plainLength < contentLength) {
      	free(plainBuf);
      	return false;
      }
      if (contentLength > 0) {
        if (searchStr != "") searchStr += '&';
        if(isEncoded){
          //url encoded form
          String decoded = urlDecode(plainBuf);
          size_t decodedLen = decoded.length();
          memcpy(plainBuf, decoded.c_str(), decodedLen);
          plainBuf[decodedLen] = 0;
          searchStr += plainBuf;
        }
        _parseArguments(searchStr);
        if(!isEncoded){
          //plain post json or other data
          RequestArgument& arg = _currentArgs[_currentArgCount++];
          arg.key = "plain";
          arg.value = String(plainBuf);
        }

  #ifdef DEBUG_ESP_HTTP_SERVER
        DEBUG_OUTPUT.print("Plain: ");
        DEBUG_OUTPUT.println(plainBuf);
  #endif
        free(plainBuf);
      }
    }

    if (isForm){
      _parseArguments(searchStr);
      if (!_parseForm(client, boundaryStr, contentLength)) {
        return false;
      }
    }
  } else {
    String headerName;
    String headerValue;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      _collectHeader(headerName.c_str(),headerValue.c_str());

	  #ifdef DEBUG_ESP_HTTP_SERVER
	  DEBUG_OUTPUT.print("headerName: ");
	  DEBUG_OUTPUT.println(headerName);
	  DEBUG_OUTPUT.print("headerValue: ");
	  DEBUG_OUTPUT.println(headerValue);
	  #endif

	  if (headerName == "Host"){
        _hostHeader = headerValue;
      }
    }
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Request: ");
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(" Arguments: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  return true;
}
Example #8
0
void mainloop()
{
  ///////////////////
  // do data logging
  ///////////////////
  if (millis() >= ulNextMeas_ms)
  {
    ds18b20();
    sendTeperatureTS(temp1, temp2, temp3, temp4);

    ulNextMeas_ms = millis() + ulMeasDelta_ms;

    pfTemp1[ulMeasCount % ulNoMeasValues] = temp1;
    pfTemp2[ulMeasCount % ulNoMeasValues] = temp2;
    pfTemp3[ulMeasCount % ulNoMeasValues] = temp3;
    pfTemp4[ulMeasCount % ulNoMeasValues] = temp4;
    pulTime[ulMeasCount % ulNoMeasValues] = millis() / 1000 + ulSecs2000_timer;

    Serial.print("Logging Temperature1: ");
    Serial.print(pfTemp1[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Temperature2: ");
    Serial.print(pfTemp2[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Temperature3: ");
    Serial.print(pfTemp3[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Temperature4: ");
    Serial.print(pfTemp4[ulMeasCount % ulNoMeasValues]);
    Serial.print(" deg Celsius - Time: ");
    Serial.println(pulTime[ulMeasCount % ulNoMeasValues]);

    ulMeasCount++;
  }

  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  unsigned long ultimeout = millis() + 250;
  while (!client.available() && (millis() < ultimeout) )
  {
    delay(1);
  }
  if (millis() > ultimeout)
  {
    Serial.println("client connection time-out!");
    return;
  }

  // Read the first line of the request
  String sRequest = client.readStringUntil('\r');
  //Serial.println(sRequest);
  client.flush();

  // stop client, if request is empty
  if (sRequest == "")
  {
    Serial.println("empty request! - stopping client");
    client.stop();
    return;
  }

  // get path; end of path is either space or ?
  // Syntax is e.g. GET /?pin=MOTOR1STOP HTTP/1.1
  String sPath = "", sParam = "", sCmd = "";
  String sGetstart = "GET ";
  int iStart, iEndSpace, iEndQuest;
  iStart = sRequest.indexOf(sGetstart);
  if (iStart >= 0)
  {
    iStart += +sGetstart.length();
    iEndSpace = sRequest.indexOf(" ", iStart);
    iEndQuest = sRequest.indexOf("?", iStart);

    // are there parameters?
    if (iEndSpace > 0)
    {
      if (iEndQuest > 0)
      {
        // there are parameters
        sPath  = sRequest.substring(iStart, iEndQuest);
        sParam = sRequest.substring(iEndQuest, iEndSpace);
      }
      else
      {
        // NO parameters
        sPath  = sRequest.substring(iStart, iEndSpace);
      }
    }
  }

  ///////////////////////////////////////////////////////////////////////////////
  // output parameters to serial, you may connect e.g. an Arduino and react on it
  ///////////////////////////////////////////////////////////////////////////////
  if (sParam.length() > 0)
  {
    int iEqu = sParam.indexOf("=");
    if (iEqu >= 0)
    {
      sCmd = sParam.substring(iEqu + 1, sParam.length());
      Serial.print("Die Eingabe ist: ");
      Serial.println(sCmd);
    }
  }


  ///////////////////////////
  // format the html response
  ///////////////////////////
  // Startseite ////////////////////////////////

  String sResponse, sResponse2, sHeader;

  if (sPath == "/")
  {
    ulReqcount++;
    int iIndex = (ulMeasCount - 1) % ulNoMeasValues;
    sResponse  = F("<html>\n<head>\n<title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title>\n");
    sResponse += F("</head>\n<body>\n<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>SMASE<BR><BR><FONT SIZE=+1>Letzte Messung um ");
    sResponse += F("Seite: Temperaturen -> Zeigt die gemessenen Temperaturen an <br>");
    sResponse += F("<hr>Seite: Grafik -> Zeigt den Temperaturverlauf (Diagramm) der letzten 24 h an <br>");
    sResponse += F("<hr>Seite: Grafik -> Zeigt den Temperaturverlauf (Tabelle) der letzten 24 h an <br>");
    sResponse += F("<hr>Seite: Settings -> Einstellungen <br>");
    sResponse += F(" <div style=\"clear:both;\"></div>");
    sResponse2 = F("<p>Temperaturverlauf - Seiten laden l&auml;nger:<BR>  <a href=\"/anzeige\"><button>Temperaturen</button></a>    <a href=\"/grafik\"><button>Grafik</button></a>     <a href=\"/tabelle\"><button>Tabelle</button></a>     <a href=\"/settings\"><button>Settings</button></a></p>");
    sResponse2 += MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
  }


  if (sPath == "/anzeige")
  {
    ulReqcount++;
    int iIndex = (ulMeasCount - 1) % ulNoMeasValues;
    sResponse  = F("<html>\n<head>\n<title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title>\n<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>\n");
    sResponse += F("<script type=\"text/javascript\">\ngoogle.charts.load('current', {'packages':['gauge']});\n");
    sResponse += F("  google.charts.setOnLoadCallback(drawGauge); \n");
    sResponse += F("\nvar gaugeOptions = {min: 0, max: 100, greenFrom: 50, greenTo:75, yellowFrom: 75, yellowTo: 90,redFrom: 90, redTo: 100, minorTicks: 10, majorTicks: ['0','10','20','30','40','50','60','70','80','90','100']};\n");
    sResponse += F("   var gauge; \n");
    sResponse += F("  function drawGauge() { \n");
    sResponse += F("       gaugeData = new google.visualization.DataTable();  \n");
    sResponse += F("       gaugeData.addColumn('number', 'oben');  \n");
    sResponse += F("       gaugeData.addColumn('number', 'mitte');  \n");
    sResponse += F("       gaugeData.addColumn('number', 'unten');  \n");
    sResponse += F("       gaugeData.addColumn('number', 'vorlauf');  \n");
    sResponse += F("       gaugeData.addRows(2);  \n");
    sResponse += F("       gaugeData.setCell(0, 0, ");
    sResponse += pfTemp1[iIndex];
    sResponse += F(" ); \n");
    sResponse += F("   gaugeData.setCell(0, 1, ");
    sResponse += pfTemp2[iIndex];
    sResponse += F(" ); \n");
    sResponse += F("   gaugeData.setCell(0, 2, ");
    sResponse += pfTemp3[iIndex];
    sResponse += F(" ); \n");
    sResponse += F("  gaugeData.setCell(0, 3, ");
    sResponse += pfTemp4[iIndex];
    sResponse += F(" ); \n");
    sResponse += F("       gauge = new google.visualization.Gauge(document.getElementById('gauge_div'));  \n");
    sResponse += F("  gauge.draw(gaugeData, gaugeOptions);  \n");
    sResponse += F("  } \n");
    sResponse += F("  </script> \n  </head> \n <body> \n<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>SMASE<BR><BR><FONT SIZE=+1>Letzte Messung um ");
    sResponse += epoch_to_string(pulTime[iIndex]).c_str();
    sResponse += F(" UTC<BR>\n");
    sResponse += F("<fieldset><legend>Pufferspeicher</legend>");
    sResponse += F("    <div id=\"gauge_div\" style=\"width:140px; height: 560px;\"></div> \n");
    sResponse += F("</fieldset>");
    sResponse += F(" <div style=\"clear:both;\"></div>");
    sResponse2 = F("<p>Temperaturverlauf - Seiten laden l&auml;nger:<BR>  <a href=\"/lauf\"><button>Vorlauf</button></a>    <a href=\"/grafik\"><button>Grafik</button></a>     <a href=\"/tabelle\"><button>Tabelle</button></a>     <a href=\"/settings\"><button>Settings</button></a></p>");
    sResponse2 += MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
  }
  // Tabelle ////////////////////////////////
  else if (sPath == "/tabelle")
    ////////////////////////////////////
    // format the html page for /tabelle
    ////////////////////////////////////
  {
    ulReqcount++;
    unsigned long ulSizeList = MakeTable(&client, false); // get size of table first

    sResponse  = F("<html><head><title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title></head><body>");
    sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
    sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
    sResponse += F("<h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>");
    sResponse += F("<FONT SIZE=+1>");
    sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Letzte Messungen im Abstand von ");
    sResponse += ulMeasDelta_ms;
    sResponse += F("ms<BR>");
    // here the big table will follow later - but let us prepare the end first

    // part 2 of response - after the big table
    sResponse2 = MakeHTTPFooter().c_str();

    // Send the response to the client - delete strings after use to keep mem low
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length() + ulSizeList).c_str());
    client.print(sResponse); sResponse = "";
    MakeTable(&client, true);
    client.print(sResponse2);
  }
  // Diagramm ////////////////////////////////
  else if (sPath == "/grafik")
    ///////////////////////////////////
    // format the html page for /grafik
    ///////////////////////////////////
  {
    ulReqcount++;
    unsigned long ulSizeList = MakeList(&client, false); // get size of list first

    sResponse  = F("<html>\n<head>\n<title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title>\n<script type=\"text/javascript\" src=\"https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}\"></script>\n");
    sResponse += F("<script type=\"text/javascript\"> google.setOnLoadCallback(drawChart);\nfunction drawChart() {var data = google.visualization.arrayToDataTable([\n['Zeit / UTC', 'Temperatur1', 'Temperatur2', 'Temperatur3', 'Temperatur4'],\n");
    // here the big list will follow later - but let us prepare the end first

    // part 2 of response - after the big list
    sResponse2  = F("]);\nvar options = {title: 'Verlauf',\n");
    sResponse2 += F("curveType:'function',legend:{ position: 'bottom'}};");
    sResponse2 += F("var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));chart.draw(data, options);}\n</script>\n</head>\n");
    sResponse2 += F("<body>\n<font color=\"#000000\"><body bgcolor=\"#d0d0f0\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\"><h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1><a href=\"/\"><button>Startseite</button></a><BR>");
    sResponse2 += F("<BR>\n<div id=\"curve_chart\" style=\"width: 600px; height: 400px\"></div>");
    sResponse2 += MakeHTTPFooter().c_str();

    // Send the response to the client - delete strings after use to keep mem low
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length() + ulSizeList).c_str());
    client.print(sResponse); sResponse = "";
    MakeList(&client, true);
    client.print(sResponse2);
  }
  // Einstellungen ////////////////////////////////
  else if (sPath == "/settings")
  {
    EEPROM.begin(512);
    delay(10);
    String apiKey = "";
    for (int i = 81; i < 100; i++)
    {
      //DEBUG_PRINT(i);
      apiKey += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.println("Thinkspeak: " + apiKey);

    EEPROM.begin(512);
    delay(10);
    String zeit = "";
    for (int i = 100; i < 105; i++)
    {
      zeit += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.print("Das ist die Zeitverschiebung: ");
    Serial.println(zeit);
    String zeittext = "";
    if (zeit != "0000")
    {
      zeittext = "Sommerzeit";
    }
    else
    {
      zeittext = "Winterzeit";
    }

    ulReqcount++;
    unsigned long ulSizeList = MakeTable(&client, false); // get size of table first

    sResponse  = F("<html><head><title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title></head><body>");
    sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
    sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
    sResponse += F("<h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>");
    sResponse += F("<FONT SIZE=+1>");
    sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Thingspeak API ist momentan: ");
    sResponse += apiKey;
    sResponse += F("<BR><BR>Das ist die Zeitverschiebung: ");
    sResponse += zeittext;
    sResponse += F("<fieldset><legend>EEPROM Setting</legend>");
    sResponse += F("<p><a href=\"/reset\"><button>RESET</button></a>&nbsp;<a href=\"?pin=FUNCTION2ON\"><button>AUSLESEN</button></a></p>");
    sResponse += F("</fieldset>");
    sResponse += F("<fieldset><legend>Allgemein Setting</legend>");
    sResponse += F("<p>Zeitumstellung <a href=\"?pin=SOMMERZEIT\"><button>SOMMERZEIT</button></a>&nbsp;<a href=\"?pin=WINTERZEIT\"><button>WINTERZEIT</button></a></p>");
    sResponse += F("<form name=\"input\" action=\"\" method=\"get\">THINGSPEAK-API: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>");
    sResponse += F("</fieldset>");
    sResponse += F("<fieldset><legend>Temperatur kalibrieren</legend>");
    sResponse += F("<p><a href=\"/temp1\"><button>Speicher oben</button></a>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a></p>");
    sResponse += F("</fieldset>");

    sResponse2 = MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
    delay(100);

    //////////////////////
    // react on parameters
    //////////////////////
    if (sCmd.length() > 0)
    {
      // write received command to html page
      sResponse += "Kommando:" + sCmd + "<BR>";

      // EEPROM RESET ////////////////////////////////
      if (sCmd.indexOf("FUNCTION1ON") >= 0)
      {
        EEPROM.begin(512);
        // write a 0 to all 512 bytes of the EEPROM
        for (int i = 0; i < 512; i++)
        {
          EEPROM.write(i, 0);

          EEPROM.end();
        }
      }
      // SHOW EEPROM ////////////////////////////////
      else if (sCmd.indexOf("FUNCTION2ON") >= 0)
      {
        EEPROM.begin(512);
        delay(10);
        String string3 = "";
        for (int i = 0; i < 150; i++)
        {
          //DEBUG_PRINT(i);
          string3 += char(EEPROM.read(i));
        }
        EEPROM.end();
        Serial.println(string3);
      }
      // SOMMERZEIT EINSTELLEN ////////////////////////////////
      else if (sCmd.indexOf("SOMMERZEIT") >= 0)
      {
        String sommer = "3600";
        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(sommer);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 100; i < 105; i++)
        {
          char c;
          if (si < sommer.length())
          {
            c = sommer[si];
          }
          else
          {
            c = 0;
          }

          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + sommer);
      }
      // WINTERZEIT EINSTELLEN ////////////////////////////////
      else if (sCmd.indexOf("WINTERZEIT") >= 0)
      {
        String winter = "0000";
        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(winter);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 100; i < 105; i++)
        {
          char c;
          if (si < winter.length())
          {
            c = winter[si];
          }
          else
          {
            c = 0;
          }
          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + winter);
      }
      // SET THINGSPEAK API ////////////////////////////////
      else
      {
        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(sCmd);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 81; i < 100; i++)
        {
          char c;
          if (si < sCmd.length())
          {
            c = sCmd[si];
            //DEBUG_PRINT("Wrote: ");
            //DEBUG_PRINT(c);
          }
          else
          {
            c = 0;
          }
          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + sCmd);
      }
    }
  }

  // Kalibrieren Temperatur 1 ////////////////////////////////
  else if (sPath == "/temp1")
    ////////////////////////////////////
    // format the html page for /tabelle
    ////////////////////////////////////
  {
    EEPROM.begin(512);
    delay(10);
    String temp1k = "";
    for (int i = 110; i < 115; i++)
    {
      temp1k += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.print("Das ist die Zeitverschiebung: ");
    Serial.println(temp1k);
    // settings();
    ulReqcount++;
    unsigned long ulSizeList = MakeTable(&client, false); // get size of table first

    sResponse  = F("<html><head><title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title></head><body>");
    sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
    sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
    sResponse += F("<h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>");
    sResponse += F("<FONT SIZE=+1>");
    sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Speicher oben: ");
    sResponse += temp1k;
    sResponse += F("Grad C<BR>");
    sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Speicher oben: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>");
    sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</p>");

    sResponse2 = MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
    delay(100);

    //////////////////////
    // react on parameters
    //////////////////////
    if (sCmd.length() > 0)
    {
      // write received command to html page
      sResponse += "Kommando:" + sCmd + "<BR>";
      // SET THINGSPEAK API ////////////////////////////////

      if (sCmd.toInt() != 0)
      {

        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(sCmd);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 110; i < 115; i++)
        {
          char c;
          if (si < sCmd.length())
          {
            c = sCmd[si];
            //DEBUG_PRINT("Wrote: ");
            //DEBUG_PRINT(c);
          }
          else
          {
            c = 0;
          }
          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + sCmd);
      }
      else
      {
        Serial.println("Der Wert " + sCmd + " war keine Zahl!!!");
      }

    }
  }
  // Kalibrieren Temperatur 2 ////////////////////////////////
  else if (sPath == "/temp2")
    ////////////////////////////////////
    // format the html page for /tabelle
    ////////////////////////////////////
  {
    EEPROM.begin(512);
    delay(10);
    String temp2k = "";
    for (int i = 115; i < 120; i++)
    {
      temp2k += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.print("Das ist die Zeitverschiebung: ");
    Serial.println(temp2k);
    // settings();
    ulReqcount++;
    unsigned long ulSizeList = MakeTable(&client, false); // get size of table first

    sResponse  = F("<html><head><title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title></head><body>");
    sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
    sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
    sResponse += F("<h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>");
    sResponse += F("<FONT SIZE=+1>");
    sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Speicher mitte: ");
    sResponse += temp2k;
    sResponse += F("Grad C<BR>");
    sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Speicher mitte: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>");
    sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</p>");

    sResponse2 = MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
    delay(100);

    //////////////////////
    // react on parameters
    //////////////////////
    if (sCmd.length() > 0)
    {
      // write received command to html page
      sResponse += "Kommando:" + sCmd + "<BR>";
      // SET THINGSPEAK API ////////////////////////////////


      if (sCmd.toInt() != 0)
      {

        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(sCmd);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 115; i < 120; i++)
        {
          char c;
          if (si < sCmd.length())
          {
            c = sCmd[si];
            //DEBUG_PRINT("Wrote: ");
            //DEBUG_PRINT(c);
          }
          else
          {
            c = 0;
          }
          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + sCmd);
      }
      else
      {
        Serial.println("Der Wert " + sCmd + " war keine Zahl!!!");
      }

    }
  }
  // Kalibrieren Temperatur 3 ////////////////////////////////
  else if (sPath == "/temp3")
    ////////////////////////////////////
    // format the html page for /tabelle
    ////////////////////////////////////
  {
    EEPROM.begin(512);
    delay(10);
    String temp3k = "";
    for (int i = 120; i < 125; i++)
    {
      temp3k += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.print("Das ist der aktuelle Korrekturwert: ");
    Serial.println(temp3k);
    // settings();
    ulReqcount++;
    unsigned long ulSizeList = MakeTable(&client, false); // get size of table first

    sResponse  = F("<html><head><title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title></head><body>");
    sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
    sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
    sResponse += F("<h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>");
    sResponse += F("<FONT SIZE=+1>");
    sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Speicher unten ");
    sResponse += temp3k;
    sResponse += F("Grad C<BR>");
    sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Speicher unten: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>");
    sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</p>");

    sResponse2 = MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
    delay(100);

    //////////////////////
    // react on parameters
    //////////////////////
    if (sCmd.length() > 0)
    {
      // write received command to html page
      sResponse += "Kommando:" + sCmd + "<BR>";
      // SET THINGSPEAK API ////////////////////////////////
      if (sCmd.toInt() != 0)
      {

        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(sCmd);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 120; i < 125; i++)
        {
          char c;
          if (si < sCmd.length())
          {
            c = sCmd[si];
            //DEBUG_PRINT("Wrote: ");
            //DEBUG_PRINT(c);
          }
          else
          {
            c = 0;
          }
          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + sCmd);
      }
      else
      {
        Serial.println("Der Wert " + sCmd + " war keine Zahl!!!");
      }
    }
  }
  // Kalibrieren Temperatur 4 ////////////////////////////////
  else if (sPath == "/temp4")
    ////////////////////////////////////
    // format the html page for /tabelle
    ////////////////////////////////////
  {
    EEPROM.begin(512);
    delay(10);
    String temp4k = "";
    for (int i = 125; i < 130; i++)
    {
      temp4k += char(EEPROM.read(i));
    }
    EEPROM.end();
    Serial.print("Das ist die Zeitverschiebung: ");
    Serial.println(temp4k);
    // settings();
    ulReqcount++;
    unsigned long ulSizeList = MakeTable(&client, false); // get size of table first

    sResponse  = F("<html><head><title>WLAN Logger f&uuml;r Pufferspeichertemperatur</title></head><body>");
    sResponse += F("<font color=\"#000000\"><body bgcolor=\"#d0d0f0\">");
    sResponse += F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\">");
    sResponse += F("<h1>WLAN Logger f&uuml;r Pufferspeichertemperatur</h1>");
    sResponse += F("<FONT SIZE=+1>");
    sResponse += F("<a href=\"/\"><button>Startseite</button></a><BR><BR>Anpassung Vorlauf: ");
    sResponse += temp4k;
    sResponse += F("Grad C<BR>");
    sResponse += F("<form name=\"input\" action=\"\" method=\"get\">Vorlauf: <input type=\"text\" name=\"$\"><input type=\"submit\" value=\"Submit\"></form>");
    sResponse += F("<p>Temperatur kalibrieren: <a href=\"/temp1\"><button>Speicher oben</button></a>&nbsp;<a href=\"/temp2\"><button>Speicher mitte</button></a>&nbsp;<a href=\"/temp3\"><button>Speicher unten</button></a>&nbsp;<a href=\"/temp4\"><button>Vorlauf</button></a>&nbsp;</p>");

    sResponse2 = MakeHTTPFooter().c_str();

    // Send the response to the client
    client.print(MakeHTTPHeader(sResponse.length() + sResponse2.length()).c_str());
    client.print(sResponse);
    client.print(sResponse2);
    delay(100);

    //////////////////////
    // react on parameters
    //////////////////////
    if (sCmd.length() > 0)
    {
      // write received command to html page
      sResponse += "Kommando:" + sCmd + "<BR>";
      // SET THINGSPEAK API ////////////////////////////////


      if (sCmd.toInt() != 0)
      {

        Serial.print("Das wird gespeichert in der seite: ");
        Serial.println(sCmd);
        EEPROM.begin(512);
        delay(10);
        int si = 0;
        for (int i = 125; i < 130; i++)
        {
          char c;
          if (si < sCmd.length())
          {
            c = sCmd[si];
            //DEBUG_PRINT("Wrote: ");
            //DEBUG_PRINT(c);
          }
          else
          {
            c = 0;
          }
          EEPROM.write(i, c);
          si++;
        }
        EEPROM.end();
        Serial.println("Wrote " + sCmd);
      }
      else
      {
        Serial.println("Der Wert " + sCmd + " war keine Zahl!!!");
      }

    }
  }



  // Send the response to the client
  client.print(sHeader);
  client.print(sResponse);

  // and stop the client
  client.stop();
  Serial.println("Client disconnected");

}
Example #9
0
void Humure::loop()
{
  // Check if a client has connected
  WiFiClient client = this->server.available();
  if (!client) {
    return;
  }
  Serial.println("");
  Serial.println("New client");

  // Wait for data from client to become available
  while(client.connected() && !client.available()){
    delay(1);
  }
  
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');

  // GET or POST?
  bool req_get;
  if ( req.startsWith("GET") ) {
    req_get = true;
  } else if ( req.startsWith("POST") ) {
    req_get = false;
  } else {
    Serial.print("Invalid request: ");
    Serial.println(req);
    return;
  }
  
  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
    Serial.print("Invalid request: ");
    Serial.println(req);
    return;
  }
  req = req.substring(addr_start + 1, addr_end);

  Serial.print("Request ");
  if (req_get)
  {
    Serial.print("GET");
  } else {
    Serial.print("POST");
  }
  Serial.print(" : ");
  Serial.println(req);
  client.flush();

  if ( req_get ) {
    if ( req == "/" ) {
        readSensor();
        sendFullPage(client);
    } else 
    if ( req ==  "/lamp") {
      jsonValue(client, String( ! led_status) );
    } else 
    if ( req ==  "/temperatur") {
      readSensor();
      jsonValue(client, String( this->t) );
    } else 
    if ( req ==  "/humidity") {
      readSensor();
      jsonValue(client, String( this->h) );
    } else {
      client.print("HTTP/1.1 404 Not Found\r\n\r\n");
    }
  } else {
    if ( req == "/lamp/on" ) {
        led_status = 0;
        jsonValue(client, String( ! led_status) );
    } else
    if ( req =="/lamp/off" ) {
        led_status = 1;
        jsonValue(client, String( ! led_status) );
    } else {
        client.print("HTTP/1.1 404 Not Found\r\n\r\n");
    }
     digitalWrite(this->led, led_status);
  }

  Serial.println("Done with client");
}
Example #10
0
// Process HTTP requests -- just call it inside the loop() function
void WebConfig::ProcessHTTP()
{
	// Accept any new web connection
	WiFiClient httpClient = pHttpServer->available();
	if (!httpClient) return;

	// Read the entire request
	String req = httpClient.readString();
	httpClient.flush();

	// after some time, do not open the web interface anymore.
	//if (millis() - startMillis > 2*60000) return;

	// response header
	String s;

	if (strlen(webLogin) > 0 || strlen(webPassword) > 0)
	{
		int authPos = req.indexOf("Authorization: Basic");

		if (authPos == -1)
		{
			// request authentication
			s = "HTTP/1.0 401 Authorization Required\r\nWWW-Authenticate: Basic realm=\"" + String(apName) + "\"\r\n\r\n";
			s += "<h1><b>ACCESS DENIED</b></h1>";
			httpClient.write(s.c_str(), s.length());
			httpClient.flush();
			return;
		}

		// there is authentication info, check it
		String authInfo = req.substring(authPos + 21);
		int endLinePos = authInfo.indexOf("\r");
		if (endLinePos == -1) { httpClient.print("Malformed request."); httpClient.stop(); return; }
		authInfo = authInfo.substring(0, endLinePos);
		if (strncmp(base64Auth, authInfo.c_str(), 64))
		{
			s = "<h1><b>ACCESS DENIED</b></h1>";
			httpClient.write(s.c_str(), s.length());
			httpClient.flush();
			return;
		}
	}

	byte mac[6];
	WiFi.macAddress(mac);
	String m = String(mac[0],HEX) + ":" + String(mac[1],HEX) + ":" + String(mac[2],HEX) + ":" + String(mac[3],HEX) + ":" + String(mac[4],HEX) + ":" + String(mac[5],HEX);

	//
	// generate HTTP response
	//

	// authentication succeeded, proceed normally
	s = "HTTP/1.1 200 OK\r\n";
	s += "Content-Type: text/html\r\n\r\n";
	s += "<!DOCTYPE HTML>\r\n<html><body>\r\n";

	// If there are parms, update variables and save settings
	bool updated = ProcessParms(req);
	if (updated)
	{
		s += "Parameters have been updated and microcontroller will restart.<br><br>\r\n";
	}

	// javascript to save configuration
	s += "<script>\r\n";
	s += "function save()\r\n";
	s += "{\r\n";
	s += "var webPort = document.getElementById('web_port').value;\r\n";
	s += "var webLogin = document.getElementById('web_login').value;\r\n";
	s += "var webPassword = document.getElementById('web_pass').value;\r\n";
	s += "var webPassword2 = document.getElementById('web_pass2').value;\r\n";
	s += "var modeap = document.getElementById('modeap').checked;\r\n";
	s += "if (modeap) isAP = true; else isAP = false;\r\n";
	s += "var apName = document.getElementById('ap_ssid').value;\r\n";
	s += "var apPassword = document.getElementById('ap_pass').value;\r\n";
	s += "var apPassword2 = document.getElementById('ap_pass2').value;\r\n";
	s += "var apChannel = document.getElementById('apChannel').value;\r\n";
	s += "var ssid = document.getElementById('ssid').value;\r\n";
	s += "var password = document.getElementById('pass').value;\r\n";
	s += "var password2 = document.getElementById('pass2').value;\r\n";
	s += "var udpPort = document.getElementById('udpPort').value;\r\n";
	s += "var tcpPort = document.getElementById('tcpPort').value;\r\n";
	s += "if (webPassword != webPassword2) { alert('WEB passwords dont match'); return; }\r\n";
	s += "if (apPassword != apPassword2) { alert('AP passwords dont match'); return; }\r\n";
	s += "if (password != password2) { alert('Router passwords dont match'); return; }\r\n";
	s += "window.location.search=webPort + '&' + webLogin + '&' + webPassword + '&' + btoa(webLogin+':'+webPassword) + '&' + (isAP?'1':'0') + '&' + apName + '&' + apPassword + '&' + apChannel + '&' + ssid + '&' + password + '&' + udpPort + '&' + tcpPort;\r\n";
	s += "}\r\n";
	s += "</script>\r\n";

	// write first part of response
	httpClient.write(s.c_str(), s.length());

	// title and mac address
	s = "<b>" + String(name) + "</b><br>\r\n";
	s += "MAC: " + m + "<br>\r\n";

	// web interface configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>WEB INTERFACE</b></td></tr>\r\n";
	s += "<tr><td>Port</td><td><input type=text id='web_port' value='" + String(webPort) + "'></td></tr>\r\n";
	s += "<tr><td>Login</td><td><input type=text id='web_login' value='" + String(webLogin) + "'></td></tr>\r\n";
	s += "<tr><td>Password</td><td><input type=password id='web_pass' value='" + String(webPassword) + "'></td></tr>\r\n";
	s += "<tr><td>Pass Confirm</td><td><input type=password id='web_pass2' value='" + String(webPassword) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// ap configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>ACCESS POINT</b></td></tr>\r\n";
	s += "<tr><td>Mode</td><td><input type=radio id='modeap' name='mode' value='ap'" + (isAP?String(" checked"):String("")) + ">Access Point</td></tr>\r\n";
	s += "<tr><td>Channel</td><td><select id='apChannel'>";
	for (byte c=1; c<14; c++) s += "<option value='" + String(c) + "'" + (c==apChannel?String(" selected"):String("")) + ">" + String(c) + "</option>";
	s += "</select></td></tr>\r\n";
	s += "<tr><td>SSID</td><td><input type=text id='ap_ssid' value='" + String(apName) + "'></td></tr>\r\n";
	s += "<tr><td>Password</td><td><input type=password id='ap_pass' value='" + String(apPassword) + "'></td></tr>\r\n";
	s += "<tr><td>Pass Confirm</td><td><input type=password id='ap_pass2' value='" + String(apPassword) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// station configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>STATION</b></td></tr>\r\n";
	s += "<tr><td>Mode</td><td><input type=radio id='modest' name='mode' value='station'" + (isAP?String(""):String(" checked")) + ">Station</td></tr>\r\n";
	s += "<tr><td>SSID</td><td><input type=text id='ssid' value='" + String(ssid) + "'></td></tr>\r\n";
	s += "<tr><td>Password</td><td><input type=password id='pass' value='" + String(password) + "'></td></tr>\r\n";
	s += "<tr><td>Pass Confirm</td><td><input type=password id='pass2' value='" + String(password) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// udp/tcp ports configuration
	s += "<table border=1>\r\n";
	s += "<tr><td colspan=2 bgcolor=#E0E0E0><b>UDP|TCP LISTENERS</b></td></tr>\r\n";
	s += "<tr><td>UDP Port</td><td><input type=text id='udpPort' value='" + String(udpPort) + "'></td></tr>\r\n";
	s += "<tr><td>TCP Port</td><td><input type=text id='tcpPort' value='" + String(tcpPort) + "'></td></tr>\r\n";
	s += "</table>\r\n";

	// save button
	s += "<input type=button value='Save and Reset' onClick='save()'>\r\n";

	// end of HTTP
	s += "</body></html>\r\n";

	// write second part of response
	httpClient.write(s.c_str(), s.length());
	httpClient.flush();

	if (updated)
	{
		// give some time
		delay(2000);

		// reset the microcontroller
		Reset();
	}
}
void ESP8266WebServer::handleClient()
{
  WiFiClient client = _server.available();
  if (!client) {
    return;
  }

#ifdef DEBUG
  Serial.println("New client");
#endif
  // Wait for data from client to become available
  while(client.connected() && !client.available()){
    delay(1);
  }

  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');

  HTTPMethod method = HTTP_GET;
  if (req.startsWith("POST")) {
    method = HTTP_POST;
  }

  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
    Serial.print("Invalid request: ");
    Serial.println(req);
#endif
    return;
  }

  req = req.substring(addr_start + 1, addr_end);

  String formData;
  if (method == HTTP_POST) {
    int contentLength = -1;
    int headerCount = 0;
    while(headerCount < 1024) { // there shouldn't be that much really
      String line = client.readStringUntil('\r');
      client.readStringUntil('\n');

      if (line.length() > 0) {  // this is a header
        ++headerCount;
        if (contentLength < 0 && line.startsWith("Content-Length")) {
          // get content length from the header
          int valuePos = line.indexOf(' ', 14);
          if (valuePos > 0) {
            String valueStr = line.substring(valuePos+1);
            contentLength = valueStr.toInt();
#ifdef DEBUG
            Serial.print("Content-Length: ");
            Serial.println(contentLength);
#endif
          }
        }
      }
      else {
        break;
      }
    }
#ifdef DEBUG
    Serial.print("headerCount=");
    Serial.println(headerCount);
#endif
    if (contentLength >= 0) {
      formData = "";
      int n = 0;   // timeout counter
      while (formData.length() < contentLength && ++n < 3)
        formData += client.readString();
    }
    else {
      formData = client.readStringUntil('\r'); // will return after timing out once
    }
  }
  else if (method == HTTP_GET) {
    int args_start = req.indexOf('?');
    if (args_start != -1) {
      formData = req.substring(args_start + 1);
      req = req.substring(0, args_start);
    }
  }

  client.flush();

#ifdef DEBUG
  Serial.print("Request: ");
  Serial.println(req);
  Serial.print("Args: ");
  Serial.println(formData);
#endif

  _parseArguments(formData);
  _handleRequest(client, req, method);

}
Example #12
0
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');

  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG
    DEBUG_OUTPUT.print("Invalid request: ");
    DEBUG_OUTPUT.println(req);
#endif
    return false;
  }
  
  String methodStr = req.substring(0, addr_start);
  String url = req.substring(addr_start + 1, addr_end);
  String searchStr = "";
  int hasSearch = url.indexOf('?');
  if (hasSearch != -1){
    searchStr = url.substring(hasSearch + 1);
    url = url.substring(0, hasSearch);
  }
  _currentUri = url;
  
  HTTPMethod method = HTTP_GET;
  if (methodStr == "POST") {
    method = HTTP_POST;
  } else if (methodStr == "DELETE") {
    method = HTTP_DELETE;
  } else if (methodStr == "PUT") {
    method = HTTP_PUT;
  } else if (methodStr == "PATCH") {
    method = HTTP_PATCH;
  }
  _currentMethod = method;
  
#ifdef DEBUG
  DEBUG_OUTPUT.print("method: ");
  DEBUG_OUTPUT.print(methodStr);
  DEBUG_OUTPUT.print(" url: ");
  DEBUG_OUTPUT.print(url);
  DEBUG_OUTPUT.print(" search: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  String formData;
  // below is needed only when POST type request
  if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
    String boundaryStr;
    String headerName;
    String headerValue;
    bool isForm = false;
    uint32_t contentLength = 0;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      if (headerName == "Content-Type"){
        if (headerValue.startsWith("text/plain")){
          isForm = false;
        } else if (headerValue.startsWith("multipart/form-data")){
          boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);
          isForm = true;
        }
      } else if (headerName == "Content-Length"){
        contentLength = headerValue.toInt();
      }
    }
  
    if (!isForm){
      if (searchStr != "") searchStr += '&';
      //some clients send headers first and data after (like we do)
      //give them a chance
      int tries = 100;//100ms max wait
      while(!client.available() && tries--)delay(1);
      size_t plainLen = client.available();
      char *plainBuf = (char*)malloc(plainLen+1);
      client.readBytes(plainBuf, plainLen);
      plainBuf[plainLen] = '\0';
#ifdef DEBUG
      DEBUG_OUTPUT.print("Plain: ");
      DEBUG_OUTPUT.println(plainBuf);
#endif
      if(plainBuf[0] == '{' || plainBuf[0] == '[' || strstr(plainBuf, "=") == NULL){
        //plain post json or other data
        searchStr += "plain=";
        searchStr += plainBuf;
      } else {
        searchStr += plainBuf;
      }
      free(plainBuf);
    }
    _parseArguments(searchStr);
    if (isForm){
      _parseForm(client, boundaryStr, contentLength);
    }
  } else {
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG
  DEBUG_OUTPUT.print("Request: ");
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(" Arguments: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  return true;
}
////////////////////////////////////
// Scrape UTC Time from server
////////////////////////////////////
char* updateCurTime(void) {
    static int timeout_busy=0;
    int ipos;
    timeout_busy=0; //reset

    const char* timeServer = "aws.amazon.com";

    // send a bad header on purpose, so we get a 400 with a DATE: timestamp
    const char* timeServerGet = "GET example.com/ HTTP/1.1";
    String utctime;
    String GmtDate;
    static char dateStamp[20];
    static char chBuf[200];
    char utctimeraw[80];
    char* dpos;

    WiFiClient client;
    if (client.connect(timeServer, 80)) {
        //Send Request
        client.println(timeServerGet);
        client.println();
        while((!client.available())&&(timeout_busy++<5000)){
          // Wait until the client sends some data
          delay(1);
        }

        // kill client if timeout
        if(timeout_busy>=5000) {
            client.flush();
            client.stop();
            Serial.println("timeout receiving timeserver data\n");
            return dateStamp;
        }

        // read the http GET Response
        String req2 = client.readString();
        // Serial.println("");
        // Serial.println("");
        // Serial.print(req2);
        // Serial.println("");
        // Serial.println("");

        // close connection
        delay(1);
        client.flush();
        client.stop();

        ipos = req2.indexOf("Date:");
        if(ipos>0) {
          GmtDate = req2.substring(ipos,ipos+35);
          // Serial.println(GmtDate);
          utctime = GmtDate.substring(18,22) + getMonth(GmtDate.substring(14,17)) + GmtDate.substring(11,13) + GmtDate.substring(23,25) + GmtDate.substring(26,28) + GmtDate.substring(29,31);
          // Serial.println(utctime.substring(0,14));
          utctime.substring(0,14).toCharArray(dateStamp, 20);
        }
    }
    else {
      Serial.println("did not connect to timeserver\n");
    }
    timeout_busy=0;     // reset timeout
    return dateStamp;   // Return latest or last good dateStamp
}
Example #14
0
bool ESP8266WebServer::_parseRequest(WiFiClient& client) {
  // Read the first line of HTTP request
  String req = client.readStringUntil('\r');
  client.readStringUntil('\n');
  //reset header value
  for (int i = 0; i < _headerKeysCount; ++i) {
    _currentHeaders[i].value =String();
   }

  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
  int addr_start = req.indexOf(' ');
  int addr_end = req.indexOf(' ', addr_start + 1);
  if (addr_start == -1 || addr_end == -1) {
#ifdef DEBUG_ESP_HTTP_SERVER
    DEBUG_OUTPUT.print("Invalid request: ");
    DEBUG_OUTPUT.println(req);
#endif
    return false;
  }

  String methodStr = req.substring(0, addr_start);
  String url = req.substring(addr_start + 1, addr_end);
  String versionEnd = req.substring(addr_end + 8);
  _currentVersion = atoi(versionEnd.c_str());
  String searchStr = "";
  int hasSearch = url.indexOf('?');
  if (hasSearch != -1){
    searchStr = url.substring(hasSearch + 1);
    url = url.substring(0, hasSearch);
  }
  _currentUri = url;
  _chunked = false;

  HTTPMethod method = HTTP_GET;
  if (methodStr == F("POST")) {
    method = HTTP_POST;
  } else if (methodStr == F("DELETE")) {
    method = HTTP_DELETE;
  } else if (methodStr == F("OPTIONS")) {
    method = HTTP_OPTIONS;
  } else if (methodStr == F("PUT")) {
    method = HTTP_PUT;
  } else if (methodStr == F("PATCH")) {
    method = HTTP_PATCH;
  }
  _currentMethod = method;

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("method: ");
  DEBUG_OUTPUT.print(methodStr);
  DEBUG_OUTPUT.print(" url: ");
  DEBUG_OUTPUT.print(url);
  DEBUG_OUTPUT.print(" search: ");
  DEBUG_OUTPUT.println(searchStr);
#endif

  //attach handler
  RequestHandler* handler;
  for (handler = _firstHandler; handler; handler = handler->next()) {
    if (handler->canHandle(_currentMethod, _currentUri))
      break;
  }
  _currentHandler = handler;

  String formData;
  // below is needed only when POST type request
  if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){
    String boundaryStr;
    String headerName;
    String headerValue;
    bool isForm = false;
    //bool isEncoded = false;
    uint32_t contentLength = 0;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 1);
      headerValue.trim();
       _collectHeader(headerName.c_str(),headerValue.c_str());

      #ifdef DEBUG_ESP_HTTP_SERVER
      DEBUG_OUTPUT.print("headerName: ");
      DEBUG_OUTPUT.println(headerName);
      DEBUG_OUTPUT.print("headerValue: ");
      DEBUG_OUTPUT.println(headerValue);
      #endif

      if (headerName.equalsIgnoreCase(FPSTR(Content_Type))){
        using namespace mime;
        if (headerValue.startsWith(FPSTR(mimeTable[txt].mimeType))){
          isForm = false;
        } else if (headerValue.startsWith(F("application/x-www-form-urlencoded"))){
          isForm = false;
          //isEncoded = true;
        } else if (headerValue.startsWith(F("multipart/"))){
          boundaryStr = headerValue.substring(headerValue.indexOf('=') + 1);
          boundaryStr.replace("\"","");
          isForm = true;
        }
      } else if (headerName.equalsIgnoreCase(F("Content-Length"))){
        contentLength = headerValue.toInt();
      } else if (headerName.equalsIgnoreCase(F("Host"))){
        _hostHeader = headerValue;
      }
    }

    // always parse url for key/value pairs
    _parseArguments(searchStr);

    if (!isForm) {
      if (contentLength) {

        // add key=value: plain={body} (post json or other data)

        size_t plainLength;
        char* plainBuf = readBytesWithTimeout(client, contentLength, plainLength, HTTP_MAX_POST_WAIT);
        if (plainLength < contentLength) {
          free(plainBuf);
          return false;
        }

        RequestArgument& arg = _currentArgs[_currentArgCount++];
        arg.key = F("plain");
        arg.value = String(plainBuf);

        free(plainBuf);

      }
    } else { // isForm is true

      if (!_parseForm(client, boundaryStr, contentLength)) {
        return false;
      }

    }
  } else {
    String headerName;
    String headerValue;
    //parse headers
    while(1){
      req = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (req == "") break;//no moar headers
      int headerDiv = req.indexOf(':');
      if (headerDiv == -1){
        break;
      }
      headerName = req.substring(0, headerDiv);
      headerValue = req.substring(headerDiv + 2);
      _collectHeader(headerName.c_str(),headerValue.c_str());

#ifdef DEBUG_ESP_HTTP_SERVER
      DEBUG_OUTPUT.print(F("headerName: "));
      DEBUG_OUTPUT.println(headerName);
      DEBUG_OUTPUT.print(F("headerValue: "));
      DEBUG_OUTPUT.println(headerValue);
#endif

      if (headerName.equalsIgnoreCase("Host")){
        _hostHeader = headerValue;
      }
    }
    _parseArguments(searchStr);
  }
  client.flush();

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print(F("Request: "));
  DEBUG_OUTPUT.println(url);
  DEBUG_OUTPUT.print(F("Arguments: "));
  DEBUG_OUTPUT.println(searchStr);

  DEBUG_OUTPUT.println(F("final list of key/value pairs:"));
  for (int i = 0; i < _currentArgCount; i++)
    DEBUG_OUTPUT.printf("  key:'%s' value:'%s'\r\n",
      _currentArgs[i].key.c_str(),
      _currentArgs[i].value.c_str());
#endif

  return true;
}