#include "base.h"
// #define USE_USB_HS
extern osSemaphoreId_t elog_dma_lockHandle;
int _write(int fd, char *ch, int len)
{
    //  HAL_UART_Transmit(&huart1, (uint8_t *)ch, len, 0xFFFF);
    if (osOK == osSemaphoreAcquire(elog_dma_lockHandle, osWaitForever))
    {
        HAL_UART_Transmit_DMA(&huart2, (uint8_t *)ch, len);
    }
    return len;
}

extern struct led led_0;
// extern struct led led_1;

extern struct ds1302 ds1302;
extern SD_HandleTypeDef hsd;

extern volatile uint16_t aa ;
extern volatile uint16_t bb ;
extern volatile uint16_t cc ;
extern volatile uint16_t dd ;
// extern osTimerId_t myTimer01Handle;

// uint8_t send_buf[8] = {0x01,0x03,0x00,0x00,0x00,0x04,0x44,0x09};
// uint8_t rcv_buf[14] = {0};
// uint8_t rcv_buf_2[13] = {0};

double voltage = 0.0;
double H2S_concentration = 0.0;
float  pH_value = 0.0;
float  temperature = 0.0;
float   H2S = 0.0;
uint8_t pH_send_buf[8] = {0x01,0x03,0x00,0x00,0x00,0x02,0xC4,0x0B};
uint8_t pH_rcv_buf[9] = {0};
uint8_t measuring_flag = 0;
uint8_t pH_measuring_flag = 0;
uint8_t pH_send_flag = 0;
uint8_t pH_rcv_flag = 0;
uint8_t pH_measure_ok = 8;
uint8_t voltage_measure_ok = 0;
uint64_t timebase;
uint8_t  measure_step = 0;
float result[3] ; /* H2S  T  pH */

void MY_INIT( )
{
    // // 使能 3243   供电
    max3243_enable();
    uart2_power_enable();
    uart3_power_enable();
    uart4_power_enable();
    uart6_power_enable();

    HAL_TIM_Base_Start_IT(&htim2);
    __HAL_TIM_ENABLE_IT(&htim2, TIM_IT_UPDATE);					// 使能定时器更新中断
}


 void measureTimer_Callback(void *argument)
{
    log_i("measure timer begin ....  " );
    led_set_state( &led_0, LED_STATE_FLICKER_QUICK );
    voltage = 0.0;
    H2S = 0.0;
    memset(pH_rcv_buf, 0, 9 ); 
    memset(result, 0, 12 ); 
    timebase = osKernelGetTickCount();
    measuring_flag = 1;
    pH_send_flag = 0;
    pH_rcv_flag = 0;
    pH_measuring_flag = 0;
    pH_measure_ok = 0;
    voltage_measure_ok = 0;
    measure_step = 0;
}



 void pHTask(void *argument)
{
    for (;;)
    { 
 
            // log_i(" ph... pH_measure_ok  %d", pH_measure_ok); 
        if ( pH_measure_ok ==0  && pH_send_flag == 0)
        {
            log_i(" send stage ... "); 
            HAL_UART_Receive_DMA(&huart3, pH_rcv_buf, 9 );
            timebase = osKernelGetTickCount();
            max3160_485_send_mode();
            pH_send_flag = 1;
            HAL_UART_Transmit_DMA(&huart3, pH_send_buf, 8 );
        }
        if ( pH_measure_ok ==0  && pH_send_flag == 1  && pH_rcv_flag == 0 )
        {
            uint64_t time_ticks = osKernelGetTickCount() ;
            // log_i( " time_ticks :%d " , time_ticks);
            if ( (time_ticks - timebase ) >400) 
            {
                log_i( " pH timeout ..... "  );
                measureTimer_Callback(NULL);   
            }
        }
        if ( pH_measure_ok ==0  && pH_rcv_flag == 1  )
        {
            log_i( " pH ok ..... "  );
            pH_measure_ok = 1;
        }
        if ( pH_measure_ok ==1     )
        {
            ;
        }
        osDelay(200); 
    }
}


