#include "sdk_common.h"
#include "SEGGER_RTT.h"
#include "nrf_drv_pwm.h"
#include "usr_config.h"
#include "system.h"
#include "nrf_gpio.h"
#include "bsp_pwm.h"

/********************** ±äÁ¿Çø *************************/

static nrf_drv_pwm_t m_pwm0 = NRF_DRV_PWM_INSTANCE(0);

static const uint16_t pwm_const = 1250;

static nrf_pwm_values_individual_t m_demo1_seq_values={0,0,0};

static nrf_pwm_sequence_t const    m_demo1_seq =
{
    .values.p_individual = &m_demo1_seq_values,
    .length              = NRF_PWM_VALUES_LENGTH(m_demo1_seq_values),
    .repeats             = 0,
    .end_delay           = 0
};

void Pwm_update_duty(uint8_t duty_1,uint8_t duty_2,uint8_t duty_3)
{
	   if(duty_1 >  100)duty_1 =100;
	   if(duty_2 >  100)duty_2 =100;
	   if(duty_3 >  100)duty_3 =100;
	  
	   if(PCB_VERSION == 1 || PCB_VERSION == 3){
			   duty_1 = 100-duty_1;
			   duty_2 = 100-duty_2;
			   duty_3 = 100-duty_3;
		 }
		 uint16_t duty1_t = (uint16_t)(duty_1*pwm_const/100);
		 uint16_t duty2_t = (uint16_t)(duty_2*pwm_const/100);
		 uint16_t duty3_t = (uint16_t)(duty_3*pwm_const/100);
     m_demo1_seq_values.channel_0 = duty1_t;
	   m_demo1_seq_values.channel_1 = duty2_t;
	   m_demo1_seq_values.channel_2 = duty3_t;
		 
		 //DEBUG_LOG("led debug %d,%d,%d\n",m_demo1_seq_values.channel_0,m_demo1_seq_values.channel_1,m_demo1_seq_values.channel_2);
}

static void Pwm_init(void)
{
    nrf_drv_pwm_config_t const config0 =
    {
        .output_pins =
        {
            PIN_LED_R, // channel 0
            PIN_LED_G, // channel 1
            PIN_LED_B, // channel 2
            NRF_DRV_PWM_PIN_NOT_USED
        },
        .irq_priority = APP_IRQ_PRIORITY_LOWEST,
        .base_clock   = NRF_PWM_CLK_125kHz,
        .count_mode   = NRF_PWM_MODE_UP,
        .top_value    = pwm_const,
        .load_mode    = NRF_PWM_LOAD_INDIVIDUAL,
        .step_mode    = NRF_PWM_STEP_AUTO
    };
    APP_ERROR_CHECK(nrf_drv_pwm_init(&m_pwm0, &config0, NULL));
		
    m_demo1_seq_values.channel_0 = pwm_const;
    m_demo1_seq_values.channel_1 = pwm_const;
    m_demo1_seq_values.channel_2 = pwm_const;

    (void)nrf_drv_pwm_simple_playback(&m_pwm0, &m_demo1_seq, 1,
                                      NRF_DRV_PWM_FLAG_LOOP);
		
}

static void cb_pwmWakeup(uint32_t t)
{
	  Pwm_init();
}

static void cb_pwmSleep(uint32_t t)
{
	  nrfx_pwm_uninit(&m_pwm0);
	  nrf_gpio_cfg_input(PIN_LED_R, NRF_GPIO_PIN_NOPULL);//IO 
	  nrf_gpio_cfg_input(PIN_LED_G, NRF_GPIO_PIN_NOPULL);
	  nrf_gpio_cfg_input(PIN_LED_B, NRF_GPIO_PIN_NOPULL);
}

void Pwm_Initialize(void){
	Pwm_init();
	Wakeup_Regist(cb_pwmWakeup);
  Sleep_Regist(cb_pwmSleep);
}
