Guru Meditation Error: Core 0 panic'ed (Interrupt wdt timeout on CPU0)

my code

#include<Arduino.h>
#include "driver/uart.h"
#include <esp_task_wdt.h>
//#include "soc/timer_group_struct.h"
//#include "soc/timer_group_reg.h"
#include <AT24Cxx.h>
#include <MCP3XXX.h>
#include "soc/rtc.h"
#include<SPI.h>
#include <SD.h>
#include <ESP32Time.h>
#include <stdio.h>
#include <MCP342x.h>
#include "MAX17048.h"
#include<ArduinoJson.h>
#include<Wire.h>
#include<FS.h>
#include<String.h>
#include<SparkFunSX1509.h>
#include "Adafruit_SHTC3.h"
#include <Adafruit_Sensor.h>
#include <WiFi.h>
#include <ESP32WebServer.h>
#include "FS.h"
#include "SPIFFS.h"
#include "CSS.h"
#define ServerVersion "1.0"
#define i2c_address 0x50
#define FORMAT_SPIFFS_IF_FAILED true
#define ServerVersion "1.0"
#define pwrkey 4
#define NUMERO_PORTA_SERIALE UART_NUM_2
#define BUF_SIZE (1024 * 4)
#define RD_BUF_SIZE (1024)
#define U2RXD 16
#define U2TXD 17
String webpage = "";
String etyp;
int sts;
ESP32WebServer server(80);
AT24Cxx eep(i2c_address, 512);
File myFile;
MCP3004 ads;
hw_timer_t *My_timer = NULL;
static const BaseType_t pro_cpu = 0;
static const BaseType_t app_cpu = 1;
MAX17048 pwr_mgmt;
uint8_t addres = 0x68;
bool SPIFFS_present = false;
MCP342x adc = MCP342x(addres);
const byte SX1509_ADDRESS = 0x3E;
SX1509 io;
ESP32Time rtc(19800);
Adafruit_SHTC3 shtc3 = Adafruit_SHTC3();
const byte SX1509_LED_PIN1 = 13;
const byte SX1509_LED_PIN2 = 14;
const byte SX1509_LED_PIN3 = 15;
static const uint32_t taskDelay = 0;
static QueueHandle_t data_queue;
static QueueHandle_t device_id_queue;
static QueueHandle_t volt_queue1;
static QueueHandle_t volt_queue2;
static QueueHandle_t volt_queue3;
static QueueHandle_t current_queue1;
static QueueHandle_t current_queue2;
static QueueHandle_t current_queue3;
static QueueHandle_t temp_queue1;
static QueueHandle_t temp_queue2;
static QueueHandle_t slot_queue1;
static QueueHandle_t slot_queue2;
static QueueHandle_t command_queue;
static QueueHandle_t uart2_queue;
static const char * TAG = "";
uint8_t rxbuf[256];     //Buffer di ricezione
uint16_t rx_fifo_len;        //Lunghezza dati
uint16_t num=0;
typedef struct Message{
  char body[20];
  int count;
}Message;
float fcg_L1V_high, fcg_L1V_low, fcg_L2V_high, fcg_L2V_low, fcg_L3V_high, fcg_L3V_low,fcg_L1C_high, fcg_L2C_high, fcg_L3C_high, fcg_L1C_LOW, fcg_L2C_LOW, fcg_L3C_LOW;
typedef struct Message1{
  char body1[60];
  String count;
}Message1;
int motor;
int sched_id;
String bcg_schedule_id1,startsrc;
long int count1;
char configu[3000];
 void readFile2(fs::FS & fs,
  const char * path) {
  Serial.printf("Reading file: %s\r\n", path);

  File file = fs.open(path);
  if (!file || file.isDirectory()) {
    Serial.println("- failed to open file for reading");
    return;
  }
  int l;
  Serial.println("- read from file:");
  while (file.available()) {
    configu[l++] = file.read();
  }
  configu[l] = '\0';
  l = 0;
//  Serial.print(configu);
  file.close();
}
/*readFile*/
void readFile(fs::FS & fs,
  const char * path) {
  char json[3000];
  Serial.printf("Reading file: %s\r\n", path);

  File file = fs.open(path);
  if (!file || file.isDirectory()) {
    Serial.println("- failed to open file for reading");
    return;
  }
  int i;
  Serial.println("- read from file:");
  while (file.available()) {
    json[i++] = file.read();
  }
  json[i] = '\0';
  i = 0;
  
uart_write_bytes(UART_NUM_2,json, strlen(json));
  file.close();
}
/*on timer*/
void IRAM_ATTR onTimer(){
count1++;
}
/*uart task*/
 static void UART_ISR_ROUTINE(void *parameters)
{
    uart_event_t event;
    size_t buffered_size;
    bool exit_condition = false;
    char data1[2048];
    char data2[2048];
    char buf11[100];
   memset(data1, '\0', sizeof(data1));
   memset(data2, '\0', sizeof(data2));
   memset(buf11, '\0', sizeof(buf11));
    //Infinite loop to run main bulk of task
    while (1) {
      esp_task_wdt_init(30, false);
     int flagX=0;
        //Loop will continually block (i.e. wait) on event messages from the event queue
  if(xQueueReceive(uart2_queue, (void * )&event,(portTickType)portMAX_DELAY)) {

         
//            //Handle received event
  if (event.type == UART_DATA) {
  uint8_t UART2_data[2000];
  static const int RX_BUF_SIZE = 1024;//321 byte need to be received at atime 
  int UART2_data_length = 0; //data length 
  ESP_ERROR_CHECK(uart_get_buffered_data_len(UART_NUM_2, (size_t*)&UART2_data_length));

// try to read 321 at once in upto 100 ticks
  UART2_data_length = uart_read_bytes(UART_NUM_2, UART2_data, RX_BUF_SIZE, 100);
for(int i=0; i<UART2_data_length;i++) 
data1[i]=((char)UART2_data[i]);
}
            //Handle frame error event
            else if (event.type == UART_FRAME_ERR) {
                //TODO...
            }
           
            //Keep adding else if statements for each UART event you want to support
            //else if (event.type == OTHER EVENT) {
                //TODO...
            //}
           
           
            //Final else statement to act as a default case
            else {
                //TODO...
            }      
        }
       
        //If you want to break out of the loop due to certain conditions, set exit condition to true
        if (exit_condition) {
            break;
        }
        int flagC = 0; 
            Serial.println(data1);
                        for(int m=0;m<strlen(data1);m++){
if((data1[m]=='+')&&(data1[m+1]=='Q')&&(data1[m+2]=='L')&&(data1[m+3]=='T')&&(data1[m+4]=='S')){
if (strlen(data1) - 1 > 25) {
     memcpy(buf11,data1,sizeof(data1));
    flagX = 1;
  }
  }
}
for(int j=0;j<strlen(data1);j++){
if((data1[j]=='+')&&(data1[j+1]=='Q')&&(data1[j+2]=='M')&&(data1[j+3]=='T')&&(data1[j+4]=='R')&&(data1[j+5]=='E')&&(data1[j+6]=='C')&&(data1[j+7]=='V')){
        Serial.println("+QMTRCEV matched");
        int k=0;
               while(data1[k] != '{') {
          k++;
        }
        int f;
        if(data1[k] == '{'){
          for(f=0;f<strlen(data1);f++){
          data2[f] = data1[k];
          k++;
        }
        data2[f]='\0';
        f=0;
        }
        Serial.println("split data print");
        Serial.print(data2);
        flagC = 1;
    }
}
         if(flagC==1) {
        StaticJsonDocument < 1000 > doc;
        DeserializationError error = deserializeJson(doc,data2 );
        serializeJsonPretty(doc, Serial);
        Serial.println();
        int command = doc["command_session"];
        if (!(command == NULL)) {
          xQueueOverwrite(command_queue, & command);
        }
        int device = doc["device_client_id"];
        if (!(device == NULL)) {
          xQueueOverwrite(device_id_queue, & device);
        }
        String Location = doc["Location"];
        String FarmId = doc["FarmId"];
        String Region = doc["Region"];
        String fcg_first_confg = doc["fcg_first_confg"];
        float fcg_motor_capacity_hp = doc["fcg_motor_capacity_hp"];
        String fcg_motor_type_phase = doc["fcg_motor_type_phase"];
        String fcg_starter_type = doc["fcg_starter_type"];
        long int fcg_max_motor_runTime = doc["fcg_max_motor_runTime"];
        String fcg_single_phase_protect = doc["fcg_single_phase_protect"];
        String fcg_voltage_protection = doc["fcg_voltage_protection"];
        String fcg_track_manual_trigger = doc["fcg_track_manual_trigger"];
        float L1V_high = doc["fcg_L1V_high"];
        if (!(L1V_high == NULL)) {
          fcg_L1V_high=L1V_high;
        }
        float L1V_low = doc["fcg_L1V_low"];
        if (!(L1V_low == NULL)) {
          fcg_L1V_low=L1V_low;
        }
        float L1C_high = doc["fcg_L1C_high"];
        if (!(L1C_high == NULL)) {
          fcg_L1C_high=L1C_high;
        }
        float L1C_LOW = doc["fcg_L1C_LOW"];
        if (!(L1C_LOW == NULL)) {
          fcg_L1C_LOW=L1C_LOW;
        }
        float L2V_high = doc["fcg_L2V_high"];
        if (!(L2V_high == NULL)) {
          fcg_L2V_high=L2V_high;
        }
        
        float L2V_low = doc["fcg_L2V_low"];
        if (!(L2V_low == NULL)) {
          fcg_L2V_low=L2V_low;
        }
        float L2C_high = doc["fcg_L2C_high"];
        if (!(L2C_high == NULL)) {
          fcg_L2C_high=L2C_high;
        }
        float L2C_LOW = doc["fcg_L2C_LOW"];
        if (!(L2C_LOW == NULL)) {
          fcg_L2C_LOW=L2C_LOW;
        }
        float L3V_high = doc["fcg_L3V_high"];
        if (!(L3V_high == NULL)) {
          fcg_L3V_high=L3V_high;
        }
        float L3V_low = doc["fcg_L3V_low"];
        if (!(L3V_low == NULL)) {
          fcg_L3V_low=L3V_low;
        }
        float L3C_high = doc["fcg_L3C_high"];
        if (!(L3C_high == NULL)) {
          fcg_L3C_high=L3C_high;
        }
        float L3C_LOW = doc["fcg_L3C_LOW"];
        if (!(L3C_LOW == NULL)) {
          fcg_L3C_LOW=L3C_LOW;
        }
        
       float bcg_schedule_id = doc["bcg_schedule_id"];
        Serial.print("bcg_schedule_id");
        Serial.println(bcg_schedule_id);
        if (!(bcg_schedule_id == NULL)) {
          sched_id=bcg_schedule_id;
        }
        long int bcg_schedule_runTime_hrs = doc["bcg_schedule_runTime_hrs"];
        int slot_begin = doc["bcg_schedule_slot_begin"];
        if (!(slot_begin == NULL)) {
          xQueueOverwrite(slot_queue2, & slot_begin);
        }
        int slot_end = doc["bcg_schedule_slot_end"];
        if (!(slot_end == NULL)) {
          xQueueOverwrite(slot_queue1, & slot_end);
        }
        int bcg_schedule_frequency = doc["bcg_schedule_frequency"];
        String bcg_schedule_sts = doc["bcg_schedule_sts"];
        String bcg_schedule_switch = doc["bcg_schedule_switch"];
        String bcg_manual_switch_in_app = doc["bcg_manual_switch_in_app"];
        byte cg_wifissid = doc["cg_wifissid"];
        byte cg_wifipass = doc["cg_wifipass"];
        int motorcon = doc["motor"];
        if(!(motorcon==NULL)){
        motor=motorcon;
        }
      }
    if (flagX == 1) {
    char * tmpbuf;
    char * tmpbufi;
    tmpbufi = strtok(buf11, ":");
    char * y;
    y = strtok(NULL, "/");
    y = y + 2;
    int z = atoi(y);
    z = z + 2000;
    tmpbuf = strtok(NULL, "/");
    int b = atoi(tmpbuf);
    tmpbuf = strtok(NULL, ",");
    int c = atoi(tmpbuf);
    tmpbuf = strtok(NULL, ":");
    int i1 = atoi(tmpbuf);
    tmpbuf = strtok(NULL, ":");
    int i2 = atoi(tmpbuf);
    tmpbuf = strtok(NULL, "+");
    int i3 = atoi(tmpbuf);
    rtc.setTime(i3, i2, i1, c, b, z);
  
  Serial.println(rtc.getTime("%A, %B %d %Y %H:%M:%S"));
  struct tm timeinfo = rtc.getTimeStruct();
    }

        memset(buf11, '\0', sizeof(buf11));
        memset(data1, '\0', sizeof(data1));
        memset(data2, '\0', sizeof(data2));
//    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 1;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 1;
//    TIMERG1.wdt_wprotect = 0;
esp_task_wdt_reset();
disableLoopWDT();

feedLoopWDT();
    vTaskDelay(1);
//    vTaskDelay(10 / portTICK_PERIOD_MS);
    }
   Serial.printf("esp_task_wdt_delete: %d\n\n", esp_task_wdt_delete(NULL));
    //Out side of loop now. Task needs to clean up and self terminate before returning
    vTaskDelete(NULL);
}
/*preading*/
void preading(void * parameters) {
  int16_t adc1, adc2, adc3;
  long value1 = 0;
  long value2 = 0;
  long value3 = 0;
  float VRMS1, VRMS2, VRMS3, AmpsRMS1, AmpsRMS2, L1C, L2C, L3C, AmpsRMS3, voltage1, voltage2, voltage3,
  ANI0, ANI1, ANI2, volt1, volt2, volt3, tempareture, humudityper,bvoltage, bpercentage;
  int deviceaddress = 0x44;
  int slotend, slotbegin;
  int flagA = 0;
  unsigned int eeaddress = 0x50;
  byte data = 00;
  byte rdata = 0xFF;
  char a;
  int flagz = 0;
  sensors_event_t event, temp, humidity;
  while (1) {
vTaskDelay(1);
disableLoopWDT();
esp_task_wdt_init(30, false);
feedLoopWDT();
    int flagB = 0;
    ANI0 = (ads.analogRead(0));
    ANI1 = (ads.analogRead(1));
    ANI2 = (ads.analogRead(2));
    volt1 = ((ANI0 / 1023) * 3.3);
    volt2 = ((ANI1 / 1023) * 3.3);
    volt3 = ((ANI2 / 1023) * 3.3);
    volt1 = volt1 * 209;
    volt2 = volt2 * 229;
    volt3 = volt3 * 229;
//    Serial.println("Step1");
    if ((volt1 == 0) || (volt2 == 0) || (volt3 == 0)) {
      flagB = 1;
    }
    if ((bvoltage < 3.5) && (flagB == 1)) {
      sts = 0;
    }
    if ((flagB == 0)) {
      sts = 1;
    }
//        Serial.println("Step2");

//    Serial.print("fcg_L1V_high");
//    Serial.println(fcg_L1V_high);
//    Serial.print("fcg_L2V_high");
//    Serial.println(fcg_L2V_high);
//    Serial.print("fcg_L3V_high");
//    Serial.println(fcg_L3V_high);
//    Serial.print("fcg_LV_low");
//    Serial.println(fcg_L2V_low);
//    Serial.print("fcg_L2V_low");
//    Serial.println(fcg_L2V_low);
//    Serial.print("fcg_L3V_low");
//    Serial.println(fcg_L3V_low);
    MCP342x::Config status;
    uint8_t err1 = adc.convertAndRead(MCP342x::channel1, MCP342x::continous,
      MCP342x::resolution16, MCP342x::gain4,
      10000, value1, status);
    uint8_t err2 = adc.convertAndRead(MCP342x::channel2, MCP342x::continous,
      MCP342x::resolution16, MCP342x::gain4,
      10000, value2, status);
    uint8_t err3 = adc.convertAndRead(MCP342x::channel3, MCP342x::continous,
      MCP342x::resolution16, MCP342x::gain4 ,
      10000, value3, status);
          Serial.println("Step3");

    voltage1 = abs(voltage1 = (float) value1);
    voltage2 = abs(voltage2 = (float) value2);
    voltage3 = abs(voltage3 = (float) value3);
    VRMS1 = (voltage1 / 2.0) * 0.707;
    VRMS2 = (voltage2 / 2.0) * 0.707;
    VRMS3 = (voltage3 / 2.0) * 0.707;
    AmpsRMS1 = VRMS1 / 30;
    AmpsRMS2 = VRMS2 / 30;
    AmpsRMS3 = VRMS3 / 30;
    AmpsRMS1 = AmpsRMS1 + 25.30;
    AmpsRMS2 = AmpsRMS2 + 25.30;
    AmpsRMS3 = AmpsRMS3 + 25.30;
//    Serial.print("fcg_L1C_high");
//    Serial.println(fcg_L1C_high);
//    Serial.print("fcg_L2C_high");
//    Serial.println(fcg_L2C_high);
//    Serial.print("fcg_L3C_high");
//    Serial.println(fcg_L3C_high);
//    Serial.print("fcg_L1C_LOW");
//    Serial.println(fcg_L1C_LOW);
//    Serial.print("fcg_L2C_LOW");
//    Serial.println(fcg_L2C_LOW);
//    Serial.print("fcg_L3C_LOW");
//    Serial.println(fcg_L3C_LOW);
//             Serial.println("Step4");

//    shtc3.getEvent( & humidity, & temp);
//    tempareture = temp.temperature;
//    humudityper = humidity.relative_humidity;
//              Serial.println("Step5");

//    if(volt1>150){
//    io.pinMode(SX1509_LED_PIN1, OUTPUT);
//    }
//    else{
//      io.pinMode(SX1509_LED_PIN1, LOW);
//    }
//    if(volt2>150){
//    io.pinMode(SX1509_LED_PIN2, OUTPUT);
//    }
//    else{
//      io.pinMode(SX1509_LED_PIN2, LOW);
//    }
//    if(volt3>150){
//    io.pinMode(SX1509_LED_PIN3, OUTPUT);
//    }
//    else{
//      io.pinMode(SX1509_LED_PIN3, LOW);
//    }
//    io.blink(SX1509_LED_PIN1, 1000, 0);
//    io.blink(SX1509_LED_PIN2, 1000, 0);
//    io.blink(SX1509_LED_PIN3, 1000, 0);
//          Serial.println("Step6");

    bpercentage = (pwr_mgmt.accuratePercent());
    bvoltage = (pwr_mgmt.voltage());
//              Serial.println("Step7");

    if (((fcg_L1V_high > volt1) && (volt1 > fcg_L1V_low) && (fcg_L2V_high > volt2) && (volt2 > fcg_L2V_low) && (fcg_L3V_high > volt3) && (volt3 > fcg_L3V_low) &&
        (fcg_L1C_high > AmpsRMS1) && (AmpsRMS1 > fcg_L1C_LOW) && (fcg_L2C_high > AmpsRMS2) && (AmpsRMS2 > fcg_L2C_LOW) && (fcg_L3C_high > AmpsRMS3) && (AmpsRMS3 > fcg_L3C_LOW))) {
      flagz = 0;

      etyp = "T";
    }
//              Serial.println("Step8");

    if (!((fcg_L1V_high > volt1) && (volt1 > fcg_L1V_low) && (fcg_L2V_high > volt2) && (volt2 > fcg_L2V_low) && (fcg_L3V_high > volt3) && (volt3 > fcg_L3V_low) &&
        (fcg_L1C_high > AmpsRMS1) && (AmpsRMS1 > fcg_L1C_LOW) && (fcg_L2C_high > AmpsRMS2) && (AmpsRMS2 > fcg_L2C_LOW) && (fcg_L3C_high > AmpsRMS3) && (AmpsRMS3 > fcg_L3C_LOW))) {
      flagz = 1;
    }

    if (flagz == 1) {
      
      etyp = "C";
      startsrc = "OFF";
      
    }
//          Serial.println("Step9");

    if ((motor == 1) && (flagz == 0)) {
      digitalWrite(25, HIGH);
      digitalWrite(26, HIGH);
      startsrc = "App";
      flagA = 0;
    }
            Serial.print("sched_id:");
        Serial.println(sched_id);
                Serial.print("motor:");
        Serial.println(motor);
//                  Serial.println("Step10");

    if ((sched_id > 3) && (motor!=1) && (flagz == 0)) {
      String a;
      xQueueReceive(slot_queue1, & slotend, 0);
      xQueueReceive(slot_queue2, & slotbegin, 0);
      String s;
      s = rtc.getTime();
      String b = (s.substring(0, 2));
      String c = (s.substring(3, 5));
      String d = (s.substring(6, 8));
      int i1 = b.toInt();
      int i2 = c.toInt();
      int i3 = d.toInt();
      int Time = ((i1 * 3600) + (i2 * 60) + i3 + 19800);
        Serial.print("Time:");
        Serial.println(Time);
        Serial.print("slotbegin:");
        Serial.println(slotbegin);
        Serial.print("slotend:");
        Serial.println(slotend);
      if ((slotend > Time) && (Time > slotbegin)) {
        digitalWrite(25, HIGH);
        digitalWrite(26, HIGH);
        startsrc = "bcg_schedule";
        flagA = 0;
      }
    }
//              Serial.println("Step11");

    if ((sched_id < 3) && (motor!=1) && (AmpsRMS1 > 0.00) && (AmpsRMS2 > 0.00) && (AmpsRMS3 > 0.00)) {
      startsrc = "ControlPanel";
    }
    if (((sched_id < 3) || (motor!=1))&&(flagA = 0)) {
      digitalWrite(25, LOW);
      digitalWrite(26, LOW);
      flagA = 1;
      startsrc="OFF";
    }
//              Serial.println("Step12");

    String dataString = "";
    dataString += String("Reading:-");
    dataString += String("L1V:");
    dataString += String(volt1);
    dataString += String("V");
    dataString += String("   ");
    dataString += String("L2V:");
    dataString += String(volt2);
    dataString += String("V");
    dataString += String("   ");
    dataString += String("L3V:");
    dataString += String(volt3);
    dataString += String("V");
    dataString += String("   ");
    dataString += String("L1C:");
    dataString += String(AmpsRMS1);
    dataString += String("A");
    dataString += String("   ");
    dataString += String("L2C:");
    dataString += String(AmpsRMS2);
    dataString += String("A");
    dataString += String("   ");
    dataString += String("L3C:");
    dataString += String(AmpsRMS3);
    dataString += String("A");
    dataString += String("   ");
    dataString += String("Tempareture:");
    dataString += String(tempareture);
    dataString += String("degrees C");
    dataString += String("   ");
    dataString += String("humidity:");
    dataString += String(humudityper);
    dataString += String("% rH");
    dataString += String("   ");
    dataString += String("Batteryvoltage:");
    dataString += String(bvoltage);
    dataString += String("V");
    dataString += String("   ");
    dataString += String("batteryLevel:");
    dataString += String(bpercentage);
    dataString += String("%");
//          Serial.println("Step13");

    xQueueOverwrite(volt_queue1, & volt1);
    xQueueOverwrite(volt_queue2, & volt2);
    xQueueOverwrite(volt_queue3, & volt3);
    xQueueOverwrite(current_queue1, & AmpsRMS1);
    xQueueOverwrite(current_queue2, & AmpsRMS2);
    xQueueOverwrite(current_queue3, & AmpsRMS3);
//    xQueueOverwrite(temp_queue1, & tempareture);
//    xQueueOverwrite(temp_queue2, & humudityper);
    bcg_schedule_id1 = String(sched_id);
    xQueueOverwrite(data_queue, & dataString);
//              Serial.println("Step14");

    //    esp_task_wdt_reset();
//    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 1;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 1;
//    TIMERG1.wdt_wprotect = 0;
    vTaskDelay(10);
    esp_task_wdt_reset();
  }
  vTaskDelete(NULL);
    Serial.printf("esp_task_wdt_delete: %d\n\n", esp_task_wdt_delete(NULL));

}