void voltageTask(void *argument)
{
    for (;;)
    { 
        if (voltage_measure_ok ==0)
        {
            voltage = ads1115_get_voltage_val(hi2c1 ,0x01, CONFIG_REG_H, CONFIG_REG_L);
            log_w( " voltage :%.6f    " , voltage);
            voltage_measure_ok = 1;
        }
        osDelay(20); 
    }
}



void measureTask(void *argument)
{
    for (;;)
    { 
    /* convert */
    if ( measure_step==0 && pH_measure_ok == 1 && voltage_measure_ok == 1  )
    {
        /** TODO  ...*/
        result[1] = (pH_rcv_buf[5]*256 + pH_rcv_buf[6])/10.0;  /* Temp /10.0*/
        result[2]  = (pH_rcv_buf[3]*256 + pH_rcv_buf[4])/100.0;  /* pH /10.0*/
        // log_i( " temperature :%.6f   pH :  %.6f " , temperature ,pH_value);
        get_h2s_2(&H2S_concentration , voltage, result[1]);
        result[0]  = H2S_concentration;   
        led_set_state(&led_0, LED_STATE_FLICKER_SLOW);
        // log_i( "H2S :  %.6f    " ,H2S);
        measure_step++;
    }

    /* 写modbus数据 */
    if ( measure_step==1 )
    {
        /*   写modbus   临界区 */
        log_i( "-------> H2S: %.6f  TEMP: %.6f pH: %.6f   ", result[0]  , result[1], result[2]);
        // 数据全反过来   40db851f41a80000402771f2 -》 f2712740......//
 
        Modbus_Set_HoldingBuff( (uint8_t *)result,  12,   0);
 
        measure_step++;
        /*pH 686 : 40db851f 41a80000  402771f2  */
    }
    /* 输出数据 uart1 */
    if ( measure_step==2 ) 
    {
        log_i( "send to screen...    " );
        int ret= HAL_UART_Transmit_IT(&huart1, (uint8_t *)result, 12);
        if( ret==HAL_OK)
            log_i( "send ok..    " );

        measure_step++;
    }
    if ( measure_step==3 ) 
    {
        osDelay(2);
    }
    osDelay(20);
    }
}



static void Default_Task_Init()
{
    measuring_flag = 0;
    if (0==Led_Port()){
        log_i("Led Port int Ok .... ");
    }
    led_set_state(&led_0, LED_STATE_FLICKER_SLOW);

    if (0==ds1302_port())
    {
        log_i("ds1302 init Ok .... ");
    }
    if ( 0== ads1115_test(hi2c1))
    {
        log_i("ads1115 init Ok .... ");
    }

    // my_ads1115.init();

    // // SD_Test();
    // // Test_Port();

    Modbus_Port( );
    RTOS_Port( );
    extern osTimerId_t measureTimerHandle;
    osTimerStart( measureTimerHandle, 3000);


    // MX_USB_DEVICE_Init();
 
}


void StartDefaultTask(void *argument)
{
    Init_Logger();
    log_i("System is initiating.... ");

    Default_Task_Init();

    // MX_USB_DEVICE_Init();  /* USB 初始化需要写在任务中 */

    for (;;)
    {
        // log_i("looo... ");
        //  CDC_Transmit_HS(send_buf, 8);
        osDelay(1000 );

        // log_i(" aa bb  cc  dd : %d   %d  %d   %d ",aa, bb,cc, dd);
    }
}

void USART1_IRQHandler(void)
{
    if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_TC) != RESET)
    {
        log_i(" uart1  tc..... ");
        // osSemaphoreRelease(elog_dma_lockHandle);
        huart1.gState = HAL_UART_STATE_READY;
        __HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_TC);
    }

    HAL_UART_IRQHandler(&huart1);
}

void USART2_IRQHandler(void)
{
    if (__HAL_UART_GET_FLAG(&huart2, UART_FLAG_TC) != RESET)
    {
        // HAL_UART_Transmit(&huart3, (uint8_t*)"tddddd", 6,0xFF);
        // extern osSemaphoreId_t elog_dma_lockHandle;
        osSemaphoreRelease(elog_dma_lockHandle);
        huart2.gState = HAL_UART_STATE_READY;
        __HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_TC);
    }

    HAL_UART_IRQHandler(&huart2);
}

