/*
 * np_app_pm.c
 *
 *  Created on: July 14, 2016
 *      Author: Alan.Lin
 *
 *  Copyright: NexPack Ltd.
 */

#include <stdint.h>

uint8_t run_the_loop = 0;
uint8_t flag_on_lpm = 0;
uint8_t developer_lpm4_setting = 0;	//record the developer setting about the lpm4
uint8_t wakeup_run_loop_flag = 0;
#if 0
extern void np_api_enter_lpm4_work();// for developer
extern void np_api_exit_lpm4_work(); // for developer

void np_function_set_run_the_loop(uint8_t t_data){
	run_the_loop = t_data;
}

uint8_t np_function_get_run_the_loop(void){
	return run_the_loop;
}

/*
 * Description: set auto enter lpm0 mode
 * Parameter: null
 * Return: null
 *
 * Author: Coody.Liu
 *
 * Copyright: NexPack.Ltd
 */
void np_function_lpm0_automode_set(void) {
	np_driver_lpm0_automode_set();
}

/*
 * Description: exit auto exit lpm0 mode
 * Parameter: null
 * Return: null
 *
 * Author: Coody.Liu
 *
 * Copyright: NexPack.Ltd
 */
void np_function_lpm0_automode_clear(void) {
	np_driver_lpm0_automode_clear();
}

void np_function_enter_lpm4_work(void){
	np_api_enter_lpm4_work();
	np_driver_spi_function_close();
	np_driver_enable_pin13_io_interrupt();
}

void np_function_exit_lpm4_work(void){
	np_driver_spi_function_open();
	np_api_exit_lpm4_work();
	//np_driver_disalbe_pin13_io_interrupt();
}

uint8_t flag_lpm4_enter = 0;
/*
 * Description: run the power save mode loop
 * Parameter: null
 * Return: null
 *
 * Author: Coody.Liu
 *
 * Copyright: NexPack.Ltd
 */
void np_function_pm_loop(void) {
	if(wakeup_run_loop_flag){
		return;
	}

	if((np_function_pm_mode_get() & LPM_4)){
		//v1_0_3--1   please reference the version.txt
		if((spi_status != SPI_BUSY)&&(np_app_spi_is_aviable())
			&&(spi_post_buf.message_num == 0)&&(spi_get_buf.message_num == 0)){

			flag_on_lpm = LPM_4;
			np_function_enter_lpm4_work();
			if(wakeup_run_loop_flag){
				np_function_exit_lpm4_work();
			}else{//bug: if io interrupt wakeup on here, the module will no way to process.
				__bis_SR_register(LPM4_bits);
			}

			flag_on_lpm = LPM_NONE;
		}
	}else if (np_function_pm_mode_get() & LPM_0){
		flag_on_lpm = LPM_0;
		__bis_SR_register(LPM0_bits);
		flag_on_lpm = LPM_NONE;
	}
}

/*
 * Description: set auto enter lpm0 mode
 * Parameter: null
 * Return: null
 *
 * Author: Coody.Liu
 *
 * Copyright: NexPack.Ltd
 */
void np_function_lpm4_automode_set(void) {
	np_driver_lpm4_automode_set();
}

/*
 * Description: exit auto exit lpm0 mode
 * Parameter: null
 * Return: null
 *
 * Author: Coody.Liu
 *
 * Copyright: NexPack.Ltd
 */
void np_function_lpm4_automode_clear(void) {
	np_driver_lpm4_automode_clear();
}


/*
 * Description: get the mode of auto lpm mode (lpm0/lpm4)
 * Parameter: null
 * Return: null
 *
 * Author: Coody.Liu
 *
 * Copyright: NexPack.Ltd
 */
uint8_t np_function_pm_mode_get(void) {
	return np_driver_lpm_mode_get();
}

uint8_t np_function_get_lpm_status(void){
	return flag_on_lpm;
}

#endif
