#include "COM_CAN.h"
#include "TYW_stdint.h"
#include "CANFD_CH0_CANFD_Communication_Matrix.h"
#include "RTE_CAN.h"
#include "Signal_Remap.h"
#include "RTE_WDT.h"
#include <string.h>
#include <stdio.h>


uint32_t Check_Infordata_CRC_32(uint8_t p [], uint32_t len ,uint32_t Crc);



#pragma alignvar(8)
uint32_t pRXBuff[CAN_RX_MSG_Block * CANFD_CH0_ID_TOTAL_MAX];
#pragma alignvar(8)
static uint32_t pTXBuff[CAN_TX_MSG_Block * 100];
#pragma alignvar(8)
static st_CANFD_SendAttribute Load_Attr[100] = {0};
st_CANFD_MsgBuff Load_AttrBuff[100] = {0};

typedef struct
{
    uint32_t Subaddr;
    uint32_t SubStep;
} st_AutoCheckAttr;
typedef union _word_split
{
    uint32_t word;
    uint8_t  byte [ 4 ];
} WORD_SPLIT_u;
typedef struct
{
    uint32_t     crc_result;        //上位机计算的CRC数值
    uint32_t     crc_Len;           //CRC计算的长度
    WORD_SPLIT_u total_msg_begin;   //报文列表首地址
    WORD_SPLIT_u total_msg;         //报文列表中包含多少条报文
    WORD_SPLIT_u total_step_begin;  //步骤列表首地址
    WORD_SPLIT_u total_step;        //共执行多少步骤

} st_CheckMessage;

typedef struct
{
    uint16_t u16ID;                 //CAN列表 报文ID
    uint16_t u16Cycle;              //CAN列表 周期单位um
    uint8_t  u8COM;                 //CAN列表
    uint8_t  u8Len;                 //CAN列表
    uint8_t  u8Mode;                //CAN列表
    uint8_t  u8MsgSTD_EXT;          //CAN列表

} st_CAN_list;

typedef struct
{
    uint32_t u32Subaddr_CAN;       //CAN数据首地址
    uint32_t u32SubStep_CAN;       //CAN操作数
    uint32_t u32Subaddr_IO;        //IO数据首地址     
    uint32_t u32SubStep_IO;        //IO操作数
    uint32_t u32Subaddr_PWM;       //PWM数据首地址
    uint32_t u32SubStep_PWM;       //PWM操作数
    uint32_t u32res1;              //保留占位
    uint32_t u32res2;              //保留占位

} st_step_list;

typedef struct
{
    uint32_t nuber;                 //CAN   ID索引
    uint8_t  msg[64];               //CAN   报文数据

} st_CAN;

typedef struct
{
    uint8_t  pin;                   //IO通道
    uint8_t  level;                 //IO电平
    uint8_t  IN_OUT;                //IO方向
    uint8_t  res1;                  //保留占位
} st_IO;

typedef struct
{
    uint8_t  pin;                   //PWM通道
    uint8_t  IN_OUT;                //PWM方向
    uint16_t duty;                  //PWM占空比
    uint16_t freq;                  //PWM频率
    uint8_t  res1;                  //保留占位
    uint8_t  res2;                  //保留占位
} st_PWM;


st_CAN_list *Total_Msg_addr;//CAN索引列表，实际使用时 Total_Msg_addr[索引ID-1].xxx;

st_step_list *step_list;         //步骤索引列表，实际使用时 step[步骤ID-1].xxxx:
//step_list[i].u32Subaddr_CAN    //第 i 步骤CAN数据首地址
//step_list[i].u32SubStep_CAN    //第 i 步骤CAN操作数
//step_list[i].u32Subaddr_IO     //第 i 步骤IO数据首地址     
//step_list[i].u32SubStep_IO     //第 i 步骤IO操作数
//step_list[i].u32Subaddr_PWM    //第 i 步骤PWM数据首地址
//step_list[i].u32SubStep_PWM    //第 i 步骤PWM操作数



