SPIFFS 是一个用于 SPI NOR flash 设备的嵌入式文件系统,支持磨损均衡、文件系统一致性检查等功能。
//初始化spiffs
void init_spiffs(void){
Serial.println("Initializing SPIFFS");
//挂载spiffs文件,挂载之后可以使用C库进行读写文件
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
Serial.println("Failed to mount or format filesystem");
} else if (ret == ESP_ERR_NOT_FOUND) {
Serial.println("Failed to find SPIFFS partition");
} else {
Serial.println("Failed to initialize SPIFFS");
}
return;
}
//这部分可以暂时不看
#ifdef CONFIG_EXAMPLE_SPIFFS_CHECK_ON_START
Serial.println("Performing SPIFFS_check().");
ret = esp_spiffs_check(conf.partition_label);
if (ret != ESP_OK) {
Serial.println("SPIFFS_check() failed");
return;
} else {
Serial.println("SPIFFS_check() successful");
}
#endif
//获取文件系统已经使用的大小和剩余大小
size_t total = 0, used = 0;
ret = esp_spiffs_info(conf.partition_label, &total, &used);
if (ret != ESP_OK) {
Serial.println("Failed to get SPIFFS partition information. Formatting...");
esp_spiffs_format(conf.partition_label);
return;
} else {
Serial.printf("Partition size: total: %d, used: %d", total, used);
Serial.println();
}
#
// 检查分区大小信息
if (used > total) {
Serial.println("Number of used bytes cannot be larger than total. Performing SPIFFS_check().");
ret = esp_spiffs_check(conf.partition_label);
// 也可以用来修复损坏的文件,清理未引用的页面等。
// More info at https://github.com/pellepl/spiffs/wiki/FAQ#powerlosses-contd-when-should-i-run-spiffs_check
if (ret != ESP_OK) {
Serial.println("SPIFFS_check() failed");
return;
} else {
Serial.println("SPIFFS_check() successful");
}
}
}
void write_log(std::string testmsg){
testmsg += "<br>";
size_t total = 0, used = 0;
FILE* f;
esp_err_t ret = esp_spiffs_info(conf.partition_label, &total, &used);
Serial.printf("Partition size: total: %d, used: %d", total, used);
Serial.println();
if (used > 10240){
f = fopen("/fat/log.txt", "w");
fclose(f);//关闭文件
}
f = fopen("/fat/log.txt", "a");
if (f == NULL) {
Serial.println("Failed to open file for writing");
return;
}
char* cstr = const_cast<char*>(testmsg.c_str());
fprintf(f, cstr);//写入字符
fclose(f);//关闭文件
}
//卸载文件系统
void ds_spiffs_deinit(void){
// All done, unmount partition and disable SPIFFS
esp_vfs_spiffs_unregister(conf.partition_label);
}
void web_ota_server_init()
{
// initWebSocket();
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send_P(200, "text/html", index_html, processor); });
server.on("/log", HTTP_GET, [](AsyncWebServerRequest *request)
{
FILE* f = fopen("/fat/log.txt", "r");
char data[10240];
if (fgets(data, 10240, f) != NULL)
{
request->send_P(200, "text/html", data, processor);
}
fclose(f);
f = nullptr;
});
ElegantOTA.begin(&server); // Start ElegantOTA
// ElegantOTA callbacks
ElegantOTA.onStart(onOTAStart);
ElegantOTA.onProgress(onOTAProgress);
ElegantOTA.onEnd(onOTAEnd);
server.onNotFound(notFound);
// Start server
server.begin();
}