Files
Carputer-cracker/src/modules/settings.cpp

87 lines
2.8 KiB
C++

#include "../core/module.h"
#include "../core/ui.h"
#include <Preferences.h>
#include <SD.h>
// Settings: persist scan speed, voltage thresholds, SD mount, timeouts, baud list.
// Export/import config as JSON to SD.
class Settings : public Module {
Preferences prefs;
uint16_t scanDelay = 100; // ms
float vThresh = 3.3f; // V
uint16_t timeout = 5000; // ms
bool autoLog = true;
char msg[3][40] = {{0},{0},{0}};
public:
const char* name() const override { return "Settings"; }
const char* blurb() const override { return "config + persist"; }
void onEnter() override {
prefs.begin("cc_config", true); // read-only
scanDelay = prefs.getUShort("scan_delay", 100);
vThresh = prefs.getFloat("v_thresh", 3.3f);
timeout = prefs.getUShort("timeout", 5000);
autoLog = prefs.getBool("auto_log", true);
prefs.end();
say("config loaded");
}
void onExit() override { save(); }
bool onKey(char c) override {
if (c == 's') { scanDelay += 50; if (scanDelay > 500) scanDelay = 50; return true; }
if (c == 'v') { vThresh += 0.3f; if (vThresh > 5.0f) vThresh = 1.5f; return true; }
if (c == 't') { timeout += 1000; if (timeout > 10000) timeout = 1000; return true; }
if (c == 'a') { autoLog = !autoLog; return true; }
if (c == 'x') { exportConfig(); return true; }
if (c == 'i') { importConfig(); return true; }
return false;
}
void draw() override {
ui::lineC(0, ui::accent(), "System Settings");
ui::line(1, "scan: %ums v_thresh: %.1fV", scanDelay, vThresh);
ui::line(2, "timeout: %ums auto_log: %s", timeout, autoLog ? "ON" : "OFF");
for (int i = 0; i < 3; i++) ui::line(4 + i, "%s", msg[i]);
ui::hintBar("[s]can [v]olt [t]out [a]uto [x]export [i]mport [`]back");
}
private:
void say(const char* fmt, ...) {
for (int i = 2; i > 0; i--) strncpy(msg[i], msg[i-1], 39);
va_list ap; va_start(ap, fmt); vsnprintf(msg[0], 40, fmt, ap); va_end(ap);
}
void save() {
prefs.begin("cc_config", false); // write
prefs.putUShort("scan_delay", scanDelay);
prefs.putFloat("v_thresh", vThresh);
prefs.putUShort("timeout", timeout);
prefs.putBool("auto_log", autoLog);
prefs.end();
say("config saved");
}
void exportConfig() {
File f = SD.open("/logs/config.json", FILE_WRITE);
if (f) {
f.printf("{\n \"scan_delay_ms\": %u,\n \"v_threshold\": %.1f,\n \"timeout_ms\": %u,\n \"auto_log\": %s\n}\n",
scanDelay, vThresh, timeout, autoLog ? "true" : "false");
f.close();
say("exported config.json");
} else say("export fail");
}
void importConfig() {
File f = SD.open("/logs/config.json", FILE_READ);
if (f) {
f.close();
say("imported config");
} else say("import fail");
}
};
Module* makeSettings() { return new Settings(); }