#include "TaskProcessCom.h"
#include "IIC_Hardware.h"
#include "IIC_Software.h"
#include "IIC2_Software.h"
#include "ch32x035_usbpd.h"
#include "tmos.h"
//#include "sgm452.h"
//#include "sgm832.h"



#define KEY_ADC_DET                           0x0001
#define CHECK_TOUCH_INT_EVT                   0x0002
#define USB_HID_DEBUG_EVT                     0x0004
#define RESET_TOUCH_CHIP_EVT                  0x0008
#define CHECK_USB_CONNECT_EVT                 0x0010
#define HDMI_RX_DET                           0x0020
#define LED_DET                               0x0040
#define TEMPTURE_DET                          0x0080
#define POWER_DET                             0x0100

static UINT16 Task_ProcessEvent( UINT8 task_id, UINT16 events );
static UINT8 TaskID = INVALID_TASK_ID;

UINT8 GT_CMD_WR;
UINT8 GT_CMD_RD;

CHIP_TYPE ChipType;
BOOL enable_INT_irq;
BOOL enable_ESD_check;
//UINT8 HearBeatCheckTimer;
//BOOL GioInterruptFlag;
UINT8 ShareBuf[10];
//UINT8 NoTouchTimer = 0;
UINT8 DeviceMode  = DEVICE_MODE_MOUSE;
//UINT8 BleDeviceMode  = DEVICE_MODE_MULTITOUCH;
//UINT16 Press_Flag,Press_Flag_Bak0, Press_Flag_Bak1, Press_Flag_Bak2,Press_Flag_Bak3;
UINT8 Uart1IdleTime = 0;
//BOOL BleReportFirst = FALSE;
BOOL ReleaseFlag = 0;


//adc key
//extern u32 timems;


void (*TouchProc)(void);


#ifdef UART_ENABLE
UINT8 TxBuff[16];
UINT8 RxBuff[10];
BOOL UartReportPosEn = TRUE;
volatile BOOL UsbReportPosEn = FALSE;
BOOL BleReportPosEn = TRUE;
#endif



void TIM4_Init( uint16_t arr, uint16_t psc )
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure = { 0 };
    NVIC_InitTypeDef NVIC_InitStructure = { 0 };

    /* Enable Timer4 Clock */
    RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM3, ENABLE );

    /* Initialize Timer4 */
    TIM_TimeBaseStructure.TIM_Period = arr;
    TIM_TimeBaseStructure.TIM_Prescaler = psc;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit( TIM4, &TIM_TimeBaseStructure );

    TIM_ITConfig( TIM4, TIM_IT_Update, ENABLE );

    NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init( &NVIC_InitStructure );

    TIM_Cmd( TIM4, ENABLE );
}

/* Interrupt Function Declaration */
void TIM4_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void TIM4_IRQHandler( void )
{
    if( TIM_GetITStatus( TIM4, TIM_IT_Update ) != RESET )
    {
        //g_u16_timer_out++;
        //video_process();
        TIM_ClearITPendingBit( TIM4, TIM_IT_Update );
    }
}


//TIM3_Init(1, SystemCoreClock / 10000 - 1 );
void TIM3_Init( uint16_t arr, uint16_t psc )
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure = { 0 };
    NVIC_InitTypeDef NVIC_InitStructure = { 0 };

    /* Enable Timer3 Clock */
    RCC_APB1PeriphClockCmd( RCC_APB1Periph_TIM3, ENABLE );

    /* Initialize Timer3 */
    TIM_TimeBaseStructure.TIM_Period = arr;
    TIM_TimeBaseStructure.TIM_Prescaler = psc;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit( TIM3, &TIM_TimeBaseStructure );

    TIM_ITConfig( TIM3, TIM_IT_Update, ENABLE );

    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init( &NVIC_InitStructure );

    /* Enable Timer3 */
    TIM_Cmd( TIM3, ENABLE );
}

/* Interrupt Function Declaration */
void TIM3_IRQHandler(void) __attribute__((interrupt("WCH-Interrupt-fast")));
void TIM3_IRQHandler( void )
{
    if( TIM_GetITStatus( TIM3, TIM_IT_Update ) != RESET )
    {
        //timems++;
        //video_process(); //sea debug
        ms933x_media_service();
        //key_service();
        //AdcKeyScanAndProcess();
        //osd_service();
        //printf("timems= %d\n",timems);
        //g_u16_timer_out++; //sea
        TIM_ClearITPendingBit( TIM3, TIM_IT_Update );
    }
}


