//A simplified version of work begun by Tzapu and chriscook8

//#include <ESP8266WiFi.h>
#include "ESP8266WiFi.h"
#include <ESP8266mDNS.h>
#include <WiFiClient.h>
#include <EEPROM.h>

#include <OneWire.h>
#include <DallasTemperature.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();
String pinnum = "0O4I0O0O5OEIFI" ;
int buttonpin = 0 ; 
//buttonpin = 0 ; // pins(1)
int pumppin1 = 4 ; // 4 ;
//pumppin1 = pins(3) ; // 4 ;
int buttpin = 0 ; // 0 ;
//buttpin = pins(5) ; // 0 ;
int heaterpin = 0 ; // 0 ;
//heaterpin = pins(7) ; // 0 ;
int acpin = 5 ; // 5 ;
//acpin = pins(9) ; // 5 ;
int pumppin2 = 0 ;
//pumppin2 = pins(11) ;
int pumppin3 = 0 ;
//pumppin3 = pins(13) ;

// to change for esp12
int sdlpin = 13;
int sdapin = 12;
//int sdlpin = 1; // rx
//int sdapin = 0; // tx
/*
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 BUTTON        0
#define LED            16

#define BUTTON         buttonpin
#define PUMP1          pumppin1
#define BUTT           buttpin
#define HEATP          heaterpin
#define ACP            acpin
#define PUMP2          pumppin2
#define PUMP3          pumppin3
#define SDL            sdlpin
#define SDA            sdapin
/*
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);

String wheretosend = "GET http://boatautomation.com/jojo/sendtoAPI-1.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];
//String who = "single temp server with switch - apserverA3";
//String devicetype = "DB18s20 Single Temp";
String who = "apserverA7-test-pushbutt-thermostat-doubletemp";
String devicetype = "" ; // "DB18s20 Single Temp";

String clearchar = " ";
int numtemp = 0; 
int delaytime = 1 ; // 1 second
int precision = 10 ; // .01
String tempreading = "C" ;
float temptemp; // temp   read from the thermometer
float temptemp2; // temp   read from the thermometer
float voltvolt; // volt read from the adc

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;
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 = 3600 ; //  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 = 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 = .5 ; // degrees diffenece to report
float voltdiff = .5 ; // volts diffenece to report

float vprecision = 100;
int  rebootfreq = 999; // reboot every 24 hours 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 = "" ; 
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 eeprom_from = 0 ;
int eeprom_to = heattostart_to ; // button_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 last = -1;

  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;

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH); // make GPIO4 output high
  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;

/* 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
  sensors.begin();
Serial.println("");
//  added on March 9
  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();  
    

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

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

  
  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() ;
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 != "" ) {
    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(".");

//  if (strfreq.toInt() != 0 ) {
//    Serial.println ("in the if whatis");
    whatis = strfreq ;
//  }
    dowhatis();
//int butt_to = butt_from + 1 ; 
//int pushbutttime_from = butt_to ;
/*
  strfreq = "";
  for (int i = actostart_from; i < actostart_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print(": ");
  Serial.print(strfreq);  
  Serial.println(".");

  if (strfreq.toInt() != 0 ) {
    Serial.println ("in the if  = 0");
    actostart = strfreq.toInt() ; // number to adjust temp to
  }
*/
  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 ) {
    Serial.println ("in the if pinnum");
    pinnum = strfreq ;
  }

  } // if eeprom(1) = 0 

  // if the stored SSID and password connected successfully, exit setup
  if ( testWifi()) {
          Serial.print ("in testwifi 0");
          launchWeb(0);
          return;
      }
  // otherwise, set up an access point to input SSID and password     
  else {

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


    WiFi.begin(rsid.c_str(), rpass.c_str());
    delay(1000);
    if ( testWifi()) {
//            s += "<p>Successfully connected to your wifi<p>";
//            s += "</html>\r\n\r\n";

            Serial.print ("in testwifi 1");
            launchWeb(0);

            return;
    }

    else{
            Serial.println("");
            Serial.println("New SSID or Password failed. Reconnect to server, and try again.");
//            s += "<p>Could not connect to your wifi<p>";
//            s += "<p>Renter your wifi name and passwrod to try again<p>";
//            s += "</html>\r\n\r\n";

            
            setupAP();
            return;
    }
      
      
      Serial.println("");
      Serial.println("Connect timed out, opening AP"); 
      setupAP();
  }
}

int testWifi(void) {
  int c = 0;
  Serial.println("");  
  Serial.println("Waiting for Wifi to connect");  
  while ( c < 40 ) {
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("");  
      Serial.println("WiFi connected.");
/// testing ap disconnect
//      WiFi.softAPdisconnect(true);
//      delay(500);
//          WiFi.mode(WIFI_STA);
      rssi = abs(WiFi.RSSI());
      return(1); 
      }      
    delay(500);
    Serial.print(WiFi.status());    
    c++;
  }
  return(0);
} 


void launchWeb(int webtype) {
    Serial.println("");
    Serial.println("WiFi connected");
//    Serial.println(WiFi.localIP());
    IPAddress ip = WiFi.localIP();
    ipadd = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
    Serial.println(ipadd);
//    Serial.println(WiFi.softAPIP());
    ip = WiFi.softAPIP();
    ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
    Serial.println(ipStr);
   /* if (!mdns.begin("esp8266", WiFi.localIP())) {
      Serial.println("Error setting up MDNS responder!");
      while(1) { 
        delay(1000);
      }
    }
    Serial.println("mDNS responder started");
    */
    // Start the server
    server.begin();
    Serial.println("Server started");   
    int b = 20;
    int c = 0;
    while(b == 20) { 
      c = c + 1 ;
      if (details == 1 ) {
        Serial.println("in while b = 20");
        Serial.print("c =");Serial.println(c);
      }
      if ( c == timetotestwifi ) {
        // testWifi() ;
        if (WiFi.status() != WL_CONNECTED) {
           newSSID = true ;
        }
        c = 0 ;
      }
      
       b = mdns1(webtype);
       torun();

       //If a new SSID and Password were sent, close the AP, and connect to local WIFI
       if (newSSID == true){
          newSSID = false;

/*
          Serial.print("SSID: ");
          Serial.print(rsid);  
          Serial.println(".");
          Serial.print("PASS: ");
          Serial.print(rpass);  
          Serial.println(".");
*/
//        s += "<p>Trying to connect to your wifi<p>";

          Serial.println("Connecting to local Wifi");
          delay(500);
          WiFi.softAPdisconnect(true);
          delay(500);
          WiFi.mode(WIFI_STA);

          WiFi.begin(rsid.c_str(), rpass.c_str());
          delay(1000);
          if ( testWifi()) {
//            s += "<p>Successfully connected to your wifi<p>";
//            WiFi.softAPdisconnect(true);
//            delay(500);
            Serial.print ("in testwifi 1");
            launchWeb(0);

            return;
          }

         else{
            Serial.println("");
            Serial.println("New SSID or Password failed. Reconnect to server, and try again.");


            setupAP();
            return;
         }
       }
    delay(100);
     }
}


void setupAP(void) {
  
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
  }
  Serial.println(""); 
  st = "<ul>";
  wifiname = "<select name='ssid'>" ;
  wifiname += "<option> </option>";

  for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      st += "<li>";
      st +=i + 1;
      st += ": ";
      st += WiFi.SSID(i);
      wifiname += "<option>" + WiFi.SSID(i) + "</option>";
      st += " (";
      st += WiFi.RSSI(i);
      st += ")";
      st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
      st += "</li>";
    }
  st += "</ul>";
  wifiname += "</select>";
  delay(100);
  WiFi.softAP(APssid);
/*
  Serial.println("st=");
  Serial.println(st);
*/
  Serial.println("softAP");
  Serial.println("");
  launchWeb(1);
}


String urldecode(const char *src){ //fix encoding
  String decoded = "";
    char a, b;
    
  while (*src) {     
    if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b))) {      
      if (a >= 'a')
        a -= 'a'-'A';       
      if (a >= 'A')                
        a -= ('A' - 10);                   
      else               
        a -= '0';                  
      if (b >= 'a')                
        b -= 'a'-'A';           
      if (b >= 'A')                
        b -= ('A' - 10);            
      else                
        b -= '0';                        
      decoded += char(16*a+b);            
      src+=3;        
    } 
    else if (*src == '+') {
      decoded += ' ';           
      *src++;       
    }  
    else {
      decoded += *src;           
      *src++;        
    }    
  }
  decoded += '\0';        
  return decoded;
}


