#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <DNSServer.h>
//#include <ESP8266mDNS.h>
#include <EEPROM.h>

#include <OneWire.h>
#include <DallasTemperature.h>
// added from ap11
#include <DHT.h>
#include <MAX31855.h>

#include <Wire.h>
#include <Adafruit_MPL115A2.h>
#define BME280_ADDRESS 0x76
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

unsigned long int hum_raw,temp_raw,pres_raw;
signed long int t_fine;

uint16_t dig_T1;
 int16_t dig_T2;
 int16_t dig_T3;
uint16_t dig_P1;
 int16_t dig_P2;
 int16_t dig_P3;
 int16_t dig_P4;
 int16_t dig_P5;
 int16_t dig_P6;
 int16_t dig_P7;
 int16_t dig_P8;
 int16_t dig_P9;
 int8_t  dig_H1;
 int16_t dig_H2;
 int8_t  dig_H3;
 int16_t dig_H4;
 int16_t dig_H5;
 int8_t  dig_H6;
    double temp_act = 0.0, press_act = 0.0,hum_act=0.0;
    signed long int temp_cal;
    unsigned long int press_cal,hum_cal;
    
Adafruit_MPL115A2 mpl115a2;

Adafruit_7segment matrix = Adafruit_7segment();

const char* host = "time.nist.gov"; // Round-robin DAYTIME protocol
// end of add from ap11
/*
 * This example serves a "hello world" on a WLAN and a SoftAP at the same time.
 * The SoftAP allow you to configure WLAN parameters at run time. They are not setup in the sketch but saved on EEPROM.
 * 
 * Connect your computer or cell phone to wifi network ESP_ap with password 12345678. A popup may appear and it allow you to go to WLAN config. If it does not then navigate to http://192.168.4.1/wifi and config it there.
 * Then wait for the module to connect to your wifi and take note of the WLAN IP it got. Then you can disconnect from ESP_ap and return to your regular WLAN.
 * 
 * Now the ESP8266 is in your network. You can reach it through http://192.168.x.x/ (the IP you took note of) or maybe at http://esp8266.local too.
 * 
 * This is a captive portal because through the softAP it will redirect any http request to http://192.168.4.1/
 */
 
/* Set these to your desired softAP credentials. They are not configurable at runtime */
//const char *softAP_ssid = "AAAP12";
String softAP_ssid = "AP-";
//const char *softAP_password = "12345678";
String softAP_password = "";

/* hostname for mDNS. Should work at least on windows. Try http://esp8266.local */
const char *myHostname = "AllAuto";

/* Don't set this wifi credentials. They are configurated at runtime and stored on EEPROM */
// char ssid[32] = "";
// char password[32] = "";

int connRes = 0 ;

// DNS server
const byte DNS_PORT = 53;

/* Soft AP network parameters */
IPAddress apIP(192, 168, 4, 1);
IPAddress netMsk(255, 255, 255, 0);
DNSServer dnsServer;
// Web server
ESP8266WebServer server(80);

/** Should I connect to WLAN asap? */
boolean connect;

/** Last time I tried to connect to WLAN */
long lastConnectTry = 0;

/** Current WLAN status */
int status = WL_IDLE_STATUS;

String connectnet = "" ;
// added on sept 10, 2016
String req = "" ;
// added code from A11
int ln = 0;
String dateTime = "";
String TimeDate = "";
int TimeDateh = 0;
int TimeDatem = 0;
int TimeDates = 0;
String DateDate = "";
String datetosave = "" ;
String TimeDatess = "0";
String TimeDatems = "0";
String TimeDatehs = "0";
char buffer[12];
char myChar = 92;
int pcurrent = 0 ;
int pcurrentold = 0 ;
int powercut = 0 ;
int tempfreq = 1000 ;  
//int dhttemp = 1 ; // DHT 
int dhttemp = 0 ; // Ds18b20 
//int dhttemp = 2 ; // Heat 
int sentapi = 0 ; // data sent = 1 or not = 0
int poweron = 0 ; // power on = 1 or power off = 0
int preverse = 0 ;
String pinnum = "0O4I0O0O5OEIFI" ;
int buttonpin = 13 ; 
//buttonpin = 0 ; // pins(1)
int pumppin1 = 4 ; // 4 ;
//pumppin1 = pins(3) ; // 4 ;
int buttpin = 14 ; // 0 ;
//buttpin = pins(5) ; // 0 ;
int heaterpin = 4 ; // 0 ;
//heaterpin = pins(7) ; // 0 ;
int acpin = 5 ; // 5 ;
//acpin = pins(9) ; // 5 ;
int pumppin2 = 5 ;
//pumppin2 = pins(11) ;
int pumppin3 = 12 ;
//pumppin3 = pins(13) ;
int powerpin = 4 ;
int powerpin2 = 5 ;

