// Neil Gershenfeld 11/12/19
//
// This work may be reproduced, modified, distributed,
//

#include <WiFi.h>

const char* ssid = "";
const char* password = "";
const char* host = "fab.cba.mit.edu";
const char* URL = "/classes/863.19/Harvard/people/joonhaenglee/week11/NetworkingTest/week11_Test.html";
const int port = 80;

WiFiClient client;

int lineNum = 0;
int Value = 0;

void setup() {
  Serial.begin(115200);
  printf("\nConnecting to WiFi ");
  WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    printf(".");
    }
  printf("\nWiFi connected with address %s\n",WiFi.localIP().toString().c_str());
  printf("Connecting to host %s\n",host);
  delay(1000);
  
  if (!client.connect(host,port)) {
    printf("Connection failed\n");
    return;
    }
  
  printf("Requesting URL %s\n\n",URL);
  client.print(String("GET ")
     + URL
     + " HTTP/1.1\r\n"
     + "Host: "+host+"\r\n"
     + "Connection: close\r\n\r\n");
  while (client.available() == 0)
    ;
  printf("Received response:\n");

  
  while(client.available()) {
    String line = client.readStringUntil('\r');
    lineNum++;
    //Serial.print(String(lineNum)+ ": ");
    //Serial.print(line);
    if (lineNum == 11) Serial.print(line);  
    }

  lineNum = 0;

  printf("\n Loop Start, once in 1 sec \n");
  }
  

void loop()
{
  //read only once in a second
  delay(1000);

  //something same as setup
  if (!client.connect(host,port)) {
    printf("Connection failed\n");
    return;
    }
  client.print(String("GET ")
     + URL
     + " HTTP/1.1\r\n"
     + "Host: "+host+"\r\n"
     + "Connection: close\r\n\r\n");
  while (client.available() == 0)
    ;
  while(client.available()) {
    String line = client.readStringUntil('\r');
    lineNum++;
    if (lineNum == 11) {
      if ( line.toInt() != Value){ 
        Serial.print(line); 
        Value = line.toInt();
      }
    } 
    }
  lineNum = 0;
  }