#include <Ticker.h>

// Compiling with: 
//  Debug level: OTA updater
//  debug Port: Serial
//  Flash Size: 4M, 3M SPIFS

// for OTA
#include <Arduino.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h> 

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

#include <OneWire.h>
#include <DallasTemperature.h>
#include <DHT.h>
#include <MAX31855.h>
#include <Wire.h>
//#include <Adafruit_MPL115A2.h>
#define BME280_ADDRESS 0x76
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
#define USE_SERIAL Serial
String versionnum = "4.01"; // compiled with DIO and 4M/1M
String firmware = "WSM";
String who = "" ;

//needs to be changed to 288000 for daily or 2016000 for weekly or 8640000 for every 30 days
int otatemp = 288000; // x number of revolutions to check for update - 


int debug = 0; // if 1 it bypasses wifi and goes directly to ap
//int debug = 0; // 4 and 14 are used for I2C

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

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

Adafruit_7segment matrix = Adafruit_7segment();

const char* host = "time.nist.gov"; // Round-robin DAYTIME protocol

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

//pumppin3 = pins(13) ;
int powerpin = 4 ;
int powerpin2 = 5 ;

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

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

#define POWER          powerpin
#define POWER2         powerpin2
#define BUTTON         buttonpin
#define PUMP1          pumppin1 // 5
#define BUTT           buttpin
#define HEATP          heaterpin
#define ACP            acpin
#define PUMP2          pumppin2 // 12
#define PUMP3          pumppin3 // 13
#define PUMP4          pumppin4 // 14

// SPI Pin connections.  
#define MISO 14
#define SCK  13
#define CS   12

//#define SDL            sdlpin
//#define SDA            sdapin
#define LED            15  // for blinking red light 
#define WD             16 // for watchdog connection

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


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

//String wheretosend = "GET http://boatautomation.com/api/sendtoAPI5.php" ;
String wheretosend = "GET http://api.aacdata.net/sendtoAPI5.php" ;
//String wheretosend = "GET http://aacdata.net/api/sendtoAPIwsm1.php" ;

String updatestring = "http://wsm.aacdata.net/updatewsm1.php?" ;

const char http_site[] = "75.103.94.221"; // 72.167.13.66
const int http_port = 80;
int timetotestwifi = 3000 ; // 300 ; // wait 300 seconds in ap mode 
String ipadd = "";
String ipStr = "";
uint8_t MAC_array[6];
char MAC_char[22];
char MAC_charAP[22];

int progmode = 20; // # 4 seconds to push button to put unit in AP mode
int rebootmode = 40; // # 8 seconds to push button to soft reboot unit
int eeprommode = 100; // # 20 seconds to push button to soft reboot unit

boolean configMode = false;  // not in config mode normally
int countmode = 0 ;
float temptodisp = 0;
int delaytime = 1 ; // 1 * 100th second for main loop
int delaytest = 8; // value/3 in seconds to test temp and voltage

//String who = "single temp server with switch - apserverA3";
//String devicetype = "DB18s20 Single Temp";

String devicetype = "" ; // "DB18s20 Single Temp";
String clearchar = " ";
int numtemp = 0; 
int totest = 0 ;

int precision = 10 ; // .1
String tempreading = "F" ;
float temptemp; // temp   read from the thermometer
float temptemp2; // temp   read from the thermometer
float voltvolt; // volt read from the adc
int wrongtempcount = 0; // counter for wrong temp if peaks
int wtcmax = 10; // max number of consecutive wrong readings
//const char* APssid = "AAAP"; // Name of access point
//const char *softAPssid = "AAAP12";
String APssid = "AP-";

String st;
String rsid = ""; // wifi name
String rpass = "" ; // wifi password
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 = 29000 ; //  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 = 25.63 ; // 27.95; // 29.6 ;

int thermostat =1 ;
int heattostart = 25 ;
/////////////////////////////////////////  to remove
// int actostart = 22 ;
int actostart = 0; // should be 22, I am using it now to test the # of rebooting times;
String reboottimes = "0" ;
int aircond = 0 ;
int heater = 0 ;
int buttonupdt = 0 ;

int resolution = 9 ;

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

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

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

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

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

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


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

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

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

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

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

// arrays to hold device addresses
  DeviceAddress insideThermometer, outsideThermometer;

Ticker flipper;

int flipcount = 0;
int oldflipcount = 0;

void flip()
{
  int state = digitalRead(WD);  // get the current state of GPIO1 pin
  digitalWrite(WD, !state);     // set pin to the opposite state
  flipcount += 1 ;

/*
  ++flipcount;
  // when the counter reaches a certain value, start blinking like crazy
  if (flipcount == 20)
  {
    flipper.attach(0.1, flip);
  }
  // when the counter reaches yet another value, stop blinking
  else if (flipcount == 120)
  {
    flipper.detach();
  }
*/
}
Ticker flipper1;

int flipcount1 = 0;
int oldflipcount1 = 0;

void flip1()
{
  int state1 = digitalRead(WD);  // get the current state of GPIO1 pin
  digitalWrite(WD, !state1);     // set pin to the opposite state
  flipcount1 += 1 ;

/*
  ++flipcount;
  // when the counter reaches a certain value, start blinking like crazy
  if (flipcount == 20)
  {
    flipper.attach(0.1, flip);
  }
  // when the counter reaches yet another value, stop blinking
  else if (flipcount == 120)
  {
    flipper.detach();
  }
*/
}