int sdlpin = 13;  // to change to 3
int sdapin = 12;  // to change to 1
//int sdlpin = 3; // rx
//int sdapin = 1; // tx

float tempmax31855 = 0 ;
/*
int io = pins(1) ; //.toInt() ; // 0;
int pumppin1 = pins(3) ; // 4 ;
int buttpin = pins(5) ; // 0 ;
int heaterpin = pins(7) ; // 0 ;
int acpin = pins(9) ; // 5 ;
int pumppin2 = pins(11) ;
int pumppin3 = pins(13) ;
*/
/*
String pins = pinnum.substring(1,1) ;
pins = pinnum.substring(2,2) ;
int pumppin = pins.toInt() ; // 4 ;
pins = pinnum.substring(3,3) ;
int buttpin = pins.toInt() ; // 0 ;
pins = pinnum.substring(4,4) ;
int heaterpin = pins.toInt() ; // 0 ;
pins = pinnum.substring(5,5) ;
int acpin = pins.toInt() ; // 5 ;
*/
#define PROGBUTT       0

#define POWER          powerpin
#define POWER2         powerpin2
#define BUTTON         buttonpin
#define PUMP1          pumppin1
#define BUTT           buttpin
#define HEATP          heaterpin
#define ACP            acpin
#define PUMP2          pumppin2
#define PUMP3          pumppin3
// SPI Pin connections.  
#define MISO 14
#define SCK  13
#define CS   12

#define SDL            sdlpin
#define SDA            sdapin
#define LED            16

// Create the temperature object, defining the pins used for communication
MAX31855 temp(MISO, CS, SCK);


/*
buttonpin = 0 ; // pins(1)
pumppin1 = pins(3) ; // 4 ;
buttpin = pins(5) ; // 0 ;
heaterpin = pins(7) ; // 0 ;
acpin = pins(9) ; // 5 ;
pumppin2 = pins(11) ;
pumppin3 = pins(13) ;
*/
// WiFiServer server(80); // removed from ap11

String wheretosend = "GET http://boatautomation.com/jojo/sendtoAPI-test.php" ;
const char http_site[] = "75.103.94.221";
const int http_port = 80;
int timetotestwifi = 300 ; // 300 ; // wait 300 seconds in ap mode 
String ipadd = "";
String ipStr = "";
uint8_t MAC_array[6];
uint8_t MAC_arrayp[6];
char MAC_char[22];
char MAC_charp[22];

int progmode = 3; // # seconds to push button to put unit in AP mode
int rebootmode = 9; // # seconds to push button to soft reboot unit
boolean configMode = false;  // not in config mode normally
int countmode = 0 ;
float temptodisp = 0;

//String who = "single temp server with switch - apserverA3";
//String devicetype = "DB18s20 Single Temp";
String who = "ap11t";
String devicetype = "" ; // "DB18s20 Single Temp";
String clearchar = " ";
int numtemp = 0; 
int delaytime = 1 ; // 1 second
int precision = 10 ; // .1
String tempreading = "F" ;
float temptemp; // temp   read from the thermometer
float temptemp2; // temp   read from the thermometer
float voltvolt; // volt read from the adc
int wrongtempcount = 0; // counter for wrong temp if peaks
int wtcmax = 10; // max number of consecutive wrong readings
//const char* APssid = "AAAP"; // Name of access point
//char* APssid = "AAAP"; // Name of access point

String st;
String rsid = ""; // "Jojo" ; //"UNITE-52ED";
String rpass = "" ; // "jojowifi" ; //"22329280";
long rssi ;
String wifiname = "" ;

// added to ap11
int ss = 0 ;
int contowifi = 0 ;
String firsteeprom = "9" ;
String message = "";

// end of add to ap11


boolean newSSID = false;
int x = 0;
int y = 0 ;
int v = 0 ;
int t = 0 ;
int t2 = 0 ;
int pb = 0 ;
int ap = 0 ;
int pbstatus = 0 ;
int pbtime = 0 ;
int freq = 2900 ; //  transmit the data every 1 hour
int frequency = freq ;
int details = 0 ;
//int details = 1 ;
 
