#include "common.h"
#include "led.h"

#include <driver/ledc.h>

/*
 * Note: the Arduino HAL doesn't handle low frequencies, because it
 * seems to insist on using a high frequency clock source...
 */

#define LED_PIN_BASE 2

void led_set(int led, enum led_mode mode)
{
    static const struct {
	uint32_t freq;
	uint32_t duty;
    } led_modes[] = {
	{ 1, 0 },		/* Off */
	{ 1, 1 << 12 },		/* On */
	{ 2, 1 << 11 },		/* Medium blink (2 Hz) */
	{ 1, 1 << 11 },		/* Slow blink (1 Hz) */
	{ 4, 1 << 11 }		/* Fast blink (4 Hz) */
    };
    ledc_channel_config_t channel_config = {
	.speed_mode            = LEDC_LOW_SPEED_MODE,
	.hpoint                = 0,
	.flags.output_invert   = 0,
	.intr_type             = LEDC_INTR_DISABLE,
	.channel               = led,
	.timer_sel             = led,
	.gpio_num              = led + LED_PIN_BASE,
	.duty                  = led_modes[mode].duty
    };
    ledc_timer_config_t timer_config = {
	.speed_mode            = LEDC_LOW_SPEED_MODE,
	.duty_resolution       = 12,
	.clk_cfg               = LEDC_USE_REF_TICK,
	.timer_num             = led,
	.freq_hz               = led_modes[mode].freq
    };

    ledc_timer_config(&timer_config);
    ledc_channel_config(&channel_config);
}

void led_init(void)
{
    for (int led = 0; led < 3; led++)
	led_set(led, LED_OFF);
}
