/*
 * bsp_adc.c
 *
 *  Created on: 2024年11月29日
 *      Author: 123
 */
#include "bsp_adc.h"
#include "CONFIG.h"
#include "log.h"

#include "bsp_motor.h"
#include "bsp_led.h"
#include "bsp_ml307r.h"
#include <string.h>

signed short RoughCalib_Value = 0; // ADC粗调偏差值
static tmosTaskID vbat_task_id = INVALID_TASK_ID;
static uint8_t vbat_low_flag = 0;  // 电压过低标志

void VBAT_ADC_Init(void)
{
    // 功能引脚数字输入禁用寄存器
    R32_PIN_IN_DIS |= (1U << 4); // 禁用数字功能
    //ADC初始化
    /* 单通道采样：选择adc通道0做采样，对应 PA4引脚， 带数据校准功能 */
   GPIOA_ModeCfg(GPIO_Pin_4, GPIO_ModeIN_Floating);
   // 采样率最高8M
   ADC_ExtSingleChSampInit(SampleFreq_8_or_4, ADC_PGA_1_2);

   RoughCalib_Value = ADC_DataCalib_Rough(); // 用于计算ADC内部偏差，记录到全局变量 RoughCalib_Value中
   logDebug("RoughCalib_Value =%d \n", RoughCalib_Value);

   ADC_ChannelCfg(0);
   ADC_ExcutSingleConver();//时间足够时建议再次转换并丢弃首次ADC数据
   DelayMs(10);
}

void ADC_GPIO_Init(void)
{
    GPIOA_ModeCfg(GPIO_Pin_4, GPIO_ModeIN_Floating);
    // 确保ADC电源已启用
    R8_ADC_CFG |= RB_ADC_POWER_ON;
}


// void Send_Low_Battery_Message(float vbat)
// {
//     char json_buffer[300];
//     char time_str[20] = {0};
//     snprintf(json_buffer, sizeof(json_buffer), 
//             "{"
//             "\"device\":{"
//                 "\"id\":\"SCV001\","
//                 "\"type\":\"SelfClosingValve\","
//                 "\"time\":\"%s\""
//             "},"
//             "\"status\":\"closed\","
//             "\"fault\":{"
//                 "\"lowBattery\":true,"
//                 "\"commError\":false,"
//                 "\"code\":1001"
//             "},"
//             "\"monitor\":{"
//                 "\"pressure\":0.8,"
//                 "\"voltage\":%.2f,"
//                 "\"lowVoltage\":true"
//             "},"
//             "\"network\":{"
//                 "\"sinr\":15.2,"
//                 "\"rsrp\":-95.5,"
//                 "\"signal\":4"
//             "},"
//             "\"standards\":{"
//                 "\"iotId\":\"IoT-SCV-12345\""
//             "}"
//             "}", 
//             time_str, vbat);
//     BSP_Module_Emergency_Send((uint8_t*)json_buffer, strlen(json_buffer));
//     logDebug("Send low battery message: %s\n", json_buffer);
// }

// // 处理电池电压低事件
// void Handle_Low_Battery(float vbat)
// {
//     if (!vbat_low_flag) {
//         VALVE_CLOSE();
//         LED_VALVE_CLOSE;
//         Send_Low_Battery_Message(vbat);
//         vbat_low_flag = 1;
//         logDebug("Voltage is too low (%.2fV),Close valve\n", vbat);
//     }
//         LED_VBAT_OPEN;
//         DelayMs(100);
// }

uint16_t VBAT_ProcessEvent(uint8_t task_id, uint16_t events)
{
    if (events & VBAT_EVT_START)
    {
        uint16_t adc_vbat = 0;
        float vbat = 0;
        float IN_VBAT = 0;
        // ADC_GPIO_Init();
        // ADC_ChannelCfg(0);
        // adc_vbat = ADC_ExcutSingleConver() + RoughCalib_Value;
        // logDebug("adc_vbat =%d \n", adc_vbat);
        // vbat = (adc_vbat/1024.0-1)*1.05;
        // logDebug("vbat =%f \n", vbat);
        // tmos_start_task(vbat_task_id, VBAT_EVT_START, MS1_TO_SYSTEM_TIME(1000*60));  //1000*60
        uint8_t retry_count = 0;
        uint8_t success = 0;
        int32_t vbat_mV = 0;
        int32_t IN_VBAT_mV = 0;
        
        while (retry_count < 3 && !success) {
            ADC_GPIO_Init();
            ADC_ChannelCfg(0);
            adc_vbat = ADC_ExcutSingleConver() + RoughCalib_Value;
            if (adc_vbat > 100 && adc_vbat < 6000) {
                // vbat = (adc_vbat/1024.0-1)*1.05;
                // IN_VBAT = vbat * 2;
                // logDebug("adc_vbat = %d, IN_VBAT = %.2f V\n", adc_vbat, IN_VBAT);
                // 使用整数计算代替浮点计算 (adc_vbat/1024.0-1)*1.05 转换为定点运算
                // 公式: ((adc_vbat * 1000) / 1024 - 1000) * 105 / 100
                vbat_mV = ((adc_vbat * 1000) / 1024 - 1000) * 105 / 100;
                IN_VBAT_mV = vbat_mV * 2;
                logDebug("adc_vbat = %d, IN_VBAT = %d.%02d V\n", adc_vbat, IN_VBAT_mV/1000, (IN_VBAT_mV%1000)/10);
                success = 1;
            } else {
                retry_count++;
                DelayMs(10);
                logDebug("ADC error %d/3\n", retry_count);
            }
        }
        
        if (success) {
            if (IN_VBAT < VBAT_LOW_THRESHOLD) {
                // Handle_Low_Battery(IN_VBAT);
                IotFlag_t.Low_Voltage_flag = 1;
            } else if (vbat_low_flag) {
                vbat_low_flag = 0;
                LED_VBAT_CLOSE;
                logDebug("Voltage is normal (%.2fV)\n", IN_VBAT);
            }
        } else {
            logDebug("Voltage measurement failed\n");
            if (!vbat_low_flag) {
                IN_VBAT = 1.0f; 
                // Handle_Low_Battery(IN_VBAT);
                IotFlag_t.Low_Voltage_flag = 1;
            }
        }

        uint32_t next_check_time = vbat_low_flag ? 
                                   MS1_TO_SYSTEM_TIME(1000*1) :  //1000*30 电压低时30秒检测一次
                                   MS1_TO_SYSTEM_TIME(1000*6);   //1000*60 正常时1分钟检测一次
        
        tmos_start_task(vbat_task_id, VBAT_EVT_START, next_check_time);
        return (events ^ VBAT_EVT_START);
    }
    return 0;
}
void BSP_VBAT_Init(void)
{
    VBAT_ADC_Init();
    vbat_task_id = TMOS_ProcessEventRegister(VBAT_ProcessEvent);
    tmos_set_event(vbat_task_id, VBAT_EVT_START);
}
