#include "app_power.h"
#include "nrf_gpio.h"
#include "usr_config.h"
#include "bsp_time.h"
#include "system.h"
#include "hal_mt.h"
#include "hal_battery.h"
#include "hal_charge.h"
#include "hal_ble_client.h"
#include "nrf_delay.h"
#include "app_flash.h"
#include "bsp_wdt.h"
#include "app_timer.h"
#include "system.h"
#include "bsp_pwm.h"
#include "app_client.h"
#include "hal_led.h"
#include "lsm6ds3tr_c.h"
#include "app_math.h"
#include "bll_imu.h"
#include "drv_qma7981.h"

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

/********************** 函数声明区 *************************/
void PWR_Off(void)
{
	  LED_Close_Enforce();
	
		bll_imu_close();
    drv_qma_power_off();
		nrf_gpio_pin_write(PIN_MT_EN,0);
		nrf_delay_ms(200);
	  ADC_Disable();
	  ADC_RemovePinChannel(PIN_CHARGING,PIN_CHARGING_CHANNEL);
		nrf_gpio_cfg_sense_input(PIN_CHARGING, NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_SENSE_HIGH);//IO 
		uint32_t err_code = sd_power_system_off();
	  DEBUG_LOG("power off...BAT:%d,ERR:%d\n",GetBatteryPersent(),err_code);
    //APP_ERROR_CHECK(err_code);
}

static void PWR_Process(void)
{
	if((0 == GetBatteryPersent() && hal_charge_Getstate()==BLE_CHARGE_PULLOUT)){
		DEBUG_LOG("BatteryPersent:%d\n",GetBatteryPersent());
		DEBUG_LOG("power off...\n");
		//保存数据到flash
		if(Flash_SaveStep() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_Power,"save step fail");
		
		extern battercb_t battery_record;
		extern void printbatter_cb(battercb_t *c,unsigned char *buff);
		memcpy(&mFlash.mbattercb_t,&battery_record,sizeof(battercb_t));
		
		mBackup.RestartCnt =0;
		if(Flash_SaveBackup() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_Power,"pwr save backup fail");
		
		if(Flash_SaveInfomation() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_Power,"pwr save information fail");
		MT_Run(1000);
		feed_watchdog();
		for(uint8_t temp = 0;temp < 10; temp++){
				app_client_DataUpdate_Send();
				nrf_delay_ms(100);
		}
		PWR_Off();
	}
}

void PWR_Init(void)
{
	Process_Start(30000,"PWR",PWR_Process);
}


