From 29875b53cf74d4e7a4e3e461a12c49c030b5b22c Mon Sep 17 00:00:00 2001
From: ConfuSomu
Date: Wed, 14 Feb 2024 15:18:29 -0500
Subject: Implement getting current time in SDL build

---
 hal/api.cpp          |  2 +-
 hal/sdl2/display.cpp | 30 +++++++++++++++++++++++++-----
 hal/sdl2/display.hpp |  2 ++
 3 files changed, 28 insertions(+), 6 deletions(-)

(limited to 'hal')

diff --git a/hal/api.cpp b/hal/api.cpp
index a983c9b..961cdd5 100644
--- a/hal/api.cpp
+++ b/hal/api.cpp
@@ -328,7 +328,7 @@ bool Api::datetime_get(datetime_t *t) {
 #ifndef SDL2_BUILD
     return rtc_get_datetime(t);
 #else
-    return false;
+    return m_sdl_display.get_datetime(t);
 #endif
 }
 
diff --git a/hal/sdl2/display.cpp b/hal/sdl2/display.cpp
index 64b92cd..a5cff6a 100644
--- a/hal/sdl2/display.cpp
+++ b/hal/sdl2/display.cpp
@@ -1,7 +1,9 @@
 #ifdef SDL2_BUILD
 #include "display.hpp"
 #include "../../buttons.hpp"
+#include "pico/types.h"
 #include <iostream>
+#include <time.h>
 
 #define SCREEN_HEIGHT 64
 #define SCREEN_WIDTH 128
@@ -43,6 +45,13 @@ SDLDisplay::SDLDisplay() {
     SDL_SetPaletteColors(m_surface->format->palette, colors, 0, 2);
 }
 
+SDLDisplay::~SDLDisplay() {
+    SDL_DestroyTexture(m_texture);
+    SDL_DestroyRenderer(m_renderer);
+    SDL_DestroyWindow(m_window);
+    SDL_Quit();
+}
+
 bool SDLDisplay::process_input() {
     SDL_Event e;
     while (SDL_PollEvent(&e) != 0) {
@@ -75,11 +84,22 @@ bool SDLDisplay::update_display(const uint8_t* oled_screen) {
     return false;
 }
 
-SDLDisplay::~SDLDisplay() {
-    SDL_DestroyTexture(m_texture);
-    SDL_DestroyRenderer(m_renderer);
-    SDL_DestroyWindow(m_window);
-    SDL_Quit();
+bool SDLDisplay::get_datetime(datetime_t* t) {
+    // Get current date and time
+    time_t rawtime;
+    struct tm* timeinfo;
+    time(&rawtime);
+    timeinfo = localtime(&rawtime);
+
+    // Map ISO C tm struct to Pico's datetime_t
+    t->day = timeinfo->tm_mday;
+    t->dotw = timeinfo->tm_wday;
+    t->month = timeinfo->tm_mon;
+    t->year = timeinfo->tm_year + 1900;
+    t->hour = timeinfo->tm_hour;
+    t->min = timeinfo->tm_min;
+    t->sec = timeinfo->tm_sec;
+    return true;
 }
 
 unsigned char rorb(unsigned char x, unsigned char n) {
diff --git a/hal/sdl2/display.hpp b/hal/sdl2/display.hpp
index a267cae..e9302bc 100644
--- a/hal/sdl2/display.hpp
+++ b/hal/sdl2/display.hpp
@@ -1,6 +1,7 @@
 #pragma once
 #ifdef SDL2_BUILD
 #include <SDL.h>
+#include "pico/types.h"
 
 class SDLDisplay {
 public:
@@ -10,6 +11,7 @@ public:
     // When returning false, please quit the program (return from main)
     bool update_display(const uint8_t* oled_screen);
     bool process_input();
+    bool get_datetime(datetime_t* t);
 private:
     SDL_Window* m_window = nullptr;
     SDL_Renderer* m_renderer = nullptr;
-- 
cgit v1.2.3-54-g00ecf