#ifndef _PROTO_MODBUS_LIB_H_
#define _PROTO_MODBUS_LIB_H_

#include "main.h"

#define MODBUS_DEFAULT_ID  (0x01)
#define MODBUS_SENDBUF_LEN (2048U)

#define U16_DATA_L      (0)//低16位
#define U16_DATA_H      (1)//高16位

#define BIG_ENDIAN      (0)//大端序
#define LITTLE_ENDIAN   (1)//小端序

#define MODBUS_TCP_PROTO_TYPE (0x0000) 


typedef struct {
  u8 send_buffer[MODBUS_SENDBUF_LEN];
  u16 len;
}modbus_communication_send_buf_t;

typedef struct
{
    u8 id;                          /*ModbusID*/
    u8 func;                        /*功能号*/
    u16 start_addr;                 /*起始地址*/
    u16 reg_number;                 /*寄存器数量*/
    u8 *write_data_addr;            /*写入寄存器数据地址*/
}modbus_analysis_data_t;

typedef enum
{
    ModbusErrorCode_Success         = 0x00,
    ModbusErrorCode_IllegalFunction = 0x01,
    ModbusErrorCode_IllegalAddr     = 0x02,
    ModbusErrorCode_IllegalData     = 0x03,
    ModbusErrorCode_DeviceBusy      = 0x06
}modbus_error_code_e;

typedef struct proto_Modbus_t proto_Modbus_t;
struct proto_Modbus_t
{
    u8 id;
    u16 (*data_read)(u16);                          /*Modbus读数据*/
    modbus_error_code_e (*data_write)(u16,u16);     /*Modbus写数据*/
    void (*init)(void);                             /*初始化函数*/
    void (*task)(void);                             /*任务函数*/
    void (*data_analysis)(u8 *,u16,void *);         /*数据解析*/
};


u16 float_to_u16(float float_data,u8 h_l);
u16 u32_to_u16(u32 u32_Data,u8 h_l);
u32 u8_to_u32(u8 *p_u8_Data,u8 endian);
u16 u8_to_u16(u8 *p_u8_Data,u8 endian);

void u32_to_u8(u32 u32_Data,u8 *p_data,u8 endian);
void u16_to_u8(u16 u16_Data,u8 *p_data,u8 endian);

u32 u32_endian_conv(u32 data);
u16 u16_endian_conv(u16 data);

u16 modbus_lib_crc16(u8 *p_data, u16 len);
void modbus_lib_data_read(u8 Id,u16 Addr,u16 Num,void (*UsartSendBuffer)(u8 *,u16 ));
void modbus_lib_multiple_data_write(u8 ID,u16 Addr,u16 Num,u16 *Data,void (*UsartSendBuffer)(u8 *,u16 ));
void modbus_lib_only_data_write(u8 ID,u16 Addr,u16 Value,void (*UsartSendBuffer)(u8 *,u16 ));
u8 modbus_lib_analysis(modbus_analysis_data_t *p_modbus, u8 *p_data, u16 len);

#endif