st_CheckMessage *PreLoad_Info;
#define FIX_LOAD_ADDRESS 0x50000


st_AutoCheckAttr Sub_Attr [ 200 ] = {0};
uint32_t         g_Verify_Result;
#define MAKE_U32(high, mid1, mid0, low) ((( uint8_t )(low)) | ((( uint8_t )(mid0)) << 8) | ((( uint8_t )(mid1)) << 16) | ((( uint8_t )(high)) << 24))
void  Execute_Specify_Step(uint32_t step);
float double0;
float double1;
float double2;
float double3;
void  COM_CAN_Init(void)
{
    /*CAN APP BUFFER INIT*/

    memset(pRXBuff, 0, sizeof(pRXBuff));
    memset(pTXBuff, 0, sizeof(pTXBuff));
    memset(Load_AttrBuff, 0, sizeof(Load_AttrBuff));
    memset(Load_Attr, 0, sizeof(Load_Attr));
    g_Verify_Result = 0;
    Msg_Load_Init( );
    
    CANFD_CH0_CanFDMsgOp.CAN_MSG_Analysis = (st_CANFDMsgStruct *)pRXBuff;
    CANFD_CH0_CanFDMsgTxOp.CanMsg = (st_CANFD_SendOperation *)pTXBuff;

    CanFD_RX_BuffInit(&CANFD_CH0_CanFDMsgOp, CANFD_CH0_CAN_MSG_CONST_ARRAY, CANFD_CH0_ID_TOTAL_MAX);
    if ( g_Verify_Result == 1U )
    {
        CanFD_TX_BuffInit(&CANFD_CH0_CanFDMsgTxOp, Load_Attr, PreLoad_Info->total_msg.word, Can_Write_FIFO);
    }
    CANFD_RX_SetEnable(&CANFD_CH0_CanFDMsgOp, 0x00);
    if ( g_Verify_Result == 1U )
    {
        CANFD_TX_SetEnable(&CANFD_CH0_CanFDMsgTxOp, 0x55);
        Execute_Specify_Step(0);
    }
}

void COM_RX_Process(void)
{
    CanFDMSg_XMS_Analysis(&CANFD_CH0_CanFDMsgOp, 5u);
}

void COM_TX_Process(void)
{
    WDT_Clear();
    CanFD_Write_Fun(&CANFD_CH0_CanFDMsgTxOp, 2u);
}

// void Msg_Load_Init(void)
// {
//     uint32_t  i = 0u;
//     uint32_t *addr;
//     uint32_t  Total_Msg;
//     uint32_t  Total_Msg_addr;
//     PreLoad_Info    = ( uint32_t    *)FIX_LOAD_ADDRESS;
//     g_Verify_Result = Check_Infordata_CRC_32(&PreLoad_Info->total_msg, 28);
//     if ( g_Verify_Result == 1U )
//     {
//         Total_Msg      = PreLoad_Info->total_msg.word;
//         Total_Msg_addr = PreLoad_Info->total_msg_begin.word;
//         addr           = ( uint32_t           *)Total_Msg_addr;
//         for ( i = 0; i < Total_Msg; i++ )
//         {
//             Load_Attr [ i ].u32MsgID    = (*(addr + i * 4));        // convert_0;
//             Load_Attr [ i ].u32MsgCycle = (*(addr + 1 + i * 4));    // convert_1;
//             Load_Attr [ i ].u8MsgPro    = (*(addr + 2 + i * 4));    // convert_2;//通道
//             Load_Attr [ i ].u8MsgDLC    = (*(addr + 3 + i * 4));    // convert_3;
//         }

//         addr = ( uint32_t * )PreLoad_Info->sub_step_addr.word;
//         for ( i = 0; i < PreLoad_Info->total_step.word; i++ )
//         {
//             Sub_Attr [ i ].Subaddr = (*(addr + 0 + i * 2));
//             Sub_Attr [ i ].SubStep = (*(addr + 1 + i * 2));
//         }
//     }
// }

