Example #1
0
/**
 * Wait for a WiFiClient to connect
 *
 * @returns: True if the client is ready, false otherwise.
 * 
 */
bool ESP8266WiFiMesh::waitForClient(WiFiClient curr_client, int max_wait)
{
	int wait = max_wait;
	while(curr_client.connected() && !curr_client.available() && wait--)
		delay(3);

	/* Return false if the client isn't ready to communicate */
	if (WiFi.status() == WL_DISCONNECTED || !curr_client.connected())
		return false;
	
	return true;
}
Example #2
0
void Farmy::sendData(const char* device_id, String api_key, WiFiClient client, String data)
{
  // Todo: use retry to connect internet.
  Serial.println("Connected to Famry.");
  Serial.println("Posted:" + data);

  // Create HTTP POST Data
  String url = String("/api/v0/user_devices/") + device_id + "/sensor_datas/";
  client.print(String("POST ") + url + " HTTP/1.1\n"+ "Host: " + host + "\n");
  client.print(String("Host: ") + host + "\n");
  client.print("Content-Type: application/json\n");
  client.print(String("X-Farmy-Api-Key: ") + api_key + "\n");
  client.print("Content-Length: ");
  client.print(data.length());
  client.print("\n\n");

  client.print(data);
  Serial.println("Posted finished -----------");

  delay(500);
  if (!client.connected()) {
      Serial.println();
      Serial.println("disconnecting.");
      client.stop();
  }
}
void loop() {
  String data;
	digitalWrite(LED_PIN, state);
	state = !state;
  if (client.connected()) {

    webSocketClient.getData(data);
    if (data.length() > 0) {
      Serial.print("Received data: ");
      Serial.println(data);
    }

    // capture the value of analog 1, send it along
    pinMode(1, INPUT);
    data = String(analogRead(1));

    webSocketClient.sendData(data);

  } else {
    Serial.println("Client disconnected.");
    while (1) {
      // Hang on disconnect.
    }
  }

  // wait to fully let the client disconnect
  delay(3000);

}
Example #4
0
void loop() {

	static boolean packetActive = false;
	static uint8_t index = 0;
	static boolean readingReturn = false;
	static uint8_t rindex = 0;

	if (!client.connected()) {
		// try to connect to a new client
		client = server.available();
	} else {
		// read data from the connected client
		if (client.available() > 0) {
			char c = client.read();

			if (packetActive) {
				commandBuffer[index] = c;
				commandBuffer[++index] = 0;
				if (c == EOP) {
					comHandler();
					packetActive = false;
				}
			}

			else if (c == SOP) {
				index = 0;
				commandBuffer[index] = c;
				commandBuffer[++index] = 0;
				packetActive = true;
			}

			if (returnReady) {
				client.println(returnBuffer);
				server.println(returnBuffer);
				Serial.println(returnBuffer);
				returnReady = false;
			}
		}
	}

	if (Serial.available() && !returnReady) {
		char s = Serial.read();

		if (s == SOP) {
			readingReturn = true;
			rindex = 0;
		}
		if (readingReturn) {
			returnBuffer[rindex] = s;
			returnBuffer[++rindex] = 0;

			if (s == EOP) {
				returnReady = true;
			}
		}
	}
}
Example #5
0
uint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){
  int res = client.read();
  if(res == -1){
    while(!client.available() && client.connected())
      yield();
    res = client.read();
  }
  return (uint8_t)res;
}
Example #6
0
void Con::TCPhandler(){
   if (this->curType&CON_TCP){
      if (ConSrv.hasClient()){
         if (ConTcp.connected()){
            ConTcp.stop();
         }
         ConTcp=ConSrv.available();
         ConTcp.write("Hello\n",6);
      }  
   }
}
Example #7
0
void connectClients() {
	if (server.hasClient()) {
		if (!serverClient || !serverClient.connected()) {
			if (serverClient) serverClient.stop();
			serverClient = server.available();
		} else {
			//no free/disconnected spot so reject
			WiFiClient rejectClient = server.available();
			rejectClient.stop();
		}
	}
}
void ThingspeakClient::getLastChannelItem(String channelId, String readApiKey) {
  JsonStreamingParser parser;
  parser.setListener(this);
  WiFiClient client;

  // http://api.thingspeak.com/channels/CHANNEL_ID/feeds.json?results=2&api_key=API_KEY
  const char host[] = "api.thingspeak.com";
  String url = "/channels/" + channelId +"/feeds.json?results=1&api_key=" + readApiKey;

  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }


  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

  int retryCounter = 0;
  while(!client.available()) {
    Serial.println(".");
    delay(1000);
    retryCounter++;
    if (retryCounter > 10) {
      return;
    }
  }

  int pos = 0;
  boolean isBody = false;
  char c;

  int size = 0;
  client.setNoDelay(false);
  while(client.connected()) {
    while((size = client.available()) > 0) {
      c = client.read();
      if (c == '{' || c == '[') {
        isBody = true;
      }
      if (isBody) {
        parser.parse(c);
      }
    }
  }
}
Example #9
0
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection:
  if (client.connect("www.hasthelargehadroncolliderdestroyedtheworldyet.com", 80)) {
    Serial5.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET / HTTP/1.1");
    client.println("Host: www.hasthelargehadroncolliderdestroyedtheworldyet.com");
    //client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();

    if( client.connected() )
    {
      Serial5.println("\tClient connected");
      while( client.available() == 0 )
      {
        //Waiting for data
        if( !client.connected() )
        {
          Serial5.println("\tClient disconnected !");
          break;
        }
      }
    }
    else
    {
      Serial5.println("\tClient not connected");
    }

  }
  else {
    // if you couldn't make a connection:
    Serial5.println("\tconnection failed");
  }
}
Example #10
0
void loop() {
  // if there are incoming bytes available 
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

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

    // do nothing forevermore:
    while(true);
  }
}
Example #11
0
void Con::printf(const char *fmt, ...){
   int l;
   char buffer[255];

   l=strlen(fmt);
   va_list ap;
   va_start(ap, fmt);
   ets_vsnprintf(buffer,255, fmt, ap);
   va_end(ap);
   if (curType&CON_SERIAL){ 
      Serial.print(buffer);
   }
   if (this->curType&CON_TCP){ 
      if (ConTcp.connected()){
         ConTcp.print(buffer);
      }
   }
}
void TimeClient::updateTime() {
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect("google.com", httpPort)) {
    Serial.println("connection failed");
    return;
  }
  
  // This will send the request to the server
  client.print(String("GET / HTTP/1.1\r\n") +
               String("Host: google.com\r\n") +
               String("Connection: close\r\n\r\n"));
  int repeatCounter = 0;
  while(!client.available() && repeatCounter < 10) {
    delay(1000); 
    Serial.println(".");
    repeatCounter++;
  }

  String line;

  int size = 0;
  client.setNoDelay(false);
  while(client.connected()) {
    while((size = client.available()) > 0) {
      line = client.readStringUntil('\n');
      line.toUpperCase();
      // example: 
      // date: Thu, 19 Nov 2015 20:25:40 GMT
      if (line.startsWith("DATE: ")) {
        Serial.println(line.substring(23, 25) + ":" + line.substring(26, 28) + ":" +line.substring(29, 31));
        int parsedHours = line.substring(23, 25).toInt();
        int parsedMinutes = line.substring(26, 28).toInt();
        int parsedSeconds = line.substring(29, 31).toInt();
        Serial.println(String(parsedHours) + ":" + String(parsedMinutes) + ":" + String(parsedSeconds));

        localEpoc = (parsedHours * 60 * 60 + parsedMinutes * 60 + parsedSeconds);
        Serial.println(localEpoc);
        localMillisAtUpdate = millis();
      }
    }
  }

}
void WundergroundClient::doUpdate(String url) {
  JsonStreamingParser parser;
  parser.setListener(this);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect("api.wunderground.com", httpPort)) {
    Serial.println("connection failed");
    return;
  }

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: api.wunderground.com\r\n" +
               "Connection: close\r\n\r\n");
  int retryCounter = 0;
  while(!client.available()) {
    delay(1000);
    retryCounter++;
    if (retryCounter > 10) {
      return;
    }
  }

  int pos = 0;
  boolean isBody = false;
  char c;

  int size = 0;
  client.setNoDelay(false);
  while(client.connected()) {
    while((size = client.available()) > 0) {
      c = client.read();
      if (c == '{' || c == '[') {
        isBody = true;
      }
      if (isBody) {
        parser.parse(c);
      }
    }
  }
}
Example #14
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");
}
void next_client() {
  // Listenning for new clients
  client = server.available();
  if (client) {
    Serial.println("New client");
    // bolean to locate when the http request ends
    boolean blank_line = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && blank_line) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: application/json");
            client.println("Access-Control-Allow-Origin: *");
            client.println("Connection: close");
            client.println();
            print_json();
            break;
        }
        if (c == '\n') {
          // when starts reading a new line
          Serial.println();
          blank_line = true;
        }
        else if (c != '\r') {
          // when finds a character on the current line
          Serial.write(c);
          blank_line = false;
        }
      }
    }  
    // closing the client connection
    delay(1);
    client.stop();
    Serial.println("Client disconnected.");
  }
}
Example #16
0
void WebServer::handleClient()
{
  WiFiClient client = _server.available();
  if (!client) {
    return;
  }

#ifdef DEBUG
  DEBUG_OUTPUT.println("New client");
#endif

  // Wait for data from client to become available
  uint16_t maxWait = HTTP_MAX_DATA_WAIT;
  while(client.connected() && !client.available() && maxWait--){
    delay(1);
  }

  if (!_parseRequest(client)) {
    return;
  }

  _currentClient = client;
  _handleRequest();
}
Example #17
0
void ArduinoOTAClass::_runUpdate() {
  if (!Update.begin(_size, _cmd)) {
#ifdef OTA_DEBUG
    OTA_DEBUG.println("Update Begin Error");
#endif
    if (_error_callback) {
      _error_callback(OTA_BEGIN_ERROR);
    }
    _udp_ota->listen(*IP_ADDR_ANY, _port);
    _state = OTA_IDLE;
    return;
  }
  Update.setMD5(_md5.c_str());
  WiFiUDP::stopAll();
  WiFiClient::stopAll();

  if (_start_callback) {
    _start_callback();
  }
  if (_progress_callback) {
    _progress_callback(0, _size);
  }

  WiFiClient client;
  if (!client.connect(_ota_ip, _ota_port)) {
#ifdef OTA_DEBUG
    OTA_DEBUG.printf("Connect Failed\n");
#endif
    _udp_ota->listen(*IP_ADDR_ANY, _port);
    if (_error_callback) {
      _error_callback(OTA_CONNECT_ERROR);
    }
    _state = OTA_IDLE;
  }

  uint32_t written, total = 0;
  while (!Update.isFinished() && client.connected()) {
    int waited = 1000;
    while (!client.available() && waited--)
      delay(1);
    if (!waited){
#ifdef OTA_DEBUG
      OTA_DEBUG.printf("Receive Failed\n");
#endif
      _udp_ota->listen(*IP_ADDR_ANY, _port);
      if (_error_callback) {
        _error_callback(OTA_RECEIVE_ERROR);
      }
      _state = OTA_IDLE;
    }
    written = Update.write(client);
    if (written > 0) {
      client.print(written, DEC);
      total += written;
      if(_progress_callback) {
        _progress_callback(total, _size);
      }
    }
  }

  if (Update.end()) {
    client.print("OK");
    client.stop();
    delay(10);
#ifdef OTA_DEBUG
    OTA_DEBUG.printf("Update Success\nRebooting...\n");
#endif
    if (_end_callback) {
      _end_callback();
    }
    ESP.restart();
  } else {
    _udp_ota->listen(*IP_ADDR_ANY, _port);
    if (_error_callback) {
      _error_callback(OTA_END_ERROR);
    }
    Update.printError(client);
#ifdef OTA_DEBUG
    Update.printError(OTA_DEBUG);
#endif
    _state = OTA_IDLE;
  }
}
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 #19
0
bool ESPWebServer::handleClientRequest(ServoControl &servoInteraction, String htmlPage)
{ 
    bool clientHandled = false;

    WiFiClient client = m_server.available();   // Listen for incoming clients

    if (client) 
    {                            
        Serial.println("New Client.");
        String header = "";
        String currentLine = "";                // make a String to hold incoming data from the client
        while (client.connected())
        {            
            if (client.available()) 
            {
                char c = client.read();             // read a byte, then
                Serial.write(c);                    // print it out the serial monitor
                header += c;
                if (c == '\n') 
                {
                    // if the current line is blank, you got two newline characters in a row.
                    // that's the end of the client HTTP request, so send a response:
                    if (currentLine.length() == 0) 
                    {
                        // checks if the client signaled an interaction
                        int index;
                        servoInteraction.type = NONE;
                        if ((index = header.indexOf("GET /openBlinds")) >= 0) 
                        {
                            servoInteraction.type = OPEN_BLINDS;
                        }
                        else if ((index = header.indexOf("GET /closeBlinds")) >= 0) 
                        {
                            servoInteraction.type = CLOSE_BLINDS;
                        }
                        else if ((index = header.indexOf("GET /setOpenBlinds")) >= 0) 
                        {
                            String passedValue;
                            index += 20;
                            char newChar = header.charAt(index);
                            while(newChar != '"')
                            {
                              passedValue += newChar;
                              index++;
                              newChar = header.charAt(index);
                            }

                            servoInteraction.type = SET_OPEN;
                            servoInteraction.setting = passedValue.toInt();
                        }
                        else if ((index = header.indexOf("GET /setCloseBlinds")) >= 0) 
                        {
                            String passedValue;
                            index += 21;
                            char newChar = header.charAt(index);
                            while(newChar != '"')
                            {
                              passedValue += newChar;
                              index++;
                              newChar = header.charAt(index);
                            }

                            servoInteraction.type = SET_CLOSE;
                            servoInteraction.setting = passedValue.toInt();
                        }

                        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                        // and a content-type so the client knows what's coming, then a blank line:
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-type:text/html");
                        client.println("Connection: close");
                        client.println();
                        
                        // Display the HTML web page
                        client.println(htmlPage);

                        // Break out of the while loop
                        clientHandled = true;
                        break;
                    } 
                    else
                    { 
                        // if you got a newline, then clear currentLine
                        currentLine = "";
                    }
                } 
                else if (c != '\r')
                {
                    // if you got anything else but a carriage return character,
                    currentLine += c;      // add it to the end of the currentLine
                }
            }
        }
        // Close the connection
        client.stop();
        Serial.println("Client disconnected.");
        Serial.println(""); 
    }

    return clientHandled;
}
Example #20
0
File: wifi.cpp Project: energia/emt
/*
 *  ======== apLoop ========
 */
