#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 "app_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_ble_uart0.h"
#include "hal_led.h"
#include "lsm6ds3tr_c.h"
#include "hal_ser_imu_mode_manage.h"
#include "app_math.h"

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

/********************** 函数声明区 *************************/
void PWR_Off(void)
{
		UART0_unInit(PIN_TXD_BLE,PIN_RXD_BLE);
	  LED_Close_Enforce();
		hal_ser_imu_mode_manage_set_required(HAL_SER_IMU_MODE_MANAGE_STANDBY, HAL_SER_IMU_MODE_MANAGE_IMU_MODE_OFF);
		hal_ser_imu_mode_manage_set_required(HAL_SER_IMU_MODE_MANAGE_NORMAL, HAL_SER_IMU_MODE_MANAGE_IMU_MODE_OFF);
		hal_ser_imu_mode_manage_set_required(HAL_SER_IMU_MODE_MANAGE_SELF_CHECK, HAL_SER_IMU_MODE_MANAGE_IMU_MODE_OFF);
		hal_ser_imu_mode_manage_set_required(HAL_SER_IMU_MODE_MANAGE_GAME, HAL_SER_IMU_MODE_MANAGE_IMU_MODE_OFF);
		hal_ser_imu_mode_manage_set_required(HAL_SER_IMU_MODE_MANAGE_REALSTEP, HAL_SER_IMU_MODE_MANAGE_IMU_MODE_OFF);
		drv_lsm_power_off();
		drv_qmc6310_power_off();
	  
		nrf_gpio_pin_write(PIN_MT_EN,0);
		nrf_delay_ms(200);
		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();
	  SEGGER_RTT_printf(0,"power off...BAT:%d,ERR:%d\n",GetBatteryPersent(),err_code);
    //APP_ERROR_CHECK(err_code);
}

static void PWR_Process(void)
{
	if((0 == GetBatteryPersent() && app_charge_Getstate()==BLE_CHARGE_PULLOUT)){
		SEGGER_RTT_printf(0,"BatteryPersent:%d\n",GetBatteryPersent());
		SEGGER_RTT_printf(0,"power off...\n");
		//保存数据到flash
		if(Flash_SaveStep() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_Power,"save step fail");
		if(Flash_SaveInfomation() != ZONE_OP_SUCCESS)Except_TxError(EXCEPT_Power,"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(10000,"PWR_Process",PWR_Process);
}


