/*
 * @Author: mbw
 * @Date: 2024-10-23 17:14:16
 * @LastEditors: mbw && 1600520629@qq.com
 * @LastEditTime: 2025-01-15 10:36:40
 * @FilePath: \JT-DT-YD4N02A_RTT_MRS-NT26K\applications\main.c
 * @Descrt_thread_
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
#include "ch32v30x.h"
#include <rtthread.h>
#include <rthw.h>
#include "drivers/pin.h"
#include <board.h>
#include "drv_gpio.h"
#include "bsp_adc.h"
#include "bsp_beep.h"
#include "bsp_led.h"
#include "bsp_relay.h"
#include "bsp_emv.h"
#include "bsp_rtc.h"
#include "bsp_flash.h"
#include "bsp_hr.h"
#include "bsp_h308.h"
#include "bsp_nt26k.h"
#include "bsp_vin_detection.h"
#include "user_sys.h"

#define LOG_TAG "main"
#define LOG_LVL LOG_LVL_DBG
#include <ulog.h>

static rt_uint32_t event_flags[kMaxEventcnt] = {0};

struct rt_event alarm_event;

rt_bool_t is_event_initialized = RT_FALSE;  // 是否初始化完成

TsSysControl SysControl;

struct rt_timer work_cnt_timer;

rt_timer_t led_state_timer;

void Send_Laser_Alarm_Event (AlarmEvent event_type);

static void Set_Event (AlarmEvent event_type)
{
    if (event_type < kMaxEventcnt)
    {
        event_flags[event_type] = (1 << event_type);
    }
}

void SYS_EventInit (void)
{
    if (!is_event_initialized)
    {
        if (rt_event_init (&alarm_event, "alarm_event", RT_IPC_FLAG_PRIO) == RT_EOK)
        {

            for (AlarmEvent event = kPowerOnEvent; event < kMaxEventcnt; event++)
            {
                Set_Event (event);
            }
            is_event_initialized = RT_TRUE;
        }
        else
        {
            is_event_initialized = RT_FALSE;
            LOG_E ("Alarm event init failed!");
        }
    }
}

rt_uint32_t Get_Sys_Event_Flag (AlarmEvent event_type)
{
    if (is_event_initialized == RT_TRUE)
    {
        if (event_type < kMaxEventcnt)
        {
            return event_flags[event_type];
        }
    }
    return kMaxEventcnt;
}

void Send_Laser_Alarm_Event (AlarmEvent event_type)
{

    if (is_event_initialized == RT_TRUE)
    {
        if (SysControl.status == kPowerDownEvent)
        {
            LOG_D ("掉电模式下不处理其他事件");
        }
        else
        {
            LOG_I ("Send_Laser_Alarm_Event = %d", event_type);
            rt_event_send (&alarm_event, Get_Sys_Event_Flag (event_type));
        }
    }
    else
    {
        is_event_initialized = RT_FALSE;
        LOG_E ("Alarm event no init !");
    }
}

int _Self_Check_Mode (void)
{
    LED_STOP (r);
    LED_STOP (g);
    LED_STOP (y);
    rt_thread_mdelay (500);
    LED_CTRL (g, "500,2500", 1);
    LED_START (g);
    rt_thread_mdelay (1000);
    LED_CTRL (y, "500,2500", 1);
    LED_START (y);
    rt_thread_mdelay (1000);
    LED_CTRL (r, "500,2500", 1);
    LED_START (r);
    rt_thread_mdelay (1000);
    LED_STOP (r);
    LED_STOP (g);
    LED_STOP (y);
    BEEP_SELF_CHECK;
    return RT_EOK;
}

void Preheat_Sensor (rt_uint32_t timeout_counter)
{
// 定义超时时间，单位为毫秒
#define TIMEOUT_MS 15000

    timeout_counter += 10;  // 每次递归增加10毫秒

    if (H308.Data.checksum != 0)
    {
        BEEP_PREAT_OK;
        LED_STOP (r);
        LED_STOP (g);
        LED_STOP (y);
        LOG_D ("预热完成");
        BEEP_PREAT_OK;
        Send_Laser_Alarm_Event (kNormalDetectionEvents);
    }
    else if (IS_H308_EndOfLife())  // 如果寿命到期，预热完成后直接到寿命过期状态
    {
        LED_STOP (r);
        LED_STOP (g);
        LED_STOP (y);
        BEEP_PREAT_OK;
        Send_Laser_Alarm_Event (kSensorFailureEvent);
    }
    else if ((timeout_counter >= TIMEOUT_MS) && (H308.Data.checksum == 0))
    {
        LED_STOP (r);
        LED_STOP (g);
        LED_STOP (y);
        BEEP_PREAT_OK;
        LOG_D ("预热完成,传感器故障");
        Send_Laser_Alarm_Event (kFaultEvent);  // 传感器故障
    }
    else
    {
        rt_thread_mdelay (10);
        Preheat_Sensor (timeout_counter);
    }
}

void Work_Cnt_Timer_Callback (void *parameter)
{
    work_duration++;
    if (IS_H308_EndOfLife())  // 每天检测一下是否过期
    {
        if (Flash_GetNum_Records (kRecordSensoEndOfLife) == 0)
        {
            Flash_Write_Record (kRecordSensoEndOfLife);
        }
        Send_Laser_Alarm_Event (kSensorFailureEvent);
    }
}

int main (void)
{
#define WORK_TIMER_CNT (1000 * 60 * 60 * 24)

    rt_err_t result = RT_EINVAL;
    rt_uint32_t received_event;

    BSP_ADC_Init();
    BSP_VIN_Detection_Init();

    if (Get_VIN_VoltageInt1000x() > 10000)
    {
        SYS_EventInit();
        BSP_SYS_Init();

        work_duration = Flash_Get_WorkDuration();
        LOG_D ("工作天数：%d", work_duration);

        TuFlashProductTimeLimitFrame LimitTime;
        if (Flash_GetProductTimeLimit (&LimitTime, kExpirationTimeId) == READY)
        {
            // 计算出 到期时间对应的RTC秒数
            H308.expiration_seconds = DateTime2Seconds (LimitTime.Struct.year,
                                                        LimitTime.Struct.month, LimitTime.Struct.day, LimitTime.Struct.hour,
                                                        LimitTime.Struct.minute, LimitTime.Struct.second);
            LOG_D ("h308_expiration_time:%04d-%02d-%02d,%02d:%02d",
                   LimitTime.Struct.year, LimitTime.Struct.month, LimitTime.Struct.day,
                   LimitTime.Struct.hour, LimitTime.Struct.minute, LimitTime.Struct.second);
        }
        if (Flash_GetNum_Records (kRecordSensoEndOfLife) == 1)
        {
            LOG_W ("寿命已到期");
            H308.end_of_life = 1;
        }
        rt_timer_init (&work_cnt_timer,
                       "work_cnt_timer",
                       Work_Cnt_Timer_Callback,
                       RT_NULL,
                       WORK_TIMER_CNT,
                       RT_TIMER_FLAG_PERIODIC);
        rt_timer_start (&work_cnt_timer);
        // 检测上电/掉电复位标志
        if (RCC_GetFlagStatus (RCC_FLAG_PORRST) != RESET)  // TODO:这块超级电容会造成掉电重启，并且标志是上电复位，只能通过其超级电容造成复位时事件创建失败进行判断，不治本
        {
            RCC_ClearFlag();
            Send_Laser_Alarm_Event (kPowerOnEvent);
        }
        else
        {
            Send_Laser_Alarm_Event (kPreheatingEvent);  // 这一句的作用是设备不是掉电重启的情况，直接进入预热模式
        }
    }
    else
    {
        LOG_D ("欠压复位\r\n");
        RCC_ClearFlag();
        NVIC_SystemReset();  // 直接重启系统
    }
    while (1)
    {
        if (is_event_initialized)
        {
            result = rt_event_recv (&alarm_event,
                                    Get_Sys_Event_Flag (kPowerOnEvent) |               // 上电
                                        Get_Sys_Event_Flag (kPowerDownEvent) |         // 掉电
                                        Get_Sys_Event_Flag (kPreheatingEvent) |        // 预热
                                        Get_Sys_Event_Flag (kNormalDetectionEvents) |  // 正常检测
                                        Get_Sys_Event_Flag (kAlarmExceptionEvent) |    // 报警异常
                                        Get_Sys_Event_Flag (kAlarmEvent) |             // 报警
                                        Get_Sys_Event_Flag (kAlarmRcyEvent) |          // 报警恢复
                                        Get_Sys_Event_Flag (kSelfCheckEvent) |         // 自检
                                        Get_Sys_Event_Flag (kFaultEvent) |             // 故障模式
                                        Get_Sys_Event_Flag (kFaultRcyEvent) |          // 故障恢复
                                        Get_Sys_Event_Flag (KMuteEvent) |              // 消音
                                        Get_Sys_Event_Flag (kSensorFailureEvent),      // 传感器寿命到期
                                    RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR,
                                    RT_WAITING_FOREVER, &received_event);
            if (result == RT_EOK)
            {
                if (is_event_initialized == RT_TRUE)
                {
                    if (received_event & Get_Sys_Event_Flag (kPowerOnEvent))  // 上电
                    {
                        LOG_D ("上电模式");
                        LOG_D ("is_event_initialized :%d", is_event_initialized);
                        SysControl.status = kPowerOnEvent;

                        Flash_Write_Record (kRecordPowerOn);
                        Send_Laser_Alarm_Event (kPreheatingEvent);
                    }
                    else if (received_event & Get_Sys_Event_Flag (kPreheatingEvent))  // 预热
                    {
                        LOG_D ("预热模式");

                        SysControl.last_status = SysControl.status;
                        SysControl.status = kPreheatingEvent;

                        LED_G_PREAT;
                        BEEP_PREAT_OK;
                        Send_Laser_Alarm_Event (kNormalDetectionEvents);
                    }
                    else if (received_event & Get_Sys_Event_Flag (kNormalDetectionEvents))  // 正常检测
                    {
                        SysControl.last_status = SysControl.status;
                        SysControl.status = kNormalDetectionEvents;

                        if (SysControl.last_status == kSelfCheckEvent)
                        {
                            rt_thread_mdelay (5000);
                            LOG_I ("自检电磁阀动作");
                            EMV_CLOSE_VALVE;
                            LOG_I ("自检风机动作");
                            relay_state_flag = 1;
                            rt_thread_mdelay (500);
                            relay_state_flag = 0;
                        }
                        if (H308.detection_flag == kH308Alarm)
                        {
                            LED_G_NORMAL;
                            rt_thread_mdelay (500);
                            Send_Laser_Alarm_Event (kAlarmEvent);
                        }
                        else if (H308.detection_flag == kH308Fault)
                        {
                            LED_G_NORMAL;
                            rt_thread_mdelay (500);
                            Send_Laser_Alarm_Event (kFaultEvent);
                        }
                        else
                        {
                            LOG_D ("正常检测模式");
                        }
                    }
                    else if (received_event & Get_Sys_Event_Flag (kAlarmExceptionEvent))  // 浓度异常
                    {
                        LOG_D ("浓度异常模式");

                        SysControl.last_status = SysControl.status;
                        SysControl.status = kAlarmExceptionEvent;

                        LED_R_ALARM;
                        LOG_D ("LED_R_ALARM");
                    }
                    else if (received_event & Get_Sys_Event_Flag (kAlarmEvent))  // 报警
                    {
                        LOG_D ("报警模式");

                        SysControl.last_status = SysControl.status;
                        SysControl.status = kAlarmEvent;

                        Flash_Write_Record (kRecordAlarm);  // 写入flash报警信息
                        EMV_CLOSE_VALVE;
                        relay_state_flag = 1;
                        LED_R_ALARM;
                        BEEP_ALARM;

#if (IOT_MODULE_SWITCH == 1)
                        Nt26k_Send_Event (kNt26kAlarmEvent);
#endif
                    }
                    else if (received_event & Get_Sys_Event_Flag (kAlarmRcyEvent))  // 报警恢复
                    {
                        LOG_D ("报警恢复模式");

                        SysControl.last_status = SysControl.status;
                        SysControl.status = kAlarmRcyEvent;

                        Flash_Write_Record (kRecordAlarmRcy);

                        relay_state_flag = 0;
                        BEEP_STOP;
#if (IOT_MODULE_SWITCH == 1)
                        Nt26k_Send_Event (kNt26kAlarmRcyEvent);
#endif

                        Send_Laser_Alarm_Event (kNormalDetectionEvents);
                    }
                    else if (received_event & Get_Sys_Event_Flag (kFaultEvent))  // 故障
                    {
                        LOG_D ("故障模式");

                        if (Flash_GetNum_Records (kRecordSensoEndOfLife) != 1)  // 当设备失效时，只上报设备失效的故障，其他故障不上报
                        {
                            SysControl.last_status = SysControl.status;
                            SysControl.status = kFaultEvent;

                            Flash_Write_Record (kRecordFault);

                            LED_Y_FAULT;
#if (IOT_MODULE_SWITCH == 1)
                            Nt26k_Send_Event (kNt26kFaultEvent);
#endif
                        }
                        else
                        {
                            Send_Laser_Alarm_Event (kSensorFailureEvent);
                        }
                    }
                    else if (received_event & Get_Sys_Event_Flag (kFaultRcyEvent))  // 故障恢复
                    {
                        LOG_D ("故障恢复模式");

                        SysControl.last_status = SysControl.status;
                        SysControl.status = kFaultRcyEvent;

                        Flash_Write_Record (kRecordFaultRcy);

                        Send_Laser_Alarm_Event (kNormalDetectionEvents);
#if (IOT_MODULE_SWITCH == 1)
                        Nt26k_Send_Event (kNt26kFaultRcyEvent);
#endif
                    }
                    else if (received_event & Get_Sys_Event_Flag (KMuteEvent))  // 消音
                    {
                        LOG_D ("消音模式");
                        SysControl.last_status = SysControl.status;
                        SysControl.status = KMuteEvent;
                        BEEP_STOP;
#if (IOT_MODULE_SWITCH == 1)
                        Nt26k_Send_Event (kNt26kSilenceEvent);
#endif
                    }
                    else if (received_event & Get_Sys_Event_Flag (kPowerDownEvent))  // 掉电
                    {
                        LOG_D ("掉电模式");
                        H308_PWR_OFF;
                        SysControl.last_status = SysControl.status;
                        SysControl.status = kPowerDownEvent;

                        // 写入掉电记录
                        Flash_Write_Record (kRecordPowerDown);

                        Flash_Set_WorkDuration (work_duration);  // 写入工作时长
#if (IOT_MODULE_SWITCH == 1)
                        Nt26k_Send_Event (kNt26kPowerDownEvent);
#endif
                        // 等待20s,要是还没断电就重启
                        for (uint8_t i = 0; i < 20; i++)
                        {
                            rt_thread_mdelay (1000);
                            LOG_D (" %d s", i);
                        }
                        NVIC_SystemReset();                                          // 直接重启系统
                    }
                    else if (received_event & Get_Sys_Event_Flag (kSelfCheckEvent))  // 自检
                    {
                        LOG_D ("自检模式");

                        SysControl.last_status = SysControl.status;
                        SysControl.status = kSelfCheckEvent;

                        _Self_Check_Mode();

#if (IOT_MODULE_SWITCH == 1)
                        Nt26k_Send_Event (kNt26kSelfCheckEvent);
#endif
                        Send_Laser_Alarm_Event (kNormalDetectionEvents);                 // 这里先返回检测模式，然后当事件触发时进入事件模式
                    }
                    else if (received_event & Get_Sys_Event_Flag (kSensorFailureEvent))  // 失效
                    {
                        SysControl.last_status = SysControl.status;
                        SysControl.status = kSensorFailureEvent;
                        LOG_D ("传感器失效模式");

                        if (Flash_GetNum_Records (kRecordSensoEndOfLife) == 0)
                        {
                            Flash_Write_Record (kRecordSensoEndOfLife);
                        }
                        LED_Y_END_OF_LIFE;
                    }
                }
            }
        }
        else
        {
            rt_thread_mdelay (1000);
        }
    }
}

#ifdef TEST_ENABLE
static void SYS_Set_RtcProductTime (int argc, char **argv)
{
    if (argc == 7)
    {
        int year = atoi (argv[1]);
        int mon = atoi (argv[2]);
        int day = atoi (argv[3]);
        int hour = atoi (argv[4]);
        int min = atoi (argv[5]);
        int second = atoi (argv[6]);
        RTC_SetTime (2000 + year, mon, day, hour, min, second);
        RTC_GetTime();
        LOG_D ("RTC: %4d-%02d-%02d, %02d:%02d:%02d", RtcDateTime.year, RtcDateTime.month, RtcDateTime.day,
               RtcDateTime.hour, RtcDateTime.minute, RtcDateTime.second);

        // 设置出厂时间
        Flash_SetProductTimeLimit (2000 + year, mon, day, hour, min, second, kFactoryTimeId);
        // 到期时间自动 + 5年30天
        Set_ExpirationTime (MAX_EXPIRATION_DAYS);
    }
    else
    {
        LOG_E ("SYS_Set_RtcProductTime      --use _cmd_ [2000 + y] [m] [d] [h] [m] [s]");
    }
}

MSH_CMD_EXPORT (SYS_Set_RtcProductTime, "SYS_Set_RtcProductTime");

static void SYS_SW_Version (void)
{
    rt_kprintf ("JT-DT-YD4N02A Software version: V%02X\r\n", (uint8_t)Flash_Get_SysCfg (kSwVerId));
}

MSH_CMD_EXPORT (SYS_SW_Version, "软件版本");

#endif
