Newer
Older
Tardis / src / Filesystem.cpp
/*
SPDX-License-Identifier: MIT
Copyright (c) 2024 Casey Reeves and the LuminaSensum contributors
*/

#include "Filesystem.h"
#include "MainBD.h"
#include "mbed.h"
#include <errno.h>
#include <functional>

#include "mbed-trace/mbed_trace.h"
#define TRACE_GROUP "FS"

// Maximum number of elements in buffer
#define BUFFER_MAX_LEN 10
#define FORCE_REFORMAT false

// function to attempt to mount the filesystem and
// reformat and mount it again should it fail
int mountFilesystem(mbed::BlockDevice &bd, mbed::FileSystem &fs) {
	int err;
	// Try to mount the filesystem
	tr_info("Mounting the filesystem... ");
	fflush(stdout);
	err = fs.mount(&bd);
	tr_info("%s", (err ? "Fail :(" : "OK"));
	if (err || FORCE_REFORMAT) {
		// Reformat if we can't mount the filesystem
		tr_info("formatting... ");
		fflush(stdout);
		err = fs.reformat(&bd);
		tr_info("%s", (err ? "Fail :(" : "OK"));
		if (err) {
			tr_err("error: %s (%d)", strerror(-err), err);
			return err;
		}
		// Try to mount the filesystem again
		tr_info("Mounting the filesystem... ");
		fflush(stdout);
		err = fs.mount(&bd);
		tr_info("%s", (err ? "Fail :(" : "OK"));
		if (err) {
			tr_err("error: %s (%d)", strerror(-err), err);
			return err;
		}
	}
	return 0;
}

// function to unmount the filesystem
int unmountFilesystem(mbed::BlockDevice &bd, mbed::FileSystem &fs) {
	// Try to unmount the filesystem
	tr_info("Unmounting the filesystem... ");
	fflush(stdout);
	int err = fs.unmount();
	tr_info("%s", (err ? "Fail :(" : "OK"));
	if (err) {
		tr_err("error: %s (%d)", strerror(-err), err);
		return err;
	}
	return 0;
}