#include "api_RS485.h"
#include "R485_Communication_Matrix.h"
#include "string.h"
#include "Display_Info.h"
#define R485_BUF_SIZE (1024 * 4 )
#define R485_UART_PORT (1)
#define R485_TX_OUT_MCU R485_TX
#define R485_RX_IN_MCU R485_RX
#define R485_DATA_PACKAGE_MIN_LEN 0x07 /* 帧头 2 ID 1 数据长度 1 校验和 1 帧尾 2*/
#define R485_DATA_LEN 0x40
static void RS485_Receive_Data_Analysis(void);
static void R485_TX_Init(void);
static void R485_RX_Init(void);
static RS485DataPacket stRS485DataRx;
static RS485ValidDataPacket_st_t stRS485RxVldData[RS485_Rx_ID_Idx_Max];
static uint32_t u32RS485RxDataBegin = 0;
static uint32_t u32RS485RxDataRe = 0;
static uint32_t u32RS485RxDataValidLenTem = 0;
static uint32_t u32RS485DataBufLen = 0;
static uint8_t RS485DataBuf[RS485_RX_BUF_LEN];
static uint32_t u32RS485RxDataValidLen = 0;
static uint8_t RS485ValidData[RS485_RX_DATA_LEN];
static uint8_t u8RS485RecVldID[RS485_Rx_ID_Idx_Max];
uint32_t RS485_send_time = 0;
uint32_t RS485_send_num = 0;
uint8_t RS485_TX_finish = 0;
// static RS485_Tx_Data_Ctrl_st_t stRS485TxData[RS485_Tx_ID_Idx_Max];
_ID0X40h_Data R485_ID40h;
_ID0X48h_Data R485_ID48h;
_ID0X41h_Data R485_ID41h;
_ID0X49h_Data R485_ID49h;
_ID0X42h_Data R485_ID42h;
_ID0X4Ah_Data R485_ID4Ah;
_ID0X4Dh_Data R485_ID4Dh;
LineSta       LineGetSta;

void R485_TX_Init(void)
{

}

void R485_RX_Init(void)
{
    // for (uint8_t i = 0; i < RS485_Rx_ID_Idx_Max; i++)
    // {
    //     stRS485RxVldData[i].u16LostTime = 0;
    //     stRS485RxVldData[i].u8Status = R485_Lost;
    //     stRS485RxVldData[i].u8Received = 0;
    //     stRS485RxVldData[i].u8ReceivedFlag = 0;
    //     memset(stRS485RxVldData[i].u8RecVal, 0, RS485_RX_DATA_LEN);
    // }
}
void bsp_R485_Init(void)
{

    // uart_config_t uart_config = {
    //     .baud_rate = 115200,
    //     .data_bits = UART_DATA_8_BITS,
    //     .parity = UART_PARITY_DISABLE,
    //     .stop_bits = UART_STOP_BITS_1,
    //     .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
    //     .source_clk = UART_SCLK_DEFAULT,
    // };
    // /* Install UART driver  */
    // uart_driver_install(R485_UART_PORT, R485_BUF_SIZE, R485_BUF_SIZE, 0, NULL, 0);   /* port rxbuff txbuff evetnqueue queuesize iarmflag */
    // uart_param_config(R485_UART_PORT, &uart_config);    /* port uartconfig */
    // ESP_ERROR_CHECK(uart_set_pin(R485_UART_PORT, R485_TX_OUT_MCU, R485_RX_IN_MCU, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE)); /* port tx rx rts cts */
    // ESP_ERROR_CHECK(uart_set_mode(R485_UART_PORT, UART_MODE_RS485_HALF_DUPLEX));
    // R485_TX_Init();
    // R485_RX_Init();
    // ESP_LOGI("485", "Init");
}

void Uart_Uninstall(void)
{
    // uart_driver_delete(R485_UART_PORT);
}



uint8_t Yadi_CAL_Data_Sum(uint8_t* pu8LinData, uint16_t u8LinLen)
{
    uint8_t u8LinSum = 0U;
    uint16_t i = 0;

    for (i = 0; i < u8LinLen; i++)
    {
        u8LinSum = (uint8_t)(u8LinSum + pu8LinData[i]);
    }

    return u8LinSum;
}