void setup() {
//  Serial.begin(115200);
  Serial.begin(9600);
//  Serial.begin(115200,SERIAL_8N1,SERIAL_TX_ONLY);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH); // make GPIO LED output high
  pinMode(WD, OUTPUT);
//  digitalWrite(WD, HIGH); // make GPIO LED output high

// added for watchdog
  digitalWrite(WD, LOW); // make GPIO LED output low
  // flip the pin every 0.5s
  flipper.attach(0.5, flip);
    
  pinMode(PROGBUTT, INPUT_PULLUP);
//  configMode = (digitalRead(PROGBUTT) ==
  who = firmware + "-" + versionnum ;

  EEPROM.begin(512);
//      digitalWrite(BUTT, LOW);
    uint8_t osrs_t = 1;             //Temperature oversampling x 1
    uint8_t osrs_p = 1;             //Pressure oversampling x 1
    uint8_t osrs_h = 1;             //Humidity oversampling x 1
    uint8_t mode = 3;               //Normal mode
    uint8_t t_sb = 5;               //Tstandby 1000ms
    uint8_t filter = 0;             //Filter off 
    uint8_t spi3w_en = 0;           //3-wire SPI Disable
    
    uint8_t ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode;
    uint8_t config_reg    = (t_sb << 5) | (filter << 2) | spi3w_en;
    uint8_t ctrl_hum_reg  = osrs_h;

  sensors.begin();
  Serial.println("");
//  added on March 9
//  Wire.begin(4 , 5); // sda, slc for esp12
//  Wire.begin(3 , 1); // for esp12 tx and rx
//  Wire.begin(12 , 13); // for esp12
////  Wire.begin(SDA , SDL); // for esp12  
////  matrix.print(0.0, DEC);
/* moved lower on oct 24-2016
  if (pinnum == "00000") {
//  int sdlpin = 13;  // to change to 3 rx
//  int sdapin = 12;  // to change to 1 tx
    sdlpin = 3;  // to change to 3 rx
    sdapin = 1;  // to change to 1 tx
  }
  else {
    sdlpin = 10;  // to change to 13 -3 rx
    sdapin = 9;  // to change to 12 - 1 tx
  }
#define SDL            sdlpin
#define SDA            sdapin
  Wire.begin(SDA , SDL); 
//  Wire.begin(sdapin , sdlpin); 
  matrix.begin(0x70);
  matrix.print(0000, DEC);
  matrix.writeDisplay();
*/
/* moved lower on Oct 20-2016
  Serial.println("Getting barometric pressure ...");
  mpl115a2.begin();
    writeReg(0xF2,ctrl_hum_reg);
    writeReg(0xF4,ctrl_meas_reg);
    writeReg(0xF5,config_reg);
    readTrim();  
*/

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

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

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

//}
// added feb 15

  Serial.println("");  Serial.println("");  Serial.println("");  
  Serial.println("");  Serial.println("");
  Serial.print("Firmware = ");  Serial.println(who);
WiFi.macAddress(MAC_array);
    for (int i = 0; i < sizeof(MAC_array); ++i){
      sprintf(MAC_char,"%s%02x:",MAC_char,MAC_array[i]);
    }
    for (int i = 3; i < sizeof(MAC_array); ++i){
      sprintf(MAC_charAP,"%s%02x:",MAC_charAP,MAC_array[i]);
    }
    Serial.println("");
    Serial.print("Mac address = ");  
    Serial.println(MAC_char);
    
    Serial.print("AP Mac address = ");  
    Serial.println(MAC_charAP);
    APssid = APssid + MAC_charAP ;

//    Serial.println(String(MAC_char).substring(0,2));
//    Serial.println(String(MAC_char).substring(14,16));
    
//char APssid = "AAAP"; // Name of access point
//const char* APssid = "AAAP"+"MAC_char.substring(0,2) ; // Name of access point
  
//  delay(10);
//  Serial.println("Startup");
  String firsteepromt = "9" ;
  if (char(EEPROM.read(0)) != firsteepromt[0] ){
      whatis = "d" ;
      dowhatis();
      debug = 1 ;
      reboottimes = "0" ;
      pinnum = "10000"  ; 
      details = 1 ; 
      delaytest = 4 ;
    
    Serial.println ("Eeprom is 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 in Eeprom: ");
  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("Password in Eeprom: ");
  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 Default: ");
  if (freq == 999999) {
    Serial.print("999999 - No transmission frequency");     
  }
  else {
    Serial.print(freq/10);Serial.print("seconds");
 
  }
//  Serial.print(freq);  
  if (strfreq.toInt() != 0 ) {
    Serial.print (" | Eeprom: ");
    if ( strfreq.toInt() != 999999 ) {
      freq = 10 * strfreq.toInt() ;
      frequency = freq ;
      Serial.print(freq/10); Serial.print("seconds");
    }
    else {
      freq = strfreq.toInt() ;
      frequency = freq ;
//      Serial.print(freq/10); 
//      Serial.println(".");
      Serial.print("999999 - No transmission frequency");     
    }
  }
  Serial.println(".");
 
  strfreq = "";

  for (int i = rebootfreq_from; i < rebootfreq_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Reboot Frequency Default: ");
  if ( rebootfreq != 999 ) {
//      rebootfreq = rebootfreq/10 ;
    Serial.print(rebootfreq/36000);
    Serial.print("Hours");
  }
  else {
    Serial.print("999 - No rebooting schedule");    
  }
//  rebootfreq = strfreq.toInt();
  if (strfreq.toInt() != 0 ) {
    Serial.print (" | Eeprom : ");
    rebootfreq = strfreq.toInt();
//    rebootfreq = 3600 * strfreq.toInt() ; // number of hours to reboot
          if (rebootfreq == 999 || rebootfreq == 0 ) {
//            rebootfreq = strfreq.toInt();
              Serial.print("999 - No rebooting schedule");
          }
          else {
            rebootfreq = 36000 * strfreq.toInt() ; // number of hours to reboot
            Serial.print(rebootfreq/36000);
            Serial.print("Hours");
          }
  }

  Serial.println(".");


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

    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("clientcode (no default): ");
  Serial.print (" only in Eeprom : ");
  Serial.print(strfreq);  
  Serial.println(".");
 
  strfreq = "";
  for (int i = delaytime_from; i < delaytime_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Loop delaytime in 100ms - Default: ");
  Serial.print(delaytime);  

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

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

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

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

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

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

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

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

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

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


//  if (strfreq != "" ) {
  if (String(strfreq) > "       " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
//    Serial.println ("in the if temp reading");
    Serial.print (" | Eeprom : ");
    tempreading = String(strfreq) ; 
    Serial.print(tempreading);  
  }
  Serial.println(".");
  
  strfreq = "";
  for (int i = adjtemp_from; i < adjtemp_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Adjust temp in Celcius Default: ");
  Serial.print(adjtemp);  
  if (strfreq.toFloat() != 0 ) {
//    Serial.println ("in the if adjust temp");
    Serial.print (" | Eeprom : ");
    adjtemp = strfreq.toFloat() ; // number to adjust temp to
    Serial.print(adjtemp); 
  }
  Serial.println(".");
  
  strfreq = "";
  for (int i = adjtemp2_from; i < adjtemp2_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Adjust temp2 in celcius/humidity Default: ");
  Serial.print(adjtemp2);  
  if (strfreq.toFloat() != 0 ) {
    Serial.print (" | Eeprom : ");
//  Serial.println ("in the if adjust temp2");
    adjtemp2 = strfreq.toFloat() ; // number to adjust temp to
    Serial.print(adjtemp2);
  }
  Serial.println(".");
  
  strfreq = "";
  for (int i = adjvolt_from; i < adjvolt_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Adjust volt ratio: ");
  Serial.print(adjvolt);  
  if (strfreq.toFloat() != 0 ) {
    Serial.print (" | Eeprom : ");
//    Serial.println ("in the if adjust volt");
    adjvolt = strfreq.toFloat() ; // number to adjust temp to
    Serial.print(adjvolt);  
  }
  Serial.println(".");

  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 Default: ");
  Serial.print(resolution);  
  if (strfreq.toInt() != 0 ) {
    Serial.print (" | Eeprom : ");
//  Serial.println ("in the if resolution");
    resolution = strfreq.toInt() ; // number to adjust temp to
    Serial.print(resolution);  
  }
  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 Default: ");
  Serial.print(whatis);  

  if (String(strfreq) > " " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
//    Serial.println ("in the if whatis");
    Serial.print (" | Eeprom : ");
    whatis = strfreq ;
//    Serial.print("whatis: ");
    Serial.print(whatis);  
  }
  dowhatis();
  Serial.println(".");
  
  strfreq = "";
  for (int i = actostart_from; i < actostart_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("Reboot times Default: 0");
  if (strfreq.toInt() != 0 ) {
    Serial.print (" | Eeprom : ");
//    Serial.println ("in the if actostart");
    actostart = strfreq.toInt() ;
    Serial.print(actostart);
//    actostart=0 ;
  }
  else {
    Serial.print (" no Eeprom value ");    
  }
  Serial.println(".");
///////////////////// to record the times rebooting - to remove later
        actostart += 1 ;
//        if ( actostart < 3) {
//          debug = 1 ;
//        }
        reboottimes = String(actostart);
        Serial.println("Clearing Eeprom");

        for (int i = actostart_from; i < actostart_to; ++i)
          { EEPROM.write(i, clearchar[0]) ; }
    
        Serial.println("Writing Reboot Times in Eeprom");
        for (int i = actostart_from; i < actostart_to; ++i)
          {
            EEPROM.write(i, reboottimes[i-actostart_from]);
//            Serial.print("Wrote: ");
//            Serial.println(reboottimes[i-actostart_from]); 
          }
        EEPROM.commit();

    Serial.print("reboottimes = ");Serial.print(reboottimes);
//  Serial.print(actostart);  
  Serial.println(".");
  
  strfreq = "";
  for (int i = heattostart_from; i < heattostart_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("heattostart Default in Celcius: ");
  Serial.print(heattostart);  
  if (strfreq.toInt() != 0 ) {
    Serial.print (" | Eeprom : ");
//    Serial.println ("in the if  = 0");
    heattostart = strfreq.toInt() ; // number to adjust temp to
    Serial.print(heattostart); 
  }
  Serial.println(".");
  
  strfreq = "";
 for (int i = button_from; i < button_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("button Default: 0");
//  Serial.print(strfreq);  

  if (strfreq.toInt() == 0 ) {
    Serial.print (" | Eeprom : 0");
//    Serial.println ("in the if button = 0");
    current = strfreq.toInt() ; // number to adjust temp to
  }
  if (strfreq.toInt() == 1 ) {
    Serial.print (" | Eeprom : 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);
    }
  }
  Serial.println(".");

  strfreq = "";

  for (int i = pinnum_from; i < pinnum_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("pinnum Default: ");
  Serial.print(pinnum);  
//  if (strfreq.toInt() != 0 ) {
  if (String(strfreq) > "    " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
    Serial.print (" | Eeprom : ");
//    Serial.println ("in the if pinnum");
    pinnum = strfreq ;
    Serial.print(pinnum);  
  }
  Serial.println(".");
  if (pinnum == "00000") {
//  int sdlpin = 13;  // to change to 3 rx
//  int sdapin = 12;  // to change to 1 tx
    sdlpin = 3;  // to change to 3 rx
    sdapin = 1;  // to change to 1 tx
    details = 0 ;
    debug = 0 ;
    Serial.println("I2C = GPIO-1(tx)=SDA-GPIO-3(rx)=SCL");
  }
  else if (pinnum == "10000") {
    sdlpin = 14;  // to change to 13 -3 rx
    sdapin = 4;  // to change to 12 - 1 tx
    Serial.println("I2C = GPIO-4=SDA - GPIO-14=SCL");
 //   details = 1 ;
 //   debug = 1 ;
  }
  else if (pinnum == "10001") {
    sdlpin = 14;  // to change to 13 -3 rx
    sdapin = 4;  // to change to 12 - 1 tx
    Serial.println("I2C = GPIO-4=SDA - GPIO-14=SCL");
    details = 1 ;
    debug = 1 ;
    delaytest = 4 ;
    whatis = "d" ;
    dowhatis();
  }
    
 strfreq = "";

//  for (int i = 132; i < 135; ++i)
  for (int i = datetosave_from; i < datetosave_to; ++i)
    {
      strfreq += char(EEPROM.read(i));
    }
  Serial.print("datetosave Default: ");
  Serial.print(datetosave);  
  if (String(strfreq) > "                       " && String(strfreq)< "ÿ" ) { // "ÿ"  ) {
    Serial.print (" | Eeprom : ");
//    Serial.println ("in the if datetosave");
    datetosave = strfreq ;
//    Serial.print("datetosave: ");
    Serial.print(datetosave);  
//    Serial.println(".");
    powercut = 1 ;
  }
  Serial.println(".");
  
  #define SDL            sdlpin
  #define SDA            sdapin
  Wire.begin(SDA , SDL); 
//  Wire.begin(sdapin , sdlpin); 
  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();
  } // if eeprom(1) = 0 
  Serial.print("Mac=");  
  Serial.println(MAC_char);

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

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

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

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

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

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

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

  Serial.print("Device 1 Address: ");
  printAddress(outsideThermometer);
  Serial.println();

  #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();  
}
    Serial.print ("debug = ");
    Serial.print (debug);
    Serial.println(".");
    Serial.print ("details = ");
    Serial.print (details);
    Serial.println(".");
    Serial.print ("delaytest = ");
    Serial.print (delaytest/2);
    Serial.println("."); 
    Serial.print ("reboot counter = ");
    Serial.print (reboottimes);
    Serial.println(".");    
    Serial.print ("who = ");
    Serial.print (who);
    Serial.println(".");
    
//    updatestring = "http://boatautomation.com/wsm/updatewsm1.php?macid='"+String(MAC_char)+"'&firmware='"+String(firmware)+"'&versionnum='"+String(versionnum)+"'&whatis='"+String(whatis)+"'&devicetodo='"+String(devicetodo)+"'";
//    updatestring = "http://boatautomation.com/wsm/updatewsm1.php?macid='"+String(MAC_char)+"'&firmware='"+String(firmware)+"'&versionnum='"+String(versionnum)+"'&whatis='"+String(whatis)+"'";
    updatestring  += "macid='"+String(MAC_char)+"'&firmware='"+String(firmware)+"'&versionnum='"+String(versionnum)+"'&whatis='"+String(whatis)+"'";
    Serial.println("updatestring = " + updatestring); 
    Serial.println("----------------------"); 
 /*
        debug = 1 ;
      reboottimes = "0" ;
      pinnum = "10000"  ; 
      details = 1 ; 
      delaytest = 4 ;
    Serial.print ("Frequency * 10 = ");
    Serial.print (freq);
    Serial.println(".");

    Serial.print ("Rebooting Frequency * 10 = ");
    Serial.print (rebootfreq);
    Serial.println(".");
  if (pinnum == "00000") {
    Serial.println("I2C = 1-3");
  }
  else {
    Serial.println("I2C = 4-14");
  }          
    Serial.print ("whatis = ");
    Serial.print (whatis);
    Serial.println(".");
*/    
    //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(".");
*/
  // 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();
    if ( debug == 0 ) {
      WiFi.begin(rsid.c_str(), rpass.c_str());
      delay(1000);
    }
    if ( testWifi()) {
//            s += "<p>           Serial.println("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) {
  if ( debug == 0 ) {
    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());
////////////////// to be removed Nov-3-2016 to have the time always available - change the ticker to count the time
        if (devicetodo.substring(16,17) == "p" ) {
          Serial.println("in check date/time");
          checktime();
        }
        return(1); 
       }      
      delay(500);
//    Serial.print(WiFi.status());    
      c++;
    }
    return(0);
  }
  else {
    return(0);
  }
} 


void launchWeb(int webtype) {
//    Serial.println("");
    Serial.print("WiFi connected as: ");
    Serial.println(WiFi.localIP());
    IPAddress ip = WiFi.localIP();
    ipadd = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
//    Serial.println(WiFi.softAPIP());
    IPAddress ips = WiFi.localIP();
    ips = WiFi.softAPIP();
    ipStr = String(ips[0]) + '.' + String(ips[1]) + '.' + String(ips[2]) + '.' + String(ips[3]);
//req.substring(req.lastIndexOf('=')+1)
    if (ipStr == "0.0.0.0") {
      Serial.println(ipadd);
/*
      matrix.print((ipadd.substring(ipadd.lastIndexOf('.')+1)).toInt(), DEC);
      matrix.writeDisplay();
      Serial.println(String(ip[0]));
      matrix.print(String(ip[0]).toInt(), DEC);
      matrix.writeDisplay();
      Serial.println(String(ip[1]));
      matrix.print(String(ip[1]).toInt(), DEC);
      matrix.writeDisplay();
      Serial.println(String(ip[2]));
      matrix.print(String(ip[2]).toInt(), DEC);
      matrix.writeDisplay();
      Serial.println(String(ip[3]));
*/
      matrix.print(String(ip[3]).toInt(), DEC);
      matrix.writeDisplay();
    }
    else {
      Serial.println(ipStr);
//      Serial.println(ipStr.substring(ipStr.lastIndexOf('.')+1))
      matrix.print(9999, DEC);
      matrix.writeDisplay();
    }

   /* 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 && debug == 0 ){
          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");
          if ( debug == 0 ) {
            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");


            configMode = false;  // not in config mode
            Serial.println(ipadd);
            matrix.print((ipStr.substring(ipStr.lastIndexOf('.')+1)).toInt(), DEC);
            matrix.writeDisplay();
            launchWeb(0);

            return;
          }

         else{
//            Serial.println("");
//            Serial.println("New SSID or Password failed. Reconnect to server, and try again.");
//            Serial.println("In AAAP mode");
            matrix.print(9999, DEC);
            matrix.writeDisplay();
            setupAP();
//            configMode = true;  // in config mode 
            return;
         }
       }
    delay(100);
     }
}


void setupAP(void) {

  configMode = true;  // in config mode
  Serial.print("Time elapsed: ");Serial.println(String(flipcount/2));
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  Serial.print("Time elapsed: ");Serial.println(String(flipcount/2));
  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);
  WiFi.softAP(APssid.c_str());
/*
  Serial.println("st=");
  Serial.println(st);
*/
  Serial.print("Time elapsed: ");Serial.println(String(flipcount/2));
  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.print("Time elapsed: ");Serial.println(String(flipcount/2));
  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);
    Serial.print("Time elapsed: ");Serial.println(String(flipcount/2));
    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 += "Firmware = "+who+"<p>";
        s += "pinnum=" + pinnum + "<p>";
        if (freq == 999999 ) {
          s += "Frequency = 999999 -> No Wi-Fi transmission scheduled";
        }
        else {
          s += "Frequency = "+String(freq/10)+"->"+String(frequency/10)+"s<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]); }
        for (int i = 1; i < 256; ++i) { EEPROM.write(i, clearchar[0]); }
        String firsteeprom = "1";
        EEPROM.write(0, firsteeprom[0] );        
        EEPROM.commit();
        s += "<p>Cleared<p>";
        y = freq ;        
        s += "<p>Rebooting now<p>";
        rebootfreq = 9999 ;
      }
      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("/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, Minimum = 10s<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());
        if ( strfreq.toInt() == 999999 ) {
          freq = strfreq.toInt();
          Serial.print ("frequency = "); Serial.println(freq);
        }
        else {
          freq = 10 * strfreq.toInt();
          Serial.print ("frequency = "); Serial.println(freq/10);
        }
        frequency = freq ;
        if (freq < 100) {
          freq = 100;
        }

        s += "<p>Saved<p>";

      }

      else if ( req.startsWith("/delaytest=") ) { // delaytest
        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("delaytest (minimum 3 seconds and maximum = frequency) = ");
        delaytest = strreqanswer.toInt() ;
        if ( delaytest < 3 ) {
          delaytest = 6;
        }
        else if (delaytest > freq ) {
          delaytest = freq*2 ;
        }
        else {
          delaytest = delaytest*2 ;
        }
        Serial.println(delaytest/2);
        s += "<p>Saved<p>";
      }

      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 ;
        y = freq ;        
        s += "<p>Rebooting now<p>";
        rebootfreq = 9999 ;
        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);
        y = freq ;        
          s += "<p>Rebooting now<p>";
          rebootfreq = 9999 ;
      }

      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 += "debug:" + String(debug) + ",";
        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+",";
        if ( freq == 999999 ) {
          s += "freq:999999-no_transmission_scheduled,";
        }
        else {
          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
        }
        s += "delaytest:"+String(delaytest/2)+",";
//        s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
//        s += "rebootfreq:"+String(rebootfreq/3600)+",";
          if (rebootfreq == 999) {
            s += "rebootfreq:"+String(rebootfreq)+",";          }
          else {
            s += "rebootfreq:"+String(rebootfreq/36000)+"H,";
          }
        if (devicetodo.startsWith("t") ) {
//          gettemp();
          s += "temp:"+ String(valuedev1) + "C,";
          if ( dhttemp == 0 ) {
            s += "temp2:"+ String(valuedev2) + "C,";
          }
          else {            
            s += "humid:"+ String(valuedev2) + "%,";
          }
        }
        s += "button:" + String(current) + ",";
        s += "pump1:" + String(Pcurrent) + ",";
        s += "pump2:" + String(Pcurrent2) + ",";
        s += "pump3:" + String(Pcurrent) + ",";
        s += "pump4:" + String(Pcurrent) + ",";
        s += "IP:"+ ipadd + ",";
        s += "Reboot_Counter:"+reboottimes+ ",";
        s += "who:" + who + ",";
        s += "pinnum:" + pinnum + ",";         
        s += "network:" + String(rsid)+" ";
        Serial.print ("All = "); Serial.println(s);
        s = webString + s;
      }
      else if ( req.startsWith("/status?") ) {
        s = "Hardware Info:<br>"  ;
        rssi = abs(WiFi.RSSI());
//        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "ADC = " + String(analogRead(A0)) + "<br>";
        s += "    Volts = " + String(valuedev3) + "<br>";
        s += "GPIO-0 = "+ String(digitalRead(0)) + "<br>";
        s += "GPIO-1 tx = "+String(digitalRead(1))+"<br>";
        s += "GPIO-2 = "+ String(digitalRead(2))+"<br>";
        s += "    Temp = "+ String(valuedev1) + "C<br>";
          if ( dhttemp == 0 ) {
            s += "    Temp2 = "+ String(valuedev2) + "C<br>";        
          }
          else {            
            s += "    Humidity = "+ String(valuedev2) + "%<br>";
          }
//          s += "    Temp2 = "+ String(valuedev2) + "<br>";        
        s += "GPIO-3 rx = " + String(digitalRead(3))+"<br>";
        s += "GPIO-4 = " + String(digitalRead(4))+"<br>";
        s += "GPIO-5 = " + String(digitalRead(5))+"<br>";
        s += "GPIO-9 = " + String(digitalRead(9))+"<br>";
        s += "GPIO-10 = " + String(digitalRead(10))+"<br>";
        s += "GPIO-12 = " + String(digitalRead(12))+"<br>";
        s += "GPIO-13 = " + String(digitalRead(13))+"<br>";
        s += "GPIO-14 = " + String(digitalRead(14))+"<br>";
        s += "GPIO-15 = " + String(digitalRead(15))+"<br>";
        s += "GPIO-16 = " + String(digitalRead(16))+"<br><br>";

        s += "Software info:<br>";
        s += "debug = " + String(debug) + "<br>";
        s += "whatis = " + whatis + "<br>";
        s += "macid = "+String(MAC_char)+"<br>";
        s += "devicetype = "+devicetype+"<br>";
        if ( freq == 999999 ) {
          s += "frequency = 999999 - no transmission scheduled<br>";
        }
        else {
          s += "frequency = "+String(freq/10)+"->"+String(frequency/10)+"s<br>";
        }
          s += "delaytest = "+String(delaytest/2)+"<br>";
//        s += "frequency = "+String(freq/10)+"->"+String(frequency/10)+"<br>";
//        s += "rebootfreq:"+String(rebootfreq/3600)+"<br>";
        if (rebootfreq == 999) {
          s += "rebootfreq = No rebooting scheduled<br>";          }
        else {
          s += "rebootfreq = "+String(rebootfreq/36000)+"H<br>";
        }
        s += "x = " + String(x) + "<br>";
        s += "y = " + String(y) + "<br>";
        s += "s = " + String(flipcount/2) + "<br>";
        s += "rotations left to transmit = " + String(freq - y) + "<br>";
        s += "reboot Counter = "+reboottimes+"<br>";
        s += "signal = "+String(rssi)+"<br>";
        s += "numtemp = "+String(numtemp)+"<br>";
        if (devicetodo.startsWith("t") ) {
//          gettemp();
          s += "temp = "+ String(valuedev1) + "C<br>";
          if ( dhttemp == 0 ) {
            s += "    temp2 = "+ String(valuedev2) + "C<br>";        
          }
          else {            
            s += "    humidity = "+ String(valuedev2) + "%<br>";
          }
//          s += "temp2 = "+ String(temptemp2) + "<br>";
          s += "resolution = "+String(resolution)+"<br>";
          s += "tempdiff = "+String(tempdiff)+"<br>";
          s += "adjtemp = "+String(adjtemp)+"<br>";
          s += "adjtemp2 = "+String(adjtemp2)+"<br>";        }
          s += "precision = " + String(precision)+"<br>";
        if (devicetodo.substring(2,3) == "v" ) {
          s += "volt = "+ String(valuedev3) + "<br>";
          s += "voltdiff = "+String(voltdiff)+"<br>";
          s += "adjvolt = "+String(adjvolt)+"<br>";
          s += "vprecision = "+String(vprecision)+"<br>";
        }
        s += "button = " + String(current) + "<br>";
        if (preverse == 1 ) {
          s += "pump1 = " ;
          if (Pcurrent==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";
           
          s += "pump2 = " ;
          if (Pcurrent2==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";  
          s += "pump3 = " ;
          if (Pcurrent3==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";
          s += "pump4 = " ;
          if (Pcurrent4==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";
        }
        else {
          s += "pump = " + String(Pcurrent) + "<br>";
          s += "pump2 = " + String(Pcurrent2) + "<br>";
          s += "pump3 = " + String(Pcurrent3) + "<br>";
          s += "pump4 = " + String(Pcurrent4) + "<br>";
        }
        s += "IP = "+ ipadd + "<br>";
        s += "who = " + who + "<br>";
        s += "pinnum = " + pinnum + "<br>";
        s += "network = " + String(rsid) + "<br>"; 
        Serial.print ("Status = "); Serial.println(s);
        s = webString + s;
      }
      else if ( req.startsWith("/info?") ) {
        s = "" ;
        rssi = abs(WiFi.RSSI());
//        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "debug=" + String(debug) + "&";
        s += "signal="+String(rssi)+"&";
        s += "macid="+String(MAC_char)+"&";
        s += "devicetype="+devicetype+"&";
        if ( freq == 999999 ) {
          s += "freq=999999-no_transmission&";
        }
        else {
          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s&";
        }
        s += "delaytest="+String(delaytest/2)+"&";
//        s += "freq="+String(freq/10)+"->"+String(frequency/10)+"s&";
//        s += "rebootfreq="+String(rebootfreq/3600)+"&";
          if (rebootfreq == 999) {
            s += "rebootfreq=999-No_rebooting&";          }
          else {
            s += "rebootfreq="+String(rebootfreq/36000)+"H&";
          }
          s += "whatis="+String(whatis)+"&";
        if (devicetodo.startsWith("t") ) {
//          gettemp();
          s += "temp="+ String(valuedev1) + "C&";
          if ( dhttemp == 0 ) {
            s += "temp2="+ String(valuedev2) + "C&";
          }
          else {            
            s += "humid="+ String(valuedev2) + "%&";
          }
//          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) + "&";
          s += "pump2=" + String(Pcurrent2) + "&";
          s += "pump3=" + String(Pcurrent3) + "&";
          s += "pump4=" + String(Pcurrent4) + "&";


        }
       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 += "Reboot_Counter="+reboottimes+ "&";
        s += "who=" + who + "&";
        s += "pinnum=" + pinnum + "&";        
        s += "network=" + String(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 ;
        if ( freq == 999999 ) {
          s += "frequency = 999999 - no transmission scheduled";
        }
        else {
//          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
          Serial.print ("frequency = "); Serial.println(freq/10);
          s += freq/10;
          s += "->";
          s += frequency/10;
        }
      }

      else if ( req.startsWith("/volts?") ) {
        s = webString ;
        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("/reboot=now") ) {
          s += "<p>Rebooting now<p>";
          rebootfreq = 9999 ;
      }
      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, Minimum 100s<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());
        if ( strfreq.toInt() == 999999 ) {
//          s += "freq:999999-no_transmission_scheduled,";
          freq = strfreq.toInt();
        }
        else {
//          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
          freq = 10 * strfreq.toInt();
        }
        frequency = freq ;

        if (freq < 100) {
          freq = 100;
        }

        Serial.print ("frequency = "); Serial.println(freq/10);
        s += "<p>Saved<p>";

      }
      else if ( req.startsWith("/rebootfreq?") ) {
        s = webString ;
        Serial.print ("Reboot frequency = "); Serial.println(rebootfreq/36000);
 //       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/36000;
          }
      }
    
      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 if ( req.startsWith("/delaytest?") ) { // delaytest
        Serial.print("delaytest = ");
        Serial.println(delaytest/2);
        s = webString ;
        s += delaytest/2;
      }
      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 ac 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() ;
        reboottimes = actostart ;

//        if (actostart < 4) {
//          debug = 1;
//        }        
        Serial.print ("actostart = "); Serial.println(actostart);
      }
      else if ( req.startsWith("/debug?") ) {
        s = webString ;
        Serial.print ("debug = "); Serial.println(debug);
        s += debug;
      }
      else if ( req.startsWith("/debug=") ) {
        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("debug = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the debug value to " + strreqanswer + " <p>";
        s += "<p>Saved<p>";
        debug = strreqanswer.toInt() ;
        Serial.print ("debug = "); Serial.println(debug);
      }

      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 += "Firmware = "+who+"<p>";
//        s += "Frequency = "+String(freq)+"<p>";
        s += "freq="+String(freq/10)+"->"+String(frequency/10)+"s<p>";
//            s += st;
        if (wifiname == "" ) {
          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>";
        }
        else {
          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]); }
//        String firsteeprom = "9";
//        EEPROM.write(0, firsteeprom[0] );
//        for (int i = 0; i < 256; ++i) { EEPROM.write(i, clearchar[0]); }
        for (int i = 1; i < 256; ++i) { EEPROM.write(i, clearchar[0]); }
        String firsteeprom = "1";
        EEPROM.write(0, firsteeprom[0] );        
        EEPROM.commit();

        s += "<p>Cleared<p>";
        y = freq ;        
        s += "<p>Rebooting now<p>";
        rebootfreq = 9999 ;
      }
      else if ( req.startsWith("/delaytest?") ) { // delaytest
        Serial.print("delaytest = ");
        Serial.println(delaytest/2);
        s = webString ;
        s += delaytest/2;
      }
      else if ( req.startsWith("/delaytest=") ) { // delaytest
        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("delaytest (minimum 3 seconds and maximum = frequency) = ");
        delaytest = strreqanswer.toInt() ;
        if ( delaytest < 3 ) {
          delaytest = 6;
        }
        else if (delaytest > freq ) {
          delaytest = freq*2 ;
        }
        else {
          delaytest = delaytest*2 ;
        }
        Serial.println(delaytest/2);
        s += "<p>Saved<p>";
      }
/*
      else if ( req.startsWith("/delaytest=") ) { // delaytest
        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("delaytest minimum 6 (= 2 seconds) and (maximum = to frequency) = ");
        delaytest = strreqanswer.toInt() ;
        if ( delaytest < 6 ) {
          delaytest = 6;
        }
        if (delaytest > freq ) {
          delaytest = freq ;
        }
        Serial.println(delaytest);
        s += "<p>Saved<p>";
      }
*/      
      else if ( req.startsWith("/tempdiff=") ) {
        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 ac 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() ;
        reboottimes = actostart ;
//        if (actostart < 4) {
//          debug = 1;
//        }
        
        Serial.print ("actostart = "); Serial.println(actostart);
      }
      else if ( req.startsWith("/debug?") ) {
        s = webString ;
        Serial.print ("debug = "); Serial.println(debug);
        s += debug;
      }
      else if ( req.startsWith("/debug=") ) {
        strreqanswer = req.substring(req.lastIndexOf('=')+1);
        Serial.print("debug = ");
        Serial.println(strreqanswer);
        s += "<p>Saving the debug value to " + strreqanswer + " <p>";
        s += "<p>Saved<p>";
        debug = strreqanswer.toInt() ;
        Serial.print ("debug = "); Serial.println(debug);
      }

      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 ;
        y = freq ;        
        s += "<p>Rebooting now<p>";
        rebootfreq = 9999 ;        
        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);
        y = freq ;        
          s += "<p>Rebooting now<p>";
          rebootfreq = 9999 ;
          
/*            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());
        
        if ( strfreq.toInt() == 999999 ) {
//          s += "freq:999999-no_transmission_scheduled,";
          freq = strfreq.toInt();
        }
        else {
//          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
          freq = 10 * strfreq.toInt();
        }
        frequency = freq ;

/*
        if (freq < 50) {
          freq = 50;
        }
*/
        Serial.print ("frequency = "); Serial.println(freq/10);
        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("Reboot 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 = 36000 * strfreq.toInt();
          }

        Serial.print ("Rebooting frequency = "); Serial.println(rebootfreq/36000);
        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 ;
                 Serial.print("Temp = "); Serial.println(temperaturetest);
//            }
//            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 - adjtemp) ) ;
                 Serial.print("new strreqanswer = "); Serial.println(strreqanswer);

//          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 - adjtemp2)) ;
//          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 += "debug:" + String(debug) + ",";
        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+",";
        if ( freq == 999999 ) {
          s += "freq:999999-no_transmission_scheduled,";
        }
        else {
          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
        }
        s += "delaytest:"+String(delaytest/2)+",";
//        s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s,";
//        s += "rebootfreq:"+String(rebootfreq/3600)+",";
          if (rebootfreq == 999) {
            s += "rebootfreq:"+String(rebootfreq)+",";          }
          else {
            s += "rebootfreq:"+String(rebootfreq/36000)+"H,";
          }
        if (devicetodo.startsWith("t") ) {
//          gettemp();
          s += "temp:"+ String(valuedev1) + "C,";
          if ( dhttemp == 0 ) {
            s += "temp2:"+ String(valuedev2) + "C,";
          }
          else {            
            s += "humid:"+ String(valuedev2) + "%,";
          }
        }
        s += "button:" + String(current) + ",";
        s += "pump1:" + String(Pcurrent) + ",";
        s += "pump2:" + String(Pcurrent2) + ",";
        s += "pump3:" + String(Pcurrent) + ",";
        s += "pump4:" + String(Pcurrent) + ",";
        s += "IP:"+ ipadd + ",";
        s += "Reboot_Counter:"+reboottimes+ ",";
        s += "who:" + who + ",";
        s += "pinnum:" + pinnum + ",";         
        s += "network:" + String(rsid)+" ";
        Serial.print ("All = "); Serial.println(s);
        s = webString + s;
        }
      else if ( req.startsWith("/status?") ) {
        s = "Hardware Info:<br>"  ;
        rssi = abs(WiFi.RSSI());
//        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "ADC = " + String(analogRead(A0)) + "<br>";
        s += "    Volts = " + String(valuedev3) + "<br>";
        s += "GPIO-0 = "+ String(digitalRead(0)) + "<br>";
        s += "GPIO-1 tx = "+String(digitalRead(1))+"<br>";
        s += "GPIO-2 = "+ String(digitalRead(2))+"<br>";
        s += "    Temp = "+ String(valuedev1) + "C<br>";
          if ( dhttemp == 0 ) {
            s += "    Temp2 = "+ String(valuedev2) + "C<br>";        
          }
          else {            
            s += "    Humidity = "+ String(valuedev2) + "%<br>";
          }
//          s += "    Temp2 = "+ String(valuedev2) + "<br>";        
        s += "GPIO-3 rx = " + String(digitalRead(3))+"<br>";
        s += "GPIO-4 = " + String(digitalRead(4))+"<br>";
        s += "GPIO-5 = " + String(digitalRead(5))+"<br>";
        s += "GPIO-9 = " + String(digitalRead(9))+"<br>";
        s += "GPIO-10 = " + String(digitalRead(10))+"<br>";
        s += "GPIO-12 = " + String(digitalRead(12))+"<br>";
        s += "GPIO-13 = " + String(digitalRead(13))+"<br>";
        s += "GPIO-14 = " + String(digitalRead(14))+"<br>";
        s += "GPIO-15 = " + String(digitalRead(15))+"<br>";
        s += "GPIO-16 = " + String(digitalRead(16))+"<br><br>";

        s += "Software info:<br>";
        s += "debug = " + String(debug) + "<br>";
        s += "whatis = " + whatis + "<br>";
        s += "macid = "+String(MAC_char)+"<br>";
        s += "devicetype = "+devicetype+"<br>";
        if ( freq == 999999 ) {
          s += "frequency = 999999 - no transmission scheduled<br>";
        }
        else {
          s += "frequency = "+String(freq/10)+"->"+String(frequency/10)+"s<br>";
        }
        s += "delaytest = "+String(delaytest/2)+"<br>";
//        s += "frequency = "+String(freq/10)+"->"+String(frequency/10)+"<br>";
//        s += "rebootfreq:"+String(rebootfreq/3600)+"<br>";
          if (rebootfreq == 999) {
            s += "rebootfreq = "+String(rebootfreq)+"<br>";          }
          else {
            s += "rebootfreq = "+String(rebootfreq/36000)+"<br>";
          }
        s += "x = " + String(x) + "<br>";
        s += "y = " + String(y) + "<br>";
        s += "s = " + String(flipcount/2) + "<br>";
        s += "rotations left to transmit = " + String(freq - y) + "<br>";
        s += "reboot Counter = "+reboottimes+"<br>";
        s += "signal = "+String(rssi)+"<br>";
        s += "numtemp = "+String(numtemp)+"<br>";
        if (devicetodo.startsWith("t") ) {
//          gettemp();
          s += "temp = "+ String(valuedev1) + "C<br>";
          if ( dhttemp == 0 ) {
            s += "    temp2 = "+ String(valuedev2) + "C<br>";        
          }
          else {            
            s += "    humidity = "+ String(valuedev2) + "%<br>";
          }
//          s += "temp2 = "+ String(temptemp2) + "<br>";
          s += "resolution = "+String(resolution)+"<br>";
          s += "tempdiff = "+String(tempdiff)+"<br>";
          s += "adjtemp = "+String(adjtemp)+"<br>";
          s += "adjtemp2 = "+String(adjtemp2)+"<br>";        }
          s += "precision = " + String(precision)+"<br>";
        if (devicetodo.substring(2,3) == "v" ) {
          s += "volt = "+ String(valuedev3) + "<br>";
          s += "voltdiff = "+String(voltdiff)+"<br>";
          s += "adjvolt = "+String(adjvolt)+"<br>";
          s += "vprecision = "+String(vprecision)+"<br>";
        }
        s += "button = " + String(current) + "<br>";
        if (preverse == 1 ) {
          s += "pump1 = " ;
          if (Pcurrent==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";
           
          s += "pump2 = " ;
          if (Pcurrent2==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";  
          s += "pump3 = " ;
          if (Pcurrent3==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";
          s += "pump4 = " ;
          if (Pcurrent4==1){
            s += "0" ;
            }
            else {
              s += "1" ;
            }
            s += "<br>";
        }
        else {
          s += "pump = " + String(Pcurrent) + "<br>";
          s += "pump2 = " + String(Pcurrent2) + "<br>";
          s += "pump3 = " + String(Pcurrent3) + "<br>";
          s += "pump4 = " + String(Pcurrent4) + "<br>";
        }
        s += "IP = "+ ipadd + "<br>";
        s += "who = " + who + "<br>";
        s += "pinnum = " + pinnum + "<br>";
        s += "network = " + String(rsid) + "<br>"; 
        Serial.print ("Status = "); Serial.println(s);
        s = webString + s;
      }
      else if ( req.startsWith("/info?") ) {
        s = "" ;
        rssi = abs(WiFi.RSSI());
//        Serial.print ("Signal = "); Serial.println(String(rssi));
        s += "debug=" + String(debug) + "&";
        s += "signal="+String(rssi)+"&";
        s += "macid="+String(MAC_char)+"&";
        s += "devicetype="+devicetype+"&";
        if ( freq == 999999 ) {
          s += "freq=999999-no_transmission&";
        }
        else {
          s += "freq:"+String(freq/10)+"->"+String(frequency/10)+"s&";
        }
        s += "delaytest:"+String(delaytest/2)+"&";
//        s += "freq="+String(freq/10)+"->"+String(frequency/10)+"s&";
//        s += "rebootfreq="+String(rebootfreq/3600)+"&";
          if (rebootfreq == 999) {
            s += "rebootfreq=999-No_rebooting&";          }
          else {
            s += "rebootfreq="+String(rebootfreq/36000)+"H&";
          }
          s += "whatis="+String(whatis)+"&";
        if (devicetodo.startsWith("t") ) {
//          gettemp();
          s += "temp="+ String(valuedev1) + "C&";
          if ( dhttemp == 0 ) {
            s += "temp2="+ String(valuedev2) + "C&";
          }
          else {            
            s += "humid="+ String(valuedev2) + "%&";
          }
//          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) + "&";
          s += "pump2=" + String(Pcurrent2) + "&";
          s += "pump3=" + String(Pcurrent3) + "&";
          s += "pump4=" + String(Pcurrent4) + "&";


        }
       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 += "Reboot_Counter="+reboottimes+ "&";
        s += "who=" + who + "&";
        s += "pinnum=" + pinnum + "&";        
        s += "network=" + String(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 ;
         if ( freq == 999999 ) {
          s += "frequency = 999999 - no transmission scheduled<br>";
        }
        else {
          Serial.print ("frequency = "); Serial.println(freq/10);
          s += freq/10;
          s += "->";
          s += frequency/10;
        }


        
       // 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 ;
 //       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) {
            Serial.print ("Reboot frequency = "); Serial.println(rebootfreq);
            s += rebootfreq ;
          }
          else {
            Serial.print ("Reboot frequency = "); Serial.println(rebootfreq/36000);
            s += rebootfreq/36000;
          }

      }

      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("/pumps?") ) {
        s = webString ;
        
       // s += String(Pcurrent);
        s += String(Pcurrent)+","+String(Pcurrent2)+","+String(Pcurrent3)+","+String(Pcurrent4);

        // write the current state to the power switch tail
//        digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
        Serial.print ("Pump = "); Serial.print(Pcurrent); 
        Serial.print ("Pump2 = "); Serial.print(Pcurrent2);
        Serial.print ("Pump3 = "); Serial.println(Pcurrent3);
        Serial.print ("Pump4 = "); Serial.println(Pcurrent4);
      }

      else if ( req.startsWith("/update=now") ) {
        s = webString ;
        s += "Checking for update";
        Serial.println ("Checking for update");
        otaupdate() ;        
        // write the current state to the power switch tail
//        digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
      }
      
      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");
  Serial.print("Time elapsed: ");Serial.println(String(flipcount/2));
  return(20);
}


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

  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() ) {
          PlnSerial("Connected Successfully");
          return;
      }
  // otherwise, set up an access point to input SSID and password     
  else
  {
      PlnSerial("");
      PlnSerial("Connect timed out, opening AP"); 
      setupAP();
  }
}    

