#include <Wire.h> 
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include "SPIFFS.h"
#include <SHT21.h>  // include SHT21 library
#include <OneWire.h>
#include <DallasTemperature.h>
#include "RTClib.h"
#include <ESPAsyncWebServer.h>

LiquidCrystal_I2C lcd(0x3F, 20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

int pinCLK = 27;
int pinDT  = 14;
int pinSW  = 12;
#define HEAT1 02
#define HEAT2 04
#define VENT 13
#define STEP 25
#define DIR 26
#define DAT 15
#define IA1 16
#define IB1 17
#define IA2 32
#define IB2 33
#define S3 34
#define HLADINA 36

//*************************************************************************************************************
int poziceEnkod = 0;
int stavPred;
int stavCLK;
int stavSW;
int nastav = 0;
int poz_home = 0, poz_menu = 0, x = 0, poz_nast = 0, ymin = 0, ymax, f_vent = 0;
int akt = 1;     //aktualizace LCD
char *type[8] = {"Teplota", "Vlhkost", "Ventilace", "Krmeni", "Tekutiny", "Vzorkovani", "WIFI", "Cerpadla"};    //menu
int temp[6] = {0,0,1,20,0,50};  //povoleni, nastaveni, tep, min, max
int hum[6] = {0,0,1,20,0,100};  //povoleni, nastaveni, hum, min, max
int sample[6] = {0,0,1,60,1,1000}; //povoleni, delay, min, max
int vent[12] = {0,0,1,1,1,100,30,1,1000,100,1,100}; //povoleni, delay, min, max, lengt, min, max, power, min, max
int krmeni[9] = {0,0,1,1,1,100,1,1,10}; //povoleni, delay, min, max, davka, min, max
int voda [9] = {0,0,1,1,1,100,1,1,10};   //povoleni, delay, min, max, davka, min, max
int wifi[6] = {0,0,1,0,0,1};     //povoleni
String wifi_name[10];
int wifi_last = 0, n;

OneWire ONE_WIRE_BUS(DAT);                  //datový pin připojen na pin 15
OneWire oneWire(ONE_WIRE_BUS);            // aktivace comunikace po datové sběrnici pro komunikaci se senzorem Dallas
DallasTemperature sensors(&oneWire);      // Spřístupnění senzoru Dallas pomocí sběrnice
DeviceAddress sensor1 = { 0x28, 0xFF, 0xBC, 0xC9, 0x71, 0x15, 0x3, 0x39 };      //definice senzorů
DeviceAddress sensor2 = { 0x28, 0xFF, 0xEA, 0xE7, 0x38, 0x16, 0x4, 0x3C };
DeviceAddress sensor3 = { 0x28, 0xFF, 0x21, 0x19, 0x39, 0x16, 0x4, 0xA1 };
DeviceAddress sensor4 = { 0x28, 0xFF, 0x4E, 0x19, 0x39, 0x16, 0x4, 0xDF };
DeviceAddress sensor5 = { 0x28, 0xFF, 0xAA, 0x54, 0x38, 0x16, 0x3, 0x4F };
DeviceAddress sensor6 = { 0x28, 0xFF, 0xF3, 0x52, 0x38, 0x16, 0x3, 0x20 };
//DeviceAddress sensor7 = { 0x28, 0xCF, 0x52, 0x79, 0xA2, 0x16, 0x3, 0x95 };  //reference
float se1 = 0, se2 = 0, se3 = 0, se4 = 0, se5 = 0, se6 = 0, se7 = 0, prum1 = 0, prum2 = 0, ref = 0;
SHT21 sht; 
float sht_temp;   // variable to store temperature
float sht_hum; // variable to store hemidity
RTC_DS3231 rtc;
unsigned long startMillis_heat, currentMillis_heat;
const unsigned long period_heat = 30000;
unsigned long startMillis_hum, currentMillis_hum;
const unsigned long period_hum = 1800000;
unsigned long startMillis_sample, currentMillis_sample;
const unsigned long period_sample = 60000;
unsigned long startMillis_vendD, currentMillis_vendD;
const unsigned long period_vendD=  3600000; 
unsigned long startMillis_vendL, currentMillis_vendL;
const unsigned long period_vendL =  1000;
unsigned long startMillis_krmeni, currentMillis_krmeni;
const unsigned long period_krmeni =  3600000;
unsigned long startMillis_vodaD, currentMillis_vodaD;
const unsigned long period_vodaD =  3600000;
unsigned long startMillis_vodaL, currentMillis_vodaL;
const unsigned long period_vodaL=  14000;

unsigned long fan_pretime = 0;
char serial_command = 0;
AsyncWebServer server(80);

char module_wifiname[20] = "default";
char module_wifipassword[20] = "default";
const char* ssid = module_wifiname;
const char* password = module_wifipassword;
//*******************************************************************************************************************  web
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
  <title>Inovace zarizeni pro chov potemnika moucneho</title>
  <style>
    html {font-family: Times New Roman; display: inline-block;}
    h2 {font-size: 2rem; color: #FF0000;}
  </style>
  </head><body>
  <h2>Inovace zarizeni pro chov potemnika moucneho</h2>  
  <form action="/get">
  
    Povoleni regulace teploty:    <input type="checkbox" name="per_temp" value="H"> <br>
        Nataveni teploty:         <input type="text" name="set_temp" ><br>
        Senzor teploty:           "(prum1+prum2)/2"<br>
    Povoleni regulace vlhkosti:   <input type=Checkbox name=per_hum value="H" ><br>
        Nastaveni vlhkosti:       <input type="text" name="set_hum" ><br>
        Senzor vlhkosti:          "sht_hum"<br>
    Povoleni ventilace:           <input type="checkbox" name="per_vent" value="H"> <br>
        Interval ventilace:       <input type="text" name="set_ventD"> <br>
        Delka ventilace:          <input type="text" name="set_ventL" ><br>
        Sila ventilace:           <input type="text" name="set_ventP" ><br>
    Povoleni krmeni:              <input type="checkbox" name="per_krmeni" value="H"> <br>
        Interval krmeni:          <input type="text" name="set_krmeniD" ><br>
        Mnozstvi krmeni:          <input type="text" name="set_krmeniL" ><br>
    Povoleni prisunu vody:        <input type="checkbox" name="per_voda" value="H"> <br>
        Interval prisunu vody:    <input type="text" name="set_vodaD" ><br>
        Mnozstvi vody:            <input type="text" name="set_vodaL" ><br>
    Povoleni ukladani dat:        <input type="checkbox" name="per_ventilace" value="H"> <br>
        Interval ukladani dat:    <input type="text" name="set_sampleD" ><br>

  <br>
    <input type="submit" value="Ulozit nastaveni">
  </form>
  <form action="/Mereni"><br>
    <input type="submit" value="Nacist mereni">
  
</body></html>)rawliteral";
void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}
/*
void Mereni() {
  String text = "";
  File filex = SPIFFS.open("/data.txt");
  String i;
  while (filex.available()){
    i = String((char)filex.read());
    if (i == "\n")
      text += "<br>";
    else if (i == ".")
      text += ",";
    else
      text += i;
  }
  filex.close();
  server.send(200, "text/html", text);
  
}
*/
//*************************************************************************************************************   
void serialcommunication() {
  if (Serial.available() > 0) {            // pokud seriova komunikace
    serial_command = Serial.read();
    if (serial_command == 'E') {           //mazání měřených dat
      SPIFFS.remove("/data.txt");
      //SPIFFS.remove("/settings.txt");
    }
    if (serial_command == 'F') {           //Formátování paměti
      SPIFFS.format();
      Serial.println("B");
    }
    if (serial_command == 'L') {          //čtení měřených dat do PC
      delay(1000);
      File filex = SPIFFS.open("/data.txt");
      while (filex.available())
        Serial.write(filex.read());
      filex.close();
      Serial.write('\0');
    }
    if (serial_command == 'a') {          //listAllFiles
        File root = SPIFFS.open("/");
        File file = root.openNextFile();
        while(file){
          Serial.print("FILE: ");
          Serial.println(file.name());
          file = root.openNextFile();
        }
    }
  }
}
//*************************************************************************************************************   
void initialdata() {
//----------------------------------------    čtení nastavení z paměti
  if (SPIFFS.exists("/settings.txt") == true) {
    wifi_last=wifi[0];
    char file[150];
    File filex = SPIFFS.open("/settings.txt");
    int i = 0;
    while (filex.available())
      file[i++] = char(filex.read());
    filex.close();

    String tem = "\0";
    i = 0;
    int z = 0, c = 0, y=0;
    for (c = 0 ; tem[c];c++)
      tem[c] = '\0';
    
    while (file[i] != '-') {
      while (file[i] != '+') {
        if (file[i] != '.') {
          tem += String(file[i]);
        }
        else {
          if(z == 0) {temp[y] = tem.toInt();}
          if(z == 1) {hum[y] = tem.toInt();}
          if(z == 2) {sample[y] = tem.toInt();}
          if(z == 3) {vent[y] = tem.toInt();}
          if(z == 4) {krmeni[y] = tem.toInt();}
          if(z == 5) {voda[y] = tem.toInt();}
          if(z == 6) {wifi[y] = tem.toInt();}
          y++;         
          tem = "\0";
        }
        i++;
      }
      Serial.println("/br");
      z++;
      y=0;
      i++;
    }
  }
//----------------------------------------    přepočet teploty
  if (temp[3]<24) {ref=temp[3];}
  else if (temp[3]==24) {ref=22.98;}
  else if (temp[3]==25) {ref=23.2;}
  else if (temp[3]==26) {ref=23.42;}
  else if (temp[3]==27) {ref=23.65;}
  else if (temp[3]==28) {ref=23.85;}
  else if (temp[3]==29) {ref=24;}
  else if (temp[3]==30) {ref=24.3;}
  else if (temp[3]==31) {ref=24.5;}
  else if (temp[3]==32) {ref=24.7;}
  else if (temp[3]==33) {ref=24.95;}
  else if (temp[3]==34) {ref=25.2;}
  else if (temp[3]==35) {ref=25.6;}
  else if (temp[3]==36) {ref=22;}
  else if (temp[3]==37) {ref=25.8;}
  else if (temp[3]==38) {ref=26;}
  else if (temp[3]>38) {ref=temp[3];}
//----------------------------------------          // de/aktivase wifi
  if ((wifi[0]==0)and(wifi_last!=wifi[0])) {
    wifi_last=wifi[0]; 
    WiFi.mode(WIFI_OFF);
  }
  else if ((wifi[0]==1)and(wifi_last!=wifi[0])) {
    wifi_last=wifi[0];
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to the WiFi network");
    Serial.println(WiFi.localIP());

    
    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
      request->send_P(200, "text/html", index_html);
      });

   // server.on("/mereni", HTTP_GET, [](AsyncWebServerRequest *request){
   //   request->send_P(200, "text/html", mereni());
   //   });

    server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
      request->send_P(200, "text/html", index_html);
      });
    server.onNotFound(notFound);
    server.begin();      
  }
}
void savedata() {                                       //uložit nastavení do paměti
  File file = SPIFFS.open("/settings.txt", FILE_WRITE);
  int i = 0;
  for (i = 0; i<6; i++) {file.print(temp[i]); file.print(".");}
  file.print("+");
  for (i = 0; i<6; i++) {file.print(hum[i]); file.print(".");}
  file.print("+");
  for (i = 0; i<6; i++) {file.print(sample[i]); file.print(".");}
  file.print("+");
  for (i = 0; i<12; i++) {file.print(vent[i]); file.print(".");}
  file.print("+");
  for (i = 0; i<9; i++) {file.print(krmeni[i]); file.print(".");}
  file.print("+");
  for (i = 0; i<9; i++) {file.print(voda[i]); file.print(".");}
  file.print("+");
  for (i = 0; i<6; i++) {file.print(wifi[i]); file.print(".");}
  file.print("+");
  file.print("-");
  file.close();

  initialdata();
}
void wifi_scan() {
  n = 0;
  n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n > 0){
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      wifi_name[i]=WiFi.SSID(i);
      delay(10);
      Serial.println(wifi_name[i]);
    }
  }
}