String clientcode = "" ;// "d2ViaG9va3M6cGFzc3dvcmQ=" ;
float adjtemp = 0 ;
float adjtemp2 = 0 ;
float adjvolt = 27.95; // 29.6 ;

int thermostat =1 ;
int heattostart = 25 ;
int actostart = 22 ;
int aircond = 0 ;
int heater = 0 ;
int buttonupdt = 1 ;

int resolution = 9 ;

float oldtemp = 0;
float newtemp = 0;
float oldtemptest = 200;
float oldtemp2 = 0;
float newtemp2 = 0;
float oldtemptest2 = 200;
float oldvolt = 0;
float newvolt = 0;
float oldvolttest = 200;

float tempdiff = 2 ; // degrees diffenece to report
float voltdiff = .5 ; // volts diffenece to report

float vprecision = 10;
int  rebootfreq = 864000; // reboot every 240 hours/ 10 days by default
String strfreq = "" ;
String strrequest = "" ;
String strreqanswer = "" ;
//String webString = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>";
String webString = "";
String devicetodo = "" ;

String whatis = "T" ; 
String tempv="";

float valuedev1 = 0 ;
float valuedev2 = 0 ;
float valuedev3 = 0 ;
int changey = 0;

int rsid_from = 1 ;
int rsid_to = rsid_from + 32 ;
int rpass_from = rsid_to ;
int rpass_to = rpass_from + 64 ; // 97
int freq_from = rpass_to ;
int freq_to = freq_from + 6 ; // 103
int rebootfreq_from = freq_to ;
int rebootfreq_to = rebootfreq_from + 3; // 106
int clientcode_from = rebootfreq_to ;
int clientcode_to = clientcode_from + 30 ; // 136
int adjtemp_from = clientcode_to ;
int adjtemp_to = adjtemp_from + 4; // 140
int adjtemp2_from = adjtemp_to ;
int adjtemp2_to = adjtemp2_from + 4; // 144
int resolution_from = adjtemp2_to ;
int resolution_to = resolution_from + 1 ; // 145
int button_from = resolution_to ;
int button_to = button_from + 1 ; // 146
int tempreading_from = button_to ;
int tempreading_to = tempreading_from + 7 ;
int precision_from = tempreading_to ;
int precision_to = precision_from + 3 ;
int tempdiff_from = precision_to ; 
int tempdiff_to = tempdiff_from + 3 ;
int delaytime_from = tempdiff_to ;
int delaytime_to = delaytime_from + 4 ;
int whatis_from = delaytime_to;
int whatis_to = whatis_from + 1 ;
int pinnum_from = whatis_to ;
int pinnum_to = pinnum_from + 5 ;
int adjvolt_from = pinnum_to;
int adjvolt_to = adjvolt_from +5;
int voltdiff_from = adjvolt_to ;
int voltdiff_to = voltdiff_from + 3;
int vprecision_from = voltdiff_to ;
int vprecision_to = vprecision_from + 3 ;
int actostart_from = vprecision_to ;
int actostart_to = actostart_from + 5 ; 
int heattostart_from = actostart_to ;
int heattostart_to = heattostart_from + 5 ; 
int datetosave_from = heattostart_to ;
int datetosave_to = datetosave_from + 23 ; 
int eeprom_from = 0 ;
int eeprom_to = datetosave_to ; 


String s = "";
// relay pin
//// #define BUTTON          0
// button state
int current = 0;
int currentold = 0 ;
int curr = 0;
int currold = 0 ;
int pushbutttime = 0 ;
// pump state
int Pcurrent = 0;
int Pcurrentold = 0 ;
int Pcurrent2 = 0;
int Pcurrentold2 = 0 ;
int Pcurrent3 = 0;
int Pcurrentold3 = 0 ;

int last = -1;
  #define DHTTYPE DHT22
  #define DHTPIN  2
float humidity, temp_f;  // Values read from sensor
  DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
  

//  float pressureKPA = 0, temperaturekpa = 0;  //??????
  float pressureKPA = 0, temperaturekpa = 0, oldpressureKPA = 0; 

//initialize 1-wire bus
  #define ONE_WIRE_BUS 2
//  OneWire oneWire(ONE_WIRE_BUS);
//  DallasTemperature sensors(&oneWire);
//  Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
  DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
  DeviceAddress insideThermometer, outsideThermometer;
//endo of add a11

