#include "includes.h"

DIP_t g_Dip;

void DIP_Switch_Init(void){
	
	GPIO_Init(GPIOB0,0,Intput);
	GPIO_Init(GPIOB0,1,Intput);
	GPIO_Init(GPIOB0,2,Intput);
	
	
	
	GPIO_PullHigh_Init(GPIOB0,0);
	GPIO_PullHigh_Init(GPIOB0,1);
	GPIO_PullHigh_Init(GPIOB0,2);
	
	memset(&g_Dip,0,sizeof(DIP_t));
	
	delay_nms(20);
	
	/*上电读取拨码状态*/
	for (U8_T i = 0; i < DIP_CHN_MAX; i++) {
		if(DIP_GetSwitchState(i) == DIP_PRESS){
			g_Dip.DIP_val |= DIP_VAL_ON << i;
		}
	}
	
	g_Dip.DIP_last_val = g_Dip.DIP_val;
	g_Dip.DIP_addr = g_Dip.DIP_val & 0x07;

	/*进入设置界面 - 先决条件*/
	Dbg_Println(DBG_BIT_Debug_STATUS,"DIP Addr:%d",g_Dip.DIP_val);
}

U8_T DIP_GetSwitchState(U8_T i){
	U8_T val = 0;
	
	switch (i)
    {
		case DIP_CH1:
			val = GPIO_Read_Status(GPIOB0,2);
			break;
		case DIP_CH2:
			val = GPIO_Read_Status(GPIOB0,1);
			break;
		case DIP_CH3:
			val = GPIO_Read_Status(GPIOB0,0);
			break;
    }
    return val;
}

void DIP_ScanTask(void)
{
    static U32_T update_20ms = 0;

    if (SysTick_1ms - update_20ms > DIP_SCAN_Time)
    {
        update_20ms = SysTick_1ms;
		
        for (U8_T i = 0; i < DIP_CHN_MAX; i++)
        {
            if (DIP_GetSwitchState(i) == DIP_PRESS)
            {
                g_Dip.delayCnt_OFF[i] = 0;
                if (g_Dip.delayCnt_ON[i] < DIP_DELAY_COUNT)
                {
                    g_Dip.delayCnt_ON[i]++;
                }
                else
                {
                    g_Dip.DIP_val |= (DIP_VAL_ON << i);              
                    g_Dip.delayCnt_ON[i] = 0;
                }
            }
            else
            {
                g_Dip.delayCnt_ON[i] = 0;
                if (g_Dip.delayCnt_OFF[i] < DIP_DELAY_COUNT)
                {
                    g_Dip.delayCnt_OFF[i]++;
                }
                else
                {
                    g_Dip.DIP_val &= ~(DIP_VAL_ON << i);             
                    g_Dip.delayCnt_OFF[i] = 0;
                }
            }
        }
    }

    if(g_Dip.DIP_val != g_Dip.DIP_last_val)
    {
		g_Dip.DIP_last_val = g_Dip.DIP_val;
		
        /*拨码开关 - Bit0~Bit3：设备地址*/
		g_Dip.DIP_addr = g_Dip.DIP_val & 0x07;

		Dbg_Println(DBG_BIT_Debug_STATUS,"DIP Change Addr:%d",g_Dip.DIP_addr);
		
		if(g_Dip.DIP_addr != g_mcu_dev.dev_addr){
			g_mcu_dev.dev_addr = g_Dip.DIP_addr;
		//	EEPROM_WriteMCUDevInfo(&g_mcu_dev);
		}		
		
    }
    
}



