/*
 * @Author: mypx
 * @Date: 2025-10-15 16:24:26
 * @LastEditTime: 2025-10-22 08:44:30
 * @LastEditors: mypx mypx_coder@163.com
 * @Description: 
 */
#include "bsp_hmi.h"
#include "usart.h"
#include "rtthread.h"
#include "et_log.h"

struct rt_messagequeue mb_hmi_mq;
static char            mq_pool[MB_HMI_RX_QUEUE_SIZE];

#if (DEBUG_MB_ENABLE == 1)
#define DBG_MB(...) ET_DBG("[MB] " __VA_ARGS__)
#else
#define DBG_MB(...)
#endif


int bsp_mb_hmi_init(void)
{
    MX_USART1_UART_Init();  // used tx
    MX_USART2_UART_Init();  // used rx

    rt_err_t result = rt_mq_init(&mb_hmi_mq, "mb_hmi_mq", mq_pool, 1, MB_HMI_RX_QUEUE_SIZE, RT_IPC_FLAG_FIFO);
    if (result != RT_EOK)
    {
        ET_ERR("mb_hmi mq init failed\n");
        return -1;
    }

    __HAL_UART_ENABLE_IT(&HMI_COM, UART_IT_RXNE);

    return 0;
}

int32_t bsp_hmi_uart_read(uint8_t *buf, uint16_t count, int32_t byte_timeout_ms, void *arg)
{
    UNUSED(arg);
    uint16_t  bytes_read = 0;
    uint8_t   byte;
    rt_tick_t timeout_ticks = rt_tick_from_millisecond(byte_timeout_ms);
    DBG_MB("start read:count:%d, timeout:%d\n", count, byte_timeout_ms);

    while (bytes_read < count)
    {
        rt_err_t result = rt_mq_recv(&mb_hmi_mq, &byte, sizeof(byte), timeout_ticks);
        if (result == RT_EOK)
        {
            DBG_MB("rx: %02X\n", byte);
            buf[bytes_read++] = byte;
        }
        else
        {
            if (bytes_read > 0)
            {
                DBG_MB("Modbus read finished %d\n", bytes_read);
                return bytes_read;
            }
            DBG_MB("HMI read timeout, no data received\n");
            return 0;
        }
    }
    DBG_MB("Actually read:%d, count:%d\r\n", bytes_read, count);

    return bytes_read;
}

int32_t bsp_hmi_uart_write(const uint8_t *buf, uint16_t count, int32_t byte_timeout_ms, void *arg)
{
    UNUSED(arg);
    rt_thread_mdelay(2);
    if (HAL_UART_Transmit(&HMI_COM, buf, count, byte_timeout_ms) == HAL_OK)
    {
        ET_DBG("HMI write:%d", count);
        return count;
    }
    else
    {
        return 0;
    }
}