void R485_RX_task(void* pvParameters)
{
//    int rxBytes = uart_read_bytes(R485_UART_PORT, &RxDataBuf[0], 1, portMAX_DELAY);
//    if (rxBytes > 0)
//    {
//        size_t rxBytes1 = 0;
//        int rxBytes2 = 0;
//        uint32_t i = 0;
//        uint32_t j = 0;
//        uart_get_buffered_data_len(R485_UART_PORT, &rxBytes1);
//        rxBytes2 = 0;
//        if (rxBytes1 > 0)
//        {
//            rxBytes2 = uart_read_bytes(R485_UART_PORT, &RxDataBuf[rxBytes], rxBytes1, 0);
       
//        rxBytes2 += rxBytes;
//        uds_uart_rx_write(RxDataBuf, rxBytes2);
//        stRS485DataRx.length = rxBytes2;
//        memcpy(stRS485DataRx.RS485Data, RxDataBuf, rxBytes2);
//        RS485_Receive_Data_Analysis();
//         }
//    }
}



static void RS485_Receive_Data_Analysis(void)
{
    // if ((u32RS485DataBufLen + stRS485DataRx.length) >= RS485_RX_BUF_LEN)
    // {
    //     u32RS485DataBufLen = 0;
    //     RS485DataBuf[0] = 0;
    // }
    // else
    // {
    //     memcpy(&RS485DataBuf[u32RS485DataBufLen], stRS485DataRx.RS485Data, stRS485DataRx.length);
    //     u32RS485DataBufLen += stRS485DataRx.length;
    // }

    // if (u32RS485DataBufLen > 4)
    // {
    //     u32RS485RxDataBegin = 0;
    //     while (u32RS485RxDataBegin < (u32RS485DataBufLen - 4))
    //     {
    //         if ((RS485DataBuf[0 + u32RS485RxDataBegin] != 'Y') ||
    //             (RS485DataBuf[1 + u32RS485RxDataBegin] != 'D') ||
    //             ((RS485DataBuf[2 + u32RS485RxDataBegin] != RS485_RECEIVE_ID_0X40) &&
    //                 (RS485DataBuf[2 + u32RS485RxDataBegin] != RS485_RECEIVE_ID_0X41) &&
    //                 (RS485DataBuf[2 + u32RS485RxDataBegin] != RS485_RECEIVE_ID_0X42) &&
    //                 (RS485DataBuf[2 + u32RS485RxDataBegin] != RS485_RECEIVE_ID_0X45) &&
    //                 (RS485DataBuf[2 + u32RS485RxDataBegin] != OTA_MODE_RX_ID)))
    //         {
    //             u32RS485RxDataBegin++;
    //             continue;
    //         }

    //         u32RS485RxDataValidLenTem = RS485DataBuf[3 + u32RS485RxDataBegin];
    //         if (u32RS485RxDataValidLenTem != RS485_RX_DATA_LEN)
    //         {
    //             if (RS485DataBuf[2 + u32RS485RxDataBegin] != OTA_MODE_RX_ID)
    //             {
    //                 u32RS485RxDataBegin++;
    //                 continue;
    //             }
    //         }

    //         u32RS485RxDataRe = u32RS485DataBufLen - u32RS485RxDataBegin;
    //         if (u32RS485RxDataRe >= (u32RS485RxDataValidLenTem + 5))
    //         {
    //             uint8_t u8YadiDataSum = 0;
    //             u8YadiDataSum = Yadi_CAL_Data_Sum(&RS485DataBuf[2 + u32RS485RxDataBegin], (u32RS485RxDataValidLenTem + 2));
    //             if (u8YadiDataSum != RS485DataBuf[u32RS485RxDataValidLenTem + 4 + u32RS485RxDataBegin])
    //             {
    //                 u32RS485RxDataBegin++;
    //                 continue;
    //             }
    //         }
    //         else
    //         {
    //             break;
    //         }
    //         u32RS485RxDataRe = u32RS485DataBufLen - u32RS485RxDataBegin;
    //         if (u32RS485RxDataRe >= (u32RS485RxDataValidLenTem + 7))
    //         {
    //             if ((RS485DataBuf[u32RS485RxDataValidLenTem + 5 + u32RS485RxDataBegin] != 0x4B) ||
    //                 (RS485DataBuf[u32RS485RxDataValidLenTem + 6 + u32RS485RxDataBegin] != 0x4A))
    //             {
    //                 u32RS485RxDataBegin++;
    //                 continue;
    //             }
    //             else
    //             {
    //                 switch (RS485DataBuf[2 + u32RS485RxDataBegin])
    //                 {
    //                     case RS485_RECEIVE_ID_0X40:
    //                         {
    //                             if (stRS485RxVldData[RS485_Rx_ID40_Idx].u8Received == 0)
    //                             {
    //                                 memcpy(stRS485RxVldData[RS485_Rx_ID40_Idx].u8RecVal, &RS485DataBuf[4 + u32RS485RxDataBegin], u32RS485RxDataValidLenTem);
    //                                 stRS485RxVldData[RS485_Rx_ID40_Idx].u8Received = 1;

    //                                 stRS485TxData[RS485_Tx_ID48_Idx].u8TxTime = 10; //ms
    //                                 stRS485TxData[RS485_Tx_ID48_Idx].u8TxEnable = 1;
    //                             }
    //                             break;
    //                         }
    //                     case RS485_RECEIVE_ID_0X41:
    //                         {
    //                             if (stRS485RxVldData[RS485_Rx_ID41_Idx].u8Received == 0)
    //                             {
    //                                 memcpy(stRS485RxVldData[RS485_Rx_ID41_Idx].u8RecVal, &RS485DataBuf[4 + u32RS485RxDataBegin], u32RS485RxDataValidLenTem);
    //                                 stRS485RxVldData[RS485_Rx_ID41_Idx].u8Received = 1;

    //                                 stRS485TxData[RS485_Tx_ID49_Idx].u8TxTime = 10; //ms
    //                                 stRS485TxData[RS485_Tx_ID49_Idx].u8TxEnable = 1;
    //                             }
    //                             break;
    //                         }
    //                     case RS485_RECEIVE_ID_0X42:
    //                         {
    //                             if (stRS485RxVldData[RS485_Rx_ID42_Idx].u8Received == 0)
    //                             {
    //                                 memcpy(stRS485RxVldData[RS485_Rx_ID42_Idx].u8RecVal, &RS485DataBuf[4 + u32RS485RxDataBegin], u32RS485RxDataValidLenTem);
    //                                 stRS485RxVldData[RS485_Rx_ID42_Idx].u8Received = 1;

    //                                 stRS485TxData[RS485_Tx_ID4A_Idx].u8TxTime = 10; //ms
    //                                 stRS485TxData[RS485_Tx_ID4A_Idx].u8TxEnable = 1;
    //                             }
    //                             break;
    //                         }
    //                     case RS485_RECEIVE_ID_0X45:
    //                         {
    //                             {
    //                                 stRS485RxVldData[RS485_Rx_ID45_Idx].u8Received = 1;

    //                                 stRS485TxData[RS485_Tx_ID4D_Idx].u8TxTime = 10; //ms
    //                                 stRS485TxData[RS485_Tx_ID4D_Idx].u8TxEnable = 1;
    //                             }
    //                             break;
    //                         }

    //                     case OTA_MODE_RX_ID:
    //                         ota_message_init(&stRS485DataRx.RS485Data[4], u32RS485RxDataValidLenTem);
    //                         break;

    //                     default:
    //                         {
    //                             break;
    //                         }
    //                 }

    //                 u32RS485RxDataValidLen = u32RS485RxDataValidLenTem;
    //                 u32RS485RxDataBegin += (u32RS485RxDataValidLenTem + 7);


    //                 continue;
    //             }
    //         }
    //         else
    //         {
    //             break;
    //         }
    //     }

    //     if (u32RS485RxDataBegin > 0)
    //     {
    //         memcpy(RS485DataBuf, &RS485DataBuf[u32RS485RxDataBegin], (u32RS485DataBufLen - u32RS485RxDataBegin));
    //         u32RS485DataBufLen -= u32RS485RxDataBegin;
    //     }
    // }
}


