#include <ESP8266WiFi.h>	
#include <SPI.h>

const char* ssid = "Pi_AP";			// network SSID
const char* password = "raspberry";	// network password

String inputString = "";         // a string to hold incoming data
String uploadString;
boolean stringComplete = false;  // whether the string is complete

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  
  // initialize serial:
  Serial.begin(9600);
  delay(10);

  inputString.reserve(20);
  
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);		// start connecting the network 
  
  while (WiFi.status() != WL_CONNECTED) {	// break when the connection is set
    delay(500);
    Serial.print(".");
  }
  
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
    
}

void loop(){
  
    serialEvent(); //call the function
    delay(500);
    
    // Check if a client has connected
    WiFiClient client = server.available();
    client.flush();   // discard all the data hasn't been uploaded
    
    if (stringComplete) {
      
    uploadString = inputString;
    
    Serial.println("data captured");
    Serial.println(inputString);

    // clear the string:
    inputString = "";
    stringComplete = false;
    Serial.println("data cleared");
  }
  
  client.println(uploadString); // keep uploading the data to keep the server running
  delay(10);
  Serial.println("data uploaded");

}

void serialEvent() {
  Serial.println("...");
  int state = Serial.available();
  Serial.println(state);
  while (Serial.available()) {
    // get the new byte:
    Serial.println("serial available starting capture");
    char inChar = (char)Serial.read();  //read the data from serial port
    Serial.println(inChar);
    // add it to the inputString:
    inputString += inChar;
    Serial.println(inputString);
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {   // starting uploading when receive a '\n'
      stringComplete = true;
    }    
  } 
}