#include "archinc.h"
#include "eventq.h"
#include "watchdog.h"
#include "cli.h"

#define WDEN    0x01
#define WDRESET 0x02
#define WDTOF   0x04
#define WDINT   0x08

// TODO: implement real watchdog functionality by using timer or eventq

static void handleEvent(void);

/* ISR declaration */
DECLARE_ISR(watchdogIsr);

#ifdef CONFIG_TOOLCHAIN_IAR
#pragma inline
#endif
static INLINE_KEYWORD void watchdogReset(void)
{
  // do watchdog feed sequence with interrupts disabled
  IRQ_DISABLE();
  WDFEED = (lpc210x_reg)0xAA;
  WDFEED = (lpc210x_reg)0x55;
  IRQ_ENABLE();
}

void watchdogKick(void)
{
  eventqPut(WATCHDOG_KICK);
}

ISR_FUNCTION(watchdogIsr)
{
}

static int resetHandler(int argc, char * argv[], int flags)
{
  watchdogReset();
  while(1); // wait for reset
  return 0; // should never get here
}

static void handleEvent(void)
{
  watchdogReset();
}

int watchdogInit(void) 
{
  cliRegisterCommand("reset", resetHandler, "reset - resets the processor via watchdog");

  // enable us to kick the 'dog
  eventqRegisterHandler(WATCHDOG_KICK, handleEvent);

  // initialize watchdog counter to 1/2 max value
  WDTC  = (lpc210x_reg)0x80000000;

  // set mode to reset
  WDMOD = (lpc210x_reg)(WDEN | WDRESET);

  // enable watchdog timer!
  watchdogReset();

  return 0;
}
