#include "wled.h" #include "fcn_declare.h" #include "const.h" #ifdef ESP8266 #include "user_interface.h" // for bootloop detection #else #include #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0) #include "esp32/rtc.h" // for bootloop detection #elif ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(3, 3, 0) #include "soc/rtc.h" #endif #endif //helper to get int value at a position in string int getNumVal(const String* req, uint16_t pos) { return req->substring(pos+3).toInt(); } //helper to get int value with in/decrementing support via ~ syntax void parseNumber(const char* str, byte* val, byte minv, byte maxv) { if (str == nullptr || str[0] == '\0') return; if (str[0] == 'r') {*val = random8(minv,maxv?maxv:255); return;} // maxv for random cannot be 0 bool wrap = false; if (str[0] == 'w' && strlen(str) > 1) {str++; wrap = true;} if (str[0] == '~') { int out = atoi(str +1); if (out == 0) { if (str[1] == '0') return; if (str[1] == '-') { *val = (int)(*val -1) < (int)minv ? maxv : min((int)maxv,(*val -1)); //-1, wrap around } else { *val = (int)(*val +1) > (int)maxv ? minv : max((int)minv,(*val +1)); //+1, wrap around } } else { if (wrap && *val == maxv && out > 0) out = minv; else if (wrap && *val == minv && out < 0) out = maxv; else { out += *val; if (out > maxv) out = maxv; if (out < minv) out = minv; } *val = out; } return; } else if (minv == maxv && minv == 0) { // limits "unset" i.e. both 0 byte p1 = atoi(str); const char* str2 = strchr(str,'~'); // min/max range (for preset cycle, e.g. "1~5~") if (str2) { byte p2 = atoi(++str2); // skip ~ if (p2 > 0) { while (isdigit(*(++str2))); // skip digits parseNumber(str2, val, p1, p2); return; } } } *val = atoi(str); } //getVal supports inc/decrementing and random ("X~Y(r|~[w][-][Z])" form) bool getVal(JsonVariant elem, byte* val, byte vmin, byte vmax) { if (elem.is()) { if (elem < 0) return false; //ignore e.g. {"ps":-1} *val = elem; return true; } else if (elem.is()) { const char* str = elem; size_t len = strnlen(str, 14); if (len == 0 || len > 12) return false; // fix for #3605 & #4346 // ignore vmin and vmax and use as specified in API if (len > 3 && (strchr(str,'r') || strchr(str,'~') != strrchr(str,'~'))) vmax = vmin = 0; // we have "X~Y(r|~[w][-][Z])" form // end fix parseNumber(str, val, vmin, vmax); return true; } return false; //key does not exist } bool getBoolVal(JsonVariant elem, bool dflt) { if (elem.is() && elem.as()[0] == 't') { return !dflt; } else { return elem | dflt; } } bool updateVal(const char* req, const char* key, byte* val, byte minv, byte maxv) { const char *v = strstr(req, key); if (v) v += strlen(key); else return false; parseNumber(v, val, minv, maxv); return true; } static size_t printSetFormInput(Print& settingsScript, const char* key, const char* selector, int value) { return settingsScript.printf_P(PSTR("d.Sf.%s.%s=%d;"), key, selector, value); } size_t printSetFormCheckbox(Print& settingsScript, const char* key, int val) { return printSetFormInput(settingsScript, key, PSTR("checked"), val); } size_t printSetFormValue(Print& settingsScript, const char* key, int val) { return printSetFormInput(settingsScript, key, PSTR("value"), val); } size_t printSetFormIndex(Print& settingsScript, const char* key, int index) { return printSetFormInput(settingsScript, key, PSTR("selectedIndex"), index); } size_t printSetFormValue(Print& settingsScript, const char* key, const char* val) { return settingsScript.printf_P(PSTR("d.Sf.%s.value=\"%s\";"),key,val); } size_t printSetClassElementHTML(Print& settingsScript, const char* key, const int index, const char* val) { return settingsScript.printf_P(PSTR("d.getElementsByClassName(\"%s\")[%d].innerHTML=\"%s\";"), key, index, val); } void prepareHostname(char* hostname) { sprintf_P(hostname, PSTR("wled-%*s"), 6, escapedMac.c_str() + 6); const char *pC = serverDescription; unsigned pos = 5; // keep "wled-" while (*pC && pos < 24) { // while !null and not over length if (isalnum(*pC)) { // if the current char is alpha-numeric append it to the hostname hostname[pos] = *pC; pos++; } else if (*pC == ' ' || *pC == '_' || *pC == '-' || *pC == '+' || *pC == '!' || *pC == '?' || *pC == '*') { hostname[pos] = '-'; pos++; } // else do nothing - no leading hyphens and do not include hyphens for all other characters. pC++; } //last character must not be hyphen if (pos > 5) { while (pos > 4 && hostname[pos -1] == '-') pos--; hostname[pos] = '\0'; // terminate string (leave at least "wled") } } bool isAsterisksOnly(const char* str, byte maxLen) { for (unsigned i = 0; i < maxLen; i++) { if (str[i] == 0) break; if (str[i] != '*') return false; } //at this point the password contains asterisks only return (str[0] != 0); //false on empty string } //threading/network callback details: https://github.com/Aircoookie/WLED/pull/2336#discussion_r762276994 bool requestJSONBufferLock(uint8_t module) { if (pDoc == nullptr) { DEBUG_PRINTLN(F("ERROR: JSON buffer not allocated!")); return false; } #if defined(ARDUINO_ARCH_ESP32) // Use a recursive mutex type in case our task is the one holding the JSON buffer. // This can happen during large JSON web transactions. In this case, we continue immediately // and then will return out below if the lock is still held. if (xSemaphoreTakeRecursive(jsonBufferLockMutex, 250) == pdFALSE) return false; // timed out waiting #elif defined(ARDUINO_ARCH_ESP8266) // If we're in system context, delay() won't return control to the user context, so there's // no point in waiting. if (can_yield()) { unsigned long now = millis(); while (jsonBufferLock && (millis()-now < 250)) delay(1); // wait for fraction for buffer lock } #else #error Unsupported task framework - fix requestJSONBufferLock #endif // If the lock is still held - by us, or by another task if (jsonBufferLock) { DEBUG_PRINTF_P(PSTR("ERROR: Locking JSON buffer (%d) failed! (still locked by %d)\n"), module, jsonBufferLock); #ifdef ARDUINO_ARCH_ESP32 xSemaphoreGiveRecursive(jsonBufferLockMutex); #endif return false; } jsonBufferLock = module ? module : 255; DEBUG_PRINTF_P(PSTR("JSON buffer locked. (%d)\n"), jsonBufferLock); pDoc->clear(); return true; } void releaseJSONBufferLock() { DEBUG_PRINTF_P(PSTR("JSON buffer released. (%d)\n"), jsonBufferLock); jsonBufferLock = 0; #ifdef ARDUINO_ARCH_ESP32 xSemaphoreGiveRecursive(jsonBufferLockMutex); #endif } // extracts effect mode (or palette) name from names serialized string // caller must provide large enough buffer for name (including SR extensions)! uint8_t extractModeName(uint8_t mode, const char *src, char *dest, uint8_t maxLen) { if (src == JSON_mode_names || src == nullptr) { if (mode < strip.getModeCount()) { char lineBuffer[256]; //strcpy_P(lineBuffer, (const char*)pgm_read_dword(&(WS2812FX::_modeData[mode]))); strncpy_P(lineBuffer, strip.getModeData(mode), sizeof(lineBuffer)/sizeof(char)-1); lineBuffer[sizeof(lineBuffer)/sizeof(char)-1] = '\0'; // terminate string size_t len = strlen(lineBuffer); size_t j = 0; for (; j < maxLen && j < len; j++) { if (lineBuffer[j] == '\0' || lineBuffer[j] == '@') break; dest[j] = lineBuffer[j]; } dest[j] = 0; // terminate string return strlen(dest); } else return 0; } if (src == JSON_palette_names && mode > (GRADIENT_PALETTE_COUNT + 13)) { snprintf_P(dest, maxLen, PSTR("~ Custom %d ~"), 255-mode); dest[maxLen-1] = '\0'; return strlen(dest); } unsigned qComma = 0; bool insideQuotes = false; unsigned printedChars = 0; char singleJsonSymbol; size_t len = strlen_P(src); // Find the mode name in JSON for (size_t i = 0; i < len; i++) { singleJsonSymbol = pgm_read_byte_near(src + i); if (singleJsonSymbol == '\0') break; if (singleJsonSymbol == '@' && insideQuotes && qComma == mode) break; //stop when SR extension encountered switch (singleJsonSymbol) { case '"': insideQuotes = !insideQuotes; break; case '[': case ']': break; case ',': if (!insideQuotes) qComma++; default: if (!insideQuotes || (qComma != mode)) break; dest[printedChars++] = singleJsonSymbol; } if ((qComma > mode) || (printedChars >= maxLen)) break; } dest[printedChars] = '\0'; return strlen(dest); } // extracts effect slider data (1st group after @) uint8_t extractModeSlider(uint8_t mode, uint8_t slider, char *dest, uint8_t maxLen, uint8_t *var) { dest[0] = '\0'; // start by clearing buffer if (mode < strip.getModeCount()) { String lineBuffer = FPSTR(strip.getModeData(mode)); if (lineBuffer.length() > 0) { unsigned start = lineBuffer.indexOf('@'); unsigned stop = lineBuffer.indexOf(';', start); if (start>0 && stop>0) { String names = lineBuffer.substring(start, stop); // include @ unsigned nameBegin = 1, nameEnd, nameDefault; if (slider < 10) { for (size_t i=0; i<=slider; i++) { const char *tmpstr; dest[0] = '\0'; //clear dest buffer if (nameBegin == 0) break; // there are no more names nameEnd = names.indexOf(',', nameBegin); if (i == slider) { nameDefault = names.indexOf('=', nameBegin); // find default value if (nameDefault > 0 && var && ((nameEnd>0 && nameDefault= 0) { nameEnd = names.indexOf(';', nameBegin+1); if (!isdigit(names[nameBegin+1])) nameBegin = names.indexOf('=', nameBegin+1); // look for default value if (nameEnd >= 0 && nameBegin > nameEnd) nameBegin = -1; if (nameBegin >= 0 && var) { *var = (uint8_t)atoi(names.substring(nameBegin+1).c_str()); } } } // we have slider name (including default value) in the dest buffer for (size_t i=0; ias(); if (!root["n"].isNull()) { // name field exists const char *name = root["n"].as(); if (name != nullptr) len = strlen(name); if (len > 0 && len < 33) { ledmapNames[i-1] = new char[len+1]; if (ledmapNames[i-1]) strlcpy(ledmapNames[i-1], name, 33); } } if (!ledmapNames[i-1]) { char tmp[33]; snprintf_P(tmp, 32, s_ledmap_tmpl, i); len = strlen(tmp); ledmapNames[i-1] = new char[len+1]; if (ledmapNames[i-1]) strlcpy(ledmapNames[i-1], tmp, 33); } } releaseJSONBufferLock(); } #endif } } } /* * Returns a new, random color wheel index with a minimum distance of 42 from pos. */ uint8_t get_random_wheel_index(uint8_t pos) { uint8_t r = 0, x = 0, y = 0, d = 0; while (d < 42) { r = random8(); x = abs(pos - r); y = 255 - x; d = MIN(x, y); } return r; } // float version of map() float mapf(float x, float in_min, float in_max, float out_min, float out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } // bootloop detection and handling // checks if the ESP reboots multiple times due to a crash or watchdog timeout // if a bootloop is detected: restore settings from backup, then reset settings, then switch boot image (and repeat) #define BOOTLOOP_INTERVAL_MILLIS 120000 // time limit between crashes: 120 seconds (2 minutes) #define BOOTLOOP_THRESHOLD 5 // number of consecutive crashes to trigger bootloop detection #define BOOTLOOP_ACTION_RESTORE 0 // default action: restore config from /bkp.cfg.json #define BOOTLOOP_ACTION_RESET 1 // if restore does not work, reset config (rename /cfg.json to /rst.cfg.json) #define BOOTLOOP_ACTION_OTA 2 // swap the boot partition #define BOOTLOOP_ACTION_DUMP 3 // nothing seems to help, dump files to serial and reboot (until hardware reset) // Platform-agnostic abstraction enum class ResetReason { Power, Software, Crash, Brownout }; #ifdef ESP8266 // Place variables in RTC memory via references, since RTC memory is not exposed via the linker in the Non-OS SDK // Use an offset of 32 as there's some hints that the first 128 bytes of "user" memory are used by the OTA system // Ref: https://github.com/esp8266/Arduino/blob/78d0d0aceacc1553f45ad8154592b0af22d1eede/cores/esp8266/Esp.cpp#L168 static volatile uint32_t& bl_last_boottime = *(RTC_USER_MEM + 32); static volatile uint32_t& bl_crashcounter = *(RTC_USER_MEM + 33); static volatile uint32_t& bl_actiontracker = *(RTC_USER_MEM + 34); static inline ResetReason rebootReason() { uint32_t resetReason = system_get_rst_info()->reason; if (resetReason == REASON_EXCEPTION_RST || resetReason == REASON_WDT_RST || resetReason == REASON_SOFT_WDT_RST) return ResetReason::Crash; if (resetReason == REASON_SOFT_RESTART) return ResetReason::Software; return ResetReason::Power; } static inline uint32_t getRtcMillis() { return system_get_rtc_time() / 160; }; // rtc ticks ~160000Hz #else // variables in RTC_NOINIT memory persist between reboots (but not on hardware reset) RTC_NOINIT_ATTR static uint32_t bl_last_boottime; RTC_NOINIT_ATTR static uint32_t bl_crashcounter; RTC_NOINIT_ATTR static uint32_t bl_actiontracker; static inline ResetReason rebootReason() { esp_reset_reason_t reason = esp_reset_reason(); if (reason == ESP_RST_BROWNOUT) return ResetReason::Brownout; if (reason == ESP_RST_SW) return ResetReason::Software; if (reason == ESP_RST_PANIC || reason == ESP_RST_WDT || reason == ESP_RST_INT_WDT || reason == ESP_RST_TASK_WDT) return ResetReason::Crash; return ResetReason::Power; } #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0) static inline uint32_t getRtcMillis() { return esp_rtc_get_time_us() / 1000; } #elif ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(3, 3, 0) static inline uint32_t getRtcMillis() { return rtc_time_slowclk_to_us(rtc_time_get(), rtc_clk_slow_freq_get_hz()) / 1000; } #endif void bootloopCheckOTA() { bl_actiontracker = BOOTLOOP_ACTION_OTA; } // swap boot image if bootloop is detected instead of restoring config #endif // detect bootloop by checking the reset reason and the time since last boot static bool detectBootLoop() { uint32_t rtctime = getRtcMillis(); bool result = false; switch(rebootReason()) { case ResetReason::Power: bl_actiontracker = BOOTLOOP_ACTION_RESTORE; // init action tracker if not an intentional reboot (e.g. from OTA or bootloop handler) // fall through case ResetReason::Software: // no crash detected, reset counter bl_crashcounter = 0; break; case ResetReason::Crash: { uint32_t rebootinterval = rtctime - bl_last_boottime; if (rebootinterval < BOOTLOOP_INTERVAL_MILLIS) { bl_crashcounter++; if (bl_crashcounter >= BOOTLOOP_THRESHOLD) { DEBUG_PRINTLN(F("!BOOTLOOP DETECTED!")); bl_crashcounter = 0; if(bl_actiontracker > BOOTLOOP_ACTION_DUMP) bl_actiontracker = BOOTLOOP_ACTION_RESTORE; // reset action tracker if out of bounds result = true; } } else { // Reset counter on long intervals to track only consecutive short-interval crashes bl_crashcounter = 0; // TODO: crash reporting goes here } break; } case ResetReason::Brownout: // crash due to brownout can't be detected unless using flash memory to store bootloop variables DEBUG_PRINTLN(F("brownout detected")); //restoreConfig(); // TODO: blindly restoring config if brownout detected is a bad idea, need a better way (if at all) break; } bl_last_boottime = rtctime; // store current runtime for next reboot return result; } void handleBootLoop() { DEBUG_PRINTF_P(PSTR("checking for bootloop: time %d, counter %d, action %d\n"), bl_last_boottime, bl_crashcounter, bl_actiontracker); if (!detectBootLoop()) return; // no bootloop detected switch(bl_actiontracker) { case BOOTLOOP_ACTION_RESTORE: restoreConfig(); ++bl_actiontracker; break; case BOOTLOOP_ACTION_RESET: resetConfig(); ++bl_actiontracker; break; case BOOTLOOP_ACTION_OTA: #ifndef ESP8266 if(Update.canRollBack()) { DEBUG_PRINTLN(F("Swapping boot partition...")); Update.rollBack(); // swap boot partition } ++bl_actiontracker; break; #else // fall through #endif case BOOTLOOP_ACTION_DUMP: dumpFilesToSerial(); break; } ESP.restart(); // restart cleanly and don't wait for another crash }