void setup() {
/* removed from apesp12
  delay(1000);
  Serial.begin(115200);
  pinMode(0, OUTPUT);
  digitalWrite(0, HIGH);
  Serial.setDebugOutput(true);
  Serial.println("");
  Serial.print("Pulled IO 0 high");
  Serial.println();
  WiFi.macAddress(MAC_array);
  for (int i = 0; i < sizeof(MAC_array); ++i){
      sprintf(MAC_char,"%s%02x:",MAC_char,MAC_array[i]);
  }
  Serial.println("");
  Serial.print("Mac address = ");  
  Serial.println(MAC_char);
*/ // end of removed from apesp12
// added from ap11
  Serial.begin(9600);
//  Serial.begin(115200,SERIAL_8N1,SERIAL_TX_ONLY);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH); // make GPIO LED output high
  pinMode(PROGBUTT, INPUT_PULLUP);
//  configMode = (digitalRead(PROGBUTT) ==
  EEPROM.begin(512);
//      digitalWrite(BUTT, LOW);
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off 
    uint8_t spi3w_en = 0;           //3-wire SPI Disable
    
    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

  sensors.begin();
  Serial.println("");
//  added on March 9
//  Wire.begin(4 , 5); // sda, slc for esp12
//  Wire.begin(3 , 1); // for esp12 tx and rx
//  Wire.begin(12 , 13); // for esp12
////  Wire.begin(SDA , SDL); // for esp12  
////  matrix.print(0.0, DEC);


  Wire.begin(SDA , SDL); // for esp12
  matrix.begin(0x70);
  matrix.print(0000, DEC);
  matrix.writeDisplay();
  Serial.println("Getting barometric pressure ...");
  mpl115a2.begin();
    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();  


/* to put if needed
    sensors.begin();

  Serial.println ("");
  Serial.print("Number of temp sensors = " );Serial.println(sensors.getDeviceCount(), DEC);
  numtemp = sensors.getDeviceCount();
*/
  // set button pin as an input
// added feb 15

//  dht.begin();           // initialize temperature sensor
pinMode(POWER2, OUTPUT);
digitalWrite(POWER2, HIGH);      
//checktime();

if (dhttemp == 1){
//  DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
  dht.begin();           // initialize temperature sensor
  numtemp = 2 ;
}
else if (dhttemp == 2) {
    numtemp = 2 ;
    printTemp31855(temp.readThermocouple(CELSIUS));
}
else if (dhttemp== 0){
  sensors.begin();

  // locate devices on the bus
  numtemp = sensors.getDeviceCount();
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(numtemp, DEC);
  Serial.println(" device(s).");

  // report parasite power requirements
  Serial.print("Parasite power is: "); 
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  // assign address manually.  the addresses below will beed to be changed
  // to valid device addresses on your bus.  device address can be retrieved
  // by using either oneWire.search(deviceAddress) or individually via
  // sensors.getAddress(deviceAddress, index)
  //insideThermometer = { 0x28, 0x1D, 0x39, 0x31, 0x2, 0x0, 0x0, 0xF0 };
  //outsideThermometer   = { 0x28, 0x3F, 0x1C, 0x31, 0x2, 0x0, 0x0, 0x2 };

  // search for devices on the bus and assign based on an index.  ideally,
  // you would do this to initially discover addresses on the bus and then 
  // use those addresses and manually assign them (see above) once you know 
  // the devices on your bus (and assuming they don't change).
  // 
  // method 1: by index
  if (!sensors.getAddress(insideThermometer, 0)) Serial.println("Unable to find address for Device 0"); 
  if (!sensors.getAddress(outsideThermometer, 1)) Serial.println("Unable to find address for Device 1"); 

  // method 2: search()
  // search() looks for the next device. Returns 1 if a new address has been
  // returned. A zero might mean that the bus is shorted, there are no devices, 
  // or you have already retrieved all of them.  It might be a good idea to 
  // check the CRC to make sure you didn't get garbage.  The order is 
  // deterministic. You will always get the same devices in the same order
  //
  // Must be called before search()
  //oneWire.reset_search();
  // assigns the first address found to insideThermometer
  //if (!oneWire.search(insideThermometer)) Serial.println("Unable to find address for insideThermometer");
  // assigns the seconds address found to outsideThermometer
  //if (!oneWire.search(outsideThermometer)) Serial.println("Unable to find address for outsideThermometer");

  // show the addresses we found on the bus
  Serial.print("Device 0 Address: ");
  printAddress(insideThermometer);
  Serial.println();

  Serial.print("Device 1 Address: ");
  printAddress(outsideThermometer);
  Serial.println();
}
//}
// added feb 15


WiFi.macAddress(MAC_arrayp);
    for (int i = 3; i < sizeof(MAC_arrayp); ++i){
      sprintf(MAC_charp,"%s%02x:",MAC_charp,MAC_arrayp[i]);
    }
    Serial.println("");
    Serial.print("Mac address for password = ");  
    Serial.println(MAC_charp);
//    softAP_password = MAC_charp ;
    softAP_password = "12345678" ;
WiFi.macAddress(MAC_array);
    for (int i = 0; i < sizeof(MAC_array); ++i){
      sprintf(MAC_char,"%s%02x:",MAC_char,MAC_array[i]);
    }
    Serial.println("");
    Serial.print("Mac address = ");  
    Serial.println(MAC_char);
    

//    Serial.println(String(MAC_char).substring(0,2));
//    Serial.println(String(MAC_char).substring(14,16));
    
//char APssid = "AAAP"; // Name of access point
//const char* APssid = "AAAP"+"MAC_char.substring(0,2) ; // Name of access point
  softAP_ssid = softAP_ssid + MAC_char ;
  
////Serial.println(softAP_password);
//  softAP_ssid = softAP_ssid + "12" ;
//  softAP_ssid.toCharArray(softAP_ssid, softAP_ssid.length());

  rsid.trim();
  rpass.trim();

  delay(10);
  Serial.println("Startup");
// end of add from ap11
/////////////////////////////////////////////  setupAP();
//  Serial.print("Configuring access point...");
  /* You can remove the password parameter if you want the AP to be open. */
//  WiFi.softAPConfig(apIP, apIP, netMsk);
////  WiFi.softAP(softAP_ssid, softAP_password);
////  WiFi.softAP(softAP_ssid.c_str(), softAP_password);
//  WiFi.softAP(softAP_ssid.c_str());
////  WiFi.softAP(softAP_ssid);
//  delay(1000); // Without delay I've seen the IP address blank
//  Serial.print("AP IP address: ");
//  Serial.println(WiFi.softAPIP());

  /* Setup the DNS server redirecting all the domains to the apIP */  
  dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
  dnsServer.start(DNS_PORT, "*", apIP);
//added from ap11
  // Read the first line of HTTP request
///  String req = server.client.readStringUntil('\r');
  // First line of HTTP request looks like "GET /path HTTP/1.1"
  // Retrieve the "/path" part by finding the spaces
///  int addr_start = req.indexOf(' ');
///  int addr_end = req.indexOf(' ', addr_start + 1);
///  if (addr_start == -1 || addr_end == -1) {
///    Serial.print("Invalid request: ");
///    Serial.println(req);
///    return(20);
///   }
///  req = req.substring(addr_start + 1, addr_end);
///  Serial.print("Request: ");
///  Serial.println(req);
//  client.flush(); 
//  String s;
 // s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from All Automations";
//  s = "<html><head></head><body><br><h1>Hello from All Automations!!</h1>";
//  s += "<p>";

  // end of added from ap11
  /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */
  server.on("/", handleRoot);
  server.on("/wifi", handleWifi);
  server.on("/wifisave", handleWifiSave);
  server.on("/generate_204", handleRoot);  //Android captive portal. Maybe not needed. Might be handled by notFound handler.
  server.on("/fwlink", handleRoot);  //Microsoft captive portal. Maybe not needed. Might be handled by notFound handler.
// added Sept 10-2016
//  server.on("/info?", handleinfo);
//  server.on("/cleareeprom", handlecleareeprom);
//  server.on("/details", handledetails );
//  server.on("/whatis", handlewhatis );
//  server.on("/whatis=", handlewhatisU );
//  server.on("/details?", handledetails );
//  server.on("/details?", handledetails );
  
  server.onNotFound ( handleNotFound );
  server.begin(); // Web server start
  Serial.println("HTTP server started");
  if (!ifCredentials() ){
    Serial.println ("in if eeprom empty");
    setupAP();
//    Serial.print("1st character is ") ; Serial.println(char(EEPROM.read(0)));
  }
  else 
  {
    Serial.println ("in else eeprom empty");
//    Serial.print("1st character is ") ; Serial.println(char(EEPROM.read(0)));

    loadCredentials(); // Load WLAN credentials from network
//    connect = strlen(rsid) > 0; // Request WLAN connect if there is a SSID
      connectWifi();
      
  }
}