uint32_t R485_Send(const uint16_t cmdID, const uint8_t* pData, uint8_t len)
{
    uint8_t dataBuf[128];
    int i = 0;
    uint16_t checksum = 0;
    uint32_t frameLen;
    // if (len + R485_DATA_PACKAGE_MIN_LEN > 71)
    // {
    //     return 0;
    // }

    // if (len != 64)
    // {
    //     return 0;
    // }

    dataBuf[0] = 0x59; /* 帧头 */
    dataBuf[1] = 0x44;
    dataBuf[2] = cmdID;         /* ID */
    // dataBuf[3] = R485_DATA_LEN; /* 长度 固定64Byte */
    dataBuf[3] = len;
    frameLen = 4;
    // 数据 Data
    for (i = 0; i < len; ++i)
    {
        dataBuf[frameLen] = pData[i];
        frameLen++;
    }

    // checksum = Yadi_CAL_Data_Sum(&dataBuf[2], R485_DATA_LEN + 2);
    checksum = Yadi_CAL_Data_Sum(&dataBuf[2], len + 2);
    // checksum = 0;
    dataBuf[frameLen] = checksum;
    frameLen++;
    dataBuf[frameLen] = 0X4B;
    frameLen++;
    dataBuf[frameLen] = 0X4A;
    frameLen++;
    // if (frameLen != 71)
    // {
    //     return 0;
    // }
    uint8_t sendresult = 0;
    sendresult = UART_Ch0_Send_Multiple_Byte(dataBuf,frameLen);
    RS485_TX_finish = 1;
    // while(1)
    // {
       if(sendresult == 0)
       {

            return sendresult;
       }
       else
       {
        sendresult = UART_Ch0_Send_Multiple_Byte(dataBuf,frameLen);
       }
        return sendresult;
    // }
    
}



