/* 
    author: liangjingheng-waveshare
    data:2025-10-13
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "led_strip.h"
#include "sdkconfig.h"

static const char *TAG = "rgb_cycle";


#define BLINK_GPIO 27

#ifdef CONFIG_BLINK_LED_STRIP

static led_strip_handle_t led_strip;

// Color array: Red, Blue, Yellow, Green, White
static const struct {
    uint8_t r;  // Red component
    uint8_t g;  // Green component
    uint8_t b;  // Blue component
} colors[] = {
    {255, 0, 0},    // Red
    {0, 0, 255},    // Blue
    {255, 255, 0},  // Yellow
    {0, 255, 0},    // Green
    {255, 255, 255} // White
};
#define COLOR_COUNT (sizeof(colors) / sizeof(colors[0]))
#define SWITCH_DELAY_MS 1000

// LED initialization function
static void configure_led(void)
{
    ESP_LOGI(TAG, "Initializing addressable RGB LED...");
    led_strip_config_t strip_config = {
        .strip_gpio_num = BLINK_GPIO,  
        .max_leds = 1,                 
    };
#if CONFIG_BLINK_LED_STRIP_BACKEND_RMT
    led_strip_rmt_config_t rmt_config = {
        .resolution_hz = 10 * 1000 * 1000,
        .flags.with_dma = false,
    };
    ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip));
#elif CONFIG_BLINK_LED_STRIP_BACKEND_SPI
    led_strip_spi_config_t spi_config = {
        .spi_bus = SPI2_HOST,
        .flags.with_dma = true,
    };
    ESP_ERROR_CHECK(led_strip_new_spi_device(&strip_config, &spi_config, &led_strip));
#else
#error "unsupported LED strip backend"
#endif
    led_strip_clear(led_strip);  // Turn off initially
}

#elif CONFIG_BLINK_LED_GPIO
// Regular GPIO LEDs do not support RGB, keep error message
#error "Please select LED_STRIP type in menuconfig (supports RGB)"
#else
#error "unsupported LED type"
#endif

void app_main(void)
{
    configure_led();  // Call LED initialization function

    int current_color = 0;
    ESP_LOGI(TAG, "Starting color cycle...");

    while (1) {
        // Get RGB values of the current color
        uint8_t r = colors[current_color].r;
        uint8_t g = colors[current_color].g;
        uint8_t b = colors[current_color].b;

        // Set LED color and refresh
        led_strip_set_pixel(led_strip, 0, r, g, b);
        led_strip_refresh(led_strip);

        ESP_LOGI(TAG, "Current color: R=%d, G=%d, B=%d", r, g, b);

        // Cycle to next color
        current_color = (current_color + 1) % COLOR_COUNT;

        // Delay for specified time
        vTaskDelay(SWITCH_DELAY_MS / portTICK_PERIOD_MS);
    }
}