void USART3_IRQHandler(void)
{

    //   if (__HAL_UART_GET_FLAG(&huart3, UART_FLAG_TC) != RESET)
    //   {
    //         max3160_485_receive_mode();
    //         // huart3.gState = HAL_UART_STATE_READY;
    //         __HAL_UART_CLEAR_FLAG(&huart3, UART_FLAG_TC);
    //   }


    //   if (__HAL_UART_GET_FLAG(&huart3, UART_FLAG_IDLE) != RESET)
    //   {
    //     log_i("....huart3 IDLE....");
    //     __HAL_UART_CLEAR_FLAG(&huart3, UART_FLAG_IDLE);
    //   }

    HAL_UART_IRQHandler(&huart3);
}

void UART4_IRQHandler(void)
{
//     if (__HAL_UART_GET_FLAG(&huart4,  UART_IT_TXE) ==SET )
//   {
//         log_i("....huart4 tc callback....");
//     //  HAL_GPIO_WritePin(DE485_GPIO_Port, DE485_Pin, SET);
//     // HAL_GPIO_WritePin(HDPLX_GPIO_Port,HDPLX_Pin, RESET);
//     __HAL_UART_CLEAR_FLAG(&huart4, UART_IT_TXE);
//   }

    HAL_UART_IRQHandler(&huart4);
}

// void USART6_IRQHandler(void)
// {

//     HAL_UART_IRQHandler(&huart6);
// }

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == huart2.Instance)
    {
        log_i("....huart2 rx callback....");
        __HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_RXNE);
    }

    if (huart->Instance == huart3.Instance)
    {
        // measure_step++;
        pH_rcv_flag = 1;
        // log_i("....huart3 rx callback....  " );
        // log_i( "rcvbuf : %d  %d %d %d  %d %d", rcv_buf_2[0], rcv_buf_2[1], rcv_buf_2[2],rcv_buf_2[3], rcv_buf_2[4], rcv_buf_2[5]);
        __HAL_UART_CLEAR_FLAG(&huart3, UART_FLAG_RXNE);
    }


}