void torun() {
  if (devicetodo.substring(16,17) == "p" ) {
    counttime();
  }
  if ( flipcount % delaytest == 0 && oldflipcount != flipcount) {
//    Serial.println("in flipcount if");
//    Serial.print("delaytest = ");Serial.println(delaytest);
//    Serial.print("flipcount = ");Serial.println(flipcount);
    totest = 1 ;
    oldflipcount = flipcount ;
    if ( configMode != true && flipcount % delaytest*4 == 0) {
      digitalWrite(LED, HIGH);
//        Serial.println("in config mode not true");
    }
  }
  if (totest == 0 && configMode != true) {
//    digitalWrite(LED, LOW);  
//    Serial.println("in totest = 0 if");
  }
//  Serial.print("x = "); Serial.print(x);     Serial.print(" - y = "); Serial.println(y);
   
if (digitalRead(PROGBUTT) == LOW) {
  totest = 0 ;
//  PSerial("In button low"); PlnSerial(String(countmode));
  countmode = countmode + 1 ;
  digitalWrite(LED, LOW);  
  if (countmode == progmode || countmode == rebootmode || countmode == eeprommode ) {
     digitalWrite(LED, HIGH);
     delay(100);
     digitalWrite(LED, LOW); 
     if (countmode == rebootmode ) {
       delay(100);
       digitalWrite(LED, HIGH);
       delay(100);
       digitalWrite(LED, LOW);      
     }
     if (countmode == eeprommode ) {
       delay(100);
       digitalWrite(LED, HIGH);
       delay(100);
       digitalWrite(LED, LOW);      
       delay(100);
       digitalWrite(LED, HIGH);
       delay(100);
       digitalWrite(LED, LOW);      
     }
     
  }
}
if (digitalRead(PROGBUTT) == HIGH && countmode > 0) {
//  PlnSerial("In button high");
  if (countmode >= eeprommode){
    PlnSerial("Resetting unit to factory values");
    countmode = 0;
    rebootfreq = 9999 ;
    for (int i = 0; i < 256; ++i) { EEPROM.write(i, clearchar[0]); }
    EEPROM.commit(); 
    configMode = false ;
  }  
  else if (countmode >= rebootmode){
    PlnSerial("Reboot command");
    countmode = 0;
    rebootfreq = 9999 ;
    configMode = false ;
  }
  else if (countmode >= progmode){
    PlnSerial("In AP mode");
    digitalWrite(LED, LOW);  
    countmode = 0;
    setupAP();
  }
  else if (countmode < progmode){
    PlnSerial("In regular mode");
    //configMode = false ;
    countmode = 0;
    digitalWrite(LED, LOW); 
       if ( debug == 0 ) {
          PlnSerial("Connecting to local Wi-fi");
          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");
            configMode = false;  // not in config mode

            launchWeb(0);

            return;
          }

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


            setupAP();
//            configMode = true;  // in config mode 
            return;
         }

  }
  else {
//    PlnSerial("in else mode");
  }
}
else {
//  PlnSerial("in else and led low");  
//  digitalWrite(LED, LOW); 
}

