#include <stdio.h>
#include "LED.h"
#include "esp_log.h"
#include "esp_rom_sys.h"
static const char *LOG_TAG = "LED";

// uint8_t led[6]={0x04,0x20,0x08,0x10,0x02,0x40 };

// uint8_t led[6]={0x20,0x02,0x04,0x08,0x10,0x40 };
// dailiao baoyang tunxing fengcun  guzhang tingji
uint8_t led[6] = {0x04, 0x40, 0x20, 0x10, 0x08, 0x02};

#include <stdio.h>

#include "esp_err.h"

static void example_ledc_init(void)
{
    // Prepare and then apply the LEDC PWM timer configuration
    ledc_timer_config_t ledc_timer = {
        .speed_mode = LEDC_MODE,
        .timer_num = LEDC_TIMER,
        .duty_resolution = LEDC_DUTY_RES,
        .freq_hz = LEDC_FREQUENCY, // Set output frequency at 5 kHz
        .clk_cfg = LEDC_AUTO_CLK};
    ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));

    // Prepare and then apply the LEDC PWM channel configuration
    ledc_channel_config_t ledc_channel = {
        .speed_mode = LEDC_MODE,
        .channel = LEDC_CHANNEL,
        .timer_sel = LEDC_TIMER,
        .intr_type = LEDC_INTR_DISABLE,
        .gpio_num = LEDC_OUTPUT_IO,
        .duty = 0, // Set duty to 0%
        .hpoint = 0};
    ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
}

void beep_init(void)
{

    // Set the LEDC peripheral configuration
    example_ledc_init();
    // Set duty to 50%
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
    // Update duty to apply the new value
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
}

static void _74HC595_WriteByte(unsigned char Byte)
{

    unsigned char i;
    for (i = 0; i < 8; i++)
    {
        uint8_t bit = (Byte >> (i)) & 0x01;
        gpio_set_level(LED_DATA_PIN, bit);
        LED_LCLK_0;
        LED_LCLK_1;
    }
    LED_SCLK_0;
    LED_SCLK_1;
}

void led_set(uint8_t led_index, uint8_t led_status)
{

    ESP_LOGI(LOG_TAG, "led_set  %s", led_status ? "open" : "close");

    if (led_status)
    {
        _74HC595_WriteByte(led[led_index]);
    }
    else
    {
        _74HC595_WriteByte(0x00);
    }
}

void beep_open()
{
    // Set duty to 50%
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, LEDC_DUTY));
    // Update duty to apply the new value
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
}

void beep_close()
{
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
    // Update duty to apply the new value
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
}

void beep_blink(uint16_t ms, uint16_t count)
{

    for (int i = 0; i < count; i++)
    {
        // printf("beep\r\n");
        beep_open();
        vTaskDelay(ms / portTICK_PERIOD_MS);
        beep_close();
        vTaskDelay(ms / portTICK_PERIOD_MS);

        // beep_open();
        // esp_rom_delay_us(ms*1000);//阻塞延时
        // beep_close();
        // esp_rom_delay_us(ms*1000);//阻塞延时
    }
}