#include "main.h"
#include "cmsis_os.h"
#include "adc.h"
#include "usart.h"
#include "gpio.h"
#include "adc.h"
#include "oled.h"
#include <stdint.h>
#include <stdio.h>  
#include "callback.h"  
#include "variables.h"
#include "led.h"
static osThreadId_t uart1TaskHandle = NULL;

static uint8_t rx1;

static uint8_t idx = 0;
static uint8_t frame[4];

void UART1_RegisterTaskHandle(osThreadId_t tid)
{
    uart1TaskHandle = tid;
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)
    {
        uint8_t b = rx1;

        if (idx == 0)
        {
            if (b != 0x0F)
            {
                HAL_UART_Receive_IT(&huart1, &rx1, 1);
                return;
            }
        }

        frame[idx++] = b;

        if (idx >= 4)
        {
            receive[0] = frame[0];
            receive[1] = frame[1];
            receive[2] = frame[2];
            receive[3] = frame[3];

            if (frame[0] == 0x0F && frame[3] == 0xF0)
            {
                UART1[0] = frame[1];
                UART1[1] = frame[2];

                if (uart1TaskHandle != NULL)
                {
                    osThreadFlagsSet(uart1TaskHandle, 0x01);
                }
            }

            idx = 0; 
        }

        HAL_UART_Receive_IT(&huart1, &rx1, 1);
    }
}

void UART1_StartRxIT(void)
{
    HAL_UART_Receive_IT(&huart1, &rx1, 1);
}

