diff --git a/ESPTimeCast.ino b/ESPTimeCast.ino index c9800aa..3772ab6 100644 --- a/ESPTimeCast.ino +++ b/ESPTimeCast.ino @@ -1,1337 +1,1337 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "mfactoryfont.h" // Custom font -#include "tz_lookup.h" // Timezone lookup, do not duplicate mapping here! -#include "days_lookup.h" // Languages for the Days of the Week - -#define HARDWARE_TYPE MD_MAX72XX::FC16_HW -#define MAX_DEVICES 4 -#define CLK_PIN 12 -#define DATA_PIN 15 -#define CS_PIN 13 - -MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES); -AsyncWebServer server(80); - -// WiFi and configuration globals -char ssid[32] = ""; -char password[32] = ""; -char openWeatherApiKey[64] = ""; -char openWeatherCity[64] = ""; -char openWeatherCountry[64] = ""; -char weatherUnits[12] = "metric"; -char timeZone[64] = ""; -char language[8] = "en"; -String mainDesc = ""; -String detailedDesc = ""; - -// Timing and display settings -unsigned long clockDuration = 10000; -unsigned long weatherDuration = 5000; -int brightness = 7; -bool flipDisplay = false; -bool twelveHourToggle = false; -bool showDayOfWeek = true; -bool showHumidity = false; -char ntpServer1[64] = "pool.ntp.org"; -char ntpServer2[64] = "time.nist.gov"; - -// Dimming -bool dimmingEnabled = false; -int dimStartHour = 18; // 6pm default -int dimStartMinute = 0; -int dimEndHour = 8; // 8am default -int dimEndMinute = 0; -int dimBrightness = 2; // Dimming level (0-15) - -// State management -bool weatherCycleStarted = false; -WiFiClient client; -const byte DNS_PORT = 53; -DNSServer dnsServer; - -String currentTemp = ""; -String weatherDescription = ""; -bool showWeatherDescription = false; -bool weatherAvailable = false; -bool weatherFetched = false; -bool weatherFetchInitiated = false; -bool isAPMode = false; -char tempSymbol = '['; -bool shouldFetchWeatherNow = false; // Flag to trigger immediate weather fetch - -unsigned long lastSwitch = 0; -unsigned long lastColonBlink = 0; -int displayMode = 0; -int currentHumidity = -1; -bool ntpSyncSuccessful = false; - -// NTP Synchronization State Machine -enum NtpState { - NTP_IDLE, - NTP_SYNCING, - NTP_SUCCESS, - NTP_FAILED -}; -NtpState ntpState = NTP_IDLE; -unsigned long ntpStartTime = 0; -const int ntpTimeout = 30000; // 30 seconds -const int maxNtpRetries = 30; -int ntpRetryCount = 0; - -// Non-blocking IP display globals -bool showingIp = false; -int ipDisplayCount = 0; -const int ipDisplayMax = 1; -String pendingIpToShow = ""; - -// Scroll flipped -textEffect_t getEffectiveScrollDirection(textEffect_t desiredDirection, bool isFlipped) { - if (isFlipped) { - // If the display is horizontally flipped, reverse the horizontal scroll direction - if (desiredDirection == PA_SCROLL_LEFT) { - return PA_SCROLL_RIGHT; - } else if (desiredDirection == PA_SCROLL_RIGHT) { - return PA_SCROLL_LEFT; - } - } - return desiredDirection; -} - -// ----------------------------------------------------------------------------- -// Configuration Load & Save -// ----------------------------------------------------------------------------- -void loadConfig() { - Serial.println(F("[CONFIG] Loading configuration...")); - - if (!LittleFS.exists("/config.json")) { - Serial.println(F("[CONFIG] config.json not found, creating with defaults...")); - DynamicJsonDocument doc(512); - doc[F("ssid")] = ""; - doc[F("password")] = ""; - doc[F("openWeatherApiKey")] = ""; - doc[F("openWeatherCity")] = ""; - doc[F("openWeatherCountry")] = ""; - doc[F("weatherUnits")] = "metric"; - doc[F("clockDuration")] = 10000; - doc[F("weatherDuration")] = 5000; - doc[F("timeZone")] = ""; - doc[F("language")] = "en"; - doc[F("brightness")] = brightness; - doc[F("flipDisplay")] = flipDisplay; - doc[F("twelveHourToggle")] = twelveHourToggle; - doc[F("showDayOfWeek")] = showDayOfWeek; - doc[F("showHumidity")] = showHumidity; - doc[F("ntpServer1")] = ntpServer1; - doc[F("ntpServer2")] = ntpServer2; - doc[F("dimmingEnabled")] = dimmingEnabled; - doc[F("dimStartHour")] = dimStartHour; - doc[F("dimEndHour")] = dimEndHour; - doc[F("dimBrightness")] = dimBrightness; - File f = LittleFS.open("/config.json", "w"); - if (f) { - serializeJsonPretty(doc, f); - f.close(); - Serial.println(F("[CONFIG] Default config.json created.")); - } else { - Serial.println(F("[ERROR] Failed to create default config.json")); - } - } - - File configFile = LittleFS.open("/config.json", "r"); - if (!configFile) { - Serial.println(F("[ERROR] Failed to open config.json for reading. Cannot load config.")); - return; - } - - DynamicJsonDocument doc(2048); - DeserializationError error = deserializeJson(doc, configFile); - configFile.close(); - - if (error) { - Serial.print(F("[ERROR] JSON parse failed during load: ")); - Serial.println(error.f_str()); - return; - } - - strlcpy(ssid, doc["ssid"] | "", sizeof(ssid)); - strlcpy(password, doc["password"] | "", sizeof(password)); - strlcpy(openWeatherApiKey, doc["openWeatherApiKey"] | "", sizeof(openWeatherApiKey)); - strlcpy(openWeatherCity, doc["openWeatherCity"] | "", sizeof(openWeatherCity)); - strlcpy(openWeatherCountry, doc["openWeatherCountry"] | "", sizeof(openWeatherCountry)); - strlcpy(weatherUnits, doc["weatherUnits"] | "metric", sizeof(weatherUnits)); - clockDuration = doc["clockDuration"] | 10000; - weatherDuration = doc["weatherDuration"] | 5000; - strlcpy(timeZone, doc["timeZone"] | "Etc/UTC", sizeof(timeZone)); - if (doc.containsKey("language")) { - strlcpy(language, doc["language"], sizeof(language)); - } else { - strlcpy(language, "en", sizeof(language)); - Serial.println(F("[CONFIG] 'language' key not found in config.json, defaulting to 'en'.")); - } - - brightness = doc["brightness"] | 7; - flipDisplay = doc["flipDisplay"] | false; - twelveHourToggle = doc["twelveHourToggle"] | false; - showDayOfWeek = doc["showDayOfWeek"] | true; - showHumidity = doc["showHumidity"] | false; - - String de = doc["dimmingEnabled"].as(); - dimmingEnabled = (de == "true" || de == "on" || de == "1"); - - dimStartHour = doc["dimStartHour"] | 18; - dimStartMinute = doc["dimStartMinute"] | 0; - dimEndHour = doc["dimEndHour"] | 8; - dimEndMinute = doc["dimEndMinute"] | 0; - dimBrightness = doc["dimBrightness"] | 0; - - strlcpy(ntpServer1, doc["ntpServer1"] | "pool.ntp.org", sizeof(ntpServer1)); - strlcpy(ntpServer2, doc["ntpServer2"] | "time.nist.gov", sizeof(ntpServer2)); - - if (strcmp(weatherUnits, "imperial") == 0) - tempSymbol = ']'; - else - tempSymbol = '['; - Serial.println(F("[CONFIG] Configuration loaded.")); - - if (doc.containsKey("showWeatherDescription")) - showWeatherDescription = doc["showWeatherDescription"]; - else - showWeatherDescription = false; -} - -// ----------------------------------------------------------------------------- -// WiFi Setup -// ----------------------------------------------------------------------------- -const char *DEFAULT_AP_PASSWORD = "12345678"; -const char *AP_SSID = "ESPTimeCast"; - -void connectWiFi() { - Serial.println(F("[WIFI] Connecting to WiFi...")); - - bool credentialsExist = (strlen(ssid) > 0); - - if (!credentialsExist) { - Serial.println(F("[WIFI] No saved credentials. Starting AP mode directly.")); - WiFi.mode(WIFI_AP); - WiFi.disconnect(true); - delay(100); - - if (strlen(DEFAULT_AP_PASSWORD) < 8) { - WiFi.softAP(AP_SSID); - Serial.println(F("[WIFI] AP Mode started (no password, too short).")); - } else { - WiFi.softAP(AP_SSID, DEFAULT_AP_PASSWORD); - Serial.println(F("[WIFI] AP Mode started.")); - } - - IPAddress apIP(192, 168, 4, 1); - WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); - dnsServer.start(DNS_PORT, "*", WiFi.softAPIP()); - Serial.print(F("AP IP address: ")); - Serial.println(WiFi.softAPIP()); - isAPMode = true; - Serial.println(F("[WIFI] AP Mode Started")); - return; - } - - WiFi.disconnect(true); - delay(100); - WiFi.begin(ssid, password); - unsigned long startAttemptTime = millis(); - const unsigned long timeout = 25000; - unsigned long animTimer = 0; - int animFrame = 0; - bool animating = true; - - while (animating) { - unsigned long now = millis(); - if (WiFi.status() == WL_CONNECTED) { - Serial.println(F("[WIFI] Connected: ") + WiFi.localIP().toString()); - isAPMode = false; - animating = false; - - pendingIpToShow = WiFi.localIP().toString(); - showingIp = true; - ipDisplayCount = 0; - P.displayClear(); - P.setCharSpacing(1); - textEffect_t actualScrollDirection = getEffectiveScrollDirection(PA_SCROLL_LEFT, flipDisplay); - P.displayScroll(pendingIpToShow.c_str(), PA_CENTER, actualScrollDirection, 120); - break; - } else if (now - startAttemptTime >= timeout) { - Serial.println(F("\r\n[WiFi] Failed. Starting AP mode...")); - WiFi.softAP(AP_SSID, DEFAULT_AP_PASSWORD); - Serial.print(F("AP IP address: ")); - Serial.println(WiFi.softAPIP()); - dnsServer.start(DNS_PORT, "*", WiFi.softAPIP()); - isAPMode = true; - animating = false; - Serial.println(F("[WIFI] AP Mode Started")); - break; - } - if (now - animTimer > 750) { - animTimer = now; - P.setTextAlignment(PA_CENTER); - switch (animFrame % 3) { - case 0: P.print(F("# ©")); break; - case 1: P.print(F("# ª")); break; - case 2: P.print(F("# «")); break; - } - animFrame++; - } - yield(); - } -} - -// ----------------------------------------------------------------------------- -// Time / NTP Functions -// ----------------------------------------------------------------------------- -void setupTime() { - sntp_stop(); - if (!isAPMode) { - Serial.println(F("[TIME] Starting NTP sync...")); - } - configTime(0, 0, ntpServer1, ntpServer2); - setenv("TZ", ianaToPosix(timeZone), 1); - tzset(); - ntpState = NTP_SYNCING; - ntpStartTime = millis(); - ntpRetryCount = 0; - ntpSyncSuccessful = false; -} - -// ----------------------------------------------------------------------------- -// Utility -// ----------------------------------------------------------------------------- -void printConfigToSerial() { - Serial.println(F("========= Loaded Configuration =========")); - Serial.print(F("WiFi SSID: ")); - Serial.println(ssid); - Serial.print(F("WiFi Password: ")); - Serial.println(password); - Serial.print(F("OpenWeather City: ")); - Serial.println(openWeatherCity); - Serial.print(F("OpenWeather Country: ")); - Serial.println(openWeatherCountry); - Serial.print(F("OpenWeather API Key: ")); - Serial.println(openWeatherApiKey); - Serial.print(F("Temperature Unit: ")); - Serial.println(weatherUnits); - Serial.print(F("Clock duration: ")); - Serial.println(clockDuration); - Serial.print(F("Weather duration: ")); - Serial.println(weatherDuration); - Serial.print(F("TimeZone (IANA): ")); - Serial.println(timeZone); - Serial.print(F("Days of the Week/Weather description language: ")); - Serial.println(language); - Serial.print(F("Brightness: ")); - Serial.println(brightness); - Serial.print(F("Flip Display: ")); - Serial.println(flipDisplay ? "Yes" : "No"); - Serial.print(F("Show 12h Clock: ")); - Serial.println(twelveHourToggle ? "Yes" : "No"); - Serial.print(F("Show Day of the Week: ")); - Serial.println(showDayOfWeek ? "Yes" : "No"); - Serial.print(F("Show Weather Description: ")); - Serial.println(showWeatherDescription ? "Yes" : "No"); - Serial.print(F("Show Humidity ")); - Serial.println(showHumidity ? "Yes" : "No"); - Serial.print(F("NTP Server 1: ")); - Serial.println(ntpServer1); - Serial.print(F("NTP Server 2: ")); - Serial.println(ntpServer2); - Serial.print(F("Dimming Enabled: ")); - Serial.println(dimmingEnabled); - Serial.print(F("Dimming Start Hour: ")); - Serial.println(dimStartHour); - Serial.print(F("Dimming Start Minute: ")); - Serial.println(dimStartMinute); - Serial.print(F("Dimming End Hour: ")); - Serial.println(dimEndHour); - Serial.print(F("Dimming End Minute: ")); - Serial.println(dimEndMinute); - Serial.print(F("Dimming Brightness: ")); - Serial.println(dimBrightness); - Serial.println(F("========================================")); - Serial.println(); -} - -// ----------------------------------------------------------------------------- -// Web Server and Captive Portal -// ----------------------------------------------------------------------------- -void handleCaptivePortal(AsyncWebServerRequest *request); - -void setupWebServer() { - Serial.println(F("[WEBSERVER] Setting up web server...")); - - server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { - Serial.println(F("[WEBSERVER] Request: /")); - request->send(LittleFS, "/index.html", "text/html"); - }); - - server.on("/config.json", HTTP_GET, [](AsyncWebServerRequest *request) { - Serial.println(F("[WEBSERVER] Request: /config.json")); - File f = LittleFS.open("/config.json", "r"); - if (!f) { - Serial.println(F("[WEBSERVER] Error opening /config.json")); - request->send(500, "application/json", "{\"error\":\"Failed to open config.json\"}"); - return; - } - DynamicJsonDocument doc(2048); - DeserializationError err = deserializeJson(doc, f); - f.close(); - if (err) { - Serial.print(F("[WEBSERVER] Error parsing /config.json: ")); - Serial.println(err.f_str()); - request->send(500, "application/json", "{\"error\":\"Failed to parse config.json\"}"); - return; - } - doc[F("mode")] = isAPMode ? "ap" : "sta"; - String response; - serializeJson(doc, response); - request->send(200, "application/json", response); - }); - - // Save, restore, status and settings handlers grouped for clarity - server.on("/save", HTTP_POST, [](AsyncWebServerRequest *request) { - Serial.println(F("[WEBSERVER] Request: /save")); - DynamicJsonDocument doc(2048); - - File configFile = LittleFS.open("/config.json", "r"); - if (configFile) { - Serial.println(F("[WEBSERVER] Existing config.json found, loading...")); - DeserializationError err = deserializeJson(doc, configFile); - configFile.close(); - if (err) { - Serial.print(F("[WEBSERVER] Error parsing existing config.json: ")); - Serial.println(err.f_str()); - } - } else { - Serial.println(F("[WEBSERVER] config.json not found, starting with empty doc.")); - } - - for (int i = 0; i < request->params(); i++) { - const AsyncWebParameter *p = request->getParam(i); - String n = p->name(); - String v = p->value(); - - Serial.printf("[SAVE] Param: %s = %s\n", n.c_str(), v.c_str()); - - if (n == "brightness") doc[n] = v.toInt(); - else if (n == "clockDuration") doc[n] = v.toInt(); - else if (n == "weatherDuration") doc[n] = v.toInt(); - else if (n == "flipDisplay") doc[n] = (v == "true" || v == "on" || v == "1"); - else if (n == "twelveHourToggle") doc[n] = (v == "true" || v == "on" || v == "1"); - else if (n == "showDayOfWeek") doc[n] = (v == "true" || v == "on" || v == "1"); - else if (n == "showHumidity") doc[n] = (v == "true" || v == "on" || v == "1"); - else if (n == "dimStartHour") doc[n] = v.toInt(); - else if (n == "dimStartMinute") doc[n] = v.toInt(); - else if (n == "dimEndHour") doc[n] = v.toInt(); - else if (n == "dimEndMinute") doc[n] = v.toInt(); - else if (n == "dimBrightness") doc[n] = v.toInt(); - else if (n == "showWeatherDescription") doc[n] = (v == "true" || v == "on" || v == "1"); - else doc[n] = v; - } - - Serial.print(F("[SAVE] Document content before saving: ")); - serializeJson(doc, Serial); - Serial.println(); - - FSInfo fs_info; - LittleFS.info(fs_info); - Serial.printf("[SAVE] LittleFS total bytes: %u, used bytes: %u\n", fs_info.totalBytes, fs_info.usedBytes); - - if (LittleFS.exists("/config.json")) { - Serial.println(F("[SAVE] Renaming /config.json to /config.bak")); - LittleFS.rename("/config.json", "/config.bak"); - } - File f = LittleFS.open("/config.json", "w"); - if (!f) { - Serial.println(F("[SAVE] ERROR: Failed to open /config.json for writing!")); - DynamicJsonDocument errorDoc(256); - errorDoc[F("error")] = "Failed to write config file."; - String response; - serializeJson(errorDoc, response); - request->send(500, "application/json", response); - return; - } - - size_t bytesWritten = serializeJson(doc, f); - Serial.printf("[SAVE] Bytes written to /config.json: %u\n", bytesWritten); - f.close(); - Serial.println(F("[SAVE] /config.json file closed.")); - - Serial.println(F("[SAVE] Attempting to open /config.json for verification.")); - File verify = LittleFS.open("/config.json", "r"); - if (!verify) { - Serial.println(F("[SAVE] ERROR: Failed to open /config.json for reading during verification!")); - DynamicJsonDocument errorDoc(256); - errorDoc[F("error")] = "Verification failed: Could not re-open config file."; - String response; - serializeJson(errorDoc, response); - request->send(500, "application/json", response); - return; - } - - Serial.println(F("[SAVE] Content of /config.json during verification read:")); - while (verify.available()) { - Serial.write(verify.read()); - } - Serial.println(); - verify.seek(0); - - DynamicJsonDocument test(2048); - DeserializationError err = deserializeJson(test, verify); - verify.close(); - - if (err) { - Serial.print(F("[SAVE] Config corrupted after save: ")); - Serial.println(err.f_str()); - DynamicJsonDocument errorDoc(256); - errorDoc[F("error")] = String("Config corrupted. Reboot cancelled. Error: ") + err.f_str(); - String response; - serializeJson(errorDoc, response); - request->send(500, "application/json", response); - return; - } - - Serial.println(F("[SAVE] Config verification successful.")); - DynamicJsonDocument okDoc(128); - okDoc[F("message")] = "Saved successfully. Rebooting..."; - String response; - serializeJson(okDoc, response); - request->send(200, "application/json", response); - Serial.println(F("[WEBSERVER] Sending success response and scheduling reboot...")); - - request->onDisconnect([]() { - Serial.println(F("[WEBSERVER] Client disconnected, rebooting ESP...")); - ESP.restart(); - }); - }); - - server.on("/restore", HTTP_POST, [](AsyncWebServerRequest *request) { - Serial.println(F("[WEBSERVER] Request: /restore")); - if (LittleFS.exists("/config.bak")) { - File src = LittleFS.open("/config.bak", "r"); - if (!src) { - Serial.println(F("[WEBSERVER] Failed to open /config.bak")); - DynamicJsonDocument errorDoc(128); - errorDoc[F("error")] = "Failed to open backup file."; - String response; - serializeJson(errorDoc, response); - request->send(500, "application/json", response); - return; - } - File dst = LittleFS.open("/config.json", "w"); - if (!dst) { - src.close(); - Serial.println(F("[WEBSERVER] Failed to open /config.json for writing")); - DynamicJsonDocument errorDoc(128); - errorDoc[F("error")] = "Failed to open config for writing."; - String response; - serializeJson(errorDoc, response); - request->send(500, "application/json", response); - return; - } - - while (src.available()) { - dst.write(src.read()); - } - src.close(); - dst.close(); - - DynamicJsonDocument okDoc(128); - okDoc[F("message")] = "✅ Backup restored! Device will now reboot."; - String response; - serializeJson(okDoc, response); - request->send(200, "application/json", response); - request->onDisconnect([]() { - Serial.println(F("[WEBSERVER] Rebooting after restore...")); - ESP.restart(); - }); - - } else { - Serial.println(F("[WEBSERVER] No backup found")); - DynamicJsonDocument errorDoc(128); - errorDoc[F("error")] = "No backup found."; - String response; - serializeJson(errorDoc, response); - request->send(404, "application/json", response); - } - }); - - server.on("/ap_status", HTTP_GET, [](AsyncWebServerRequest *request) { - Serial.print(F("[WEBSERVER] Request: /ap_status. isAPMode = ")); - Serial.println(isAPMode); - String json = "{\"isAP\": "; - json += (isAPMode) ? "true" : "false"; - json += "}"; - request->send(200, "application/json", json); - }); - - // Settings endpoints (brightness, flip, etc.) - server.on("/set_brightness", HTTP_POST, [](AsyncWebServerRequest *request) { - if (!request->hasParam("value", true)) { - request->send(400, "application/json", "{\"error\":\"Missing value\"}"); - return; - } - int newBrightness = request->getParam("value", true)->value().toInt(); - if (newBrightness < 0) newBrightness = 0; - if (newBrightness > 15) newBrightness = 15; - brightness = newBrightness; - P.setIntensity(brightness); - Serial.printf("[WEBSERVER] Set brightness to %d\n", brightness); - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_flip", HTTP_POST, [](AsyncWebServerRequest *request) { - bool flip = false; - if (request->hasParam("value", true)) { - String v = request->getParam("value", true)->value(); - flip = (v == "1" || v == "true" || v == "on"); - } - flipDisplay = flip; - P.setZoneEffect(0, flipDisplay, PA_FLIP_UD); - P.setZoneEffect(0, flipDisplay, PA_FLIP_LR); - Serial.printf("[WEBSERVER] Set flipDisplay to %d\n", flipDisplay); - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_twelvehour", HTTP_POST, [](AsyncWebServerRequest *request) { - bool twelveHour = false; - if (request->hasParam("value", true)) { - String v = request->getParam("value", true)->value(); - twelveHour = (v == "1" || v == "true" || v == "on"); - } - twelveHourToggle = twelveHour; - Serial.printf("[WEBSERVER] Set twelveHourToggle to %d\n", twelveHourToggle); - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_dayofweek", HTTP_POST, [](AsyncWebServerRequest *request) { - bool showDay = false; - if (request->hasParam("value", true)) { - String v = request->getParam("value", true)->value(); - showDay = (v == "1" || v == "true" || v == "on"); - } - showDayOfWeek = showDay; - Serial.printf("[WEBSERVER] Set showDayOfWeek to %d\n", showDayOfWeek); - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_humidity", HTTP_POST, [](AsyncWebServerRequest *request) { - bool showHumidityNow = false; - if (request->hasParam("value", true)) { - String v = request->getParam("value", true)->value(); - showHumidityNow = (v == "1" || v == "true" || v == "on"); - } - showHumidity = showHumidityNow; - Serial.printf("[WEBSERVER] Set showHumidity to %d\n", showHumidity); - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_language", HTTP_POST, [](AsyncWebServerRequest *request) { - if (!request->hasParam("value", true)) { - request->send(400, "application/json", "{\"error\":\"Missing value\"}"); - return; - } - String lang = request->getParam("value", true)->value(); - strlcpy(language, lang.c_str(), sizeof(language)); - Serial.printf("[WEBSERVER] Set language to %s\n", language); - shouldFetchWeatherNow = true; - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_weatherdesc", HTTP_POST, [](AsyncWebServerRequest *request) { - bool showDesc = false; - if (request->hasParam("value", true)) { - String v = request->getParam("value", true)->value(); - showDesc = (v == "1" || v == "true" || v == "on"); - } - showWeatherDescription = showDesc; - Serial.printf("[WEBSERVER] Set showWeatherDescription to %d\n", showWeatherDescription); - request->send(200, "application/json", "{\"ok\":true}"); - }); - - server.on("/set_units", HTTP_POST, [](AsyncWebServerRequest *request) { - if (request->hasParam("value", true)) { - String v = request->getParam("value", true)->value(); - if (v == "1" || v == "true" || v == "on") { - strcpy(weatherUnits, "imperial"); - tempSymbol = ']'; // Fahrenheit symbol - } else { - strcpy(weatherUnits, "metric"); - tempSymbol = '['; // Celsius symbol - } - Serial.printf("[WEBSERVER] Set weatherUnits to %s\n", weatherUnits); - shouldFetchWeatherNow = true; - request->send(200, "application/json", "{\"ok\":true}"); - } else { - request->send(400, "application/json", "{\"error\":\"Missing value parameter\"}"); - } - }); - - server.begin(); - Serial.println(F("[WEBSERVER] Web server started")); -} - -void handleCaptivePortal(AsyncWebServerRequest *request) { - Serial.print(F("[WEBSERVER] Captive Portal Redirecting: ")); - Serial.println(request->url()); - request->redirect(String("http://") + WiFi.softAPIP().toString() + "/"); -} - -// ----------------------------------------------------------------------------- -// Weather Fetching and API settings -// ----------------------------------------------------------------------------- -String normalizeWeatherDescription(String str) { - str.replace("å", "a"); - str.replace("ä", "a"); - str.replace("à", "a"); - str.replace("á", "a"); - str.replace("â", "a"); - str.replace("ã", "a"); - str.replace("ā", "a"); - str.replace("ă", "a"); - str.replace("ą", "a"); - - str.replace("æ", "ae"); - - str.replace("ç", "c"); - str.replace("č", "c"); - str.replace("ć", "c"); - - str.replace("ď", "d"); - - str.replace("é", "e"); - str.replace("è", "e"); - str.replace("ê", "e"); - str.replace("ë", "e"); - str.replace("ē", "e"); - str.replace("ė", "e"); - str.replace("ę", "e"); - - str.replace("ğ", "g"); - str.replace("ģ", "g"); - - str.replace("ĥ", "h"); - - str.replace("í", "i"); - str.replace("ì", "i"); - str.replace("î", "i"); - str.replace("ï", "i"); - str.replace("ī", "i"); - str.replace("į", "i"); - - str.replace("ĵ", "j"); - - str.replace("ķ", "k"); - - str.replace("ľ", "l"); - str.replace("ł", "l"); - - str.replace("ñ", "n"); - str.replace("ń", "n"); - str.replace("ņ", "n"); - - str.replace("ó", "o"); - str.replace("ò", "o"); - str.replace("ô", "o"); - str.replace("ö", "o"); - str.replace("õ", "o"); - str.replace("ø", "o"); - str.replace("ō", "o"); - str.replace("ő", "o"); - - str.replace("œ", "oe"); - - str.replace("ŕ", "r"); - - str.replace("ś", "s"); - str.replace("š", "s"); - str.replace("ș", "s"); - str.replace("ŝ", "s"); - - str.replace("ß", "ss"); - - str.replace("ť", "t"); - str.replace("ț", "t"); - - str.replace("ú", "u"); - str.replace("ù", "u"); - str.replace("û", "u"); - str.replace("ü", "u"); - str.replace("ū", "u"); - str.replace("ů", "u"); - str.replace("ű", "u"); - - str.replace("ŵ", "w"); - - str.replace("ý", "y"); - str.replace("ÿ", "y"); - str.replace("ŷ", "y"); - - str.replace("ž", "z"); - str.replace("ź", "z"); - str.replace("ż", "z"); - - str.toLowerCase(); - // Filter out anything that's not a–z or space - String result = ""; - for (unsigned int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - if ((c >= 'a' && c <= 'z') || c == ' ') { - result += c; - } - // else: ignore punctuation, emoji, symbols - } - return result; -} - -bool isNumber(const char *str) { - for (int i = 0; str[i]; i++) { - if (!isdigit(str[i]) && str[i] != '.' && str[i] != '-') return false; - } - return true; -} - -bool isFiveDigitZip(const char *str) { - if (strlen(str) != 5) return false; - for (int i = 0; i < 5; i++) { - if (!isdigit(str[i])) return false; - } - return true; -} - -String buildWeatherURL() { - String base = "http://api.openweathermap.org/data/2.5/weather?"; - - float lat = atof(openWeatherCity); - float lon = atof(openWeatherCountry); - - bool latValid = isNumber(openWeatherCity) && isNumber(openWeatherCountry) && lat >= -90.0 && lat <= 90.0 && lon >= -180.0 && lon <= 180.0; - - if (latValid) { - base += "lat=" + String(lat, 8) + "&lon=" + String(lon, 8); - } else if (isFiveDigitZip(openWeatherCity) && String(openWeatherCountry).equalsIgnoreCase("US")) { - base += "zip=" + String(openWeatherCity) + "," + String(openWeatherCountry); - } else { - base += "q=" + String(openWeatherCity) + "," + String(openWeatherCountry); - } - - base += "&appid=" + String(openWeatherApiKey); - base += "&units=" + String(weatherUnits); - - String langForAPI = String(language); // Start with the global language - - if (langForAPI == "eo" || langForAPI == "sw" || langForAPI == "ja") { - langForAPI = "en"; // Override to "en" for the API - } - base += "&lang=" + langForAPI; - - return base; -} - -void fetchWeather() { - Serial.println(F("[WEATHER] Fetching weather data...")); - if (WiFi.status() != WL_CONNECTED) { - Serial.println(F("[WEATHER] Skipped: WiFi not connected")); - weatherAvailable = false; - weatherFetched = false; - return; - } - if (!openWeatherApiKey || strlen(openWeatherApiKey) != 32) { - Serial.println(F("[WEATHER] Skipped: Invalid API key (must be exactly 32 characters)")); - weatherAvailable = false; - weatherFetched = false; - return; - } - if (!(strlen(openWeatherCity) > 0 && strlen(openWeatherCountry) > 0)) { - Serial.println(F("[WEATHER] Skipped: City or Country is empty.")); - return; - } - - Serial.println(F("[WEATHER] Connecting to OpenWeatherMap...")); - const char *host = "api.openweathermap.org"; - String url = buildWeatherURL(); - Serial.println(F("[WEATHER] URL: ") + url); - - IPAddress ip; - if (!WiFi.hostByName(host, ip)) { - Serial.println(F("[WEATHER] DNS lookup failed!")); - weatherAvailable = false; - return; - } - - if (!client.connect(host, 80)) { - Serial.println(F("[WEATHER] Connection failed")); - weatherAvailable = false; - return; - } - - Serial.println(F("[WEATHER] Connected, sending request...")); - String request = String("GET ") + url + " HTTP/1.1\r\n" + F("Host: ") + host + F("\r\n") + F("Connection: close\r\n\r\n"); - - if (!client.print(request)) { - Serial.println(F("[WEATHER] Failed to send request!")); - client.stop(); - weatherAvailable = false; - return; - } - - unsigned long weatherStart = millis(); - const unsigned long weatherTimeout = 10000; - - bool isBody = false; - String payload = ""; - String line = ""; - - while ((client.connected() || client.available()) && millis() - weatherStart < weatherTimeout && WiFi.status() == WL_CONNECTED) { - line = client.readStringUntil('\n'); - if (line.length() == 0) continue; - - if (line.startsWith(F("HTTP/1.1"))) { - int statusCode = line.substring(9, 12).toInt(); - if (statusCode != 200) { - Serial.print(F("[WEATHER] HTTP error: ")); - Serial.println(statusCode); - client.stop(); - weatherAvailable = false; - return; - } - } - - if (!isBody && line == F("\r")) { - isBody = true; - while (client.available()) { - payload += (char)client.read(); - } - break; - } - yield(); - } - client.stop(); - - if (millis() - weatherStart >= weatherTimeout) { - Serial.println(F("[WEATHER] ERROR: Weather fetch timed out!")); - weatherAvailable = false; - return; - } - - Serial.println(F("[WEATHER] Response received.")); - Serial.println(F("[WEATHER] Payload: ") + payload); - - DynamicJsonDocument doc(2048); - DeserializationError error = deserializeJson(doc, payload); - if (error) { - Serial.print(F("[WEATHER] JSON parse error: ")); - Serial.println(error.f_str()); - weatherAvailable = false; - return; - } - - if (doc.containsKey(F("main")) && doc[F("main")].containsKey(F("temp"))) { - float temp = doc[F("main")][F("temp")]; - currentTemp = String((int)round(temp)) + "º"; - Serial.printf("[WEATHER] Temp: %s\n", currentTemp.c_str()); - weatherAvailable = true; - } else { - Serial.println(F("[WEATHER] Temperature not found in JSON payload")); - weatherAvailable = false; - return; - } - - if (doc.containsKey(F("main")) && doc[F("main")].containsKey(F("humidity"))) { - currentHumidity = doc[F("main")][F("humidity")]; - Serial.printf("[WEATHER] Humidity: %d%%\n", currentHumidity); - } else { - currentHumidity = -1; - } - - if (doc.containsKey(F("weather")) && doc[F("weather")].is()) { - JsonObject weatherObj = doc[F("weather")][0]; - if (weatherObj.containsKey(F("main"))) { - mainDesc = weatherObj[F("main")].as(); - } - if (weatherObj.containsKey(F("description"))) { - detailedDesc = weatherObj[F("description")].as(); - } - } else { - Serial.println(F("[WEATHER] Weather description not found in JSON payload")); - } - - weatherDescription = normalizeWeatherDescription(detailedDesc); - - Serial.printf("[WEATHER] Description used: %s\n", weatherDescription.c_str()); - - weatherFetched = true; -} - -// ----------------------------------------------------------------------------- -// Main setup() and loop() -// ----------------------------------------------------------------------------- -/* -DisplayMode key: - 0: Clock - 1: Weather - 2: Weather Description -*/ -unsigned long descStartTime = 0; -bool descScrolling = false; -const unsigned long descriptionDuration = 3000; // 3s for short text - -void setup() { - Serial.begin(115200); - Serial.println(); - Serial.println(F("[SETUP] Starting setup...")); - - if (!LittleFS.begin()) { - Serial.println(F("[ERROR] LittleFS mount failed in setup! Halting.")); - while (true) { - delay(1000); - } - } - Serial.println(F("[SETUP] LittleFS file system mounted successfully.")); - - P.begin(); - P.setCharSpacing(0); - P.setFont(mFactory); - loadConfig(); - P.setIntensity(brightness); - P.setZoneEffect(0, flipDisplay, PA_FLIP_UD); - P.setZoneEffect(0, flipDisplay, PA_FLIP_LR); - Serial.println(F("[SETUP] Parola (LED Matrix) initialized")); - connectWiFi(); - Serial.println(F("[SETUP] Wifi connected")); - setupWebServer(); - Serial.println(F("[SETUP] Webserver setup complete")); - Serial.println(F("[SETUP] Setup complete")); - Serial.println(); - printConfigToSerial(); - setupTime(); - displayMode = 0; - lastSwitch = millis(); - lastColonBlink = millis(); -} - -void advanceDisplayMode() { - int oldMode = displayMode; - if (displayMode == 0) { - displayMode = 1; // clock -> weather - } else if (displayMode == 1 && showWeatherDescription && weatherAvailable && weatherDescription.length() > 0) { - displayMode = 2; // weather -> description - } else { - displayMode = 0; // description (or weather if no desc) -> clock - } - lastSwitch = millis(); - // Serial print for debugging - const char *modeName = displayMode == 0 ? "CLOCK" : displayMode == 1 ? "WEATHER" - : "DESCRIPTION"; - Serial.printf("[LOOP] Switching to display mode: %s\n", modeName); -} - -void loop() { - if (isAPMode) { - dnsServer.processNextRequest(); - } - - // AP Mode animation - static unsigned long apAnimTimer = 0; - static int apAnimFrame = 0; - if (isAPMode) { - unsigned long now = millis(); - if (now - apAnimTimer > 750) { - apAnimTimer = now; - apAnimFrame++; - } - P.setTextAlignment(PA_CENTER); - switch (apAnimFrame % 3) { - case 0: P.print(F("= ©")); break; - case 1: P.print(F("= ª")); break; - case 2: P.print(F("= «")); break; - } - yield(); - return; - } - - // Dimming - time_t now = time(nullptr); - struct tm timeinfo; - localtime_r(&now, &timeinfo); - int curHour = timeinfo.tm_hour; - int curMinute = timeinfo.tm_min; - int curTotal = curHour * 60 + curMinute; - int startTotal = dimStartHour * 60 + dimStartMinute; - int endTotal = dimEndHour * 60 + dimEndMinute; - bool isDimming = false; - - if (dimmingEnabled) { - if (startTotal < endTotal) { - isDimming = (curTotal >= startTotal && curTotal < endTotal); - } else { - isDimming = (curTotal >= startTotal || curTotal < endTotal); - } - if (isDimming) { - P.setIntensity(dimBrightness); - } else { - P.setIntensity(brightness); - } - } else { - P.setIntensity(brightness); - } - - // Show IP after WiFi connect - if (showingIp) { - if (P.displayAnimate()) { - ipDisplayCount++; - if (ipDisplayCount < ipDisplayMax) { - textEffect_t actualScrollDirection = getEffectiveScrollDirection(PA_SCROLL_LEFT, flipDisplay); - P.displayScroll(pendingIpToShow.c_str(), PA_CENTER, actualScrollDirection, 120); - } else { - showingIp = false; - P.displayClear(); - delay(500); - displayMode = 0; - lastSwitch = millis(); - } - } - yield(); - return; - } - - static bool colonVisible = true; - const unsigned long colonBlinkInterval = 800; - if (millis() - lastColonBlink > colonBlinkInterval) { - colonVisible = !colonVisible; - lastColonBlink = millis(); - } - - static unsigned long ntpAnimTimer = 0; - static int ntpAnimFrame = 0; - static bool tzSetAfterSync = false; - - static unsigned long lastFetch = 0; - const unsigned long fetchInterval = 300000; // 5 minutes - - switch (ntpState) { - case NTP_IDLE: break; - case NTP_SYNCING: - { - time_t now = time(nullptr); - if (now > 1000) { - Serial.println(F("\n[TIME] NTP sync successful.")); - ntpSyncSuccessful = true; - ntpState = NTP_SUCCESS; - } else if (millis() - ntpStartTime > ntpTimeout || ntpRetryCount > maxNtpRetries) { - Serial.println(F("\n[TIME] NTP sync failed.")); - ntpSyncSuccessful = false; - ntpState = NTP_FAILED; - } else { - if (millis() - ntpStartTime > ((unsigned long)ntpRetryCount * 1000)) { - Serial.print(F(".")); - ntpRetryCount++; - } - } - break; - } - case NTP_SUCCESS: - if (!tzSetAfterSync) { - const char *posixTz = ianaToPosix(timeZone); - setenv("TZ", posixTz, 1); - tzset(); - tzSetAfterSync = true; - } - ntpAnimTimer = 0; - ntpAnimFrame = 0; - break; - case NTP_FAILED: - ntpAnimTimer = 0; - ntpAnimFrame = 0; - break; - } - - // --- MODIFIED WEATHER FETCHING LOGIC --- - if (WiFi.status() == WL_CONNECTED) { - // Check if an immediate fetch is requested OR if the regular interval has passed - if (!weatherFetchInitiated || shouldFetchWeatherNow || (millis() - lastFetch > fetchInterval)) { - if (shouldFetchWeatherNow) { - Serial.println(F("[LOOP] Immediate weather fetch requested by web server.")); - shouldFetchWeatherNow = false; // Reset the flag after handling - } else if (!weatherFetchInitiated) { - Serial.println(F("[LOOP] Initial weather fetch.")); - } else { - Serial.println(F("[LOOP] Regular interval weather fetch.")); - } - - weatherFetchInitiated = true; - weatherFetched = false; // Mark as not yet fetched - fetchWeather(); - lastFetch = millis(); - } - } else { - weatherFetchInitiated = false; - // It's good practice to reset the flag if WiFi disconnects to avoid stale requests - shouldFetchWeatherNow = false; - } - // --- END MODIFIED WEATHER FETCHING LOGIC --- - - const char *const *daysOfTheWeek = getDaysOfWeek(language); - const char *daySymbol = daysOfTheWeek[timeinfo.tm_wday]; - - char timeStr[9]; - if (twelveHourToggle) { - int hour12 = timeinfo.tm_hour % 12; - if (hour12 == 0) hour12 = 12; - sprintf(timeStr, " %d:%02d", hour12, timeinfo.tm_min); - } else { - sprintf(timeStr, " %02d:%02d", timeinfo.tm_hour, timeinfo.tm_min); - } - - char timeSpacedStr[20]; - int j = 0; - for (int i = 0; timeStr[i] != '\0'; i++) { - timeSpacedStr[j++] = timeStr[i]; - if (timeStr[i + 1] != '\0') { - timeSpacedStr[j++] = ' '; - } - } - timeSpacedStr[j] = '\0'; - - String formattedTime; - if (showDayOfWeek) { - formattedTime = String(daySymbol) + " " + String(timeSpacedStr); - } else { - formattedTime = String(timeSpacedStr); - } - - // --- Weather Description Mode handling --- - static unsigned long descStartTime = 0; - static bool descScrolling = false; - static unsigned long descScrollEndTime = 0; // for post-scroll delay - const unsigned long descriptionDuration = 3000; // 3s for short text - const unsigned long descriptionScrollPause = 300; // 300ms pause after scroll - - // Only advance mode by timer for clock/weather, not description! - unsigned long displayDuration = (displayMode == 0) ? clockDuration : weatherDuration; - if ((displayMode == 0 || displayMode == 1) && millis() - lastSwitch > displayDuration) { - advanceDisplayMode(); - } - - // --- WEATHER DESCRIPTION Display Mode --- - if (displayMode == 2 && showWeatherDescription && weatherAvailable && weatherDescription.length() > 0) { - String desc = weatherDescription; - desc.toUpperCase(); - - if (desc.length() > 8) { - if (!descScrolling) { - P.displayClear(); - textEffect_t actualScrollDirection = getEffectiveScrollDirection(PA_SCROLL_LEFT, flipDisplay); - P.displayScroll(desc.c_str(), PA_CENTER, actualScrollDirection, 100); - descScrolling = true; - descScrollEndTime = 0; // reset end time at start - } - if (P.displayAnimate()) { - if (descScrollEndTime == 0) { - descScrollEndTime = millis(); // mark the time when scroll finishes - } - // wait small pause after scroll stops - if (millis() - descScrollEndTime > descriptionScrollPause) { - descScrolling = false; - descScrollEndTime = 0; - advanceDisplayMode(); - } - } else { - descScrollEndTime = 0; // reset if not finished - } - yield(); - return; - } else { - if (descStartTime == 0) { - P.setTextAlignment(PA_CENTER); - P.setCharSpacing(1); - P.print(desc.c_str()); - descStartTime = millis(); - } - if (millis() - descStartTime > descriptionDuration) { - descStartTime = 0; - advanceDisplayMode(); - } - yield(); - return; - } - } - - static bool weatherWasAvailable = false; - // --- CLOCK Display Mode --- - if (displayMode == 0) { - P.setCharSpacing(0); - if (ntpState == NTP_SYNCING) { - if (millis() - ntpAnimTimer > 750) { - ntpAnimTimer = millis(); - switch (ntpAnimFrame % 3) { - case 0: P.print(F("S Y N C ®")); break; - case 1: P.print(F("S Y N C ¯")); break; - case 2: P.print(F("S Y N C °")); break; - } - ntpAnimFrame++; - } - } else if (!ntpSyncSuccessful) { - P.setTextAlignment(PA_CENTER); - P.print(F("?/")); - } else { - String timeString = formattedTime; - if (!colonVisible) timeString.replace(":", " "); - P.print(timeString); - } - yield(); - return; - } - - // --- WEATHER Display Mode --- - if (displayMode == 1) { - P.setCharSpacing(1); - if (weatherAvailable) { - String weatherDisplay; - if (showHumidity && currentHumidity != -1) { - int cappedHumidity = (currentHumidity > 99) ? 99 : currentHumidity; - weatherDisplay = currentTemp + " " + String(cappedHumidity) + "%"; - } else { - weatherDisplay = currentTemp + tempSymbol; - } - P.print(weatherDisplay.c_str()); - weatherWasAvailable = true; - } else { - if (weatherWasAvailable) { - Serial.println(F("[DISPLAY] Weather not available, showing clock...")); - weatherWasAvailable = false; - } - if (ntpSyncSuccessful) { - String timeString = formattedTime; - if (!colonVisible) timeString.replace(":", " "); - P.setCharSpacing(0); - P.print(timeString); - } else { - P.setCharSpacing(0); - P.setTextAlignment(PA_CENTER); - P.print(F("?*")); - } - } - yield(); - return; - } - - yield(); +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mfactoryfont.h" // Custom font +#include "tz_lookup.h" // Timezone lookup, do not duplicate mapping here! +#include "days_lookup.h" // Languages for the Days of the Week + +#define HARDWARE_TYPE MD_MAX72XX::FC16_HW +#define MAX_DEVICES 4 +#define CLK_PIN 12 +#define DATA_PIN 15 +#define CS_PIN 13 + +MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES); +AsyncWebServer server(80); + +// WiFi and configuration globals +char ssid[32] = ""; +char password[32] = ""; +char openWeatherApiKey[64] = ""; +char openWeatherCity[64] = ""; +char openWeatherCountry[64] = ""; +char weatherUnits[12] = "metric"; +char timeZone[64] = ""; +char language[8] = "en"; +String mainDesc = ""; +String detailedDesc = ""; + +// Timing and display settings +unsigned long clockDuration = 10000; +unsigned long weatherDuration = 5000; +int brightness = 7; +bool flipDisplay = false; +bool twelveHourToggle = false; +bool showDayOfWeek = true; +bool showHumidity = false; +char ntpServer1[64] = "pool.ntp.org"; +char ntpServer2[64] = "time.nist.gov"; + +// Dimming +bool dimmingEnabled = false; +int dimStartHour = 18; // 6pm default +int dimStartMinute = 0; +int dimEndHour = 8; // 8am default +int dimEndMinute = 0; +int dimBrightness = 2; // Dimming level (0-15) + +// State management +bool weatherCycleStarted = false; +WiFiClient client; +const byte DNS_PORT = 53; +DNSServer dnsServer; + +String currentTemp = ""; +String weatherDescription = ""; +bool showWeatherDescription = false; +bool weatherAvailable = false; +bool weatherFetched = false; +bool weatherFetchInitiated = false; +bool isAPMode = false; +char tempSymbol = '['; +bool shouldFetchWeatherNow = false; // Flag to trigger immediate weather fetch + +unsigned long lastSwitch = 0; +unsigned long lastColonBlink = 0; +int displayMode = 0; +int currentHumidity = -1; +bool ntpSyncSuccessful = false; + +// NTP Synchronization State Machine +enum NtpState { + NTP_IDLE, + NTP_SYNCING, + NTP_SUCCESS, + NTP_FAILED +}; +NtpState ntpState = NTP_IDLE; +unsigned long ntpStartTime = 0; +const int ntpTimeout = 30000; // 30 seconds +const int maxNtpRetries = 30; +int ntpRetryCount = 0; + +// Non-blocking IP display globals +bool showingIp = false; +int ipDisplayCount = 0; +const int ipDisplayMax = 1; +String pendingIpToShow = ""; + +// Scroll flipped +textEffect_t getEffectiveScrollDirection(textEffect_t desiredDirection, bool isFlipped) { + if (isFlipped) { + // If the display is horizontally flipped, reverse the horizontal scroll direction + if (desiredDirection == PA_SCROLL_LEFT) { + return PA_SCROLL_RIGHT; + } else if (desiredDirection == PA_SCROLL_RIGHT) { + return PA_SCROLL_LEFT; + } + } + return desiredDirection; +} + +// ----------------------------------------------------------------------------- +// Configuration Load & Save +// ----------------------------------------------------------------------------- +void loadConfig() { + Serial.println(F("[CONFIG] Loading configuration...")); + + if (!LittleFS.exists("/config.json")) { + Serial.println(F("[CONFIG] config.json not found, creating with defaults...")); + DynamicJsonDocument doc(512); + doc[F("ssid")] = ""; + doc[F("password")] = ""; + doc[F("openWeatherApiKey")] = ""; + doc[F("openWeatherCity")] = ""; + doc[F("openWeatherCountry")] = ""; + doc[F("weatherUnits")] = "metric"; + doc[F("clockDuration")] = 10000; + doc[F("weatherDuration")] = 5000; + doc[F("timeZone")] = ""; + doc[F("language")] = "en"; + doc[F("brightness")] = brightness; + doc[F("flipDisplay")] = flipDisplay; + doc[F("twelveHourToggle")] = twelveHourToggle; + doc[F("showDayOfWeek")] = showDayOfWeek; + doc[F("showHumidity")] = showHumidity; + doc[F("ntpServer1")] = ntpServer1; + doc[F("ntpServer2")] = ntpServer2; + doc[F("dimmingEnabled")] = dimmingEnabled; + doc[F("dimStartHour")] = dimStartHour; + doc[F("dimEndHour")] = dimEndHour; + doc[F("dimBrightness")] = dimBrightness; + File f = LittleFS.open("/config.json", "w"); + if (f) { + serializeJsonPretty(doc, f); + f.close(); + Serial.println(F("[CONFIG] Default config.json created.")); + } else { + Serial.println(F("[ERROR] Failed to create default config.json")); + } + } + + File configFile = LittleFS.open("/config.json", "r"); + if (!configFile) { + Serial.println(F("[ERROR] Failed to open config.json for reading. Cannot load config.")); + return; + } + + DynamicJsonDocument doc(2048); + DeserializationError error = deserializeJson(doc, configFile); + configFile.close(); + + if (error) { + Serial.print(F("[ERROR] JSON parse failed during load: ")); + Serial.println(error.f_str()); + return; + } + + strlcpy(ssid, doc["ssid"] | "", sizeof(ssid)); + strlcpy(password, doc["password"] | "", sizeof(password)); + strlcpy(openWeatherApiKey, doc["openWeatherApiKey"] | "", sizeof(openWeatherApiKey)); + strlcpy(openWeatherCity, doc["openWeatherCity"] | "", sizeof(openWeatherCity)); + strlcpy(openWeatherCountry, doc["openWeatherCountry"] | "", sizeof(openWeatherCountry)); + strlcpy(weatherUnits, doc["weatherUnits"] | "metric", sizeof(weatherUnits)); + clockDuration = doc["clockDuration"] | 10000; + weatherDuration = doc["weatherDuration"] | 5000; + strlcpy(timeZone, doc["timeZone"] | "Etc/UTC", sizeof(timeZone)); + if (doc.containsKey("language")) { + strlcpy(language, doc["language"], sizeof(language)); + } else { + strlcpy(language, "en", sizeof(language)); + Serial.println(F("[CONFIG] 'language' key not found in config.json, defaulting to 'en'.")); + } + + brightness = doc["brightness"] | 7; + flipDisplay = doc["flipDisplay"] | false; + twelveHourToggle = doc["twelveHourToggle"] | false; + showDayOfWeek = doc["showDayOfWeek"] | true; + showHumidity = doc["showHumidity"] | false; + + String de = doc["dimmingEnabled"].as(); + dimmingEnabled = (de == "true" || de == "on" || de == "1"); + + dimStartHour = doc["dimStartHour"] | 18; + dimStartMinute = doc["dimStartMinute"] | 0; + dimEndHour = doc["dimEndHour"] | 8; + dimEndMinute = doc["dimEndMinute"] | 0; + dimBrightness = doc["dimBrightness"] | 0; + + strlcpy(ntpServer1, doc["ntpServer1"] | "pool.ntp.org", sizeof(ntpServer1)); + strlcpy(ntpServer2, doc["ntpServer2"] | "time.nist.gov", sizeof(ntpServer2)); + + if (strcmp(weatherUnits, "imperial") == 0) + tempSymbol = ']'; + else + tempSymbol = '['; + Serial.println(F("[CONFIG] Configuration loaded.")); + + if (doc.containsKey("showWeatherDescription")) + showWeatherDescription = doc["showWeatherDescription"]; + else + showWeatherDescription = false; +} + +// ----------------------------------------------------------------------------- +// WiFi Setup +// ----------------------------------------------------------------------------- +const char *DEFAULT_AP_PASSWORD = "12345678"; +const char *AP_SSID = "ESPTimeCast"; + +void connectWiFi() { + Serial.println(F("[WIFI] Connecting to WiFi...")); + + bool credentialsExist = (strlen(ssid) > 0); + + if (!credentialsExist) { + Serial.println(F("[WIFI] No saved credentials. Starting AP mode directly.")); + WiFi.mode(WIFI_AP); + WiFi.disconnect(true); + delay(100); + + if (strlen(DEFAULT_AP_PASSWORD) < 8) { + WiFi.softAP(AP_SSID); + Serial.println(F("[WIFI] AP Mode started (no password, too short).")); + } else { + WiFi.softAP(AP_SSID, DEFAULT_AP_PASSWORD); + Serial.println(F("[WIFI] AP Mode started.")); + } + + IPAddress apIP(192, 168, 4, 1); + WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); + dnsServer.start(DNS_PORT, "*", WiFi.softAPIP()); + Serial.print(F("AP IP address: ")); + Serial.println(WiFi.softAPIP()); + isAPMode = true; + Serial.println(F("[WIFI] AP Mode Started")); + return; + } + + WiFi.disconnect(true); + delay(100); + WiFi.begin(ssid, password); + unsigned long startAttemptTime = millis(); + const unsigned long timeout = 25000; + unsigned long animTimer = 0; + int animFrame = 0; + bool animating = true; + + while (animating) { + unsigned long now = millis(); + if (WiFi.status() == WL_CONNECTED) { + Serial.println(F("[WIFI] Connected: ") + WiFi.localIP().toString()); + isAPMode = false; + animating = false; + + pendingIpToShow = WiFi.localIP().toString(); + showingIp = true; + ipDisplayCount = 0; + P.displayClear(); + P.setCharSpacing(1); + textEffect_t actualScrollDirection = getEffectiveScrollDirection(PA_SCROLL_LEFT, flipDisplay); + P.displayScroll(pendingIpToShow.c_str(), PA_CENTER, actualScrollDirection, 120); + break; + } else if (now - startAttemptTime >= timeout) { + Serial.println(F("\r\n[WiFi] Failed. Starting AP mode...")); + WiFi.softAP(AP_SSID, DEFAULT_AP_PASSWORD); + Serial.print(F("AP IP address: ")); + Serial.println(WiFi.softAPIP()); + dnsServer.start(DNS_PORT, "*", WiFi.softAPIP()); + isAPMode = true; + animating = false; + Serial.println(F("[WIFI] AP Mode Started")); + break; + } + if (now - animTimer > 750) { + animTimer = now; + P.setTextAlignment(PA_CENTER); + switch (animFrame % 3) { + case 0: P.print(F("# ©")); break; + case 1: P.print(F("# ª")); break; + case 2: P.print(F("# «")); break; + } + animFrame++; + } + yield(); + } +} + +// ----------------------------------------------------------------------------- +// Time / NTP Functions +// ----------------------------------------------------------------------------- +void setupTime() { + sntp_stop(); + if (!isAPMode) { + Serial.println(F("[TIME] Starting NTP sync...")); + } + configTime(0, 0, ntpServer1, ntpServer2); + setenv("TZ", ianaToPosix(timeZone), 1); + tzset(); + ntpState = NTP_SYNCING; + ntpStartTime = millis(); + ntpRetryCount = 0; + ntpSyncSuccessful = false; +} + +// ----------------------------------------------------------------------------- +// Utility +// ----------------------------------------------------------------------------- +void printConfigToSerial() { + Serial.println(F("========= Loaded Configuration =========")); + Serial.print(F("WiFi SSID: ")); + Serial.println(ssid); + Serial.print(F("WiFi Password: ")); + Serial.println(password); + Serial.print(F("OpenWeather City: ")); + Serial.println(openWeatherCity); + Serial.print(F("OpenWeather Country: ")); + Serial.println(openWeatherCountry); + Serial.print(F("OpenWeather API Key: ")); + Serial.println(openWeatherApiKey); + Serial.print(F("Temperature Unit: ")); + Serial.println(weatherUnits); + Serial.print(F("Clock duration: ")); + Serial.println(clockDuration); + Serial.print(F("Weather duration: ")); + Serial.println(weatherDuration); + Serial.print(F("TimeZone (IANA): ")); + Serial.println(timeZone); + Serial.print(F("Days of the Week/Weather description language: ")); + Serial.println(language); + Serial.print(F("Brightness: ")); + Serial.println(brightness); + Serial.print(F("Flip Display: ")); + Serial.println(flipDisplay ? "Yes" : "No"); + Serial.print(F("Show 12h Clock: ")); + Serial.println(twelveHourToggle ? "Yes" : "No"); + Serial.print(F("Show Day of the Week: ")); + Serial.println(showDayOfWeek ? "Yes" : "No"); + Serial.print(F("Show Weather Description: ")); + Serial.println(showWeatherDescription ? "Yes" : "No"); + Serial.print(F("Show Humidity ")); + Serial.println(showHumidity ? "Yes" : "No"); + Serial.print(F("NTP Server 1: ")); + Serial.println(ntpServer1); + Serial.print(F("NTP Server 2: ")); + Serial.println(ntpServer2); + Serial.print(F("Dimming Enabled: ")); + Serial.println(dimmingEnabled); + Serial.print(F("Dimming Start Hour: ")); + Serial.println(dimStartHour); + Serial.print(F("Dimming Start Minute: ")); + Serial.println(dimStartMinute); + Serial.print(F("Dimming End Hour: ")); + Serial.println(dimEndHour); + Serial.print(F("Dimming End Minute: ")); + Serial.println(dimEndMinute); + Serial.print(F("Dimming Brightness: ")); + Serial.println(dimBrightness); + Serial.println(F("========================================")); + Serial.println(); +} + +// ----------------------------------------------------------------------------- +// Web Server and Captive Portal +// ----------------------------------------------------------------------------- +void handleCaptivePortal(AsyncWebServerRequest *request); + +void setupWebServer() { + Serial.println(F("[WEBSERVER] Setting up web server...")); + + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { + Serial.println(F("[WEBSERVER] Request: /")); + request->send(LittleFS, "/index.html", "text/html"); + }); + + server.on("/config.json", HTTP_GET, [](AsyncWebServerRequest *request) { + Serial.println(F("[WEBSERVER] Request: /config.json")); + File f = LittleFS.open("/config.json", "r"); + if (!f) { + Serial.println(F("[WEBSERVER] Error opening /config.json")); + request->send(500, "application/json", "{\"error\":\"Failed to open config.json\"}"); + return; + } + DynamicJsonDocument doc(2048); + DeserializationError err = deserializeJson(doc, f); + f.close(); + if (err) { + Serial.print(F("[WEBSERVER] Error parsing /config.json: ")); + Serial.println(err.f_str()); + request->send(500, "application/json", "{\"error\":\"Failed to parse config.json\"}"); + return; + } + doc[F("mode")] = isAPMode ? "ap" : "sta"; + String response; + serializeJson(doc, response); + request->send(200, "application/json", response); + }); + + // Save, restore, status and settings handlers grouped for clarity + server.on("/save", HTTP_POST, [](AsyncWebServerRequest *request) { + Serial.println(F("[WEBSERVER] Request: /save")); + DynamicJsonDocument doc(2048); + + File configFile = LittleFS.open("/config.json", "r"); + if (configFile) { + Serial.println(F("[WEBSERVER] Existing config.json found, loading...")); + DeserializationError err = deserializeJson(doc, configFile); + configFile.close(); + if (err) { + Serial.print(F("[WEBSERVER] Error parsing existing config.json: ")); + Serial.println(err.f_str()); + } + } else { + Serial.println(F("[WEBSERVER] config.json not found, starting with empty doc.")); + } + + for (int i = 0; i < request->params(); i++) { + const AsyncWebParameter *p = request->getParam(i); + String n = p->name(); + String v = p->value(); + + Serial.printf("[SAVE] Param: %s = %s\n", n.c_str(), v.c_str()); + + if (n == "brightness") doc[n] = v.toInt(); + else if (n == "clockDuration") doc[n] = v.toInt(); + else if (n == "weatherDuration") doc[n] = v.toInt(); + else if (n == "flipDisplay") doc[n] = (v == "true" || v == "on" || v == "1"); + else if (n == "twelveHourToggle") doc[n] = (v == "true" || v == "on" || v == "1"); + else if (n == "showDayOfWeek") doc[n] = (v == "true" || v == "on" || v == "1"); + else if (n == "showHumidity") doc[n] = (v == "true" || v == "on" || v == "1"); + else if (n == "dimStartHour") doc[n] = v.toInt(); + else if (n == "dimStartMinute") doc[n] = v.toInt(); + else if (n == "dimEndHour") doc[n] = v.toInt(); + else if (n == "dimEndMinute") doc[n] = v.toInt(); + else if (n == "dimBrightness") doc[n] = v.toInt(); + else if (n == "showWeatherDescription") doc[n] = (v == "true" || v == "on" || v == "1"); + else doc[n] = v; + } + + Serial.print(F("[SAVE] Document content before saving: ")); + serializeJson(doc, Serial); + Serial.println(); + + FSInfo fs_info; + LittleFS.info(fs_info); + Serial.printf("[SAVE] LittleFS total bytes: %u, used bytes: %u\n", fs_info.totalBytes, fs_info.usedBytes); + + if (LittleFS.exists("/config.json")) { + Serial.println(F("[SAVE] Renaming /config.json to /config.bak")); + LittleFS.rename("/config.json", "/config.bak"); + } + File f = LittleFS.open("/config.json", "w"); + if (!f) { + Serial.println(F("[SAVE] ERROR: Failed to open /config.json for writing!")); + DynamicJsonDocument errorDoc(256); + errorDoc[F("error")] = "Failed to write config file."; + String response; + serializeJson(errorDoc, response); + request->send(500, "application/json", response); + return; + } + + size_t bytesWritten = serializeJson(doc, f); + Serial.printf("[SAVE] Bytes written to /config.json: %u\n", bytesWritten); + f.close(); + Serial.println(F("[SAVE] /config.json file closed.")); + + Serial.println(F("[SAVE] Attempting to open /config.json for verification.")); + File verify = LittleFS.open("/config.json", "r"); + if (!verify) { + Serial.println(F("[SAVE] ERROR: Failed to open /config.json for reading during verification!")); + DynamicJsonDocument errorDoc(256); + errorDoc[F("error")] = "Verification failed: Could not re-open config file."; + String response; + serializeJson(errorDoc, response); + request->send(500, "application/json", response); + return; + } + + Serial.println(F("[SAVE] Content of /config.json during verification read:")); + while (verify.available()) { + Serial.write(verify.read()); + } + Serial.println(); + verify.seek(0); + + DynamicJsonDocument test(2048); + DeserializationError err = deserializeJson(test, verify); + verify.close(); + + if (err) { + Serial.print(F("[SAVE] Config corrupted after save: ")); + Serial.println(err.f_str()); + DynamicJsonDocument errorDoc(256); + errorDoc[F("error")] = String("Config corrupted. Reboot cancelled. Error: ") + err.f_str(); + String response; + serializeJson(errorDoc, response); + request->send(500, "application/json", response); + return; + } + + Serial.println(F("[SAVE] Config verification successful.")); + DynamicJsonDocument okDoc(128); + okDoc[F("message")] = "Saved successfully. Rebooting..."; + String response; + serializeJson(okDoc, response); + request->send(200, "application/json", response); + Serial.println(F("[WEBSERVER] Sending success response and scheduling reboot...")); + + request->onDisconnect([]() { + Serial.println(F("[WEBSERVER] Client disconnected, rebooting ESP...")); + ESP.restart(); + }); + }); + + server.on("/restore", HTTP_POST, [](AsyncWebServerRequest *request) { + Serial.println(F("[WEBSERVER] Request: /restore")); + if (LittleFS.exists("/config.bak")) { + File src = LittleFS.open("/config.bak", "r"); + if (!src) { + Serial.println(F("[WEBSERVER] Failed to open /config.bak")); + DynamicJsonDocument errorDoc(128); + errorDoc[F("error")] = "Failed to open backup file."; + String response; + serializeJson(errorDoc, response); + request->send(500, "application/json", response); + return; + } + File dst = LittleFS.open("/config.json", "w"); + if (!dst) { + src.close(); + Serial.println(F("[WEBSERVER] Failed to open /config.json for writing")); + DynamicJsonDocument errorDoc(128); + errorDoc[F("error")] = "Failed to open config for writing."; + String response; + serializeJson(errorDoc, response); + request->send(500, "application/json", response); + return; + } + + while (src.available()) { + dst.write(src.read()); + } + src.close(); + dst.close(); + + DynamicJsonDocument okDoc(128); + okDoc[F("message")] = "✅ Backup restored! Device will now reboot."; + String response; + serializeJson(okDoc, response); + request->send(200, "application/json", response); + request->onDisconnect([]() { + Serial.println(F("[WEBSERVER] Rebooting after restore...")); + ESP.restart(); + }); + + } else { + Serial.println(F("[WEBSERVER] No backup found")); + DynamicJsonDocument errorDoc(128); + errorDoc[F("error")] = "No backup found."; + String response; + serializeJson(errorDoc, response); + request->send(404, "application/json", response); + } + }); + + server.on("/ap_status", HTTP_GET, [](AsyncWebServerRequest *request) { + Serial.print(F("[WEBSERVER] Request: /ap_status. isAPMode = ")); + Serial.println(isAPMode); + String json = "{\"isAP\": "; + json += (isAPMode) ? "true" : "false"; + json += "}"; + request->send(200, "application/json", json); + }); + + // Settings endpoints (brightness, flip, etc.) + server.on("/set_brightness", HTTP_POST, [](AsyncWebServerRequest *request) { + if (!request->hasParam("value", true)) { + request->send(400, "application/json", "{\"error\":\"Missing value\"}"); + return; + } + int newBrightness = request->getParam("value", true)->value().toInt(); + if (newBrightness < 0) newBrightness = 0; + if (newBrightness > 15) newBrightness = 15; + brightness = newBrightness; + P.setIntensity(brightness); + Serial.printf("[WEBSERVER] Set brightness to %d\n", brightness); + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_flip", HTTP_POST, [](AsyncWebServerRequest *request) { + bool flip = false; + if (request->hasParam("value", true)) { + String v = request->getParam("value", true)->value(); + flip = (v == "1" || v == "true" || v == "on"); + } + flipDisplay = flip; + P.setZoneEffect(0, flipDisplay, PA_FLIP_UD); + P.setZoneEffect(0, flipDisplay, PA_FLIP_LR); + Serial.printf("[WEBSERVER] Set flipDisplay to %d\n", flipDisplay); + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_twelvehour", HTTP_POST, [](AsyncWebServerRequest *request) { + bool twelveHour = false; + if (request->hasParam("value", true)) { + String v = request->getParam("value", true)->value(); + twelveHour = (v == "1" || v == "true" || v == "on"); + } + twelveHourToggle = twelveHour; + Serial.printf("[WEBSERVER] Set twelveHourToggle to %d\n", twelveHourToggle); + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_dayofweek", HTTP_POST, [](AsyncWebServerRequest *request) { + bool showDay = false; + if (request->hasParam("value", true)) { + String v = request->getParam("value", true)->value(); + showDay = (v == "1" || v == "true" || v == "on"); + } + showDayOfWeek = showDay; + Serial.printf("[WEBSERVER] Set showDayOfWeek to %d\n", showDayOfWeek); + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_humidity", HTTP_POST, [](AsyncWebServerRequest *request) { + bool showHumidityNow = false; + if (request->hasParam("value", true)) { + String v = request->getParam("value", true)->value(); + showHumidityNow = (v == "1" || v == "true" || v == "on"); + } + showHumidity = showHumidityNow; + Serial.printf("[WEBSERVER] Set showHumidity to %d\n", showHumidity); + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_language", HTTP_POST, [](AsyncWebServerRequest *request) { + if (!request->hasParam("value", true)) { + request->send(400, "application/json", "{\"error\":\"Missing value\"}"); + return; + } + String lang = request->getParam("value", true)->value(); + strlcpy(language, lang.c_str(), sizeof(language)); + Serial.printf("[WEBSERVER] Set language to %s\n", language); + shouldFetchWeatherNow = true; + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_weatherdesc", HTTP_POST, [](AsyncWebServerRequest *request) { + bool showDesc = false; + if (request->hasParam("value", true)) { + String v = request->getParam("value", true)->value(); + showDesc = (v == "1" || v == "true" || v == "on"); + } + showWeatherDescription = showDesc; + Serial.printf("[WEBSERVER] Set showWeatherDescription to %d\n", showWeatherDescription); + request->send(200, "application/json", "{\"ok\":true}"); + }); + + server.on("/set_units", HTTP_POST, [](AsyncWebServerRequest *request) { + if (request->hasParam("value", true)) { + String v = request->getParam("value", true)->value(); + if (v == "1" || v == "true" || v == "on") { + strcpy(weatherUnits, "imperial"); + tempSymbol = ']'; // Fahrenheit symbol + } else { + strcpy(weatherUnits, "metric"); + tempSymbol = '['; // Celsius symbol + } + Serial.printf("[WEBSERVER] Set weatherUnits to %s\n", weatherUnits); + shouldFetchWeatherNow = true; + request->send(200, "application/json", "{\"ok\":true}"); + } else { + request->send(400, "application/json", "{\"error\":\"Missing value parameter\"}"); + } + }); + + server.begin(); + Serial.println(F("[WEBSERVER] Web server started")); +} + +void handleCaptivePortal(AsyncWebServerRequest *request) { + Serial.print(F("[WEBSERVER] Captive Portal Redirecting: ")); + Serial.println(request->url()); + request->redirect(String("http://") + WiFi.softAPIP().toString() + "/"); +} + +// ----------------------------------------------------------------------------- +// Weather Fetching and API settings +// ----------------------------------------------------------------------------- +String normalizeWeatherDescription(String str) { + str.replace("å", "a"); + str.replace("ä", "a"); + str.replace("à", "a"); + str.replace("á", "a"); + str.replace("â", "a"); + str.replace("ã", "a"); + str.replace("ā", "a"); + str.replace("ă", "a"); + str.replace("ą", "a"); + + str.replace("æ", "ae"); + + str.replace("ç", "c"); + str.replace("č", "c"); + str.replace("ć", "c"); + + str.replace("ď", "d"); + + str.replace("é", "e"); + str.replace("è", "e"); + str.replace("ê", "e"); + str.replace("ë", "e"); + str.replace("ē", "e"); + str.replace("ė", "e"); + str.replace("ę", "e"); + + str.replace("ğ", "g"); + str.replace("ģ", "g"); + + str.replace("ĥ", "h"); + + str.replace("í", "i"); + str.replace("ì", "i"); + str.replace("î", "i"); + str.replace("ï", "i"); + str.replace("ī", "i"); + str.replace("į", "i"); + + str.replace("ĵ", "j"); + + str.replace("ķ", "k"); + + str.replace("ľ", "l"); + str.replace("ł", "l"); + + str.replace("ñ", "n"); + str.replace("ń", "n"); + str.replace("ņ", "n"); + + str.replace("ó", "o"); + str.replace("ò", "o"); + str.replace("ô", "o"); + str.replace("ö", "o"); + str.replace("õ", "o"); + str.replace("ø", "o"); + str.replace("ō", "o"); + str.replace("ő", "o"); + + str.replace("œ", "oe"); + + str.replace("ŕ", "r"); + + str.replace("ś", "s"); + str.replace("š", "s"); + str.replace("ș", "s"); + str.replace("ŝ", "s"); + + str.replace("ß", "ss"); + + str.replace("ť", "t"); + str.replace("ț", "t"); + + str.replace("ú", "u"); + str.replace("ù", "u"); + str.replace("û", "u"); + str.replace("ü", "u"); + str.replace("ū", "u"); + str.replace("ů", "u"); + str.replace("ű", "u"); + + str.replace("ŵ", "w"); + + str.replace("ý", "y"); + str.replace("ÿ", "y"); + str.replace("ŷ", "y"); + + str.replace("ž", "z"); + str.replace("ź", "z"); + str.replace("ż", "z"); + + str.toLowerCase(); + // Filter out anything that's not a–z or space + String result = ""; + for (unsigned int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if ((c >= 'a' && c <= 'z') || c == ' ') { + result += c; + } + // else: ignore punctuation, emoji, symbols + } + return result; +} + +bool isNumber(const char *str) { + for (int i = 0; str[i]; i++) { + if (!isdigit(str[i]) && str[i] != '.' && str[i] != '-') return false; + } + return true; +} + +bool isFiveDigitZip(const char *str) { + if (strlen(str) != 5) return false; + for (int i = 0; i < 5; i++) { + if (!isdigit(str[i])) return false; + } + return true; +} + +String buildWeatherURL() { + String base = "http://api.openweathermap.org/data/2.5/weather?"; + + float lat = atof(openWeatherCity); + float lon = atof(openWeatherCountry); + + bool latValid = isNumber(openWeatherCity) && isNumber(openWeatherCountry) && lat >= -90.0 && lat <= 90.0 && lon >= -180.0 && lon <= 180.0; + + if (latValid) { + base += "lat=" + String(lat, 8) + "&lon=" + String(lon, 8); + } else if (isFiveDigitZip(openWeatherCity) && String(openWeatherCountry).equalsIgnoreCase("US")) { + base += "zip=" + String(openWeatherCity) + "," + String(openWeatherCountry); + } else { + base += "q=" + String(openWeatherCity) + "," + String(openWeatherCountry); + } + + base += "&appid=" + String(openWeatherApiKey); + base += "&units=" + String(weatherUnits); + + String langForAPI = String(language); // Start with the global language + + if (langForAPI == "eo" || langForAPI == "sw" || langForAPI == "ja") { + langForAPI = "en"; // Override to "en" for the API + } + base += "&lang=" + langForAPI; + + return base; +} + +void fetchWeather() { + Serial.println(F("[WEATHER] Fetching weather data...")); + if (WiFi.status() != WL_CONNECTED) { + Serial.println(F("[WEATHER] Skipped: WiFi not connected")); + weatherAvailable = false; + weatherFetched = false; + return; + } + if (!openWeatherApiKey || strlen(openWeatherApiKey) != 32) { + Serial.println(F("[WEATHER] Skipped: Invalid API key (must be exactly 32 characters)")); + weatherAvailable = false; + weatherFetched = false; + return; + } + if (!(strlen(openWeatherCity) > 0 && strlen(openWeatherCountry) > 0)) { + Serial.println(F("[WEATHER] Skipped: City or Country is empty.")); + return; + } + + Serial.println(F("[WEATHER] Connecting to OpenWeatherMap...")); + const char *host = "api.openweathermap.org"; + String url = buildWeatherURL(); + Serial.println(F("[WEATHER] URL: ") + url); + + IPAddress ip; + if (!WiFi.hostByName(host, ip)) { + Serial.println(F("[WEATHER] DNS lookup failed!")); + weatherAvailable = false; + return; + } + + if (!client.connect(host, 80)) { + Serial.println(F("[WEATHER] Connection failed")); + weatherAvailable = false; + return; + } + + Serial.println(F("[WEATHER] Connected, sending request...")); + String request = String("GET ") + url + " HTTP/1.1\r\n" + F("Host: ") + host + F("\r\n") + F("Connection: close\r\n\r\n"); + + if (!client.print(request)) { + Serial.println(F("[WEATHER] Failed to send request!")); + client.stop(); + weatherAvailable = false; + return; + } + + unsigned long weatherStart = millis(); + const unsigned long weatherTimeout = 10000; + + bool isBody = false; + String payload = ""; + String line = ""; + + while ((client.connected() || client.available()) && millis() - weatherStart < weatherTimeout && WiFi.status() == WL_CONNECTED) { + line = client.readStringUntil('\n'); + if (line.length() == 0) continue; + + if (line.startsWith(F("HTTP/1.1"))) { + int statusCode = line.substring(9, 12).toInt(); + if (statusCode != 200) { + Serial.print(F("[WEATHER] HTTP error: ")); + Serial.println(statusCode); + client.stop(); + weatherAvailable = false; + return; + } + } + + if (!isBody && line == F("\r")) { + isBody = true; + while (client.available()) { + payload += (char)client.read(); + } + break; + } + yield(); + } + client.stop(); + + if (millis() - weatherStart >= weatherTimeout) { + Serial.println(F("[WEATHER] ERROR: Weather fetch timed out!")); + weatherAvailable = false; + return; + } + + Serial.println(F("[WEATHER] Response received.")); + Serial.println(F("[WEATHER] Payload: ") + payload); + + DynamicJsonDocument doc(2048); + DeserializationError error = deserializeJson(doc, payload); + if (error) { + Serial.print(F("[WEATHER] JSON parse error: ")); + Serial.println(error.f_str()); + weatherAvailable = false; + return; + } + + if (doc.containsKey(F("main")) && doc[F("main")].containsKey(F("temp"))) { + float temp = doc[F("main")][F("temp")]; + currentTemp = String((int)round(temp)) + "º"; + Serial.printf("[WEATHER] Temp: %s\n", currentTemp.c_str()); + weatherAvailable = true; + } else { + Serial.println(F("[WEATHER] Temperature not found in JSON payload")); + weatherAvailable = false; + return; + } + + if (doc.containsKey(F("main")) && doc[F("main")].containsKey(F("humidity"))) { + currentHumidity = doc[F("main")][F("humidity")]; + Serial.printf("[WEATHER] Humidity: %d%%\n", currentHumidity); + } else { + currentHumidity = -1; + } + + if (doc.containsKey(F("weather")) && doc[F("weather")].is()) { + JsonObject weatherObj = doc[F("weather")][0]; + if (weatherObj.containsKey(F("main"))) { + mainDesc = weatherObj[F("main")].as(); + } + if (weatherObj.containsKey(F("description"))) { + detailedDesc = weatherObj[F("description")].as(); + } + } else { + Serial.println(F("[WEATHER] Weather description not found in JSON payload")); + } + + weatherDescription = normalizeWeatherDescription(detailedDesc); + + Serial.printf("[WEATHER] Description used: %s\n", weatherDescription.c_str()); + + weatherFetched = true; +} + +// ----------------------------------------------------------------------------- +// Main setup() and loop() +// ----------------------------------------------------------------------------- +/* +DisplayMode key: + 0: Clock + 1: Weather + 2: Weather Description +*/ +unsigned long descStartTime = 0; +bool descScrolling = false; +const unsigned long descriptionDuration = 3000; // 3s for short text + +void setup() { + Serial.begin(115200); + Serial.println(); + Serial.println(F("[SETUP] Starting setup...")); + + if (!LittleFS.begin()) { + Serial.println(F("[ERROR] LittleFS mount failed in setup! Halting.")); + while (true) { + delay(1000); + } + } + Serial.println(F("[SETUP] LittleFS file system mounted successfully.")); + + P.begin(); + P.setCharSpacing(0); + P.setFont(mFactory); + loadConfig(); + P.setIntensity(brightness); + P.setZoneEffect(0, flipDisplay, PA_FLIP_UD); + P.setZoneEffect(0, flipDisplay, PA_FLIP_LR); + Serial.println(F("[SETUP] Parola (LED Matrix) initialized")); + connectWiFi(); + Serial.println(F("[SETUP] Wifi connected")); + setupWebServer(); + Serial.println(F("[SETUP] Webserver setup complete")); + Serial.println(F("[SETUP] Setup complete")); + Serial.println(); + printConfigToSerial(); + setupTime(); + displayMode = 0; + lastSwitch = millis(); + lastColonBlink = millis(); +} + +void advanceDisplayMode() { + int oldMode = displayMode; + if (displayMode == 0) { + displayMode = 1; // clock -> weather + } else if (displayMode == 1 && showWeatherDescription && weatherAvailable && weatherDescription.length() > 0) { + displayMode = 2; // weather -> description + } else { + displayMode = 0; // description (or weather if no desc) -> clock + } + lastSwitch = millis(); + // Serial print for debugging + const char *modeName = displayMode == 0 ? "CLOCK" : displayMode == 1 ? "WEATHER" + : "DESCRIPTION"; + Serial.printf("[LOOP] Switching to display mode: %s\n", modeName); +} + +void loop() { + if (isAPMode) { + dnsServer.processNextRequest(); + } + + // AP Mode animation + static unsigned long apAnimTimer = 0; + static int apAnimFrame = 0; + if (isAPMode) { + unsigned long now = millis(); + if (now - apAnimTimer > 750) { + apAnimTimer = now; + apAnimFrame++; + } + P.setTextAlignment(PA_CENTER); + switch (apAnimFrame % 3) { + case 0: P.print(F("= ©")); break; + case 1: P.print(F("= ª")); break; + case 2: P.print(F("= «")); break; + } + yield(); + return; + } + + // Dimming + time_t now = time(nullptr); + struct tm timeinfo; + localtime_r(&now, &timeinfo); + int curHour = timeinfo.tm_hour; + int curMinute = timeinfo.tm_min; + int curTotal = curHour * 60 + curMinute; + int startTotal = dimStartHour * 60 + dimStartMinute; + int endTotal = dimEndHour * 60 + dimEndMinute; + bool isDimming = false; + + if (dimmingEnabled) { + if (startTotal < endTotal) { + isDimming = (curTotal >= startTotal && curTotal < endTotal); + } else { + isDimming = (curTotal >= startTotal || curTotal < endTotal); + } + if (isDimming) { + P.setIntensity(dimBrightness); + } else { + P.setIntensity(brightness); + } + } else { + P.setIntensity(brightness); + } + + // Show IP after WiFi connect + if (showingIp) { + if (P.displayAnimate()) { + ipDisplayCount++; + if (ipDisplayCount < ipDisplayMax) { + textEffect_t actualScrollDirection = getEffectiveScrollDirection(PA_SCROLL_LEFT, flipDisplay); + P.displayScroll(pendingIpToShow.c_str(), PA_CENTER, actualScrollDirection, 120); + } else { + showingIp = false; + P.displayClear(); + delay(500); + displayMode = 0; + lastSwitch = millis(); + } + } + yield(); + return; + } + + static bool colonVisible = true; + const unsigned long colonBlinkInterval = 800; + if (millis() - lastColonBlink > colonBlinkInterval) { + colonVisible = !colonVisible; + lastColonBlink = millis(); + } + + static unsigned long ntpAnimTimer = 0; + static int ntpAnimFrame = 0; + static bool tzSetAfterSync = false; + + static unsigned long lastFetch = 0; + const unsigned long fetchInterval = 300000; // 5 minutes + + switch (ntpState) { + case NTP_IDLE: break; + case NTP_SYNCING: + { + time_t now = time(nullptr); + if (now > 1000) { + Serial.println(F("\n[TIME] NTP sync successful.")); + ntpSyncSuccessful = true; + ntpState = NTP_SUCCESS; + } else if (millis() - ntpStartTime > ntpTimeout || ntpRetryCount > maxNtpRetries) { + Serial.println(F("\n[TIME] NTP sync failed.")); + ntpSyncSuccessful = false; + ntpState = NTP_FAILED; + } else { + if (millis() - ntpStartTime > ((unsigned long)ntpRetryCount * 1000)) { + Serial.print(F(".")); + ntpRetryCount++; + } + } + break; + } + case NTP_SUCCESS: + if (!tzSetAfterSync) { + const char *posixTz = ianaToPosix(timeZone); + setenv("TZ", posixTz, 1); + tzset(); + tzSetAfterSync = true; + } + ntpAnimTimer = 0; + ntpAnimFrame = 0; + break; + case NTP_FAILED: + ntpAnimTimer = 0; + ntpAnimFrame = 0; + break; + } + + // --- MODIFIED WEATHER FETCHING LOGIC --- + if (WiFi.status() == WL_CONNECTED) { + // Check if an immediate fetch is requested OR if the regular interval has passed + if (!weatherFetchInitiated || shouldFetchWeatherNow || (millis() - lastFetch > fetchInterval)) { + if (shouldFetchWeatherNow) { + Serial.println(F("[LOOP] Immediate weather fetch requested by web server.")); + shouldFetchWeatherNow = false; // Reset the flag after handling + } else if (!weatherFetchInitiated) { + Serial.println(F("[LOOP] Initial weather fetch.")); + } else { + Serial.println(F("[LOOP] Regular interval weather fetch.")); + } + + weatherFetchInitiated = true; + weatherFetched = false; // Mark as not yet fetched + fetchWeather(); + lastFetch = millis(); + } + } else { + weatherFetchInitiated = false; + // It's good practice to reset the flag if WiFi disconnects to avoid stale requests + shouldFetchWeatherNow = false; + } + // --- END MODIFIED WEATHER FETCHING LOGIC --- + + const char *const *daysOfTheWeek = getDaysOfWeek(language); + const char *daySymbol = daysOfTheWeek[timeinfo.tm_wday]; + + char timeStr[9]; + if (twelveHourToggle) { + int hour12 = timeinfo.tm_hour % 12; + if (hour12 == 0) hour12 = 12; + sprintf(timeStr, " %d:%02d", hour12, timeinfo.tm_min); + } else { + sprintf(timeStr, " %02d:%02d", timeinfo.tm_hour, timeinfo.tm_min); + } + + char timeSpacedStr[20]; + int j = 0; + for (int i = 0; timeStr[i] != '\0'; i++) { + timeSpacedStr[j++] = timeStr[i]; + if (timeStr[i + 1] != '\0') { + timeSpacedStr[j++] = ' '; + } + } + timeSpacedStr[j] = '\0'; + + String formattedTime; + if (showDayOfWeek) { + formattedTime = String(daySymbol) + " " + String(timeSpacedStr); + } else { + formattedTime = String(timeSpacedStr); + } + + // --- Weather Description Mode handling --- + static unsigned long descStartTime = 0; + static bool descScrolling = false; + static unsigned long descScrollEndTime = 0; // for post-scroll delay + const unsigned long descriptionDuration = 3000; // 3s for short text + const unsigned long descriptionScrollPause = 300; // 300ms pause after scroll + + // Only advance mode by timer for clock/weather, not description! + unsigned long displayDuration = (displayMode == 0) ? clockDuration : weatherDuration; + if ((displayMode == 0 || displayMode == 1) && millis() - lastSwitch > displayDuration) { + advanceDisplayMode(); + } + + // --- WEATHER DESCRIPTION Display Mode --- + if (displayMode == 2 && showWeatherDescription && weatherAvailable && weatherDescription.length() > 0) { + String desc = weatherDescription; + desc.toUpperCase(); + + if (desc.length() > 8) { + if (!descScrolling) { + P.displayClear(); + textEffect_t actualScrollDirection = getEffectiveScrollDirection(PA_SCROLL_LEFT, flipDisplay); + P.displayScroll(desc.c_str(), PA_CENTER, actualScrollDirection, 100); + descScrolling = true; + descScrollEndTime = 0; // reset end time at start + } + if (P.displayAnimate()) { + if (descScrollEndTime == 0) { + descScrollEndTime = millis(); // mark the time when scroll finishes + } + // wait small pause after scroll stops + if (millis() - descScrollEndTime > descriptionScrollPause) { + descScrolling = false; + descScrollEndTime = 0; + advanceDisplayMode(); + } + } else { + descScrollEndTime = 0; // reset if not finished + } + yield(); + return; + } else { + if (descStartTime == 0) { + P.setTextAlignment(PA_CENTER); + P.setCharSpacing(1); + P.print(desc.c_str()); + descStartTime = millis(); + } + if (millis() - descStartTime > descriptionDuration) { + descStartTime = 0; + advanceDisplayMode(); + } + yield(); + return; + } + } + + static bool weatherWasAvailable = false; + // --- CLOCK Display Mode --- + if (displayMode == 0) { + P.setCharSpacing(0); + if (ntpState == NTP_SYNCING) { + if (millis() - ntpAnimTimer > 750) { + ntpAnimTimer = millis(); + switch (ntpAnimFrame % 3) { + case 0: P.print(F("S Y N C ®")); break; + case 1: P.print(F("S Y N C ¯")); break; + case 2: P.print(F("S Y N C °")); break; + } + ntpAnimFrame++; + } + } else if (!ntpSyncSuccessful) { + P.setTextAlignment(PA_CENTER); + P.print(F("?/")); + } else { + String timeString = formattedTime; + if (!colonVisible) timeString.replace(":", " "); + P.print(timeString); + } + yield(); + return; + } + + // --- WEATHER Display Mode --- + if (displayMode == 1) { + P.setCharSpacing(1); + if (weatherAvailable) { + String weatherDisplay; + if (showHumidity && currentHumidity != -1) { + int cappedHumidity = (currentHumidity > 99) ? 99 : currentHumidity; + weatherDisplay = currentTemp + " " + String(cappedHumidity) + "%"; + } else { + weatherDisplay = currentTemp + tempSymbol; + } + P.print(weatherDisplay.c_str()); + weatherWasAvailable = true; + } else { + if (weatherWasAvailable) { + Serial.println(F("[DISPLAY] Weather not available, showing clock...")); + weatherWasAvailable = false; + } + if (ntpSyncSuccessful) { + String timeString = formattedTime; + if (!colonVisible) timeString.replace(":", " "); + P.setCharSpacing(0); + P.print(timeString); + } else { + P.setCharSpacing(0); + P.setTextAlignment(PA_CENTER); + P.print(F("?*")); + } + } + yield(); + return; + } + + yield(); } \ No newline at end of file diff --git a/LICENSE b/LICENSE index f288702..3877ae0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,674 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 1829fa6..89618d2 100644 --- a/README.md +++ b/README.md @@ -1,202 +1,202 @@ -![ESPTimeCast](assets/logo.svg) - -**ESPTimeCast** is a WiFi-connected LED matrix clock and weather station based on ESP8266 and MAX7219. -It displays the current time, day of the week, and local weather (temp/humidity/weather description) fetched from OpenWeatherMap. -Setup and configuration are fully managed via a built-in web interface. - -![clock - weather](assets/demo.gif) - - -3D Printable Case - -Get the 3D printable case! - - -[![Download on Printables](https://img.shields.io/badge/Printables-Download-orange?logo=prusa)](https://www.printables.com/model/1344276-esptimecast-wi-fi-clock-weather-display) -[![Available on Cults3D](https://img.shields.io/badge/Cults3D-Download-blue?logo=cults3d)](https://cults3d.com/en/3d-model/gadget/wifi-connected-led-matrix-clock-and-weather-station-esp8266-and-max7219) - - ---- - -## ✨ Features - -- **LED Matrix Display (8x32)** powered by MAX7219, with custom font support -- **Simple Web Interface** for all configuration (WiFi, weather, time zone, display durations, and more) -- **Automatic NTP Sync** with robust status feedback and retries -- **Day of Week Display** with custom font -- **Weather Fetching** from OpenWeatherMap (every 5 minutes, temp/humidity/description) -- **Fallback AP Mode** for easy first-time setup or configuration -- **Timezone Selection** from IANA names (DST integrated on backend) -- **Day of the week display** in multiple languages -- **Persistent Config** stored in LittleFS, with backup/restore system -- **Status Animations** for WiFi conection, AP mode, time syncing. -- **Advanced Settings** panel with: - - Custom **Primary/Secondary NTP server** input - - Display **Day of the Week** toggle (defualt in on) - - **24/12h clock mode** toggle (24-hour default) - - **Imperial Units (°F)** toggle (metric °C defaults) - - Show **Humidity** toggle (display Humidity besides Temperature) - - **Weather description** toggle (displays: heavy rain, scattered clouds, thunderstorm etc.) - - **Flip display** (180 degrees) - - Adjustable display **brightness** - - Dimming Hours **Scheduling** - ---- - -## 🪛 Wiring - - - - Note: although the pins are labeled differently in the V4, the positions are the same as the V3.x - -**Wemos D1 Mini (ESP8266) → MAX7219** - -| Wemos D1 Mini (v3.x) | Wemos D1 Mini (v4.0) | MAX7219 | -|:-------------:|:-------:|:-------:| -| GND | GND | GND | -| D6 | 12 | CLK | -| D7 | 13 | CS | -| D8 | 15 | DIN | -| 3V3 | 3V3 | VCC | - - -Wiring - -Note: Thanks to @Wood578Guy for the Wiring diagram and the info on V4 - ---- - -## 🌐 Web UI & Configuration - -The built-in web interface provides full configuration for: - -- **WiFi settings** (SSID & Password) -- **Weather settings** (OpenWeatherMap API key, City, Country, Coordinates) -- **Time zone** (will auto-populate if TZ is found) -- **Day of the week** languages -- **Display durations** for clock and weather (milliseconds) -- **Advanced Settings** (see below) - -### First-time Setup / AP Mode - -1. Power on the device. If WiFi fails, it auto-starts in AP mode: - - **SSID:** `ESPTimeCast` - - **Password:** `12345678` - - Open `http://192.168.4.1` or `http://setup.esp` in your browser. -2. Set your WiFi and all other options. -3. Click **Save Setting** – the device saves config, reboots, and connects. -4. The device shows its local IP adress after boot so you can login again for setting changes - -### UI Example: -Web Interface - ---- - -## ⚙️ Advanced Settings - -Click the **cog icon** next to “Advanced Settings” in the web UI to reveal extra configuration options. - -**Available advanced settings:** - -- **Primary NTP Server**: Override the default NTP server (e.g. `pool.ntp.org`) -- **Secondary NTP Server**: Fallback NTP server (e.g. `time.nist.gov`) -- **Day of the Week**: Display Day of the Week in the disered language -- **24/12h Clock**: Switch between 24-hour and 12-hour time formats (24-hour default) -- **Imperial Units (°F)** toggle (metric °C defaults) -- **Humidity**: Display Humidity besides Temperature -- **Weather description** toggle (display weather description in the selected language* for 3 seconds or scrolls once if description is too long) -- **Flip Display**: Invert the display vertically/horizontally -- **Brightness**: 0 (dim) to 15 (bright) -- **Dimming Feature**: Start time, end time and desired brightness selection - -*Non-English characters converted to their closest English alphabet. -Tip: Dont't forget to press the save button to keep your settings - ---- - -## 📝 Configuration Notes - -- **OpenWeatherMap API Key:** [Get yours here]([https://home.openweathermap.org/users/sign_up]) -- **City Name:** e.g. `Tokyo`, `London`, etc. -- **Country Code:** 2-letter code (e.g., `JP`, `GB`) -- **ZIP Code:** Enter your ZIP code in the city field and US in the country field (US only) -- **Latitude and Longitude** You can enter coordinates in the city field (lat.) and country field (long.) -- **Time Zone:** Select from IANA zones (e.g., `America/New_York`, handles DST automatically) - ---- - -## 🔧 Installation - -1. **Clone this repo** -2. **Flash the ESP8266** using Arduino IDE or PlatformIO (Flash size "4MB FS:2MB OTA:~1019KB") -4. **Upload `/data` folder** with LittleFS uploader (see below) - -### Board Setup - -- Install ESP8266 board package: - `http://arduino.esp8266.com/stable/package_esp8266com_index.json` -- Select **Wemos D1 Mini** (or your ESP8266 variant) in Tools → Board -- Select Flash Size "4MB FS:2MB OTA:~1019KB" under Tools - -### Dependencies - -Install these libraries (Library Manager / PlatformIO): - -- `ArduinoJson` by Benoit Blanchon -- `MD_Parola / MD_MAX72xx` all dependencies by majicDesigns -- `ESPAsyncTCP` by ESP32Async -- `ESPAsyncWebServer` by ESP32Async - -### LittleFS Upload - -Install the [LittleFS Uploader](https://randomnerdtutorials.com/arduino-ide-2-install-esp8266-littlefs/). - -**To upload `/data`:** - -1. Open Command Palette: - - Windows: `Ctrl+Shift+P` - - macOS: `Cmd+Shift+P` -2. Run: `Upload LittleFS to ESP8266` - -**Important:** Serial Monitor **must be closed** before uploading! - ---- - -## 📺 Display Behavior - -**ESPTimeCast** automatically switches between two display modes: Clock and Weather. -If "Show Weather Description" is eneabled a third mode (Description) will display with a duration of 3 seconds, if the description is too long to fit on the display the description will scroll from right to left once. - -What you see on the LED matrix depends on whether the device has successfully fetched the current time (via NTP) and weather (via OpenWeatherMap). -The following table summarizes what will appear on the display in each scenario: - -| Display Mode | 🕒 NTP Time | 🌦️ Weather Data | 📺 Display Output | -|:------------:|:----------:|:--------------:|:--------------------------------------------| -| **Clock** | ✅ Yes | — | 🗓️ Day Icon + ⏰ Time (e.g. `@ 14:53`) | -| **Clock** | ❌ No | — | `! NTP` (NTP sync failed) | -| **Weather** | — | ✅ Yes | 🌡️ Temperature (e.g. `23ºC`) | -| **Weather** | ✅ Yes | ❌ No | 🗓️ Day Icon + ⏰ Time (e.g. `@ 14:53`) | -| **Weather** | ❌ No | ❌ No | `! TEMP` (no weather or time data) | - -### **How it works:** - -- The display automatically alternates between **Clock** and **Weather** modes (the duration for each is configurable). -- If "Show Weather Description" is eneabled a third mode **Description** will display after the **Weather** display with a duration of 3 seconds. -- In **Clock** mode, if NTP time is available, you’ll see the current time plus a unique day-of-week icon. If NTP is not available, you'll see `! NTP`. -- In **Weather** mode, if weather is available, you’ll see the temperature (like `23ºC`). If weather is not available but time is, it falls back to showing the clock. If neither is available, you’ll see `! TEMP`. -- All status/error messages (`! NTP`, `! TEMP`) are big icons shown on the dsiplay. - -**Legend:** -- 🗓️ **Day Icon**: Custom symbol for day of week (`@`, `=`, etc.) -- ⏰ **Time**: Current time (HH:MM) -- 🌡️ **Temperature**: Weather from OpenWeatherMap -- ✅ **Yes**: Data available -- ❌ **No**: Data not available -- — : Value does not affect this mode - ---- - -## ☕ Support this project - -If you like this project, you can [buy me a coffee](https://paypal.me/officialuphoto)! - +![ESPTimeCast](assets/logo.svg) + +**ESPTimeCast** is a WiFi-connected LED matrix clock and weather station based on ESP8266 and MAX7219. +It displays the current time, day of the week, and local weather (temp/humidity/weather description) fetched from OpenWeatherMap. +Setup and configuration are fully managed via a built-in web interface. + +![clock - weather](assets/demo.gif) + + +3D Printable Case + +Get the 3D printable case! + + +[![Download on Printables](https://img.shields.io/badge/Printables-Download-orange?logo=prusa)](https://www.printables.com/model/1344276-esptimecast-wi-fi-clock-weather-display) +[![Available on Cults3D](https://img.shields.io/badge/Cults3D-Download-blue?logo=cults3d)](https://cults3d.com/en/3d-model/gadget/wifi-connected-led-matrix-clock-and-weather-station-esp8266-and-max7219) + + +--- + +## ✨ Features + +- **LED Matrix Display (8x32)** powered by MAX7219, with custom font support +- **Simple Web Interface** for all configuration (WiFi, weather, time zone, display durations, and more) +- **Automatic NTP Sync** with robust status feedback and retries +- **Day of Week Display** with custom font +- **Weather Fetching** from OpenWeatherMap (every 5 minutes, temp/humidity/description) +- **Fallback AP Mode** for easy first-time setup or configuration +- **Timezone Selection** from IANA names (DST integrated on backend) +- **Day of the week display** in multiple languages +- **Persistent Config** stored in LittleFS, with backup/restore system +- **Status Animations** for WiFi conection, AP mode, time syncing. +- **Advanced Settings** panel with: + - Custom **Primary/Secondary NTP server** input + - Display **Day of the Week** toggle (defualt in on) + - **24/12h clock mode** toggle (24-hour default) + - **Imperial Units (°F)** toggle (metric °C defaults) + - Show **Humidity** toggle (display Humidity besides Temperature) + - **Weather description** toggle (displays: heavy rain, scattered clouds, thunderstorm etc.) + - **Flip display** (180 degrees) + - Adjustable display **brightness** + - Dimming Hours **Scheduling** + +--- + +## 🪛 Wiring + + + + Note: although the pins are labeled differently in the V4, the positions are the same as the V3.x + +**Wemos D1 Mini (ESP8266) → MAX7219** + +| Wemos D1 Mini (v3.x) | Wemos D1 Mini (v4.0) | MAX7219 | +|:-------------:|:-------:|:-------:| +| GND | GND | GND | +| D6 | 12 | CLK | +| D7 | 13 | CS | +| D8 | 15 | DIN | +| 3V3 | 3V3 | VCC | + + +Wiring + +Note: Thanks to @Wood578Guy for the Wiring diagram and the info on V4 + +--- + +## 🌐 Web UI & Configuration + +The built-in web interface provides full configuration for: + +- **WiFi settings** (SSID & Password) +- **Weather settings** (OpenWeatherMap API key, City, Country, Coordinates) +- **Time zone** (will auto-populate if TZ is found) +- **Day of the week** languages +- **Display durations** for clock and weather (milliseconds) +- **Advanced Settings** (see below) + +### First-time Setup / AP Mode + +1. Power on the device. If WiFi fails, it auto-starts in AP mode: + - **SSID:** `ESPTimeCast` + - **Password:** `12345678` + - Open `http://192.168.4.1` or `http://setup.esp` in your browser. +2. Set your WiFi and all other options. +3. Click **Save Setting** – the device saves config, reboots, and connects. +4. The device shows its local IP adress after boot so you can login again for setting changes + +### UI Example: +Web Interface + +--- + +## ⚙️ Advanced Settings + +Click the **cog icon** next to “Advanced Settings” in the web UI to reveal extra configuration options. + +**Available advanced settings:** + +- **Primary NTP Server**: Override the default NTP server (e.g. `pool.ntp.org`) +- **Secondary NTP Server**: Fallback NTP server (e.g. `time.nist.gov`) +- **Day of the Week**: Display Day of the Week in the disered language +- **24/12h Clock**: Switch between 24-hour and 12-hour time formats (24-hour default) +- **Imperial Units (°F)** toggle (metric °C defaults) +- **Humidity**: Display Humidity besides Temperature +- **Weather description** toggle (display weather description in the selected language* for 3 seconds or scrolls once if description is too long) +- **Flip Display**: Invert the display vertically/horizontally +- **Brightness**: 0 (dim) to 15 (bright) +- **Dimming Feature**: Start time, end time and desired brightness selection + +*Non-English characters converted to their closest English alphabet. +Tip: Dont't forget to press the save button to keep your settings + +--- + +## 📝 Configuration Notes + +- **OpenWeatherMap API Key:** [Get yours here]([https://home.openweathermap.org/users/sign_up]) +- **City Name:** e.g. `Tokyo`, `London`, etc. +- **Country Code:** 2-letter code (e.g., `JP`, `GB`) +- **ZIP Code:** Enter your ZIP code in the city field and US in the country field (US only) +- **Latitude and Longitude** You can enter coordinates in the city field (lat.) and country field (long.) +- **Time Zone:** Select from IANA zones (e.g., `America/New_York`, handles DST automatically) + +--- + +## 🔧 Installation + +1. **Clone this repo** +2. **Flash the ESP8266** using Arduino IDE or PlatformIO (Flash size "4MB FS:2MB OTA:~1019KB") +4. **Upload `/data` folder** with LittleFS uploader (see below) + +### Board Setup + +- Install ESP8266 board package: + `http://arduino.esp8266.com/stable/package_esp8266com_index.json` +- Select **Wemos D1 Mini** (or your ESP8266 variant) in Tools → Board +- Select Flash Size "4MB FS:2MB OTA:~1019KB" under Tools + +### Dependencies + +Install these libraries (Library Manager / PlatformIO): + +- `ArduinoJson` by Benoit Blanchon +- `MD_Parola / MD_MAX72xx` all dependencies by majicDesigns +- `ESPAsyncTCP` by ESP32Async +- `ESPAsyncWebServer` by ESP32Async + +### LittleFS Upload + +Install the [LittleFS Uploader](https://randomnerdtutorials.com/arduino-ide-2-install-esp8266-littlefs/). + +**To upload `/data`:** + +1. Open Command Palette: + - Windows: `Ctrl+Shift+P` + - macOS: `Cmd+Shift+P` +2. Run: `Upload LittleFS to ESP8266` + +**Important:** Serial Monitor **must be closed** before uploading! + +--- + +## 📺 Display Behavior + +**ESPTimeCast** automatically switches between two display modes: Clock and Weather. +If "Show Weather Description" is eneabled a third mode (Description) will display with a duration of 3 seconds, if the description is too long to fit on the display the description will scroll from right to left once. + +What you see on the LED matrix depends on whether the device has successfully fetched the current time (via NTP) and weather (via OpenWeatherMap). +The following table summarizes what will appear on the display in each scenario: + +| Display Mode | 🕒 NTP Time | 🌦️ Weather Data | 📺 Display Output | +|:------------:|:----------:|:--------------:|:--------------------------------------------| +| **Clock** | ✅ Yes | — | 🗓️ Day Icon + ⏰ Time (e.g. `@ 14:53`) | +| **Clock** | ❌ No | — | `! NTP` (NTP sync failed) | +| **Weather** | — | ✅ Yes | 🌡️ Temperature (e.g. `23ºC`) | +| **Weather** | ✅ Yes | ❌ No | 🗓️ Day Icon + ⏰ Time (e.g. `@ 14:53`) | +| **Weather** | ❌ No | ❌ No | `! TEMP` (no weather or time data) | + +### **How it works:** + +- The display automatically alternates between **Clock** and **Weather** modes (the duration for each is configurable). +- If "Show Weather Description" is eneabled a third mode **Description** will display after the **Weather** display with a duration of 3 seconds. +- In **Clock** mode, if NTP time is available, you’ll see the current time plus a unique day-of-week icon. If NTP is not available, you'll see `! NTP`. +- In **Weather** mode, if weather is available, you’ll see the temperature (like `23ºC`). If weather is not available but time is, it falls back to showing the clock. If neither is available, you’ll see `! TEMP`. +- All status/error messages (`! NTP`, `! TEMP`) are big icons shown on the dsiplay. + +**Legend:** +- 🗓️ **Day Icon**: Custom symbol for day of week (`@`, `=`, etc.) +- ⏰ **Time**: Current time (HH:MM) +- 🌡️ **Temperature**: Weather from OpenWeatherMap +- ✅ **Yes**: Data available +- ❌ **No**: Data not available +- — : Value does not affect this mode + +--- + +## ☕ Support this project + +If you like this project, you can [buy me a coffee](https://paypal.me/officialuphoto)! + diff --git a/data/config.json b/data/config.json index 60f776d..a4b20df 100644 --- a/data/config.json +++ b/data/config.json @@ -1,19 +1,19 @@ -{ - "ssid": "", - "password": "", - "openWeatherApiKey": "", - "openWeatherCity": "", - "openWeatherCountry": "", - "clockDuration": 10000, - "weatherDuration": 5000, - "timeZone": "", - "weatherUnits": "metric", - "brightness": 10, - "flipDisplay": false, - "ntpServer1": "pool.ntp.org", - "ntpServer2": "time.nist.gov", - "twelveHourToggle": false, - "showDayOfWeek": true, - "showHumidity": false, - "language": "en" +{ + "ssid": "", + "password": "", + "openWeatherApiKey": "", + "openWeatherCity": "", + "openWeatherCountry": "", + "clockDuration": 10000, + "weatherDuration": 5000, + "timeZone": "", + "weatherUnits": "metric", + "brightness": 10, + "flipDisplay": false, + "ntpServer1": "pool.ntp.org", + "ntpServer2": "time.nist.gov", + "twelveHourToggle": false, + "showDayOfWeek": true, + "showHumidity": false, + "language": "en" } \ No newline at end of file diff --git a/data/index.html b/data/index.html index 4c1ac49..dbf84c5 100644 --- a/data/index.html +++ b/data/index.html @@ -1,1041 +1,1041 @@ - - - - - -ESPTimeCast Settings - - - - -
- -

