#include "SGMCD1020Q.h"
#include "Simulated_SPI_1_Master.h"

static SGMCD_DeviceType currentDevice = SGMCD_DEVICE_1;

/* 选择SGMCD1020Q设备 */
void SGMCD1020Q_SelectDevice(SGMCD_DeviceType device)
{    
    /* 选择指定设备 */
    switch(device)
    {
        case SGMCD_DEVICE_1:
            SGMCD1020Q_CS1_Output_Low();
            break;
        case SGMCD_DEVICE_2:
            SGMCD1020Q_CS2_Output_Low();
            break;
        case SGMCD_DEVICE_3:
            SGMCD1020Q_CS3_Output_Low();
            break;
        default:
            break;
    }
    
    currentDevice = device;
}

/* 取消选择所有设备 */
void SGMCD1020Q_DeselectAllDevices(void)
{
    SGMCD1020Q_CS1_Output_High();
    SGMCD1020Q_CS2_Output_High();
    SGMCD1020Q_CS3_Output_High();
}

/* 32位SPI数据传输 */
uint32_t SGMCD1020Q_SPI_Transfer(uint32_t data)
{
    uint32_t rxData = 0;
    uint8_t i;
    uint8_t txBytes[4], rxBytes[4];
    
    /* 确保设备已选择 */
    SGMCD1020Q_SelectDevice(currentDevice);

    /* 分解32位数据为4个字节（大端模式） */
    txBytes[0] = (data >> 24) & 0xFF;
    txBytes[1] = (data >> 16) & 0xFF;
    txBytes[2] = (data >> 8) & 0xFF;
    txBytes[3] = data & 0xFF;
    
    /* 传输4个字节 */
    for(i = 0; i < 4; i++)
    {
        rxBytes[i] = Sim_SPI_Master_1_Byte_Read(txBytes[i]);
    }
    
    /* 组合接收到的数据 */
    rxData = ((uint32_t)rxBytes[0] << 24) | 
             ((uint32_t)rxBytes[1] << 16) | 
             ((uint32_t)rxBytes[2] << 8) | 
             (uint32_t)rxBytes[3];
    
    return rxData;
}


/* 读取寄存器 */
uint32_t SGMCD1020Q_ReadRegister(uint8_t regAddr)
{
    uint32_t command;
    
    /* 构建读命令：地址(7位) + 类型0(读) + 24位数据(0) */
    command = ((uint32_t)regAddr << 24);
    
    return SGMCD1020Q_SPI_Transfer(command);
}

/* 写入寄存器 */
void SGMCD1020Q_WriteRegister(uint8_t regAddr, uint32_t data)
{
    uint32_t command;
    
    /* 构建写命令：地址(7位) + 类型1(写) + 24位数据 */
    command = ((uint32_t)regAddr << 25) | (1 << 24) | (data & 0xFFFFFF);
    
    SGMCD1020Q_SPI_Transfer(command);
}

/* 读取开关状态 */
uint32_t SGMCD1020Q_ReadSwitchStatus(void)
{
    return SGMCD1020Q_ReadRegister(SGMCD_REG_READ_SWITCH_STATUS);
}

/* 设置通道湿润电流 */
void SGMCD1020Q_SetWettingCurrent(uint8_t channel, uint8_t currentLevel)
{
    uint32_t regValue = 0;
    uint8_t i;
    
    /* 设置所有通道为相同的湿润电流（可根据需要修改为单个通道设置） */
    for(i = 0; i < 8; i++)
    {
        regValue |= ((uint32_t)currentLevel << (i * 3));
    }
    
    if(channel < 14) 
    {
        /* SG通道 */
        if(channel < 8)
            SGMCD1020Q_WriteRegister(SGMCD_REG_WETTING_CURRENT_SG0, regValue);
        else
            SGMCD1020Q_WriteRegister(SGMCD_REG_WETTING_CURRENT_SG1, regValue);
    }
    else 
    {
        /* SP通道 */
        SGMCD1020Q_WriteRegister(SGMCD_REG_WETTING_CURRENT_SP, regValue);
    }
}

