#ifndef __PH_H
#define __PH_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 PH_USE_MAX485 0
#define PH_USE_MAX3160_232 0
#define PH_USE_MAX3160_485 1
 
#define  PH_Rcv_Buf_Size   9
#define  PH_Command_Number       1

static void PH_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 
{
  PH_Event_Ready ,
  PH_Event_Test,
  PH_Event_Test_OK  ,
  PH_Event_Get_Data,
  PH_Event_Check_Data  ,
} Module_PH_Event_TypeDef;

typedef enum 
{
  PH_State_Waiting  ,
  PH_State_Test ,
  PH_State_Test_Start ,
  PH_State_Testing ,
  PH_State_Test_OK ,
  PH_State_Ready  ,
  PH_State_Get_DATA  ,
  PH_State_Get_DATA_Wait  ,
  PH_State_Get_DATA_OK,
  PH_Statee_Get_DATA_Check  ,
  PH_State_Stop ,
  PH_State_Timeout ,
  PH_State_Error   ,
} Module_PH_State_TypeDef;

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

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

    uint8_t result_buf[1024];
    uint8_t size_received;

    uint64_t  timebase_ticks;
    uint64_t  timeout_ticks;
    uint8_t  event_flag;

    // uint8_t command_seq ;      /* 命令序号 */
    // uint8_t mode;  /* 0 : normal , 1 : get wavelength ,  2 : get sn  */

    // uint8_t vipersn_buf[15];
    // uint8_t PH_Wavelength_Buf[2][ PH_Rcv_Buf_Size ];
    // uint8_t PH_Data_Buf[2][ PH_Rcv_Buf_Size ];

}PH_TypeDef;

extern PH_TypeDef ph ;

int PH_Init( void );
void PH_Task( void);
void PH_Port( void);
int PH_Test( );
void PH_Start( );
void PH_Stop( );

void PH_Set_Sendbuf(   uint8_t * buf, uint16_t size );
void PH_Set_Rcvbuf(   uint8_t * buf, uint16_t size );
void PH_Set_Timeout_ms(    uint64_t ms_ticks );
int PH_Validate(   );


int PH_Transmit();
int PH_Receive();

void PH_Trans_GPIO(void) ;

void PH_Trans_Cplt_GPIO(void) ;

int PH_CallBack( PH_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 != PH_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) ;
*/