#include <WiFi.h>
#include <WiFiClient.h>

/*
Pasos: 
1. En https://dweet.io/play/ condigure el siguiente parametro del POST con:
   
   -> Parameter: node_udea_00X

2. En https://dweet.io/follow coloque el nombre de la cosa:

   -> Parameter: node_udea_00X

3. Con el ESP32 observe lo que sucede en la pagina anterior
*/

// WiFi parameters
const char* ssid = "Wokwi-GUEST";
const char* password = "";

const int analogInPin = 34; // GPIO34
int sensorValue = 0;        // Value read from the pot

String thing_name = "node_udea_00X"; // Cambie el X por un numero

// Host
const char* host = "dweet.io";

void setup() {
  // Start Serial
  Serial.begin(115200);
  delay(10);  

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  // WiFi.begin(ssid, password);
  WiFi.begin(ssid, password, 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

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

void loop() {
  Serial.print("Connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // Read the analog in value
  sensorValue  = analogRead(analogInPin);


  // We now create a URI for the request
  String url = "/dweet/for/" + thing_name + "?value=" + String(sensorValue);

  // Send request
  Serial.print("Requesting URL: ");
  Serial.println(url);
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 1000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  
  // Read all the lines from the answer
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  // Close connecting
  Serial.println();
  Serial.println("closing connection");

}