int mdns1(int webtype){
  // Check for any mDNS queries and send responses
  //mdns.update();
  
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return(20);
  }
  Serial.println("");
  Serial.println("New client");

  // Wait for data from client to become available
  while(client.connected() && !client.available()){
    delay(1);
   }
  
  // Read the first line of HTTP request
  String req = 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 += "<p>";
  
  if ( webtype == 1 ) { // in ap server mode
      if (req == "/")
      {
        IPAddress ip = WiFi.softAPIP();
        String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation at ";
//        s += " at ";
//        s += ipStr;
//        s += "<p>";
        s += "Signal = "+String(rssi)+"<p>";
        s += "Macid = "+String(MAC_char)+"<p>";
        s += "Device Type = "+devicetype+"<p>";
        s += "Frequency = "+String(freq)+"<p>";
//            s += st;
//        s += "<form method='get' action='a'><label>WiFi Name: </label><input name='ssid' length=32><label> - Password: </label><input name='pass' length=64><input type='submit'></form>";
        s += "<form method='get' action='a'><label>WiFi Name: </label>" + wifiname+"<label> - Password: </label><input name='pass' length=64><input type='submit'></form>";

//        s += "</html>\r\n\r\n";
        Serial.println("Sending 200");
      }
      else if ( req.startsWith("/cleareeprom") ) {
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation";
        s += "<p>Clearing the EEPROM<p>";
//        s += "</html>\r\n\r\n";
        Serial.println("Sending 200");  
        Serial.println("clearing eeprom");
        for (int i = 0; i < 256; ++i) { EEPROM.write(i, clearchar[0]); }
        EEPROM.commit();
        s += "<p>Cleared<p>";
      }
      else if ( req.startsWith("/a?ssid=") ) {
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation";
//        s += "<p>Saving SSID and password<p>";
        s += "<p>Saving your new WiFi Name and Password...<p>";
  
        newSSID = true;
        String qsid; //WiFi SSID 

        qsid = urldecode(req.substring(8,req.indexOf('&')).c_str()); //correct coding for spaces as "+"
        Serial.println(qsid);
        Serial.println("");
        rsid = qsid;
        
        String qpass; //Wifi Password
        qpass = urldecode(req.substring(req.lastIndexOf('=')+1).c_str());//correct for coding spaces as "+"
        Serial.println(qpass);
        Serial.println("");
        rpass = qpass;

        Serial.println("clearing eeprom");
        for (int i = 1; i < 97; ++i) { EEPROM.write(i, clearchar[0]); }
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();
        //EEPROM.write(0, 9);
    
        Serial.println("writing eeprom ssid:");
        for (int i = 1; i < qsid.length(); ++i)
          {
            EEPROM.write(i, qsid[i-1]);
            Serial.print("Wrote: ");
            Serial.println(qsid[i-1]); 
          }
        Serial.println("writing eeprom pass:"); 
        for (int i = 0; i < rpass.length(); ++i)
          {
            EEPROM.write(33+i, rpass[i]);
            Serial.print("Wrote: ");
            Serial.println(rpass[i]); 
          }    

        EEPROM.commit();

//        s += "<p> New SSID and Password saved</html>\r\n\r\n"; 
        s += "<p> Your new WiFi Name and Password saved</p>"; 
        s += "<p> Trying to connect to your WiFi with it.</p>"; 
        s += "<p> Check your WiFi network in the next minute.</p>";
        s += "<p>If AAAP is still available and you can connect to it,</p>";
        s += "<p>your WiFi credentials were wrong. </p>";
//        s += "<p>you should go to <a href='/192.168.4.1' target='_self'>192.168.4.1</a> and retype your WiFi credentials</p>"; 
//        s += "<p>Click <a href='/' target='_blank'>here</a> to retype your WiFi credentials</p>"; 
        s += "<p> </p>"; 
        s += "<p>Click <a href='http://192.168.4.1' target='_self'>here</a> to retype your WiFi credentials</p>"; 
        
//        return (20) ;
//        s += "</html>\r\n\r\n"; 

      }
      else if ( req.startsWith("/details=") ) { // details = 0 or 1

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("details = ");
        Serial.println(strreqanswer);

        s += "<p>Saved<p>";
        details = strreqanswer.toInt() ;
        
      }
      else if ( req.startsWith("/pinnum=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("pinnum = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the pinnum value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = pinnum_from; i < pinnum_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom pinnum:");
        for (int i = pinnum_from; i < pinnum_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-pinnum_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-pinnum_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        pinnum = strreqanswer ;
        
        Serial.print ("pinnum = "); Serial.println(pinnum);
      }

      else if ( req.startsWith("/whatis=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("whatis = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the whatis value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = whatis_from; i < whatis_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom whatis:");
        for (int i = whatis_from; i < whatis_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-whatis_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-whatis_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        whatis = strreqanswer ;
        dowhatis() ;
        Serial.print ("whatis = "); Serial.println(whatis);
/*
           s += "<p>Rebooting now<p>";

          Serial.println("Rebooting");
          delay(500);
          ESP.restart(); 
*/
      }

      else if ( req.startsWith("/whatis?") ) {
        s = webString ;
        Serial.print ("whatis = "); Serial.println(whatis);
        s += whatis;
        
      }

      else if ( req.startsWith("/pinnum?") ) {
        s = webString ;
        Serial.print ("pinnum = "); Serial.println(pinnum);
        s += pinnum;
        
      }
      else if ( req.startsWith("/all?") ) {
        s = "" ;
        rssi = abs(WiFi.RSSI());
        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "signal:"+String(rssi)+",";
        s += "macid:"+String(MAC_char)+",";
        s += "numtemp:"+String(numtemp)+",";
        s += "resolution:"+String(resolution)+",";
        s += "adjtemp:"+String(adjtemp)+",";
        s += "adjtemp2:"+String(adjtemp2)+",";
        s += "devicetype:"+devicetype+",";
        s += "freq:"+String(freq)+",";
//        s += "rebootfreq:"+String(rebootfreq/3600)+",";
          if (rebootfreq == 999) {
            s += "rebootfreq="+String(rebootfreq)+",";          }
          else {
            s += "rebootfreq="+String(rebootfreq/3600)+",";
          }
        if (devicetodo.startsWith("t") ) {
          gettemp();
          s += "temp:"+ String(temptemp) + ",";
          s += "temp:"+ String(temptemp2) + ",";
        }
        s += "button = " + String(current) + ",";
        s += "pump = " + String(Pcurrent) + ",";
        s += "IP:"+ ipadd + ",";
//        s += "network:" + rsid + ",";
//        s += "pass:" + rpass + ",";
        s += "who:" + who + ",";
        s += "network:" + rsid;
        Serial.print ("All = "); Serial.println(s);
        s = webString + s;
      }
      else if ( req.startsWith("/info?") ) {
        s = "" ;
        rssi = abs(WiFi.RSSI());
        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "signal="+String(rssi)+"&";
        s += "macid="+String(MAC_char)+"&";
        s += "devicetype="+devicetype+"&";
        s += "freq="+String(freq)+"&";
//        s += "rebootfreq="+String(rebootfreq/3600)+"&";
          if (rebootfreq == 999) {
            s += "rebootfreq="+String(rebootfreq)+"&";          }
          else {
            s += "rebootfreq="+String(rebootfreq/3600)+"&";
          }
          s += "whatis="+String(whatis)+"&";
        if (devicetodo.startsWith("t") ) {
          gettemp();
          s += "temp="+ String(temptemp) + "&";
          s += "temp2="+ String(temptemp2) + "&";
          s += "numtemp="+String(numtemp)+"&";
          s += "resolution="+String(resolution)+"&";
          s += "tempdiff="+String(tempdiff)+"&";
          s += "adjtemp="+String(adjtemp)+"&";
          s += "adjtemp2="+String(adjtemp2)+"&";
          s += "precision="+String(precision)+"&";
        }
        if (devicetodo.substring(2,3) == "v" ) {
          s += "volt="+ String(valuedev3) + "&";
          s += "voltdiff="+String(voltdiff)+"&";
          s += "adjvolt="+String(adjvolt)+"&";
          s += "vprecision="+String(vprecision)+"&";
        }
        
        if (devicetodo.substring(6,7) == "p" ) {
          s += "pump = " + String(Pcurrent) + "&";
        }
       if (devicetodo.substring(4,5) == "s" ) {
         s += "button = " + String(current) + "&";
       }
       if (devicetodo.substring(8,9) == "b" ) {
         s += "butt = " + String(curr) + " for " + String(pushbutttime) + "s&";
       }
       s += "IP="+ ipadd + "&";
//        s += "pass:" + rpass + "&";
        s += "who=" + who + "&";
        s += "network=" + rsid;
        Serial.print ("Info = "); Serial.println(s);
        s = webString + s;
      }
      else if ( req.startsWith("/frequency?") ) {
        s = webString ;
 //       readeeprom(req,freq_from, freq_to);
//        freq = freq/10 ;
        Serial.print ("frequency = "); Serial.println(freq);
        s += freq;
        
//        Serial.print ("frequency = "); Serial.println(freq);
      }

      else if ( req.startsWith("/volts?") ) {
        s = webString ;
 //       readeeprom(req,freq_from, freq_to);
//        freq = freq/10 ;
        Serial.print ("volts = "); Serial.println(valuedev3);
        s += valuedev3;
        
//        Serial.print ("frequency = "); Serial.println(freq);
      }
      else if ( req.startsWith("/adjtempadd?") ) {
        s = webString ;
        s += adjtemp;
        Serial.print ("adjtemp = "); Serial.println(adjtemp);
      }
      else if ( req.startsWith("/adjtemp2add?") ) {
        s = webString ;
        s += adjtemp2;
        Serial.print ("adjtemp2 = "); Serial.println(adjtemp2);
      }

      else if ( req.startsWith("/adjvoltdiv?") ) {
        s = webString ;
        s += adjvolt;
        Serial.print ("adjvolt = "); Serial.println(adjvolt);
      }

      else if ( req.startsWith("/readeeprom?") ) {
        s = webString ;
            String readeepr = "";
            readeepr += char(EEPROM.read(0));
            for (int i = freq_from ; i < eeprom_to; ++i)
            {
              readeepr += char(EEPROM.read(i));
            }
            Serial.print("Normal Level:");
            Serial.print(readeepr);
        s += readeepr;
        Serial.print ("readeepr = "); Serial.println(readeepr);
      }

      else if ( req.startsWith("/devicetype?") ) {
        s = webString ;
        s += devicetype;
        Serial.print ("devicetype = "); Serial.println(devicetype);
      }

      else if ( req.startsWith("/resolution?") ) {
        s = webString ;
        s += resolution ;
        Serial.print ("resolution = "); Serial.println(resolution);
      }

      else if ( req.startsWith("/rebootfreq?") ) {
        s = webString ;
        Serial.print ("Reboot frequency = "); Serial.println(rebootfreq);
 //       readeeprom(req,freq_from, freq_to);
//        rebootfreq = rebootfreq/36000 ;
//        rebootfreq = rebootfreq/3600 ;
        Serial.print ("Reboot frequency = "); Serial.println(rebootfreq);
          if (rebootfreq == 999) {
            s += rebootfreq ;
          }
          else {
            s += rebootfreq/3600;
          }
      }
    
      else if ( req.startsWith("/macid?") ) {
        s = webString ;
        Serial.print ("Mac id = "); Serial.println(String(MAC_char));
        s += String(MAC_char);
      }

      else if ( req.startsWith("/who?") ) {
        s = webString ;
        Serial.print ("Who = "); Serial.println(who);
        s += who;
      }

      else if ( req.startsWith("/signal?") ) {
        s = webString ;
        rssi = abs(WiFi.RSSI());
        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += String(rssi);
      }

      else if ( req.startsWith("/clientcode?") ) {
        s = webString ;
        s += clientcode;
        Serial.print ("clientcode = "); Serial.println(clientcode);
      }
      else
      
      {
        s += "Command not found";
//        s += "HTTP/1.1 404 Not Found\r\n\r\n";
        Serial.println("Sending 404");
      }
  } 
  else
  {
      if (req == "/")
      {
        s += "Signal = "+String(rssi)+"<p>";
        s += "Macid = "+String(MAC_char)+"<p>";
        s += "Device Type = "+devicetype+"<p>";
        s += "Frequency = "+String(freq)+"<p>";
//            s += st;
        s += "<form method='get' action='a'><label>WiFi Name: </label>" + wifiname+"<label> - Password: </label><input name='pass' length=64><input type='submit'></form>";
        Serial.println("Sending 200");
      }
      else if ( req.startsWith("/cleareeprom") ) {
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation";
        s += "<p>Clearing the EEPROM<p>";
//        s += "</html>\r\n\r\n";
        Serial.println("Sending 200");  
        Serial.println("clearing eeprom");
        for (int i = 0; i < 256; ++i) { EEPROM.write(i, clearchar[0]); }
//        EEPROM.write(0, 9);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        s += "<p>Cleared<p>";
      }

//  for (int i = precision_from; i < precision_to; ++i)
      else if ( req.startsWith("/tempdiff=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("tempdiff = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the tempdiff value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = tempdiff_from; i < tempdiff_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom tempdiff:");
        for (int i = tempdiff_from; i < tempdiff_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-tempdiff_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-tempdiff_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        tempdiff = strreqanswer.toFloat() ;
        y = freq ;        
        
        Serial.print ("tempdiff = "); Serial.println(tempdiff);
      }

      else if ( req.startsWith("/voltdiff=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("voltdiff = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the voltdiff value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = voltdiff_from; i < voltdiff_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom voltdiff:");
        for (int i = voltdiff_from; i < voltdiff_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-voltdiff_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-voltdiff_from]); 
          }
        EEPROM.commit();

        y = freq ;        
        s += "<p>Saved<p>";
        voltdiff = strreqanswer.toFloat() ;
        
        Serial.print ("voltdiff = "); Serial.println(voltdiff);
      }
      else if ( req.startsWith("/heattemp?") ) {
        s = webString ;
        Serial.print ("heat temp set at = "); Serial.println(heattostart);
        s += heattostart;
      }
      else if ( req.startsWith("/heattemp=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("heattostart = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the heater thermostat value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = heattostart_from; i < heattostart_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom heattostart:");
        for (int i = heattostart_from; i < heattostart_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-heattostart_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-heattostart_from]); 
          }
        EEPROM.commit();

        y = freq ;        
        s += "<p>Saved<p>";
        heattostart = strreqanswer.toFloat() ;
        
        Serial.print ("heattostart = "); Serial.println(heattostart);
      }

      else if ( req.startsWith("/actemp?") ) {
        s = webString ;
        Serial.print ("A/C temp set at = "); Serial.println(actostart);
        s += actostart;
      }
      else if ( req.startsWith("/actemp=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("actostart = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the acer thermostat value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = actostart_from; i < actostart_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom actostart:");
        for (int i = actostart_from; i < actostart_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-actostart_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-actostart_from]); 
          }
        EEPROM.commit();
        y = freq ;        

        s += "<p>Saved<p>";
        actostart = strreqanswer.toFloat() ;
        
        Serial.print ("actostart = "); Serial.println(actostart);
      }

      else if ( req.startsWith("/pinnum=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("pinnum = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the pinnum value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = pinnum_from; i < pinnum_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom pinnum:");
        for (int i = pinnum_from; i < pinnum_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-pinnum_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-pinnum_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        pinnum = strreqanswer ;
        
        Serial.print ("pinnum = "); Serial.println(pinnum);
      }

      else if ( req.startsWith("/whatis=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("whatis = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the whatis value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = whatis_from; i < whatis_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom whatis:");
        for (int i = whatis_from; i < whatis_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-whatis_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-whatis_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        whatis = strreqanswer ;
        dowhatis() ;
        y = freq ;        
        
        Serial.print ("whatis = "); Serial.println(whatis);
/*            s += "<p>Rebooting now<p>";

          Serial.println("Rebooting");
          delay(500);
          ESP.restart(); 
*/
     }
      else if ( req.startsWith("/whatis?") ) {
        s = webString ;
        Serial.print ("whatis = "); Serial.println(whatis);
        s += whatis;
        
      }

      else if ( req.startsWith("/pinnum?") ) {
        s = webString ;
        Serial.print ("pinnum = "); Serial.println(pinnum);
        s += pinnum;
      }
        

      else if ( req.startsWith("/delaytime=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("delaytime = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the delaytime value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = delaytime_from; i < delaytime_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom delaytime:");
        for (int i = delaytime_from; i < delaytime_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-delaytime_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-delaytime_from]); 
          }
        EEPROM.commit();

        y = freq ;        
        s += "<p>Saved<p>";
        delaytime = strreqanswer.toInt() ;
        
        Serial.print ("delaytime = "); Serial.println(delaytime);
      }

      else if ( req.startsWith("/precision=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("precision = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the precision value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = precision_from; i < precision_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom precision:");
        for (int i = precision_from; i < precision_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-precision_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-precision_from]); 
          }
        EEPROM.commit();
        y = freq ;        

        s += "<p>Saved<p>";
        precision = strreqanswer.toInt() ;
        
        Serial.print ("precision = "); Serial.println(precision);
      }

      else if ( req.startsWith("/vprecision=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("vprecision = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the vprecision value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = vprecision_from; i < vprecision_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom vprecision:");
        for (int i = vprecision_from; i < vprecision_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-vprecision_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-vprecision_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        vprecision = strreqanswer.toInt() ;
        y = freq ;        
        Serial.print ("vprecision = "); Serial.println(vprecision);
      }

      else if ( req.startsWith("/tempreading=") ) {
//        s += "<p>Saving the temp reading value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("tempreading = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the temp reading value to " + strreqanswer + " <p>";

        Serial.println("clearing eeprom");
        for (int i = tempreading_from; i < tempreading_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom tempreading:");
        for (int i = tempreading_from; i < tempreading_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-tempreading_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-tempreading_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        tempreading = String(strreqanswer) ;
        
        Serial.print ("tempreading = "); Serial.println(tempreading);
      }

      else if ( req.startsWith("/details=") ) { // details = 0 or 1

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("details = ");
        Serial.println(strreqanswer);

        s += "<p>Saved<p>";
        details = strreqanswer.toInt() ;
        
      }
      
      else if ( req.startsWith("/button=") ) {
        s += "<p>Saving the button value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("Button = ");
        Serial.println(strreqanswer);

        Serial.println("clearing eeprom");
        for (int i = button_from; i < button_to; ++i) { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom button:");
        for (int i = button_from; i < button_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-button_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-button_from]); 
          }
        EEPROM.commit();

        s += "<p>Saved<p>";
        current = strreqanswer.toInt() ;
        if (devicetodo.substring(4,5) == "s" ) {
          digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
          buttonupdt = 1 ;
          senddatatoapi();
        }
//        adjtemp = strreqanswer.toFloat() ;
        Serial.print ("Button = "); Serial.println(current);
      }
      else if ( req.startsWith("/pushbutton=") ) {
        s += "<p>Saving the button value<p>";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("Push Button = ");
        Serial.println(strreqanswer);
/*
        Serial.println("clearing eeprom");
        for (int i = butt_from; i < butt_to; ++i) { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom butt:");
        for (int i = butt_from; i < butt_to; ++i)
          {
            EEPROM.write(i, strreqanswer[i-butt_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-butt_from]); 
          }
        EEPROM.commit();
*/
        s += "<p>Saved<p>";
        
        pushbutttime = strreqanswer.toInt() ;
        if ( pushbutttime == 0 ) {
           curr = 0 ;
           pbstatus = 0 ;
           digitalWrite(BUTT, curr == 1 ? HIGH : LOW);
           buttonupdt = 1 ;
           senddatatoapi();
        }
        else {
          curr = 1 ;
          pbstatus = 1 ;
        }
        Serial.print("pushbutttime = " ) ;
        Serial.println(pushbutttime);
        Serial.print("pbstatus = " ) ;
        Serial.println(pbstatus);
/*
        if (devicetodo.substring(8,9) == "b" ) {
          digitalWrite(BUTT, curr == O ? HIGH : LOW);
          senddatatoapi();
        }
*/
        Serial.print ("Push Butt = "); Serial.println(curr);
      }
      else if ( req.startsWith("/a?ssid=") ) {
        s += "<p>Saving your new WiFi Name and Password...<p>";

        newSSID = true;
        String qsid; //WiFi SSID 

        qsid = urldecode(req.substring(8,req.indexOf('&')).c_str()); //correct coding for spaces as "+"
        Serial.println(qsid);
        Serial.println("");
        rsid = qsid;
        
        String qpass; //Wifi Password
        qpass = urldecode(req.substring(req.lastIndexOf('=')+1).c_str());//correct for coding spaces as "+"
        Serial.println(qpass);
        Serial.println("");
        rpass = qpass;
      
        Serial.println("clearing eeprom");
        for (int i = 0; i < 97; ++i) { EEPROM.write(i, clearchar[0]) ; }

        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();
        
        Serial.print("1st eeprom char="); Serial.println(char(EEPROM.read(0)));
        Serial.println("writing eeprom ssid:");
        for (int i = 1; i < qsid.length(); ++i)
          {
            EEPROM.write(i, qsid[i-1]);
            Serial.print("Wrote: ");
            Serial.println(qsid[i-1]); 
          }
        Serial.println("writing eeprom pass:"); 
        for (int i = 0; i < rpass.length(); ++i)
          {
            EEPROM.write(33+i, rpass[i]);
            Serial.print("Wrote: ");
            Serial.println(rpass[i]); 
          }    
        EEPROM.commit();
//        s += "<p> New SSID and Password accepted</html>\r\n\r\n"; 
        s += "<p> Your new WiFi Name and Password saved</p>"; 
        s += "<p> Trying to connect to your WiFi with it.</p>"; 
        s += "<p> Check your WiFi network in the next minute.</p>";
        s += "<p>If AAAP is still available and you can connect to it,</p>";
        s += "<p>your WiFi credentials were wrong. </p>";
//        s += "<p>you should go to <a href='/192.168.4.1' target='_self'>192.168.4.1</a> and retype your WiFi credentials</p>"; 
//        s += "<p>Click <a href='/' target='_blank'>here</a> to retype your WiFi credentials</p>"; 
        s += "<p> </p>"; 
        s += "<p>Click <a href='http://192.168.4.1' target='_self'>here</a> to retype your WiFi credentials</p>"; 
        y = freq ;        
        
//        return (20) ;
//        s += "</html>\r\n\r\n"; 
      }
      else if ( req.startsWith("/readeeprom?") ) {
        s = webString ;
            String readeepr = "";
            readeepr += char(EEPROM.read(0));
            for (int i = freq_from ; i < eeprom_to; ++i)
            {
              readeepr += char(EEPROM.read(i));
            }
            Serial.print("Normal Level:");
            Serial.print(readeepr);
        s += readeepr;
        Serial.print ("readeepr = "); Serial.println(readeepr);
      }

      else if ( req.startsWith("/frequency=") ) {
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation";
        s += "<p>Saving the transmission frequency<p>";
//        s += "</html>\r\n\r\n";

        String strfreq = req.substring(req.lastIndexOf('=')+1);
        Serial.print("frequency = ");
        Serial.println(strfreq);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        Serial.println("clearing eeprom");
//        for (int i = 97; i < 103; ++i) { EEPROM.write(i, clearchar[0]; }
          for (int i = freq_from; i < freq_to; ++i) 
            { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom frequency:");
//        for (int i = 97; i < 103; ++i)
          for (int i = freq_from; i < freq_to; ++i)
          {
            EEPROM.write(i, strfreq[i-freq_from]);
            Serial.print("Wrote: ");
            Serial.println(strfreq[i-freq_from]); 
          }
        EEPROM.commit();
        Serial.print("frequency toInt = ");
        Serial.println(strfreq.toInt());
        
        freq = strfreq.toInt();
/*
        if (freq < 50) {
          freq = 50;
        }
*/
        Serial.print ("frequency = "); Serial.println(freq);
        s += "<p>Saved<p>";

      }

      else if ( req.startsWith("/rebootfreq=") ) {
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation";
        s += "<p>Saving the frequency for rebooting<p>";
//        s += "</html>\r\n\r\n";

        String strfreq = req.substring(req.lastIndexOf('=')+1);
        Serial.print("frequency = ");
        Serial.println(strfreq);

        Serial.println("clearing eeprom");
//        for (int i = 103; i < 106; ++i) 
        for (int i = rebootfreq_from; i < rebootfreq_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();
    
        Serial.println("writing eeprom ssid:");
//        for (int i = 103; i < 106; ++i)
        for (int i = rebootfreq_from; i < rebootfreq_to; ++i)
          {
            EEPROM.write(i, strfreq[i-rebootfreq_from]);
            Serial.print("Wrote: ");
            Serial.println(strfreq[i-rebootfreq_from]); 
          }
        EEPROM.commit();
            rebootfreq = strfreq.toInt();

          if (rebootfreq == 999) {
//            rebootfreq = strfreq.toInt();
            Serial.print ("Rebooting frequency = "); Serial.println(rebootfreq);
          }
          else {
            rebootfreq = 3600 * strfreq.toInt();
          }

        Serial.print ("Rebooting frequency = "); Serial.println(rebootfreq);
        s += "<p>Rebooting frequency saved<p>";

      }

      else if ( req.startsWith("/clientcode=") ) {
//        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from Boat Automation";
        s += "<p>Saving the client code<p>";
//        s += "</html>\r\n\r\n";

        clientcode = req.substring(req.lastIndexOf('=')+1);
        Serial.print("clientcode = ");
        Serial.println(clientcode);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        Serial.println("clearing eeprom");
//        for (int i = 106; i < 136; ++i) { EEPROM.write(i, clearchar[0]); }
        for (int i = clientcode_from; i < clientcode_to; ++i)
            { EEPROM.write(i, clearchar[0]) ; }
        Serial.println("writing eeprom ssid:");
//        for (int i = 106; i < 136; ++i)
         for (int i = clientcode_from; i < clientcode_to; ++i)
          {
            EEPROM.write(i, clientcode[i-clientcode_from]);
            Serial.print("Wrote: ");
            Serial.println(clientcode[i-clientcode_from]); 
          }
        EEPROM.commit();
        s += "<p>Saved<p>";
      }
      else if ( req.startsWith("/reboot=now") ) {
          s += "<p>Rebooting now<p>";
          rebootfreq = 9999 ;
/*          Serial.println("Rebooting");
          delay(500);
          ESP.restart(); 
*/
      }

      else if ( req.startsWith("/clientcode?") ) {
        s = webString ;
        s += clientcode;
        Serial.print ("clientcode = "); Serial.println(clientcode);
      }
      else if ( req.startsWith("/adjtempadd?") ) {
        s = webString ;
        s += adjtemp;
        Serial.print ("adjtemp = "); Serial.println(adjtemp);
      }
      else if ( req.startsWith("/adjtemp2add?") ) {
        s = webString ;
        s += adjtemp2;
        Serial.print ("adjtemp2 = "); Serial.println(adjtemp2);
      }

      else if ( req.startsWith("/adjvoltdiv?") ) {
        s = webString ;
        s += adjvolt;
        Serial.print ("adjvolt = "); Serial.println(adjvolt);
      }

          
      else if ( req.startsWith("/adjtemp=") ) {
//        writeeeprom(req,adjtemp_from, adjtemp_to);
                strreqanswer = req.substring(req.lastIndexOf('=')+1);
                Serial.print("new temp = ");
                Serial.println(strreqanswer);
/*
        if (strreqanswer != "0" )
        {
*/          
            float temperaturetest = 0 ;
//            int i = 0 ;
//            for ( i ; i < 10; ++i){
               gettemp() ;
               if (temptemp > -127 ) {
                 temperaturetest = temptemp ;
//            }
//            temperaturetest = temperaturetest / i ;
//              s += "<p>Saving the adjust temperature value from " + String(valuedev1) + " to " + adjtemp + " <p>";
              s += "<p>Saving the temperature value from " + String(temptemp) + " to " + String(strreqanswer) + " <p>";

                strreqanswer = String ( strreqanswer.toFloat() - temperaturetest ) ;
//          s += "</html>\r\n\r\n";

        
              String firsteeprom = "9";
              EEPROM.write(0, firsteeprom[0] );
              EEPROM.commit();
  
              Serial.println("clearing eeprom");
//            for (int i = 136; i < 140; ++i) 
              for (int i = adjtemp_from; i < adjtemp_to; ++i)
                { EEPROM.write(i, clearchar[0]) ; }
    
                Serial.println("writing eeprom adjtemp:");
//              for (int i = 136; i < 140; ++i)
              for (int i = adjtemp_from; i < adjtemp_to; ++i)
              {
              EEPROM.write(i, strreqanswer[i-adjtemp_from]);
              Serial.print("Wrote: ");
              Serial.println(strreqanswer[i-adjtemp_from]); 
            }
            EEPROM.commit();
            s += "<p>Saved<p>";
            y = freq ;        

            adjtemp = strreqanswer.toFloat() ;
            Serial.print ("adjtemp = "); Serial.println(adjtemp);
/*
          }
          else {
            Serial.println ("adjtemp not saved ");
            s += "<p>NOT Saved<p>";

          }
*/
        }
      }
      else if ( req.startsWith("/adjtemp2=") ) {
//        writeeeprom(req,adjtemp_from, adjtemp_to);
          strreqanswer = req.substring(req.lastIndexOf('=')+1);
          Serial.print("new temp2 = ");
          Serial.println(strreqanswer);
/*          
        if (strreqanswer != "0" )
        {
*/
            float temperaturetest = 0 ;
//            int i = 0 ;
//            for ( i ; i < 10; ++i){
               gettemp() ;
               if (temptemp2 > -127 ) {
                 temperaturetest = temptemp2 ;
//            }
//            temperaturetest = temperaturetest / i ;
//              s += "<p>Saving the adjust temperature value from " + String(valuedev1) + " to " + adjtemp + " <p>";
              s += "<p>Saving the temperature2 value from " + String(temptemp2) + " to " + String(strreqanswer) + " <p>";

                strreqanswer = String ( strreqanswer.toFloat() - temperaturetest ) ;
//          s += "</html>\r\n\r\n";

        
              String firsteeprom = "9";
              EEPROM.write(0, firsteeprom[0] );
              EEPROM.commit();
  
              Serial.println("clearing eeprom");
//            for (int i = 136; i < 140; ++i) 
              for (int i = adjtemp2_from; i < adjtemp2_to; ++i)
                { EEPROM.write(i, clearchar[0]) ; }
    
                Serial.println("writing eeprom adjtemp2:");
//              for (int i = 136; i < 140; ++i)
              for (int i = adjtemp2_from; i < adjtemp2_to; ++i)
              {
              EEPROM.write(i, strreqanswer[i-adjtemp2_from]);
              Serial.print("Wrote: ");
              Serial.println(strreqanswer[i-adjtemp2_from]); 
            }
            EEPROM.commit();
            s += "<p>Saved<p>";

            adjtemp2 = strreqanswer.toFloat() ;
            Serial.print ("adjtemp2 = "); Serial.println(adjtemp2);
            y = freq ;        

/*
          }

          else {
            Serial.println ("adjtemp2 not saved ");
            s += "<p>NOT Saved<p>";

          }
          */
        }
      }
      else if ( req.startsWith("/adjvolt=") ) {
//        writeeeprom(req,adjvolt_from, adjvolt_to);
        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        s += "<p>Saving the adjust volt value from " + String(valuedev3) + " to " + strreqanswer + "<p>";
//        s += "</html>\r\n\r\n";

//        strreqanswer = strreqanswer.toFloat() ;
//        Serial.print("adjvolt to= ");
//        Serial.println(strreqanswer);
        if (strreqanswer != "0" ){
//          getvolt();
//          strreqanswer = String (analogRead(A0) / strreqanswer.toFloat()) ;
            float analogtest = 0 ;
            int i = 0 ;
            for ( i ; i < 10; ++i){
               analogtest = analogtest + analogRead(A0) ;
            }
            analogtest = analogtest / i ;

          strreqanswer = String (analogtest / strreqanswer.toFloat()) ;

//          strreqanswer = String(strreqanswer) ; 
          Serial.print("adjvolt = ");
          Serial.println(strreqanswer);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        Serial.println("clearing eeprom");
//        for (int i = 136; i < 140; ++i) 
        for (int i = adjvolt_from; i < adjvolt_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom adjvolt:");
//        for (int i = 136; i < 140; ++i)
        for (int i = adjvolt_from; i < adjvolt_to; ++i)

          {
            EEPROM.write(i, strreqanswer[i-adjvolt_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-adjvolt_from]); 
          }
        EEPROM.commit();
        s += "<p> Adjvolt Factor = " + strreqanswer + " <p>";
        adjvolt = strreqanswer.toFloat() ;
        y = freq ;        
          s += "<p>Rebooting now<p>";
          rebootfreq = 9999 ;

/*
          Serial.println("Rebooting");
          delay(500);
          ESP.restart(); 
*/
        }
        else
        {
          s += "<p>NOT Saved<p>";
          Serial.println("Adjvolt not saved");
        }
        

        Serial.print ("adjvolt = "); Serial.println(adjvolt);
      }

      else if ( req.startsWith("/resolution=") ) {
        s += "<p>Saving the resolution value<p>";
//        s += "</html>\r\n\r\n";

        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("resolution = ");
        Serial.println(strreqanswer);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        Serial.println("clearing eeprom");
//        for (int i = 140; i < 141; ++i) 
        for (int i = resolution_from; i < resolution_to; ++i)

            { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("writing eeprom resolution:");
//        for (int i = 140; i < 141; ++i)
        for (int i = resolution_from; i < resolution_to; ++i)

          {
            EEPROM.write(i, strreqanswer[i-resolution_from]);
            Serial.print("Wrote: ");
            Serial.println(strreqanswer[i-resolution_from]); 
          }
        EEPROM.commit();
        s += "<p>Saved<p>";

        resolution = strreqanswer.toInt() ;
        y = freq ;        
//        sensors.setResolution(0,resolution);
        Serial.print ("resolution = "); Serial.println(resolution);
      }

      else if ( req.startsWith("/all?") ) {
        s = "" ;
        rssi = abs(WiFi.RSSI());
        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "signal:"+String(rssi)+",";
        s += "macid:"+String(MAC_char)+",";
        s += "numtemp:"+String(numtemp)+",";
        s += "resolution:"+String(resolution)+",";
        s += "adjtemp:"+String(adjtemp)+",";
        s += "adjtemp2:"+String(adjtemp2)+",";
        s += "devicetype:"+devicetype+",";
        s += "freq:"+String(freq)+",";
//        s += "rebootfreq:"+String(rebootfreq/3600)+",";
          if (rebootfreq == 999) {
            s += "rebootfreq="+String(rebootfreq)+",";          }
          else {
            s += "rebootfreq="+String(rebootfreq/3600)+",";
          }
        if (devicetodo.startsWith("t") ) {
          gettemp();
          s += "temp:"+ String(temptemp) + ",";
          s += "temp:"+ String(temptemp2) + ",";
        }
        s += "button = " + String(current) + ",";
        s += "pump = " + String(Pcurrent) + ",";
        s += "IP:"+ ipadd + ",";
        s += "who:" + who + ",";
        s += "network:" + rsid;
        Serial.print ("All = "); Serial.println(s);
        s = webString + s;
      }
      else if ( req.startsWith("/info?") ) {
        s = "" ;
        rssi = abs(WiFi.RSSI());
        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "signal="+String(rssi)+"&";
        s += "macid="+String(MAC_char)+"&";
        s += "devicetype="+devicetype+"&";
        s += "freq="+String(freq)+"&";
//        s += "rebootfreq="+String(rebootfreq/3600)+"&";
          if (rebootfreq == 999) {
            s += "rebootfreq="+String(rebootfreq)+"&";          }
          else {
            s += "rebootfreq="+String(rebootfreq/3600)+"&";
          }
          s += "whatis="+String(whatis)+"&";
        if (devicetodo.startsWith("t") ) {
          gettemp();
//          s += "temp="+ String(valuedev1) + "&";
          s += "temp="+ String(temptemp) + "&";
          s += "temp2="+ String(temptemp2) + "&";
          s += "numtemp="+String(numtemp)+"&";
          s += "resolution="+String(resolution)+"&";
          s += "tempdiff="+String(tempdiff)+"&";
          s += "adjtemp="+String(adjtemp)+"&";
          s += "adjtemp2="+String(adjtemp2)+"&";
          s += "precision="+String(precision)+"&";
        }
        if (devicetodo.substring(2,3) == "v" ) {
          s += "volt="+ String(valuedev3) + "&";
          s += "voltdiff="+String(voltdiff)+"&";
          s += "adjvolt="+String(adjvolt)+"&";
          s += "vprecision="+String(vprecision)+"&";
        }
        
        if (devicetodo.substring(6,7) == "p" ) {
          s += "pump = " + String(Pcurrent) + "&";
        }
       if (devicetodo.substring(4,5) == "s" ) {
         s += "button = " + String(current) + "&";
       }
       if (devicetodo.substring(8,9) == "b" ) {
         s += "butt = " + String(curr) + " for " + String(pushbutttime) + "s&";
       }
        s += "IP="+ ipadd + "&";
//        s += "pass:" + rpass + "&";
        s += "who=" + who + "&";
        s += "network=" + rsid;
        Serial.print ("Info = "); Serial.println(s);
        s = webString + s;
      }


      else if ( req.startsWith("/frequency?") ) {
        s = webString ;
 //       readeeprom(req,freq_from, freq_to);
//        freq = freq/10 ;
        Serial.print ("frequency = "); Serial.println(freq);
        s += freq;
        
        Serial.print ("frequency = "); Serial.println(freq);
      }
      else if ( req.startsWith("/adjtemp?") ) {
        s = webString ;
        s += adjtemp;
        Serial.print ("adjtemp = "); Serial.println(adjtemp);
      }
      else if ( req.startsWith("/adjtemp2?") ) {
        s = webString ;
        s += adjtemp2;
        Serial.print ("adjtemp2 = "); Serial.println(adjtemp2);
      }

      else if ( req.startsWith("/adjvolt?") ) {
        s = webString ;
        s += adjvolt;
        Serial.print ("adjvolt = "); Serial.println(adjvolt);
      }

      else if ( req.startsWith("/tempdiff?") ) {
        s = webString ;
        s += tempdiff;
        Serial.print ("tempdiff = "); Serial.println(tempdiff);
      }
      
      else if ( req.startsWith("/voltdiff?") ) {
        s = webString ;
        s += voltdiff;
        Serial.print ("voltdiff = "); Serial.println(voltdiff);
      }
      
      else if ( req.startsWith("/delaytime?") ) {
        s = webString ;
        s += delaytime;
        Serial.print ("delaytime = "); Serial.println(delaytime);
      }

      else if ( req.startsWith("/devicetype?") ) {
        s = webString ;
        s += devicetype;
        Serial.print ("devicetype = "); Serial.println(devicetype);
      }

      else if ( req.startsWith("/resolution?") ) {
        s = webString ;
        s += resolution ;
        Serial.print ("resolution = "); Serial.println(resolution);
      } 

      else if ( req.startsWith("/precision?") ) {
        s = webString ;
        s += precision ;
        Serial.print ("precision = "); Serial.println(precision);
      }

      else if ( req.startsWith("/vprecision?") ) {
        s = webString ;
        s += vprecision ;
        Serial.print ("vprecision = "); Serial.println(vprecision);
      }

      else if ( req.startsWith("/tempreading?") ) {
        s = webString ;
        s += tempreading ;
        Serial.print ("tempreading = "); Serial.println(tempreading);
      }
      else if ( req.startsWith("/rebootfreq?") ) {
        s = webString ;
        Serial.print ("Reboot frequency = "); Serial.println(rebootfreq);
 //       readeeprom(req,freq_from, freq_to);
//        rebootfreq = rebootfreq/36000 ;
//        rebootfreq = rebootfreq/3600 ;
        Serial.print ("Reboot frequency = "); Serial.println(rebootfreq);
//      s += rebootfreq/3600;
          if (rebootfreq == 999) {
            s += rebootfreq ;
          }
          else {
            s += rebootfreq/3600;
          }

      }

      else if ( req.startsWith("/macid?") ) {
        s = webString ;
        Serial.print ("Mac id = "); Serial.println(String(MAC_char));
        s += String(MAC_char);
      }

      else if ( req.startsWith("/who?") ) {
        s = webString ;
        Serial.print ("Who = "); Serial.println(who);
        s += who;
      }

      else if ( req.startsWith("/signal?") ) {
        s = webString ;
        rssi = abs(WiFi.RSSI());
        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += String(rssi);
      }

      else if ( req.startsWith("/numtemp?") ) {
        s = webString ;
        s += String(numtemp);
        Serial.print ("number of temp senders = "); Serial.println(String(numtemp));
        s += String(numtemp);
      }
      else if ( req.startsWith("/temp?") ) {
        s = webString ;
        if (devicetodo.startsWith("t") ) {
          gettemp();
          s += String(valuedev1);
        }
        else {
          s += "n/a";
        }
      }

      else if ( req.startsWith("/button?") ) {
        s = webString ;
        
        s += String(current);
        // write the current state to the power switch tail
//        digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
        Serial.print ("Button = "); Serial.println(current);
      }

      else if ( req.startsWith("/pump?") ) {
        s = webString ;
        
        s += String(Pcurrent);
        // write the current state to the power switch tail
//        digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
        Serial.print ("Pump = "); Serial.println(Pcurrent);
      }
      else
      {
        s += "Command not found";
//        s += "HTTP/1.1 404 Not Found\r\n\r\n";
//        s = "HTTP/1.1 404 Not Found\r\n\r\n";
        Serial.println("Sending 404");
      }       
  }

  s += "</html>\r\n\r\n";
  client.print(s);
  Serial.println("Done with client");
  return(20);
}


void loop(void) {
  // put your main code here, to run repeatedly:
  Serial.print("in the loop - x = ");  Serial.println(x);

  x += 1;

}

////void transmitdata(){
//  Serial.print( "transmitting data");
//  Serial.print(" - x = "); Serial.print(x);     Serial.print(" - y = "); Serial.println(y);
////  gettemp();
////}

void reconnectI() {
  if ( testWifi()) {
          Serial.print ("in testwifi 0");
          return;
      }
  // otherwise, set up an access point to input SSID and password     
  else
  {
      Serial.println("");
      Serial.println("Connect timed out, opening AP"); 
      setupAP();
  }
}    

void torun() {
//  Serial.print("x = "); Serial.print(x);     Serial.print(" - y = "); Serial.println(y);
  pb += 1 ;
    PSerial("pbstatus = ");PlnSerial (String (pbstatus)) ;
    PSerial("curr = ");PlnSerial (String (curr)) ;
  if (pbstatus == 1 ) {
    PSerial("in if pbstatus = ");PlnSerial (String (pbstatus)) ;
//    digitalWrite(BUTT, HIGH);
      digitalWrite(BUTT, curr == 1 ? HIGH : LOW);
      buttonupdt = 1 ;
      senddatatoapi();
    pbstatus = 2 ;
    pbtime = pb ;
//    curr = 0 ;
//    pushbutttime
  }
  else if (pbstatus == 2 ) {
    
    PSerial("in else pbtime = ");PlnSerial (String (pbtime)) ;
    PSerial("in else pb = ");PlnSerial (String (pb)) ;
    PSerial("in else pushbutttime + pbtime = ");PlnSerial (String (pushbutttime+pbtime)) ;
    if (pb > pushbutttime + pbtime ) {
      curr = 0 ;
      PSerial("in if pb > pushbutttime = ");PlnSerial (String (pushbutttime)) ;
      digitalWrite(BUTT, curr == 1 ? HIGH : LOW);
      buttonupdt = 1 ;
      senddatatoapi();
      pbtime = 0 ;
      pushbutttime = 0 ;
      pbstatus = 0 ;
    }
  
  }
/*
  else if (pbstatus == 0 ) {  // ???????
      curr = 0 ;
      PlnSerial("in if pbstatus = 0");
      digitalWrite(BUTT, curr == 1 ? HIGH : LOW);
      senddatatoapi();
      pbtime = 0 ;
      pushbutttime = 0 ;
      pbstatus = 0 ;
  }
*/
    if (WiFi.status() == WL_CONNECTED) {
       x += 1 ;
       y += 1 ;
       v += 1 ;
       t += 1 ;
       t2 += 1 ;
       ap = ap + 1 ;
       Serial.print("ap = ");Serial.println (String (ap));
      if (freq == 999999) {

      }
      else {
        if ( y > freq + 1) { //  || y == 1 ) {
          if (devicetodo.startsWith("t") ) {
              if (v > 1 ) {
                PSerial("oldtemptest = ");PlnSerial (String (oldtemptest));
                PSerial("valuedev1 = ");PlnSerial (String (valuedev1));
                PSerial("oldtemptest2 = ");PlnSerial (String (oldtemptest2));
                PSerial("valuedev2 = ");PlnSerial (String (valuedev2));
                if (valuedev1 != -127) {
                   oldtemptest= valuedev1 ;
                }
                else {
                  oldtemptest = 200 ;
                }
                if (valuedev2 != -127) {
                   oldtemptest2= valuedev2 ;
                }
                else {
                  oldtemptest2 = 200 ;
                }
                
              }
              else {
                valuedev1 = -127 ;
                PSerial("in v=0 valuedev1 = ");PlnSerial (String (valuedev1));
                valuedev2 = -127 ;
                PSerial("in v=0 valuedev2 = ");PlnSerial (String (valuedev2));
              }
          }
          
          if (devicetodo.substring(2,3) == "v" ) {
            getvolt();

            oldvolttest= voltvolt ;
            PSerial("oldvolttest = ");PlnSerial (String (oldvolttest)) ;
            voltvolt = (oldvolt + valuedev3) / v ;
            PSerial("voltvolt = ");PlnSerial (String (voltvolt)) ;
            valuedev3 = voltvolt ;
              if (vprecision == 1) {
                valuedev3 = round(valuedev3 * 10);
                valuedev3 = valuedev3/10 ;
                PSerial("valuedev3 after making it 1 decimal = ");PlnSerial (String (valuedev3));
                valuedev3 = (int) round(valuedev3) ;                
                PSerial("valuedev3 after making it integer and rounded = ");PlnSerial (String (valuedev3));
              }
              else {
                valuedev3 = round(valuedev3 * vprecision);
                valuedev3 = valuedev3/vprecision ;                    
              }

            valuedev3 = round(valuedev3 * vprecision);
            valuedev3 = valuedev3/vprecision ;                    
            PSerial("oldvolttest = ");PlnSerial (String (oldvolttest)) ;
            PSerial("valuedev3 = ");PlnSerial (String (valuedev3) );
          }
          if (devicetodo.substring(6,7) == "p" ) {
            Pcurrent = digitalRead(PUMP1);
//            PSerial ("");
//            PSerial ("PUMP1 = "); PlnSerial(String(current)) (
            Pcurrentold = Pcurrent ;
          }
          if (devicetodo.substring(11,13) == "a" ) {
              getpressure();
              get280();
              if (oldpressureKPA == 0) {
                oldpressureKPA = pressureKPA;
              }
              if (pressureKPA < 3000 ) {
//                ap += 1;
                pressureKPA = (oldpressureKPA + pressureKPA)/2;
                PSerial("pressureKPA = ");PlnSerial (String (pressureKPA));
                Serial.print("pressureKPA 1 = ");Serial.println (String (pressureKPA));
                oldpressureKPA = pressureKPA ;
              }
              else {
                pressureKPA = oldpressureKPA ;
                PSerial("Could not read ap - pressureKPA = ");PlnSerial (String (pressureKPA));
                Serial.print("Could not read ap - pressureKPA = ");Serial.println (String (pressureKPA));
              }
            
          }

          senddatatoapi();
            t = 0 ;
            t2 = 0 ;
            y = 0;
            v = 0;
            ap = 0;
            oldtemp = 0;
            newtemp = 0;
            oldtemp2 = 0;
            newtemp2 = 0;
            oldvolt = 0;
            newvolt = 0;
            //oldpressureKPA = 0 ;
        
        }

        else
        {
          if (devicetodo.substring(12,13) == "a" ) {
              getpressure();
              get280();
              if (pressureKPA < 3000 ) {
                if (oldpressureKPA == 0) {
                  oldpressureKPA = pressureKPA;
                }                
                pressureKPA = (oldpressureKPA + pressureKPA)/2;
                Serial.print("pressureKPA 2 = ");Serial.println (String (pressureKPA));
                Serial.print("ap 2 = ");Serial.println (String (ap));
                if (abs(oldpressureKPA - pressureKPA) > 1){
                  PSerial("in abs oldpressureKPA = ");PlnSerial (String (oldpressureKPA));
                  senddatatoapi();
                  ap = 0;
                }
                PSerial("pressureKPA = ");PlnSerial (String (pressureKPA));
                Serial.print("pressureKPA 3 = ");Serial.println (String (pressureKPA));
                oldpressureKPA = pressureKPA ;
              }
              else {
                pressureKPA = oldpressureKPA ;
                PSerial("Could not read ap - pressureKPA = ");PlnSerial (String (pressureKPA));
                Serial.print("Could not read ap - pressureKPA = ");Serial.println (String (pressureKPA));

              }
            
          }
          if (devicetodo.startsWith("t") ) {
            gettemp();
            if ( temptemp == -127 ) {
//              valuedev1 = "'n/a'" ;
                t = t - 1 ;
                valuedev1 = temptemp ;
//            PSerial("in bad temp v = ");PSerial(String(v));PSerial(" - y = ");PlnSerial (String ((y));
                  
            }
            else {
              if ( oldtemptest == 200 ){
                  oldtemptest= temptemp ;
              }
              PSerial("temptemp before adj = ");PlnSerial (String (temptemp));
              temptemp = temptemp + adjtemp ;
              PSerial("temptemp after adj = ");PlnSerial (String (temptemp));
              PSerial("oldtemp = ");PlnSerial (String (oldtemp));
              newtemp = oldtemp + temptemp  ;
              PSerial("newtemp = ");PlnSerial (String (newtemp));
              valuedev1 = newtemp/t ;
              PSerial("valuedev1 after newtemp/t = ");PlnSerial (String (valuedev1));
              if (precision == 1) {
                valuedev1 = round(valuedev1 * 10);
                valuedev1 = valuedev1/10 ;
                PSerial("valuedev1 after making it 1 decimal = ");PlnSerial (String (valuedev1));
                valuedev1 = (int) round(valuedev1) ;                
                PSerial("valuedev1 after making it integer and rounded = ");PlnSerial (String (valuedev1));
              }
              else {
                valuedev1 = round(valuedev1 * precision);
                PSerial("valuedev1 after * precision = ");PlnSerial (String (valuedev1));
                valuedev1 = valuedev1/precision ;
              }                    
              PSerial("valuedev1 after / precision= ");PlnSerial (String (valuedev1));
              oldtemp = newtemp;
              temptemp = (oldtemp + valuedev1) / t ; // ?????????????
              PSerial("temptemp after oldtemp = ");PlnSerial (String (temptemp));
              if ( thermostat == 1 ){
                if (heater == 1) {
                  if ( valuedev1 < heattostart) {
                    current = 1;
//                  digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
                  }
                  else {
                    current = 0 ;
//                  digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
                  }
                  digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
                  buttonupdt = 1 ;
                  senddatatoapi();
                }
              }

            PSerial("oldtemptest = ");PlnSerial (String (oldtemptest));
            PSerial("valuedev1 = ");PlnSerial (String (valuedev1));
            PSerial("diffence = ");PlnSerial (String (abs(valuedev1 - oldtemptest)));
              if (abs(valuedev1 - oldtemptest) > tempdiff ) { // abs(valuedev1/tempdiff)) {
                PSerial("differnce = ");PlnSerial (String (abs(valuedev1 - oldtemptest)));
                PSerial("oldtemptest in if= ");PlnSerial (String (oldtemptest));
                PSerial("valuedev1 in if = ");PlnSerial (String (valuedev1));
                senddatatoapi();
                oldtemptest= valuedev1 ;
              }
  
            }
            if ( temptemp2 == -127 ) {
//              valuedev1 = "'n/a'" ;
                t2 = t2 - 1 ;
                valuedev2 = temptemp2 ;
//            PSerial("in bad temp v = ");PSerial(String(v));PSerial(" - y = ");PlnSerial (String ((y));
                  
            }
            else if ( numtemp == 2 ) {
              if ( oldtemptest2 == 200 ){
                  oldtemptest2= temptemp2 ;
              }
              PSerial("temptemp2 before adj = ");PlnSerial (String (temptemp2));
              temptemp2 = temptemp2 + adjtemp2 ;
              PSerial("temptemp2 after adj = ");PlnSerial (String (temptemp2));
              PSerial("oldtemp2 = ");PlnSerial (String (oldtemp2));
              newtemp2 = oldtemp2 + temptemp2  ;
              PSerial("newtemp2 = ");PlnSerial (String (newtemp2));
              valuedev2 = newtemp2/t2 ;
              PSerial("valuedev2 after newtemp2/t2 = ");PlnSerial (String (valuedev2));
              if (precision == 1) {
                valuedev2 = round(valuedev2 * 10);
                valuedev2 = valuedev2/10 ;
                PSerial("valuedev2 after making it 1 decimal = ");PlnSerial (String (valuedev2));
                valuedev2 = (int) round(valuedev2) ;                
                PSerial("valuedev2 after making it integer and rounded = ");PlnSerial (String (valuedev2));
              }
              else {
                valuedev2 = round(valuedev2 * precision);
                PSerial("valuedev2 after * precision = ");PlnSerial (String (valuedev2));
                valuedev2 = valuedev2/precision ;                    
                PSerial("valuedev2 after / precision= ");PlnSerial (String (valuedev2));
              }
              oldtemp2 = newtemp2;
              temptemp2 = (oldtemp2 + valuedev2) / t2 ; // ?????????????
              PSerial("temptemp2 after oldtemp2 = ");PlnSerial (String (temptemp2));
/*
              if ( thermostat == 1 ){
                if (heater == 1) {
                  if ( valuedev1 < heattostart) {
                    current = 1;
//                  digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
                  }
                  else {
                    current = 0 ;
//                  digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
                  }
                  digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
                  senddatatoapi();
                }
              }
*/              

            PSerial("oldtemptest2 = ");PlnSerial (String (oldtemptest2));
            PSerial("valuedev2 = ");PlnSerial (String (valuedev2));
            PSerial("diffence2 = ");PlnSerial (String (abs(valuedev2 - oldtemptest2)));
              if (abs(valuedev2 - oldtemptest2) > tempdiff ) { // abs(valuedev1/tempdiff)) {
                PSerial("difference2 = ");PlnSerial (String (abs(valuedev2 - oldtemptest2)));
                PSerial("oldtemptest2 in if= ");PlnSerial (String (oldtemptest2));
                PSerial("valuedev2 in if = ");PlnSerial (String (valuedev2));
                senddatatoapi();
                oldtemptest2= valuedev2 ;
              }
  
            }
          }
         
          if (devicetodo.substring(6,7) == "p" ) {
//            digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
            Pcurrent = digitalRead(PUMP1);
            PSerial ("");
            PSerial ("PUMP = "); PlnSerial(String(current));
            PSerial ("old PUMP = "); PlnSerial(String(currentold));
            if (Pcurrentold != Pcurrent ) {
              PSerial("in change of pump status");
              senddatatoapi();
            }
            Pcurrentold = Pcurrent ;
          }
          if (devicetodo.substring(2,3) == "v" ) {
            getvolt();
            if ( oldvolttest == 200 ){
                oldvolttest= voltvolt ;
            }
              PSerial("x = ");PlnSerial (String (x));
              PSerial("y = ");PlnSerial (String (y));
              PSerial("t = ");PlnSerial (String (t));
              PSerial("v = ");PlnSerial (String (v));
              PSerial("adjvolt = ");PlnSerial (String (adjvolt));
              PSerial("oldvolt = ");PlnSerial (String (oldvolt));
              PSerial("oldvolttest= ");PlnSerial (String (oldvolttest));
              PSerial("newvolt = ");PlnSerial (String (newvolt));
              PSerial("valuedev3 = ");PlnSerial (String (valuedev3));

              newvolt = oldvolt + voltvolt  ;
              PSerial("voltvolt = ");PlnSerial (String (voltvolt));
              PSerial("newvolt = ");PlnSerial (String (newvolt));
              valuedev3 = newvolt/v ;
              PSerial("valuedev3 = ");PlnSerial (String (valuedev3));
              if (vprecision == 1) {
                valuedev3 = round(valuedev3 * 10);
                valuedev3 = valuedev3/10 ;
                PSerial("valuedev3 after making it 1 decimal = ");PlnSerial (String (valuedev3));
                valuedev3 = (int) round(valuedev3) ;                
                PSerial("valuedev3 after making it integer and rounded = ");PlnSerial (String (valuedev3));
              }
              else {
                valuedev3 = round(valuedev3 * vprecision);
                valuedev3 = valuedev3/vprecision ;                    
                PSerial("valuedev3 = ");PlnSerial (String (valuedev3));
              }
              oldvolt = newvolt;

//            if (abs(valuedev3 - oldvolttest) > voltdiff ) { // abs(valuedev1/tempdiff)) {
            if (abs(voltvolt - oldvolttest) > voltdiff ) { // abs(valuedev1/tempdiff)) {
              PSerial("volt difference = ");PlnSerial (String (abs(voltvolt - oldvolttest)));
              PSerial("oldvolttest in if= ");PlnSerial (String (oldvolttest));
              PSerial("valuedev3 in if = ");PlnSerial (String (valuedev3));
              PSerial("voltvolt in if = ");PlnSerial (String (voltvolt));
                valuedev3 = voltvolt ;
                senddatatoapi();
               oldvolt = 0;
               newvolt = 0;
               oldvolttest= voltvolt ;
               
               v = 0 ;
            }
          }
          if ( x == 1) {
//            valuedev1 = temptemp;
//            valuedev3 = voltvolt;
//            senddatatoapi();
              freq = 5 ;
              Serial.println("in x = 1") ;
//              Serial.print("Temp Frequency = "); Serial.println(freq);
//              Serial.print("Frequency = "); Serial.println(frequency);
          }
          else if (x == 1000 ) {
            freq = frequency ;
              Serial.println("in x = 1000") ;
//              Serial.print("Temp Frequency = "); Serial.println(freq);
//              Serial.print("Frequency = "); Serial.println(frequency);
          }
        }
      }
      if (rebootfreq == 999) {

      }
      else if (rebootfreq == 9999) {
          PlnSerial("Rebooting");
          delay(500);
          ESP.restart(); 
      }
      else {
        if (x == rebootfreq + (freq - 80)) { // reboot frequency plus freq minus 8/th of a second
          PlnSerial("Rebooting");
          delay(500);
          ESP.restart(); 
        }
      }
    }
  delay (delaytime*1000) ;
}

void senddatatoapi()
{  
  if ( !getPage() ) {
    PlnSerial("GET request failed");
  }
  else {
    PlnSerial("GET request succeded");
  }
}

bool getPage() {
   WiFiClient client;
  
  // Attempt to make a connection to the remote server
  if ( !client.connect(http_site, http_port) ) {
//   if (!client.connect(Accessip, Accesport)) {
    return false;
  }

   float temptodisp = (valuedev1*1.8)+32;
 
    if (precision == 1) {
           temptodisp = round(temptodisp * 10);
           temptodisp = temptodisp/10 ;
           PSerial("temptodisp after making it 1 decimal = ");PlnSerial (String (temptodisp));
           temptodisp = (int) round(temptodisp) ;                
           PSerial("temptodisp after making it integer and rounded = ");PlnSerial (String (temptodisp));
    }
    else {
      temptodisp = (round(temptodisp * precision) ) ; // / precision ;
      temptodisp = (temptodisp / precision)  ; // / precision ;
    }

 
  matrix.print(temptodisp, DEC);
  matrix.writeDisplay();

  String strvaluedev1 = "" ;
  
  if ( valuedev1 == -127 ) {
       strvaluedev1 = "n/a" ;
   }
   else {
      strvaluedev1 = String(valuedev1) ;
   }
  String strvaluedev2 = "" ;
  if ( valuedev2 == -127 ) {
       strvaluedev2 = "n/a" ;
   }
   else {
      strvaluedev2 = String(valuedev2) ;
   }
strvaluedev1 = temp_act;
strvaluedev2 = hum_act;
pressureKPA = press_act;
  String toprint = "" ;
  // Make an HTTP GET request
//  String toprint = "GET http://boatautomation.com/jojo/sendtoAPI-1.php?macid='"+String(MAC_char)+"'&temp1='"+String(valuedev1)+"'&temp2='"+String(valuedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq)+"'&rebootfreq='"+String(rebootfreq)+"'&ip='"+ipadd+"' HTTP/1.1" ;
  if ( buttonupdt == 1) {
    toprint = wheretosend + "?macid='"+String(MAC_char)+"'&baro='"+String(pressureKPA)+"'&pushbutton='"+String(curr)+"'&button='"+String(current)+"'&pump='"+String(Pcurrent)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq)+"'&rebootfreq='"+String(rebootfreq)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"' HTTP/1.1" ;
    buttonupdt = 0 ;
  }
  else {
//    toprint = wheretosend + "?macid='"+String(MAC_char)+"'&pump='"+String(Pcurrent)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq)+"'&rebootfreq='"+String(rebootfreq)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"' HTTP/1.1" ;
// changed on March 9 for barometric
//    toprint = wheretosend + "?macid='"+String(MAC_char)+"'&pushbutton='"+5+"'&button='"+5+"'&pump='"+String(Pcurrent)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq)+"'&rebootfreq='"+String(rebootfreq)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"' HTTP/1.1" ;
    toprint = wheretosend + "?macid='"+String(MAC_char)+"'&baro='"+String(pressureKPA)+"'&pushbutton='"+5+"'&button='"+5+"'&pump='"+String(Pcurrent)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq)+"'&rebootfreq='"+String(rebootfreq)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"' HTTP/1.1" ;
  }
  PSerial("toprint = "); PlnSerial(String(toprint));
  Serial.print("toprint = "); Serial.println(String(toprint));
  client.println(toprint);
////  client.println("GET /test.html HTTP/1.1");
  client.print("Host: ");
  client.println(wheretosend + "?macid='"+String(MAC_char)+"'&signal='"+String(rssi)+"'&pump='"+String(Pcurrent)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(valuedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq)+"'&rebootfreq='"+String(rebootfreq)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"'");



  delay(2000);
  while(client.available()){
    String line = client.readStringUntil('\r');
    PSerial("line = :");
    PlnSerial(String(line));

  }

  client.println("Connection: close");
  client.println();
  return true;
}

void getpressure(){
    pressureKPA = mpl115a2.getPressure();  
//    Serial.print("Pressure (kPa): "); Serial.print(pressureKPA, 4); Serial.println(" kPa");
    PSerial("Pressure (kPa): ");PSerial (String (pressureKPA, 4)) ; PlnSerial (" kPa") ;
    pressureKPA = 10*pressureKPA;  
//    Serial.print("Pressure (mpar): "); Serial.print(pressureKPA, 4); Serial.println(" mpar");
    PSerial("Pressure (mpar): ");PSerial (String (pressureKPA, 4)) ; PlnSerial (" mpar") ;
    Serial.print("Pressure (mpar): ");Serial.print (String (pressureKPA, 4)) ; Serial.println (" mpar") ;

              if (precision == 1) {
                pressureKPA = round(pressureKPA * 10);
                pressureKPA = pressureKPA/10 ;
                PSerial("pressureKPA after making it 1 decimal = ");PlnSerial (String (pressureKPA));
                pressureKPA = (int) round(pressureKPA) ;                
                PSerial("pressureKPA after making it integer and rounded = ");PlnSerial (String (pressureKPA));
              }
              else {
                pressureKPA = round(pressureKPA * precision) ;
                pressureKPA = pressureKPA / precision ;
                PSerial("pressureKPA after * precision = ");PlnSerial (String (pressureKPA));
              }                    

//  temperatureC = mpl115a2.getTemperature();  
//  Serial.print("Temp (*C): "); Serial.print(temperatureC, 1); Serial.println(" *C");
}

void gettemp() {
  
  tempv = ""; // added Feb 15
////    float temptemp;
////  String temperature;
  String temperature = "";
  sensors.requestTemperatures(); // Send the command to get temperatures

//  temptemp = sensors.getTempCByIndex(0);  // removed Feb 15

  // print the device information
  printData(insideThermometer);
  temptemp = tempv.toFloat(); 
  if (temptemp == -127.0) {
  }
  else {
    PSerial ("tempreading = "); PlnSerial(String(tempreading));
    if (precision == 1) {
           temptemp = round(temptemp * 10);
           temptemp = temptemp/10 ;
           PSerial("temptemp after making it 1 decimal = ");PlnSerial (String (temptemp));
           temptemp = (int) round(temptemp) ;                
           PSerial("temptemp after making it integer and rounded = ");PlnSerial (String (temptemp));
    }
    else {
      temptemp = (round(temptemp * precision) ) ; // / precision ;
      temptemp = (temptemp / precision)  ; // / precision ;
    }

    PSerial("temptemp: ");
    PlnSerial(String(temptemp));
    PSerial("temptemp after rounding: ");
    PlnSerial(String(temptemp));
  }

    printData(outsideThermometer);
    temptemp2 = tempv.toFloat(); 
//  temperature = String(temptemp);
//  temperature = String(temptemp + adjtemp);
//  Serial.print("Temperature  in C: ");
//  Serial.println(temperature);
  if (temptemp2 == -127.0) {
  }
  else {
    PSerial ("tempeading = "); PlnSerial(String(tempreading));
//    temptemp = temptemp + adjtemp ;
//    if ( tempreading  == "F" ) {
//      temptemp = (temptemp * 2) + 30 ;
//      //F = (C x 2) + 30
//    }
   if (precision == 1) {
           temptemp2 = round(temptemp2 * 10);
           temptemp2 = temptemp2/10 ;
           PSerial("temptemp2 after making it 1 decimal = ");PlnSerial (String (temptemp2));
           temptemp2 = (int) round(temptemp2) ;                
           PSerial("temptemp2 after making it integer and rounded = ");PlnSerial (String (temptemp2));
   }
   else {
     temptemp2 = (round(temptemp2 * precision) ) ; // / precision ;
     temptemp2 = (temptemp2 / precision)  ; // / precision ;
   }
    PSerial("temptemp2: ");
    PlnSerial(String(temptemp2));

/*
  PSerial("temptemp after rounding: ");
  PlnSerial(String(temptemp));
  Serial.print("precision: ");
  PlnSerial(String(precision));
*/
  PSerial("temptemp2 after rounding: ");
  PlnSerial(String(temptemp2));
    
  }
  
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) PSerial("0");
    PlnSerial(String(deviceAddress[i], HEX));
  }
}

// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  PSerial("Temp C: ");
  PSerial(String(tempC));
//  Serial.print(" Temp F: ");
//  Serial.print(DallasTemperature::toFahrenheit(tempC));
  PlnSerial(" ");    
    tempv=String(tempC);  
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  PSerial("Resolution: ");
  PSerial(String(sensors.getResolution(deviceAddress)));
  PlnSerial(" ");    
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  PSerial("Device Address: ");
  printAddress(deviceAddress);
  PSerial(" ");
  printTemperature(deviceAddress);
  PlnSerial(" ");
}

void getvolt(){
/*
float testvolt = 0 ;
int i = 0 ;
  for ( i ; i < 10; ++i){
//    testvolt = testvolt + analogRead(A0) ;
    testvolt = testvolt + (analogRead(A0) / adjvolt) ;
//    PSerial( i ); PSerial("testvolt = ");PlnSerial (String (testvolt));
    PSerial( i ); PSerial("analog = ");PlnSerial (String ((analogRead(A0) / adjvolt)));

  }
  voltvolt = testvolt / i ;
*/
//    PSerial("analog = ");PlnSerial (String (analogRead(A0));

  voltvolt =  (analogRead(A0) / adjvolt) ;
  voltvolt = (round(voltvolt * vprecision) ) ; // / precision ;
  voltvolt = (voltvolt / vprecision)  ; // / precision ;

    
////    voltvolt = analogRead(A0);
//        PSerial("volts = ");
//        PlnSerial(String(voltvolt));
//        PSerial("output: ");
//        PlnSerial(String(voltvolt));
//        PlnSerial(String(analogRead(A0));
//    voltvolt = voltvolt / adjvolt ;
//    voltvolt = (round(voltvolt * vprecision) ) ; // / precision ;
//    voltvolt = (voltvolt / vprecision)  ; // / precision ;
/*
  PSerial("voltvolt after rounding: ");
  PlnSerial(String(voltvolt));
  PSerial("vprecision: ");
  PlnSerial(String(vprecision));
  PSerial("voltvolt after rounding: ");
  PlnSerial(String(voltvolt));
*/    
  
}

void dowhatis() {
  thermostat = 0 ;
  aircond = 0 ;
  heater = 0 ;
  
if (whatis == "B") {
  devicetype = "temp-volt";
  devicetodo = "t,v,,,,,,,";
 }
 else if (whatis == "C") {
  devicetype = "temp-volt-switch";
  devicetodo = "t,v,s,,,,,,";
 } 
 else if (whatis == "D") {
  devicetype = "temp-volt-switch-pump";
  devicetodo = "t,v,s,p,,,,,";
 }
 else if (whatis == "E") {
  devicetype = "temp-switch";
  devicetodo = "t, ,s,,,,,,";
 }
 else if (whatis == "F") {
  devicetype = "temp-switch-heater";
  devicetodo = "t, ,s, , ,h,,,";
  thermostat = 1 ;
  heater = 1 ;
 }
 else if (whatis == "G") {
  devicetype = "temp-switch-a/c";
  devicetodo = "t, ,s, , ,a,,,";
  thermostat = 1 ;
  aircond = 1 ;  
 }
 else if (whatis == "H") {
  devicetype = "temp-switch-heater & A/C";
  devicetodo = "t, ,s, , ,b,,,";
  thermostat = 1 ;
  aircond = 1 ;  
  heater = 1 ;
 }
 else if (whatis == "I") {
  devicetype = "temp volt & atmospheric pressure";
  devicetodo = "t,v, , , , ,a,,";
 }

 else if (whatis == "P") {
  devicetype = "pump";
  devicetodo = " , , ,p,,,,,";
 }
 else if (whatis == "R") { // device means reading 0 - 1023 on adc
  devicetype = "dev";
  devicetodo = " , , ,d,,,,,";
 }
 else if (whatis == "S") {
  devicetype = "switch";
  devicetodo = " , ,s,,,,,,";
 }
else if ( whatis == "T") {
  devicetype = "temp";
  devicetodo = "t,,,,,,,,";
 }
 else if (whatis == "U") {
  devicetype = "push button";
  devicetodo = " , , , ,b,,,";
 }
 else if (whatis == "V") {
  devicetype = "volt";
  devicetodo = " ,v,,,,,,,";
 }
 else if (whatis == "W") {
  devicetype = "temp, volt, switch, pump & push button";
  devicetodo = "t,v,s,p,b,,,";
 }
 else if (whatis == "X") {
  devicetype = "temp & push button";
  devicetodo = "t, , , ,b,,,";
 }
 else {
  
 }

 if (devicetodo.substring(4,5) == "s" ) {

// relay pin
//  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(BUTTON, OUTPUT);
   
  // grab the current state of the button
  current = digitalRead(BUTTON);
  currentold = 0 ;

  PSerial ("");
  PSerial ("Button = "); PlnSerial(String(current));
 }


  if (devicetodo.substring(6,7) == "p" ) {
// relay pin
//    pinMode(PUMP1, INPUT_PULLUP);
    pinMode(PUMP1, INPUT);
    digitalWrite(PUMP1, LOW);

//  pinMode(BUTTON, OUTPUT);
   
  // grab the current state of the button
    Pcurrent = digitalRead(PUMP1);
    Pcurrentold = Pcurrent ;

    PSerial ("");
    PSerial ("Pump = "); PlnSerial(String(Pcurrent));
  }
 if (devicetodo.substring(8,9) == "b" ) {

// relay pin
//  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(BUTT, OUTPUT);
   
  // grab the current state of the button
  curr = digitalRead(BUTT);
  currold = 0 ;

  PSerial ("");
  PSerial ("Push Button = "); PlnSerial(String(curr));
 }
 if (devicetodo.substring(8,9) == "h" ) {

  thermostat = 1 ;
  heater = 1 ;
  PSerial ("");
  PSerial ("Heater is = "); PlnSerial(String(heater));
 }
 if (devicetodo.substring(8,9) == "a" ) {

  thermostat = 1 ;
  aircond = 1 ;
  PSerial ("");
  PSerial ("A/C is = "); PlnSerial(String(aircond));
 }

}

void PSerial(String value) {
  if (details != 0 ) {
    Serial.print(value);
  }
}

void PlnSerial(String value) {
  if (details != 0 ) {
    Serial.println(value);
  }
}

void pins(int pinp) {
  String pin = pinnum.substring(pinp,pinp+1) ;
  int pinpr = 0 ;
  if ( pin == "C" ) {
    pinpr = 12 ;
  }
  else if ( pin == "E" ) {
    pinpr = 13 ;
  }
  else if ( pin == "F" ) {
    pinpr = 14 ;
  }
  else if ( pin == "G" ) {
    pinpr = 15 ;
  }
  else if ( pin == "H" ) {
    pinpr = 16 ;
  }
  else  {
    pinpr = pin.toInt() ;
  }
  return  ;
}

void get280()
{
//    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;
    
    readData();
    
    temp_cal = calibration_T(temp_raw);
    press_cal = calibration_P(pres_raw);
    hum_cal = calibration_H(hum_raw);
    temp_act = (double)temp_cal / 100.0;
    press_act = (double)press_cal / 100.0;
    hum_act = (double)hum_cal / 1024.0;
    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");    
      temp_act = (round(temp_act * precision) ) ; // / precision ;
      temp_act = (temp_act / precision)  ; // / precision ;

      hum_act = (round(hum_act * precision) ) ; // / precision ;
      hum_act = (hum_act / precision)  ; // / precision ;

      press_act = press_act/100 ;
      press_act = (round(press_act * vprecision) ) ; // / precision ;
      press_act = (press_act / vprecision)  ; // / precision ;

    Serial.print("TEMP : ");
    Serial.print(temp_act);
    Serial.print(" DegC  PRESS : ");
    Serial.print(press_act);
    Serial.print(" hPa  HUM : ");
    Serial.print(hum_act);
    Serial.println(" %");    

    delay(1000);
}

void readTrim()
{
    uint8_t data[32],i=0;
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0x88);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,24);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xA1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,1);
    data[i] = Wire.read();
    i++;
    
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xE1);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,7);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;    
    }
    dig_T1 = (data[1] << 8) | data[0];
    dig_T2 = (data[3] << 8) | data[2];
    dig_T3 = (data[5] << 8) | data[4];
    dig_P1 = (data[7] << 8) | data[6];
    dig_P2 = (data[9] << 8) | data[8];
    dig_P3 = (data[11]<< 8) | data[10];
    dig_P4 = (data[13]<< 8) | data[12];
    dig_P5 = (data[15]<< 8) | data[14];
    dig_P6 = (data[17]<< 8) | data[16];
    dig_P7 = (data[19]<< 8) | data[18];
    dig_P8 = (data[21]<< 8) | data[20];
    dig_P9 = (data[23]<< 8) | data[22];
    dig_H1 = data[24];
    dig_H2 = (data[26]<< 8) | data[25];
    dig_H3 = data[27];
    dig_H4 = (data[28]<< 4) | (0x0F & data[29]);
    dig_H5 = (data[30] << 4) | ((data[29] >> 4) & 0x0F);
    dig_H6 = data[31];   
}
void writeReg(uint8_t reg_address, uint8_t data)
{
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(reg_address);
    Wire.write(data);
    Wire.endTransmission();    
}


