#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <DNSServer.h>
//#include <ESP8266mDNS.h> - from ap11
#include <EEPROM.h>
//#include "ESP8266WiFi.h" - from ap11
//#include <ESP8266mDNS.h> - from ap11

#include <OneWire.h>
#include <DallasTemperature.h>
#include <DHT.h>
#include <MAX31855.h>

/* 
 * 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 = "AA-Restorant";
const char *softAP_password = "12345678";

/* 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 ;

// added from a11
//endo of add a11


// 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); removed from apesp12

/** 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 code from A11
#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

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-2.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];
char MAC_char[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 = "ap-restoauto-sept2016";
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

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

boolean newSSID = false;
//added to ap11
String firsteeprom = "9" ;
int ss = 0 ; //added to ap11
int contowifi = 0 ; // added to ap11
// end of add to ap11

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 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() {
/* old 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);
*/
// 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_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
  
  delay(10);
  Serial.println("Startup");
  String firsteepromt = "9" ;
  if (char(EEPROM.read(0)) != firsteepromt[0] ){
    
    
    Serial.println ("in if eeprom empty");
    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)));
  // read eeprom for ssid and pass
    Serial.println("Reading EEPROM ssid");
  
  
  for (int i = rsid_from; i < rsid_to; ++i)
    {
      rsid += char(EEPROM.read(i));
    }
  Serial.print("SSID: ");
  Serial.print(rsid);
  Serial.println(".");
  Serial.print("lengh of SSID: ");
  Serial.println(rsid.length());
  Serial.print("rsid toInt =  ");
  Serial.println(rsid.toInt());

  Serial.println("Reading EEPROM pass");
  
  for (int i = rpass_from; i < rpass_to; ++i)
    {
      rpass += char(EEPROM.read(i));
    }
  Serial.print("PASS: ");
  Serial.print(rpass);  
  Serial.println(".");
  strfreq = "";
