/*******************************************************************************
 * DESCRIPTION   : RCLK watchdog timer driver
 ******************************************************************************/
/******************************************************************************
 * @file          rwdt.c
 * - Version      : 0.014
 * @brief         RCLK Watchdog Timer driver
 * .
 *****************************************************************************/
/******************************************************************************
 * History : DD.MM.YYYY Version  Description
 *         : 29.04.2025 0.01     First Release
 *****************************************************************************/

#include <stdint.h>
#include <wdt.h>
#include <wdt_register.h>
#include <mem_io.h>
#include <intc.h>
#include <intc_id.h>
#include <log.h>

/* Initialization RCLK Watchdog Timer, see 154.1.3 Operation of h/w manual */
void rwdt_init(int start)
{
	uint8_t wdta_val;

    wdta_val = mem_read8(RWDT_RWTCSRA);
    if (((wdta_val & RWTCSRA_TME) != 0) && start) {
        wdta_val &= ~(RWTCSRA_TME);
        mem_write32(RWDT_RWTCSRA, RWTCSRA_UPPER | wdta_val);

        mem_write32(RWDT_RWTCNT, RWTCNT_UPPER | 0x0U);

        wdta_val = mem_read8(RWDT_RWTCSRA);
        wdta_val &= ~(RWTCSRA_WOVF);
	    mem_write32(RWDT_RWTCSRA, RWTCSRA_UPPER | wdta_val);

        /* skip set CKS0, CKS1 */
    }

    do {
        wdta_val = mem_read8(RWDT_RWTCSRA);
    } while ((wdta_val & RWTCSRA_WRFLG) != 0);

    /* start the counting by setting the TME bit in RWTCSRA to 1 */
    /*
    if (start) {
        wdta_val |= RWTCSRA_TME;
        mem_write32(RWDT_RWTCSRA, RWTCSRA_UPPER | wdta_val);
    }
    */
}

/*
void rwdt_update(void)
{
    mem_write32(RWDT_RWTCNT, RWTCNT_UPPER | 0U);
}

// RWTCNT overflow
void rwdt_handler(void)
{
	uint8_t wdta_val;

    wdta_val = mem_read8(RWDT_RWTCSRA);
    if ((wdta_val & RWTCSRA_WOVF) != 0) {
        // it's overflowed.
    }

    // RWTCNT, RWTCSRA, RWTCSRB are initialized.
    // should we run rwdt_init() again?
}
*/

/* Initialization System Watchdog Timer */
void swdt_init(int start)
{
	uint8_t wdta_val;

    wdta_val = mem_read8(SWDT_SWTCSRA);
    if (((wdta_val & RWTCSRA_TME) != 0) && start) {
        wdta_val &= ~(RWTCSRA_TME);
        mem_write32(SWDT_SWTCSRA, RWTCSRA_UPPER | wdta_val);

        mem_write32(SWDT_SWTCNT, RWTCNT_UPPER | 0x0U);

        wdta_val = mem_read8(SWDT_SWTCSRA);
        wdta_val &= ~(RWTCSRA_WOVF);
        mem_write32(SWDT_SWTCSRA, RWTCSRA_UPPER | wdta_val);

        /* skip set CKS0, CKS1 */
    }

    do {
        wdta_val = mem_read8(SWDT_SWTCSRA);
    } while ((wdta_val & RWTCSRA_WRFLG) != 0);

    /* start the counting by setting the TME bit in SWTCSRA to 1 */
    /* do nothing */
}
