#include "usr_config.h"
#include "app_Authen.h"
#include "system.h"
#include "hal_ble_client.h"
#include "hal_ble_host.h"
#include "bsp_time.h"
#include "ble_comm.h"
#include "bll_imu.h"
#include "app_flash.h"
#include "app_Authen.h"
#include "app_connect_manage.h"

/************************ º¯ÊýÉùÃ÷ ***********************************/

static uint8_t Phoneflag =0;
static uint32_t tim =0;

static void cb_BLE_Client_BLE_AUTHEN(void* handle){
	BLE_Client_Rx_t* target = handle;
	Phoneflag = target->pDat[0];
	tim = TIME_GetTicks();
}

static BLE_Client_Tx_t m_Client_BLE_AUTHEN = {
	.n = 10,
	.t = 100,
};

static void app_Authen_Process(void){
	static uint8_t state =0;
	bll_imu_data_t data= {0};
	static uint8_t LIFE_SIGNAL =0;
	uint8_t buf =0;
	
  switch(state){
		case 0:
			    if(slave_isconnect()){
						 if(BLE_RIGHT_CONNTED == app_conneted_getRight()){
								tim = TIME_GetTicks();
								state =1;
						 }
					}
					else{
						 if(host_isconnect()){
							  buf =1;
								BLE_Host_Tx_Send(&m_Client_BLE_AUTHEN,BLE_AUTHEN,&buf,1);
						 }
					}
			    break;
	  case 1:
			    if(1 == Phoneflag){
						state = 2;
						Phoneflag =0;
					}
					else if(TIME_GetTicks() -tim >= 3000){
						if(slave_isconnect()){
							 slave_disconnect();
						}
						else {
							state =3;
							Phoneflag =0;
						}
					}
			    break;
		case 2:
			    if(!slave_isconnect()){
						 state =3;
					}
					else {
						  int16_t data_size = 0;
		
							data_size = bll_imu_get_data_num(BLL_IMU_DIR_FRONT);
							
							if(data_size > 0){
								
									bll_imu_get_data(BLL_IMU_DIR_FRONT, data_size -1 , &data);
									
									int32_t acc_norm = (data.acc[0] * data.acc[0] +data.acc[1] * data.acc[1] + data.acc[2] * data.acc[2]);
									
									if(abs(acc_norm - 4194304) < 362144 && data.acc[2] > 1536){
										LIFE_SIGNAL = 3;
									}
									else if(LIFE_SIGNAL > 0)LIFE_SIGNAL --;
									
									if(abs(acc_norm - 4194304) < 362144 && data.acc[2] < -1024)LIFE_SIGNAL = 0;
									
									if(LIFE_SIGNAL > 0){
										 buf =3;
										 BLE_Client_Tx_Send(&m_Client_BLE_AUTHEN,BLE_AUTHEN,&buf,1);
										 state =3;
									}

							}
					}
			    break;
		case 3:
			    state =0;
					Phoneflag =0;
			    break;
		default:state=0;Phoneflag =0;break;
			   
	}
}

void app_Authen_Init(void)
{
	Process_Start(100,"app_charge",app_Authen_Process);
	BLE_Client_Rx_Regist(BLE_AUTHEN,cb_BLE_Client_BLE_AUTHEN);
}