//PSerial("configmode = "); PlnSerial(String(configMode));
if (configMode == true && flipcount % 2 == 0 && digitalRead(PROGBUTT) == HIGH) { // 
//  digitalWrite(LED, LOW);  
//  PlnSerial("in if configmode = true");
//  delay(100);  
     int state1 = digitalRead(LED);  // get the current state of LED
     digitalWrite(LED, !state1);  

}
//  flipper.attach(0.5, flip);
  
    pb += 1 ;
//    PSerial("pbstatus = ");PlnSerial (String (pbstatus)) ;
//    PSerial("curr = ");PlnSerial (String (curr)) ;
  if (pbstatus == 1 ) {
    PSerial("push button status, now = ");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 && digitalRead(PROGBUTT) == HIGH) {
    if ( digitalRead(PROGBUTT) == HIGH) {
       x += 1 ;
       y += 1 ;
//       v += 1 ;
//       t += 1 ;
//       t2 += 1 ;
       ap += 1 ;      
//       Serial.print("ap = ");Serial.println (String (ap));
//      if ( x % delaytest == 0 ) {
      if ( totest == 1  ) {
//        digitalWrite(LED, HIGH); 
      }
      if (freq == 999999) {
        
      }
      else {
        if ( y > freq + 1) { //  || y == 1 ) {
          if (devicetodo.substring(16,17) == "p" ) {
//          if (devicetodo == " , , , , , , , ,p" ) {
            ispoweron();          
          }
          if (devicetodo.startsWith("t") && totest == 1  ) {
               t += 1 ;
               t2 += 1 ;

              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" && totest == 1  ) {
            getvolt();
            v += 1 ;

            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("volts = ");PSerial (String (valuedev3) );
          }
          if (devicetodo.substring(6,7) == "p" ) {
            Pcurrent = digitalRead(PUMP1);
            Pcurrent2 = digitalRead(PUMP2);
            Pcurrent3 = digitalRead(PUMP3);
            Pcurrent4 = digitalRead(PUMP4);

            Pcurrentold = Pcurrent ;
            Pcurrentold2 = Pcurrent2 ;
            Pcurrentold3 = Pcurrent3 ;
            Pcurrentold4 = Pcurrent4 ;
            if (devicetodo.substring(4,5) == " " ) {
              current = digitalRead(BUTTON);
//            currentold = 0 ;
            }

            if (devicetodo.substring(8,9) == " " ) {            
              curr = digitalRead(BUTT);
            }
            buttonupdt = 1 ;
//            PSerial ("");
//            PSerial ("PUMP1 = "); PlnSerial(String(current)) (
//            Pcurrentold = Pcurrent ;
          }
          if (devicetodo.substring(11,13) == "a" && totest == 1  ) {
              getpressure();
              get280();
              if (oldpressureKPA == 0) {
                oldpressureKPA = pressureKPA;
              }
              if (pressureKPA < 3000 ) {
//                ap += 1;
                pressureKPA = (oldpressureKPA + pressureKPA)/2;
                PSerial("pressure = ");PlnSerial (String (pressureKPA));
//                Serial.print("pressureKPA 1 = ");Serial.println (String (pressureKPA));
                if (abs(oldpressureKPA - pressureKPA) > 1){
                  PSerial("in difference pressure > 1. Diff = ");PlnSerial (String (abs(oldpressureKPA - pressureKPA)));
                  senddatatoapi();
                  ap = 0;
                }
                oldpressureKPA = pressureKPA ;
              }
              else {
                pressureKPA = oldpressureKPA ;
                PlnSerial("Could not read 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;
            if ( totest == 1  ) {
              PSerial(" | x = ");PSerial (String (x));
              PSerial(" | s = ");PlnSerial (String (flipcount/2));
              totest = 0 ;
              digitalWrite(LED, LOW);
            }
        }
        else
        {
           if (devicetodo.substring(12,13) == "a" && totest == 1  ) {
              getpressure();
              get280();
              if (pressureKPA < 3000 ) {
                if (oldpressureKPA == 0) {
                  oldpressureKPA = pressureKPA;
                }                
                pressureKPA = (oldpressureKPA + pressureKPA)/2;
//                Serial.print("pressureKPA 2 = ");Serial.println (String (pressureKPA));
//                PSerial("pressureKPA 2 = ");PlnSerial (String (pressureKPA));
//                Serial.print("ap 2 = ");Serial.println (String (ap));
                if (abs(oldpressureKPA - pressureKPA) > 1){
                  PSerial("in difference pressure > 1. Diff = ");PlnSerial (String (abs(oldpressureKPA - pressureKPA)));
                  senddatatoapi();
                  ap = 0;
                }
                PSerial("pressureKPA = ");PlnSerial (String (pressureKPA));
//                Serial.print("pressureKPA 3 = ");Serial.println (String (pressureKPA));
                oldpressureKPA = pressureKPA ;
              }
              else {
                pressureKPA = oldpressureKPA ;
                PlnSerial("Could not read pressureKPA = "); // PlnSerial (String (pressureKPA));
//                Serial.print("Could not read ap - pressureKPA = ");Serial.println (String (pressureKPA));

              }
            
          }

          if (devicetodo.substring(16,17) == "p" ) {
//          if (devicetodo == " , , , , , , , ,p" ) {
            ispoweron();          
          }
          if (devicetodo.startsWith("t") && totest == 1  ) {
            gettemp();
            t += 1 ;
            t2 += 1 ;
            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));
// removed 6-9-2016 to add in gettemp
//              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)) {
                PlnSerial("");PSerial("temp1 difference = ");PlnSerial (String (abs(valuedev1 - oldtemptest)));
//                PSerial("oldtemptest in if= ");PlnSerial (String (oldtemptest));
//                PSerial("valuedev1 in if = ");PlnSerial (String (valuedev1));
                senddatatoapi();
                oldtemptest= valuedev1 ;
              }
              PSerial("Temp1 = ");PSerial (String (valuedev1));
            }
            if ( numtemp == 2) {
             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 ( oldtemptest2 == 200 ){
                  oldtemptest2= temptemp2 ;
              }
//              PSerial("temptemp2 before adj = ");PlnSerial (String (temptemp2));
// removed 6-9-2016 to add in gettemp
//              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)) {
                PlnSerial("");PSerial("temp2 difference2 = ");PlnSerial (String (abs(valuedev2 - oldtemptest2)));
//                PSerial("oldtemptest2 in if= ");PlnSerial (String (oldtemptest2));
//                PSerial("valuedev2 in if = ");PlnSerial (String (valuedev2));
                senddatatoapi();
                oldtemptest2= valuedev2 ;
              }
              if (dhttemp == 0) {
                PSerial(" | Temp2 = ");PSerial (String (valuedev2));
              }
              else 
              {
                PSerial(" | Humid = ");PSerial (String (valuedev2));
              }
             }
            }
          }
          if (devicetodo.substring(2,3) == "v" && totest == 1  ) {
            getvolt();
            v += 1 ;
            if ( oldvolttest == 200 ){
                oldvolttest= voltvolt ;
            }
 /* removed nov-2-2016
              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)) {
              PlnSerial("");PSerial("volt difference = ");PlnSerial (String (abs(voltvolt - oldvolttest)));
/* removed nov-2-2016
              PSerial("oldvolttest in if= ");PlnSerial (String (oldvolttest));
              PSerial("valuedev3 in if = ");PlnSerial (String (valuedev3));
              PSerial("voltvolt in if = ");PlnSerial (String (voltvolt));
              PSerial("voltvolt = ");PlnSerial (String (voltvolt));
*/
              valuedev3 = voltvolt ;
              senddatatoapi();
              oldvolt = 0;
              newvolt = 0;
              oldvolttest= voltvolt ;
              v = 0 ;
            }
            PSerial(" | Volts = ");PSerial (String (voltvolt));
          }
          if ( totest == 1  ) {
             PSerial(" | x = ");PSerial (String (x));
             PSerial(" | s = ");PlnSerial (String (flipcount/2));
             totest = 0 ;
             digitalWrite(LED, LOW);
          }         
          if (devicetodo.substring(6,7) == "p" ) {
//            digitalWrite(BUTTON, current == 1 ? HIGH : LOW);
            Pcurrent = digitalRead(PUMP1);
            Pcurrent2 = digitalRead(PUMP2);
            Pcurrent3 = digitalRead(PUMP3);
            Pcurrent4 = digitalRead(PUMP4);
///
            if (devicetodo.substring(4,5) == " " ) {
              current = digitalRead(BUTTON);
//            currentold = 0 ;
            }

            if (devicetodo.substring(8,9) == " " ) {            
              curr = digitalRead(BUTT);
            }

//            PSerial ("");
//            PSerial ("PUMP = "); PlnSerial(String(Pcurrent));
//            PSerial ("old PUMP = "); PlnSerial(String(Pcurrentold));
            int tosendapi = 0;
            if (Pcurrentold != Pcurrent ) {
              PSerial("in change of pump1 status, now = ");PlnSerial(String(Pcurrent));
              tosendapi = 1 ;
            }
            if (Pcurrentold2 != Pcurrent2 ) {
              PSerial("in change of pump2 status, now = ");PlnSerial(String(Pcurrent2));
              tosendapi = 1 ;
            //  senddatatoapi();
            }
            if (Pcurrentold3 != Pcurrent3 ) {
              PSerial("in change of pump3 status, now = ");PlnSerial(String(Pcurrent3));
              tosendapi = 1 ;
           //   senddatatoapi();
            }
            if (Pcurrentold4 != Pcurrent4 ) {
              PSerial("in change of pump4 status, now = ");PlnSerial(String(Pcurrent4));
              tosendapi = 1 ;
           //   senddatatoapi();
            }
/*
            if ((devicetodo.substring(4,5) == " " ) && ( currentold != current )) {
              Serial.print("in change of p1 status");
              tosendapi = 1 ;
            }
            if ((devicetodo.substring(8,9) == " " ) && ( currold != curr )) {
              Serial.print("in change of p2 status");
              tosendapi = 1 ;
            }
*/            
            if ( tosendapi == 1 ) {
              buttonupdt = 1 ;
              senddatatoapi();
            }
            Pcurrentold = Pcurrent ;
            Pcurrentold2 = Pcurrent2 ;
            Pcurrentold3 = Pcurrent3 ;
            Pcurrentold4 = Pcurrent4 ;
            currentold = current ;
            currold = curr ;

          }

          if ( x == 1) { // starts with 5s frequency
//            valuedev1 = temptemp;
//            valuedev3 = voltvolt;
//            senddatatoapi();
              digitalWrite(LED, LOW); 
//              freq = 100 ;
              freq = delaytest*25 ;
              details = 1 ;
//              Serial.println("in x = 1") ;
//              Serial.print("Temp Frequency = "); Serial.println(freq);
//              Serial.print("Frequency = "); Serial.println(frequency);
          }
          else if (x == tempfreq ) {  // time to run the scheduled frequency
                    
            if ( debug == 0 ) {
              details = 0 ;
              PlnSerial("Details is now off") ;
              freq = frequency ; 
            }
            
//              Serial.print("Temp Frequency = "); Serial.println(freq);
//              Serial.print("Frequency = "); Serial.println(frequency);
          }
        }
      }
    }

      if (rebootfreq == 999) {

      }
      else if (rebootfreq == 9999) {
          senddatatoapi();
          Serial.println("Rebooting");
          matrix.print(0.0, DEC);
          matrix.writeDisplay();
          delay(500);
          ESP.restart(); 
      }
      else {
        if (x == rebootfreq + (freq - 80)) { // reboot frequency plus freq minus 8/th of a second
          senddatatoapi();
//          PlnSerial("Rebooting");
          Serial.println("Rebooting");
          matrix.print(0.0, DEC);
          matrix.writeDisplay();
          delay(500);
          ESP.restart(); 
        }
      }
