//Bibliotecas
#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266HTTPClient.h>

//Configuração Wifi
const char *ssid = "IFSC";
const char *password = "campuschapeco";
WiFiClient client;

//Pinout
#define D5 14 // botão
#define D3 0  // LED

void setup() {
  pinMode(D3, OUTPUT);
  pinMode(D5, INPUT);
  digitalWrite(D3, LOW);  

  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  Serial.print("Conectando");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Conectado!");
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());
  Serial.print("MAC: ");
  Serial.println(WiFi.macAddress());
}

// Envio para o servidor
void EnviaServer(String postData){
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    http.begin(client, "http://modulo8.migueldebarba.com.br/tools/insertleitura.php");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    int httpCode = http.POST(postData);
    String payload = http.getString();

    Serial.println("httpCode: " + String(httpCode));
    Serial.println("payload: " + payload);

    http.end();
  } else {
    Serial.println("WiFi caiu 💀");
  }
}

void loop() {
  if (digitalRead(D5) == HIGH) {

    digitalWrite(D3, HIGH);

    String idmac = WiFi.macAddress();    
    float temperatura = random(0, 100);
    float umidade = random(0, 100);  
    float luz = random(0, 1024);   

    String postData = 
      "idmac=" + idmac +
      "&umidade=" + String(umidade) +
      "&temperatura=" + String(temperatura) +
      "&luz=" + String(luz) +
      "&from=ESP";

    EnviaServer(postData);

    delay(1000);
    digitalWrite(D3, LOW);
  }
}