#include "hal_mt.h"
#include "nrf_gpio.h"
#include "usr_config.h"
#include "bsp_time.h"
#include "system.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "app_flash.h"

#define MT_DUTY_CYCLE_H		8
#define MT_DUTY_CYCLE_L		2

/************************ 函数声明 ***********************************/
void MT_process(void);

/************************ 变量 ***********************************/

/************************ 函数定义 ***********************************/
static uint32_t mt_time = 0;
void MT_Run(uint32_t tim)
{
	DEBUG_LOG("MT MT_Run:%d \n",tim);
	if(tim>0){
		mt_time = tim;
		nrf_gpio_pin_write(PIN_MT_EN,1);
		Process_SetHoldOn(MT_process,1);
	}
}

bool MT_GetState(void)
{
        if( 0 != mt_time)return true;
        return false;
}    

void gpio_mt_run(uint32_t tim)
{
	MT_Run(tim);
}

void MT_process(void)
{
	
}

void MT_TimerCounter(void* t)
{
	static uint32_t low_level = 0;
	static uint32_t hight_level = 0;
	
	if(mt_time>0)
	{
		if(mt_time >=HeartTime_Interval)
		{
			mt_time -=HeartTime_Interval;
			

			if(hight_level != MT_DUTY_CYCLE_H)
			{
				nrf_gpio_pin_write(PIN_MT_EN,1);
				hight_level++;
			}
			else if(low_level != MT_DUTY_CYCLE_L)
			{
				low_level++;
				nrf_gpio_pin_write(PIN_MT_EN,0);
			}
			
			if(hight_level == MT_DUTY_CYCLE_H && low_level == MT_DUTY_CYCLE_L)
			{
				low_level = 0;
				hight_level = 0;
			}
			
		}
		else 
		{
			mt_time=0;
			low_level = 0;
			hight_level = 0;
		}
		
		if(mt_time==0)
		{
			nrf_gpio_pin_write(PIN_MT_EN,0);
			Process_SetHoldOn(MT_process,0);
		}
		
	}
}

void cb_BLE_Client_R_SHOCK(void* handle)
{
	BLE_Client_Rx_t *target = handle;
	
	uint16_t t = ((uint16_t)(target->pDat[0])<<8) | ((uint16_t)(target->pDat[1])<<0);
	
	if(mFlash.isHost)
	{
		if(target->pDat[2]==1){
			MT_Run(t);
		}
		else if(target->pDat[2]==0){
			MT_Run(t);
			BLE_Host_Tx_Send(0,BLE_SHOCK,target->pDat,target->datLen);
		}
		else{
			BLE_Host_Tx_Send(0,BLE_SHOCK,target->pDat,target->datLen);
		}
	}
	else
	{
		if((target->pDat[2]==2)||(target->pDat[2]==0))
		{
			MT_Run(t);
		}
	}

	DEBUG_LOG("MT RUN:%d \n",t);
}

void MT_Init(void)
{
	nrf_gpio_cfg_output(PIN_MT_EN);		nrf_gpio_pin_write(PIN_MT_EN,0); MT_Run(100);
	TIME_Regist(MT_TimerCounter);
	Process_Start(0,"MT",MT_process);
	Process_SetHoldOn(MT_process,1);
	BLE_Client_Rx_Regist(BLE_SHOCK,cb_BLE_Client_R_SHOCK);
}