//if (configMode == true) {
//  digitalWrite(LED, HIGH);
//}
//Serial.print("x = "); Serial.println(x);
///////////////////////////////////////////////////  a revoir
  if (countmode > 0) {
    matrix.print(countmode, DEC);
    matrix.writeDisplay();
    Serial.print("Pushed for "); Serial.println(countmode);// Serial.println("s");

  }
  else if ( x > 10 && configMode == true) {
    matrix.print(9999, DEC);
    matrix.writeDisplay();

//    PlnSerial("In AAAP mode");  
//    PlnSerial(ipStr);

  }
  else if ( x > 10 && configMode == false ) {
    if ( tempreading == "F" ) {
      temptodisp = (valuedev1*1.8)+32;
    }
    else {
      temptodisp = valuedev1;
    }

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

//    Serial.print("Temp: "); Serial.println(temptodisp);  
//    Serial.println(ipadd);
  }
  if (x % otatemp == 0 ){
    otaupdate() ;
  }

  if ( x == 100000000 ) {
     x = tempfreq ;
     flipcount = 0 ;
     totest = 0 ;
  }
  delay (100*delaytime) ;
}

void otaupdate() 
{
      
//      if(WiFi.waitForConnectResult() == WL_CONNECTED){
      if ( testWifi()){

        Serial.println ("In the updating file");
        Serial.print("updatestring = "); Serial.println(updatestring);
//      http://boatautomation.com/wsm/updatewsm1.php?macid=''&firmware='AP12'&versionnum='3.00'&whatis='T'&devicetodo='
       
//        t_httpUpdate_return ret = ESPhttpUpdate.update("http://boatautomation.com/wsm/update/WebUpdate-jojo1.bin");
// t_httpUpdate_return ret = ESPhttpUpdate.update("http://boatautomation.com", 80, "/wsm/updatewsm1.php", who);
        t_httpUpdate_return ret = ESPhttpUpdate.update(updatestring, who);

//        t_httpUpdate_return ret = ESPhttpUpdate.update("http://boatautomation.com/wsm/updatewsm1.php");
        //t_httpUpdate_return  ret = ESPhttpUpdate.update("https://server/file.bin");

        switch(ret) {
            case HTTP_UPDATE_FAILED:
                USE_SERIAL.printf("HTTP_UPDATE_FAILED Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
                Serial.println("");Serial.println("No update available");
//      Serial.println("");
//      Serial.print("Mem left = "); Serial.println(ESP.getFreeSketchSpace());
                break;

            case HTTP_UPDATE_NO_UPDATES:
                USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
                Serial.println("");Serial.println("No update available");
//                Serial.println("HTTP_UPDATE_NO_UPDATES");
                break;

            case HTTP_UPDATE_OK:
                USE_SERIAL.println("HTTP_UPDATE_OK");
                Serial.println("Updated");
//                Serial.println("HTTP_UPDATE_OK");
                break;
        }
    }
    else {
      Serial.println("Not connected - Not Updated");
    }
//    ESPhttpUpdate.update("75.103.94.221", 80, "/arduino.bin");
//    ESPhttpUpdate.update("http://www.aacdata.net", 80, "/wsm/update/arduino.bin");
//    Serial.println ("Done updating file");
//          Serial.println("Rebooting");
//          delay(500);
//          ESP.restart(); 

}

void senddatatoapi()
{  
  if ( freq == 999999 || (configMode == true && debug == 1)) {
    if (freq == 999999 ) {
          PlnSerial("frequency=999999 - no transmission scheduled");
    }
    else {
          PlnSerial("AP and debug mode-no transmission");
    }
  }
  else {
    if ( !getPage() ) {
      PlnSerial("Could not connect to server");
      sentapi = 0 ;
   }
    else {
      PlnSerial("Connection to server succeded");
      sentapi = 1 ;
    }
  }
}

bool getPage() {
   WiFiClient client;
  
  // Attempt to make a connection to the remote server
  if ( !client.connect(http_site, http_port) ) {
//  if ( !testWifi()){
    
//   if (!client.connect(Accessip, Accesport)) {
    return false;
  }
/*
   if ( tempreading = "C" ) { 
     float temptodisp = valuedev1;
   }
   else { // to change to celcius or farhaneigh
     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();
*/
       delay(10);
       digitalWrite(LED, HIGH);
       delay(100);
       digitalWrite(LED, LOW);   
       delay(100);
       digitalWrite(LED, HIGH);
       delay(100);
       digitalWrite(LED, LOW);  
              
  if (preverse == 1 ) {
    if (Pcurrent == 1) {
       Pcurrent = 0 ;
//       PlnSerial("in if preverse and pcurrent = 1 "); 
       }
    else {
       Pcurrent = 1 ;
//       PlnSerial("in if preverse and pcurrent = 0 "); 
    }
    if (Pcurrent2 == 1) {
       Pcurrent2 = 0 ;
//       PlnSerial("in if preverse and pcurrent2 = 1 "); 
       }
    else {
       Pcurrent2 = 1 ;
//       PlnSerial("in if preverse and pcurrent2 = 0 "); 
    }
    if (Pcurrent3 == 1) {
       Pcurrent3 = 0 ;
//       PlnSerial("in if preverse and pcurrent3 = 1 "); 
       }
    else {
       Pcurrent3 = 1 ;
//       PlnSerial("in if preverse and pcurrent3 = 0 "); 
    }
    if (Pcurrent4 == 1) {
       Pcurrent4 = 0 ;
//       PlnSerial("in if preverse and pcurrent4 = 1 "); 
       }
    else {
       Pcurrent4 = 1 ;
 //      PlnSerial("in if preverse and pcurrent4 = 0 "); 
    }

   }
//  PSerial("Pcurrent = "); PlnSerial(String(Pcurrent));
/////////////////////////////////////// a voir et corriger
  if (dhttemp == 1) {
//     valuedev1 = temp_f ;
//     valuedev2 = humidity;
  }
  String strvaluedev1 = "" ;
  if ( valuedev1 == -127 || valuedev1 == 185 || valuedev1 == 0) {
       strvaluedev1 = "n/a" ;
   }
   else {
      strvaluedev1 = String(valuedev1) ;
   }
  String strvaluedev2 = "" ;
  if ( valuedev2 == -127 || valuedev2 == 185 || valuedev2 == 0) {
       strvaluedev2 = "n/a" ;
   }
   else {
      strvaluedev2 = String(valuedev2) ;
   }
/////////////////////////////////////// a voir et corriger
  if (devicetodo.substring(12,13) == "a" ) {
    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) {
// if ( datetosave == "                       " ) {
    PlnSerial("in buttonupdt = 1");
//   toprint = wheretosend + "?macid='"+String(MAC_char)+"'&datesaved='"+String(datetosave)+"'&power='"+"'&baro='"+String(pressureKPA,1)+String(pcurrent)+"'&pushbutton='"+String(curr)+"'&button='"+String(current)+"'&pump='"+String(Pcurrent)+"'&pump2='"+String(Pcurrent2)+"'&pump3='"+String(Pcurrent3)+"'&pump4='"+String(Pcurrent4)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq/10)+"'&rebootfreq='"+String(rebootfreq/10)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"' HTTP/1.1" ;
   toprint = wheretosend + "?macid='"+String(MAC_char)+"'&datesaved='"+String(datetosave)+"'&power='"+"'&baro='"+String(pressureKPA,1)+String(pcurrent)+"'&pushbutton='"+String(curr)+"'&button='"+String(current)+"'&pump='"+String(Pcurrent)+"'&pump2='"+String(Pcurrent2)+"'&pump3='"+String(Pcurrent3)+"'&pump4='"+String(Pcurrent4)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq/10)+"'&rebootfreq='"+String(rebootfreq/10)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"'&reboottimes='"+reboottimes+"' HTTP/1.1" ;
   if ((devicetodo.substring(4,5) == "s" ) || (devicetodo.substring(8,9) == "b" )) {            
     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" ;
    toprint = wheretosend + "?macid='"+String(MAC_char)+"'&datesaved='"+String(datetosave)+"'&power='"+String(pcurrent)+"'&baro='"+String(pressureKPA,1)+"'&pushbutton='"+5+"'&button='"+5+"'&pump='"+String(Pcurrent)+"'&pump2='"+String(Pcurrent2)+"'&pump3='"+String(Pcurrent3)+"'&pump4='"+String(Pcurrent4)+"'&signal='"+String(rssi)+"'&temp1='"+String(strvaluedev1)+"'&temp2='"+String(strvaluedev2)+"'&temp3='"+String(valuedev3)+"'&freq='"+String(freq/10)+"'&rebootfreq='"+String(rebootfreq/10)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"'&reboottimes='"+reboottimes+"' HTTP/1.1" ;
  }
  PSerial("toprint = "); PlnSerial(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/10)+"'&rebootfreq='"+String(rebootfreq/10)+"'&clientcode='"+String(clientcode)+"'&ip='"+ipadd+"'&reboottimes='"+reboottimes+"'");
  if (preverse == 1 ) {
    if (Pcurrent == 1) {
       Pcurrent = 0 ;
//       PlnSerial("in if preverse and pcurrent = 1 "); 
       }
    else {
       Pcurrent = 1 ;
//       PlnSerial("in if preverse and pcurrent = 0 "); 
    }
    if (Pcurrent2 == 1) {
       Pcurrent2 = 0 ;
//       PlnSerial("in if preverse and pcurrent2 = 1 "); 
       }
    else {
       Pcurrent2 = 1 ;
 //      PlnSerial("in if preverse and pcurrent2 = 0 "); 
    }
    if (Pcurrent3 == 1) {
       Pcurrent3 = 0 ;
 //      PlnSerial("in if preverse and pcurrent3 = 1 "); 
       }
    else {
       Pcurrent3 = 1 ;
//       PlnSerial("in if preverse and pcurrent3 = 0 "); 
    }
    if (Pcurrent4 == 1) {
       Pcurrent4 = 0 ;
//       PlnSerial("in if preverse and pcurrent4 = 1 "); 
       }
    else {
       Pcurrent4 = 1 ;
//       PlnSerial("in if preverse and pcurrent4 = 0 "); 
    }
   }


//  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() {
  if (dhttemp == 1) {
    humidity = dht.readHumidity();          // Read humidity (percent)
    temp_f = dht.readTemperature(false);     // Read temperature as Celsius
    if (isnan(humidity) || isnan(temp_f)) {
      PlnSerial("Failed to read from DHT sensor!");
      temp_f = -127.0;
      humidity = -127.0;
      temptemp = -127.0 ;
      temptemp2 = -127.0 ;
      return;
    }
    else {
      temptemp = temp_f ;
      temptemp = temptemp + adjtemp ;
      temptemp2 = humidity ;
      temptemp2 = temptemp2 + adjtemp2 ;

      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));
           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 {
        temptemp = (round(temptemp * precision) ) ; // / precision ;
        temptemp = (temptemp / precision)  ; // / precision ;
        temptemp2 = (round(temptemp2 * precision) ) ; // / precision ;
        temptemp2 = (temptemp2 / precision)  ; // / precision ;
      }
      
    }

  }
  else if (dhttemp == 2) {
    printTemp31855(temp.readThermocouple(CELSIUS));
    temptemp = tempmax31855 ;
    if ( temptemp == 0 ) {
      temptemp == -127.0 ;
      temptemp2 == -127.0 ;
      return;
    }

      temptemp = temptemp + adjtemp ;
//      PSerial("tempmax31855 temptemp = ");PlnSerial (String (temptemp));
      printTemp31855(temp.readJunction(CELSIUS));
      temptemp2 = tempmax31855 ;
      temptemp2 = temptemp2 + adjtemp2 ;
//      PSerial("tempmax31855 temptemp2 = ");PlnSerial (String (temptemp2));
      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));
           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 {
        temptemp = (round(temptemp * precision) ) ; // / precision ;
        temptemp = (temptemp / precision)  ; // / precision ;
        temptemp2 = (round(temptemp2 * precision) ) ; // / precision ;
        temptemp2 = (temptemp2 / precision)  ; // / precision ;
      }

  }
  else if ( dhttemp == 0){
  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();
 
//  PSerial("temptemp before anything = ");PlnSerial (String (temptemp));

//  if ((abs(temptemp - oldtemptest) > 20 * tempdiff && oldtemptest < 200 && wrongtempcount < wtcmax) || temptemp == 185 ){
//  if ((wrongtempcount < wtcmax) && oldtemptest < 200 )|| temptemp == 185 || temptemp == 0 ){    
    if ( temptemp == 0 || temptemp == 185 ) {
      temptemp = -127 ;
      wrongtempcount += 1 ;
//      PSerial("wrongtempcount = ");PlnSerial (String (wrongtempcount));
    }
  else {
    wrongtempcount = 0 ;
    temptemp = temptemp + adjtemp ;
//    PSerial ("temptemp = "); PlnSerial(String(temptemp));
    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));

  }
  if ( numtemp > 1 ) {
    printData(outsideThermometer);
    temptemp2 = tempv.toFloat(); 

//  temperature = String(temptemp);
//  temperature = String(temptemp + adjtemp);
//  Serial.print("Temperature  in C: ");
//  Serial.println(temperature);
///////////////////////////////////////////////////////////// a faire come temp1
//  if (abs(temptemp2 - oldtemptest2) > 4 * tempdiff )  {
//  if ((abs(temptemp2 - oldtemptest2) > 20 * tempdiff && oldtemptest2 < 200 && wrongtempcount < wtcmax) || temptemp2 == 185 ){
    if ( temptemp2 == 0 || temptemp2 == 185 ) {
      temptemp2 = -127 ;
      wrongtempcount += 1 ;
//      PSerial("wrongtempcount = ");PlnSerial (String (wrongtempcount));
    }
  else {
    wrongtempcount = 0 ;
    temptemp2 = temptemp2 + adjtemp2 ;
//    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));
    
   }
  }
 }  
