I'm trying to write the payload of a MQTT message into a file in the SPIFFS file system of my esp32 board. I've tried this:
if(file.print((long)payload)) {
Serial.println("File was written");
}else {
Serial.println("File write failed");
}
payload is a byte* and file was opened in the setup() function like:
File file;
if(!SPIFFS.exists("/testfile")){
file = SPIFFS.open("/testfile", "r+");
}
I always get an error when writing to it telling me that the file write failed. Is this the correct approach for what I'm trying to accomplish?
2 Answers 2
Use file.write(payload, length);
for byte array. length
should be the count of payload bytes, not the size of the payload array.
print
and write
return the count of bytes written. It is not meaningful to use the return value as boolean.
Open the file in the loop or the subroutine, but not in setup as file is then a local var to setup
In your code it should be
file = SPIFFS.open("/testfile", "a"); // a ... append
a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
r+ positions stream at the beginning of the file
and to get lines you can afterwards analyze you should use
if(file){
file.println("Your MQTT payload");
Serial.println("File was written");
file.close();
} else {
Serial.println("File write failed");
}
and do not forget to close after the operation.
EDIT
As reaction to the comments here a "clean solution" as a function:
bool writeLog(const char fileName[], char payloadMqtt[]) {
File logFile = SPIFFS.open(fileName, "a");
if (!logFile) {
Serial.println("logFile open failed");
return false;
}
else {
//Write data to file
Serial.println("writing Data to logFile");
logFile.print(payloadMqtt);
logFile.close();
return true;
}
}
You call it with:
writeLog("/myfilepath", payload);
and can also be used like
if (writeLog("/myfilepath", payload)) Serial.println("Log save success");
else Serial.println("Log save failure");
Hope this helps to understand the nature of SPIFFS/LittleFS/SD operations
-
Sorry, I put FIle file; outside the setup(), but I open it inside. And it doesn't make much sense to me to open the file inside the loop. Also, my problem is that payload is a byte array so I guess I need a casting to write that into the fileJohnny– Johnny2020年04月29日 07:50:15 +00:00Commented Apr 29, 2020 at 7:50
-
You should only open before writing and close after writing, we are on a MCU not a full scale OS. Look into the lib spiffs_api.h/cpp to see what open means for your memory (aside from unwanted errors andother probs) . If your payload is a char array you just use file.println(payload)Codebreaker007– Codebreaker0072020年04月29日 08:26:28 +00:00Commented Apr 29, 2020 at 8:26