Skip to content

Instantly share code, notes, and snippets.

@sticilface
Created November 26, 2015 12:12
Show Gist options
  • Save sticilface/f322185bcc52deb84008 to your computer and use it in GitHub Desktop.
Save sticilface/f322185bcc52deb84008 to your computer and use it in GitHub Desktop.
Use SPIFFS like EEPROM
struct spiffs_helper_t {
File f;
spiffs_helper_t(const char * _path ) {
f = SPIFFS.open(_path, "r+"); // try to open if there... for read and write
if (!f) {
f = SPIFFS.open(_path, "w+"); // if fail open for read/write but new
}
};
~spiffs_helper_t() {
f.close(); // close file when done
}
bool makesize(size_t size) {
if ( size < f.size()) {
return true;
} else {
f.seek(0, SeekEnd);
do {
f.write(0);
} while (size > f.position() ) ;
if (f.position() == size) {
return true;
} else {
return false;
}
}
}
template <class T> int readfrom(int position, T& value)
{
if (!f) return 0;
if (f.seek(sizeof(float)*position, SeekSet)) {
byte* p = (byte*)(void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
*p++ = f.read();
return i;
}
}
template <class T> int writeto(int position, const T& value)
{
if (!f) return 0;
size_t location = sizeof(float) * position;
bool success = false;
if (!f.seek(location, SeekSet)) {
if (makesize(location)) success = true;
} else success = true;
if (success) {
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
f.write(*p++);
return i;
} else return 0;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment