/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.1
 *
 * @date        2025-04-31
 *
 * @attention
 *
 *  Copyright (C) 2026 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (Geehy Semiconductor Software License Agreement).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the Geehy Semiconductor Software License Agreement for the governing permissions
 *  and limitations under the License.
 */


#include "CDD_Usart.h"
#include "Mcu.h"
#include "Lin.h"
#include "Port.h"
#include "Dio.h"

#define LIN_SLEEP_TEST

extern const Usart_ConfigType g_usartConfg[USART_CHANNEL_NUM];
extern ISR(USART1_IRQHandler);
extern ISR(USART2_IRQHandler);

uint8 txData[8] = {0x85,0x95,0xA4,0xB0,0xC3,0xD1,0xE6,0xF2};
uint8 txData1[1] = {0x55};
uint16 rxData[10] = {0};

void delay(uint32 value)
{
    while(value--);
}

uint8 testTxData[8]={0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08}; 
uint8 *testRxData = NULL; 

/*!
 * @brief       send one frame data
 *
 * @param       channel: lin channel
 *              pid:frame pid data
 *              cs: select checksum
 *              drc: select master or slave
 *              dl: data length
 *              sdu: data ptr
 * 
 * @retval      0: send correctly
 *              -1: channel status error
 *              -2: channel status error
 *              -3: send data error
 *              -4: tx data busy
 *              -5: go to sleep fail
 *              -6: channel status error
 *
 * @note        Note
 */
int Lin_SendOneFrame(uint8 channel,
                     uint8 pid,
                     Lin_FrameCsModelType cs,
                     Lin_FrameResponseType drc,
                     uint8 dl,
                     uint8* sdu)
{
    uint32 timeOut = 0;
    Lin_PduType Pdu;
    Pdu.Pid = pid;
    Pdu.Cs = cs;
    Pdu.Drc = drc;
    Pdu.Dl = dl;
    Pdu.SduPtr = sdu;
    
    /* Enter wake-up detection state after initialization */
    if ((uint8)LIN_CH_SLEEP_STATE != g_LinChannelStatus[LIN_CONFIG_CHANNEL_0])
    {
        /* state error */
        return -1;
    }
    
    /* wake-up the lin master */
    //Lin_WakeupInternal(LIN_CONFIG_CHANNEL_0);
    Lin_Wakeup(LIN_CONFIG_CHANNEL_0);
    
    /* lin channel initialized success,entering communication */
    if ((uint8)LIN_CH_OPERATIONAL != g_LinChannelStatus[LIN_CONFIG_CHANNEL_0])
    {
        /* state error */
        return -2;
    }
    
    /* normal transmission of host data */
    if (E_OK != Lin_SendFrame(channel,&Pdu))
    {
        /* send error */
        printf("send data error!\r\n");
        return -3;
    }
    
    /* get the status of the LIN bus and check if the transmission was successful */
    while((LIN_TX_OK != Lin_GetStatus(LIN_CONFIG_CHANNEL_0,&testRxData)) && (timeOut < LIN_OPERATION_TIMEOUT))
    {
        timeOut++;
    }
    if (timeOut > LIN_OPERATION_TIMEOUT)
    {
        /* send error */
        printf("send data busy!\r\n");
        return -4;
    }
    
    printf("send data ok!\r\n");
    printf("send data is: ");
    for (int tempSize = 0; tempSize < 8; tempSize++)
    {
        printf(" %02X", sdu[tempSize]);
    }
    printf("\r\n");
    /* enter sleep mode directly after successfully sendling data */
    if (E_OK != Lin_GoToSleepInternal(LIN_CONFIG_CHANNEL_0))
    {
        /* api error */
        return -5;
    }
    
    /* set the status to sleep */
    if ((uint8)LIN_CH_SLEEP_STATE != g_LinChannelStatus[LIN_CONFIG_CHANNEL_0])
    {
        /* state error */
        return -6;
    }
    
    /* send ok */
    return 0;
}

/*              
    * Pin number        | Function       
    * ----------------- |------------    
    * PTA 2             | LIN_TX     
    * PTB 3             | LIN_RX       
*/

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    Mcu_Init(&g_mcuConfig);
    Mcu_InitClock(McuClockSettingConfig_0);

    //LIN TX PIN:PA2;LIN RX PIN:PA3
    Port_Init(&g_portConfig);

    Usart_Init(g_usartConfg);
    Dio_WriteChannel(DIO_PORT_A_PIN_8,DIO_STD_HIGH);
    Lin_Init(&g_linConfig);
    
    NVIC_EnableIRQ(USART2_IRQn);
    NVIC_EnableIRQ(USART1_IRQn);
    
    printf("G32A1085 Lin demo start!\r\n");
    
#ifdef LIN_MASTER_NODECFG
    Lin_SendOneFrame(LIN_CONFIG_CHANNEL_0, /* channel 0 */
                   0x10,                                     /* master request frame */
                   LIN_CLASSIC_CS,                           /* classic checksum */
                   LIN_MASTER_RESPONSE,                      /* send using master */
                   8U,                                       /* 8 bytes sent */
                   testTxData) ;                             /* send data */

#ifdef LIN_SLEEP_TEST

    g_LinChannelStatus[LIN_CONFIG_CHANNEL_0] = LIN_CHANNEL_TX_COMPLETE_STATE;
    Lin_GoToSleep(LIN_CONFIG_CHANNEL_0);

#endif 
#endif

    while(1)
    {
        #ifdef LIN_SLAVE_NODECFG
            if(0 != g_receiveOnceFlg)
            {
                g_receiveOnceFlg = 0;
                printf("Slave mode received data: ");
                for(int i = 0;i < 8; i++)
                {
                    printf("0x%x ",g_responseBuf[i]);
                }
                printf("\r\n");
            }
            else
            {
                /* do nothing */
            }
        #endif
    }

}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
* @note
*/
int fputc(int ch, FILE* f)
{
    int reVal = 0;
    reVal = Usart_PutRedefinition(USART1_ID,&ch);
    
    return reVal;
}

/* If configuring the full library using versions after IAR 9.30,
   it is necessary to implement the _write function for printf redirection.*/
size_t __write(int handle,const unsigned char *buf,size_t bufSize)
{
    int32 tempCh = 0;
    for(int i=0; i<bufSize; i++)
    {
        Usart_PutRedefinition(USART1_ID,&tempCh);
    }
    return bufSize;
}

#elif defined (__GNUC__)

/* For Arm Cross GCC: Eclipse */
int _write(int fd,const unsigned char *buf,int len)
{
    int32 tempCh = 0;
    for(int i=0; i<len; i++)
    {
        int32 tempCh = (int32)buf[i];
        Usart_PutRedefinition(USART1_ID,&tempCh);
    }
    return len;
}

#endif

