#include "includes.h"

DIP_t g_Dip;

void DIP_Switch_Init(void){
	
	GPIO_Init(GPIOA0,10,Intput);
	GPIO_Init(GPIOA0,9,Intput);
	GPIO_Init(GPIOA0,8,Intput);

	
	GPIO_PullHigh_Init(GPIOA0,10);
	GPIO_PullHigh_Init(GPIOA0,9);
	GPIO_PullHigh_Init(GPIOA0,8);
	
	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.addr = g_Dip.DIP_val & 0x07;
	g_Dip.Dev_Port = Passive_Port;

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

U8_T DIP_GetSwitchState(U8_T i){
	U8_T val = 0;
	
	switch (i)
    {
		case DIP_CH1:
			val = GPIO_Read_Status(GPIOA0,10);
			break;
		case DIP_CH2:
			val = GPIO_Read_Status(GPIOA0,9);
			break;
		case DIP_CH3:
			val = GPIO_Read_Status(GPIOA0,8);
			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.addr = g_Dip.DIP_val & 0x07;
		
		Dbg_Println(DBG_BIT_SYS_STATUS,"DIP Scan %d",g_Dip.addr);
    }
    
}