void Msg_Load_Init(void)
{
    uint32_t  i = 0u;
    uint32_t  j = 0u;
    uint32_t  k = 0u;
    uint32_t *addr;

    st_CAN *can_list;
    st_IO  *io_list;
    st_PWM *pwm_list;



    PreLoad_Info    = ( uint32_t    *)FIX_LOAD_ADDRESS;
    g_Verify_Result = Check_Infordata_CRC_32(&PreLoad_Info->total_msg_begin, PreLoad_Info->crc_Len ,PreLoad_Info->crc_result);
    if ( g_Verify_Result == 1U )
    {
        Total_Msg_addr = (st_CAN_list*)PreLoad_Info->total_msg_begin.word;
        //addr           = ( uint32_t           *)Total_Msg_addr;
        for ( i = 0; i < PreLoad_Info->total_msg.word; i++ )
        {
            Load_Attr [ i ].u32MsgID    = Total_Msg_addr[i].u16ID; //(*(addr + i * 4));        // convert_0;
            Load_Attr [ i ].u32MsgCycle = Total_Msg_addr[i].u16Cycle; //(*(addr + 1 + i * 4));    // convert_1;
            Load_Attr [ i ].u8MsgPro    = Total_Msg_addr[i].u8COM; //(*(addr + 2 + i * 4));    // convert_2;
            Load_Attr [ i ].u8MsgDLC    = Total_Msg_addr[i].u8Len; //(*(addr + 3 + i * 4));    // convert_3;

                //Total_Msg_addr[CAN_addr[i].nuber].u16ID;       
                //Total_Msg_addr[CAN_addr[i].nuber].u16Cycle;    
                //Total_Msg_addr[CAN_addr[i].nuber].u8COM;       
                //Total_Msg_addr[CAN_addr[i].nuber].u8Len;       


                // Total_Msg_addr[i].u8Mode;      
                // Total_Msg_addr[i].u8MsgSTD_EXT;




            //printf("%04x %04X %02X %02X %02X %02X \r\n",Total_Msg_addr[i].u16ID
            //                                        ,Total_Msg_addr[i].u16Cycle
            //                                        ,Total_Msg_addr[i].u8COM
            //                                        ,Total_Msg_addr[i].u8Len
            //                                        ,Total_Msg_addr[i].u8Mode
            //                                        ,Total_Msg_addr[i].u8MsgSTD_EXT);


        }

        //printf("\r\n");

        step_list = (st_step_list*)PreLoad_Info->total_step_begin.word;


        //for ( i = 0; i < PreLoad_Info->total_step.word; i++ )
        //{
        //    printf("%08x %08X %08X %08X %08X %08X \r\n" ,step_list[i].u32Subaddr_CAN
        //                                                ,step_list[i].u32SubStep_CAN
        //                                                ,step_list[i].u32Subaddr_IO
        //                                                ,step_list[i].u32SubStep_IO
        //                                                ,step_list[i].u32Subaddr_PWM
        //                                                ,step_list[i].u32SubStep_PWM);
        //}
        
        //for ( k = 0; k < PreLoad_Info->total_step.word; k++ )
        //{
        //    can_list = (st_CAN *)step_list[k].u32Subaddr_CAN;
        //    io_list  = (st_IO  *)step_list[k].u32Subaddr_IO;
        //    pwm_list = (st_PWM *)step_list[k].u32Subaddr_PWM;

        //    printf("\r\nNo.%d :\r\n CAN:\r\n",(k+1));
        //    for ( i = 0; i < step_list[k].u32SubStep_CAN; i++ )
        //    {
        //        printf("%08x :\r\n",can_list[i].nuber);

        //        for ( j = 0; j < 64; j++ )
        //        {
        //            printf("%02x",can_list[i].msg[j]);
        //        }
        //        printf("\r\n");

        //    }

        //    printf("\r\nIO:\r\n");
        //    for ( i = 0; i < step_list[k].u32SubStep_IO; i++ )
        //    {
        //        printf("%02X %02X %02X  \r\n",io_list[i].pin
        //                                    ,io_list[i].level
        //                                    ,io_list[i].IN_OUT);
        //    }
        //    
        //    printf("\r\nPWM:\r\n");
        //    for ( i = 0; i < step_list[k].u32SubStep_PWM; i++ )
        //    {
        //        printf("%02x %02x %04x %04x\r\n",pwm_list[i].pin
        //                                        ,pwm_list[i].IN_OUT
        //                                        ,pwm_list[i].duty
        //                                        ,pwm_list[i].freq);
        //    }
        //}








    }
}



