#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>

const char *ssid = "IFSC";
const char *password = "campuschapeco";

WiFiClientSecure client;

#define D3 0 

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

  Serial.begin(9600);

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

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

  client.setInsecure();
}

void EnviaServer(String postData) {
  HTTPClient http;

  http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);

  String url = "https://modulo8.migueldebarba.com.br/felipearthur/insertleitura.php";

  Serial.println("Enviando para:");
  Serial.println(url);
  Serial.println("Dados:");
  Serial.println(postData);

  if (http.begin(client, url)) {

    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("Resposta: " + payload);

    http.end();

  } else {
    Serial.println("Erro ao iniciar conexão HTTP");
  }
}

void loop() {

  digitalWrite(D3, HIGH);

  String idmac = WiFi.macAddress();
  String from = "ESP8266";

  float temperatura = random(0, 55);
  float umidade = random(0, 100);
  float luz = random(0, 1024);
  float altura = random(0, 200);
  float largura = random(0, 200);

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

  EnviaServer(postData);

  digitalWrite(D3, LOW);

  delay(5000); 
}