#include"Define.h"
#include <GSMMannager.h>

// #include "msc.h"

#include<driver/periph_ctrl.h>
#include "SensorOptoSky.h"
#include <SoftwareSerial.h>
#include <Ticker.h>
#include <updatebyme.h>
#include "mymsc.h"
//#include "MyWebServer.h"
#include "SDmanger.h"
//#include "HttpsOTAUpdate.h"
#include "slave.h"
#include "log.h"
#include "Myhttpserver.h"
#define beePin 39
#define BeeChain 0
#include <wifidebug.h>
#include <serilaFS.h>
#define LOGGING
//myPort将原来ESP8266对内通讯改为，485对内的通讯
// #define MYPORT_TX 45
// #define MYPORT_RX 46
#define WATCHDOG_TIMEOUT_SECONDS 600
int hassend = 0;
GSMMannger *gsmmanger;
UpDateClassByme *ProgrameUper;
EventGroupHandle_t Eventgroup;

SensorOptoSky IS1Sensor;
myHttpServer *httpserver;
// SoftwareSerial myPort(MYPORT_RX, MYPORT_TX, false);
 HardwareSerial myPort(4);
// swSer(14, 12, false, 256);
// u_char a[]={0x01,0x04,0x00,0x00,0x00,0x06,0x70,0x08};
u_char ret[17];
u_char windret[17];
Ticker ticker;
slave myslave;
String log_path;
String log_data;
bool IsNetOK = false;
String fenge(String str, String fen, int index)
{
    int weizhi;
    String temps[str.length()];
    int i = 0;
    do
    {
        weizhi = str.indexOf(fen);
        if (weizhi != -1)
        {
            temps[i] = str.substring(0, weizhi);
            str = str.substring(weizhi + fen.length(), str.length());
            i++;
        }
        else
        {
            if (str.length() > 0)
                temps[i] = str;
        }
    } while (weizhi >= 0);

    if (index > i)
        return "-1";
    return temps[index];
}
// void beebee(int timemill)
// {
//     ledcAttachPin(beePin, BeeChain);
//     ledcWrite(BeeChain, 125);
//     vTaskDelay(timemill);
    
//     ledcWrite(BeeChain, 0);
//         vTaskDelay(timemill);
    
//     ledcWrite(BeeChain, 125);
//         vTaskDelay(timemill);
    
//     ledcWrite(BeeChain, 0);
//     ledcDetachPin(beePin);
// }

void beebee(int timemill)
{
    // === 替换 ledcAttachPin ===
    // 旧: ledcAttachPin(beePin, BeeChain);
    // 新: ledcAttach(pin, freq, resolution_bits);
    // 假设频率仍然是 220Hz，分辨率是 8位 (0-255)
    // 注意：如果 BeeChain 被用作一个通道号，并且你希望显式地使用它，
    // 新的 ledcAttach 函数并没有直接的 channel 参数。
    // 但是，你可以通过 ledcSetChannelPin(BeeChain, beePin); 来实现类似目的。
    // 最常见的用法是让 ledcAttach 自动选择通道。
    
    // 如果 BeeChain 只是一个 "逻辑链" 或者通道号，现在我们直接用 beePin 和频率、分辨率
   // ledcAttach(beePin, 220, 8); // 将 beePin 关联到 LEDC，设置频率 220Hz，8位分辨率
                               // 这会在内部自动分配一个空闲的 LEDC 通道给 beePin。
    // === 替换 ledcWrite ===
    // 旧: ledcWrite(BeeChain, 125);
    // 新: ledcWrite(pin, duty);
    ledcWrite(beePin, 125); // 在 beePin 上设置 125 的占空比 (~49%，因为 125/255)
    vTaskDelay(timemill); // 使用实时操作系统任务延迟
    ledcWrite(beePin, 0); // 在 beePin 上设置 0 的占空比 (关闭)
    vTaskDelay(timemill);
    ledcWrite(beePin, 125); // 在 beePin 上设置 125 的占空比 (打开)
    vTaskDelay(timemill);
    ledcWrite(beePin, 0); // 在 beePin 上设置 0 的占空比 (关闭)
    // === 替换 ledcDetachPin ===
    // 旧: ledcDetachPin(beePin);
    // 新: ledcDetach(pin);
    ledcDetach(beePin); // 从 LEDC 分离 beePin
}


