#include "dev_rs485.h"
#include "hdl_led.h"

static void rs485_rxpin_init(void)
{
    LL_PERIPH_WE(LL_PERIPH_GPIO);

    stc_gpio_init_t stcGpioInit={0};
    
    GPIO_StructInit(&stcGpioInit);
    
    stcGpioInit.u16PinDir = PIN_DIR_OUT;

    stcGpioInit.u16PinDrv = PIN_HIGH_DRV;

    stcGpioInit.u16PullUp = PIN_PU_ON;
    
    stcGpioInit.u16PinAttr = PIN_ATTR_DIGITAL;

    (void)GPIO_Init(RS485_CTRL_PORT, RS485_CTRL_PIN, &stcGpioInit);

    LL_PERIPH_WP(LL_PERIPH_GPIO);
}

static void rs485_rxpin_enable(void)
{
    GPIO_ResetPins(RS485_CTRL_PORT,RS485_CTRL_PIN);
}

static void rs485_rxpin_disable(void)
{
   GPIO_SetPins(RS485_CTRL_PORT,RS485_CTRL_PIN);
}


int dev_rs485_init(void)
{
    hdl_com_uart_init();

    rs485_rxpin_init();
    
    rs485_rxpin_enable();

    return 0;
}

int dev_rs485_rx_register(dev_rs485_cb_t fnCallback)
{
    hdl_com_uart_rx_register((com_rx_callback)fnCallback);

    return 0;
}

void dev_rs485_send(uint8_t* buf, int len)
{
    rs485_rxpin_disable();
    
    hdl_com_uart_send(buf, len);
    
    rs485_rxpin_enable();
    
}

int dev_rs485_deinit(void)
{
    return 0;
}