//*******************************************************************************************************************
void V_heat(){                              //regulace teploty
  sensors.requestTemperatures();          // požadavek pro získání teploty
  se1 = sensors.getTempC(sensor1);
  se2 = sensors.getTempC(sensor2);
  se3 = sensors.getTempC(sensor3);
  se4 = sensors.getTempC(sensor4);
  se5 = sensors.getTempC(sensor5);
  se6 = sensors.getTempC(sensor6);
  prum1= (se1+se2+se4+se5)/4;
  prum2= (se2+se3+se5+se6)/4;
  if(temp[0]==1){
    if (prum1<ref){digitalWrite(HEAT1, HIGH); Serial.println("heat1");}
    else {digitalWrite(HEAT1, LOW);}
    if (prum2<ref){digitalWrite(HEAT2, HIGH);}
    else {digitalWrite(HEAT2, LOW);}
  }
}
//---------------------------------------------------
void V_HUM() {
  int uroven = analogRead(HLADINA);
  int f_pump = 0;
  sht_hum = sht.getHumidity();
  if ((sht_hum<hum[3])and(uroven<800)) {      //dodej vodu
    f_pump = 1;
  }
  else if ((sht_hum>hum[3]+10)and(uroven>100)) {   //odebere vodu
    f_pump = -1;
  }
  else if ((sht_hum>hum[3]+20)and(uroven<50)) {    //ventilace
    f_pump = -2;
  }
  else {f_pump = 0;}

  if (f_pump == 1) {digitalWrite(IA2, HIGH);}
  else if (f_pump == -1) {digitalWrite(IB2, HIGH);}
  else if (f_pump == -2) {
    digitalWrite(VENT, HIGH);
    delay(10000);
  }
  else {
    digitalWrite(IA2, LOW);
    digitalWrite(IB2, LOW);  }
  
}
//---------------------------------------------------
void V_VENT() {
    float fanspeedd = vent[9] / 100.0;
    int c_vent = 0;
    if (f_vent == 1) {
      currentMillis_vendL = millis();
      c_vent = 1;
      if (currentMillis_vendL - startMillis_vendL>= vent[6]*period_vendL)
      {
        startMillis_vendL = currentMillis_vendL;
        f_vent = 0;
        c_vent = 0;
      }
    }
    if(c_vent == 1) {
      if (millis() - fan_pretime <= (100 - (100 * fanspeedd))) {
        digitalWrite (VENT, LOW);
      }
      else {
        digitalWrite (VENT, HIGH);
      }
      if (millis() - fan_pretime >= (100)) {
        fan_pretime = millis();
      }
    }
    else {digitalWrite (VENT, LOW);}
}
//---------------------------------------------------
void V_KRMENI() {
  digitalWrite(DIR, LOW);     //směr
  for(int u= 0; u<1800; u++)
  {
    digitalWrite(STEP,HIGH);
    delay(1);
    digitalWrite(STEP,LOW);
    delay(1);
  }
}
//---------------------------------------------------
void V_VODA() {
  digitalWrite(IA1, HIGH);    //jen voda tam
  delay(1000*voda[6]);
  digitalWrite(IA1, LOW);
}
//---------------------------------------------------
void V_sample() {
  DateTime now = rtc.now();               //print data
  int ye = now.year();
  int mo = now.month();
  int da = now.day();
  int ho = now.hour();
  int mi = now.minute();
  int sec = now.second();
  sht_temp = sht.getTemperature();
  sht_hum = sht.getHumidity();
  sensors.requestTemperatures();
  se1 = sensors.getTempC(sensor1);
  se2 = sensors.getTempC(sensor2);
  se3 = sensors.getTempC(sensor3);
  se4 = sensors.getTempC(sensor4);
  se5 = sensors.getTempC(sensor5);
  se6 = sensors.getTempC(sensor6);   
  File file = SPIFFS.open("/data.txt", FILE_APPEND);
  file.print(ye);
  file.print("/");
  file.print(mo);
  file.print("/");
  file.print(da);
  file.print("\t");
  file.print(ho);
  file.print(":");
  file.print(mi);
  file.print(":");
  file.print(sec);
  file.print("\t");
  file.print(sht_temp);
  file.print("\t");
  file.print(sht_hum);
  file.print("\t\t");
  file.print(se1);
  file.print("\t");
  file.print(se2);
  file.print("\t");
  file.print(se3);
  file.print("\t");
  file.print(se4);
  file.print("\t");
  file.print(se5);
  file.print("\t");
  file.print(se6);
  file.print("\t");
  file.print(se7);
  file.print("\n");
  file.close();
}
//*************************************************************************************************************   setup
void setup() {
  Serial.begin(19200);
  Wire.begin();                           // begin Wire(I2C)
  sensors.begin();                        //spuštění senzorů DS18B20
  lcd.init();
  lcd.backlight();
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  pinMode(pinCLK, INPUT);
  pinMode(pinDT, INPUT);
  pinMode(pinSW, INPUT_PULLUP);
  pinMode(HEAT1, OUTPUT);
  pinMode(HEAT2, OUTPUT);
  pinMode(VENT, OUTPUT);
  pinMode(STEP, OUTPUT);
  pinMode(DIR, OUTPUT);
  pinMode(HLADINA, INPUT);
  pinMode(IA1, OUTPUT);
  pinMode(IB1, OUTPUT);
  pinMode(IA2, OUTPUT);
  pinMode(IB2, OUTPUT);
  digitalWrite(HEAT1, LOW);
  digitalWrite(HEAT2, LOW);
  digitalWrite(VENT, LOW);
  digitalWrite(STEP, LOW);
  digitalWrite(DIR, LOW);
  digitalWrite(IA1, LOW);
  digitalWrite(IB1, LOW);
  digitalWrite(IA2, LOW);
  digitalWrite(IB2, LOW);
  
  stavPred = digitalRead(pinCLK);
  
  startMillis_heat = millis();
  startMillis_hum = millis();
  startMillis_sample = millis();
  startMillis_vendD = millis();
  startMillis_krmeni = millis();
  startMillis_vodaD = millis();
  startMillis_vodaL = millis();

  initialdata();
} 
//*************************************************************************************************************   loop
void loop() {
  serialcommunication();
  
  encoder();
  LCDscreen();
  if (digitalRead(S3) == HIGH) {
    //------------------------------------------------------ ok
    currentMillis_heat = millis();
    if ((currentMillis_heat - startMillis_heat>= period_heat)and(temp[0] == 1)){
      startMillis_heat = currentMillis_heat;
      V_heat();
    }
    //------------------------------------------------------ ok
    currentMillis_hum = millis();
    if ((currentMillis_hum - startMillis_hum>= period_hum)and(hum[0] == 1)) {
      startMillis_hum = currentMillis_hum;
      V_HUM();
    }
    //------------------------------------------------------ ok
    currentMillis_vendD = millis();
    if ((currentMillis_vendD - startMillis_vendD>= vent[3]*period_vendD)and(vent[0] == 1)){
      startMillis_vendD = currentMillis_vendD;
      f_vent = 1;
      startMillis_vendL = millis();
    }
    V_VENT();
    //------------------------------------------------------ 
    currentMillis_krmeni = millis();
    if ((currentMillis_krmeni - startMillis_krmeni>= krmeni[3]*period_krmeni)and(krmeni[0] == 1)){
      startMillis_krmeni = currentMillis_krmeni;
      V_KRMENI();
    }
    //------------------------------------------------------ ok
    currentMillis_vodaD = millis();
    if ((currentMillis_vodaD - startMillis_vodaD>= voda[3]*period_vodaD)and(voda[0] == 1)){
      startMillis_vodaD = currentMillis_vodaD;
      V_VODA();
    }
    //------------------------------------------------------ ok
    currentMillis_sample = millis();
    if ((currentMillis_sample - startMillis_sample>= sample[3]*period_sample)and(sample[0] == 1)){
      startMillis_sample = currentMillis_sample;
      V_sample();
    }
  }
    
}
//*************************************************************************************** ENCODER
void encoder() {
  stavCLK = digitalRead(pinCLK);
  
  if (stavCLK != stavPred) {
    if (digitalRead(pinDT) != stavCLK) {
      poziceEnkod ++;
      akt = 1;
    }
    else {
      poziceEnkod--;
      akt = 1;
    }
    if (nastav == 0) {
      if(poziceEnkod < 0) {poziceEnkod = 0;}
      if(poziceEnkod > 7) {poziceEnkod = 7;}
      poz_home = poziceEnkod;
    }
    else if (nastav == 1) {
      if(poziceEnkod < 0) {poziceEnkod = 0;}
      if(poziceEnkod > x) {poziceEnkod = x;}
      poz_menu = poziceEnkod;
    }
    else if (nastav == 2) {
      if(poziceEnkod < ymin) {poziceEnkod = ymin;}
      if(poziceEnkod > ymax) {poziceEnkod = ymax;}
      if (poz_home == 0) {temp[(poz_menu-1)*3] = poziceEnkod;}
      if (poz_home == 1) {hum[(poz_menu-1)*3] = poziceEnkod;}
      if (poz_home == 2) {vent[(poz_menu-1)*3] = poziceEnkod;}
      if (poz_home == 3) {krmeni[(poz_menu-1)*3] = poziceEnkod;}
      if (poz_home == 4) {voda[(poz_menu-1)*3] = poziceEnkod;}
      if (poz_home == 5) {sample[(poz_menu-1)*3] = poziceEnkod;}
      if (poz_home == 6) {wifi[(poz_menu-1)*3] = poziceEnkod;}      
    }
  }
  stavPred = stavCLK;
  stavSW = digitalRead(pinSW);
  if (stavSW == 0) {
    if (nastav == 0) {
      nastav = 1;
      poziceEnkod = 0;
    }
    else if ((nastav == 1)and(poz_menu == 0)) {
      nastav = 0;
      poziceEnkod = poz_home;
    }
    else if ((nastav == 1)and(poz_menu != 0)) {
      if (poz_home == 0){
        nastav = 2;
        poziceEnkod = temp[(poz_menu-1)*3];
        ymin = temp[((poz_menu-1)*3)+1];
        ymax = temp[((poz_menu-1)*3)+2];
      }
      if (poz_home == 1){
        nastav = 2;
        poziceEnkod = hum[(poz_menu-1)*3];
        ymin = hum[((poz_menu-1)*3)+1];
        ymax = hum[((poz_menu-1)*3)+2];
      }
      if (poz_home == 2){
        nastav = 2;
        poziceEnkod = vent[(poz_menu-1)*3];
        ymin = vent[((poz_menu-1)*3)+1];
        ymax = vent[((poz_menu-1)*3)+2];
      }
      if (poz_home == 3){
        nastav = 2;
        poziceEnkod = krmeni[(poz_menu-1)*3];
        ymin = krmeni[((poz_menu-1)*3)+1];
        ymax = krmeni[((poz_menu-1)*3)+2];
      }
      if (poz_home == 4){
        nastav = 2;
        poziceEnkod = voda[(poz_menu-1)*3];
        ymin = voda[((poz_menu-1)*3)+1];
        ymax = voda[((poz_menu-1)*3)+2];
      }
      if (poz_home == 5){
        nastav = 2;
        poziceEnkod = sample[(poz_menu-1)*3];
        ymin = sample[((poz_menu-1)*3)+1];
        ymax = sample[((poz_menu-1)*3)+2];
      }
      if (poz_home == 6){
        nastav = 2;
        poziceEnkod = wifi[(poz_menu-1)*3];
        ymin = wifi[((poz_menu-1)*3)+1];
        ymax = wifi[((poz_menu-1)*3)+2];
        if ((wifi[0]==1)and(poz_menu==2)) {
          Serial.println("!");
          }
        
      }
      if (poz_home == 7 ){
        if (poz_menu == 1) {Serial.println("hum ->");}
        else if (poz_menu == 2)  {Serial.println("hum <-");}
        else if (poz_menu == 3)  {Serial.println("tekut <-");}
        else if (poz_menu == 4)  {Serial.println("tekut ->");}
        else {Serial.println("all off");}
      }
    }
    else if (nastav == 2) {
      nastav = 1;
      poziceEnkod = poz_menu;
      if(poz_home != 7){savedata();}
    }
    akt = 1;
    delay(200);
  }
}