int testWifi(void) {
  int c = 0;
//  Serial.println("");  
//  Serial.println("Waiting for Wifi to connect");  
  while ( c < 40 ) {
    if (WiFi.status() == WL_CONNECTED) {
      connRes = 3 ;
//      Serial.println("");  
      Serial.print("WiFi connected: ");
      Serial.println(toStringIp(WiFi.localIP()));
///   testing ap disconnect
//      WiFi.softAPdisconnect(true);
//      delay(500);
//          WiFi.mode(WIFI_STA);
      rssi = abs(WiFi.RSSI());
      
      if (devicetodo.substring(16,17) == "p" ) {
        Serial.println("in check time");
         checktime();
      }
      return(1); 
      }      
    delay(500);
//    Serial.print(WiFi.status());    
    c++;
  }
  if (newSSID == true ) {
    connRes = 4 ;
  }
  else {
    connRes = 0 ;
  }
  return(0);
} 



void connectWifi() {
  Serial.println("Connecting as wifi client...");
  WiFi.disconnect();

  //WiFi.begin ( ssid, password );
  rsid.trim();
  rpass.trim();

  WiFi.begin(rsid.c_str(), rpass.c_str());
  delay(1000);
////  connRes = WiFi.waitForConnectResult();
//connRes = 4 ;
////  Serial.print ( "connRes: " );
////  Serial.println ( connRes );
 if ( testWifi()) {
          Serial.print ("in testwifi 0");
          return;
      }
  // otherwise, set up an access point to input SSID and password     
  else {
    if ( String(WiFi.softAPIP()) != String(apIP) ) {
      Serial.println ("in ap not started, sending to setup ap");
        setupAP();
        return;
    }    
  }

}


