// rtc_manager.cpp - RTC Manager Implementation #include #include "rtc_manager.h" #include "task_config.h" RTC_DS3231 rtc; bool rtcInitialized = false; bool initRTC() { Serial.println("Initializing DS3231 RTC..."); // Initialize I2C Wire.begin(RTC_SDA_PIN, RTC_SCL_PIN); // Initialize RTC if (!rtc.begin()) { Serial.println("RTC not found!"); rtcInitialized = false; return false; } // Check if RTC is running if (rtc.lostPower()) { Serial.println("RTC lost power, setting default time!"); // Set to compile time rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } // Sync system time from RTC syncSystemTimeFromRTC(); rtcInitialized = true; Serial.println("RTC initialized successfully!"); Serial.print(" Current time: "); Serial.println(getRTCTimeString()); return true; } bool isRTCRunning() { return rtcInitialized && !rtc.lostPower(); } void setRTCTime(uint32_t unixtime) { if (!rtcInitialized) return; rtc.adjust(DateTime(unixtime)); syncSystemTimeFromRTC(); Serial.printf("RTC time set to: %s\n", getRTCTimeString().c_str()); } uint32_t getRTCTime() { if (!rtcInitialized) return 0; DateTime now = rtc.now(); return now.unixtime(); } String getRTCTimeString() { if (!rtcInitialized) return String("RTC Not Initialized"); DateTime now = rtc.now(); char buffer[25]; snprintf(buffer, sizeof(buffer), "%04d-%02d-%02d %02d:%02d:%02d", now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); return String(buffer); } bool syncTimeFromNTP() { // This will be called from WiFi STA mode // Implementation depends on WiFi connection // For now, placeholder Serial.println("NTP sync requested (requires WiFi STA mode)"); return false; } void timeSyncTask(void *pvParameters) { Serial.println("Time Sync Task started on Core 1"); static uint32_t lastNTPSync = 0; static uint32_t lastRTCSync = 0; const uint32_t RTC_SYNC_INTERVAL_MS = 3600000; while (1) { uint32_t now = millis(); if (now - lastNTPSync > NTP_SYNC_INTERVAL_MS) { lastNTPSync = now; } if (now - lastRTCSync > RTC_SYNC_INTERVAL_MS) { if (rtcInitialized) { syncSystemTimeFromRTC(); Serial.printf("[RTC] System time synced: %s\n", getRTCTimeString().c_str()); } lastRTCSync = now; } vTaskDelay(pdMS_TO_TICKS(60000)); } } uint64_t getMicrosTimestamp() { // Get current time in microseconds struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * 1000000ULL + tv.tv_usec; } String unixTimeToString(uint32_t unixtime) { time_t t = unixtime; struct tm* timeinfo = localtime(&t); char buffer[25]; strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", timeinfo); return String(buffer); } void syncSystemTimeFromRTC() { if (!rtcInitialized) return; DateTime now = rtc.now(); struct timeval tv; tv.tv_sec = now.unixtime(); tv.tv_usec = 0; settimeofday(&tv, NULL); // Set timezone (KST = UTC+9) setenv("TZ", "KST-9", 1); tzset(); }