String Datenow="";
void printbytcp(String str)
{
  //tcpserver.SendDataToClinet(str);
//   Serial.println(str);
//   write_log(log_path,0,str);
    str=Datenow+"#######"+str;
    int lennn=str.length();
    char *temp = new char[lennn];
    memcpy(temp, str.c_str(),  str.length());
   bool flagsucc = httpserver->UpdateData(Http_Log_Path, temp, lennn);
   vTaskDelay(3000);
    delete[] temp;

}




void readmeichaung()
{
/////////////////////////////////now///////////////////////////
    double temprature = myslave.getMLX();
    // Serial.println("wendu");
    // Serial.println(temprature);
    // Serial.println("hello word");
    write_log(log_path,10,"temprature:" + String(temprature));
////////////////////////////////now////////////////////////////
    myslave.getWehter();
    memcpy(windret,myslave.ret,17);
    float VV = (windret[3] * 256 + windret[4]) * 1.0 / 100;
    float DD = (windret[5] * 256 + windret[6]) * 1.0 / 10;
    float TT = (windret[7] * 256 + windret[8]) * 1.0 / 100;
    float HH = (windret[9] * 256 + windret[10]) * 1.0 / 100;
    long PP = (windret[13] * 256 + windret[14]) * 256 * 256 + (windret[11] * 256 + windret[12]);
    // Serial.println("VV:" + String(VV) + "DD:" + String(DD) + "TT:" + String(TT) + "HH:" + String(HH) + "PP:" + String(PP));
    write_log(log_path,10,"VV:" + String(VV) + " DD:" + String(DD) + " TT:" + String(TT) + " HH:" + String(HH) + " PP:" + String(PP));
}


