/*
 * Sources:
 * https://www.arduino.cc/en/Tutorial/Button
 * https://techtutorialsx.com/2017/05/19/esp32-http-get-requests/
 */

#include <WiFi.h>
#include <HTTPClient.h>
 
const char* ssid     = "LeWe";
const char* password = "5275274365464843";
const char* bellUrl = "http://192.168.1.117/bell/on";

const int buttonPin = 21;    // the number of the pushbutton pin
const int ledPin =  23;      // the number of the LED pin
int buttonState = 0;

 
void setup() {

  Serial.begin(115200);
  btStop(); // turn off bluetooth

  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  connectWifi();

}
 
void loop() {
 
  if ((WiFi.status() == WL_CONNECTED)) {

    buttonState = digitalRead(buttonPin);
    delay(100);

    if (buttonState == HIGH) {
      digitalWrite(ledPin, HIGH);
      
      HTTPClient http;
   
      http.begin(bellUrl);
      Serial.print("GET ");
      Serial.println(bellUrl);
      int httpCode = http.GET();
   
      if (httpCode > 0) {
          //String payload = http.getString();
          Serial.println(httpCode);
          //Serial.println(payload);
        }
      else {
        Serial.println("Error on HTTP request");
      }
   
      http.end();
      delay(200);
    }
    else {
      digitalWrite(ledPin, LOW); 
    }
  }
  else {
    Serial.println("WiFi not connected!");
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
    delay(50);
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
    connectWifi();
  }
 
}

void connectWifi() {
  boolean ledStatus = false;
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    ledStatus = !ledStatus;
    digitalWrite(ledPin, ledStatus);
  }
 
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
