I need to write a custom function to add it to the Marlin (2.x.x) Firmware with the cardreader.h library (Anycubic Kobra max firmare) in order to read a gcode file and extract the comments in the beginning (thumbnail data). My code does not return any errors compiling, I know that the SD card is mounted, but in the serial monitor returns "Error opening file". I now the file exists, the name is correct but for some reason I cannot open it and read it.
here is the code:
#include "../../../../sd/cardreader.h"
char* readThumbnailComments(const char *filename) {
if (!card.isMounted()) {
SERIAL_ECHOLNPGM("Card not mounted!");
return NULL;
} else {
SERIAL_ECHOLNPGM("Card mounted!");
}
char nonConstFilename[32];
strncpy(nonConstFilename, filename, sizeof(nonConstFilename));
nonConstFilename[sizeof(nonConstFilename) - 1] = '\0';
card.openFileRead(nonConstFilename);
char *result = (char*) malloc(492 * sizeof(char));
size_t result_size = 492;
result[0] = '\0';
if (card.isFileOpen()) {
char buffer[492];
size_t index = 0;
bool capture_comments = false;
while (card.read(&buffer[index], 1) == 1) { // Read one character at a time
if (buffer[index] == '\n' || buffer[index] == '\r') {
buffer[index] = '\0'; // Null-terminate the string
if (capture_comments) {
if (strncmp(buffer, "; thumbnail end", 15) == 0) {
break; // Stop capturing comments
} else {
if (index > 2) {
strncat(result, buffer + 2, result_size - strlen(result) - 1); // Copy without the "; "
strncat(result, "\n", result_size - strlen(result) - 1); // Add a newline character
}
}
} else {
if (strncmp(buffer, "; thumbnail begin", 17) == 0) {
capture_comments = true; // Start capturing comments
}
}
index = 0; // Reset the index
} else {
index = (index < sizeof(buffer) - 1) ? index + 1 : index;
}
}
card.closefile(false); // Close the file
} else {
SERIAL_ECHOLNPGM("Error opening file");
free(result);
return NULL;
}
return result;
}
And from the UI menu cpp file I use following command:
card.mount(); // Initialize the SD card
char *thumbnail_comments = readThumbnailComments(filenavigator.filelist.longFilename());
Now if I print out thumbnail_comments it come out as null and lie mentioned in the console "Error opening file"
Any suggestions?