/* 使能/禁用中断 */
void SGMCD1020Q_EnableInterrupt(uint8_t channel, uint8_t enable)
{
    uint32_t regValue = enable ? 0xFFFFFFFF : 0x00000000;
    
    if(channel < 14) 
    {
        /* SG通道中断使能 */
        SGMCD1020Q_WriteRegister(SGMCD_REG_INT_ENABLE_SG, regValue & 0x3FFF);
    }
    else 
    {
        /* SP通道中断使能 */
        SGMCD1020Q_WriteRegister(SGMCD_REG_INT_ENABLE_SP, regValue & 0xFF);
    }
}

/* 进入低功耗模式 */
void SGMCD1020Q_EnterLowPowerMode(void)
{
    SGMCD1020Q_WriteRegister(SGMCD_REG_ENTER_LPM, 0x000000);
}

/* 设备复位 */
void SGMCD1020Q_Reset(void)
{
    SGMCD1020Q_WriteRegister(SGMCD_REG_RESET, 0x000000);
}

/* 读取故障状态 */
uint32_t SGMCD1020Q_ReadFaultStatus(void)
{
    return SGMCD1020Q_ReadRegister(SGMCD_REG_FAULT_STATUS);
}

/* 配置设备参数（综合函数） */
void SGMCD1020Q_ConfigureDevice(void)
{
    /* 设置SP0为开关对电池(SB)，其他为开关对地(SG) */
    SGMCD1020Q_WriteRegister(SGMCD_REG_DEVICE_CONFIG, 0x000001);
    
    /* 设置所有通道湿润电流为8mA */
    SGMCD1020Q_SetWettingCurrent(0, WETTING_CURRENT_8MA);
    
    /* 使能所有通道中断 */
    SGMCD1020Q_EnableInterrupt(0, 1);  /* SG通道 */
    SGMCD1020Q_EnableInterrupt(14, 1); /* SP通道 */
    
    /* 设置低功耗模式轮询周期为64ms */
    SGMCD1020Q_WriteRegister(SGMCD_REG_LPM_CONFIG, 0x00000F);
}



/* 定义INT_B引脚 */
// #define INT_B_PIN DioConf_DioChannel_P02_03  /* 根据实际连接修改 */

/* 全局变量存储开关状态 */
static uint32_t switchStatus = 0;
static uint8_t deviceInitialized = 0;

/* SGMCD1020Q应用初始化 */
void SGMCD1020Q_Init(void)
{    
    SGMCD1020Q_DeselectAllDevices();
    /* 初始化模拟SPI（模式0，MSB优先） */
    Sim_SPI_Master_1_Start(SIM_SPI_MODE_0, SIM_SPI_MSB_FIRST);
    /* 选择设备1 */
    SGMCD1020Q_SelectDevice(SGMCD_DEVICE_1);
    /* 配置设备参数 */
    SGMCD1020Q_ConfigureDevice();

    SGMCD1020Q_DeselectAllDevices();

    /* 初始化模拟SPI（模式0，MSB优先） */
    Sim_SPI_Master_1_Start(SIM_SPI_MODE_0, SIM_SPI_MSB_FIRST);
    /* 选择设备1 */
    SGMCD1020Q_SelectDevice(SGMCD_DEVICE_2);
    /* 配置设备参数 */
    SGMCD1020Q_ConfigureDevice();
    
    SGMCD1020Q_DeselectAllDevices();

    /* 初始化模拟SPI（模式0，MSB优先） */
    Sim_SPI_Master_1_Start(SIM_SPI_MODE_0, SIM_SPI_MSB_FIRST);
    /* 选择设备1 */
    SGMCD1020Q_SelectDevice(SGMCD_DEVICE_3);
    /* 配置设备参数 */
    SGMCD1020Q_ConfigureDevice();
    SGMCD1020Q_DeselectAllDevices();
    
    deviceInitialized = 1;
}
volatile SGMCD1020Q_SwitchStatus_t SGMCD1020Q_1;
volatile SGMCD1020Q_SwitchStatus_t SGMCD1020Q_2;
volatile SGMCD1020Q_SwitchStatus_t SGMCD1020Q_3;
/* 读取并处理开关状态 */
void SGMCD1020Q_ReadAndProcessSwitches(uint8_t Chip)
{
  if (!deviceInitialized)
    return;

  uint32_t newStatus = 0;
  newStatus = SGMCD1020Q_ReadSwitchStatus();

  if (Chip == 1)
  {
    SGMCD1020Q_1.raw_value = newStatus;
  }
  else if (Chip == 2)
  {
    SGMCD1020Q_2.raw_value = newStatus;
  }
  else if (Chip == 3)
  {
    SGMCD1020Q_3.raw_value = newStatus;
  }
  else
  {
    ;
  }
}