String get_GPS(void)
{
    
    write_log(log_path,10,"check GPS...");
    gsmmanger->modem->sendAT(GF("+CGNSPWR?"));
    gsmmanger->modem->waitResponse("OK");
    
  
    write_log(log_path,10,"Open GPS...");
    gsmmanger->modem->sendAT(GF("+CGNSPWR=1"));
    gsmmanger->modem->waitResponse("OK");

    gsmmanger->modem->sendAT(GF("+CGNSAID=31,1,1,1"));
    gsmmanger->modem->waitResponse("OK");

    
    gsmmanger->modem->sendAT(GF("+CGNSINF"));
    
    String gpsbac;
    gsmmanger->modem->waitResponse(5000,gpsbac);
    // Serial.println(gps);

    write_log(log_path,10,"gpsbac is " + gpsbac);
    String Date =  gpsbac.substring(18,32);
    write_log(log_path,10,"get gps data is " + Date);
    String  temp = Date.substring(0,4) + "-" + Date.substring(4,6) + "-" +Date.substring(6,8) + " " + Date.substring(8,10) + ":" +Date.substring(10,12) + ":" +Date.substring(12,-1);
    Date = temp;

    write_log(log_path,10,"gps time is" + Date);
   
    if(Date.indexOf(",") != -1) 
    {
        return "-1";
    }
    


    write_log(log_path,10,"gpsdate:"+Date);
    return Date;
}
// String get_ti()
// {
//    return gsmmanger->modem->getNetworkTime;
// }
// #include "esp_task_wdt.h"
// 用于存储 loop 任务的句柄（如果需要）
TaskHandle_t loopTaskHandle = NULL; 
#include <esp_task_wdt.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
void setup()
{



    

//esp_task_wdt_init(20, true);
    Serial.begin(460800);
    Serial.println("start");
    //return;
    Serial.println(Curentvsion);
    sdcard::lock();
       // vTaskDelay(5000);
    sdcard::init_sdcard();
    String hasbeenformat = sdcard::ReadFileToString("/do_not_remove_and_edit_this_file");
    if(hasbeenformat == ""){
        sdcard::formatSDCard();
        sdcard::WriteStringToFile("/do_not_remove_and_edit_this_file","do not remove and edit this file \n\
            this file is used to tell the system that the sdcard has been formated,\
            \nif you want to format the sdcard,please delete this file,\n\
            the system will format the sdcard automatically next reboot.");
        //重启
        esp_restart();
    }
   // vTaskDelay(5000);
    //sdcard::formatSDCard();
    // while (1)
    // {
    //     vTaskDelay(5000);
    //     Serial.println("restart");
        
    
    //     /* code */
    // }
    
    sdcard::testwriet();
    sdcard::Mkdir("/up");
    sdcard::Mkdir("/down");
    sdcard::Mkdir("/other");
    sdcard::Mkdir("/gps");
    sdcard::Mkdir("/log");
    sdcard::unlock();
    write_log(log_path,10,log_data);
    // Serial.println(gsmmanger->GetDataAndTime());
    Eventgroup = xEventGroupCreate();
    if (Eventgroup == NULL)
    {
        Serial.println("create eventgroup failed");
        /* code */
    }
    


      




    xTaskCreatePinnedToCore(
      TaskSerialFS,   // Function that should be called
      "TaskSerialFS", // Name of the task (for debugging)
      1000*10,      // Stack size (bytes)
      NULL,      // Parameter to pass
      1,         // Task priority
      NULL,       // Task handle
      0); // run on core 0
    beginWIFI();

    // pinMode(21, OUTPUT);
    // digitalWrite(21, HIGH);
    pinMode(beePin, OUTPUT);
    // ledcSetup(BeeChain, 220, 8);
    // ledcAttachPin(beePin, 0);
    ledcAttach(beePin, 220, 8);
    beebee(1000);
 
    myslave.init(46,45);
    //sleep(3); 
    readmeichaung();
    //原来的SIM800，改为现在的AIR780E4G模块，使用的是串口2。
    
    Serial.println("start GSMMannger");
    //    gsmmanger = new GSMMannger(2, 19, 20);


    #if ARDUINO_USB_CDC_ON_BOOT

    gsmmanger = new GSMMannger(2, 2, 3);
    #else
    gsmmanger = new GSMMannger(2, 19, 20);
    #endif
    IsNetOK = gsmmanger->setpu();
    httpserver = new myHttpServer();
    gsmmanger->client->setTimeout(20*1000); //设置客户端超时20秒

    if (IsNetOK)
    {
        Serial.println("start httpserver");
        
       // httpserver->setup1(*gsmmanger->client, "82.156.1.111");
        httpserver->setup1(*gsmmanger->client, "iot.iris-rs.cn");
      //  httpserver->http1=new HttpClient(*gsmmanger->client, "82.156.1.111");
        
           
        
    }


   // Serial.println("start httpserver"+String(httpserver->http->iServerName));
    String Date = httpserver->getnetData();
    //String "1989-03-27 00:00:01";
    dateandtime tmtemp;
    tmtemp.year=Date.substring(0,4).toInt();
    tmtemp.month=Date.substring(5,7).toInt();
    tmtemp.day=Date.substring(8,10).toInt();
    tmtemp.hour=Date.substring(11,13).toInt();
    tmtemp.minute=Date.substring(14,16).toInt();
    tmtemp.second=Date.substring(17,19).toInt();
    setoffsettime(tmtemp);


    if (Date=="error")
    {
        Serial.println("getnetData failed,esp_restart");
        esp_restart();
        /* code */
    }
    
    Serial.println("date is :"+Date);
    String tem = fenge(Date," ",0);
    log_path = "/log/"+tem+".log";
    setpathforlog(log_path);
    log_data = Date+"\r\nSystem starts working.";
    write_log(log_path,10,"");
    write_log(log_path,10,log_data);
    write_log(log_path,10,"AIR780E Init Success.");
 


    gsmmanger->modem->sendAT(GF("+CGPIO=1,11,1"));  //点灯
    gsmmanger->modem->waitResponse("OK");
    
    // while (1)
    // {
    //     Serial.println(gsmmanger->GetDataAndTime());
    //     delay(1000);
    // }
    
    write_log(log_path,10,"GPS Init ....");
    for(int a = 0 ; a<100 ;a++)
    {
        String gpsbac = get_GPS();
        if (gpsbac != "-1")
        {
            Serial.println(gpsbac);
            write_log(log_path,10,"GPS Init Success.");
            break;
        }
        vTaskDelay(1000);
        
    } 
    vTaskDelay(1000);
    //////////////////////////////初始化http模块//////////////////////////////////////////////
     //http = new HttpClient(*gsmmanger->client, "82.156.1.111");
   if (IsNetOK)
    {
            ProgrameUper = new UpDateClassByme(httpserver->http1);
    }


    IS1Sensor.initSensor();
    String StationID = IS1Sensor.SensorInfo.serialnumber;
    String SensorID = IS1Sensor.SensorInfo.SensorName;
    if (IsNetOK)
    {
        ProgrameUper->initme(Curentvsion);
        ProgrameUper->StationID=StationID;
        ProgrameUper->CheckAndUpdate();
        write_log(log_path,10,"Http Init Success.");
        String Upheader = StationID + "##" + SensorID + "##" + String(IS1Sensor.SensorInfo.BandNum) + "##" + String(IS1Sensor.SensorInfo.a1,9) + ":" + String(IS1Sensor.SensorInfo.a2,9) + ":" + String(IS1Sensor.SensorInfo.a3,9) + ":" + String(IS1Sensor.SensorInfo.a4,9)+"##"+ProgrameUper->CurrentVersion;
          Serial.println(Upheader);
        httpserver->UpdateData(Http_Sensorinfo_UP_Path, (char *)Upheader.c_str(), Upheader.length());
    }

   // ProgrameUper->DownloadFirmwareForurl("");
    ////////////////////////////上传IS1设备信息//////////////////////////////////////////////

    //////////////////////////////初始化IS1///////////////////////////////////////////////////

    // String Date=getnetData();

     write_log(log_path,10,"IS1 Init ....");
     ///////////////////////////////////////////////////////////////////////////////////////
     //
   //httpserver-> http1->stop();

   //  ticker.attach(10 * 60, Reuploaddata2);
    write_log(log_path,10,"IS1 Init Success.");
    ///////////////////////////////////////////////////////////////////////////////////////

    log_data = "System Init Success";
   write_log(log_path,10,"-------------------------------------------------system has been restart-----------------------------------------------------");  

       // --- 转换为毫秒 ---
    const uint32_t WATCHDOG_TIMEOUT_MS = WATCHDOG_TIMEOUT_SECONDS * 1000;
    
    // ------------------- 配置 TWDT -------------------
    
    // 1. 定义配置结构体
    esp_task_wdt_config_t twdt_config = {
        .timeout_ms = WATCHDOG_TIMEOUT_MS,  // 设置超时时间（毫秒）
        
        // 监控核心 0 和核心 1 的空闲任务。
        // 在 Arduino 环境中，通常 loop() 运行在核心 1 上 (如果启用了双核)，
        // 核心 0 处理 WiFi/蓝牙/网络栈。监控两者是系统级别的健壮做法。
        // (1 << 0) | (1 << 1) == 0b11 == 3
        .idle_core_mask = (1 << 0) | (1 << 1), 
        
        // 当 TWDT 超时时，触发系统复位（false），而不是触发软件 panic（true）。
        .trigger_panic = false, 
    };
       esp_err_t err = esp_task_wdt_init(&twdt_config);
    if (err != ESP_OK) {
        Serial.printf("TWDT initialization failed: %s\n", esp_err_to_name(err));
        // 如果 TWDT 初始化失败，可能需要重启或报警
        return;
    }
    
    // 3. 将当前的 loop 任务（运行你的 getDateFromHttp 的任务）添加到 TWDT 监控列表
     loopTaskHandle = xTaskGetCurrentTaskHandle();

    if (esp_task_wdt_add(loopTaskHandle) != ESP_OK) {
        Serial.println("Failed to add loop task to TWDT!");
    } else {
        Serial.printf("TWDT initialized and monitoring loop task for %d ms (%d s)\n", 
                      WATCHDOG_TIMEOUT_MS, WATCHDOG_TIMEOUT_SECONDS);
    }
}
String lastdate="";
dateandtime temnow = {2025, 1, 1, 0, 0, 0};