WiFi Settings

- - - -
- - -
-

Weather Settings

- - -
Required to fetch weather data. Get your API key here.
- - -
- - -
- -
- Visit OpenWeatherMap to find your location.

- Location format examples: City, Country Code - Osaka, JP | ZIP,Country Code - 94040, US | Latitude, Longitude - 34.6937, 135.5023 -
- -

Clock Settings

- - - - - - - -
-
- - - -
-
- - - -
-
- - - - -
- - - -
- - - + + + + + +ESPTimeCast Settings + + + + +
+ +

WiFi Settings

+ + + +
+ + +
+

Weather Settings

+ + +
Required to fetch weather data. Get your API key here.
+ + +
+ + +
+ +
+ Visit OpenWeatherMap to find your location.

+ Location format examples: City, Country Code - Osaka, JP | ZIP,Country Code - 94040, US | Latitude, Longitude - 34.6937, 135.5023 +
+ +

Clock Settings

+ + + + + + + +
+
+ + + +
+
+ + + +
+
+ + + + +
+ + + +
+ + + \ No newline at end of file diff --git a/days_lookup.h b/days_lookup.h index 3a0deee..7b5dd7e 100644 --- a/days_lookup.h +++ b/days_lookup.h @@ -1,49 +1,49 @@ -#ifndef DAYS_LOOKUP_H -#define DAYS_LOOKUP_H - -typedef struct { - const char* lang; - const char* days[7]; // Sunday to Saturday (tm_wday order) -} DaysOfWeekMapping; - -const DaysOfWeekMapping days_mappings[] = { - { "af", { "s&u&n", "m&a&a", "d&i&n", "w&o&e", "d&o&n", "v&r&y", "s&o&n" } }, - { "cs", { "n&e&d", "p&o&n", "u&t&e", "s&t&r", "c&t&v", "p&a&t", "s&o&b" } }, - { "da", { "s&o&n", "m&a&n", "t&i&r", "o&n&s", "t&o&r", "f&r&e", "l&o&r" } }, - { "de", { "s&o&n", "m&o&n", "d&i&e", "m&i&t", "d&o&n", "f&r&e", "s&a&m" } }, - { "en", { "s&u&n", "m&o&n", "t&u&e", "w&e&d", "t&h&u", "f&r&i", "s&a&t" } }, - { "eo", { "d&i&m", "l&u&n", "m&a&r", "m&e&r", "j&a&u", "v&e&n", "s&a&b" } }, - { "es", { "d&o&m", "l&u&n", "m&a&r", "m&i&e", "j&u&e", "v&i&e", "s&a&b" } }, - { "et", { "p&a", "e&s", "t&e", "k&o", "n&e", "r&e", "l&a" } }, - { "fi", { "s&u&n", "m&a&a", "t&i&s", "k&e&s", "t&o&r", "p&e&r", "l&a&u" } }, - { "fr", { "d&i&m", "l&u&n", "m&a&r", "m&e&r", "j&e&u", "v&e&n", "s&a&m" } }, - { "hr", { "n&e&d", "p&o&n", "u&t&o", "s&r&i", "c&e&t", "p&e&t", "s&u&b" } }, - { "hu", { "v&a&s", "h&e&t", "k&e&d", "s&z&e", "c&s&u", "p&e&t", "s&z&o" } }, - { "it", { "d&o&m", "l&u&n", "m&a&r", "m&e&r", "g&i&o", "v&e&n", "s&a&b" } }, - { "ja", { "±", "²", "³", "´", "µ", "¶", "·" } }, - { "lt", { "s&e&k", "p&i&r", "a&n&t", "t&r&e", "k&e&t", "p&e&n", "s&e&s" } }, - { "lv", { "s&v&e", "p&i&r", "o&t&r", "t&r&e", "c&e&t", "p&i&e", "s&e&s" } }, - { "nl", { "z&o&n", "m&a&a", "d&i&n", "w&o&e", "d&o&n", "v&r&i", "z&a&t" } }, - { "no", { "s&o&n", "m&a&n", "t&i&r", "o&n&s", "t&o&r", "f&r&e", "l&o&r" } }, - { "pl", { "n&i&e", "p&o&n", "w&t&o", "s&r&o", "c&z&w", "p&i&a", "s&o&b" } }, - { "pt", { "d&o&m", "s&e&g", "t&e&r", "q&u&a", "q&u&i", "s&e&x", "s&a&b" } }, - { "ro", { "d&u&m", "l&u&n", "m&a&r", "m&i&e", "j&o&i", "v&i&n", "s&a&m" } }, - { "sk", { "n&e&d", "p&o&n", "u&t&o", "s&t&r", "s&t&v", "p&i&a", "s&o&b" } }, - { "sl", { "n&e&d", "p&o&n", "t&o&r", "s&r&e", "c&e&t", "p&e&t", "s&o&b" } }, - { "sv", { "s&o&n", "m&a&n", "t&i&s", "o&n&s", "t&o&r", "f&r&e", "l&o&r" } }, - { "sw", { "j&p&l", "j&u&m", "j&t&t", "j&t&n", "a&l&k", "i&j&m", "j&m&s" } }, - { "tr", { "p&a&z", "p&a&z", "s&a&l", "c&a&r", "p&e&r", "c&u&m", "c&u&m" } } -}; - -#define DAYS_MAPPINGS_COUNT (sizeof(days_mappings)/sizeof(days_mappings[0])) - -inline const char* const* getDaysOfWeek(const char* lang) { - for (size_t i = 0; i < DAYS_MAPPINGS_COUNT; i++) { - if (strcmp(lang, days_mappings[i].lang) == 0) - return days_mappings[i].days; - } - // fallback to English if not found - return days_mappings[4].days; // "en" is index 4 -} - +#ifndef DAYS_LOOKUP_H +#define DAYS_LOOKUP_H + +typedef struct { + const char* lang; + const char* days[7]; // Sunday to Saturday (tm_wday order) +} DaysOfWeekMapping; + +const DaysOfWeekMapping days_mappings[] = { + { "af", { "s&u&n", "m&a&a", "d&i&n", "w&o&e", "d&o&n", "v&r&y", "s&o&n" } }, + { "cs", { "n&e&d", "p&o&n", "u&t&e", "s&t&r", "c&t&v", "p&a&t", "s&o&b" } }, + { "da", { "s&o&n", "m&a&n", "t&i&r", "o&n&s", "t&o&r", "f&r&e", "l&o&r" } }, + { "de", { "s&o&n", "m&o&n", "d&i&e", "m&i&t", "d&o&n", "f&r&e", "s&a&m" } }, + { "en", { "s&u&n", "m&o&n", "t&u&e", "w&e&d", "t&h&u", "f&r&i", "s&a&t" } }, + { "eo", { "d&i&m", "l&u&n", "m&a&r", "m&e&r", "j&a&u", "v&e&n", "s&a&b" } }, + { "es", { "d&o&m", "l&u&n", "m&a&r", "m&i&e", "j&u&e", "v&i&e", "s&a&b" } }, + { "et", { "p&a", "e&s", "t&e", "k&o", "n&e", "r&e", "l&a" } }, + { "fi", { "s&u&n", "m&a&a", "t&i&s", "k&e&s", "t&o&r", "p&e&r", "l&a&u" } }, + { "fr", { "d&i&m", "l&u&n", "m&a&r", "m&e&r", "j&e&u", "v&e&n", "s&a&m" } }, + { "hr", { "n&e&d", "p&o&n", "u&t&o", "s&r&i", "c&e&t", "p&e&t", "s&u&b" } }, + { "hu", { "v&a&s", "h&e&t", "k&e&d", "s&z&e", "c&s&u", "p&e&t", "s&z&o" } }, + { "it", { "d&o&m", "l&u&n", "m&a&r", "m&e&r", "g&i&o", "v&e&n", "s&a&b" } }, + { "ja", { "±", "²", "³", "´", "µ", "¶", "·" } }, + { "lt", { "s&e&k", "p&i&r", "a&n&t", "t&r&e", "k&e&t", "p&e&n", "s&e&s" } }, + { "lv", { "s&v&e", "p&i&r", "o&t&r", "t&r&e", "c&e&t", "p&i&e", "s&e&s" } }, + { "nl", { "z&o&n", "m&a&a", "d&i&n", "w&o&e", "d&o&n", "v&r&i", "z&a&t" } }, + { "no", { "s&o&n", "m&a&n", "t&i&r", "o&n&s", "t&o&r", "f&r&e", "l&o&r" } }, + { "pl", { "n&i&e", "p&o&n", "w&t&o", "s&r&o", "c&z&w", "p&i&a", "s&o&b" } }, + { "pt", { "d&o&m", "s&e&g", "t&e&r", "q&u&a", "q&u&i", "s&e&x", "s&a&b" } }, + { "ro", { "d&u&m", "l&u&n", "m&a&r", "m&i&e", "j&o&i", "v&i&n", "s&a&m" } }, + { "sk", { "n&e&d", "p&o&n", "u&t&o", "s&t&r", "s&t&v", "p&i&a", "s&o&b" } }, + { "sl", { "n&e&d", "p&o&n", "t&o&r", "s&r&e", "c&e&t", "p&e&t", "s&o&b" } }, + { "sv", { "s&o&n", "m&a&n", "t&i&s", "o&n&s", "t&o&r", "f&r&e", "l&o&r" } }, + { "sw", { "j&p&l", "j&u&m", "j&t&t", "j&t&n", "a&l&k", "i&j&m", "j&m&s" } }, + { "tr", { "p&a&z", "p&a&z", "s&a&l", "c&a&r", "p&e&r", "c&u&m", "c&u&m" } } +}; + +#define DAYS_MAPPINGS_COUNT (sizeof(days_mappings)/sizeof(days_mappings[0])) + +inline const char* const* getDaysOfWeek(const char* lang) { + for (size_t i = 0; i < DAYS_MAPPINGS_COUNT; i++) { + if (strcmp(lang, days_mappings[i].lang) == 0) + return days_mappings[i].days; + } + // fallback to English if not found + return days_mappings[4].days; // "en" is index 4 +} + #endif // DAYS_LOOKUP_H \ No newline at end of file diff --git a/mfactoryfont.h b/mfactoryfont.h index b90d573..e531658 100644 --- a/mfactoryfont.h +++ b/mfactoryfont.h @@ -1,262 +1,262 @@ -// Data file for user example user defined fonts -#pragma once - -MD_MAX72XX::fontType_t mFactory[] PROGMEM = -{ -1, 0, // 0 - 'Empty Cell' - 1, 0, // 1 - 'Sad Smiley' - 1, 0, // 2 - 'Happy Smiley' - 1, 0, // 3 - 'Heart' - 1, 0, // 4 - 'Diamond' - 1, 0, // 5 - 'Clubs' - 1, 0, // 6 - 'Spades' - 1, 0, // 7 - 'Bullet Point' - 1, 0, // 8 - 'Rev Bullet Point' - 1, 0, // 9 - 'Hollow Bullet Point' - 1, 0, // 10 - 'Rev Hollow BP' - 1, 0, // 11 - 'Male' - 1, 0, // 12 - 'Female' - 1, 0, // 13 - 'Music Note 1' - 1, 0, // 14 - 'Music Note 2' - 1, 0, // 15 - 'Snowflake' - 1, 0, // 16 - 'Right Pointer' - 1, 0, // 17 - 'Left Pointer' - 1, 0, // 18 - 'UpDown Arrows' - 1, 0, // 19 - 'Full Block' - 1, 0, // 20 - 'Half Block Bottom' - 1, 0, // 21 - 'Half Block LHS' - 1, 0, // 22 - 'Half Block RHS' - 1, 0, // 23 - 'Half Block Top' - 1, 0, // 24 - 'Up Arrow' - 1, 0, // 25 - 'Down Arrow' - 1, 0, // 26 - 'Right Arrow' - 1, 0, // 27 - 'Left Arrow' - 1, 0, // 28 - '30% shading' - 1, 0, // 29 - '50% shading' - 1, 0, // 30 - 'Up Pointer' - 1, 0, // 31 - 'Down Pointer' - 1, 0, // 32 - 'Space' - 1, 0, // 33 - '!' - 1, 0, // 34 - '""' - 13, 63, 192, 127, 192, 63, 0, 250, 0, 255, 9, 1, 0, 250, // 35 - '#' - 16, 72, 84, 36, 0, 12, 112, 12, 0, 124, 4, 120, 0, 56, 68, 68, 0, // 36 - '$' - 6, 66, 37, 18, 72, 164, 66, // 37 - '%' - 1, 1, // 38 - '&' - 1, 0, // 39 - '' - 1, 0, // 40 - '(' - 1, 0, // 41 - ')' - 20, 250, 130, 250, 254, 130, 170, 186, 254, 130, 250, 226, 250, 134, 254, 130, 234, 234, 246, 254, 124, // 42 - '*' - 1, 0, // 43 - '+' - 3, 64, 0, 0, // 44 - ',' - 2, 8, 8, // 45 - '-' - 1, 128, // 46 - '.' - 15, 130, 246, 238, 130, 254, 250, 130, 250, 254, 130, 234, 234, 246, 254, 124, // 47 - '/' - 3, 126, 129, 126, // 48 - '0' - 2, 2, 255, // 49 - '1' - 3, 194, 177, 142, // 50 - '2' - 3, 66, 137, 118, // 51 - '3' - 3, 15, 8, 255, // 52 - '4' - 3, 79, 137, 113, // 53 - '5' - 3, 126, 137, 114, // 54 - '6' - 3, 1, 249, 7, // 55 - '7' - 3, 118, 137, 118, // 56 - '8' - 3, 78, 145, 126, // 57 - '9' - 1, 36, // 58 - ':' - 1, 0, // 59 - ';' - 1, 0, // 60 - '<' - 9, 254, 17, 17, 254, 0, 255, 17, 17, 14, // 61 - '=' - 1, 0, // 62 - '>' - 7, 124, 254, 254, 162, 254, 254, 254, // 63 - '?' - 1, 250, // 64 - '@' - 3, 124, 10, 124, // 65 - 'A' - 3, 126, 74, 52, // 66 - 'B' - 3, 60, 66, 36, // 67 - 'C' - 3, 126, 66, 60, // 68 - 'D' - 3, 126, 74, 66, // 69 - 'E' - 3, 126, 10, 2, // 70 - 'F' - 3, 60, 82, 116, // 71 - 'G' - 3, 126, 8, 126, // 72 - 'H' - 1, 126, // 73 - 'I' - 3, 32, 64, 62, // 74 - 'J' - 3, 126, 8, 118, // 75 - 'K' - 3, 126, 64, 64, // 76 - 'L' - 3, 126, 4, 126, // 77 - 'M' - 3, 126, 2, 124, // 78 - 'N' - 3, 60, 66, 60, // 79 - 'O' - 3, 126, 18, 12, // 80 - 'P' - 3, 60, 66, 124, // 81 - 'Q' - 3, 126, 18, 108, // 82 - 'R' - 3, 68, 74, 50, // 83 - 'S' - 3, 2, 126, 2, // 84 - 'T' - 3, 62, 64, 62, // 85 - 'U' - 3, 30, 96, 30, // 86 - 'V' - 3, 126, 32, 126, // 87 - 'W' - 3, 118, 8, 118, // 88 - 'X' - 3, 6, 120, 6, // 89 - 'Y' - 3, 98, 90, 70, // 90 - 'Z' - 4, 126, 129, 129, 66, // 91 - '[' - 3, 6, 28, 48, // 92 - '\' - 4, 255, 9, 9, 1, // 93 - ']' - 3, 8, 4, 8, // 94 - '^' - 3, 32, 32, 32, // 95 - '_' - 4, 255, 8, 20, 227, // 96 - '`' - 3, 249, 21, 249, // 97 - 'a' - 3, 253, 149, 105, // 98 - 'b' - 3, 121, 133, 73, // 99 - 'c' - 3, 253, 133, 121, // 100 - 'd' - 3, 253, 149, 133, // 101 - 'e' - 3, 253, 21, 5, // 102 - 'f' - 3, 121, 165, 233, // 103 - 'g' - 3, 253, 17, 253, // 104 - 'h' - 3, 1, 253, 1, // 105 - 'i' - 3, 65, 129, 125, // 106 - 'j' - 3, 253, 17, 237, // 107 - 'k' - 3, 253, 129, 129, // 108 - 'l' - 3, 253, 9, 253, // 109 - 'm' - 3, 253, 5, 249, // 110 - 'n' - 3, 121, 133, 121, // 111 - 'o' - 3, 253, 37, 25, // 112 - 'p' - 3, 121, 133, 249, // 113 - 'q' - 3, 253, 37, 217, // 114 - 'r' - 3, 137, 149, 101, // 115 - 's' - 3, 5, 253, 5, // 116 - 't' - 3, 125, 129, 125, // 117 - 'u' - 3, 61, 193, 61, // 118 - 'v' - 3, 253, 65, 253, // 119 - 'w' - 3, 237, 17, 237, // 120 - 'x' - 3, 13, 241, 13, // 121 - 'y' - 3, 197, 181, 141, // 122 - 'z' - 1, 0, // 123 - '{' - 1, 0, // 124 - '|' - 1, 0, // 125 - '}' - 0, // 126 - '~' - 0, // 127 - '' - 0, // 128 - '€' - 0, // 129 - '' - 0, // 130 - '‚' - 0, // 131 - 'ƒ' - 0, // 132 - '„' - 0, // 133 - '…' - 0, // 134 - '†' - 0, // 135 - '‡' - 0, // 136 - 'ˆ' - 0, // 137 - '‰' - 0, // 138 - 'Š' - 0, // 139 - '‹' - 0, // 140 - 'Œ' - 0, // 141 - '' - 0, // 142 - 'Ž' - 0, // 143 - '' - 0, // 144 - '' - 0, // 145 - '‘' - 0, // 146 - '’' - 0, // 147 - '“' - 0, // 148 - '”' - 1, 0, // 149 - '•' - 1, 0, // 150 - '–' - 1, 0, // 151 - '—' - 0, // 152 - '˜' - 0, // 153 - '™' - 0, // 154 - 'š' - 0, // 155 - '›' - 0, // 156 - 'œ' - 0, // 157 - '' - 0, // 158 - 'ž' - 0, // 159 - 'Ÿ' - 0, // 160 - '' - 0, // 161 - '¡' - 0, // 162 - '¢' - 0, // 163 - '£' - 0, // 164 - '¤' - 0, // 165 - '¥' - 0, // 166 - '¦' - 0, // 167 - '§' - 0, // 168 - '¨' - 8, 224, 224, 0, 0, 0, 0, 0, 0, // 169 - '©' - 8, 224, 224, 0, 252, 252, 0, 0, 0, // 170 - 'ª' - 8, 224, 224, 0, 252, 252, 0, 255, 255, // 171 - '«' - 0, // 172 - '¬' - 0, // 173 - '­' - 5, 64, 0, 0, 0, 0, // 174 - '®' - 5, 64, 0, 64, 0, 0, // 175 - '¯' - 5, 64, 0, 64, 0, 64, // 176 - '°' - 6, 254, 146, 146, 146, 254, 0, // 177 - '±' - 7, 128, 126, 42, 42, 170, 254, 0, // 178 - '²' - 8, 128, 152, 64, 62, 80, 136, 128, 0, // 179 - '³' - 8, 72, 40, 152, 254, 16, 40, 68, 0, // 180 - '´' - 8, 68, 36, 20, 254, 20, 36, 68, 0, // 181 - 'µ' - 8, 168, 232, 172, 250, 172, 232, 168, 0, // 182 - '¶' - 8, 128, 136, 136, 254, 136, 136, 128, 0, // 183 - '·' - 0, // 184 - '¸' - 0, // 185 - '¹' - 3, 4, 10, 4, // 186 - 'º' - 0, // 187 - '»' - 0, // 188 - '¼' - 0, // 189 - '½' - 0, // 190 - '¾' - 0, // 191 - '¿' - 0, // 192 - 'À' - 0, // 193 - 'Á' - 0, // 194 - 'Â' - 0, // 195 - 'Ã' - 0, // 196 - 'Ä' - 0, // 197 - 'Å' - 0, // 198 - 'Æ' - 0, // 199 - 'Ç' - 0, // 200 - 'È' - 0, // 201 - 'É' - 0, // 202 - 'Ê' - 0, // 203 - 'Ë' - 0, // 204 - 'Ì' - 0, // 205 - 'Í' - 0, // 206 - 'Î' - 0, // 207 - 'Ï' - 0, // 208 - 'Ð' - 0, // 209 - 'Ñ' - 0, // 210 - 'Ò' - 0, // 211 - 'Ó' - 0, // 212 - 'Ô' - 0, // 213 - 'Õ' - 0, // 214 - 'Ö' - 0, // 215 - '×' - 0, // 216 - 'Ø' - 0, // 217 - 'Ù' - 0, // 218 - 'Ú' - 0, // 219 - 'Û' - 0, // 220 - 'Ü' - 0, // 221 - 'Ý' - 0, // 222 - 'Þ' - 0, // 223 - 'ß' - 0, // 224 - 'à' - 0, // 225 - 'á' - 0, // 226 - 'â' - 0, // 227 - 'ã' - 0, // 228 - 'ä' - 0, // 229 - 'å' - 0, // 230 - 'æ' - 0, // 231 - 'ç' - 0, // 232 - 'è' - 0, // 233 - 'é' - 0, // 234 - 'ê' - 0, // 235 - 'ë' - 0, // 236 - 'ì' - 0, // 237 - 'í' - 0, // 238 - 'î' - 0, // 239 - 'ï' - 0, // 240 - 'ð' - 0, // 241 - 'ñ' - 0, // 242 - 'ò' - 0, // 243 - 'ó' - 0, // 244 - 'ô' - 0, // 245 - 'õ' - 0, // 246 - 'ö' - 0, // 247 - '÷' - 0, // 248 - 'ø' - 0, // 249 - 'ù' - 0, // 250 - 'ú' - 0, // 251 - 'û' - 0, // 252 - 'ü' - 0, // 253 - 'ý' - 0, // 254 - 'þ' - 0, // 255 - 'ÿ' -}; +// Data file for user example user defined fonts +#pragma once + +MD_MAX72XX::fontType_t mFactory[] PROGMEM = +{ +1, 0, // 0 - 'Empty Cell' + 1, 0, // 1 - 'Sad Smiley' + 1, 0, // 2 - 'Happy Smiley' + 1, 0, // 3 - 'Heart' + 1, 0, // 4 - 'Diamond' + 1, 0, // 5 - 'Clubs' + 1, 0, // 6 - 'Spades' + 1, 0, // 7 - 'Bullet Point' + 1, 0, // 8 - 'Rev Bullet Point' + 1, 0, // 9 - 'Hollow Bullet Point' + 1, 0, // 10 - 'Rev Hollow BP' + 1, 0, // 11 - 'Male' + 1, 0, // 12 - 'Female' + 1, 0, // 13 - 'Music Note 1' + 1, 0, // 14 - 'Music Note 2' + 1, 0, // 15 - 'Snowflake' + 1, 0, // 16 - 'Right Pointer' + 1, 0, // 17 - 'Left Pointer' + 1, 0, // 18 - 'UpDown Arrows' + 1, 0, // 19 - 'Full Block' + 1, 0, // 20 - 'Half Block Bottom' + 1, 0, // 21 - 'Half Block LHS' + 1, 0, // 22 - 'Half Block RHS' + 1, 0, // 23 - 'Half Block Top' + 1, 0, // 24 - 'Up Arrow' + 1, 0, // 25 - 'Down Arrow' + 1, 0, // 26 - 'Right Arrow' + 1, 0, // 27 - 'Left Arrow' + 1, 0, // 28 - '30% shading' + 1, 0, // 29 - '50% shading' + 1, 0, // 30 - 'Up Pointer' + 1, 0, // 31 - 'Down Pointer' + 1, 0, // 32 - 'Space' + 1, 0, // 33 - '!' + 1, 0, // 34 - '""' + 13, 63, 192, 127, 192, 63, 0, 250, 0, 255, 9, 1, 0, 250, // 35 - '#' + 16, 72, 84, 36, 0, 12, 112, 12, 0, 124, 4, 120, 0, 56, 68, 68, 0, // 36 - '$' + 6, 66, 37, 18, 72, 164, 66, // 37 - '%' + 1, 1, // 38 - '&' + 1, 0, // 39 - '' + 1, 0, // 40 - '(' + 1, 0, // 41 - ')' + 20, 250, 130, 250, 254, 130, 170, 186, 254, 130, 250, 226, 250, 134, 254, 130, 234, 234, 246, 254, 124, // 42 - '*' + 1, 0, // 43 - '+' + 3, 64, 0, 0, // 44 - ',' + 2, 8, 8, // 45 - '-' + 1, 128, // 46 - '.' + 15, 130, 246, 238, 130, 254, 250, 130, 250, 254, 130, 234, 234, 246, 254, 124, // 47 - '/' + 3, 126, 129, 126, // 48 - '0' + 2, 2, 255, // 49 - '1' + 3, 194, 177, 142, // 50 - '2' + 3, 66, 137, 118, // 51 - '3' + 3, 15, 8, 255, // 52 - '4' + 3, 79, 137, 113, // 53 - '5' + 3, 126, 137, 114, // 54 - '6' + 3, 1, 249, 7, // 55 - '7' + 3, 118, 137, 118, // 56 - '8' + 3, 78, 145, 126, // 57 - '9' + 1, 36, // 58 - ':' + 1, 0, // 59 - ';' + 1, 0, // 60 - '<' + 9, 254, 17, 17, 254, 0, 255, 17, 17, 14, // 61 - '=' + 1, 0, // 62 - '>' + 7, 124, 254, 254, 162, 254, 254, 254, // 63 - '?' + 1, 250, // 64 - '@' + 3, 124, 10, 124, // 65 - 'A' + 3, 126, 74, 52, // 66 - 'B' + 3, 60, 66, 36, // 67 - 'C' + 3, 126, 66, 60, // 68 - 'D' + 3, 126, 74, 66, // 69 - 'E' + 3, 126, 10, 2, // 70 - 'F' + 3, 60, 82, 116, // 71 - 'G' + 3, 126, 8, 126, // 72 - 'H' + 1, 126, // 73 - 'I' + 3, 32, 64, 62, // 74 - 'J' + 3, 126, 8, 118, // 75 - 'K' + 3, 126, 64, 64, // 76 - 'L' + 3, 126, 4, 126, // 77 - 'M' + 3, 126, 2, 124, // 78 - 'N' + 3, 60, 66, 60, // 79 - 'O' + 3, 126, 18, 12, // 80 - 'P' + 3, 60, 66, 124, // 81 - 'Q' + 3, 126, 18, 108, // 82 - 'R' + 3, 68, 74, 50, // 83 - 'S' + 3, 2, 126, 2, // 84 - 'T' + 3, 62, 64, 62, // 85 - 'U' + 3, 30, 96, 30, // 86 - 'V' + 3, 126, 32, 126, // 87 - 'W' + 3, 118, 8, 118, // 88 - 'X' + 3, 6, 120, 6, // 89 - 'Y' + 3, 98, 90, 70, // 90 - 'Z' + 4, 126, 129, 129, 66, // 91 - '[' + 3, 6, 28, 48, // 92 - '\' + 4, 255, 9, 9, 1, // 93 - ']' + 3, 8, 4, 8, // 94 - '^' + 3, 32, 32, 32, // 95 - '_' + 4, 255, 8, 20, 227, // 96 - '`' + 3, 249, 21, 249, // 97 - 'a' + 3, 253, 149, 105, // 98 - 'b' + 3, 121, 133, 73, // 99 - 'c' + 3, 253, 133, 121, // 100 - 'd' + 3, 253, 149, 133, // 101 - 'e' + 3, 253, 21, 5, // 102 - 'f' + 3, 121, 165, 233, // 103 - 'g' + 3, 253, 17, 253, // 104 - 'h' + 3, 1, 253, 1, // 105 - 'i' + 3, 65, 129, 125, // 106 - 'j' + 3, 253, 17, 237, // 107 - 'k' + 3, 253, 129, 129, // 108 - 'l' + 3, 253, 9, 253, // 109 - 'm' + 3, 253, 5, 249, // 110 - 'n' + 3, 121, 133, 121, // 111 - 'o' + 3, 253, 37, 25, // 112 - 'p' + 3, 121, 133, 249, // 113 - 'q' + 3, 253, 37, 217, // 114 - 'r' + 3, 137, 149, 101, // 115 - 's' + 3, 5, 253, 5, // 116 - 't' + 3, 125, 129, 125, // 117 - 'u' + 3, 61, 193, 61, // 118 - 'v' + 3, 253, 65, 253, // 119 - 'w' + 3, 237, 17, 237, // 120 - 'x' + 3, 13, 241, 13, // 121 - 'y' + 3, 197, 181, 141, // 122 - 'z' + 1, 0, // 123 - '{' + 1, 0, // 124 - '|' + 1, 0, // 125 - '}' + 0, // 126 - '~' + 0, // 127 - '' + 0, // 128 - '€' + 0, // 129 - '' + 0, // 130 - '‚' + 0, // 131 - 'ƒ' + 0, // 132 - '„' + 0, // 133 - '…' + 0, // 134 - '†' + 0, // 135 - '‡' + 0, // 136 - 'ˆ' + 0, // 137 - '‰' + 0, // 138 - 'Š' + 0, // 139 - '‹' + 0, // 140 - 'Œ' + 0, // 141 - '' + 0, // 142 - 'Ž' + 0, // 143 - '' + 0, // 144 - '' + 0, // 145 - '‘' + 0, // 146 - '’' + 0, // 147 - '“' + 0, // 148 - '”' + 1, 0, // 149 - '•' + 1, 0, // 150 - '–' + 1, 0, // 151 - '—' + 0, // 152 - '˜' + 0, // 153 - '™' + 0, // 154 - 'š' + 0, // 155 - '›' + 0, // 156 - 'œ' + 0, // 157 - '' + 0, // 158 - 'ž' + 0, // 159 - 'Ÿ' + 0, // 160 - '' + 0, // 161 - '¡' + 0, // 162 - '¢' + 0, // 163 - '£' + 0, // 164 - '¤' + 0, // 165 - '¥' + 0, // 166 - '¦' + 0, // 167 - '§' + 0, // 168 - '¨' + 8, 224, 224, 0, 0, 0, 0, 0, 0, // 169 - '©' + 8, 224, 224, 0, 252, 252, 0, 0, 0, // 170 - 'ª' + 8, 224, 224, 0, 252, 252, 0, 255, 255, // 171 - '«' + 0, // 172 - '¬' + 0, // 173 - '­' + 5, 64, 0, 0, 0, 0, // 174 - '®' + 5, 64, 0, 64, 0, 0, // 175 - '¯' + 5, 64, 0, 64, 0, 64, // 176 - '°' + 6, 254, 146, 146, 146, 254, 0, // 177 - '±' + 7, 128, 126, 42, 42, 170, 254, 0, // 178 - '²' + 8, 128, 152, 64, 62, 80, 136, 128, 0, // 179 - '³' + 8, 72, 40, 152, 254, 16, 40, 68, 0, // 180 - '´' + 8, 68, 36, 20, 254, 20, 36, 68, 0, // 181 - 'µ' + 8, 168, 232, 172, 250, 172, 232, 168, 0, // 182 - '¶' + 8, 128, 136, 136, 254, 136, 136, 128, 0, // 183 - '·' + 0, // 184 - '¸' + 0, // 185 - '¹' + 3, 4, 10, 4, // 186 - 'º' + 0, // 187 - '»' + 0, // 188 - '¼' + 0, // 189 - '½' + 0, // 190 - '¾' + 0, // 191 - '¿' + 0, // 192 - 'À' + 0, // 193 - 'Á' + 0, // 194 - 'Â' + 0, // 195 - 'Ã' + 0, // 196 - 'Ä' + 0, // 197 - 'Å' + 0, // 198 - 'Æ' + 0, // 199 - 'Ç' + 0, // 200 - 'È' + 0, // 201 - 'É' + 0, // 202 - 'Ê' + 0, // 203 - 'Ë' + 0, // 204 - 'Ì' + 0, // 205 - 'Í' + 0, // 206 - 'Î' + 0, // 207 - 'Ï' + 0, // 208 - 'Ð' + 0, // 209 - 'Ñ' + 0, // 210 - 'Ò' + 0, // 211 - 'Ó' + 0, // 212 - 'Ô' + 0, // 213 - 'Õ' + 0, // 214 - 'Ö' + 0, // 215 - '×' + 0, // 216 - 'Ø' + 0, // 217 - 'Ù' + 0, // 218 - 'Ú' + 0, // 219 - 'Û' + 0, // 220 - 'Ü' + 0, // 221 - 'Ý' + 0, // 222 - 'Þ' + 0, // 223 - 'ß' + 0, // 224 - 'à' + 0, // 225 - 'á' + 0, // 226 - 'â' + 0, // 227 - 'ã' + 0, // 228 - 'ä' + 0, // 229 - 'å' + 0, // 230 - 'æ' + 0, // 231 - 'ç' + 0, // 232 - 'è' + 0, // 233 - 'é' + 0, // 234 - 'ê' + 0, // 235 - 'ë' + 0, // 236 - 'ì' + 0, // 237 - 'í' + 0, // 238 - 'î' + 0, // 239 - 'ï' + 0, // 240 - 'ð' + 0, // 241 - 'ñ' + 0, // 242 - 'ò' + 0, // 243 - 'ó' + 0, // 244 - 'ô' + 0, // 245 - 'õ' + 0, // 246 - 'ö' + 0, // 247 - '÷' + 0, // 248 - 'ø' + 0, // 249 - 'ù' + 0, // 250 - 'ú' + 0, // 251 - 'û' + 0, // 252 - 'ü' + 0, // 253 - 'ý' + 0, // 254 - 'þ' + 0, // 255 - 'ÿ' +};