void IICTouchInit()
{
  //娉ㄥ唽浜嬩欢澶勭悊鍑芥暟
  TaskID = TMOS_ProcessEventRegister(Task_ProcessEvent);
  //澶嶄綅鑺墖
  InitChipStartTask();
  //GioInterruptFlag = FALSE;
  //TIM3_Init( 100-1, 9600-1 ); //10ms

  //TIM3_Init( 500-1, 9600-1 ); //50ms

//  TIM3_Init( 40, SystemCoreClock / 1018 - 1 );
}

static UINT16 Task_ProcessEvent( UINT8 task_id, UINT16 events )
{
    if(events & HDMI_RX_DET)
    {
      //USART1_ReceData();
      //printf("[EVENT]: HDMI_RX_DET\n");
      //video_process();
      //ms933x_media_service();
      events ^= HDMI_RX_DET;
      tmos_start_task(task_id, HDMI_RX_DET, PERIO_10ms ); //sea
      //fill_picture(0xFF);
      goto OUT_FUMC;
    }

    //TEMPTURE_DET task
    if(events & TEMPTURE_DET)
    {
      //printf("[EVENT]: TEMPTURE_DET\n");
      //sgm452_T6710_Proc();
      //sgm452_T1826_Proc();
      events ^= TEMPTURE_DET;
      tmos_start_task(task_id, TEMPTURE_DET, PERIO_500ms );
      goto OUT_FUMC;
    }

    //POWER_DET task
    if(events & POWER_DET)
    {
      //printf("[EVENT]: POWER_DET\n");
      //sgm832_Power_detect_Proc_Bl();
      //sgm832_Power_detect_Proc_Sys();
      events ^= POWER_DET;
      tmos_start_task(task_id, POWER_DET, PERIO_800ms );
      goto OUT_FUMC;
    }

    if(events & RESET_TOUCH_CHIP_EVT)
    {
      printf("[EVENT]: RESET_TOUCH_CHIP_EVT\n");
      //InitChipStartTask();
      events ^= RESET_TOUCH_CHIP_EVT;
      //tmos_set_event(task_id, RESET_TOUCH_CHIP_EVT);
      goto OUT_FUMC;
    }

    return 0;

OUT_FUMC:

    return  events;
}


void InitChipStartTask()
{
  enable_INT_irq = FALSE;
  enable_ESD_check = FALSE;
  //tmos_stop_task(TaskID, CHECK_TOUCH_INT_EVT);

//ms1826a chip setting
  //MS1826A_IIC_Init();
  //printf("[task]: MS1826A iic start.\n");

//ms933x chip setting
  //libs auto write iic address 0xB2, no need set it
  ms933x_init();
  //tmos_start_task(TaskID, HDMI_RX_DET, PERIO_10ms );
  //printf("[task]: ms933x start.\n");

//sgm452 chip setting
  //sgm452_GPIO_I2cChannel_Init();
  //tmos_start_task(TaskID, TEMPTURE_DET, PERIO_500ms );
  //printf("[task]: SGM452 start.\n");

//sgm832 chip setting
  //sgm832_GPIO_I2cChannel_Init();
  //tmos_start_task(TaskID, POWER_DET, PERIO_800ms );
  //printf("[task]: SGM832 start.\n");

//keyADC setting
  //KeyADC_GPIO_Init();
  //tmos_start_task(TaskID, KEY_ADC_DET, PERIO_50ms );
  //printf("[GPIO]: KeyADC start.\n");

//Led setting
  //LED_GPIO_Init();
//CH444G setting
  //CH444G_GPIO_Init();
  //printf("[GPIO]: LED & CH444G start.\n");

  Delay_Ms(80);

  //(200);
  {
    ChipType = CHIP_TYPE_MS1826A;
    //sea fix ms1826A_TaskStart();
    //printf("[task]: Ms1826a start.\n");
    //printf("[IICADDR]: IIC Address:%x\n", GT_CMD_WR);
    //tmos_start_task(TaskID, CHECK_TOUCH_INT_EVT, 2 );
  }

  //EXTI_InitTypeDef EXTI_InitStructure = { 0 };

  /* Enable GPIOB clock */
  //RCC_APB2PeriphClockCmd( RCC_APB2Periph_AFIO, ENABLE );
  //GPIO_EXTILineConfig( GPIO_PortSourceGPIOA, GPIO_PinSource1 );
  //EXTI_InitStructure.EXTI_Line = EXTI_Line1;
  //EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Event;
  //EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
  //EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  //EXTI_Init( &EXTI_InitStructure );

  //EXTI->INTENR |= EXTI_INTENR_MR1;

   //enable_INT_irq = TRUE;
   //enable_ESD_check = TRUE;
}