/* sdstoring*/
void sdstoring(void * parameters) {
  String dataString;
  while (1) {
    esp_task_wdt_init(30, false);
    xQueueReceive(data_queue, & dataString, 0);
    File myFile = SD.open("/data.txt", FILE_APPEND);
    myFile.println(dataString);
    myFile.close();
    
disableLoopWDT();

feedLoopWDT();
//    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 1;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 1;
//    TIMERG1.wdt_wprotect = 0;
    vTaskDelay(10);
    
//    vTaskDelay(10 / portTICK_PERIOD_MS);
esp_task_wdt_reset();
  }
  Serial.printf("esp_task_wdt_delete: %d\n\n", esp_task_wdt_delete(NULL));
  vTaskDelete(NULL);
}


/*aws task*/
void aws(void *parameters){
    int i, ack;
  char a;
  timerAlarmEnable(My_timer); //Just Enable
  float L1V, L2V, L3V, L1C, L2C, L3C, DT, DH;
//  readFile(SPIFFS, "/jsonfile.json");
//  delay(1000);
//  StaticJsonDocument < 1024 > doc;
//  DeserializationError error = deserializeJson(doc, configu);
//  serializeJsonPretty(doc, Serial);
//  Serial.println();
  StaticJsonDocument < 1024 > doc;
  char json[] = "{\"command_session\":0,\"AccountId\":\"A500\",\"DeviceMode\":\"F\",\"Connection\":\"C600\",\"DeviceType\":\"c\",\"serial\":3000,\"SimId\":420,\"status\":\"Active\",\"device_client_id\":\"DL500\",\"Location\":\"venkatapuram\",\"FarmId\":\"F123\",\"Region\":\"bangalore\",\"fcg_first_confg\":\"x\",\"fcg_motor_capacity_hp\":10,\"fcg_motor_type_phase\":3,\"fcg_starter_type\":\"STOD\",\"fcg_max_motor_runTime\":3500,\"fcg_single_phase_protect\":1,\"fcg_voltage_protection\":1,\"fcg_track_manual_trigger\":0,\"fcg_L1V_high\":350,\"fcg_L1V_low\":150,\"fcg_L1C_high\":80,\"fcg_L1C_LOW\":0,\"fcg_L2V_high\":350,\"fcg_L2V_low\":150,\"fcg_L2C_high\":80,\"fcg_L2C_LOW\":0,\"fcg_L3V_high\":350,\"fcg_L3V_low\":150,\"fcg_L3C_high\":80,\"fcg_L3C_LOW\":0,\"bcg_schedule_id\":0,\"bcg_schedule_runTime_hrs\":10,\"bcg_schedule_slot_begin\":1,\"bcg_schedule_slot_end\":86399,\"bcg_schedule_frequency\":50,\"bcg_schedule_sts\":1,\"bcg_schedule_status\":1,\"bcg_schedule_switch\":0,\"bcg_manual_switch_in_app\":\"motor OFF\",\"cg_wifissid\":\"Riosh 2G\",\"cg_wifipass\":\"@1Riosh@1\"}";
  DeserializationError error = deserializeJson(doc, json);
  serializeJsonPretty(doc, Serial);
  Serial.println();
  int command_session = doc["command_session"];
  String AccountId = doc["AccountId"];
  char DeviceMode = doc["DeviceMode"];
  String Connection = doc["Connection"];
  String DeviceType = doc["DeviceType"];
  int serial = doc["serial"];
  int SimId = doc["SimId"];
  String Status1 = doc["status"];
  String device_client_id = doc["device_client_id"];
  String Location = doc["Location"];
  String FarmId = doc["FarmId"];
  String Region = doc["Region"];
  String fcg_first_confg = doc["fcg_first_confg"];
  float fcg_motor_capacity_hp = doc["fcg_motor_capacity_hp"];
  String fcg_motor_type_phase = doc["fcg_motor_type_phase"];
  String fcg_starter_type = doc["fcg_starter_type"];
  long int fcg_max_motor_runTime = doc["fcg_max_motor_runTime"];
  String fcg_single_phase_protect = doc["fcg_single_phase_protect"];
  String fcg_voltage_protection = doc["fcg_voltage_protection"];
  String fcg_track_manual_trigger = doc["fcg_track_manual_trigger"];
    fcg_L1V_high = doc["fcg_L1V_high"];
    fcg_L1V_low = doc["fcg_L1V_low"];
    fcg_L1C_high = doc["fcg_L1C_high"];
    fcg_L1C_LOW = doc["fcg_L1C_LOW"];
    fcg_L2V_high = doc["fcg_L2V_high"];
    fcg_L2V_low = doc["fcg_L2V_low"];
    fcg_L2C_high = doc["fcg_L2C_high"];
   fcg_L2C_LOW = doc["fcg_L2C_LOW"];
   fcg_L3V_high = doc["fcg_L3V_high"];
   fcg_L3V_low = doc["fcg_L3V_low"];
   fcg_L3C_high = doc["fcg_L3C_high"];
   fcg_L3C_LOW = doc["fcg_L3C_LOW"];
  sched_id = doc["bcg_schedule_id"];
  long int bcg_schedule_runTime_hrs = doc["bcg_schedule_runTime_hrs"];
  int bcg_schedule_slot_begin = doc["bcg_schedule_slot_begin"];
  int bcg_schedule_slot_end = doc["bcg_schedule_slot_end"];
  int bcg_schedule_frequency = doc["bcg_schedule_frequency"];
  String bcg_schedule_sts = doc["bcg_schedule_sts"];
  String bcg_schedule_switch = doc["bcg_schedule_switch"];
  String bcg_manual_switch_in_app = doc["bcg_manual_switch_in_app"];
  byte cg_wifissid = doc["cg_wifissid"];
  byte cg_wifipass = doc["cg_wifipass"];
//      unsigned int address90 = 90;
//      unsigned int address120 = 120;
//        if (cg_wifipass !=NULL) {
//        char str[10];
//        sprintf(str, "%d", cg_wifipass);
//
//        //        str[j]='\0';
//        for (int i = 0; str[i] != '\0'; i++) {
//        eep.write(address90, str[i]);
//        address90++;
//        }
//        eep.write(address90, '\0');
//        Serial.print("writeWIFIPASS:");
//        Serial.println(str);
//      }
//      if (cg_wifipass !=NULL) {
//        char str[10];
//        sprintf(str, "%d", cg_wifipass);
//
//        //        str[j]='\0';
//        for (int i = 0; str[i] != '\0'; i++) {
//        eep.write(address120, str[i]);
//        address120++;
//        }
//        eep.write(address120, '\0');
//        Serial.print("writeWIFIPASS:");
//        Serial.println(str);
//      }
  xQueueOverwrite(slot_queue1, & bcg_schedule_slot_end);
  xQueueOverwrite(slot_queue2, & bcg_schedule_slot_begin);
//  xQueueOverwrite(bsvoltage_queue1, & fcg_L1V_high);
//  xQueueOverwrite(bsvoltage_queue2, & fcg_L1V_low);
//  xQueueOverwrite(bscurrent_queue1, & fcg_L1C_high);
//  xQueueOverwrite(bscurrent_queue2, & fcg_L1C_LOW);
//  xQueueOverwrite(bsvoltage_queue3, & fcg_L2V_high);
//  xQueueOverwrite(bsvoltage_queue4, & fcg_L2V_low);
//  xQueueOverwrite(bscurrent_queue3, & fcg_L2C_high);
//  xQueueOverwrite(bscurrent_queue4, & fcg_L2C_LOW);
//  xQueueOverwrite(bsvoltage_queue5, & fcg_L3V_high);
//  xQueueOverwrite(bsvoltage_queue6, & fcg_L3V_low);
//  xQueueOverwrite(bscurrent_queue5, & fcg_L3C_high);
//  xQueueOverwrite(bscurrent_queue6, & fcg_L3C_LOW);
  xQueueOverwrite(device_id_queue, & device_client_id);
  String tpc = "";
  tpc += String("/");
  tpc += String(AccountId);
  tpc += String("/");
  tpc += String(device_client_id);
  tpc += String("/");
  tpc += String(FarmId);
  tpc += String("/");
  tpc += String(Connection);
  tpc += String("/");
  String msg1 = "";
  String msg2 = "";
  String cmd1 = "";
  String cmd2 = "";
  String at = "";
  String at1 = "";
  String at2 = "";
  at += String("AT+QMTPUB=0,0,0,0,\"dv01/");

  at1 += String("AT+QMTSUB=0,1,\"dv01/");
  at2 += String("AT+QMTSUB=0,2,\"dv01/");
  cmd1 += String(at1);
  cmd1 += String("cmd");
  cmd1 += String(tpc);
  cmd1 += String("businessconfig\",1\r");
  cmd2 += String(at2);
  cmd2 += String("cmd");
  cmd2 += String(tpc);
  cmd2 += String("motorcontrol\",1\r");
  msg1 += String(at);
  msg1 += String("msg");
  msg1 += String(tpc);
  msg1 += String("tmetry\"\r");
  //msg1 +=String("businesscloud\"\r");
  msg2 += String(at);
  msg2 += String("msg");
  msg2 += String(tpc);
  msg2 += String("cmdack\"\r");
  Serial.println(cmd1);
  Serial.println(cmd2);
  Serial.println(msg1);
  Serial.println(msg2);
  char cmd11[100];
  char cmd22[100];
  char msg11[100];
  char msg22[100];
  
  char u=char(26);
  strcpy(cmd11, cmd1.c_str());
  strcpy(cmd22, cmd2.c_str());
  strcpy(msg11, msg1.c_str());
  strcpy(msg22, msg2.c_str());
  uart_write_bytes(UART_NUM_2,cmd11, strlen(cmd11));
  delay(2000);

  uart_write_bytes(UART_NUM_2,cmd22, strlen(cmd22));
  delay(2000);
//      TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 1;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 1;
//    TIMERG1.wdt_wprotect = 0;
  while(1){
    esp_task_wdt_init(30, false);
disableLoopWDT();

feedLoopWDT();
   String mtyp = "S";
//Serial.print("count1:");  
//Serial.println(count1);
   if(count1 >15){
      count1=0;

    xQueueReceive(volt_queue1, & L1V, 0);
    xQueueReceive(volt_queue2, & L2V, 0);
    xQueueReceive(volt_queue3, & L3V, 0);
    xQueueReceive(current_queue1, & L1C, 0);
    xQueueReceive(current_queue2, & L2C, 0);
    xQueueReceive(current_queue3, & L3C, 0);
//    xQueueReceive(temp_queue1, & DT, 0);
//    xQueueReceive(temp_queue2, & DH, 0);


uart_write_bytes(UART_NUM_2,msg11, strlen(msg11));
vTaskDelay(2000);

 StaticJsonDocument<1000> doc;
JsonObject tmetry = doc.createNestedObject("tmetry");
tmetry["tstmp"]=(rtc.getTime("%d/%m/%Y:%H:%M:%S"));
tmetry["mtyp"]=mtyp;
tmetry["etyp"]=etyp;
tmetry["sts"]=sts;
tmetry["L1V"]=L1V;
tmetry["L2V"]=L2V;
tmetry["L3V"]=L3V;
tmetry["L1C"]=L1C;
tmetry["L2C"]=L2C;
tmetry["L3C"]=L3C;
tmetry["DT"]=DT;
tmetry["DH"]=DH;
tmetry["sched_id"]=bcg_schedule_id1;
tmetry["strt_src"]=startsrc;;
        
char output[1000];
memset(output, '\0', sizeof(output));
serializeJsonPretty( doc, output);
uart_write_bytes(UART_NUM_2,output, strlen(output));
uart_write_bytes(UART_NUM_2,&u, strlen(&u));
}
 xQueueReceive(command_queue, & command_session, 0);
    xQueueReceive(device_id_queue, & device_client_id, 0);

    DynamicJsonDocument doc3(1024);
    if (command_session == 100) {
       String s;
      s = rtc.getTime();
      String b = (s.substring(0, 2));
      String c = (s.substring(3, 5));
      String d = (s.substring(6, 8));
      int i1 = b.toInt();
      int i2 = c.toInt();
      int i3 = d.toInt();
      int Time = ((i1 * 3600) + (i2 * 60) + i3 + 19800);
    uart_write_bytes(UART_NUM_2,msg22, strlen(msg22));  
//      TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//      TIMERG0.wdt_feed = 1;
//      TIMERG0.wdt_wprotect = 0;
//      TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//      TIMERG1.wdt_feed = 1;
//      TIMERG1.wdt_wprotect = 0;
      vTaskDelay(2000);
//    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 1;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 1;
//    TIMERG1.wdt_wprotect = 0;
      JsonObject cmdack = doc3.createNestedObject("cmdack");
      cmdack["command_session"] = command_session;
      cmdack["ack_receipt_Time"] = Time;
      cmdack["device_client_id"] = device_client_id;
      cmdack["tstmp"] = (rtc.getTime("%d/%m/%Y:%H:%M:%S"));
      char output1[500];
      serializeJsonPretty(doc3, output1);
      uart_write_bytes(UART_NUM_2,output1, strlen(output1));
      uart_write_bytes(UART_NUM_2,&u, strlen(&u));
    }
        //int flagM=0;
    //if((L1V<150.00)&&(L2V<150.00)&&(L3V<150.00)){
    // for(int j=0;j<60;j++){
    //  delay(1000); 
    //}
    // Serial2.print("AT+CFUN=0");
    // delay(300);
    // flagM=1;
    //}
    //if((L1V>200.00)&&(L2V>200.00)&&(L3V>200.00)&&(flagM=1)){
    // for(int j=0;j<30;j++){
    //  delay(1000); 
    //}
    // Serial2.print("AT+CFUN=1");
    // delay(300);
    // ESP.restart();
    //}
//    delay(1000);
//    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 1;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 1;
//    TIMERG1.wdt_wprotect = 0;
    vTaskDelay(10);
//vTaskDelay(100/ portTICK_PERIOD_MS);
esp_task_wdt_reset();
  }  
    vTaskDelete(NULL);
  Serial.printf("esp_task_wdt_delete: %d\n\n", esp_task_wdt_delete(NULL));
  }
