/*
 * uart_tasks.h
 *
 *  Created on: Aug 14, 2024
 *      Author: jakubski
 */

#ifndef INC_UART_TASKS_H_
#define INC_UART_TASKS_H_

#include "FreeRTOS.h"
#include "FreeRTOSConfig.h"
#include "task.h"
#include "message_buffer.h"

#include "main.h"
#include "serial_protocol.h"
#include "measurements.h"

#define UART_RX_BUFF_SIZE 256
#define UART_TX_BUFF_SIZE 256

#define UART1_RX_BUFF_SIZE UART_RX_BUFF_SIZE
#define UART1_TX_BUFF_SIZE UART_TX_BUFF_SIZE
#define UART2_RX_BUFF_SIZE UART_RX_BUFF_SIZE
#define UART2_TX_BUFF_SIZE UART_TX_BUFF_SIZE
#define UART3_RX_BUFF_SIZE UART_RX_BUFF_SIZE
#define UART3_TX_BUFF_SIZE UART_TX_BUFF_SIZE
#define UART6_RX_BUFF_SIZE UART_RX_BUFF_SIZE
#define UART6_TX_BUFF_SIZE UART_TX_BUFF_SIZE
#define UART8_RX_BUFF_SIZE UART_RX_BUFF_SIZE
#define UART8_TX_BUFF_SIZE UART_TX_BUFF_SIZE
#define INPUT_DATA_BUFF_SIZE UART8_RX_BUFF_SIZE
#define OUTPUT_DATA_BUFF_SIZE 128

struct _SerialProtocolFrameHeader {
    uint16_t frameId;
    SerialProtocolCommands frameCommand;
    SerialProtocolRespStatus respStatus;
    uint16_t frameDataLength;
    portBASE_TYPE isResponseFrame;
};
typedef struct _SerialProtocolFrameHeader SerialProtocolFrameHeader;

struct _SerialProtocolFrameData {
	SerialProtocolFrameHeader frameHeader;
    uint8_t dataBuffer[INPUT_DATA_BUFF_SIZE];
};

typedef struct _SerialProtocolFrameData SerialProtocolFrameData;

typedef void (*ProcessDataCallbackFunc) (void* arg, SerialProtocolFrameData* spFrameData);

struct _UartTaskData {
    uint8_t* uartRxBuffer;
    uint16_t uartRxBufferLen;
    uint16_t uartRxBufferPos;
    uint8_t* uartTxBuffer;
    uint16_t uartTxBufferLen;
    uint8_t* frameData;
    uint16_t frameDataLen;
    uint16_t frameBytesCount;
    osThreadId_t uartRecieveTaskHandle;
    osThreadId_t uartTransmitTaskHandle;
    osMutexId_t rxDataBufferMutex;
    MessageBufferHandle_t processRxDataMsgBuffer;
    ProcessDataCallbackFunc processDataCb;
    osMessageQueueId_t *sendCmdToSlaveQueue;
    UART_HandleTypeDef* huart;
    uint8_t uartNumber;
};

typedef struct _UartTaskData UartTaskData;

extern RESMeasurements resMeasurements[SLAVES_COUNT];
extern SesnorsInfo sensorsInfo[SLAVES_COUNT];
extern uint32_t slaveLastSeen[SLAVES_COUNT];
extern osMutexId_t resMeasurementsMutex;
extern osMutexId_t sensorsInfoMutex;

extern UartTaskData uart1TaskData; // Board 1
extern UartTaskData uart3TaskData; // Board 2
extern UartTaskData uart6TaskData; // Board 3
extern UartTaskData uart2TaskData; // Board 4
extern UartTaskData uart8TaskData; // Debug

void UartTasksInit(void);
void UartTaskCreate (UartTaskData* uartTaskData);

void UartRxTask (void* argument);
void UartTxTask (void* argument);
void HandleUartRxCallback (UartTaskData* uartTaskData, UART_HandleTypeDef* huart, uint16_t Size);

void MeasurmentsReqSchedulerTaskInit(void);
void MeasurmentsReqSchedulerTask(void* argument);


#endif /* INC_UART_TASKS_H_ */
