
#include "NVS_Test.h"

uint32_t BenCiXieRuNum = 0U;
uint32_t TotalExecutionNum = 0U;
uint32_t LastNum = 0U;
uint32_t BeforeLastNum = 0U;
uint32_t ReceivedValue = 0U;
uint8_t RenWuDelay = 0U;
uint8_t errNum = 0U;
uint32_t TurnOffPowerCount = 0U;
uint32_t TurnOffPowerCountHistory = 0U;
uint32_t JieShouDaoValue = 0U;
static void NVS_Test_BenCiXieRuNum(void);

void NVS_Test_Init(void)
{
    BenCiXieRuNum = 0U;
    TotalExecutionNum = 0U;
    LastNum = 0xFFFFFFFFU;
    BeforeLastNum = 0xFFFFFFFFU;
    ReceivedValue = 0U;    
    RenWuDelay = 0U;
    TurnOffPowerCount = 0U;
    TurnOffPowerCountHistory = 0U;
    errNum = 0U;
    JieShouDaoValue = 0U;
    RS485_TX_finish = 2U;  /*发出的RS485信号标志位，初始化为2，不发不收*/
}

void NVS_Test_Service(void)
{
    

    if(RS485_TX_finish == 2U)
    {
        if (errNum == 0U)
        {
            BeforeLastNum = LastNum;
            LastNum = BenCiXieRuNum;
            NVS_Test_BenCiXieRuNum();
            RS485_TX_finish = 0U;/*上电后满足等待时间后，开始发第一帧信号*/
        } 
    }
    else if(RS485_TX_finish == 0U)
    {
        ;/*执行发的功能*/
    }
    else
    {   
        if(RS485_TX_finish == 3U)
        {
            if (TotalExecutionNum != 0U)
            {
                if(JieShouDaoValue != LastNum)
                {
                    if ((JieShouDaoValue != BeforeLastNum) && (TurnOffPowerCount != TurnOffPowerCountHistory))
                    {
                        errNum ++;
                    }
                    else if (TurnOffPowerCount == TurnOffPowerCountHistory)
                    {
                        errNum ++;
                    }
                    if (JieShouDaoValue != BeforeLastNum)
                    {
                        errNum ++;
                    }
                }
            }

            if (TurnOffPowerCount != TurnOffPowerCountHistory)
            {
                TurnOffPowerCountHistory = TurnOffPowerCount; /*断电后重启第一次对比标记，只有此时才执行对比上上次的值，之后不能对比*/
            }

            if (errNum == 0U)
            {

                BeforeLastNum = LastNum;
                LastNum = BenCiXieRuNum;
                NVS_Test_BenCiXieRuNum();
                TotalExecutionNum ++;
                RS485_TX_finish = 0U;/*执行读的功能，对比完没问题再重新外发*/
            }
            else
            {
                RS485_TX_finish = 0xFFU;/*不再执行任何收发操作*/
            }
        }
        else
        {
            ;/*等待仪表回复*/
        }
    }
}

void NVS_Test_DelayCount(void)
{
    RenWuDelay ++ ;
}

static void NVS_Test_BenCiXieRuNum(void)
{
    uint32_t hahaha = (((BenCiXieRuNum * 7U) / 3U) + 257U);

    if (hahaha < 0xFFFFFFFF)
    {
        BenCiXieRuNum = hahaha;
    }
    else
    {
        BenCiXieRuNum = 1u;
    }
    
}


