/*
 * watchdog.c
 *
 *  Created on: Feb 24, 2026
 *      Author: tad
 */

#include "ES28.h"
#include "uart.h"
#include <stdio.h>

// A few magic numbers for the watchdog (from the datasheet)

#define KEY_ACCESS 0x00005555
#define KEY_UPDATE 0x0000AAAA
#define KEY_START  0x0000CCCC

int main( void ) {

    uart2_init();

    printf( "Hello dog world\r\n");

    // Use the built-in blue user button as a proxy
    // for petting the dog.
    RCC->IOPENR |= RCC_IOPENR_GPIOCEN;
    GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODE13_Msk) | (GPIO_INPUT << GPIO_MODER_MODE13_Pos);

    // The watchdog is always accessible, so no need to turn any clocks on for it.

    // First, unlock the watchdog registers by
    // writing a special value to the key register
    IWDG->KR = KEY_ACCESS;

    // Now set up the prescaler - the watchdog clock
    // runs at 32KHz.  We'll set up a 1ms tick.
    // We can only update when the PVU status bit is clear.
    while( IWDG->SR & IWDG_SR_PVU );
    IWDG->PR = 0b011;

    // The reload register is 12 bits (4096) we'll
    // set it to 4000 so that we need to pet the
    // dog at least once every 4 seconds (a somewhat
    // needy dog.)
    // We can only update when the RVU status bit is clear
    while( IWDG->SR & IWDG_SR_RVU );
    IWDG->RLR = 4000;

    // Wake the dog...
    IWDG->KR = KEY_START;

    // Pet once, so the first countdown also runs from IWDG_RLR (4 seconds)
    IWDG->KR = KEY_UPDATE;

    // Now, loop and pet the dog whenever the
    // blue user button is pushed.
    while(1){
        if ( (GPIOC->IDR & GPIO_IDR_ID13) == 0 ){
            // Pet the dog
            IWDG->KR = KEY_UPDATE;
            printf( "Nice Doggy\r\n");
            delay_ms(100);  // be nice to the terminal.
        }
    }
    return 0;
}
