#include "uart.h"
#include "gd32e23x_usart.h"
#include "gd32e23x_rcu.h"
#include "gd32e23x_gpio.h"
#include "board_config.h"
#include "uart_ring_buffer.h"


void rs485_init(void) {
    /* 使能 GPIOA 和 USART0 时钟 */
    rcu_periph_clock_enable(RS485_GPIO_RCU);
    rcu_periph_clock_enable(RS485_RCU);

    /* 配置 PA2 为 USART0_TX，PA3 为 USART0_RX */
    gpio_af_set(RS485_GPIO_PORT, GPIO_AF_1, RS485_TX_PIN | RS485_RX_PIN );

    gpio_mode_set(RS485_GPIO_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, RS485_TX_PIN | RS485_RX_PIN);
    gpio_output_options_set(RS485_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, RS485_TX_PIN | RS485_RX_PIN);

    // gpio_mode_set(RS485_GPIO_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, RS485_EN_PIN);
    // gpio_output_options_set(RS485_GPIO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, RS485_EN_PIN);

    /* 配置波特率、数据位、停止位等 */
    usart_deinit(RS485_PHY);
    usart_word_length_set(RS485_PHY, USART_WL_8BIT);
    usart_stop_bit_set(RS485_PHY, USART_STB_1BIT);
    usart_parity_config(RS485_PHY, USART_PM_NONE);
    usart_baudrate_set(RS485_PHY, RS485_BAUDRATE);
    usart_receive_config(RS485_PHY, USART_RECEIVE_ENABLE);
    usart_transmit_config(RS485_PHY, USART_TRANSMIT_ENABLE);

    // usart_driver_assertime_config(RS485_PHY, 0x01);
    // usart_driver_deassertime_config(RS485_PHY, 0x10);

    // usart_rs485_driver_enable(RS485_PHY);

    usart_interrupt_enable(RS485_PHY, USART_INT_RBNE);
    // usart_interrupt_enable(RS485_PHY, USART_INT_IDLE);

    nvic_irq_enable(RS485_IRQ, 0);
    
    usart_enable(RS485_PHY);
}

uint32_t rs485_send_byte(uint8_t data) {
    // 等待发送缓冲区空
    while (RESET == usart_flag_get(RS485_PHY, USART_FLAG_TBE));

    // 发送数据
    usart_data_transmit(RS485_PHY, data);

    // 等待发送完成
    while (RESET == usart_flag_get(RS485_PHY, USART_FLAG_TC));

    return 0; // 成功
}

uint32_t rs485_send_str(uint8_t* str, uint16_t len) {
    // 发送数据 - 最优化版本，避免索引变量
    uint8_t* end = str + len;
    while (str < end) {
        // 等待发送缓冲区空
        while (RESET == usart_flag_get(RS485_PHY, USART_FLAG_TBE));
        usart_data_transmit(RS485_PHY, *str++);
    }

    // 等待最后一个字节发送完成（重要！）
    while (RESET == usart_flag_get(RS485_PHY, USART_FLAG_TC));

    return 0; // 成功
}
