Login
1 branch 0 tags
Ben (Desktop/Arch) Much smoother rendering f0d75c6 1 month ago 75 Commits
moon / esp32 / main / esp32_main.c
#include "audio_player.h"
#include "buttons.h"
#include "lvgl_port.h"
#include "moon.h"
#include "st7735.h"

#include <string.h>
#include "esp_log.h"
#include "esp_pm.h"
#include "esp_task_wdt.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

static const char* TAG = "moon";

// Stub implementations - ESP32 uses ST7735 driver directly, not blit_buf
void blit_buf(const void* buf, int yStart, int yEnd) {
	(void)buf;
	(void)yStart;
	(void)yEnd;
}

void blit_buf_rect(const void* buf,
                   int xStart,
                   int yStart,
                   int xEnd,
                   int yEnd) {
	(void)buf;
	(void)xStart;
	(void)yStart;
	(void)xEnd;
	(void)yEnd;
}

// Forward declarations from shared code
extern void setup(void);
extern void loop(void);

static int64_t last_tick_us = 0;

void app_main(void) {
	// Subscribe main task to watchdog so we can feed it during long renders
	esp_task_wdt_add(xTaskGetCurrentTaskHandle());

	ESP_LOGI(TAG, "Initializing ST7735 display...");
	st7735_init();

	ESP_LOGI(TAG, "Initializing buttons...");
	buttons_init();

	ESP_LOGI(TAG, "Initializing LVGL...");
	lvgl_port_init();
	lvgl_port_indev_init();

	ESP_LOGI(TAG, "Running setup...");
	setup();

	last_tick_us = esp_timer_get_time();

	// Lock CPU at 160MHz (80/240 break display)
	esp_pm_config_t pm_cfg = {
	    .max_freq_mhz = 160,
	    .min_freq_mhz = 160,
	    .light_sleep_enable = false,
	};
	esp_pm_configure(&pm_cfg);

	ESP_LOGI(TAG, "Entering main loop...");
	while (1) {
		// Calculate elapsed time for LVGL tick
		int64_t now_us = esp_timer_get_time();
		uint32_t elapsed_ms = (now_us - last_tick_us) / 1000;
		last_tick_us = now_us;

		// Update LVGL tick
		if (elapsed_ms > 0) {
			lv_tick_inc(elapsed_ms);
		}

		// Poll button state
		buttons_update();

		// Run application loop
		loop();

		// Smoothly transition background brightness
		update_backlight_brightness();

		// Handle LVGL tasks and sleep until next timer fires
		uint32_t time_till_next = lv_timer_handler();
		esp_task_wdt_reset();

		if (time_till_next > 2) {
			vTaskDelay(pdMS_TO_TICKS(time_till_next - 1));
		} else {
			taskYIELD();
		}
	}
}