/**
 * httpUpdate.ino
 *
 *  Created on: 27.11.2015
 *
 */
#include <Ticker.h>
#include <Arduino.h>
#include <ESP8266mDNS.h>
#include <WiFiClient.h>
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

#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 = "3.04.20";
String firmware = "AP12-4M,3MSP-QIO-ck,";
String who = "" ;

int otatemp = 200; // x number of revolutions to check upate - needs to be changed to daily or weekly

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" ;
const char http_site[] = "75.103.94.221";
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 = ""; // "Jojo" ; //"UNITE-52ED";
String rpass = "" ; // "jojowifi" ; //"22329280";
long rssi ;
String wifiname = "" ;

boolean newSSID = false;
int x = 0;
int y = 0 ;
int v = 0 ;
int t = 0 ;
int t2 = 0 ;
int pb = 0 ;
int ap = 0 ;
int pbstatus = 0 ;
int pbtime = 0 ;
int freq = 29000 ; //  transmit the data every 1 hour
int frequency = freq ;
int details = 0 ;
//int details = 1 ;
//String updatestring = "" ;
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();
  }
*/
}


String macid = "60:01:94:0a:ce:59:" ;
String updatestring = "http://boatautomation.com/wsm/updatewsm1.php?macid='"+String(macid)+"'";

void setup() {
/*
    USE_SERIAL.begin(9600);
    // USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }
*/
  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.println("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() ;
      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(".");
    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)+"'";

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


//    WiFiMulti.addAP("Jojo-Ext", "boat-2016");
//x = 1 ;
//}
  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;
}


void loop() {
  Serial.print("in the loop - x = ");  Serial.println(x);
  delay(500);
  ESP.restart(); 
/*          
    // wait for WiFi connection
    if((WiFiMulti.run() == WL_CONNECTED)) {

//        t_httpUpdate_return ret = ESPhttpUpdate.update("http://www.aacdata.net/wsm/update/httpUpdate-jojo1.bin");
        //t_httpUpdate_return  ret = ESPhttpUpdate.update("https://server/file.bin");
      if (x % 200 == 0 ){
        otaupdate() ;
      }
    }
x += 1 ;
Serial.print ("x = ");Serial.println (x);
*/
}

void torun() {
/*
    if((WiFiMulti.run() == WL_CONNECTED)) {

//        t_httpUpdate_return ret = ESPhttpUpdate.update("http://www.aacdata.net/wsm/update/httpUpdate-jojo1.bin");
        //t_httpUpdate_return  ret = ESPhttpUpdate.update("https://server/file.bin");
      if (x % 200 == 0 ){
        otaupdate() ;
      }
    }
x += 1 ;
Serial.print ("x = ");Serial.println (x);
*/
  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 == "C" ) {
      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) ;

}


