/*
 * communication_protocol.c
 *
 *  Created on: 2024年5月18日
 *      Author: 34509
 */

#include <communication_protocol.h>
#include "uart_dev.h"
#include "inflash.h"

SL_Mppt_Scan_Broadcast_pack g_Scan_Broadcast_pack = {
        .start_Flag = "SL",
        .address = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
        .function_Code = SL_Function_Code_Broadcast_Scan,
        .check_Bit_H = 0x36,
        .check_Bit_L = 0xE6,
        .end_Flag = 0x16,
};

/* 读取串口数据时用该数组解析 */
static uint8_t uart_buff[50]={0x00};


/**
  * @brief  校验算法
  * @param
  * @retval
  */
uint16_t CheckFunc(uint8_t *arr_buff, uint8_t len)
{
    uint16_t crc = 0xFFFF;
    uint16_t i, j;
    for (j = 0; j < len; ++j) {
        crc = crc ^ (*arr_buff++);
        for (i = 0; i < 8; ++i) {
            if ((crc&0x0001) > 0) {
                crc = crc >> 1;
                crc = crc ^ 0xa001;
            }
            else {
                crc = crc >> 1;
            }
        }
    }
    return crc;
}

/**
  * @brief  检测485总线是否繁忙
  * @param
  * @retval 1 繁忙
  *         0 空闲
  */
uint8_t Check_485_bus_busy(device_handle device)
{
    uart_device_info *device_info = (uart_device_info *)device;
    if((!device) || (!device_info->init))
       return 0;

    USART_ITConfig(device_info->uart_index, USART_IT_RXNE, ENABLE);

    uint16_t num_ago = ring_queue_length(device);
    Delay_Ms(2);
    uint16_t num_now = ring_queue_length(device);

    USART_ITConfig(device_info->uart_index, USART_IT_RXNE, DISABLE);

    if (num_now == num_ago) {
        return 0;
    }
    return 1;
}

/**
  * @brief  匹配起始标志"SL"
  * @param  start_buff  起始标志
  * @retval 1 匹配成功
  *         0 匹配失败
  */
static int Match_Startflag(uint8_t start_buff[2])
{
    if ((start_buff[0] == g_slConfigInfo.start_Flag[0]) && \
            (start_buff[1] == g_slConfigInfo.start_Flag[1])) {
        return 1;
    }
    return 0;
}

/**
  * @brief  读取串口数据
  * @param  uart_handle 串口句柄
  * @param  buff        缓冲区
  * @param  buff_size   缓冲区长度
  * @retval
  */
static int uart_read_climate_pack(device_handle uart_handle,uint8_t *buff, uint32_t buff_size)
{


}

/**
  * @brief  处理一条消息
  * @param
  * @retval
  */
void FRT_MsgHandler(device_handle device, uint8_t *pMsg, uint32_t MsgLen)
{
    SL_Mppt_Recv_pack *pack = (SL_Mppt_Recv_pack *)pMsg;

}

/**
  * @brief  读取并解析串口数据
  * @param
  * @retval
  */
void read_and_process_uart_data(device_handle device)
{
//    printf("ring_queue_length = %d \n", ring_queue_length(device));
    if (ring_queue_length(device) > 10) {
        memset(uart_buff, 0, sizeof(uart_buff));
        int ret = uart_read_climate_pack(device, uart_buff, sizeof(uart_buff));
        if(ret > 0){
            FRT_MsgHandler(device, uart_buff, ret);
        }
    }
}