void Execute_Specify_Step(uint32_t step)
{

    uint32_t  i = 0u;
    uint32_t  j = 0u;
    static st_PWM *PWM_addr;
    static st_IO *IO_addr;
    static st_CAN *CAN_addr;
    uint32_t  buff_idx;
    uint32_t  buff_id;
    uint8_t  *pbuff;

    if ( g_Verify_Result == 1U )
    {
        if ( step < PreLoad_Info->total_step.word )
        {

            CAN_addr = (st_CAN *)step_list[step].u32Subaddr_CAN;
            for ( i = 0; i < step_list[step].u32SubStep_CAN; i++ )
            {
                // pbuff = ( void    *)(CAN_addr[i].msg);
                
                for ( j = 0; j < /*CAN0_FD_DLC_ChangeTo_Register(Load_Attr [ i ].u8MsgDLC)*/64; j++ )
                {
                    Load_AttrBuff [ CAN_addr[ i ].nuber ].sig.Msg [ j ] = CAN_addr[i].msg[ j ];
                }
                
                    CanFD_Msg_TX_SetMsgBuffer(&CANFD_CH0_CanFDMsgTxOp, CAN_addr[ i ].nuber , \
                                              CAN0_FD_DLC_ChangeTo_Register(Load_Attr [ i ].u8MsgDLC),\
                                              Load_AttrBuff [ CAN_addr[ i ].nuber ].sig.Msg);
            }

            IO_addr = (st_IO *)step_list[step].u32Subaddr_IO;
            for ( i = 0; i < step_list[step].u32SubStep_IO; i++ )//step是步数,u32SubStep_IO是每个步数的
            {   //pin是每个IO的pin,level是每个IO的level,  u32SubStep_IO等同于IO_addr[i]里的i;
                F1KM_16843_Port_IO_P [IO_addr[i].pin].Set_Output(IO_addr[i].level);
            } 

            PWM_addr = (st_PWM *)step_list[step].u32Subaddr_PWM;
            for ( i = 0; i < step_list[step].u32SubStep_PWM; i++ )
            {
                F1KM_16843_Port_PWM_Out[PWM_addr[i].pin].PWM_Output(PWM_addr[i].duty, PWM_addr[i].freq);
            } 
        }
    }
}

