/*
 *  Simple HTTP get webclient test
 */

#include <ESP8266WiFi.h>

const char* ssid     = "hazard18";
const char* password = "pu1f0xylu1";

const char* host = "192.168.1.97";

void setup() {
  pinMode(0, OUTPUT);
  pinMode(4, INPUT);
  pinMode(A0, INPUT);

  
  Serial.begin(115200);
  delay(100);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {

  delay(500);
  ++value;


  Serial.print("connecting to ");
  Serial.println(host);
  
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 8084;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  
  // We now create a URI for the request
  
  int gpio4 = digitalRead(4);
  int gpioA0 = analogRead(A0);
  
  String url = "/gpio?status=" + String(gpio4) + "&a0=" + String(gpioA0);
  Serial.print("Requesting URL (" + String(value) + ")" + " : ");
  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");
  delay(500);


  
  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
    if (line.toInt() == 0){
      Serial.print("at 0");
      digitalWrite(0, LOW);
    }else{
      Serial.print("at 1");
      digitalWrite(0, HIGH);
    }
  }
  
  Serial.println();
  Serial.println("closing connection");
}
