//08:3A:F2:A7:80:6C //esp32 желтые ноги
//08:3A:F2:66:31:30 //esp32 lilygo2,3
//08:3A:F2: //esp32 lilygo4,7
//EC:94:CB:6C:EC:A4  esp32 самоделка

#define LILYGO_T5_V213
#define Threshold 40 /* чем больше это значение,  тем выше чувствительность сенсора */

#include <Arduino.h>            // In-built
#include <esp_task_wdt.h>       // In-built
#include "esp_adc_cal.h"        // In-built
#include <GxEPD.h>
#include <boards.h>
#include <GxDEPG0213BN/GxDEPG0213BN.h>    // 2.13" b/w  form DKE GROUP
#include GxEPD_BitmapExamples
// FreeFonts from Adafruit_GFX
#include <Fonts/FreeMonoBold9pt7b.h>
#include <Fonts/FreeMonoBold12pt7b.h>
#include <Fonts/FreeMonoBold18pt7b.h>
#include <Fonts/FreeMonoBold24pt7b.h>
#include "font_prazo_24.h"
#include <GxIO/GxIO_SPI/GxIO_SPI.h>
#include <GxIO/GxIO.h>
#include "im1.h"

#include <ArduinoJson.h>        // https://github.com/bblanchon/ArduinoJson
#include <HTTPClient.h>         // In-built
#include <time.h>               // In-built
#include <esp_now.h>
#include <esp_wifi.h>
#include <WiFi.h>
#include "owm_credentials.h"//NTP+OPENWEATHER
#include "NTPClient.h"
#include "WiFiUdp.h"
#include <UnixTime.h>
UnixTime stamp(0);  // указать GMT (3 для Москвы)
//#include <SD.h>
//#include <FS.h>
GxIO_Class io(SPI,  EPD_CS, EPD_DC,  EPD_RSET);
GxEPD_Class display(io, EPD_RSET, EPD_BUSY);
#include <Wire.h>
#include "Adafruit_HTU21DF.h"
Adafruit_HTU21DF htu = Adafruit_HTU21DF();
//**********************************************************************************
#define BOARD_ID 1

uint8_t broadcastAddress1[] = {0x8, 0x3A, 0xF2, 0xA7, 0x80, 0x6C};
uint8_t broadcastAddress2[] = {0xEC, 0x94, 0xCB, 0x6C, 0xEC, 0xA4};
typedef struct struct_message {
    int id;
    float temp;
    float hum;
    int readingId;
} struct_message;
struct_message myData;
unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 10000;        // Interval at which to publish sensor readings
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
unsigned int readingId = 0;

// Insert your SSID
constexpr char WIFI_SSID[] = "VOVA-47";
 esp_now_peer_info_t peerInfo;
//*****************************************************************************
String  Time_str = "--:--:--";
String  Date_str = "-- --- ----";
int     wifi_signal, CurrentHour = 0, CurrentMin = 0, CurrentSec = 0, EventCnt = 0, vref = 1100;
//Day of the week
const char* weekday_D[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
int mon = 1; //Month
int date = 1;
int dow = 6;
int years = 2022;
int volt = 0;
int temp;
//int tempmax;
//int tempmin;
int hum;
RTC_DATA_ATTR int tempmax = 300;//несбрасываемые в режиме сна переменная
RTC_DATA_ATTR int tempmin = 270;
boolean zntemp = 1;//1+,0-
RTC_DATA_ATTR boolean znmin = 1;
RTC_DATA_ATTR boolean znmax = 0;
RTC_DATA_ATTR int tik = 1;//такты по 20мин до полного обновления
RTC_DATA_ATTR int tMin = 0;//минуты
RTC_DATA_ATTR int tHour = 0;//часы
RTC_DATA_ATTR int tax = 0;//время макс темп
RTC_DATA_ATTR int tin = 0;//время мин темп

int sen =0;
bool now1=0;
boolean ntp=0;//флаг соед с нтп
const char* month_M[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
long SleepDuration   = 20; // сон в минутах Sleep time in minutes, aligned to the nearest minute boundary, so if 30 will always update at 00 or 30 past the hour
int  WakeupHour      = 8;  // Don't wakeup until after 07:00 to save battery power
int  SleepHour       = 23; // Sleep after 23:00 to save battery power
long StartTime       = 0;
long SleepTimer      = 0;
long Delta           = 10; // ESP32 rtc speed compensation, prevents display at xx:59:yy and then xx:00:yy (one minute later) to save power

bool dattemp=1;

void setup()
{
  
  Serial.begin(115200);
  while (!Serial);
  // delay(1000);
  StartTime = millis();
 // Serial.println();
  Serial.println("setup");
//pinMode(22, OUTPUT);
  // print_GPIO_wake_up();


 print_wakeup_touchpad();
 //  Serial.print("sen2=");
//  Serial.println(sen);
 print_wakeup_reason();
 // timeClient.begin();
  // Set offset time in seconds to adjust for your timezone, for example:
  // GMT +1 = 3600
  // GMT +8 = 28800
  // GMT -1 = -3600
  // GMT 0 = 0
  timeClient.setTimeOffset(10800);  

  
  SPI.begin(EPD_SCLK, EPD_MISO, EPD_MOSI);
    
  display.init();

 display.cp437(true);
  if (!htu.begin()) {
    Serial.println("Couldn't find sensor!");
    dattemp=0;
   // while (1);
  }

}
void loop()
{
   Serial.println (sen);
  if (tik == 1 || tik > 3)
  { 
   if(StartWiFi())
    {tik = 1;
     ntpTime();
    }
    StopWiFi();
  }
  else {now1=1;
        int tims = SleepDuration;
         tims=20;
     if(tik==0)
      {tims=1;
       tik = 1;
      }
    
       tMin = tMin + tims;
      if(tMin>59)
      {tMin=tMin-60;
      tHour=tHour+1;
      if(tHour>23){tHour=0;}
       }
       
  }

  ++tik;
if(dattemp==1)htu21();

if(now1<1)Now();// передача данных между несколькими esp32 esp8266 в одной WiFi сети
 
 if((tHour==0)&&(tMin<20))
 {
  tempmax = 300;//обнуление суточных данных
 tempmin = 270;
 znmin = 1;//+
 znmax = 0;//-
 }
  
if(sen==7)
{
 Kalendar();  
  BeginSleep();
}

if(sen==9)
{
GxepdPage1();//data time
}


  // GxepdPage1();
  GxepdPage2();//termometr
 // Touch();

 
  
 //sen = 0;
  BeginSleep();
}
