#include "app_test.h"

uint8_t rx_buf[32];     // RS485 receive buffer
uint8_t rs_rx_flag = 0; // RS485 receive flag
uint8_t rs_rx_len;      // RS485 receive length

void app_RS485_test(void)
{
    HAL_UARTEx_ReceiveToIdle_IT(&huart3, rx_buf, 32);

    while (1)
    {
        if (rs_rx_flag)
        {
            debug_printf("RS485 RX Recv (%d bytes): %c %c %c", rs_rx_len, rx_buf[0], rx_buf[1], rx_buf[2]);
            HAL_UART_Transmit(&huart3, rx_buf, rs_rx_len, 1000);
            rs_rx_flag = 0;
        }
    }
}

void app_big_laser_test(void)
{
    HAL_GPIO_WritePin(POWER_12V_EN_GPIO_Port, POWER_12V_EN_Pin, GPIO_PIN_SET);
    HAL_TIM_PWM_Start(&htim10, TIM_CHANNEL_1);
    while (1)
    {
        for (uint8_t pulse = 0; pulse < 100; pulse += 10)
        {
            __HAL_TIM_SetCompare(&htim10, TIM_CHANNEL_1, pulse);
            HAL_Delay(10);
        }
        for (uint8_t pulse = 100; pulse > 0; pulse -= 10)
        {
            __HAL_TIM_SetCompare(&htim10, TIM_CHANNEL_1, pulse);
            HAL_Delay(10);
        }
    }
}

void app_small_laser_test(void)
{
    HAL_GPIO_WritePin(POWER_5V_EN_GPIO_Port, POWER_5V_EN_Pin, GPIO_PIN_SET);
    HAL_TIM_PWM_Start(&htim10, TIM_CHANNEL_1);
    while (1)
    {
        for (uint8_t pulse = 0; pulse < 100; pulse += 10)
        {
            __HAL_TIM_SetCompare(&htim10, TIM_CHANNEL_1, pulse);
            HAL_Delay(10);
        }
        for (uint8_t pulse = 100; pulse > 0; pulse -= 10)
        {
            __HAL_TIM_SetCompare(&htim10, TIM_CHANNEL_1, pulse);
            HAL_Delay(10);
        }
    }
}

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
    if (huart->Instance == USART3)
    {
        rs_rx_flag = 1;
        rs_rx_len = Size;
        HAL_UARTEx_ReceiveToIdle_IT(&huart3, rx_buf, 32);
    }
}
