#include "electrode.h"

// 除磷控制相关变量
uint8_t phosphorus_running = 0;    // 除磷运行状态
uint8_t polarity_state = 0;        // 极性状态：0-正常，1-反转
uint32_t phosphorus_timer = 0;     // 运行时间计数器（分钟）
uint32_t PHOSPHORUS_RUN_TIME = 20;    // 默认运行时间20分钟
uint32_t PHOSPHORUS_STOP_TIME = 40;   // 默认停止时间40分钟

// 除磷极性控制函数
void Control_Phosphorus_Polarity(void)
{
    if(polarity_state)
    {
        // 反转极性
        Control_Plate1(1);  // 极板1为正极
        Control_Plate2(0);  // 极板2为负极
    }
    else
    {
        // 正常极性
        Control_Plate1(0);  // 极板1为负极
        Control_Plate2(1);  // 极板2为正极
    }
}

// 除磷时间更新函数
void Phosphorus_Timer_Update(void)
{
    uint8_t pump_status = Read_WaterPump_Status();
    
    // 水泵启动时，启动除磷
    if(pump_status && !phosphorus_running)
    {
        phosphorus_running = 1;
        phosphorus_timer = 0;
        // 切换极性并启动
        polarity_state = !polarity_state;
        Control_Phosphorus_Polarity();
    }
    
    // 除磷运行计时
    if(phosphorus_running)
    {
        phosphorus_timer++;
        // 判断是否达到运行时间
        if(phosphorus_timer >= PHOSPHORUS_RUN_TIME)
        {
            Control_Phosphorus(0);  // 停止除磷
            phosphorus_running = 0;
            phosphorus_timer = 0;
        }
    }
}

// 设置运行时间
void Set_Phosphorus_Runtime(uint32_t minutes)
{
    PHOSPHORUS_RUN_TIME = minutes;
   // printf("设置除磷运行时间：%d分钟\n", PHOSPHORUS_RUN_TIME);
}

// 设置停止时间
void Set_Phosphorus_StopTime(uint32_t minutes)
{
    PHOSPHORUS_STOP_TIME = minutes;
   // printf("设置除磷停止时间：%d分钟\n", PHOSPHORUS_STOP_TIME);
}

// 定义状态常量，使代码更易读
#define DEPHOSPHO_ENABLED    1
#define DEPHOSPHO_DISABLED   0

uint8_t Dephosphorization_state = DEPHOSPHO_DISABLED;  // 初始化为禁用状态

uint8_t electrode_Init(uint8_t state)
{
    if (state)
    {
        Phosphorus_Timer_Update();
        Dephosphorization_state = DEPHOSPHO_ENABLED;
        return DEPHOSPHO_ENABLED;
    }
    else
    {
        Control_Phosphorus(0);
        Dephosphorization_state = DEPHOSPHO_DISABLED;
        return DEPHOSPHO_DISABLED;
    }
}

