diff --git a/src/SDmanger copy.cppback b/src/SDmanger copy.cppback new file mode 100644 index 0000000..61c8d77 --- /dev/null +++ b/src/SDmanger copy.cppback @@ -0,0 +1,289 @@ +#include"SDmanger.h" +File Comenfile; + +int sdcard::init_sdcard() +{ + SD_MMC.setPins(9,10,11,12,13,14); + int succ = SD_MMC.begin("/sdcard", true,true,150); + if (succ) { + Serial.printf("SD_MMC Begin: %d\n", succ); + uint8_t cardType = SD_MMC.cardType(); + Serial.print("SD_MMC Card Type: "); + if (cardType == CARD_MMC) { + Serial.println("MMC"); + } else if (cardType == CARD_SD) { + Serial.println("SDSC"); + } else if (cardType == CARD_SDHC) { + Serial.println("SDHC"); + } else { + Serial.println("UNKNOWN"); + } + + uint64_t cardSize = SD_MMC.cardSize() / (1024 * 1024); + Serial.printf("SD_MMC Card Size: %lluMB\n", cardSize); + + } else { + Serial.printf("Failed to mount SD card VFAT filesystem. \n"); + Serial.println("Do you have an SD Card installed?"); + Serial.println("Check pin 12 and 13, not grounded, or grounded with 10k resistors!\n\n"); + // major_fail(); + } + + return ESP_OK; +} + + void sdcard::mylistDir( const char * dirname, uint8_t levels) { + + Serial.printf("Listing directory: %s\n", "/"); + String dir(dirname); + File root = SD_MMC.open(dirname); + if (!root) { + Serial.println("Failed to open directory"); + return; + } + if (!root.isDirectory()) { + Serial.println("Not a directory"); + return; + } + + File filex = root.openNextFile(); + while (filex) { + if (filex.isDirectory()) + { + Serial.print(" DIR : "); + Serial.println(filex.name()); + if (levels) { + String filename=dir+"/"+String(filex.name()); + mylistDir( filename.c_str(), levels - 1); + } + } + else + { + Serial.print(" FILE: "); + Serial.print(filex.name()); + Serial.print(" SIZE: "); + Serial.println(filex.size()); + } + filex = root.openNextFile(); + } +} +bool sdcard::ListDir(const char * dirname,Vector &stringlist) +{ + stringlist.clear(); + + + String dir(dirname); + File root = SD_MMC.open(dirname); + if (!root) { + Serial.println("Failed to open directory"); + return true; + } + if (!root.isDirectory()) { + Serial.println("Not a directory"); + return true; + } + + File filex = root.openNextFile(); + while (filex) + { + if (filex.isDirectory()) { + + } else { + String filename=dir+"/"+String(filex.name()); + stringlist.push_back(filename); + + if (stringlist.size()==stringlist.max_size()) + { + + return false; + /* code */ + } + + } + filex = root.openNextFile(); + } + + return true; + +} + + + void sdcard::delete_old_stuff() { + + Serial.printf("Total space: %lluMB\n", SD_MMC.totalBytes() / (1024 * 1024)); + Serial.printf("Used space: %lluMB\n", SD_MMC.usedBytes() / (1024 * 1024)); + + //listDir( "/", 0); + + float full = 1.0 * SD_MMC.usedBytes() / SD_MMC.totalBytes();; + if (full < 0.8) { + Serial.printf("Nothing deleted, %.1f%% disk full\n", 100.0 * full); + } else { + Serial.printf("Disk is %.1f%% full ... deleting oldest file\n", 100.0 * full); + while (full > 0.8) { + + double del_number = 999999999; + char del_numbername[50]; + + File f = SD_MMC.open("/"); + + File file = f.openNextFile(); + + while (file) { + //Serial.println(file.name()); + if (!file.isDirectory()) { + + char foldname[50]; + strcpy(foldname, file.name()); + for ( int x = 0; x < 50; x++) { + if ( (foldname[x] >= 0x30 && foldname[x] <= 0x39) || foldname[x] == 0x2E) { + } else { + if (foldname[x] != 0) foldname[x] = 0x20; + } + } + + double i = atof(foldname); + if ( i > 0 && i < del_number) { + strcpy (del_numbername, file.name()); + del_number = i; + } + //Serial.printf("Name is %s, number is %f\n", foldname, i); + } + file = f.openNextFile(); + + } + Serial.printf("lowest is Name is %s, number is %f\n", del_numbername, del_number); + if (del_number < 999999999) { + deleteFolderOrFile(del_numbername); + } + full = 1.0 * SD_MMC.usedBytes() / SD_MMC.totalBytes(); + Serial.printf("Disk is %.1f%% full ... \n", 100.0 * full); + f.close(); + } + } +} + + void sdcard::deleteFolderOrFile(const char * val) { + // Function provided by user @gemi254 + Serial.printf("Deleting : %s\n", val); + File f = SD_MMC.open(val); + if (!f) { + Serial.printf("Failed to open %s\n", val); + return; + } + + if (f.isDirectory()) { + File file = f.openNextFile(); + while (file) { + if (file.isDirectory()) { + Serial.print(" DIR : "); + Serial.println(file.name()); + } else { + Serial.print(" FILE: "); + Serial.print(file.name()); + Serial.print(" SIZE: "); + Serial.print(file.size()); + if (SD_MMC.remove(file.name())) { + Serial.println(" deleted."); + } else { + Serial.println(" FAILED."); + } + } + file = f.openNextFile(); + } + f.close(); + //Remove the dir + if (SD_MMC.rmdir(val)) { + Serial.printf("Dir %s removed\n", val); + } else { + Serial.println("Remove dir failed"); + } + + } else { + //Remove the file + if (SD_MMC.remove(val)) { + Serial.printf("File %s deleted\n", val); + } else { + Serial.println("Delete failed"); + } + } +} + + void sdcard:: testwriet() +{ + File file; + file = SD_MMC.open("/gps/try.txt", "wb"); + file.println("hello world"); + file.flush(); + file.close(); +} + + + + void sdcard::WriteStringToFile(String name,String Str) + { + File file; + + file = SD_MMC.open(name, "w+"); + file.println(Str); + file.flush(); + file.close(); + } + void sdcard::WriteStringToFile(String name,char *data,size_t lenth) + { + File file; + + file = SD_MMC.open(name, "wb"); + file.write((const byte *)data,lenth); + file.flush(); + file.close(); + } + bool sdcard::Mkdir(String path) + { + return SD_MMC.mkdir(path); + } + +namespace sdcard +{ + void openFileformWirte(String Path) + { + if (Comenfile.available()) + { + Comenfile.close(); + /* code */ + } + Comenfile = SD_MMC.open(Path, "w+"); + + } + + void WritetoFileCommen(String Str) + { + if (Comenfile.available()) + { + Comenfile.print(Str); + Comenfile.flush(); + /* code */ + } + } + + void WritetoFileCommen(char *data,size_t lenth) + { + if (Comenfile.available()) + { + Comenfile.write((const byte *)data,lenth); + Comenfile.flush(); + /* code */ + } + + } + + void closeCommenFile() + { + if (Comenfile.available()) + { + Comenfile.close(); + /* code */ + } + + } +} \ No newline at end of file diff --git a/src/main2.cppback b/src/main2.cppback new file mode 100644 index 0000000..4dceaa3 --- /dev/null +++ b/src/main2.cppback @@ -0,0 +1,543 @@ +#include"Define.h" +#include + +#include +#include "SensorOptoSky.h" +#include +#include +#include +//#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 + +#define LOGGING +//myPort将原来ESP8266对内通讯改为,485对内的通讯 +// #define MYPORT_TX 45 +// #define MYPORT_RX 46 +int hassend = 0; +GSMMannger *gsmmanger; +UpDateClassByme *ProgrameUper; + + +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); +} + + + +String Datenow=""; +void printbytcp(String str) +{ + //tcpserver.SendDataToClinet(str); + Serial.println(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"); +////////////////////////////////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)); +} + + +String get_GPS(void) +{ + Serial.println("check GPS..."); + gsmmanger->modem->sendAT(GF("+CGNSPWR?")); + gsmmanger->modem->waitResponse("OK"); + + Serial.println("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"); + + Serial.println("get GNSS..."); + 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"; + } + + Serial.println(gpsbac); + write_log(log_path,10,"gpsdate:"+Date); + return Date; +} +// String get_ti() +// { +// return gsmmanger->modem->getNetworkTime; +// } +#include "esp_task_wdt.h" +void setup() +{ + +esp_task_wdt_init(20, true); + Serial.begin(115200); + Serial.println("start"); + //return; + Serial.println(Curentvsion); + sdcard::init_sdcard(); + sdcard::testwriet(); + sdcard::Mkdir("/up"); + sdcard::Mkdir("/down"); + sdcard::Mkdir("/other"); + sdcard::Mkdir("/gps"); + sdcard::Mkdir("/log"); + + beginWIFI(); + // sdcard::mylistDir("/",2); + { + } + // pinMode(21, OUTPUT); + // digitalWrite(21, HIGH); + pinMode(beePin, OUTPUT); + ledcSetup(BeeChain, 220, 8); + ledcAttachPin(beePin, 0); + 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(); + + 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(); + 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"; + 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; + + + ProgrameUper->initme(Curentvsion); + ProgrameUper->StationID=StationID; + ProgrameUper->CheckAndUpdate(); + write_log(log_path,10,"Http Init Success."); + // ProgrameUper->DownloadFirmwareForurl(""); + ////////////////////////////上传IS1设备信息////////////////////////////////////////////// + + //////////////////////////////初始化IS1/////////////////////////////////////////////////// + + // String Date=getnetData(); + 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()); + write_log(log_path,10,"IS1 Init ...."); + /////////////////////////////////////////////////////////////////////////////////////// + // + httpserver-> http1->stop(); + ticker.attach(60 * 60, Reuploaddata2); + write_log(log_path,10,"IS1 Init Success."); + /////////////////////////////////////////////////////////////////////////////////////// + + log_data = "System Init Success"; + write_log(log_path,10,log_data); + // Serial.println(gsmmanger->GetDataAndTime()); +} +String lastdate=""; +void loop() +{ + 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()); + Serial.println("wendu"); + Serial.println(temprature); + log_data ="wendu :"+temprature; + write_log(log_path,10,log_data); + + ////sim 循环 + + write_log(log_path,10,"start gsmmanger->loop()"); + 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()"); + IS1Sensor.TakeOneJob(); ////IS1采集一次 + String StationID = IS1Sensor.SensorInfo.serialnumber; + String SensorID = IS1Sensor.SensorInfo.SensorName; + +///////////////获取时间 +////////通过GPS获取时间,如果获取失败就通过4G访问网页获取。如果获取成功那就对GPS数据进行分割解析出时间。 + String gpsbac; + for(int i = 0 ;i < 5 ; i++) + { + write_log(log_path,10,"start getnetData()"); + Date = httpserver->getnetData(); + if(Date == "error") + { + write_log(log_path,10,"start get_GPS()"); + Date = get_GPS(); + if(Date != "-1") + { + 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{ + Serial.println("Finish Put StationGPSinfo Data"); + } + delete[] temp; + + } + if(hassend >= 0) + { + hassend--; + } + } + else + { + // break; + } + + } + else + { + break; + } + if (i==200) + { + write_log(log_path,10," get_GPS and getnetData failed,esp_restart"); + esp_restart(); + } + vTaskDelay(500); + + } + write_log(log_path,10,"Date is : "+Date); + // delay(15000); + if (fenge(Date, " ", 0)!=lastdate) + { + lastdate=fenge(Date, " ", 0); + log_path = "/log/"+lastdate+".log"; + myslave.claeryuliang(); + 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)); + memcpy(temp + Upheader.length(), IS1Sensor.UpData,IS1Sensor.SensorInfo.BandNum * 2); + bool flagsucc = httpserver->UpdateData(Http_Sepctral_Path, temp, lennn); + //输出前100个字节 字符 + + Serial.println("temp is :"); + Serial.write(temp, 100); + + for (int i = 0; i < 100 && i < lennn; i++) + { + Serial.print(temp[i], HEX); + Serial.print(" "); + } + + + vTaskDelay(3000); + if (!flagsucc) + { + sdcard::WriteStringToFile(Upname, temp, lennn); + log_data ="Up_data upload failed,save to SD."; + write_log(log_path,10,log_data); + } + else + { + Serial.println("finish Put Up Data"); + log_data ="finish Put Up Data."; + write_log(log_path,10,log_data); + } + delete[] temp; + + + + //////////////////////上传Down数据////////////////// + write_log(log_path,10,"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]; + } + Serial.println("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); + vTaskDelay(3000); + //输出前100个 + Serial.println("temp is :"); + Serial.write(temp, 100); + + + if (!flagsucc) + { + sdcard::WriteStringToFile(Downname, temp, lennn); + log_data ="Down_data upload failed,save to SD."; + write_log(log_path,10,log_data); + }else{ + Serial.println("finish Put Down Data"); + 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"); + vTaskDelay(3000); + if (!flagsucc) + { + sdcard::WriteStringToFile(othername, temp, lennn); + log_data ="put Other Data failed,save to SD."; + write_log(log_path,10,log_data); + }else{ + Serial.println("finish Put Other Data"); + log_data ="finish Put Other Data."; + write_log(log_path,10,log_data); + } + delete[] temp; + + + //结束并等待一定时间 + // http->stop(); delay(100);return; + + delay(120000); +#ifdef DINBIAO + abort(); + ESP.restart(); +#endif + return; +} + + + + + diff --git a/src/mymsc.cpp b/src/mymsc.cpp new file mode 100644 index 0000000..c3aa2e3 --- /dev/null +++ b/src/mymsc.cpp @@ -0,0 +1,100 @@ +// #if !SOC_USB_OTG_SUPPORTED || ARDUINO_USB_MODE +// #error Device does not support USB_OTG or native USB CDC/JTAG is selected +// #endif + +#include +#include +#include + +// USB Mass Storage Class (MSC) object +USBMSC msc; + + + +static int32_t onWrite(uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) { + uint32_t secSize = SD_MMC.sectorSize(); + if (!secSize) { + return false; // disk error + } + //log_v("Write lba: %ld\toffset: %ld\tbufsize: %ld", lba, offset, bufsize); + // Serial.printf("Write lba: %ld\toffset: %ld\tbufsize: %ld\n", lba, offset, bufsize); + for (int x = 0; x < bufsize / secSize; x++) { + uint8_t blkbuffer[secSize]; + memcpy(blkbuffer, (uint8_t *)buffer + secSize * x, secSize); + if (!SD_MMC.writeRAW(blkbuffer, lba + x)) { + return false; + } + } + return bufsize; +} + +static int32_t onRead(uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) { + uint32_t secSize = SD_MMC.sectorSize(); + if (!secSize) { + return false; // disk error + } + //log_v("Read lba: %ld\toffset: %ld\tbufsize: %ld\tsector: %lu", lba, offset, bufsize, secSize); + //Serial.printf("Read lba: %ld\toffset: %ld\tbufsize: %ld\tsector: %lu\n", lba, offset, bufsize, secSize); + for (int x = 0; x < bufsize / secSize; x++) { + if (!SD_MMC.readRAW((uint8_t *)buffer + (x * secSize), lba + x)) { + return false; // outside of volume boundary + } + } + return bufsize; +} + +static bool onStartStop(uint8_t power_condition, bool start, bool load_eject) { + log_i("Start/Stop power: %u\tstart: %d\teject: %d", power_condition, start, load_eject); + return true; +} + +static void usbEventCallback(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { + if (event_base == ARDUINO_USB_EVENTS) { + arduino_usb_event_data_t *data = (arduino_usb_event_data_t *)event_data; + switch (event_id) { + case ARDUINO_USB_STARTED_EVENT: Serial.println("USB PLUGGED"); break; + case ARDUINO_USB_STOPPED_EVENT: Serial.println("USB UNPLUGGED"); break; + case ARDUINO_USB_SUSPEND_EVENT: Serial.printf("USB SUSPENDED: remote_wakeup_en: %u\n", data->suspend.remote_wakeup_en); break; + case ARDUINO_USB_RESUME_EVENT: Serial.println("USB RESUMED"); break; + + default: break; + } + } +} + +void setupmsc() { +// Serial.begin(115200); + Serial.println("Starting Serial"); + + Serial.println("Mounting SDcard"); + // SD_MMC.setPins(clk, cmd, d0, d1, d2, d3); + // if (!SD_MMC.begin("/sdcard", onebit)) { + // Serial.println("Mount Failed"); + // return; + // } + + Serial.println("Initializing MSC"); + // Initialize USB metadata and callbacks for MSC (Mass Storage Class) + msc.vendorID("ESP32123"); + msc.productID("USB_MSC123"); + msc.productRevision("1.0"); + msc.onRead(onRead); + msc.onWrite(onWrite); + msc.onStartStop(onStartStop); + msc.mediaPresent(true); + msc.begin(SD_MMC.numSectors(), SD_MMC.sectorSize()); + + Serial.println("Initializing USB"); + Serial.printf("Card Size: %lluMB\n", SD_MMC.totalBytes() / 1024 / 1024); + Serial.printf("Sector: %d\tCount: %d\n", SD_MMC.sectorSize(), SD_MMC.numSectors()); + vTaskDelay(5000); + USB.begin(); + USB.onEvent(usbEventCallback); + + // Serial.printf("Card Size: %lluMB\n", SD_MMC.totalBytes() / 1024 / 1024); + // Serial.printf("Sector: %d\tCount: %d\n", SD_MMC.sectorSize(), SD_MMC.numSectors()); +} + +// void loop() { +// delay(-1); +// } \ No newline at end of file diff --git a/src/mymsc.h b/src/mymsc.h new file mode 100644 index 0000000..c9a0f0f --- /dev/null +++ b/src/mymsc.h @@ -0,0 +1 @@ +void setupmsc() ; \ No newline at end of file diff --git a/src/serilaFS.cpp b/src/serilaFS.cpp new file mode 100644 index 0000000..62bcadd --- /dev/null +++ b/src/serilaFS.cpp @@ -0,0 +1,284 @@ +#include "serilaFS.h" +#include +#include "SDmanger.h" +#include +#include "mymsc.h" +Stream *Serilaforfs = nullptr; +bool ListDir(const char *dirname) +{ + String dir(dirname); + File root = SD_MMC.open(dirname); + if (!root) + { + Serial.println("Failed to open directory"); + return true; + } + if (!root.isDirectory()) + { + Serial.println("Not a directory"); + return true; + } + Serilaforfs->println("------------------------------------ " + dir + "------------------------------------"); + if (dir == "/") + { + dir = ""; + /* code */ + } + + File filex = root.openNextFile(); + int i = 0; + while (filex) + { + if (filex.isDirectory()) + { + + Serial.println(dir + "/" + String(filex.name())); + } + else + { + + Serial.println(dir + "/" + String(filex.name()) + "\t Size:" + String(filex.size() / 1024) + " Kb"); + } + vTaskDelay(1); + Serial.flush(); + filex = root.openNextFile(); + i++; + if (i % 20 == 0) + { + vTaskDelay(1); + }; + } + + return true; +} + +void deleteFolderOrFile(const char *val) +{ + // Function provided by user @gemi254 + Serial.printf("Deleting : %s\n", val); + File f = SD_MMC.open(val); + if (!f) + { + Serial.printf("Failed to open %s\n", val); + return; + } + + if (f.isDirectory()) + { + File file = f.openNextFile(); + while (file) + { + if (file.isDirectory()) + { + Serial.print(" DIR : "); + Serial.println(file.name()); + } + else + { + Serial.print(" FILE: "); + Serial.print(file.name()); + Serial.print(" SIZE: "); + Serial.print(file.size()); + if (SD_MMC.remove(file.name())) + { + Serial.println(" deleted."); + } + else + { + Serial.println(" FAILED."); + } + } + file = f.openNextFile(); + } + f.close(); + // Remove the dir + if (SD_MMC.rmdir(val)) + { + Serial.printf("Dir %s removed\n", val); + } + else + { + Serial.println("Remove dir failed"); + } + } + else + { + // Remove the file + if (SD_MMC.remove(val)) + { + Serial.printf("File %s deleted\n", val); + } + else + { + Serial.println("Delete failed"); + } + } +} + +void GetFile(const char *filepath) +{ + String path(filepath); + File file = SD_MMC.open(filepath, "rb"); + if (!file || file.isDirectory()) + { + Serial.println("Error: File not found or is a directory"); + return; + } + Serial.println("File Size: " + String(file.size() / 1024) + " Kb"); + const size_t bufferSize = 512; + uint8_t buffer[bufferSize]; + size_t bytesRead; + while ((bytesRead = file.read(buffer, bufferSize)) > 0) + { + Serilaforfs->write(buffer, bytesRead); + // 延时一下防止阻塞 + vTaskDelay(1); + } + file.close(); + Serilaforfs->println("\n--- End of File ---"); +} + +void TaskSerialFS(void *pvParameters) +{ + Serilaforfs = &Serial; + if (Serilaforfs == nullptr) + vTaskDelete(NULL); + ; + + while (1) + { + // vTaskDelay(1); + // Serilaforfs->println("SerilaFS Task Running..."); + // Serial.printf("SerilaFS Command Recv : "); + if (Serilaforfs->available()) + { + + // Serial.println("SerilaFS Command Recv : "); + String command = Serilaforfs->readStringUntil('\n'); + command.trim(); // 去除命令字符串的前后空白字符 + // 命令格式 command 参数1 command 有 ls 及 get 两种 先分割 rm + int spaceIndex = command.indexOf(' '); + String cmd; + String param; + if (spaceIndex != -1) + { + cmd = command.substring(0, spaceIndex); + param = command.substring(spaceIndex + 1); + } + else + { + cmd = command; // 如果没有参数,整个字符串就是命令 + param = "/"; + } + // 如果param不是./开头 返回错误 + if (!param.startsWith("/")) + { + Serilaforfs->println("Error: Path must start with ./"); + vTaskDelay(1); + continue; + ; + } + if (cmd == "ls") + { + + sdcard::lock(); + ListDir(param.c_str()); + sdcard::unlock(); + } + if (cmd == "get") + { + sdcard::lock(); + GetFile(param.c_str()); + sdcard::unlock(); + Serilaforfs->println("\n--- End of File ---"); + } + if (cmd == "rm") + { + sdcard::lock(); + if (SD_MMC.remove(param.c_str())) + { + Serilaforfs->printf("File %s deleted\n", param.c_str()); + } + else + { + Serilaforfs->println("Delete failed"); + } + sdcard::unlock(); + } + if (cmd == "rmdir") + { + sdcard::lock(); + if (SD_MMC.rmdir(param.c_str())) + { + Serilaforfs->printf("Dir %s deleted\n", param.c_str()); + } + else + { + Serilaforfs->println("Remove dir failed"); + } + sdcard::unlock(); + } + if (cmd == "rmdirfiles") + { + sdcard::lock(); + sdcard::deleteFolderOrFile(param.c_str()); + sdcard::unlock(); + } + if (cmd == "msc") + { + Serilaforfs->println("start msc wait for mount sdcard"); + xEventGroupSetBits(Eventgroup, START_MSC_BIT); + } + + if (cmd == "stop") + { + Serilaforfs->println("waiting for stop work"); + xEventGroupSetBits(Eventgroup, STOP_WORK_BIT); + } + if (cmd == "start") + { + xEventGroupSetBits(Eventgroup, StART_WORK_BIT); + } + if (cmd == "format") + { + String passwd=param; + if(passwd!="/iris") + { + Serilaforfs->println("Error: Wrong password for format sdcard"); + vTaskDelay(1); + continue; + } + Serilaforfs->println("Start format sdcard"); + sdcard::lock(); + sdcard::formatSDCard(); + sdcard::unlock(); + Serilaforfs->println("Format sdcard completed"); + //重启 + ESP.restart(); + } + if (cmd == "help" || cmd == "?" || cmd == "h") + { + Serilaforfs->println("Command List:"); + Serilaforfs->println("ls - List files in directory"); + Serilaforfs->println("get - Get file content"); + Serilaforfs->println("rm - Remove file"); + Serilaforfs->println("rmdir - Remove directory"); + Serilaforfs->println("rmdirfiles - Remove directory and all its contents"); + Serilaforfs->println("msc - Start Mass Storage Class (MSC) mode"); + Serilaforfs->println("format - Format the SD card (password required)"); + Serilaforfs->println("help - Show this help message"); + Serilaforfs->println("stop - Stop system work"); + Serilaforfs->println("start - Start system work"); + } + + /* code */ + } + + vTaskDelay(1); + /* code */ + } + + Serial.println("TaskSerialFS exit"); + vTaskDelay(1); + vTaskDelete(NULL); +} diff --git a/src/serilaFS.h b/src/serilaFS.h new file mode 100644 index 0000000..abaea82 --- /dev/null +++ b/src/serilaFS.h @@ -0,0 +1,3 @@ + + +void TaskSerialFS(void *pvParameters); \ No newline at end of file