const uint32_t CRC32_Table [ 256 ] = {
    0x00000000ul, 0x77073096ul, 0xEE0E612Cul, 0x990951BAul,
    0x076DC419ul, 0x706AF48Ful, 0xE963A535ul, 0x9E6495A3ul,
    0x0EDB8832ul, 0x79DCB8A4ul, 0xE0D5E91Eul, 0x97D2D988ul,
    0x09B64C2Bul, 0x7EB17CBDul, 0xE7B82D07ul, 0x90BF1D91ul,
    0x1DB71064ul, 0x6AB020F2ul, 0xF3B97148ul, 0x84BE41DEul,
    0x1ADAD47Dul, 0x6DDDE4EBul, 0xF4D4B551ul, 0x83D385C7ul,
    0x136C9856ul, 0x646BA8C0ul, 0xFD62F97Aul, 0x8A65C9ECul,
    0x14015C4Ful, 0x63066CD9ul, 0xFA0F3D63ul, 0x8D080DF5ul,
    0x3B6E20C8ul, 0x4C69105Eul, 0xD56041E4ul, 0xA2677172ul,
    0x3C03E4D1ul, 0x4B04D447ul, 0xD20D85FDul, 0xA50AB56Bul,
    0x35B5A8FAul, 0x42B2986Cul, 0xDBBBC9D6ul, 0xACBCF940ul,
    0x32D86CE3ul, 0x45DF5C75ul, 0xDCD60DCFul, 0xABD13D59ul,
    0x26D930ACul, 0x51DE003Aul, 0xC8D75180ul, 0xBFD06116ul,
    0x21B4F4B5ul, 0x56B3C423ul, 0xCFBA9599ul, 0xB8BDA50Ful,
    0x2802B89Eul, 0x5F058808ul, 0xC60CD9B2ul, 0xB10BE924ul,
    0x2F6F7C87ul, 0x58684C11ul, 0xC1611DABul, 0xB6662D3Dul,
    0x76DC4190ul, 0x01DB7106ul, 0x98D220BCul, 0xEFD5102Aul,
    0x71B18589ul, 0x06B6B51Ful, 0x9FBFE4A5ul, 0xE8B8D433ul,
    0x7807C9A2ul, 0x0F00F934ul, 0x9609A88Eul, 0xE10E9818ul,
    0x7F6A0DBBul, 0x086D3D2Dul, 0x91646C97ul, 0xE6635C01ul,
    0x6B6B51F4ul, 0x1C6C6162ul, 0x856530D8ul, 0xF262004Eul,
    0x6C0695EDul, 0x1B01A57Bul, 0x8208F4C1ul, 0xF50FC457ul,
    0x65B0D9C6ul, 0x12B7E950ul, 0x8BBEB8EAul, 0xFCB9887Cul,
    0x62DD1DDFul, 0x15DA2D49ul, 0x8CD37CF3ul, 0xFBD44C65ul,
    0x4DB26158ul, 0x3AB551CEul, 0xA3BC0074ul, 0xD4BB30E2ul,
    0x4ADFA541ul, 0x3DD895D7ul, 0xA4D1C46Dul, 0xD3D6F4FBul,
    0x4369E96Aul, 0x346ED9FCul, 0xAD678846ul, 0xDA60B8D0ul,
    0x44042D73ul, 0x33031DE5ul, 0xAA0A4C5Ful, 0xDD0D7CC9ul,
    0x5005713Cul, 0x270241AAul, 0xBE0B1010ul, 0xC90C2086ul,
    0x5768B525ul, 0x206F85B3ul, 0xB966D409ul, 0xCE61E49Ful,
    0x5EDEF90Eul, 0x29D9C998ul, 0xB0D09822ul, 0xC7D7A8B4ul,
    0x59B33D17ul, 0x2EB40D81ul, 0xB7BD5C3Bul, 0xC0BA6CADul,
    0xEDB88320ul, 0x9ABFB3B6ul, 0x03B6E20Cul, 0x74B1D29Aul,
    0xEAD54739ul, 0x9DD277AFul, 0x04DB2615ul, 0x73DC1683ul,
    0xE3630B12ul, 0x94643B84ul, 0x0D6D6A3Eul, 0x7A6A5AA8ul,
    0xE40ECF0Bul, 0x9309FF9Dul, 0x0A00AE27ul, 0x7D079EB1ul,
    0xF00F9344ul, 0x8708A3D2ul, 0x1E01F268ul, 0x6906C2FEul,
    0xF762575Dul, 0x806567CBul, 0x196C3671ul, 0x6E6B06E7ul,
    0xFED41B76ul, 0x89D32BE0ul, 0x10DA7A5Aul, 0x67DD4ACCul,
    0xF9B9DF6Ful, 0x8EBEEFF9ul, 0x17B7BE43ul, 0x60B08ED5ul,
    0xD6D6A3E8ul, 0xA1D1937Eul, 0x38D8C2C4ul, 0x4FDFF252ul,
    0xD1BB67F1ul, 0xA6BC5767ul, 0x3FB506DDul, 0x48B2364Bul,
    0xD80D2BDAul, 0xAF0A1B4Cul, 0x36034AF6ul, 0x41047A60ul,
    0xDF60EFC3ul, 0xA867DF55ul, 0x316E8EEFul, 0x4669BE79ul,
    0xCB61B38Cul, 0xBC66831Aul, 0x256FD2A0ul, 0x5268E236ul,
    0xCC0C7795ul, 0xBB0B4703ul, 0x220216B9ul, 0x5505262Ful,
    0xC5BA3BBEul, 0xB2BD0B28ul, 0x2BB45A92ul, 0x5CB36A04ul,
    0xC2D7FFA7ul, 0xB5D0CF31ul, 0x2CD99E8Bul, 0x5BDEAE1Dul,
    0x9B64C2B0ul, 0xEC63F226ul, 0x756AA39Cul, 0x026D930Aul,
    0x9C0906A9ul, 0xEB0E363Ful, 0x72076785ul, 0x05005713ul,
    0x95BF4A82ul, 0xE2B87A14ul, 0x7BB12BAEul, 0x0CB61B38ul,
    0x92D28E9Bul, 0xE5D5BE0Dul, 0x7CDCEFB7ul, 0x0BDBDF21ul,
    0x86D3D2D4ul, 0xF1D4E242ul, 0x68DDB3F8ul, 0x1FDA836Eul,
    0x81BE16CDul, 0xF6B9265Bul, 0x6FB077E1ul, 0x18B74777ul,
    0x88085AE6ul, 0xFF0F6A70ul, 0x66063BCAul, 0x11010B5Cul,
    0x8F659EFFul, 0xF862AE69ul, 0x616BFFD3ul, 0x166CCF45ul,
    0xA00AE278ul, 0xD70DD2EEul, 0x4E048354ul, 0x3903B3C2ul,
    0xA7672661ul, 0xD06016F7ul, 0x4969474Dul, 0x3E6E77DBul,
    0xAED16A4Aul, 0xD9D65ADCul, 0x40DF0B66ul, 0x37D83BF0ul,
    0xA9BCAE53ul, 0xDEBB9EC5ul, 0x47B2CF7Ful, 0x30B5FFE9ul,
    0xBDBDF21Cul, 0xCABAC28Aul, 0x53B39330ul, 0x24B4A3A6ul,
    0xBAD03605ul, 0xCDD70693ul, 0x54DE5729ul, 0x23D967BFul,
    0xB3667A2Eul, 0xC4614AB8ul, 0x5D681B02ul, 0x2A6F2B94ul,
    0xB40BBE37ul, 0xC30C8EA1ul, 0x5A05DF1Bul, 0x2D02EF8Dul};