void loop() {

  x += 1 ;
//  if (connect && x == 100) {
  if (connect ) {
////    Serial.println ( "Connect requested" );
    connect = false;
    connectWifi();
    x = 0 ;
    lastConnectTry = millis();
////    Serial.print ( "in if connect - lastConnectTry = " );
////    Serial.println ( lastConnectTry );
  }
  {
//    int s = WiFi.status();
    ss = WiFi.status();
//      Serial.print ( "Status 1: " );
//      Serial.println ( ss );
    
    if (ss == 0 && millis() > (lastConnectTry + 60000) ) {
      //* If WLAN disconnected and idle try to connect 
      //* Don't set retry time too low as retry interfere the softAP operation 
      Serial.print ( "in if ss = 0 - lastConnectTry = " );
      Serial.println ( lastConnectTry );
      
      connect = true;
    }
    if (status != ss) { // WLAN status change
////      Serial.print ( "Status 2: " );
////      Serial.println ( ss );
      status = ss;
//      if (s == WL_CONNECTED) {
        //* Just connected to WLAN 
      if (ss == 3) {  // connected to wifi
        contowifi = 1;
////        Serial.println ( "" );
////        Serial.print ( "Connected to " );
////        Serial.println ( rsid );
////        Serial.print ( "IP address: " );
////        Serial.println ( WiFi.localIP() );
        x = 0 ;

        // Setup MDNS responder
 //       if (!MDNS.begin(myHostname)) {
 //         Serial.println("Error setting up MDNS responder!");
 //       } else {
 //         Serial.println("mDNS responder started");
 //         // Add service to MDNS-SD
 //         MDNS.addService("http", "tcp", 80);
 //       }
      } 
//      else { //  if (s == WL_NO_SSID_AVAIL) {
      else if (ss == 4 || ss == 6 ) {
////        Serial.println ("in ss = 4 or 6");
////        Serial.println(WiFi.softAPIP());
        contowifi = 2;
        if ( String(WiFi.softAPIP()) != String(apIP) ) {
          Serial.println ("in the if apIP" );
          setupAP();
        }
      }
      else if (ss == WL_NO_SSID_AVAIL) {
        WiFi.disconnect();
        Serial.println("in else wl connected");
        if (rsid != "") {
          contowifi = 2;
          Serial.println("in if rsid, contowifi = 2");
        }
//        rsid = "";
//        rpass = "";

      }
    }
  }

  // Do work:  //DNS
  dnsServer.processNextRequest();
//  Serial.println("below dns");

  //HTTP
  server.handleClient();
//  Serial.println("below handle client");
if ( x > 3000000 && contowifi == 1 && ( String(WiFi.softAPIP()) == String(apIP) )){
  Serial.println ( "in the disconnect the ap and x = " + String(x)+ "and contowifi = " + String(contowifi));
  Serial.println( WiFi.softAPIP());
  WiFi.softAPdisconnect(true);
}
//Serial.println(x) ;
}