uint8_t sendmsgAll[8];
uint32_t sendnum = 1;
uint8_t getbanbenhaoflag = 0;
uint32_t send80time = 0;
void RS485_User_Tx_Data(void)
{

#if(1)
            uint8_t flag = 0;
            uint32_t sendfinishflag = 0;

                // if(RS485_send_time > 3000)
                // {
                if(MENU_CHECK_STEP == 16)
                {
                    // if(send80time < 1000)
                    // {
                    //     send80time++;
                    // }
                }
                    if(send80time < 2000)
                    {
                        send80time++;
                    }
                    else
                    {
                        
                    }
                    switch (RS485_send_num)
                    {
                        case RS485_Tx_ID48_Idx:
                            
                            sendfinishflag = R485_Send_0x40(); 
                            RS485_TX_finish = 1;
                            if(sendfinishflag == 0)
                            {
                                if(RS485_TX_finish == 1)
                                {
                                    // sendnum++;
                                    RS485_send_time = 0;
                                    RS485_send_num ++;
                                }
                                
                            }
                            break;
                        case RS485_Tx_ID49_Idx:
                        
                            sendfinishflag = R485_Send_0x41();
                            if(sendfinishflag == 0)
                            {
                                RS485_send_time = 0;
                                RS485_TX_finish = 1;
                                
                                if(RS485_TX_finish == 1)
                                {
                                    RS485_send_num ++;
                                }
                            }
                            break;
                        case RS485_Tx_ID4A_Idx:
                            sendfinishflag = R485_Send_0x42();
                            if(sendfinishflag == 0)
                            {
                                RS485_send_time = 0;
                                RS485_TX_finish = 1;
                                if(RS485_TX_finish == 1)
                                {
                                    RS485_send_num++;
                                }
                            }
                            break;
                        case 3:
                        sendfinishflag = R485_Send_0x45();
                            if(sendfinishflag == 0)
                            {
                                RS485_send_time = 0;
                                RS485_TX_finish = 1;
                                if(RS485_TX_finish == 1)
                                {
                                    if((MENU_CHECK_STEP == 3 || Get_Display_Type( ) == 0||Get_Display_Type( ) == 3 || MENU_CHECK_STEP == 16 || MENU_CHECK_STEP == 0))
                                    // if((MENU_CHECK_STEP == 3 || Get_Display_Type( ) == 3 || MENU_CHECK_STEP == 16 ) && clearOdoFlag != 1)
                                    {
                                        RS485_send_num ++;
                                    }
                                    else
                                    {
                                        RS485_send_num = 0;
                                    }
                                    
                                }
                            }
                        break;
                        case 4:
                            sendfinishflag = 0;
                            if(MENU_CHECK_STEP == 16)
                            {
                                    Openble[0] = 0x59;
                                    Openble[1] = 0x44;
                                    Openble[2] = 0xA;
                                    Openble[3] = 0x8A;
                                    Openble[4] = 0xA;
                                    Openble[5] = 0xA;
                                    Openble[6] = name2;
                                    Openble[7] = name1;
                                    Openble[8] = 1;
                                    
                                    Openble[9] = btmac[0];
                                    Openble[10] = btmac[1];
                                    Openble[11] = btmac[2];
                                    Openble[12] = btmac[3];
                                    Openble[13] = btmac[4];
                                    Openble[14] = btmac[5];

                                    Openble[15] = 0x4B;
                                    Openble[16] = 0x4A;
                                    UART_Ch2_Send_Multiple_Byte(Openble,sizeof(Openble));
                                    // if(send80time < 500)
                                    // {
                                    //     RS485_send_num++;
                                    // }
                            }
                            else
                            {
                                    Openble[0] = 0x59;
                                    Openble[1] = 0x44;
                                    Openble[2] = 0xA;
                                    Openble[3] = 0x8A;
                                    Openble[4] = 0xA;
                                    Openble[5] = 0xA;
                                    Openble[6] = name2;
                                    Openble[7] = name1;
                                    Openble[8] = 0;
                                    
                                    Openble[9] = btmac[0];
                                    Openble[10] = btmac[1];
                                    Openble[11] = btmac[2];
                                    Openble[12] = btmac[3];
                                    Openble[13] = btmac[4];
                                    Openble[14] = btmac[5];

                                    Openble[15] = 0x4B;
                                    Openble[16] = 0x4A;
                                    UART_Ch2_Send_Multiple_Byte(Openble,sizeof(Openble));
                            }
                            // if(send80time > 500)
                            // {
                                sendfinishflag = R485_Send_0x80();
                                if(sendfinishflag == 0)
                                {
                                    RS485_send_time = 0;
                                    RS485_TX_finish = 1;
                                    if(RS485_TX_finish == 1)
                                    {
                                        RS485_send_num++;
                                    }
                                }
                            // }

                        default:
                            flag = 1;
                            RS485_send_time = 0;
                            RS485_send_num = 0;
                            getbanbenhaoflag = 1;
                            break;
                     }
                
            

#endif
}
uint8_t backtime = 0;
void backsend(void)
{
    if(clearOdoFlag == 0)
    {
        backtime = 20;
    }
    else
    {
        backtime = 10;
    }
    if(RS485_send_time>=backtime)
    {
        RS485_send_time = 0;
        RS485_TX_finish = 0;
        sendnum--;
        RS485_send_num--;
    }
}
/**
 * @brief R485状态计时函数
 */
void R485_Timer_Handel(void)
{
    // for (uint8_t i = 0; i < RS485_Rx_ID_Idx_Max; i++)
    // {
    //     if (stRS485RxVldData[i].u8Status != R485_Lost)
    //     {
    //         if (stRS485RxVldData[i].u16LostTime <= R485_LOST_TIEMR_VAL)
    //         {
    //             stRS485RxVldData[i].u16LostTime++;
    //         }
    //         else
    //         {
    //             stRS485RxVldData[i].u8Status = R485_Lost;
    //             memset(stRS485RxVldData[i].u8RecVal, 0, RS485_RX_DATA_LEN);
    //             switch (i)
    //             {
    //                 case RS485_Rx_ID40_Idx:
    //                     memset(R485_ID40h.Msg, 0, RS485_RX_DATA_LEN);
    //                     break;
    //                 case RS485_Rx_ID41_Idx:
    //                     memset(R485_ID41h.Msg, 0, RS485_RX_DATA_LEN);
    //                     break;
    //                 case RS485_Rx_ID42_Idx:
    //                     memset(R485_ID42h.Msg, 0, RS485_RX_DATA_LEN);
    //                     break;
    //                 default:
    //                     break;
    //             }
    //         }
    //     }
    // }
}




