/*******************************************************************************
 * @file    power_ctrl.h
 * @brief   Power Management and Control Functions
 * @author  Charles KWON <charleskwon@medithings.co.kr>
 * @date    2025-01-30
 * @copyright (c) 2025 Medithings Inc. All rights reserved.
 *
 * @details Power on/off control, sleep mode, button state machine.
 ******************************************************************************/

#ifndef POWER_CTRL_H
#define POWER_CTRL_H

#include <stdint.h>
#include <stdbool.h>
#include "bsp.h"
#include "main.h"

/*==============================================================================
 * CONSTANTS
 *============================================================================*/

#define POWER_HOLD          NRF_GPIO_PIN_MAP(0,8)
#define POWER_BUTTON        NRF_GPIO_PIN_MAP(1,8)

#define POWER_ON_DELAY      5       /* Power button polling interval (ms) */
#define POWER_OFF_DELAY     3000    /* Power-off sequence delay (ms) */
#define POWER_RESET_DELAY   2000    /* System reset delay (ms) */

/*==============================================================================
 * EXTERNAL VARIABLES
 *============================================================================*/

extern volatile bool processing;
extern volatile bool power_state;
extern bool power_off_duble_prohibit;
extern bool device_status;
extern bool device_reset;
extern uint16_t cnt_s;
extern uint8_t m_reset_status;

/* External state flags */
extern bool go_device_power_off;
extern bool go_sleep_mode_enter;
extern bool go_NVIC_SystemReset;

/*==============================================================================
 * FUNCTION PROTOTYPES
 *============================================================================*/

/**
 * @brief Initialize power control timers
 */
void power_ctrl_timers_init(void);

/**
 * @brief Start power-on delay timer
 */
void power_ctrl_timers_start(void);

/**
 * @brief Initiate device power-off sequence
 */
void device_power_off(void);

/**
 * @brief Enter sleep mode
 */
void sleep_mode_enter(void);

/**
 * @brief Power button timer callback - power-on state machine
 * @param p_context Unused timer context
 */
void power_button_handler(void * p_context);

/**
 * @brief Power-off timer callback
 * @param p_context Unused timer context
 */
void power_off_timeout_handler(void * p_context);

/**
 * @brief Power management timer callback
 * @param p_context Unused timer context
 */
void pm_timeout_handler(void * p_context);

/**
 * @brief Control main power state
 * @param device_power_st ON or OFF
 */
void power_control_set(on_off_cont_t device_power_st);

/**
 * @brief Handle BSP button events
 * @param event BSP event type
 */
void power_bsp_event_handler(bsp_event_t event);

#endif /* POWER_CTRL_H */
