#include "rs485_driver.h"
#include <string.h>

static UART_HandleTypeDef *g_huart_485 = NULL;
static GPIO_TypeDef* g_de_re_port = NULL;
static uint16_t g_de_re_pin = 0;
volatile uint8_t g_rs485_tx_busy = 0;

void RS485_Init(UART_HandleTypeDef *huart, GPIO_TypeDef* de_re_port, uint16_t de_re_pin)
{
    g_huart_485 = huart;
    g_de_re_port = de_re_port;
    g_de_re_pin = de_re_pin;
    g_rs485_tx_busy = 0;
    HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_RESET); // 初始为接收模式
}

HAL_StatusTypeDef RS485_SendData(uint8_t *pData, uint16_t Size)
{
    HAL_StatusTypeDef ret;

    if (g_rs485_tx_busy)
    {
        return HAL_BUSY;
    }

    g_rs485_tx_busy = 1;
    HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_SET); // 设置为发送模式
    ret = HAL_UART_Transmit(g_huart_485, pData, Size, 0xffff);
    HAL_GPIO_WritePin(g_de_re_port, g_de_re_pin, GPIO_PIN_RESET); // 切换回接收模式
    g_rs485_tx_busy = 0;

    return ret;
}