//*************************************************************************************** LCDscreen
void LCDscreen() {
  if (akt == 1 ) {
    lcd.clear();
    //********************************* zakladni menu
    if (nastav == 0) {
      lcd.setCursor(0,0);
      lcd.print(type[poz_home]);
      lcd.setCursor(13,0);
      lcd.print("Str: /");
      lcd.setCursor(17,0);
      lcd.print(poz_home + 1);
      lcd.setCursor(19,0);
      lcd.print(8);
      if (poz_home == 0) { // Teplota 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(temp[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("AKT:  ");
        lcd.print("na.na");
        lcd.print(" 'C");
        lcd.setCursor(1,3);
        lcd.print("NAST: ");
        lcd.print(temp[3]);
        lcd.print(" 'C");
        x = 2;
      }
      if (poz_home == 1) { // Vlhkost 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(hum[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("AKT:  ");
        lcd.print("na.na");
        lcd.print(" %RH");
        lcd.setCursor(1,3);
        lcd.print("NAST: ");
        lcd.print(hum[3]);
        lcd.print(" %RH");
        x = 2;
      }
      if (poz_home == 2) { // Ventilace 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(vent[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(vent[3]);
        lcd.print(" hod");
        lcd.setCursor(1,3);
        lcd.print("L ");
        lcd.print(vent[6]);
        lcd.print(" s,");
        lcd.setCursor(11,3);
        lcd.print("P ");
        lcd.print(vent[9]);
        lcd.print(" %");
        x = 4;
      }
      if (poz_home == 3) { // Krmeni 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(krmeni[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(krmeni[3]);
        lcd.print(" hod");
        lcd.setCursor(1,3);
        lcd.print("DAVKA ");
        lcd.print(krmeni[6]);
        x = 3;
      }
      if (poz_home == 4) { // Tekutiny 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(voda[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(voda[3]);
        lcd.print(" hod");
        lcd.setCursor(1,3);
        lcd.print("DAVKA ");
        lcd.print(voda[6]);
        lcd.print(" x10 ml");
        x = 3;
      }
      if (poz_home == 5) { // Vzorkovani 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(sample[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(sample[3]);
        lcd.print(" min");
        x = 2;
      }
      if (poz_home == 6) { // WIFI
        lcd.setCursor(1,1); 
        lcd.print("Stav:");
        if(wifi[0] == 0) {
          lcd.setCursor(6,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(6,1);
          lcd.print("ON");
          lcd.setCursor(1,2);
        }
        x = 1;
      }
      if (poz_home == 7) { // Cerpadla
        x = 4;
      }
    }
    //********************************** nastaveni
    if ((nastav == 1)or(nastav == 2)) {
      if (poz_home == 2) {
        if (poz_menu == 4) {lcd.setCursor(10,3);}
        else {lcd.setCursor(0,poz_menu);}
        lcd.print("[");
      }
      else if (poz_home == 7) {
        if (poz_menu == 1) {lcd.setCursor(0,2);}
        if (poz_menu == 2) {lcd.setCursor(0,3);}
        if (poz_menu == 3) {lcd.setCursor(8,2);}
        if (poz_menu == 4) {lcd.setCursor(8,3);}
        lcd.print("[");
      }
      else {
        lcd.setCursor(0,poz_menu);
        lcd.print("[");
      }
      lcd.setCursor(1,0);
      lcd.print("<-  ");
      lcd.print(type[poz_home]);
      if (poz_home == 0) { // Teplota 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(temp[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("NAST: ");
        lcd.print(temp[3]);
        lcd.print(" 'C");
        x = 2;
      }
      if (poz_home == 1) { // Vlhkost 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(hum[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("NAST: ");
        lcd.print(hum[3]);
        lcd.print(" %RH");
        x = 2;
      }
      if (poz_home == 2) { // Ventilace 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(vent[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(vent[3]);
        lcd.print(" hod");
        lcd.setCursor(1,3);
        lcd.print("L ");
        lcd.print(vent[6]);
        lcd.print(" s,");
        lcd.setCursor(11,3);
        lcd.print("P ");
        lcd.print(vent[9]);
        lcd.print(" %");
        x = 4;
      }
      if (poz_home == 3) { // Krmeni 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(krmeni[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(krmeni[3]);
        lcd.print(" hod");
        lcd.setCursor(1,3);
        lcd.print("DAVKA ");
        lcd.print(krmeni[6]);
        x = 3;
      }
      if (poz_home == 4) { // Tekutiny 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(voda[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(voda[3]);
        lcd.print(" hod");
        lcd.setCursor(1,3);
        lcd.print("DAVKA ");
        lcd.print(voda[6]);
        lcd.print(" x10 ml");
        x = 3;
      }
      if (poz_home == 5) { // Vzorkovani 
        lcd.setCursor(1,1);
        lcd.print("Stav regulace:");
        if(sample[0] == 0) {
          lcd.setCursor(15,1);
          lcd.print("OFF");
        }
        else {
          lcd.setCursor(15,1);
          lcd.print("ON");
        }
        lcd.setCursor(1,2);
        lcd.print("INTERVAL:  ");
        lcd.print(sample[3]);
        lcd.print(" min");
        x = 2;
      }
      if (poz_home == 6) { // WIFI
        lcd.setCursor(1,1); 
        lcd.print("Stav:");
        if(wifi[0] == 0) {
          lcd.setCursor(6,1);
          lcd.print("OFF");
          n=0;
          x = 1;
        }
        else {
          lcd.setCursor(6,1);
          lcd.print("ON");
          lcd.setCursor(1,2);
          lcd.print("Pripojit");
          x = 2;
        }
        
      }
      if (poz_home == 7) { // Cerpadla
        lcd.setCursor(1,1); 
        lcd.print("HUM");
        lcd.setCursor(9,1); 
        lcd.print("TEKUTINY");
        lcd.setCursor(1,2); 
        lcd.print("IN");
        lcd.setCursor(1,3); 
        lcd.print("OUT");
        lcd.setCursor(9,2); 
        lcd.print("IN");
        lcd.setCursor(9,3); 
        lcd.print("OUT");
        x = 4;
      }

      
    }
  }
  akt = 0;
}
