/*******************************************************************************
 TEST medi50  Dec 23
 //=========power_control.c====================
 *******************************************************************************
 *
 * [Module overview]
 * Device power sequence manager (power on / off / sleep).
 *
 * [Power-on flow]
 *   device_activated()
 *     -> Start power_loop timer -> completes immediately (no sensor init needed)
 *     -> Sensor (IMU) is handled by imu_read_direct() at measurement time
 *
 * [Sleep mode]
 *   device_sleep_mode()
 *     -> Clear processing flag
 *
 * [Reactivation]
 *   device_reactivated()
 *     -> Re-init I2C then restart power sequence from the beginning
 *
 * [Timer]
 *   Single-shot app_timer, calls power_loop at 20ms interval
 *
 ******************************************************************************/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "main.h"
#include "power_control.h"
#include "nrf_delay.h"


#include "nrf_log.h"
#include "app_timer.h"
#include "debug_print.h"
#include "i2c_manager.h"


/* Single-shot timer instance for power sequence */
APP_TIMER_DEF(m_power_timer_id);

/* Power sequence state machine timer interval (20ms) */
// 2025-12-08 change to #define POWER_LOOP_INTERVAL 30 -> 20
#define POWER_LOOP_INTERVAL 20

/* Power sequence current step (0: I2C init, 1: reserved, 2: complete) */
static uint8_t p_order;

/* Power sequence lock flag (true = sequence in progress) */
bool lock_check = false;

/**
 * @brief Enter device sleep mode
 *
 * @return 0 (always succeeds)
 */
int device_sleep_mode(void)
{
	int rc = 0;
	nrf_delay_ms(2);
	DBG_PRINTF("Device_Sleep_Mode OK!\r\n");
	nrf_delay_ms(10);
	return rc;
}


/**
 * @brief Power on device (start power sequence)
 *
 * Resets the sequence step to 0, sets the lock flag, and starts
 * the timer to drive the power_loop() state machine.
 *
 * @return 0 (always succeeds)
 */
int device_activated(void)
{
	int rc = 0;
	p_order = 0;           /* State machine start step (Step 0: I2C init) */
	lock_check =true;      /* Lock: power sequence in progress */
	power_timer_start();   /* First power_loop() call after 20ms */

	return rc;
}

/**
 * @brief Power-up sequence state machine
 *
 * Executes hardware initialization steps
 * Called by app_timer at POWER_LOOP_INTERVAL (20ms)
 *
 * Sequence:
 *   0: I2C init
 *   1: (reserved)
 *   2: Complete
 */
/*
 * Power sequence state machine (20ms single-shot timer callback).
 *
 * [Execution flow]
 *   1) Timer callback entry -> stop timer (single-shot)
 *   2) Execute init step for current p_order
 *   3) If p_order < 2, advance to next step and restart timer
 *   4) If p_order == 2, power sequence complete
 *
 * No sensor init needed -- imu_read_direct() handles it per measurement.
 */
void power_loop(void *p_context)
{
    UNUSED_PARAMETER(p_context);

    power_timer_stop();   /* Stop current timer (single-shot, manual restart needed) */

    /* No sensor init needed -- imu_read_direct() handles it per measurement */
    /* Add switch(p_order) here if future power sequence steps are needed */
    p_order = 2;

    /* Advance to next step or finish */
    /* Advance to next step or finish sequence */
    if (p_order < 2)
	{
        p_order++;             /* Move to next step */
        power_timer_start();   /* Execute next step after 20ms */
    }
	else
	{
        /* Power sequence fully complete */
        DBG_PRINTF("[PWR] Device Activated OK!\r\n");
    }
}


/**
 * @brief Reactivate device (on wake from sleep)
 *
 * Re-initializes I2C and restarts the power sequence from the beginning.
 * Called when waking from sleep mode.
 *
 * @return 0 (always succeeds)
 */
int device_reactivated(void)
{
	int rc = 0;
	sw_i2c_init_once();    /* Re-initialize I2C bus */
	nrf_delay_ms(10);      /* Stabilization delay */
	lock_check = true;     /* Lock: power sequence in progress */
	p_order = 0;           /* Restart state machine from Step 0 */
	power_timer_start();   /* Start power_loop() after 20ms */
	return rc;
}

/**
 * @brief Start power sequence timer
 *
 * Single-shot mode; calls power_loop() after POWER_LOOP_INTERVAL (20ms).
 */
void power_timer_start(void)
{
	APP_ERROR_CHECK(app_timer_start(m_power_timer_id, APP_TIMER_TICKS(POWER_LOOP_INTERVAL), NULL));
}


/**
 * @brief Stop power sequence timer
 */
void power_timer_stop(void)
{
	APP_ERROR_CHECK(app_timer_stop(m_power_timer_id));

}


/**
 * @brief Initialize power sequence timer (call once at app startup)
 *
 * Creates a single-shot timer with power_loop() as callback.
 * Must manually restart via power_timer_start() after each step.
 */
void power_timer_init(void)  //active start
{
 APP_ERROR_CHECK(app_timer_create(&m_power_timer_id, APP_TIMER_MODE_SINGLE_SHOT, power_loop));

	// 2025-12-08 change to  APP_TIMER_MODE_REPEATED mode
	//APP_ERROR_CHECK(app_timer_create(&m_power_timer_id,  APP_TIMER_MODE_REPEATED, power_loop));


}
