/*
 * displayData.c
 *
 *  Created on: 30.04.2020
 *      Author: akos
 */

#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>

#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Task.h>
#include <ti/sysbios/knl/Mailbox.h>

#include <ti/sysbios/knl/Clock.h>
#include <ti/sysbios/knl/Semaphore.h>
#include <ti/sysbios/knl/Mailbox.h>
#include <ti/sysbios/gates/GateSwi.h>

#include <ti/drivers/UART.h>

#include "44_ielad_lib_EXT/ieladLib.h"
#include "utils/crc/crc16.h"

UART_Handle displayUARTHandle = NULL;
UART_Handle dataUARTHandle = NULL;
Mailbox_Handle dataTxMailbox;

void processMessage(ieladMsg* msg)
{
}

void clockFxn(void)
{
    ieladMsg txmsg;
    memset(&txmsg, 0, sizeof(txmsg));

    txmsg.header.syncByte = DISPLAY_MSG_SYNC_BYTE;
    txmsg.header.msgID = IELAD_RESET_ALIGNMENT_MSG_ID;
    txmsg.header.length = sizeof(ieladHeader) + 2;

    Mailbox_post(dataTxMailbox, &txmsg, BIOS_NO_WAIT);
}

void dataTxTaskFxn(void)
{
    ieladMsg msg;
    static unsigned char frameCounter;

    while (1)
    {
        Mailbox_pend(dataTxMailbox, &msg, BIOS_WAIT_FOREVER);

        msg.header.frameCounter = frameCounter++;
        const unsigned short checksum = crc16((uint8_t*)&msg.header.syncByte, msg.header.length - 2);

        memcpy(&msg.payload[msg.header.length - sizeof(ieladHeader) - sizeof(checksum)], &checksum, sizeof(checksum));

        UART_write(dataUARTHandle, &msg, msg.header.length);
    }
}

void displayDataRxTaskFxn(void)
{
    char rxData;
    ieladMsg eladMsg;
    ieladParserState parserState;

    initParserState(&parserState);

    ieladMsg txmsg;
    memset(&txmsg, 0, sizeof(txmsg));

    txmsg.header.syncByte = DISPLAY_MSG_SYNC_BYTE;
    txmsg.header.msgID = IELAD_RESET_ALIGNMENT_MSG_ID;
    txmsg.header.length = sizeof(ieladHeader) + 2;

    while (1)
    {
//        const int bytesRead = UART_read(displayUARTHandle, &rxData, 1);
        int bytesRead = 1;

        char* foo = (char*)&txmsg;
        rxData = *foo++;

        if (bytesRead == 1)
        {
            const parserResult result = parser(rxData, &eladMsg, &parserState);

            switch (result)
            {
                case PARSE_COMPLETED:
                {
                    processMessage(&eladMsg);
                    initParserState(&parserState);
                    break;
                }
                case PARSE_CRC_ERROR:
                {
                    initParserState(&parserState);
                    break;
                }
                case PARSE_ERROR:
                {
                    initParserState(&parserState);
                    break;
                }
            }
        }
    }
}


