#include "tc_system.h"
#include "tc_thread.h"
#include "com_ttySx.h"

static com_ttySx_t ttyS2;
static com_ttySx_t ttyS3;
static int loop_quit = 0;
static tc_thread_t ttyS2_thread;
static tc_thread_t ttyS3_thread;


void* com_ttyS2_loop(void* argv)
{
    com_ttySx_t* dev = (com_ttySx_t*)argv;
    uint8_t rxbuff[18];
    uint8_t txbuff[18];
    int txlen=0;
    int rxlen=0;
    while(loop_quit == 0)
    {
        txlen = sprintf(txbuff, "Hello ttyS3");txbuff[txlen++]='\0';
        com_ttySx_send(dev, txbuff, txlen);
        com_ttySx_recv_with_timeout(dev, rxbuff, 12, 1000);
        msleep(1000);
    }
    return NULL;
}
void* com_ttyS3_loop(void* argv)
{
    com_ttySx_t* dev = (com_ttySx_t*)argv;
    uint8_t rxbuff[18];
    uint8_t txbuff[18];
    int txlen=0;
    int rxlen=0;
    while(loop_quit == 0)
    {
        rxlen = com_ttySx_recv_with_timeout(dev, rxbuff, 12, 1000);
        if (rxlen){
            if (strcmp(rxbuff, "Hello ttyS3")==0)
            {
                txlen = sprintf(txbuff, "ttyS3 ACK");txbuff[txlen++]='\0';
                com_ttySx_send(dev, txbuff, txlen);
            }
        }
    }
    return NULL;
}


void rs232_test(int loop)
{
    printf("%s(%d):%s | loop=%d\n", __FILE__, __LINE__, __FUNCTION__, loop);
    com_ttySx_init(&ttyS2, "/dev/ttyS2", 19200, 8, 'N', 1);
    printf("%s(%d):%s | loop=%d\n", __FILE__, __LINE__, __FUNCTION__, loop);
    com_ttySx_init(&ttyS3, "/dev/ttyS3", 19200, 8, 'N', 1);


    printf("%s(%d):%s | loop=%d\n", __FILE__, __LINE__, __FUNCTION__, loop);
    tc_thread_init(&ttyS2_thread, com_ttyS2_loop, &ttyS2);
    printf("%s(%d):%s | loop=%d\n", __FILE__, __LINE__, __FUNCTION__, loop);
    tc_thread_init(&ttyS3_thread, com_ttyS3_loop, &ttyS3);
    printf("%s(%d):%s | loop=%d\n", __FILE__, __LINE__, __FUNCTION__, loop);
    
    loop_quit = 0;
    while(loop>0)
    {
        msleep(1000);
        loop--;
        printf("%s(%d):%s | loop=%d\n", __FILE__, __LINE__, __FUNCTION__, loop);
    }
    loop_quit = 1;


    printf("%s(%d):%s | loop_quit=%d\n", __FILE__, __LINE__, __FUNCTION__, loop_quit);
    tc_thread_exit(&ttyS2_thread);
    printf("%s(%d):%s | loop_quit=%d\n", __FILE__, __LINE__, __FUNCTION__, loop_quit);
    tc_thread_exit(&ttyS3_thread);
    
    printf("%s(%d):%s | loop_quit=%d\n", __FILE__, __LINE__, __FUNCTION__, loop_quit);
    com_ttySx_exit(&ttyS2);
    printf("%s(%d):%s | loop_quit=%d\n", __FILE__, __LINE__, __FUNCTION__, loop_quit);
    com_ttySx_exit(&ttyS3);
    printf("%s(%d):%s | loop_quit=%d\n", __FILE__, __LINE__, __FUNCTION__, loop_quit);
    
}