/*********************************************************************
 * INCLUDES
 */
#include "ble_comm.h"
#include "app_flash.h"
#include "app_safe.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "hal_led.h"

static void app_safe_Process(void)
{
	static uint8_t cnt =0;
	if(mBackup.ErrStartCnt >0){
		cnt++;
		if(cnt >=60){//一分钟后清空标志位
			mBackup.ErrStartCnt =0;
		  if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_Power,"save ErrStartCnt fail");
			DEBUG_LOG("clear mBackup.ErrorStartFlag\n");
		}
	}

	if(mBackup.RestartCnt > 1){
		 
		 char buff[40]={0};
		 memset(buff,0,sizeof(buff));
		 if(mFlash.isHost){
		    sprintf(buff,"left shoes restart:%d",mBackup.RestartCnt);
		 }else{
    		sprintf(buff,"right shoes restart:%d",mBackup.RestartCnt);	 
		 }
		 if(0 == Except_TxError(EXCEPT_Power,(const char*)buff)){
			  mBackup.RestartCnt =0;
		 }
	}
}

//恢复出厂设置
static void cb_BLE_RESTSETTING(void* handle)
{
	Flash_DeleteAllInfor();
	Flash_DeleteAllStep();
	Flash_DeleteAllBackup();

	BLE_Client_Rx_t* target = handle;
	uint8_t cmd = target->pDat[0];

	BLE_Host_Tx_Send(0,BLE_RESTSETTING,&cmd,1);

	nrf_delay_ms(500);

	NVIC_SystemReset();
}

static void app_CONNTED_LED_Process(void){
	static uint8_t lastconeted =0;
	static uint8_t BlinkTime =0;
	static uint8_t BlinkfLAG =0;
	uint8_t nowconeted =0;
	if(mFlash.isHost)
	    nowconeted = host_isconnect();
  else
	    nowconeted = slave_isconnect();
	
//	DEBUG_LOG("mFlash.isHost %d,nowconeted:%d,\n",mFlash.isHost,nowconeted);
	if(nowconeted != lastconeted){
		 lastconeted = nowconeted;
		 if(nowconeted){
			 BlinkfLAG =1;
			 BlinkTime =0;
			 DEBUG_LOG("COLOR_PURPLE\r\n");
//			 LED_Start(LED_LRCHECK,COLOR_CYAN);
			 LED_Start(LED_LRCHECK,COLOR_PURPLE);
			 Process_SetHoldOn(app_CONNTED_LED_Process,1);
		 }
		 else{
			 BlinkfLAG =0;
			 BlinkTime =0;
			 Process_SetHoldOn(app_CONNTED_LED_Process,0);
			 LED_Stop(LED_LRCHECK);
		 }
	}
	
	if(BlinkfLAG){BlinkTime++;
		if(BlinkTime <=30){
			 BlinkfLAG =1;
		}
		else{
			 BlinkfLAG =0;
			 BlinkTime =0;
			 LED_Stop(LED_LRCHECK);
		}
	}
}

static uint8_t update_led =0;

static void cb_BLE_LEDON_PURPLE(void* handle)
{
	 update_led = 1;
}

static void app_BLE_LEDON_PURPLE_process(void){
	 if(update_led){update_led=0;
		  LED_Start(LED_ONPURPLE,COLOR_PURPLE);
		  Process_SetHoldOn(app_BLE_LEDON_PURPLE_process,1);
	 }
	 
	 static uint32_t Lastch =0;
	 uint32_t ch = nrf_gpio_pin_read(PIN_CHARGING);
	 
	 if(!ch && Lastch != ch){
		 LED_Stop(LED_ONPURPLE);
		 Process_SetHoldOn(app_BLE_LEDON_PURPLE_process,0);
	 }
	 Lastch = ch;
}

void app_safe_Init(void)
{
	mBackup.RestartCnt++;
	
	Process_Start(1000,"app_safe",app_safe_Process);
	
//	Process_Start(100,"app_CONNTED_LED",app_CONNTED_LED_Process);
	
	BLE_Client_Rx_Regist(BLE_RESTSETTING,cb_BLE_RESTSETTING);
	
	//常亮紫色灯
	BLE_Client_Rx_Regist(BLE_LEDON_PURPLE,cb_BLE_LEDON_PURPLE);
	Process_Start(100,"app_BLE_LEDON_PURPLE",app_BLE_LEDON_PURPLE_process);
	
}

 





