#ifndef __SC6__H
#define __SC6__H

#ifdef __cplusplus
	extern "C" {
#endif

#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"
#include "usart.h"

#include "elog.h"

#include <string.h>
#include "bsp_uart.h"
 
#define SC6_USE_MAX485 0
#define SC6_USE_MAX3160_232 0
#define SC6_USE_MAX3160_485 1
 
#define  SC6_RESUMED_Buf_Size   (12) 
#define  SC6_PAUSEED_Buf_Size   (11) 
#define  SC6_Result_Buf_Size    (286 ) 
#define  SC6_Rcv_Buf_Size       (2*SC6_Result_Buf_Size +2*SC6_RESUMED_Buf_Size ) 
#define  SC6_Command_Number       2

static void SC6_MAX3160_232(void) 
{
    HAL_GPIO_WritePin(SEL_232_485_GPIO_Port,SEL_232_485_Pin, RESET);
    HAL_GPIO_WritePin(HDPLX_GPIO_Port,HDPLX_Pin, RESET);
}

typedef enum 
{
	SC6_Event_Ready ,
	SC6_Event_Test,
	SC6_Event_Test_OK  ,
	SC6_Event_Get_Data,
	SC6_Event_Check_Data  ,
} Module_SC6_Event_TypeDef;

typedef enum 
{
    SC6_State_Waiting,
    SC6_State_Test,
	SC6_State_Test_Data_Getting,
	SC6_State_Test_OK,
	SC6_State_Ready,
    SC6_State_Start,
    SC6_State_Start_Trans,
    SC6_State_Data_Getting,
    SC6_State_Check_Data,
    SC6_State_OK,
	SC6_State_Stop ,
	SC6_State_Timeout ,
	SC6_State_Error   ,
} Module_SC6_State_TypeDef;

extern UART_HELPER_TypeDef *SC6_uart_helper;
typedef struct 
{
    int (*init)(void);
    void (*port)(void);
    int (*test)(void);
    void (*start)(void);
    void (*stop)(void);
    osMessageQueueId_t cmdQueue;  // 队列可选

    volatile Module_SC6_State_TypeDef state; 
    uint8_t data_ok;                 /* 接收数据完整可以处理 */

    uint8_t result_buf[1024];
    uint16_t size_received;

    uint64_t  timebase_ticks;
    uint64_t  timeout_ticks;
    uint8_t  event_flag;

    uint8_t	SC6_sn_buf[4];
    uint8_t SC6_Result_Buf[ SC6_Rcv_Buf_Size ];
    uint8_t SC6_Data_Buf[ SC6_Rcv_Buf_Size ];
	uint16_t index_SC6_LPT;  // 记录出现开始标记的位置

}SC6_TypeDef;

extern SC6_TypeDef sc6 ;

int SC6_Init( void );
void SC6_Task( void);
void SC6_Port( void);
int SC6_Test( );
void SC6_Start( );
void SC6_Stop( );

void SC6_Set_Sendbuf(   uint8_t * buf, uint16_t size );
void SC6_Set_Rcvbuf(   uint8_t * buf, uint16_t size );
void SC6_Set_Timeout_ms(    uint64_t ms_ticks );
int SC6_Validate(   );


int SC6_Transmit();
int SC6_Receive();

void SC6_Trans_GPIO(void) ;

void SC6_Trans_Cplt_GPIO(void) ;

int SC6_CallBack( SC6_TypeDef *pPH, uint8_t *buf, uint16_t size );

 
 

#ifdef __cplusplus
	}
#endif
#endif


/*
    ph.init();
    ph.port();
    ph.test();

    // uint64_t ticks = osKernelGetTickCount();

    // while ( ph.state != SC6_State_Ready )
    // {
    //     if ( ( osKernelGetTickCount() -ticks) > 5000   )
    //     {
    //         log_e(" pH test error.... %d", ph.state) ;
    //         break;
    //     }
    // }
    osDelay(1000);
    log_w(" pH test ok.... %d", ph.state) ;
*/