uint32_t Check_Infordata_CRC_32(uint8_t p [], uint32_t len ,uint32_t Crc)
{
    uint32_t  i;
    uint32_t m32           = 0u;
    uint32_t FlashCrcValue = 0xFFFFFFFF;
    uint32_t result        = 0;
    //if ( len < 0xff )
    {
        for ( i = 0; i < len; i++ )
        {
            FlashCrcValue = CRC32_Table [ (FlashCrcValue ^ p [ i ]) & 0xFF ] ^ ((FlashCrcValue >> 8) & 0x00ffffff);
        }

        FlashCrcValue ^= 0xffffffff;
    }

    m32 = Crc;//((( uint32_t )p [ i + 3 ] << 24) & 0xff000000) | ((( uint32_t )p [ i + 2 ] << 16) & 0x00ff0000) | ((( uint32_t )p [ i + 1 ] << 8) & 0x0000ff00) | ((( uint32_t )p [ i ]) & 0xff0000ff);

    if ( (m32 == FlashCrcValue) && (FlashCrcValue != 0xFFFFFFFF) )
    {
        result = 1;
    }

    return result;
}

uint32_t Get_Total_CheckStep(void)
{
    uint32_t ret = 0;
    if ( g_Verify_Result == 1U )
    {
        ret = PreLoad_Info->total_step.word;
    }
    else
    {
        ret = 0;
    }
    return ret;
}