void livemode(void *parameters){
  
     char a,b;
  Serial.print("Welcome to livemomde"); 
   pinMode(32,OUTPUT);
digitalWrite(32,HIGH);
  if (!SPIFFS.begin(true)) {
  Serial.println("SPIFFS initialisation failed...");
  SPIFFS_present = false; 
  }
  else
  {
    Serial.println(F("SPIFFS initialised... file access enabled..."));
    SPIFFS_present = true; 
  }
    if (! shtc3.begin()) {
    Serial.println("Couldn't find SHTC3");
    while (1) ;
  }


   
  if (io.begin(SX1509_ADDRESS) == false)
  {
    Serial.println("Failed to communicate. Check wiring and address of SX1509.");
    while (1);
  }
io.clock(INTERNAL_CLOCK_2MHZ, 4);
   Serial.print("Initializing SD card...");

  if (SD.exists("example.txt")) {
    Serial.println("example.txt exists.");
  } else {
    Serial.println("example.txt doesn't exist.");
  }
  pinMode(25,OUTPUT);
  pinMode(26,OUTPUT);
uart_write_bytes(UART_NUM_2,"ATV1\r", strlen("ATV1\r"));
  delay(500);
uart_write_bytes(UART_NUM_2,"ATE1\r", strlen("ATE1\r"));
  delay(500);
uart_write_bytes(UART_NUM_2,"AT+CMEE=2\r", strlen("AT+CMEE=2\r"));
delay(500);
uart_write_bytes(UART_NUM_2,"AT+IPR?\r", strlen("T+IPR?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"ATI\r", strlen("ATI\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+GSN\r", strlen("AT+GSN\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"ATI\r", strlen("ATI\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+CPIN?\r", strlen("AT+CPIN?\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+CIMI\r", strlen("AT+CIMI\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QCCID\r", strlen("AT+QCCID\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CSQ\r", strlen("AT+CSQ\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CREG?\r", strlen("AT+CREG?\r"));
  delay(300);
  uart_write_bytes(UART_NUM_2,"AT+CGREG?\r", strlen("AT+CGREG?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+COPS?\r", strlen("AT+COPS?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"ATI\r", strlen("ATI\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CSQ\r", strlen("AT+CSQ\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CREG?\r", strlen("AT+CREG?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CGREG?\r", strlen("AT+CGREG?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+COPS?\r", strlen("AT+COPS?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CPIN?\r", strlen("AT+CPIN?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QLTS=1\r", strlen("AT+QLTS=1\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QIFGCNT=0\r", strlen("AT+QIFGCNT=0\r"));
  delay(300);
   uart_write_bytes(UART_NUM_2,"AT+QICSGP=1,\"airtelgprs.com\"\r", strlen("AT+QICSGP=1,\"airtelgprs.com\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QIREGAPP\r", strlen("AT+QIREGAPP\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QIACT\r", strlen("AT+QIACT\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSECREAD=\"NVRAM:CA0\"\r", strlen("AT+QSECREAD=\"NVRAM:CA0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSECREAD=\"NVRAM:CC0\"\r", strlen("AT+QSECREAD=\"NVRAM:CC0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSECREAD=\"NVRAM:CK0\"\r", strlen("AT+QSECREAD=\"NVRAM:CK0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"cacert\",0,\"NVRAM:CA0\"\r", strlen("AT+QSSLCFG=\"cacert\",0,\"NVRAM:CA0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"clientcert\",0,\"NVRAM:CC0\"\r", strlen("AT+QSSLCFG=\"clientcert\",0,\"NVRAM:CC0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"clientkey\",0,\"NVRAM:CK0\"\r", strlen("AT+QSSLCFG=\"clientkey\",0,\"NVRAM:CK0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"seclevel\",0,2\r", strlen("AT+QSSLCFG=\"seclevel\",0,2\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"sslversion\",0,4\r", strlen("AT+QSSLCFG=\"sslversion\",0,4\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"ciphersuite\",0,\"0xFFFF\"\r", strlen("AT+QSSLCFG=\"ciphersuite\",0,\"0xFFFF\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"ignorertcTime\",1\r", strlen("AT+QSSLCFG=\"ignorertcTime\",1\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QMTCFG=\"ssl\",0,1,0\r", strlen("AT+QMTCFG=\"ssl\",0,1,0\r"));
  delay(300);

uart_write_bytes(UART_NUM_2,"AT+QMTOPEN=0,\"a38zppqrq5r0ag-ats.iot.ap-south-1.amazonaws.com\",8883\r", strlen("AT+QMTOPEN=0,\"a38zppqrq5r0ag-ats.iot.ap-south-1.amazonaws.com\",8883\r"));
 delay(20000);

uart_write_bytes(UART_NUM_2,"AT+QMTCONN=0,\"dv01\"\r", strlen("AT+QMTCONN=0,\"dv01\"\r"));
   delay(5000);
   disableCore0WDT();
   disableCore1WDT();
esp_err_t esp_task_wdt_delete(TaskHandle_t handle);
   xTaskCreatePinnedToCore(preading,
                          "Task 0",
                          5120,
                          NULL,
                          3,
                          NULL,
                          tskNO_AFFINITY);
   xTaskCreatePinnedToCore(sdstoring,
                          "Task 1",
                          5120,
                          NULL,
                          1,
                          NULL,
                          tskNO_AFFINITY);

    xTaskCreatePinnedToCore(aws,
                          "Task 1",
                          20000,
                          NULL,
                          2,
                          NULL,
                          tskNO_AFFINITY);
  //Delete "setup and loop" task
  vTaskDelete(NULL);
}
void configurationmode(void *parameters){
  char a;
  unsigned int address25 = 0;
  unsigned int address26 = 30;
  unsigned int address27 = 60;

  int m = 0;
  char str1[10];
  char str2[10];
  char str3[10];
  do {
    str1[m++] = eep.read(address25);
    address25++;
  } while (str1[m - 1] != '\0');
  Serial.print("str1:");
  Serial.println(str1);
  do {
    str1[m++] = eep.read(address26);
    address26++;
  } while (str1[m - 1] != '\0');
  Serial.print("str2:");
  Serial.println(str2);
  do {
    str1[m++] = eep.read(address27);
    address27++;
  } while (str1[m - 1] != '\0');
  Serial.print("str3:");
  Serial.println(str3);
uart_write_bytes(UART_NUM_2,"ATV1\r", strlen("ATV1\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"ATE1\r", strlen("ATE1\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CMEE=2\r", strlen("AT+CMEE=2\r"));
uart_write_bytes(UART_NUM_2,"AT+IPR?\r", strlen("T+IPR?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"ATI\r", strlen("ATI\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+GSN\r", strlen("AT+GSN\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"ATI\r", strlen("ATI\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+CPIN?\r", strlen("AT+CPIN?\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+CIMI\r", strlen("AT+CIMI\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QCCID\r", strlen("AT+QCCID\r"));
  delay(300);

uart_write_bytes(UART_NUM_2,"AT+CSQ\r", strlen("AT+CSQ\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CREG?\r", strlen("AT+CREG?\r"));
  delay(300);
  uart_write_bytes(UART_NUM_2,"AT+CGREG?\r", strlen("AT+CGREG?\r"));
  delay(300);

uart_write_bytes(UART_NUM_2,"AT+COPS?\r", strlen("AT+COPS?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"ATI\r", strlen("ATI\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CSQ\r", strlen("AT+CSQ\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CREG?\r", strlen("AT+CREG?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CGREG?\r", strlen("AT+CGREG?\r"));
  
uart_write_bytes(UART_NUM_2,"AT+COPS?\r", strlen("AT+COPS?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+CPIN?\r", strlen("AT+CPIN?\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QIFGCNT=0\r", strlen("AT+QIFGCNT=0\r"));
  delay(300);
Serial2.print("AT+QICSGP=1,\"airtelgprs.com\"\r");
   uart_write_bytes(UART_NUM_2,"AT+QICSGP=1,\"airtelgprs.com\"\r", strlen("AT+QICSGP=1,\"airtelgprs.com\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QIREGAPP\r", strlen("AT+QIREGAPP\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QIACT\r", strlen("AT+QIACT\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSECWRITE=\"NVRAM:CC0\",", strlen("AT+QSECWRITE=\"NVRAM:CC0\","));
uart_write_bytes(UART_NUM_2,str3, strlen(str3));
uart_write_bytes(UART_NUM_2,",100\r", strlen(",100\r"));
  delay(300);
    readFile(SPIFFS, "/certificate.pem.crt");
  delay(1000);
uart_write_bytes(UART_NUM_2,"AT+QSECWRITE=\"NVRAM:CK0\",", strlen("AT+QSECWRITE=\"NVRAM:CK0\","));
uart_write_bytes(UART_NUM_2,str1, strlen(str1));
uart_write_bytes(UART_NUM_2,",100\r", strlen(",100\r"));
delay(300);
  readFile(SPIFFS, "/private.pem.key");
  delay(1000);
uart_write_bytes(UART_NUM_2,"AT+QSECWRITE=\"NVRAM:CA0\",", strlen("AT+QSECWRITE=\"NVRAM:CA0\","));
uart_write_bytes(UART_NUM_2,str2, strlen(str2));
uart_write_bytes(UART_NUM_2,",100\r", strlen(",100\r"));
delay(300);
readFile(SPIFFS, "/rootca.pem");
delay(1000);
uart_write_bytes(UART_NUM_2,"AT+QSECREAD=\"NVRAM:CA0\"\r", strlen("AT+QSECREAD=\"NVRAM:CA0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSECREAD=\"NVRAM:CC0\"\r", strlen("AT+QSECREAD=\"NVRAM:CC0\"\r"));
  delay(300);
   uart_write_bytes(UART_NUM_2,"AT+QSECREAD=\"NVRAM:CK0\"\r", strlen("AT+QSECREAD=\"NVRAM:CK0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"cacert\",0,\"NVRAM:CA0\"\r", strlen("AT+QSSLCFG=\"cacert\",0,\"NVRAM:CA0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"clientcert\",0,\"NVRAM:CC0\"\r", strlen("AT+QSSLCFG=\"clientcert\",0,\"NVRAM:CC0\"\r"));
  delay(300);
   uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"clientkey\",0,\"NVRAM:CK0\"\r", strlen("AT+QSSLCFG=\"clientkey\",0,\"NVRAM:CK0\"\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"seclevel\",0,2\r", strlen("AT+QSSLCFG=\"seclevel\",0,2\r"));
  delay(300);
uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"sslversion\",0,4\r", strlen("AT+QSSLCFG=\"sslversion\",0,4\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"ciphersuite\",0,\"0xFFFF\"\r", strlen("AT+QSSLCFG=\"ciphersuite\",0,\"0xFFFF\"\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+QSSLCFG=\"ignorertcTime\",1\r", strlen("AT+QSSLCFG=\"ignorertcTime\",1\r"));
  delay(300);
 uart_write_bytes(UART_NUM_2,"AT+QMTCFG=\"ssl\",0,1,0\r", strlen("AT+QMTCFG=\"ssl\",0,1,0\r"));
  
delay(75000);
 uart_write_bytes(UART_NUM_2,"AT+QMTOPEN=0,\"a38zppqrq5r0ag-ats.iot.ap-south-1.amazonaws.com\",8883\r", strlen("AT+QMTOPEN=0,\"a38zppqrq5r0ag-ats.iot.ap-south-1.amazonaws.com\",8883\r"));
  
delay(10000);
uart_write_bytes(UART_NUM_2,"AT+QMTCONN=0,\"\r", strlen("AT+QMTCONN=0,\"dv_dev_test_1\"\r"));
   

   }   
void runmode(void *parameters){
  int b;
  int c=22; // dummy Addressing passing
Serial.println("Please select the which run mode");
Serial.println("1.Configure mode");
Serial.println("2.Live mode");
Serial.flush();
while(Serial.available()==0) {} 
b=Serial.parseInt();
if(b==1)
{
Serial.println("Welcome to configuration mode");

 configurationmode(&c);

 }
 if(b==2)
 {
 Serial.println("Welcome to Live mode");
 
  xTaskCreatePinnedToCore(UART_ISR_ROUTINE,
                          "UART_ISR_ROUTINE",
                          10120,
                          NULL,
                          1,
                          NULL,
                          tskNO_AFFINITY);
//vTaskDelete(NULL);
// xTaskCreate(UART_ISR_ROUTINE,
//                          "UART_ISR_ROUTINE",
//                          10120,
//                          NULL,
//                          1,
//                          NULL);
 livemode(&c);
 }
 if(b>2||b<0)
 {
  Serial.print("Selected Wrong mode");
  //ESP.restart();
 }
}
void factorymode(void * parameters) {
  Serial.print("Welcome to configure mode");
  //  unsigned int address1=0;
  //  unsigned int address2=0;
  // readEEPROM(eeprom, address);
  const char ssid[] = "Riosh 2G";
  const char password[] = "@1Riosh@1";
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(250);
    Serial.print('.');
  }
  Serial.println("\nConnected to " + WiFi.SSID() + " Use IP address: " + WiFi.localIP().toString()); // Report which SSID and IP is in use

  if (!SPIFFS.begin(true)) {
    Serial.println("SPIFFS initialisation failed...");
    SPIFFS_present = false;
  } else {
    Serial.println(F("SPIFFS initialised... file access enabled..."));
    SPIFFS_present = true;
  }
  //----------------------------------------------------------------------   
  ///////////////////////////// Server Commands 
  server.on("/", HomePage);
  server.on("/Firstconfig", File_Upload);
  server.on("/fupload", HTTP_POST, []() {
    server.send(200);
  }, handleFileUpload);

  server.on("/lisence", File_Upload);
  server.on("/fupload", HTTP_POST, []() {
    server.send(200);
  }, handleFileUpload);

  server.on("/privatekey", File_Upload);
  server.on("/fupload", HTTP_POST, []() {
    server.send(200);
  }, handleFileUpload);

  server.on("/RootCAcert", File_Upload);
  server.on("/fupload", HTTP_POST, []() {
    server.send(200);
  }, handleFileUpload);
  server.on("/delete", File_Delete);
  ///////////////////////////// End of Request commands
  server.begin();
  Serial.println("HTTP server started");
}
void setup() {
  int b;
  int c=22;
  char a;
  pinMode(pwrkey,OUTPUT);
  digitalWrite(pwrkey,LOW);
  delay(2000);
  digitalWrite(pwrkey,HIGH);
  delay(2000);
Serial.begin(115200);
  SPI.begin();
  ads.begin(15,13,12,14);
    while (!Serial) {
    ;
  }
  delay(4000);
  while(Serial.available()>0){
    a=Serial.read();
    Serial.print(a);
  }
        digitalWrite(25, LOW);
      digitalWrite(26, LOW);
My_timer = timerBegin(0, 80, true);
timerAttachInterrupt(My_timer, &onTimer, true);
timerAlarmWrite(My_timer, 1000000, true);
esp_err_t esp_task_wdt_reset(void);                // Reset calling task' the Task Watchdog timer


  Serial.print("Initializing SD card...");

  if (!SD.begin(5)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // open a new file and immediately close it:
  Serial.println("Creating example.txt...");
  myFile = SD.open("example.txt", FILE_WRITE);
  myFile.close();

  // Check to see if the file exists:
  if (SD.exists("example.txt")) {
    Serial.println("example.txt exists.");
  } else {
    Serial.println("example.txt doesn't exist.");
  }

  // delete the file:
  Serial.println("Removing example.txt...");
  SD.remove("example.txt");

  if (SD.exists("example.txt")) {
    Serial.println("example.txt exists.");
  } else {
    Serial.println("example.txt doesn't exist.");
  }
  Wire.begin();
  pwr_mgmt.attatch(Wire);
      uart_config_t Configurazione_UART2 = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
    };
    uart_param_config(NUMERO_PORTA_SERIALE, &Configurazione_UART2);
 
 
 esp_err_t uart_disable_pattern_det_intr(uart_port_t uart_num2);
    //Firma: void esp_log_level_set(const char *tag, esp_log_level_tlevel)
    esp_log_level_set(TAG, ESP_LOG_INFO);
 
 
   
    //Firma: esp_err_tuart_set_pin(uart_port_tuart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num)
    uart_set_pin(NUMERO_PORTA_SERIALE, U2TXD, U2RXD, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
 
 
    //Firma: uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));
    //       uart_driver_install(Numero_porta, RXD_BUFFER, TXD_Buffer, event queue handle and size, flags to allocate an interrupt)
    uart_driver_install(NUMERO_PORTA_SERIALE, BUF_SIZE, BUF_SIZE, 20, &uart2_queue, 0);
//      esp_task_wdt_init(WDT_TIMEOUT, false); //enable panic so ESP32 restarts
//  esp_task_wdt_add(NULL);
 data_queue = xQueueCreate(1, sizeof(Message1));
  volt_queue1 = xQueueCreate(1, sizeof(Message));
  volt_queue2 = xQueueCreate(1, sizeof(Message));
  volt_queue3 = xQueueCreate(1, sizeof(Message));
  current_queue1 = xQueueCreate(1, sizeof(Message));
  current_queue2 = xQueueCreate(1, sizeof(Message));
  current_queue3 = xQueueCreate(1, sizeof(Message));
  temp_queue1 = xQueueCreate(1, sizeof(Message));
  temp_queue2 = xQueueCreate(1, sizeof(Message));
  command_queue = xQueueCreate(1, sizeof(Message));
  slot_queue1 = xQueueCreate(1, sizeof(Message));
  slot_queue2 = xQueueCreate(1, sizeof(Message));
  device_id_queue = xQueueCreate(1, sizeof(Message));
       MCP342x::generalCallReset();
  delay(1);
  
  // Check device present

   
Serial.println("WELCOME TO IOT WORLD");  
Serial.println("Please select the which run mode");
Serial.println("1.Factory mode");
Serial.println("2.Run mode mode");
Serial.flush();
 long long counter = millis();
  while (Serial.available() == 0) {
    if (millis() - counter > (60 * 1000)) {
      Serial.println("time exceeded and no inputs");

  xTaskCreatePinnedToCore(UART_ISR_ROUTINE,
                          "UART_ISR_ROUTINE",
                          10120,
                          NULL,
                          1,
                          NULL,
                          tskNO_AFFINITY);
//vTaskDelete(NULL);
//xTaskCreate(UART_ISR_ROUTINE,
//                          "UART_ISR_ROUTINE",
//                          10120,
//                          NULL,
//                          1,
//                          NULL);   
      livemode(NULL);
      break;
    }
  }
b=Serial.parseInt();
if(b==1)
{
Serial.println("Welcome to Factory mode");

 factorymode(&c);

 }
 while(b==2)
 {
 Serial.println("Welcome to Run mode");
 runmode(&c);
 }
 if(b>2||b<0)
 {
  Serial.print("Selected Wrong mode");
//  ESP.restart();
 }
 
}
void loop(void){
  server.handleClient();
}
void SendHTML_Content(){
  server.sendContent(webpage);
  webpage = "";
}
void File_Upload(){
  append_page_header();
  webpage += F("<h3>Select File to Upload</h3>"); 
  webpage += F("<FORM action='/fupload' method='post' enctype='multipart/form-data'>");
  webpage += F("<input class='buttons' style='width:40%' type='file' name='fupload' id = 'fupload' value=''><br>");
  webpage += F("<br><button class='buttons' style='width:10%' type='submit'>Upload File</button><br>");
  webpage += F("<a href='/'>[Back]</a><br><br>");
  append_page_footer();
  server.send(200, "text/html",webpage);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String file_size(int bytes){
  String fsize = "";
  if (bytes < 1024)                 fsize = String(bytes)+" B";
  else if(bytes < (1024*1024))      fsize = String(bytes/1024.0,3)+" KB";
  else if(bytes < (1024*1024*1024)) fsize = String(bytes/1024.0/1024.0,3)+" MB";
  else                              fsize = String(bytes/1024.0/1024.0/1024.0,3)+" GB";
  return fsize;
}
void SendHTML_Stop(){
  server.sendContent("");
  server.client().stop(); // Stop is needed because no content length was sent
}
void SendHTML_Header(){
  server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); 
  server.sendHeader("Pragma", "no-cache"); 
  server.sendHeader("Expires", "-1"); 
  server.setContentLength(CONTENT_LENGTH_UNKNOWN); 
  server.send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. 
  append_page_header();
  server.sendContent(webpage);
  webpage = "";
}
void ReportCouldNotCreateFile(String target){
  SendHTML_Header();
  webpage += F("<h3>Could Not Create Uploaded File (write-protected?)</h3>"); 
  webpage += F("<a href='/"); webpage += target + "'>[Back]</a><br><br>";
  append_page_footer();
  SendHTML_Content();
  SendHTML_Stop();
}
File UploadFile; 
void handleFileUpload(){ // upload a new file to the Filing system
  HTTPUpload& uploadfile = server.upload(); 
  if(uploadfile.status == UPLOAD_FILE_START)
  {
    String filename = uploadfile.filename;
    if(!filename.startsWith("/")) filename = "/"+filename;
    Serial.print("Upload File Name: "); Serial.println(filename);
    SPIFFS.remove(filename);                  // Remove a previous version, otherwise data is appended the file again
    UploadFile = SPIFFS.open(filename, "w");  // Open the file for writing in SPIFFS (create it, if doesn't exist)
  }
  else if (uploadfile.status == UPLOAD_FILE_WRITE)
  {
    if(UploadFile) UploadFile.write(uploadfile.buf, uploadfile.currentSize); // Write the received bytes to the file
  } 
  else if (uploadfile.status == UPLOAD_FILE_END)
  {
    if(UploadFile)          // If the file was successfully created
    {                                    
      UploadFile.close();   // Close the file again
      Serial.print("Upload Size: "); 
      Serial.println(uploadfile.totalSize);
       Serial.print("uploadfile.filename");
      Serial.print(uploadfile.filename);
      String filename1 = uploadfile.filename;
      unsigned int address25 = 0;
      unsigned int address26 = 30;
      unsigned int address27 = 60;
      int j = 0;
      if (filename1 == "private.pem.key") {
        char str[10];
        sprintf(str, "%d", uploadfile.totalSize);

        //        str[j]='\0';
        for (int i = 0; str[i] != '\0'; i++) {
          eep.write(address25, str[i]);
          address25++;
        }
        eep.write(address25, '\0');
        Serial.print("writeEEPROM1:");
        Serial.println(str);
      }
      if (filename1 == "rootca.pem") {
        char str1[10];
        sprintf(str1, "%d", uploadfile.totalSize);

        //        str1[j]='\0';
        for (int i = 0; str1[i] != '\0'; i++) {
          eep.write(address26, str1[i]);
          address26++;
        }
        eep.write(address26, '\0');
        Serial.print("writeEEPROM2:");
        Serial.print(str1);
      }
      if (filename1 == "certificate.pem.crt") {
        char str2[10];
        sprintf(str2, "%d", uploadfile.totalSize);
        //        str2[j]='\0';
        for (int i = 0; str2[i] != '\0'; i++) {
          eep.write(address27, str2[i]);
          address27++;
        }
        eep.write(address27, '\0');
        Serial.print("writeEEPROM3:");
        Serial.print(str2);
      }
      webpage = "";
      append_page_header();
      webpage += F("<h3>File was successfully uploaded</h3>"); 
      webpage += F("<h2>Uploaded File Name: "); webpage += uploadfile.filename+"</h2>";
      webpage += F("<h2>File Size: "); webpage += file_size(uploadfile.totalSize) + "</h2><br>"; 
      append_page_footer();
      server.send(200,"text/html",webpage);
    } 
    else
    {
      ReportCouldNotCreateFile("upload");
    }
  }
}

void ReportSPIFFSNotPresent(){
  SendHTML_Header();
  webpage += F("<h3>No SPIFFS Card present</h3>"); 
  webpage += F("<a href='/'>[Back]</a><br><br>");
  append_page_footer();
  SendHTML_Content();
  SendHTML_Stop();
}
void ReportFileNotPresent(String target){
  SendHTML_Header();
  webpage += F("<h3>File does not exist</h3>"); 
  webpage += F("<a href='/"); webpage += target + "'>[Back]</a><br><br>";
  append_page_footer();
  SendHTML_Content();
  SendHTML_Stop();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SPIFFS_file_delete(String filename) { // Delete the file 
  if (SPIFFS_present) { 
    SendHTML_Header();
    File dataFile = SPIFFS.open("/"+filename, "r"); // Now read data from SPIFFS Card 
    if (dataFile)
    {
      if (SPIFFS.remove("/"+filename)) {
        Serial.println(F("File deleted successfully"));
        webpage += "<h3>File '"+filename+"' has been erased</h3>"; 
        webpage += F("<a href='/delete'>[Back]</a><br><br>");
      }
      else
      { 
        webpage += F("<h3>File was not deleted - error</h3>");
        webpage += F("<a href='delete'>[Back]</a><br><br>");
      }
    } else ReportFileNotPresent("delete");
    append_page_footer(); 
    SendHTML_Content();
    SendHTML_Stop();
  } else ReportSPIFFSNotPresent();
} 
void SelectInput(String heading1, String command, String arg_calling_name){
  SendHTML_Header();
  webpage += F("<h3>"); webpage += heading1 + "</h3>"; 
  webpage += F("<FORM action='/"); webpage += command + "' method='post'>"; // Must match the calling argument e.g. '/chart' calls '/chart' after selection but with arguments!
  webpage += F("<input type='text' name='"); webpage += arg_calling_name; webpage += F("' value=''><br>");
  webpage += F("<type='submit' name='"); webpage += arg_calling_name; webpage += F("' value=''><br><br>");
  webpage += F("<a href='/'>[Back]</a><br><br>");
  append_page_footer();
  SendHTML_Content();
  SendHTML_Stop();
}
void File_Delete(){
  if (server.args() > 0 ) { // Arguments were received
    if (server.hasArg("delete")) SPIFFS_file_delete(server.arg(0));
  }
  else SelectInput("Select a File to Delete","delete","delete");
}
void HomePage(){
  SendHTML_Header();
  webpage += F("<a href='/upload1'><button>Upload</button></a>");
    webpage += F("<a href='/upload2'><button>Upload</button></a>");
      webpage += F("<a href='/upload3'><button>Upload</button></a>");
  append_page_footer();
  SendHTML_Content();
  SendHTML_Stop(); // Stop is needed because no content length was sent
}
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data ) {
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));      //writes the MSB
  Wire.write((int)(eeaddress & 0xFF));    //writes the LSB
  Wire.write(data);
  Wire.endTransmission();
  }
byte readEEPROM(int deviceaddress, unsigned int eeaddress ) {
  byte rdata = 0xFF;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));      //writes the MSB
  Wire.write((int)(eeaddress & 0xFF));    //writes the LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) 
    rdata = Wire.read();
  return rdata;
  }

/* new file*/

// #include<Arduino.h>
// #include"CSS.h"
 #define ServerVersion "1.0"
 extern String  webpage;
 void append_page_header() {
  webpage  = F("<!DOCTYPE html><html>");
  webpage += F("<head>");
  webpage += F("<title>File Server</title>"); // NOTE: 1em = 16px
  webpage += F("<meta name='viewport' content='user-scalable=yes,initial-scale=1.0,width=device-width'>");
  webpage += F("<style>");
  webpage += F("body{max-width:65%;margin:0 auto;font-family:arial;font-size:105%;text-align:center;color:blue;background-color:#F7F2Fd;}");
  webpage += F("ul{list-style-type:none;margin:0.1em;padding:0;border-radius:0.375em;overflow:hidden;background-color:#dcade6;font-size:1em;}");
  webpage += F("li{float:left;border-radius:0.375em;border-right:0.06em solid #bbb;}last-child {border-right:none;font-size:85%}");
  webpage += F("li a{display: block;border-radius:0.375em;padding:0.44em 0.44em;text-decoration:none;font-size:85%}");
  webpage += F("li a:hover{background-color:#EAE3EA;border-radius:0.375em;font-size:85%}");
  webpage += F("section {font-size:0.88em;}");
  webpage += F("h1{color:white;border-radius:0.5em;font-size:1em;padding:0.2em 0.2em;background:#558ED5;}");
  webpage += F("h2{color:orange;font-size:1.0em;}");
  webpage += F("h3{font-size:0.8em;}");
  webpage += F("table{font-family:arial,sans-serif;font-size:0.9em;border-collapse:collapse;width:85%;}"); 
  webpage += F("th,td {border:0.06em solid #dddddd;text-align:left;padding:0.3em;border-bottom:0.06em solid #dddddd;}"); 
  webpage += F("tr:nth-child(odd) {background-color:#eeeeee;}");
  webpage += F(".rcorners_n {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:20%;color:white;font-size:75%;}");
  webpage += F(".rcorners_m {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:50%;color:white;font-size:75%;}");
  webpage += F(".rcorners_w {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:70%;color:white;font-size:75%;}");
  webpage += F(".column{float:left;width:50%;height:45%;}");
  webpage += F(".row:after{content:'';display:table;clear:both;}");
  webpage += F("*{box-sizing:border-box;}");
  webpage += F("footer{background-color:#eedfff; text-align:center;padding:0.3em 0.3em;border-radius:0.375em;font-size:60%;}");
  webpage += F("button{border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:20%;color:white;font-size:130%;}");
  webpage += F(".buttons {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:15%;color:white;font-size:80%;}");
  webpage += F(".buttonsm{border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:9%; color:white;font-size:70%;}");
  webpage += F(".buttonm {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:15%;color:white;font-size:70%;}");
  webpage += F(".buttonw {border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:40%;color:white;font-size:70%;}");
  webpage += F("a{font-size:75%;}");
  webpage += F("p{font-size:75%;}");
  webpage += F("</style></head><body><h1>File Server "); webpage += String(ServerVersion) + "</h1>";
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void append_page_footer(){ // Saves repeating many lines of code for HTML page footers
  webpage += F("<ul>");
  webpage += F("<li><a href='/'>Home</a></li>"); // Lower Menu bar command entries
  webpage += F("<li><a href='/Firstconfig'>Firstconfig</a></li>");
  webpage += F("<li><a href='/lisence'>lisence</a></li>"); 
   webpage += F("<li><a href='/privatekey'>privatekey</a></li>");
    webpage += F("<li><a href='/RootCAcert'>RootCAcert</a></li>");
   webpage += F("<li><a href='/delete'>Delete</a></li>"); 
 webpage += F("</ul>");
  webpage += F("</body></html>");
}

The sketch could be simpler if the Arduino Serial2 was used, and nothing was done with the WDT and the UART_ISR_ROUTINE was not needed.
I wrote down what I noticed, it might not all be worth mentioning:

  1. Are those multiple files together ?

  2. You could just use the Arduino "Serial2.begin(115200);" instead of those lower level functions.

  3. Do you really need all those tasks and all those queues ?

  4. What is the UART_ISR_ROUTINE for ? I think that you can use the Arduino Serial2.

  5. This is unsafe code in my opinion. Stopping the do-while statement depends on the data that is read from the (emulated) EEPROM. If the data is never 0x00, then it will not stop.

do {
    str1[m++] = eep.read(address25);
    address25++;
  } while (str1[m - 1] != '\0');
  1. This might wait forever:
  void runmode(void *parameters) {
    ...
    while (Serial.available() == 0) {}
    ...
  1. You set all task on the core "tskNO_AFFINITY" and let the Operating System decide which core it will use. But now you don't know which of you tasks is running on Core0. It is best to let the ESP32 do all the wifi things with Core0 and Arduino things with Core1. I suggest to use Core1 for all your tasks.

  2. Why do you deal with the WDT so often ? I even see "disableCore0WDT();" and "disableCore1WDT();". If you run Arduino code, then you have to check your code that it will not get stuck in a loop, and add a delay or yield there.

  3. Can you try to remove a few includes, and see which one is not needed. You can start by removing "#include <Arduino.h>".

1 Like
  1. Serial2.begin(115200); I was used to work in this but cannot able to extract the receive data exactly.
  2. yes all the tasks and queues I need.
    3.UART_ISR_ROUTINE is a uart2 receive data it works as a interrupt.
  3. I will change to use EEPROM.
  4. ok I will use only core 1.
  5. I will remove few includes.

The Arduino Serial library has a internal buffer. If you check if something is available with "Serial2.available()", and then read it with "Serial2.read()" and then store it in your own buffer, then you can build incoming commands in your own buffer.
The internal buffer inside the Serial library gives time to do other things.

It is hard to see through the code and the usage of the UART_ISR_ROUTINE() function. I did not carefully check everything, but it seems to be a complex and bad solution to fix an easy problem.

What about the waiting in the while loop ?

Bad: while(Serial.available() == 0) {}
Good: while(Serial.available() == 0) { delay(1); }
Good: while(Serial.available() == 0) { yield(); }
Maybe even better: if(Serial.available() > 0) { ...

If you move everything to Core1, then I hope that Core1 gives a WDT timeout. That means the problem is in your code and can be fixed.

putting code onto core0 when using WiFI is beyond your, @jagadish22495, skill level.

Hello koepel, thanks for your reply.

  1. Actually problem with preading() function, sdcard() function and aws() function and UART_ISR_ROUTINE() function.
    Here whether problem with task delay or anything else triggering the watch dog trigger could able to find.

Noted all your points. Sure I will make it done.

Hello Idahowalker, thank you for your reply.
Actually I doesn't have a problem with wi-Fi.

good luck.

will you Please suggest me task create and task delay for freeRTOS two cores. I'm suspecting the same will you please tell me.

Put all your tasks on core1, get rid of tskNo_Affinity use 1 instead.

You will not be able to use core0 when using WiFi. <<<<<<<<<<<Do you understand that statement?

Are you saying that you get a WDT timeout on Core0 with this message: "Guru Meditation Error: Core 0 panic’ed (Interrupt wdt timeout on CPU0" ?

What happens if you remove all the WDT calls ?

I learned the ESP32 from https://randomnerdtutorials.com/, but I can not find that they change the WDT settings. The default settings are good enough.

Could you give all your tasks the priority 0 ?
I read that there is a idle task for the WatchDog that runs at priority 0. If you have a task with higher priority, then that task must be released sometimes, for example with a "xTaskDelay()". Giving all the tasks a priority 0 reduces any trouble with that.

does this stop the wdt.

void preading(void * parameters) {
  int16_t adc1, adc2, adc3;
  long value1 = 0;
  long value2 = 0;
  long value3 = 0;
  float VRMS1, VRMS2, VRMS3, AmpsRMS1, AmpsRMS2, L1C, L2C, L3C, AmpsRMS3, voltage1, voltage2, voltage3,
  ANI0, ANI1, ANI2, volt1, volt2, volt3, tempareture, humudityper,bvoltage, bpercentage;
  int deviceaddress = 0x44;
  int slotend, slotbegin;
  int flagA = 0;
  unsigned int eeaddress = 0x50;
  byte data = 00;
  byte rdata = 0xFF;
  char a;
  int flagz = 0;
  while (1) {
vTaskDelay(1);
//
//    int flagB = 0;
//    ANI0 = (ads.analogRead(0));
//    ANI1 = (ads.analogRead(1));
//    ANI2 = (ads.analogRead(2));
//    volt1 = ((ANI0 / 1023) * 3.3);
//    volt2 = ((ANI1 / 1023) * 3.3);
//    volt3 = ((ANI2 / 1023) * 3.3);
//    volt1 = volt1 * 209;
//    volt2 = volt2 * 209;
//    volt3 = volt3 * 229;
////    Serial.println("Step1");
//    if ((volt1 == 0) || (volt2 == 0) || (volt3 == 0)) {
//      flagB = 1;
//    }
//    if ((bvoltage < 3.5) && (flagB == 1)) {
//      sts = 0;
//    }
//    if ((flagB == 0)) {
//      sts = 1;
//    }
////        Serial.println("Step2");
//
////    Serial.print("fcg_L1V_high");
////    Serial.println(fcg_L1V_high);
////    Serial.print("fcg_L2V_high");
////    Serial.println(fcg_L2V_high);
////    Serial.print("fcg_L3V_high");
////    Serial.println(fcg_L3V_high);
////    Serial.print("fcg_LV_low");
////    Serial.println(fcg_L2V_low);
////    Serial.print("fcg_L2V_low");
////    Serial.println(fcg_L2V_low);
////    Serial.print("fcg_L3V_low");
////    Serial.println(fcg_L3V_low);
//    MCP342x::Config status;
//    uint8_t err1 = adc.convertAndRead(MCP342x::channel1, MCP342x::continous,
//      MCP342x::resolution16, MCP342x::gain4,
//      10000, value1, status);
//    uint8_t err2 = adc.convertAndRead(MCP342x::channel2, MCP342x::continous,
//      MCP342x::resolution16, MCP342x::gain4,
//      10000, value2, status);
//    uint8_t err3 = adc.convertAndRead(MCP342x::channel3, MCP342x::continous,
//      MCP342x::resolution16, MCP342x::gain4 ,
//      10000, value3, status);
//          Serial.println("Step3");
//
//    voltage1 = abs(voltage1 = (float) value1);
//    voltage2 = abs(voltage2 = (float) value2);
//    voltage3 = abs(voltage3 = (float) value3);
//    VRMS1 = (voltage1 / 2.0) * 0.707;
//    VRMS2 = (voltage2 / 2.0) * 0.707;
//    VRMS3 = (voltage3 / 2.0) * 0.707;
//    AmpsRMS1 = VRMS1 / 30;
//    AmpsRMS2 = VRMS2 / 30;
//    AmpsRMS3 = VRMS3 / 30;
//    AmpsRMS1 = AmpsRMS1 + 25.30;
//    AmpsRMS2 = AmpsRMS2 + 25.30;
//    AmpsRMS3 = AmpsRMS3 + 25.30;
////    Serial.print("fcg_L1C_high");
////    Serial.println(fcg_L1C_high);
////    Serial.print("fcg_L2C_high");
////    Serial.println(fcg_L2C_high);
////    Serial.print("fcg_L3C_high");
////    Serial.println(fcg_L3C_high);
////    Serial.print("fcg_L1C_LOW");
////    Serial.println(fcg_L1C_LOW);
////    Serial.print("fcg_L2C_LOW");
////    Serial.println(fcg_L2C_LOW);
////    Serial.print("fcg_L3C_LOW");
////    Serial.println(fcg_L3C_LOW);
////             Serial.println("Step4");
//
//    tempareture = sht.getTemperature();
//    humudityper = sht.getHumidity();
////              Serial.println("Step5");
//
////    if(volt1>150){
////    io.pinMode(SX1509_LED_PIN1, OUTPUT);
////    }
////    else{
////      io.pinMode(SX1509_LED_PIN1, LOW);
////    }
////    if(volt2>150){
////    io.pinMode(SX1509_LED_PIN2, OUTPUT);
////    }
////    else{
////      io.pinMode(SX1509_LED_PIN2, LOW);
////    }
////    if(volt3>150){
////    io.pinMode(SX1509_LED_PIN3, OUTPUT);
////    }
////    else{
////      io.pinMode(SX1509_LED_PIN3, LOW);
////    }
////    io.blink(SX1509_LED_PIN1, 1000, 0);
////    io.blink(SX1509_LED_PIN2, 1000, 0);
////    io.blink(SX1509_LED_PIN3, 1000, 0);
////          Serial.println("Step6");
//
////    bpercentage = (pwr_mgmt.accuratePercent());
////    bvoltage = (pwr_mgmt.voltage());
////              Serial.println("Step7");
//
//    if (((fcg_L1V_high > volt1) && (volt1 > fcg_L1V_low) && (fcg_L2V_high > volt2) && (volt2 > fcg_L2V_low) && (fcg_L3V_high > volt3) && (volt3 > fcg_L3V_low) &&
//        (fcg_L1C_high > AmpsRMS1) && (AmpsRMS1 > fcg_L1C_LOW) && (fcg_L2C_high > AmpsRMS2) && (AmpsRMS2 > fcg_L2C_LOW) && (fcg_L3C_high > AmpsRMS3) && (AmpsRMS3 > fcg_L3C_LOW))) {
//      flagz = 0;
//
//      etyp = "T";
//    }
////              Serial.println("Step8");
//
//    if (!((fcg_L1V_high > volt1) && (volt1 > fcg_L1V_low) && (fcg_L2V_high > volt2) && (volt2 > fcg_L2V_low) && (fcg_L3V_high > volt3) && (volt3 > fcg_L3V_low) &&
//        (fcg_L1C_high > AmpsRMS1) && (AmpsRMS1 > fcg_L1C_LOW) && (fcg_L2C_high > AmpsRMS2) && (AmpsRMS2 > fcg_L2C_LOW) && (fcg_L3C_high > AmpsRMS3) && (AmpsRMS3 > fcg_L3C_LOW))) {
//      flagz = 1;
//      digitalWrite(25, LOW);
//      digitalWrite(26, LOW);
//    }
//
//    if (flagz == 1) {
//      
//      etyp = "C";
//      startsrc = "OFF";
//      
//    }
////          Serial.println("Step9");
//
//    if ((motor == 1) && (flagz == 0)) {
//      digitalWrite(25, HIGH);
//      digitalWrite(26, HIGH);
//      startsrc = "App";
//      flagA = 0;
//    }
//        Serial.print("sched_id:");
//        Serial.println(sched_id);
//        Serial.print("motor:");
//        Serial.println(motor);
////                  Serial.println("Step10");
//
//    if ((sched_id > 3) && (motor!=1) && (flagz == 0)) {
//      String a;
//      xQueueReceive(slot_queue1, & slotend, 0);
//      xQueueReceive(slot_queue2, & slotbegin, 0);
//      String s;
//      s = rtc.getTime();
//      String b = (s.substring(0, 2));
//      String c = (s.substring(3, 5));
//      String d = (s.substring(6, 8));
//      int i1 = b.toInt();
//      int i2 = c.toInt();
//      int i3 = d.toInt();
//      int Time = ((i1 * 3600) + (i2 * 60) + i3 + 19800);
//        Serial.print("Time:");
//        Serial.println(Time);
//        Serial.print("slotbegin:");
//        Serial.println(slotbegin);
//        Serial.print("slotend:");
//        Serial.println(slotend);
//      if ((slotend > Time) && (Time > slotbegin)) {
//        digitalWrite(25, HIGH);
//        digitalWrite(26, HIGH);
//        startsrc = "bcg_schedule";
//        flagA = 0;
//      }
//    }
////              Serial.println("Step11");
//int flagS=0;
//    if ((sched_id ==2) && (motor!=1) && (AmpsRMS1 > 0.00) && (AmpsRMS2 > 0.00) && (AmpsRMS3 > 0.00)) {
//      startsrc = "ControlPanel";
//      flagS=1;
//    }
//    if ((sched_id ==2) && (motor!=1)&&(flagA = 0)&&(flagS==0)) {
//      digitalWrite(25, LOW);
//      digitalWrite(26, LOW);
//      flagA = 1;
//      startsrc="OFF";
//    }
////              Serial.println("Step12");
//
//    String dataString = "";
//    dataString += String("Reading:-");
//    dataString += String("L1V:");
//    dataString += String(volt1);
//    dataString += String("V");
//    dataString += String("   ");
//    dataString += String("L2V:");
//    dataString += String(volt2);
//    dataString += String("V");
//    dataString += String("   ");
//    dataString += String("L3V:");
//    dataString += String(volt3);
//    dataString += String("V");
//    dataString += String("   ");
//    dataString += String("L1C:");
//    dataString += String(AmpsRMS1);
//    dataString += String("A");
//    dataString += String("   ");
//    dataString += String("L2C:");
//    dataString += String(AmpsRMS2);
//    dataString += String("A");
//    dataString += String("   ");
//    dataString += String("L3C:");
//    dataString += String(AmpsRMS3);
//    dataString += String("A");
//    dataString += String("   ");
//    dataString += String("Tempareture:");
//    dataString += String(tempareture);
//    dataString += String("degrees C");
//    dataString += String("   ");
//    dataString += String("humidity:");
//    dataString += String(humudityper);
//    dataString += String("% rH");
//    dataString += String("   ");
//    dataString += String("Batteryvoltage:");
//    dataString += String(bvoltage);
//    dataString += String("V");
//    dataString += String("   ");
//    dataString += String("batteryLevel:");
//    dataString += String(bpercentage);
//    dataString += String("%");
////          Serial.println("Step13");
//
//    xQueueOverwrite(volt_queue1, & volt1);
//    xQueueOverwrite(volt_queue2, & volt2);
//    xQueueOverwrite(volt_queue3, & volt3);
//    xQueueOverwrite(current_queue1, & AmpsRMS1);
//    xQueueOverwrite(current_queue2, & AmpsRMS2);
//    xQueueOverwrite(current_queue3, & AmpsRMS3);
//    xQueueOverwrite(temp_queue1, & tempareture);
//    xQueueOverwrite(temp_queue2, & humudityper);
//    bcg_schedule_id1 = String(sched_id);
//    xQueueOverwrite(data_queue, & dataString);
////              Serial.println("Step14");
//
//    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG0.wdt_feed = 10;
//    TIMERG0.wdt_wprotect = 0;
//    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
//    TIMERG1.wdt_feed = 10;
//    TIMERG1.wdt_wprotect = 0;
//        vTaskDelay(100 / portTICK_PERIOD_MS);

  }
  vTaskDelete(NULL);
    Serial.printf("esp_task_wdt_delete: %d\n\n", esp_task_wdt_delete(NULL));

}

/* sdstoring*/
void sdstoring(void * parameters) {
  String dataString;
  while (1) {
    xQueueReceive(data_queue, & dataString, 0);
    File myFile = SD.open("/data.txt", FILE_APPEND);
    myFile.println(dataString);
    myFile.close();

    TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
    TIMERG0.wdt_feed = 10;
    TIMERG0.wdt_wprotect = 0;
    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
    TIMERG1.wdt_feed = 10;
    TIMERG1.wdt_wprotect = 0;
    vTaskDelay(100);
        TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
    TIMERG0.wdt_feed = 10;
    TIMERG0.wdt_wprotect = 0;
    TIMERG1.wdt_wprotect = TIMG_WDT_WKEY_VALUE;
    TIMERG1.wdt_feed = 10;
    TIMERG1.wdt_wprotect = 0;
    vTaskDelay(1000 / portTICK_PERIOD_MS);
  }
  vTaskDelete(NULL);
}

?

BTW troubleshooting code snippets suck.

You did not show you tried all the changes I suggested, YOU DID NOT POST ALL THE CODE.

So now I am left to figure this cht out the stupid way. One line at a time.

On 2nd thought. I'm not doing it, I'm going back to working on my drone. The engines spin up and the MPU is working. Good luck to you.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.