void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{

  if (huart->Instance == huart3.Instance)
  {
    /* 拷贝数据 到菜单 */
    log_i("huart3 log dma idle....");
    __HAL_UART_CLEAR_IDLEFLAG(&huart3);
//  __HAL_UART_CLEAR_FLAG(&huart3, UART_FLAG_IDLE);
  }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{

  if (huart->Instance == huart3.Instance)
  {
    max3160_485_receive_mode();
    // huart3.gState = HAL_UART_STATE_READY;
    __HAL_UART_CLEAR_FLAG(&huart3, UART_FLAG_TC);
  }



//   if (huart->Instance == huart6.Instance)
//   {
//     HAL_UART_Transmit(&huart3, (uint8_t*)"tccccc", 6,0xFF);
//     // HAL_GPIO_TogglePin(GRN_GPIO_Port,GRN_Pin);
//     // extern osSemaphoreId_t elog_dma_lockHandle;
//     osSemaphoreRelease(elog_dma_lockHandle);
//     __HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_TC);
//   }
}

 
void TIM2_IRQHandler(void)
{
    if(__HAL_TIM_GET_FLAG(&htim2, TIM_FLAG_UPDATE))			// 更新中断标记被置位
    {
  
    }
    HAL_TIM_IRQHandler( &htim2 );
}
 

void Soft_Reboot()
{
    __set_FAULTMASK(1);//关闭总中断
    NVIC_SystemReset();//请求单片机重启

}


void SD_Test()
{
    BSP_SD_Init();
    // printf_sdcard_info( );
    if (Init_FatFas_Mount())
    {
        log_i("SD mount failure .. ");
    }
    else
    {
        log_i(" SD mount success.. ");
    }
    // extern SD_HandleTypeDef hsd;

    if ( open_file( "0:aa.txt") == 0)
    {
        write_file( (char*)"data\r\n", 6 );
        // close_file();
    }
    else
    {
        log_e(" open file failure .. ");
    }    
}

/*
    log_i("test uart2 .... ");
    HAL_GPIO_WritePin(UART_EN_GPIO_Port,UART_EN_Pin, SET);
    HAL_UART_Transmit(&huart2, (uint8_t*)"usart2\r\n", 8,0xFF);

    HAL_UART_Transmit_IT(&huart4, send_buf, 8 );
    // while ( __HAL_UART_GET_FLAG(&huart4, UART_FLAG_TC) == RESET);
    // HAL_UART_Receive_IT(&huart4, rcv_buf_2, 13 );

    // HAL_GPIO_WritePin(UART_EN_GPIO_Port,UART_EN_Pin,RESET);

    log_i("test uart6 485.... ");
    HAL_GPIO_WritePin(R_W_GPIO_Port,R_W_Pin, SET);
    // HAL_UART_Transmit(&huart6, (uint8_t*)"uart66\r\n", 8,0xFF);
    HAL_UART_Transmit_IT(&huart6, send_buf, 8 );
    while ( __HAL_UART_GET_FLAG(&huart6, UART_FLAG_TC) == RESET);
    HAL_GPIO_WritePin(R_W_GPIO_Port,R_W_Pin,RESET);
    HAL_UART_Receive_IT(&huart6, rcv_buf, 13 );


    // log_i("test uart3 3160 232.... ");
    // HAL_GPIO_WritePin(SEL_232_485_GPIO_Port,SEL_232_485_Pin, RESET);
    // HAL_GPIO_WritePin(HDPLX_GPIO_Port,HDPLX_Pin, RESET);
    // // HAL_UART_Transmit(&huart3, (uint8_t*)"uart3160\r\n", 10,0xFF);
    // // HAL_UART_Transmit(&huart3, send_buf, 8,0xFF);
    // HAL_UART_Receive_IT(&huart3, rcv_buf_2, 13 );
    // HAL_UART_Transmit_IT(&huart3, send_buf, 8 );
    // while ( __HAL_UART_GET_FLAG(&huart3, UART_FLAG_TC) == RESET);


    // log_i("test uart3 3160 485.... ");
    // HAL_GPIO_WritePin(SEL_232_485_GPIO_Port,SEL_232_485_Pin, SET);
    // HAL_GPIO_WritePin(DE485_GPIO_Port, DE485_Pin, RESET);
    // HAL_GPIO_WritePin(HDPLX_GPIO_Port,HDPLX_Pin, SET);
    // // HAL_UART_Transmit(&huart3, (uint8_t*)"uart3160\r\n", 10,0xFF);
    // // HAL_UART_Transmit(&huart3, send_buf, 8,0xFF);

    // // HAL_UART_Receive_IT(&huart3, rcv_buf_2, 13 );
    // HAL_UART_Transmit_IT(&huart3, send_buf, 8 );
    // while ( __HAL_UART_GET_FLAG(&huart3, UART_FLAG_TC) == RESET);
    //     HAL_GPIO_WritePin(DE485_GPIO_Port, DE485_Pin, SET);
    //   HAL_GPIO_WritePin(HDPLX_GPIO_Port,HDPLX_Pin, RESET);  
    // // HAL_UART_Receive_IT (&huart3, rcv_buf_2,2 );
    // if ( HAL_UART_Receive (&huart3, rcv_buf_2, 2 ,2000) ==HAL_OK) 
    // {
    //     log_i("rcv ok");
    // }

    // log_i( "rcvbuf : %d  %d %d", rcv_buf_2[0], rcv_buf_2[1], rcv_buf_2[2]);

    // HAL_GPIO_WritePin(DE485_GPIO_Port, DE485_Pin, SET);
    // HAL_GPIO_WritePin(HDPLX_GPIO_Port,HDPLX_Pin, RESET);


*/

// void measureTimer_Callback(void *argument)
// {
//     log_i("measure timer begin ....  " );
//     // led_set_state( &led_0, LED_STATE_FLICKER_QUICK );
//     // voltage = 0.0;
//     // H2S = 0.0;
//     // memset(pH_rcv_buf, 0, 9 ); 
//     // memset(result, 0, 12 ); 
//     // timebase = osKernelGetTickCount();
//     // measuring_flag = 1;
//     // pH_send_flag = 0;
//     // pH_rcv_flag = 0;
//     // pH_measuring_flag = 0;
//     // pH_measure_ok = 0;
//     // voltage_measure_ok = 0;
//     // measure_step = 0;
// }

// void pH_Task(void *argument)
// {
//     max3160_485_receive_mode();
//   for(;;)
//   {

//     // if ( pH_measure_ok ==0  && pH_send_flag == 0)
//     // {
//     //     log_i(" send stage ... "); 
//     //     HAL_UART_Receive_DMA(&huart3, pH_rcv_buf, 9 );
//     //     timebase = osKernelGetTickCount();
//     //     max3160_485_send_mode();
//     //     pH_send_flag = 1;
//     //     HAL_UART_Transmit_DMA(&huart3, pH_send_buf, 8 );
//     // }
//     // if ( pH_measure_ok ==0  && pH_send_flag == 1  && pH_rcv_flag == 0 )
//     // {
//     //     uint64_t time_ticks = osKernelGetTickCount() ;
//     //     // log_i( " time_ticks :%d " , time_ticks);
//     //     if ( (time_ticks - timebase ) >400) 
//     //     {
//     //         log_i( " pH timeout ..... "  );
//     //         measureTimer_Callback(NULL);   
//     //     }
//     // }
//     // if ( pH_measure_ok ==0  && pH_rcv_flag == 1  )
//     // {
//     //     log_i( " pH ok ..... "  );
//     //     pH_measure_ok = 1;
//     // }
//     // if ( pH_measure_ok ==1     )
//     // {
//     //     ;
//     // }
//     osDelay(50);
//   }
// }


// void Measure_Task(void *argument)
// {
//   for (;;)
//   { 
//     // /* convert */
//     // if ( measure_step==0 && pH_measure_ok == 1 && voltage_measure_ok == 1  )
//     // {
//     //     /** TODO  ...*/
//     //     result[1] = (pH_rcv_buf[5]*256 + pH_rcv_buf[6])/10.0;  /* Temp /10.0*/
//     //     result[2]  = (pH_rcv_buf[3]*256 + pH_rcv_buf[4])/100.0;  /* pH /10.0*/
//     //     // log_i( " temperature :%.6f   pH :  %.6f " , temperature ,pH_value);
//     //     get_h2s_2(&H2S_concentration , voltage, result[1]);
//     //     result[0]  = H2S_concentration;   
//     //     led_set_state(&led_0, LED_STATE_FLICKER_SLOW);
//     //     // log_i( "H2S :  %.6f    " ,H2S);
//     //     measure_step++;
//     // }

//     // /* 写modbus数据 */
//     // if ( measure_step==1 )
//     // {
//     //     /*   写modbus   临界区 */
//     //     log_i( "-------> H2S: %.6f  TEMP: %.6f pH: %.6f   ", result[0]  , result[1], result[2]);
//     //     // 数据全反过来   40db851f41a80000402771f2 -》 f2712740......//
 
//     //     Modbus_Set_HoldingBuff( (uint8_t *)result,  12,   0);
 
//     //     measure_step++;
//     //     /*pH 686 : 40db851f 41a80000  402771f2  */
//     // }
//     // /* 输出数据 uart1 */
//     // if ( measure_step==2 ) 
//     // {
//     //     log_i( "send to screen...    " );
//     //     int ret= HAL_UART_Transmit_IT(&huart1, (uint8_t *)result, 12);
//     //     if( ret==HAL_OK)
//     //         log_i( "send ok..    " );

//     //     measure_step++;
//     // }
//     // if ( measure_step==3 ) 
//     // {
//     //     osDelay(2);
//     // }
//     osDelay(20);
 
//   }
// }