// added may 4th-2016
/*
      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));
           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 {
        temptemp = (round(temptemp * precision) ) ; // / precision ;
        temptemp = (temptemp / precision)  ; // / precision ;
        temptemp2 = (round(temptemp2 * precision) ) ; // / precision ;
        temptemp2 = (temptemp2 / precision)  ; // / precision ;
      }
*/
}

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

// Print the temperature, or the type or fault for Max31855
void printTemp31855(double temperature) {
  float oldtemp31855 = valuedev1 ;
  switch ((int) temperature) {
    case FAULT_OPEN:
        PlnSerial("FAULT_OPEN");
        tempmax31855 = oldtemp31855;
      break;
    case FAULT_SHORT_GND:
        PlnSerial("FAULT_SHORT_GND");
        tempmax31855 = oldtemp31855;
      break;
    case FAULT_SHORT_VCC:
        PlnSerial("FAULT_SHORT_VCC");
        tempmax31855 = oldtemp31855;
      break;
    case NO_MAX31855:
        PlnSerial("NO_MAX31855");
      break;
    default:
          tempmax31855 = temperature ;
//          PSerial("Max31855 = ");  PlnSerial(String(tempmax31855));
      break;
  }
//  PSerial("   ");
}
// 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-baro";
//  devicetodo = "t,v, , , , ,a, ,";

  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-pump";
  devicetodo = "t,v, ,p, , , , , ";
 }
 else if (whatis == "d") {
  devicetype = "temp-volt-pump-rev";
  devicetodo = "t,v, ,p, , , , , ";
  preverse = 1;
 }
 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 == "P") {
  devicetype = "pump";
  devicetodo = " , , ,p, , , , , ";
  tempfreq = 2 ;
 }
  
 else if (whatis == "Q") {
  devicetype = "pump";
  devicetodo = " , , ,p, , , , , ";
  preverse = 1;
  tempfreq = 2 ;
 }
 else if (whatis == "p") { // power failure
  devicetype = "power";
  devicetodo = " , , , , , , , ,p";
  
  tempfreq = 2 ;
 }
  else if (whatis == "o") { // power failure + temp
  devicetype = "power & temp";
  devicetodo = "t, , , , , , , ,p";
  dhttemp = 0;  // ds18b20 sensor
  
 }
 else if (whatis == "R") { // device means reading 0 - 1023 on adc
  devicetype = "dev";
  devicetodo = " , , ,d, , , , , ";
 }
 else if (whatis == "S") {
  devicetype = "switch";
  devicetodo = " , ,s, , , , , , ";
  tempfreq = 2 ;
 }