void readData()
{
    int i = 0;
    uint32_t data[8];
    Wire.beginTransmission(BME280_ADDRESS);
    Wire.write(0xF7);
    Wire.endTransmission();
    Wire.requestFrom(BME280_ADDRESS,8);
    while(Wire.available()){
        data[i] = Wire.read();
        i++;
    }
    pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4);
    temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4);
    hum_raw  = (data[6] << 8) | data[7];
}


signed long int calibration_T(signed long int adc_T)
{
    
    signed long int var1, var2, T;
    var1 = ((((adc_T >> 3) - ((signed long int)dig_T1<<1))) * ((signed long int)dig_T2)) >> 11;
    var2 = (((((adc_T >> 4) - ((signed long int)dig_T1)) * ((adc_T>>4) - ((signed long int)dig_T1))) >> 12) * ((signed long int)dig_T3)) >> 14;
    
    t_fine = var1 + var2;
    T = (t_fine * 5 + 128) >> 8;
    return T; 
}

unsigned long int calibration_P(signed long int adc_P)
{
    signed long int var1, var2;
    unsigned long int P;
    var1 = (((signed long int)t_fine)>>1) - (signed long int)64000;
    var2 = (((var1>>2) * (var1>>2)) >> 11) * ((signed long int)dig_P6);
    var2 = var2 + ((var1*((signed long int)dig_P5))<<1);
    var2 = (var2>>2)+(((signed long int)dig_P4)<<16);
    var1 = (((dig_P3 * (((var1>>2)*(var1>>2)) >> 13)) >>3) + ((((signed long int)dig_P2) * var1)>>1))>>18;
    var1 = ((((32768+var1))*((signed long int)dig_P1))>>15);
    if (var1 == 0)
    {
        return 0;
    }    
    P = (((unsigned long int)(((signed long int)1048576)-adc_P)-(var2>>12)))*3125;
    if(P<0x80000000)
    {
       P = (P << 1) / ((unsigned long int) var1);   
    }
    else
    {
        P = (P / (unsigned long int)var1) * 2;    
    }
    var1 = (((signed long int)dig_P9) * ((signed long int)(((P>>3) * (P>>3))>>13)))>>12;
    var2 = (((signed long int)(P>>2)) * ((signed long int)dig_P8))>>13;
    P = (unsigned long int)((signed long int)P + ((var1 + var2 + dig_P7) >> 4));
    return P;
}

unsigned long int calibration_H(signed long int adc_H)
{
    signed long int v_x1;
    
    v_x1 = (t_fine - ((signed long int)76800));
    v_x1 = (((((adc_H << 14) -(((signed long int)dig_H4) << 20) - (((signed long int)dig_H5) * v_x1)) + 
              ((signed long int)16384)) >> 15) * (((((((v_x1 * ((signed long int)dig_H6)) >> 10) * 
              (((v_x1 * ((signed long int)dig_H3)) >> 11) + ((signed long int) 32768))) >> 10) + (( signed long int)2097152)) * 
              ((signed long int) dig_H2) + 8192) >> 14));
   v_x1 = (v_x1 - (((((v_x1 >> 15) * (v_x1 >> 15)) >> 7) * ((signed long int)dig_H1)) >> 4));
   v_x1 = (v_x1 < 0 ? 0 : v_x1);
   v_x1 = (v_x1 > 419430400 ? 419430400 : v_x1);
   return (unsigned long int)(v_x1 >> 12);   
}