/* 故障处理函数 */
void SGMCD1020Q_HandleFault(uint32_t faultStatus)
{
    /* 处理各种故障情况 */
    if(faultStatus & (1 << 7)) /* UV故障 */
    {
        /* 欠压处理 */
    }
    
    if(faultStatus & (1 << 6)) /* OV故障 */
    {
        /* 过压处理 */
    }
    
    if(faultStatus & (1 << 5)) /* 温度警告 */
    {
        /* 温度警告处理 */
    }
    
    if(faultStatus & (1 << 4)) /* 过温故障 */
    {
        /* 过温处理 */
    }
}

/* 中断服务函数（如果使用硬件中断） */
void SGMCD1020Q_InterruptHandler(void)
{
    /* 读取开关状态并处理 */
    SGMCD1020Q_ReadAndProcessSwitches(SGMCD_DEVICE_1);
    
    /* 读取故障状态（可选） */
    uint32_t faultStatus = SGMCD1020Q_ReadFaultStatus();
    if(faultStatus & 0x01000000) /* 检查故障标志 */
    {
        SGMCD1020Q_HandleFault(faultStatus);
    }
}
uint8_t SGMCD1020Q_Select_Num=0;
/* 主循环处理 */
void SGMCD1020Q_MainFunction(void)
{
  /* 检查INT_B引脚状态（轮询方式） */
  // if (Dio_ReadChannel(INT_B_PIN) == STD_LOW)
  // {
  //   SGMCD1020Q_InterruptHandler();
  // }
  if (SGMCD1020Q_Select_Num < 3)
  {
    SGMCD1020Q_Select_Num++;
  }
  else
  {
    SGMCD1020Q_Select_Num = 0;
  }

  if (SGMCD1020Q_Select_Num == 0)
  {
    /* 选择设备1 */
    SGMCD1020Q_SelectDevice(SGMCD_DEVICE_1);
    SGMCD1020Q_ReadAndProcessSwitches(SGMCD_DEVICE_1);
    SGMCD1020Q_DeselectAllDevices();
  }
  else if (SGMCD1020Q_Select_Num == 1)
  {
    /* 选择设备2 */
    SGMCD1020Q_SelectDevice(SGMCD_DEVICE_2);
    SGMCD1020Q_ReadAndProcessSwitches(SGMCD_DEVICE_2);
    SGMCD1020Q_DeselectAllDevices();
  }
  else if (SGMCD1020Q_Select_Num == 2)
  {
    /* 选择设备3 */
    SGMCD1020Q_SelectDevice(SGMCD_DEVICE_3);
    SGMCD1020Q_ReadAndProcessSwitches(SGMCD_DEVICE_3);
    SGMCD1020Q_DeselectAllDevices();
  }
  else
  {
    ;
  }
}

/* 进入低功耗模式 */
void SGMCD1020Q_GoToSleep(void)
{
    SGMCD1020Q_EnterLowPowerMode();
}

/* 唤醒设备 */
void SGMCD1020Q_WakeUp(void)
{
    /* 通过CS_B唤醒 */
    SGMCD1020Q_SelectDevice(currentDevice);
    SGMCD1020Q_ReadSwitchStatus(); /* 发送SPI命令唤醒 */
}