//  for (int i = 96; i < 102; ++i)
  for (int i = freq_from; i < freq_to; ++i)

    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Frequency: ");
  Serial.print(strfreq);  
  Serial.println(".");
  if (strfreq.toInt() != 0 ) {
    Serial.print ("in the if frequency = ");
//    freq = 10 * strfreq.toInt() ;
    freq = strfreq.toInt() ;
    frequency = freq ;
Serial.println(freq);  
  
  }

  strfreq = "";
  for (int i = clientcode_from; i < clientcode_to; ++i)

    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("clientcode: ");
  Serial.print(strfreq);  
  Serial.println(".");
  
  strfreq = "";

  for (int i = rebootfreq_from; i < rebootfreq_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Frequency: ");
  Serial.print(strfreq);  
  Serial.println(".");
//  rebootfreq = strfreq.toInt();
  if (strfreq.toInt() != 0 ) {
    Serial.println ("in the if reboot frequency");
    rebootfreq = strfreq.toInt();
//    rebootfreq = 3600 * strfreq.toInt() ; // number of hours to reboot
          if (rebootfreq == 999) {
//            rebootfreq = strfreq.toInt();
            Serial.print ("Rebooting frequency = "); Serial.println(rebootfreq);
          }
          else {
            if (rebootfreq == 0) {
              rebootfreq = 999 ;
            }
            rebootfreq = 3600 * strfreq.toInt() ; // number of hours to reboot
          }

  }
//int delaytime_from = tempdiff_to ;

  strfreq = "";
  for (int i = delaytime_from; i < delaytime_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("temp delaytime: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if temp delaytime");
    delaytime = strfreq.toInt() ; // delaytime temp
  }

    strfreq = "";
  for (int i = tempdiff_from; i < tempdiff_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("tempdiff: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if temp tempdiff");
    tempdiff = strfreq.toFloat() ; // tempdiff temp
  }

    strfreq = "";
  for (int i = voltdiff_from; i < voltdiff_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("voltdiff: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if temp voltdiff");
    voltdiff = strfreq.toFloat() ; // voltdiff temp
  }

  strfreq = "";
  for (int i = precision_from; i < precision_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("temp precision: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if temp precision");
    precision = strfreq.toFloat() ; // precision temp
  }

  #define TEMPERATURE_PRECISION   resolution
  // set the resolution to 9 bit
  sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);
  sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION);

  Serial.print("Device 0 Resolution: ");
  Serial.print(sensors.getResolution(insideThermometer), DEC); 
  Serial.println();

  Serial.print("Device 1 Resolution: ");
  Serial.print(sensors.getResolution(outsideThermometer), DEC); 
  Serial.println();

  strfreq = "";
  for (int i = vprecision_from; i < vprecision_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("temp vprecision: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if temp vprecision");
    vprecision = strfreq.toFloat() ; // vprecision temp
  }

  strfreq = "";
  for (int i = tempreading_from; i < tempreading_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Temp reading in : ");
  Serial.print(strfreq);  
  Serial.println(".");

//  if (strfreq != "" ) {
  if (String(strfreq) > "       " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
    Serial.println ("in the if temp reading");
    tempreading = String(strfreq) ; 
  }

  strfreq = "";
  for (int i = adjtemp_from; i < adjtemp_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Adjust temp: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if adjust temp");
    adjtemp = strfreq.toFloat() ; // number to adjust temp to
  }

  strfreq = "";
  for (int i = adjtemp2_from; i < adjtemp2_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Adjust temp2: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if adjust temp2");
    adjtemp2 = strfreq.toFloat() ; // number to adjust temp to
  }

  strfreq = "";
  for (int i = adjvolt_from; i < adjvolt_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Adjust volt: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toFloat() != 0 ) {
    Serial.println ("in the if adjust volt");
    adjvolt = strfreq.toFloat() ; // number to adjust temp to
  }

  strfreq = "";

//  for (int i = 132; i < 135; ++i)
  for (int i = resolution_from; i < resolution_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("resolution: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toInt() != 0 ) {
    Serial.println ("in the if resolution");
    resolution = strfreq.toInt() ; // number to adjust temp to
  }

    Serial.print ("Frequency = ");
    Serial.println (freq);

    Serial.print ("Rebooting Frequency = ");
    Serial.println (rebootfreq);
          
          //convert SSID and Password sting to char
          char ssid[rsid.length()];
          rsid.toCharArray(ssid, rsid.length());         
          char pass[rpass.length()];
          rpass.toCharArray(pass, rpass.length());

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

  Serial.print("SSID: ");
  Serial.print(rsid);
  Serial.println(".");
  Serial.print("PASS: ");
  Serial.print(rpass);  
  Serial.println(".");

  strfreq = "";

//  for (int i = 132; i < 135; ++i)
  for (int i = whatis_from; i < whatis_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("whatis: ");
  Serial.print(strfreq);  
  Serial.println(".");
//Serial.println(strfreq.toInt());  
//Serial.println(String(strfreq)> "ÿ");  
//Serial.println(String(strfreq)< "ÿ");
//Serial.println(String(strfreq)= String("ÿ"));  
  

//Serial.println(strfreq.toFloat());  
  //if (strfreq.toInt() != 0 ) {
  if (String(strfreq) > " " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
//    Serial.println ("in the if whatis");
    whatis = strfreq ;
    Serial.print("whatis: ");
    Serial.print(strfreq);  
    Serial.println(".");
  }
    dowhatis();

  strfreq = "";
  for (int i = actostart_from; i < actostart_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("actostart: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toInt() != 0 ) {
    Serial.println ("in the if actostart");
    actostart = strfreq.toInt() ;
  }

  strfreq = "";
  for (int i = heattostart_from; i < heattostart_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print(": ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toInt() != 0 ) {
    Serial.println ("in the if  = 0");
    heattostart = strfreq.toInt() ; // number to adjust temp to
  }

  
  strfreq = "";
 for (int i = button_from; i < button_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("button: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toInt() == 0 ) {
    Serial.println ("in the if button = 0");
    current = strfreq.toInt() ; // number to adjust temp to
  }
  if (strfreq.toInt() == 1 ) {
    Serial.println ("in the if button = 1");
    current = strfreq.toInt() ; // number to adjust temp to
    if (devicetodo.substring(4,5) == "s" ) {
      digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
    }

  }

  strfreq = "";

  for (int i = pinnum_from; i < pinnum_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("pinnum: ");
  Serial.print(strfreq);  
  Serial.println(".");

//  if (strfreq.toInt() != 0 ) {
  if (String(strfreq) > "    " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
    Serial.println ("in the if pinnum");
    pinnum = strfreq ;
  }

 strfreq = "";

//  for (int i = 132; i < 135; ++i)
  for (int i = datetosave_from; i < datetosave_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("strfreq datetosave: ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (String(strfreq) > "                       " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
    Serial.println ("in the if datetosave");
    datetosave = strfreq ;
    Serial.print("datetosave: ");
    Serial.print(datetosave);  
    Serial.println(".");
    powercut = 1 ;
  }

  } // if eeprom(1) = 0 
//    Serial.print("Mac=");  
    Serial.println(MAC_char);


// end of add from ap11
  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);
  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);

  /* Setup web pages: root, wifi config pages, SO captive portal detectors and not found. */
// removed from apesp12 - no
  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.
  server.onNotFound ( handleNotFound );


  server.begin(); // Web server start
  Serial.println("HTTP server started");
  if (!ifCredentials() ){
    Serial.println ("in if eeprom empty");
//    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();
  }

}

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());

  connRes = WiFi.waitForConnectResult();
  Serial.print ( "connRes: " );
  Serial.println ( connRes );
}

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 ( s );
    
    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) {
        contowifi = 1;
        Serial.println ( "" );
        Serial.print ( "Connected to " );
        Serial.println ( rsid );
        Serial.print ( "IP address: " );
        Serial.println ( WiFi.localIP() );

        // 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 == 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");

}