void loop()
{
        if (xEventGroupGetBits(Eventgroup) & STOP_WORK_BIT)
    {
        Serial.println("system stop work NOW!!");


        xEventGroupClearBits(Eventgroup, STOP_WORK_BIT);
        xEventGroupWaitBits(Eventgroup, StART_WORK_BIT, pdTRUE, pdFALSE, portMAX_DELAY);
        Serial.println("system start work");

        /* code */
    }

    if(xEventGroupGetBits(Eventgroup) & START_MSC_BIT)
    {
        Serial.println("start msc now");
        xEventGroupClearBits(Eventgroup, START_MSC_BIT);
        setupmsc();
        while (1)
        {
            vTaskDelay(1000);
            esp_task_wdt_reset(); //手动喂狗
            /* code */
        }
        
    }

    
    String Date;

/////////////////NOW/////////////////////
    // String tem = fenge(Date," ",0);
    // log_path = "/log/"+tem+".txt";
    //write_log(log_path,10,"");
    //write_log(log_path,10,Date);

    String yuliang = String(myslave.getYuliang());
    delay(1010);
    // Serial.println("yuliang "+yuliang);
  
    write_log(log_path,10,"getYuliang :"+yuliang);

/////////////////NOW/////////////////////
    String yuliangfz = String(myslave.getYuliang()); 
    delay(1010);
    // Serial.println("fuzhao " + yuliangfz);

    log_data ="fuzhao :"+yuliangfz;
    write_log(log_path,10,log_data);

////////////////////////////NOW///////////////////////////
    myslave.getWehter();
    memcpy(windret,myslave.ret,17);
    float VV = (windret[3] * 256 + windret[4]) * 1.0 / 100;
    float DD = (windret[5] * 256 + windret[6]) * 1.0 / 10;
    float TT = (windret[7] * 256 + windret[8]) * 1.0 / 100;
    float HH = (windret[9] * 256 + windret[10]) * 1.0 / 100;
    long PP = (windret[13] * 256 + windret[14]) * 256 * 256 + (windret[11] * 256 + windret[12]);
    //Serial.println("VV:" + String(VV) + "DD:" + String(DD) + "TT:" + String(TT) + "HH:" + String(HH) + "PP:" + String(PP));
    write_log(log_path,10,"VV:" + String(VV) + "DD:" + String(DD) + "TT:" + String(TT) + "HH:" + String(HH) + "PP:" + String(PP));


////////////////////////////NOW///////////////////////////
    String temprature =String(myslave.getMLX());

    log_data ="wendu :"+temprature;
    write_log(log_path,10,log_data);
 
    ////sim 循环
    
    write_log(log_path,10,"start gsmmanger->loop()");
    if (IsNetOK)
    {
         gsmmanger->loop();
    }
    
   
#ifdef DINBIAO
        String Datenow1= httpserver->getnetData();
        Datenow =fenge(Datenow1, " ", 0) + "_" + fenge(fenge(Datenow1, " ", 1), ":", 0) + "_" + fenge(fenge(Datenow1, " ", 1), ":", 1) + "_" + fenge(fenge(Datenow1, " ", 1), ":", 2);
        IS1Sensor.PrintFunc=printbytcp;
#endif
    write_log(log_path,10,"start TakeOneJob()");
     esp_task_wdt_reset(); //手动喂狗
    IS1Sensor.TakeOneJob(); ////IS1采集一次
    String StationID = IS1Sensor.SensorInfo.serialnumber;
    String SensorID = IS1Sensor.SensorInfo.SensorName;

 esp_task_wdt_reset(); //手动喂狗

///////////////获取时间
////////通过GPS获取时间，如果获取失败就通过4G访问网页获取。如果获取成功那就对GPS数据进行分割解析出时间。
    String gpsbac;
    for(int i = 0 ;i < 5 ; i++)
    {
        write_log(log_path,10,"start getnetData()");
        if (IsNetOK)
        {
           Date = httpserver->getnetData();  
        }else{
            Date="error";
        }
        
        
        if(Date == "error")
        {
            write_log(log_path,10,"start get_GPS()");
            Date = get_GPS(); 
            if(Date != "-1" & IsNetOK) 
            {
                break;
                if(hassend == 0)
                {
                    gpsbac = StationID+"#"+Date;
                    int lennn = gpsbac.length();
                    char *temp = new char[lennn];
                    memcpy(temp, gpsbac.c_str(),  gpsbac.length());
                    bool flagsucc = httpserver->UpdateData(Http_Station_GPS_INfo_Path, temp, lennn);

                    if (!flagsucc)
                    {
                    // sdcard::WriteStringToFile(nameoffile, temp, lennn);
                    }
                    else{
                
                    write_log(log_path,10,"Finish Put StationGPSinfo Data");
                    }
                    delete[] temp;
                
                }
                if(hassend >= 0)
                {
                    hassend--;
                }
            }
            else
            {
                Date=getlocaltime();
               // break;
            }

        }
        else
        {
               break;
        }
        if (i==200)
        {
            write_log(log_path,10," get_GPS and getnetData failed,esp_restart");
            esp_restart();
        }
        vTaskDelay(500);
        
    }
     esp_task_wdt_reset(); //手动喂狗
    temnow.year=Date.substring(0,4).toInt();
    temnow.month=Date.substring(5,7).toInt();
    temnow.day=Date.substring(8,10).toInt();
    temnow.hour=Date.substring(11,13).toInt();
    temnow.minute=Date.substring(14,16).toInt();
    temnow.second=Date.substring(17,19).toInt();
    setoffsettime(temnow);
    write_log(log_path,10,"Date is : "+Date);
    // delay(15000);
    if (fenge(Date, " ", 0)!=lastdate)
    {
        lastdate=fenge(Date, " ", 0);
        log_path = "/log/"+lastdate+".log";
        setpathforlog(log_path);
        myslave.claeryuliang();
        if(IsNetOK)
        { ProgrameUper->CheckAndUpdate();}
       

    }

    /////////*获取相关信息*//////////////////////////
    String datestring=fenge(Date, " ", 0) + "_" + fenge(fenge(Date, " ", 1), ":", 0) + "_" + fenge(fenge(Date, " ", 1), ":", 1) + "_" + fenge(fenge(Date, " ", 1), ":", 2);
    String Upheader = Date + "##" + StationID + "##" + SensorID + "##" + "UP" + "##"+String(IS1Sensor.shutterup)+"##";
    String Upname = "/up/" +datestring+ "_" + StationID + "_" + SensorID + "_" + "UP";
    String Downheader = Date + "##" + StationID + "##" + SensorID + "##" + "DOWN" + "##"+String(IS1Sensor.shutterdown)+"##";
    String Downname = "/down/" + datestring + "_" + StationID + "_" + SensorID + "_" + "DOWN";
    String senderID = Date + "##" + StationID + "##" + SensorID + "##" + String(temprature) + "##"+yuliang+"##"+yuliangfz+"##";
    String othername = "/other/" +datestring + "_" + StationID + "_" + SensorID + "_" + String(temprature);
    // Serial.println(senderID);
    // Serial.println( Upheader);
    // Serial.println(Upheader.length());

    //////////////////////上传up数据//////////////////
    write_log(log_path,10,"put up data");
    size_t lennn = IS1Sensor.SensorInfo.BandNum * 2 + Upheader.length();
    char *temp = new char[IS1Sensor.SensorInfo.BandNum * 2 + Upheader.length()];
    memcpy(temp, Upheader.c_str(), Upheader.length());
    char *str=(char *)IS1Sensor.UpData;
    int lenofis=IS1Sensor.SensorInfo.BandNum * 2 ;
     for (size_t i = 0; i < IS1Sensor.SensorInfo.BandNum * 2; i++)
     {
        //temp[Upheader.length()+i]=str[i];
     }
    // Serial.println("lenth of up data is "+String(lennn));
    write_log(log_path,10,"lenth of up data is "+String(lennn));
    memcpy(temp + Upheader.length(), IS1Sensor.UpData,IS1Sensor.SensorInfo.BandNum * 2);
    bool flagsucc = httpserver->UpdateData(Http_Sepctral_Path, temp, lennn);
     //输出前100个字节 字符
esp_task_wdt_reset(); //手动喂狗
    // Serial.println("temp is :");
    // Serial.write(temp, 100);
    // write_log(log_path,10,"temp is :");

    // for (int i = 0; i < 100 && i < lennn; i++)
    // {
    //     Serial.print(temp[i], HEX);
    //     Serial.print(" ");
    // }
    String log_temp="temp is :";
    for (int i = 0; i < 100 && i < lennn; i++)
    {
        log_temp+=String(temp[i], HEX)+" ";
    }
    write_log(log_path,10,log_temp);
     

    vTaskDelay(3000);
    if (!flagsucc)
    {
        //计算md5并保存 为读取时判断数据是否正确
        MD5Builder md5my;
        md5my.begin();
        md5my.add((uint8_t *)temp, lennn);
        md5my.calculate();
        String md5string = md5my.toString();
        sdcard::lock();
        sdcard::WriteStringToFile(Upname, temp, lennn);
        sdcard::WriteStringToFile(Upname + ".md5", (char *)md5string.c_str(), md5string.length());
        sdcard::unlock();
        

        log_data ="Up_data upload failed,save to SD. md5 is"+md5string;
        write_log(log_path,10,log_data);
    }
    else
    {
      
        write_log(log_path,10,"finish Put Up Data");
        log_data ="finish Put Up Data.";
        write_log(log_path,10,log_data);
    }
    delete[] temp;
    


    //////////////////////上传Down数据//////////////////
    write_log(log_path,0,"put dowm data");
    lennn = IS1Sensor.SensorInfo.BandNum * 2 + Downheader.length();
    temp = new char[lennn];
    memcpy(temp, Downheader.c_str(), Downheader.length());
    str=(char *)IS1Sensor.DownData;
    lenofis=IS1Sensor.SensorInfo.BandNum * 2 ;
    for (size_t i = 0; i < IS1Sensor.SensorInfo.BandNum * 2; i++)
    {
        //  temp[Downheader.length()+i]=str[i];
    }

    write_log(log_path,10,"lenth of down data is "+String(lennn));
    memcpy(temp + Downheader.length(), IS1Sensor.DownData,IS1Sensor.SensorInfo.BandNum * 2);
    flagsucc = httpserver->UpdateData(Http_Sepctral_Path, temp, lennn);
    esp_task_wdt_reset(); //手动喂狗
    vTaskDelay(3000);
    String log_temp1="down data is :";
    for (int i = 0; i < 100 && i < lennn; i++)
    {
        log_temp1+=String(temp[i], HEX)+" ";
    }
    write_log(log_path,0,log_temp1);




    if (!flagsucc)
    {
        //计算md5并保存 为读取时判断数据是否正确
        MD5Builder md5my;
        md5my.begin();
        md5my.add((uint8_t *)temp, lennn);
        md5my.calculate();
        String md5string = md5my.toString();
        sdcard::lock();
        sdcard::WriteStringToFile(Downname, temp, lennn);
        sdcard::unlock();
        sdcard::WriteStringToFile(Downname + ".md5", (char *)md5string.c_str(), md5string.length());
        log_data ="Down_data upload failed,save to SD. md5 is"+md5string;
        write_log(log_path,10,log_data);
    }else{

        log_data ="finish Put Down Data.";
        write_log(log_path,10,log_data);
    }
    delete[] temp;
    
    //////////////////////上传其他数据//////////////////
    lennn = 12 + senderID.length();
    temp = new char[lennn];
    memcpy(temp, senderID.c_str(),  senderID.length());
    memcpy(temp + senderID.length(), windret + 3, 12);
    flagsucc = httpserver->UpdateData(Http_Wind_Path, temp, lennn, "application/json");
    esp_task_wdt_reset(); //手动喂狗
    vTaskDelay(3000);
    if (!flagsucc)
    {
        // 计算md5并保存 为读取时判断数据是否正确
        MD5Builder md5my;
        md5my.begin();
        md5my.add((uint8_t *)temp, lennn);
        md5my.calculate();
        String md5string = md5my.toString();
        
        sdcard::lock();
        sdcard::WriteStringToFile(othername, temp, lennn);
        sdcard::WriteStringToFile(othername + ".md5", (char *)md5string.c_str(), md5string.length());
        sdcard::unlock();
        log_data="other_data upload failed.save to sd";
        write_log(log_path,10,log_data);
    }else{
        log_data ="finish Put Other Data.";
        write_log(log_path,10,log_data);
    }
    delete[] temp;
    if (0)
    
    {
        String onelinestr="";
        onelinestr="date:"+Date+",upshutter:"+String(IS1Sensor.shutterup)+",downshutter:"+String(IS1Sensor.shutterdown)+",StationID:"+StationID+"\n";
        String fodernamer=fenge(Date, " ", 0);
        sdcard::lock();
        sdcard::Mkdir("/Data");
        sdcard::Mkdir("/Data/"+fodernamer);
        sdcard::unlock();
        onelinestr+="UPDN,";
        for (size_t i = 0; i < IS1Sensor.SensorInfo.BandNum; i++)
        {
            onelinestr+=String(IS1Sensor.UpData[i*2]*256+IS1Sensor.UpData[i*2+1]);
            if (i!=IS1Sensor.SensorInfo.BandNum-1)
            {
                onelinestr+=",";
            }
            
        }
        onelinestr+="\n";
        onelinestr+="DOWNDN,";
        for (size_t i = 0; i < IS1Sensor.SensorInfo.BandNum; i++)
        {
            onelinestr+=String(IS1Sensor.DownData[i*2]*256+IS1Sensor.DownData[i*2+1]);
            if (i!=IS1Sensor.SensorInfo.BandNum-1)
            {
                onelinestr+=",";
            }
            
        }
        onelinestr+="\n";
        sdcard::lock();

            sdcard::WriteStringToFile("/Data/"+fodernamer+"/"+datestring+".csv", (char *)onelinestr.c_str(), onelinestr.length());
        sdcard::unlock();

    }
    

    //结束并等待一定时间
    // http->stop(); delay(100);return;
    esp_task_wdt_reset(); //手动喂狗
    delay(120000);
    esp_task_wdt_reset(); //手动喂狗
#ifdef DINBIAO
    abort();
    ESP.restart();
#endif 
    return;
}