else if ( whatis == "T") {
  devicetype = "temp";
  devicetodo = "t, , , , , , , , ";
  dhttemp = 0;  // ds18b20 sensor
 }
 else if (whatis == "U") {
  devicetype = "push button";
  devicetodo = " , , , ,b, , , ";
  tempfreq = 2 ;
 }
 else if (whatis == "V") {
  devicetype = "volt";
  devicetodo = " ,v, , , , , , , ";
 }
 else if (whatis == "v") {
  devicetype = "temp-humid-volt-pump";
  devicetodo = "t,v, ,p, , , , , ";
  dhttemp = 1;  // dht22 sensor
 }
 else if (whatis == "W") {
  devicetype = "temp-humid-volt-pump";
  devicetodo = "t,v, ,p, , , , , ";
  dhttemp = 1;  // dht22 sensor
  preverse = 1;
 }
 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 ( whatis == "Y") {
  devicetype = "temp-humidity";
  devicetodo = "t, , , , , , , , ";
  dhttemp = 1;  // dht22 sensor
 }
 else if ( whatis == "y") {
  devicetype = "temp-humidity-volt";
  devicetodo = "t,v, , , , , , , ";
  dhttemp = 1;  // dht22 sensor
 }
else if ( whatis == "Z") {
  devicetype = "high_temp";
  devicetodo = "t, , , , , , , , ";
  dhttemp = 2; // 500 to 800 degrees heat
 }

else if ( whatis == "Z") {
  devicetype = "high_temp-volt";
  devicetodo = "t,v, , , , , , , ";
  dhttemp = 2; // 500 to 800 degrees heat
 }
else if ( whatis == "1") {
  devicetype = "high_temp-volt-pump";
  devicetodo = "t,v, ,p, , , , , ";
  dhttemp = 2; // 500 to 800 degrees heat
 }