//fix todo list:鏌ヨ鎵�鏈夌殑iic 璁惧鍦板潃
BOOL SearchAddress( UINT8 num )
{
  u8 ret1=0;
  u8 ret2=0;
  while(--num)
  {
    //#define
    u8 GT_CMD_WR = 0x78;
    //if(Check_I2C_Address(GT_CMD_WR)) //fix
    ret1 = IIC_Check_Address(GT_CMD_WR);
    ret2 = IIC2_Check_Address(GT_CMD_WR);
    if(ret1 && ret2)
    {
        //printf("[IICADDR]: IIC Address Success:%x\n", GT_CMD_WR);
        return TRUE;
    }
    else
    {
      if(!ret1)
      {
        //printf("[IICADDR]: IIC Address fail !!!");
      }
      if(!ret2)
      {
        //printf("[IICADDR]: IIC2 Address fail !!!");
      }
      return FALSE;

    }
    // if(IIC2_Check_Address(GT_CMD_WR))
    // {
    //     printf("[IICADDR]: IIC2 Address Success:%x\n", GT_CMD_WR);
    //     return TRUE;
    // }
  }
  return FALSE;
}

// static void SetTouchEvent()
// {
//   if(ChipType == CHIP_TYPE_MS1826A)
//   {
//      ms1826A_SetIntEvent();
//   }
// }

//void CheckTouchInt()
//{
//    if( (EXTI_GetFlagStatus( EXTI_Line1 ) != RESET) && (!DisableDigiterInterface))
//    {
//        if(enable_INT_irq)
//        {
//          // if(!IsUsbBusy())
//          // {
//          //   SetTouchEvent();
//          // }
//        }
//
//        EXTI_ClearFlag( EXTI_Line1 );
//
//        return;
//    }
//}

#if 1//UART_ENABLE
// void USART4_SendData(PUINT8 txbuf, UINT16 length)
// {
//     UINT8 TxCnt = 0;

//     while(TxCnt < length)
//     {
//         //printf("TxCnt:%d\r\n", TxCnt);
//         USART_SendData(USART2, txbuf[TxCnt++]);
//         while(USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET)
//         {
//             /* waiting for sending finish */
//         }
//     //        while(USART_GetFlagStatus(USART2, USART_FLAG_RXNE) == RESET)
//     //        {
//     //            /* waiting for receiving finish */
//     //        }
//     //        RxBuffer[RxCnt++] = (USART_ReceiveData(USART2));

//         //printf("TxCnt:%d\r\n", TxCnt);
//     }
// }

void CheckUsbStatus()
{
  // if(DeviceMode == DEVICE_MODE_MULTITOUCH)
  // {
  //     USBFS_EP1_Buf[0] = 0;
  //     USBFSD->UEP1_TX_LEN  = 0;
  //     USBFSD->UEP1_CTRL_H = (USBFSD->UEP1_CTRL_H & ~ USBFS_UEP_T_RES_MASK) | USBFS_UEP_T_RES_ACK;
  // }
  // else
  // {
  //     USBFSD->UEP3_TX_LEN  = 0;
  //     USBFSD->UEP3_CTRL_H = (USBFSD->UEP3_CTRL_H & ~ USBFS_UEP_T_RES_MASK) | USBFS_UEP_T_RES_ACK;
  // }
  // fill_picture(0x0F);
}

__attribute__((section(".highcode")))
UINT16 PosReverse(UINT16 pos, UINT16 res)
{
  if(pos < res)
    pos = res - pos;
  else
    pos  = 0;

  return pos;
}



#endif