__extern void apLoop()
{
    /* Did a client connect/disconnect since the last time we checked? */
    int a = WiFi.getTotalDevices();
    if (a != num_clients) {
        if (a > num_clients) {  // new Client connected
            int i;
            /* display all clients on the network */
            Serial.println("New client connected. All clients:");
            for (i = 0; i < a; i++) {
                Serial.print("  Client #");
                Serial.print(i);
                Serial.print(" at IP address = ");
                Serial.print(WiFi.deviceIpAddress(i));
                Serial.print(", MAC = ");
                Serial.println(WiFi.deviceMacAddress(i));
            }
        } 
        else {                  // a Client disconnected
            Serial.print("Client disconnected, ");
            Serial.print(a);
            Serial.println(" clients remaining.");
        }    
        num_clients = a;
    }

    if (num_clients > 0) {
        /* listen for incoming clients */
        WiFiClient client = server.available();

        if (client) {
            /* if there's a client, read and process commands */
            Serial.print("new client socket: ");
            Serial.println(++num_sockets);

            static char buffer[80] = {0};
            int bufLen = 0;

            /* while connected to the client, read commands and send results */
            while (client.connected()) {

                /* if there's a byte to read from the client .. */
                if (client.available()) {
                    /* copy it to the command buffer, byte at a time */
                    char c = client.read();

                    /* ignore bogus characters */
                    if (c == '\0' || c == '\r') continue;

                    /* never overrun the command buffer */
                    if (bufLen >= (int)(sizeof (buffer))) { 
                        bufLen = sizeof (buffer) - 1;
                    }
                    buffer[bufLen++] = c;

                    /* if there's a new line, we have a complete command */
                    if (c == '\n') {
                        doCommand(buffer, bufLen, client);
                        /* reset command buffer index to get next command */
                        bufLen = 0;
                    }
                }
            }

            /* client disconnected, close the connection */
            client.stop();
            Serial.println("client socket disconnected");
        }
    }

    delay(100);
}
Example #21
0
/*
 *  ======== apLoop ========
 */
