/*
    WiFi Setting for ESP8266 + ESP32

*/

// verhindert doppelte Verwendung
#ifndef MY_WIFI_H      // if not define then define .... endif
#define MY_WIFI_H


#define ESP8266  // uncomment for ESP8266
//#define ESP32
#ifdef ESP8266
  #include <ESP8266WiFi.h>
#else
  #include <WiFi.h>      // für ESP32
#endif

// hard coded WiFi data
const char* ssid      = "XXX";
const char* password  = "XXX";

//#define STATIC_IP      // uncomment for static IP, set IP below
#ifdef STATIC_IP
  IPAddress ip(192,168,0,120);
  IPAddress gateway(192,168,0,1);
  IPAddress subnet(255,255,255,0);
#endif

#define WIFI_TIMEOUT 30000              // checks WiFi every ...ms. Reset after this time, if WiFi cannot reconnect.
unsigned long last_wifi_check_time = 0;

#define BUILT_IN_LED   2   // GPIO2 for D1mini

// * Connect to WiFi. If no connection is made within WIFI_TIMEOUT, ESP gets resettet.
void initWiFi() {
  //WiFi.config(ip, dns, gateway, subnet);
  pinMode(BUILT_IN_LED, OUTPUT);   // LED_BUILTIN
  
  WiFi.mode(WIFI_STA);
  #ifdef STATIC_IP  
    WiFi.config(ip, gateway, subnet);
  #endif
  
//  if (!WiFi.config(local_IP, gateway, subnet, dns)) {
//    Serial.println("Wifi STA Failed to configure");
//  }  
  
  WiFi.begin(ssid, password);
  Serial.print("\n\nStart connecting to WiFi ..");
  
  unsigned long connect_start = millis();  
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    digitalWrite(BUILT_IN_LED, !digitalRead(BUILT_IN_LED));  // LED blink fast
    delay(500);
	
    if(millis() - connect_start > WIFI_TIMEOUT) {
      Serial.println();
      Serial.print("Tried ");
      Serial.print(WIFI_TIMEOUT);
      Serial.print("ms. Resetting ESP now.");
      ESP.reset();
    }	
  }
  digitalWrite(BUILT_IN_LED, HIGH);  // LED off
  
  Serial.print("\nWiFi connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
//  Serial.println(WiFi.softAPIP());  // by default, the NTP will be started after 60 secs  // Print ESP MAC Address
  Serial.println(WiFi.localIP());
  Serial.print("MAC address:  ");
  Serial.println(WiFi.macAddress());

   //The ESP8266 tries to reconnect automatically when the connection is lost
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
}

void checkWiFi() {
  if(millis() - last_wifi_check_time > WIFI_TIMEOUT) {
    Serial.print("Checking WiFi... ");
    if(WiFi.status() != WL_CONNECTED) {
      Serial.println("WiFi connection lost. Reconnecting...");
      initWiFi();
    } else {
      Serial.println("OK");
    }
    last_wifi_check_time = millis();
  }
}


#endif  // MY_WIFI_H