else if ( whatis == "2") {
  devicetype = "high_temp-volt-pump";
  devicetodo = "t,v, ,p, , , , , ";
  dhttemp = 2; // 500 to 800 degrees heat
  preverse = 1;
 }

 if (devicetodo.substring(4,5) == "s" ) {
//  buttonupdt = 1 ;
// 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);
    pinMode(PUMP2, INPUT);
    pinMode(PUMP3, INPUT);
    pinMode(PUMP4, INPUT);
//    digitalWrite(PUMP1, LOW);
//    digitalWrite(PUMP2, LOW);
//    digitalWrite(PUMP3, LOW);

//  pinMode(BUTTON, OUTPUT);
   
  // grab the current state of the button
    Pcurrent = digitalRead(PUMP1);
    Pcurrentold = Pcurrent ;
    Pcurrent2 = digitalRead(PUMP2);
    Pcurrentold2 = Pcurrent2 ;
    Pcurrent3 = digitalRead(PUMP3);
    Pcurrentold3 = Pcurrent3 ;
    Pcurrent4 = digitalRead(PUMP4);
    Pcurrentold4 = Pcurrent4 ;
    
    PSerial ("");
    PSerial ("Pump1 = "); PlnSerial(String(Pcurrent));
    PSerial ("Pump2 = "); PlnSerial(String(Pcurrent2));
    PSerial ("Pump3 = "); PlnSerial(String(Pcurrent3));
    PSerial ("Pump4 = "); PlnSerial(String(Pcurrent4));
    if (devicetodo.substring(4,5) == " " ) {
      pinMode(BUTTON, INPUT);
      digitalWrite(BUTTON, LOW);
   
  // grab the current state of the button
      current = digitalRead(BUTTON);
      currentold = 0 ;
      PSerial ("B1 = "); PlnSerial(String(current));
    }

    if (devicetodo.substring(8,9) == " " ) {
//      buttonupdt = 1 ;
      pinMode(BUTT, INPUT);
   
  // grab the current state of the button
      curr = digitalRead(BUTT);
      currold = 0 ;

      PSerial ("");
      PSerial ("B2 = "); PlnSerial(String(curr));
    }
  }
 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 ispoweron() {
  PSerial("powercut = "); PlnSerial(String(powercut));
  PSerial("sentapi = "); PlnSerial(String(sentapi));
  if ( powercut == 1) {
    pcurrent = 0 ;
//    datetosave = dateTime ;
    senddatatoapi();
    PlnSerial("Sending api");

    if ( sentapi == 1) {
      powercut = 0 ;
      datetosave = "                        " ;
        PSerial("datetosave = ");
        PlnSerial(datetosave);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        PlnSerial("clearing eeprom");
//        for (int i = 140; i < 141; ++i) 
        for (int i = datetosave_from; i < datetosave_to; ++i)

            { EEPROM.write(i, clearchar[0]) ; }
/*    
        PlnSerial("writing eeprom datetosave:");
//        for (int i = 140; i < 141; ++i)
        for (int i = datetosave_from; i < datetosave_to; ++i)

          {
            EEPROM.write(i, datetosave[i-datetosave_from]);
            PSerial("Wrote: ");
            PlnSerial(datetosave[i-datetosave_from]); 
          }
*/
        EEPROM.commit();
//        s += "<p>Saved<p>";

//        resolution = strreqanswer.toInt() ;
//        y = freq ;        
//        sensors.setResolution(0,resolution);
        PSerial("datetosave = "); PlnSerial(datetosave);
      
    }
  }
  else {
    pcurrent = digitalRead(POWER);
//   PSerial ("");
//            PSerial ("PUMP1 = "); PlnSerial(String(current)) (

  }
if (pcurrent == 1) {  // IO0 is 1 
/*
  PSerial("connecting to ");
  PlnSerial(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 13;

  if (!client.connect(host, httpPort)) {
    PlnSerial("connection failed");
    return;
  }

  PlnSerial(">Sending Header<}");
  
  // This will send the request to the server
///////////////////////////////////////////////////  missing line here
  delay(100);

  // Read all the lines of the reply from server and print them to Serial
  // expected line is like : Date: Thu, 01 Jan 2015 22:00:14 GMT
//  char buffer[12];
//  String dateTime = "";
  PlnSerial(">  Listening...<");

  while(client.available())
  {
    String line = client.readStringUntil('\r');

    if (line.indexOf("Date") != -1)
    {
      PSerial("=====>");
    } else
    {
      // PSerial(line);
      // date starts at pos 7
      TimeDate = line.substring(7);
      PlnSerial(TimeDate);
      // time starts at pos 14
      TimeDate = line.substring(7, 15);
      datetosave = TimeDate ;
      TimeDate.toCharArray(buffer, 10);
      PlnSerial("UTC Date/Time:");
      PlnSerial(buffer);
      TimeDate = line.substring(16, 24);          
      TimeDate.toCharArray(buffer, 10);
      PlnSerial(buffer);
//    $date = date('Y-m-d\TH:i:s\-\0\0\:\0\0');
      PSerial("datetosave1 = "); PlnSerial(datetosave); 
//      datetosave += myChar + TimeDate + myChar + "-" + myChar + "0" + myChar + "0" + myChar + ":" + myChar + "0" + myChar + "0" ;   
        datetosave += "T" + TimeDate + "-00:00" ;   

      PSerial("datetosave = "); PlnSerial(datetosave); 
 
    }
  }

  PlnSerial("");
  PlnSerial("closing connection");
  client.println("Connection: close");
  client.println();
  PlnSerial("Close connection}");
  PlnSerial(">WiFi Connected<}");
*/
datetosave = dateTime ;

  if (pcurrentold == 0 ){
        datetosave = dateTime ;
        senddatatoapi();
         PlnSerial("Sending api");
  }
  
}
else if (pcurrentold == 1){ // save the last time read in eeprom
//     else if ( req.startsWith("/resolution=") ) {
//        s += "<p>Saving the resolution value<p>";
//        s += "</html>\r\n\r\n";

       // strreqanswer = req.substring(req.lastIndexOf('=')+1);
        PSerial("in else datetosave = ");
        datetosave = dateTime ;
        
        PlnSerial("datetosave = " + datetosave);
        String firsteeprom = "9";
        EEPROM.write(0, firsteeprom[0] );
        EEPROM.commit();

        PlnSerial("clearing eeprom");
//        for (int i = 140; i < 141; ++i) 
        for (int i = datetosave_from; i < datetosave_to; ++i)

            { EEPROM.write(i, clearchar[0]) ; }
    
        PlnSerial("writing eeprom datetosave:");
//        for (int i = 140; i < 141; ++i)
        for (int i = datetosave_from; i < datetosave_to; ++i)

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

//        resolution = strreqanswer.toInt() ;
//        y = freq ;        
//        sensors.setResolution(0,resolution);
        Serial.println("datetosave = " + datetosave);
        powercut = 1 ;
        Serial.println("Powering off in 10s "); 
        delay(5000);
        Serial.println("Off"); 
        digitalWrite(POWER2, LOW);      
        delay(10000);
  
}
if ( digitalRead(POWER2) == 0  && pcurrent == 1 ) {
  Serial.println("restarting");
  digitalWrite(POWER2, HIGH);      
}

    if ( sentapi == 1) {
        
    }
  pcurrentold = pcurrent ;
}

void counttime() {
  if (TimeDates < 59) {
    TimeDates += 1 ;

  }
  else if ( TimeDates == 59 ) {
    TimeDates = 0 ;

    if (TimeDatem < 59 ) {
      TimeDatem += 1 ;    
    }
    else if ( TimeDatem == 59 ) {
      TimeDatem = 0 ;
//      checktime() ;
//Serial.println("*********************************************checked time");      

      if ( TimeDateh < 23 ) {
        TimeDateh += 1 ;
        if (TimeDateh == 23 ) {
          //TimeDateh = 0 ;
          if (TimeDateh == 23 && TimeDatem == 59 && TimeDates == 59 ) {
            checktime() ;

PlnSerial("*********************************************checked time");      
          // to continue with days or restart the datetime
          }
        }
      }
    }
  }
      if ((TimeDates == 59 ) && (TimeDatem == 10 || TimeDatem == 20 || TimeDatem == 30 || TimeDatem == 40 || TimeDatem == 50 || TimeDatem == 0 )){
        checktime() ;
PlnSerial("*********************************************checked time");      
      }

    if (TimeDateh < 10) {
      TimeDatehs = "0"+String(TimeDateh);
    }      
    else {
      TimeDatehs = String(TimeDateh);
    }
    if (TimeDatem < 10) {
      TimeDatems = "0"+String(TimeDatem);
    }      
    else {
      TimeDatems = String(TimeDatem);
    }
    if (TimeDates < 10) {
      TimeDatess = "0"+String(TimeDates);
    }      
    else {
      TimeDatess = String(TimeDates);
    }
dateTime = DateDate + "T" + TimeDatehs + ":" + TimeDatems + ":" + TimeDatess + "-00:00" ;   
PlnSerial ("Date = " + dateTime );
}

void checktime() {
  dateTime = "" ;
 while ((dateTime == "") || dateTime.startsWith("d")) {
  PSerial("connecting to ");
  PlnSerial(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 13;

///  if (!client.connect(host, httpPort)) {
///    PlnSerial("connection failed");
///    return;
///  }
int ttt = 0 ;
  //while (!client.connect(host, httpPort) && ttt < 20 ) {
  while ( ttt < 20 ) {
    if (!client.connect(host, httpPort)) {
      PlnSerial("connection failed");
    }
    else {
      PlnSerial("connection succeeded");
      ttt = 20 ;
    }
    ttt++ ;
    
  }
  PlnSerial(">Sending Header<}");
  
  // This will send the request to the server
  client.print("HEAD / HTTP/1.1\r\nAccept: */*\r\nUser-Agent: Mozilla/4.0 (compatible; ESP8266 NodeMcu Lua;)\r\n\r\n");

  delay(100);

  // Read all the lines of the reply from server and print them to Serial
  // expected line is like : Date: Thu, 01 Jan 2015 22:00:14 GMT
//  char buffer[12];
  PlnSerial(">  Listening...<");

  while(client.available())
  {
    String line = client.readStringUntil('\r');

    if (line.indexOf("Date") != -1)
    {
      PSerial("=====>");
    } else
    {
///      TimeDate = line.substring(7);
      DateDate = line.substring(7);
      PlnSerial(DateDate);
      // time starts at pos 14
///      TimeDate = line.substring(7, 15);
      DateDate = line.substring(7, 15);
///      datetosave = TimeDate ;
///      TimeDate.toCharArray(buffer, 10);
      DateDate.toCharArray(buffer, 10);
      PlnSerial("UTC Date/Time:");
      PlnSerial(buffer);
      TimeDate = line.substring(16, 24);          
      TimeDateh = line.substring(16, 18).toInt();          
      PlnSerial("Hours:" + String(TimeDateh));
      TimeDatem = line.substring(19, 21).toInt();          
      PlnSerial("Minutes:" + String(TimeDatem));
      TimeDates = line.substring(22, 24).toInt();          
      PlnSerial("Seconds:" + String(TimeDates));
      TimeDate.toCharArray(buffer, 10);
      PlnSerial(buffer);
//    $date = date('Y-m-d\TH:i:s\-\0\0\:\0\0');
//      PSerial("datetosave1 = "); PlnSerial(datetosave); 
//      datetosave += myChar + TimeDate + myChar + "-" + myChar + "0" + myChar + "0" + myChar + ":" + myChar + "0" + myChar + "0" ;   
          dateTime = DateDate + "T" + TimeDate + "-00:00" ;   
        dateTime = DateDate + "T" + String(TimeDateh) + ":" + String(TimeDatem) + ":" + String(TimeDates) + "-00:00" ;   
      PSerial("dateTime = "); PlnSerial(dateTime); 
      
    }
  }

  PlnSerial("");
  PlnSerial("closing connection");
  client.println("Connection: close");
  client.println();
  PlnSerial("Close connection}");
  PlnSerial(">WiFi Connected<}");
 }

}

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); changed nov-2-2016
    delay(100);
}

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