__extern void apLoop()
{
    /* Did a client connect/disconnect since the last time we checked? */
    int a = WiFi.getTotalDevices();
    if (a != num_clients) {
        if (a > num_clients) {  // new Client connected
            int i;
            digitalWrite(MAIN_LED_PIN, !digitalRead(MAIN_LED_PIN));
            /* display all clients on the network */
            Serial.println("New client connected. All clients:");
            for (i = 0; i < a; i++) {
                Serial.print("  Client #");
                Serial.print(i);
                Serial.print(" at IP address = ");
                Serial.print(WiFi.deviceIpAddress(i));
                Serial.print(", MAC = ");
                Serial.println(WiFi.deviceMacAddress(i));
            }
        } 
        else {                  // a Client disconnected
            digitalWrite(MAIN_LED_PIN, !digitalRead(MAIN_LED_PIN));
            Serial.print("Client disconnected, ");
            Serial.print(a);
            Serial.println(" clients remaining.");
        }    
        num_clients = a;
    }

    if (num_clients > 0) {
        /* listen for incoming clients */
        WiFiClient client = server.available();

        if (client) {
            /* if there's a client, read and process commands */
            Serial.print("new client socket: ");
            Serial.println(++num_sockets);

            static char buffer[64] = {0};
            int bufLen = 0;

            /* while connected to the client, read commands and send results */
            unsigned int lapse = 0;
            unsigned int start = millis();
            while (client.connected()) {

                /* if there's a byte to read from the client .. */
                if (client.available()) {
                    /* copy it to the command buffer, byte at a time */
                    char c = client.read();

                    /* ignore bogus characters */
                    if (c == '\0' || c == '\r') continue;
                    
                    /* never overrun the command buffer */
                    if (bufLen >= (int)(sizeof (buffer))) { 
                        bufLen = sizeof (buffer) - 1;
                    }
                    buffer[bufLen++] = c;
                    //Serial.print(num_sockets); Serial.print(": ");
                    //Serial.println((int)c);

                    /* if there's a new line, we have a complete command */
                    if (c == '\n') {
                        doCommand(buffer, bufLen, client);
                        /* reset command buffer index to get next command */
                        bufLen = 0;
                    }

                    lapse = 0;
                    start = millis();
                }
                else {
                    lapse = millis() - start;
                }
            }

            Serial.print("client socket disconnected: lapse = ");
            Serial.println(lapse);

            /* client disconnected or timed out, close the connection */
            client.stop();

            /* disconnect => implicitly stop the motor */
            motorWASD = ' ';
        }
    }

    /* check for new connections 2 times per second */
    delay(500);
}
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 #23
0
bool ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){

#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Parse Form: Boundary: ");
  DEBUG_OUTPUT.print(boundary);
  DEBUG_OUTPUT.print(" Length: ");
  DEBUG_OUTPUT.println(len);
#endif
  String line;
  int retry = 0;
  do {
    line = client.readStringUntil('\r');
    ++retry;
  } while (line.length() == 0 && retry < 3);

  client.readStringUntil('\n');
  //start reading the form
  if (line == ("--"+boundary)){
    RequestArgument* postArgs = new RequestArgument[32];
    int postArgsLen = 0;
    while(1){
      String argName;
      String argValue;
      String argType;
      String argFilename;
      bool argIsFile = false;

      line = client.readStringUntil('\r');
      client.readStringUntil('\n');
      if (line.startsWith("Content-Disposition")){
        int nameStart = line.indexOf('=');
        if (nameStart != -1){
          argName = line.substring(nameStart+2);
          nameStart = argName.indexOf('=');
          if (nameStart == -1){
            argName = argName.substring(0, argName.length() - 1);
          } else {
            argFilename = argName.substring(nameStart+2, argName.length() - 1);
            argName = argName.substring(0, argName.indexOf('"'));
            argIsFile = true;
#ifdef DEBUG_ESP_HTTP_SERVER
            DEBUG_OUTPUT.print("PostArg FileName: ");
            DEBUG_OUTPUT.println(argFilename);
#endif
            //use GET to set the filename if uploading using blob
            if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename");
          }
#ifdef DEBUG_ESP_HTTP_SERVER
          DEBUG_OUTPUT.print("PostArg Name: ");
          DEBUG_OUTPUT.println(argName);
#endif
          argType = "text/plain";
          line = client.readStringUntil('\r');
          client.readStringUntil('\n');
          if (line.startsWith("Content-Type")){
            argType = line.substring(line.indexOf(':')+2);
            //skip next line
            client.readStringUntil('\r');
            client.readStringUntil('\n');
          }
#ifdef DEBUG_ESP_HTTP_SERVER
          DEBUG_OUTPUT.print("PostArg Type: ");
          DEBUG_OUTPUT.println(argType);
#endif
          if (!argIsFile){
            while(1){
              line = client.readStringUntil('\r');
              client.readStringUntil('\n');
              if (line.startsWith("--"+boundary)) break;
              if (argValue.length() > 0) argValue += "\n";
              argValue += line;
            }
#ifdef DEBUG_ESP_HTTP_SERVER
            DEBUG_OUTPUT.print("PostArg Value: ");
            DEBUG_OUTPUT.println(argValue);
            DEBUG_OUTPUT.println();
#endif

            RequestArgument& arg = postArgs[postArgsLen++];
            arg.key = argName;
            arg.value = argValue;

            if (line == ("--"+boundary+"--")){
#ifdef DEBUG_ESP_HTTP_SERVER
              DEBUG_OUTPUT.println("Done Parsing POST");
#endif
              break;
            }
          } else {
            _currentUpload.status = UPLOAD_FILE_START;
            _currentUpload.name = argName;
            _currentUpload.filename = argFilename;
            _currentUpload.type = argType;
            _currentUpload.totalSize = 0;
            _currentUpload.currentSize = 0;
#ifdef DEBUG_ESP_HTTP_SERVER
            DEBUG_OUTPUT.print("Start File: ");
            DEBUG_OUTPUT.print(_currentUpload.filename);
            DEBUG_OUTPUT.print(" Type: ");
            DEBUG_OUTPUT.println(_currentUpload.type);
#endif
            if(_currentHandler && _currentHandler->canUpload(_currentUri))
              _currentHandler->upload(*this, _currentUri, _currentUpload);
            _currentUpload.status = UPLOAD_FILE_WRITE;
            uint8_t argByte = _uploadReadByte(client);
readfile:
            while(argByte != 0x0D){
              if (!client.connected()) return _parseFormUploadAborted();
              _uploadWriteByte(argByte);
              argByte = _uploadReadByte(client);
            }

            argByte = _uploadReadByte(client);
            if (!client.connected()) return _parseFormUploadAborted();
            if (argByte == 0x0A){
              argByte = _uploadReadByte(client);
              if (!client.connected()) return _parseFormUploadAborted();
              if ((char)argByte != '-'){
                //continue reading the file
                _uploadWriteByte(0x0D);
                _uploadWriteByte(0x0A);
                goto readfile;
              } else {
                argByte = _uploadReadByte(client);
                if (!client.connected()) return _parseFormUploadAborted();
                if ((char)argByte != '-'){
                  //continue reading the file
                  _uploadWriteByte(0x0D);
                  _uploadWriteByte(0x0A);
                  _uploadWriteByte((uint8_t)('-'));
                  goto readfile;
                }
              }

              uint8_t endBuf[boundary.length()];
              client.readBytes(endBuf, boundary.length());

              if (strstr((const char*)endBuf, boundary.c_str()) != NULL){
                if(_currentHandler && _currentHandler->canUpload(_currentUri))
                  _currentHandler->upload(*this, _currentUri, _currentUpload);
                _currentUpload.totalSize += _currentUpload.currentSize;
                _currentUpload.status = UPLOAD_FILE_END;
                if(_currentHandler && _currentHandler->canUpload(_currentUri))
                  _currentHandler->upload(*this, _currentUri, _currentUpload);
#ifdef DEBUG_ESP_HTTP_SERVER
                DEBUG_OUTPUT.print("End File: ");
                DEBUG_OUTPUT.print(_currentUpload.filename);
                DEBUG_OUTPUT.print(" Type: ");
                DEBUG_OUTPUT.print(_currentUpload.type);
                DEBUG_OUTPUT.print(" Size: ");
                DEBUG_OUTPUT.println(_currentUpload.totalSize);
#endif
                line = client.readStringUntil(0x0D);
                client.readStringUntil(0x0A);
                if (line == "--"){
#ifdef DEBUG_ESP_HTTP_SERVER
                  DEBUG_OUTPUT.println("Done Parsing POST");
#endif
                  break;
                }
                continue;
              } else {
                _uploadWriteByte(0x0D);
                _uploadWriteByte(0x0A);
                _uploadWriteByte((uint8_t)('-'));
                _uploadWriteByte((uint8_t)('-'));
                uint32_t i = 0;
                while(i < boundary.length()){
                  _uploadWriteByte(endBuf[i++]);
                }
                argByte = _uploadReadByte(client);
                goto readfile;
              }
            } else {
              _uploadWriteByte(0x0D);
              goto readfile;
            }
            break;
          }
        }
      }
    }

    int iarg;
    int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount;
    for (iarg = 0; iarg < totalArgs; iarg++){
      RequestArgument& arg = postArgs[postArgsLen++];
      arg.key = _currentArgs[iarg].key;
      arg.value = _currentArgs[iarg].value;
    }
    if (_currentArgs) delete[] _currentArgs;
    _currentArgs = new RequestArgument[postArgsLen];
    for (iarg = 0; iarg < postArgsLen; iarg++){
      RequestArgument& arg = _currentArgs[iarg];
      arg.key = postArgs[iarg].key;
      arg.value = postArgs[iarg].value;
    }
    _currentArgCount = iarg;
    if (postArgs) delete[] postArgs;
    return true;
  }
#ifdef DEBUG_ESP_HTTP_SERVER
  DEBUG_OUTPUT.print("Error: line: ");
  DEBUG_OUTPUT.println(line);
#endif
  return false;
}
Example #24
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 #25
0
AJ_Status AJ_Net_Recv(AJ_IOBuffer* buf, uint32_t len, uint32_t timeout)
{
    AJ_Status status = AJ_ERR_READ;
    uint32_t ret;
    uint32_t rx = AJ_IO_BUF_SPACE(buf);
    uint32_t recvd = 0;
    unsigned long Recv_lastCall = millis();

    // first we need to clear out our buffer
    uint32_t M = 0;

    AJ_InfoPrintf(("AJ_Net_Recv(buf=0x%p, len=%d., timeout=%d.)\n", buf, len, timeout));

    if (rxLeftover != 0) {
        // there was something leftover from before,
        AJ_InfoPrintf(("AJ_NetRecv(): leftover was: %d\n", rxLeftover));
        M = min(rx, rxLeftover);
        memcpy(buf->writePtr, rxDataStash, M);  // copy leftover into buffer.
        buf->writePtr += M;  // move the data pointer over
        memmove(rxDataStash, rxDataStash + M, rxLeftover - M); // shift left-overs toward the start.
        rxLeftover -= M;
        recvd += M;

        // we have read as many bytes as we can
        // higher level isn't requesting any more
        if (recvd == rx) {
            AJ_InfoPrintf(("AJ_Net_Recv(): status=AJ_OK\n"));
            return AJ_OK;
        }
    }

    if ((M != 0) && (rxLeftover != 0)) {
        AJ_InfoPrintf(("AJ_Net_REcv(): M was: %d, rxLeftover was: %d\n", M, rxLeftover));
    }

    // wait for data to become available
    // time out if nothing arrives
    while (g_client.connected() &&
           g_client.available() == 0 &&
           (millis() - Recv_lastCall < timeout)) {
        delay(50); // wait for data or timeout
    }

    // return timeout if nothing is available
    AJ_InfoPrintf(("AJ_Net_Recv(): millis %d, Last_call %d timeout %d Avail: %d\n", millis(), Recv_lastCall, timeout, g_client.available()));
    if (g_client.connected() && (millis() - Recv_lastCall >= timeout) && (g_client.available() == 0)) {
        AJ_InfoPrintf(("AJ_Net_Recv(): timeout. status=AJ_ERR_TIMEOUT\n"));
        return AJ_ERR_TIMEOUT;
    }

    if (g_client.connected()) {
        uint32_t askFor = rx;
        askFor -= M;
        AJ_InfoPrintf(("AJ_Net_Recv(): ask for: %d\n", askFor));
        ret = g_client.read(buf->writePtr, askFor);
        AJ_InfoPrintf(("AJ_Net_Recv(): read(): ret %d  askfor %d\n", ret, askFor));

        if (askFor < ret) {
            AJ_InfoPrintf(("AJ_Net_Recv(): BUFFER OVERRUN: askFor=%u, ret=%u\n", askFor, ret));
        }

        if (ret == -1) {
            AJ_ErrPrintf(("AJ_Net_Recv(): read() failed. status=AJ_ERR_READ\n"));
            status = AJ_ERR_READ;
        } else {
            AJ_InfoPrintf(("AJ_Net_Recv(): ret now %d\n", ret));
            AJ_DumpBytes("Recv", buf->writePtr, ret);

            if (ret > askFor) {
                AJ_InfoPrintf(("AJ_Net_Recv(): new leftover %d\n", ret - askFor));
                // now shove the extra into the stash
                memcpy(rxDataStash + rxLeftover, buf->writePtr + askFor, ret - askFor);
                rxLeftover += (ret - askFor);
                buf->writePtr += rx;
            } else {
                buf->writePtr += ret;
            }
            status = AJ_OK;
        }
    }

    return status;
}
Example #26
0
void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {
      // Print local IP address and start web server
      Serial.println("");
      Serial.println("WiFi connected.");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      //server.begin();

      // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /5/on") >= 0) {
              Serial.println("GPIO 5 on");
              output5State = "on";
              digitalWrite(output5, HIGH);
            } else if (header.indexOf("GET /5/off") >= 0) {
              Serial.println("GPIO 5 off");
              output5State = "off";
              digitalWrite(output5, LOW);
            } else if (header.indexOf("GET /4/on") >= 0) {
              Serial.println("GPIO 4 on");
              output4State = "on";
              digitalWrite(output4, HIGH);
            } else if (header.indexOf("GET /4/off") >= 0) {
              Serial.println("GPIO 4 off");
              output4State = "off";
              digitalWrite(output4, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #77878A;}</style></head>");

            // Web Page Heading
            client.println("<body><h1>ESP8266 Web Server</h1>");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("<p>GPIO 5 - State " + output5State + "</p>");
            // If the output5State is off, it displays the ON button
            if (output5State=="off") {
              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");
            }

            // Display current state, and ON/OFF buttons for GPIO 4
            client.println("<p>GPIO 4 - State " + output4State + "</p>");
            // If the output4State is off, it displays the ON button
            if (output4State=="off") {
              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}