/******************************************************/
/* Copyright (C) 2008 Arch Rock Corporation 2008      */
/* License Agreement: refer to LICENSE.txt            */
/*                                                    */
/******************************************************/

/*!
@file lcd.c

Simple program to drive the RAVEN LCD

*/
#include <sys/svcs.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include "uart.h"
#include "raven.h"

//! timer descripter, used to hold the return value of timer()
static int16_t g_timerfd;

//! Maximum LED blink window, in units of 200ms epochs
#define LEDMAX 8

//! Current LED blink count, in units of 200ms epochs, initialized to 0
static uint8_t LED_cnt = 0;

//! Current LED blink limit, in units of 200ms epochs, initialized to 0
static uint8_t LED_limit = 0;

//! timer_handler 
//! 
//! @brief this function is invoked when the timer is fired
//!
//! @param event equals to SETITIMER as this is a setitimer() callback
//! @param cbargs passes \em resource back from setitimer() call
//! @param context passes \em context back from setitimer() call
//!
//! @return none
//!
void timer_handler(event_t event, void * cbargs, void * context)
{  
  LED_cnt++;
  if (LED_cnt < LED_limit) { 
    if (LED_cnt & 1) led_on();	/* toggle till we hit limit */
    else led_off();
  } else {
    led_off();			/* then silent */
  }

  if (LED_cnt >= LEDMAX) {
    LED_cnt = 0;		/* reset count */
    LED_limit = LED_limit + 2;	/* bump the limit */
    if (LED_limit > LEDMAX) LED_limit=2;
  }
}

//! __main 
//!
//! @brief this function is invoked after boot
//!
//! @param event equals MAIN as this is a boot event
//! @param cbargs is NULL for boot event
//! @param context is NULL for boot event
//!
//! @return none
//!
void __main(event_t event, void * cbargs, void * context)
{
  char hello[] = "ROCKRAVEN";
  itimerval_t timevalue;
  uart_init();

  print_msg(hello, sizeof(hello));

 // Create a 200 ms peroidic timer to fire timer_handler.
  g_timerfd = timer();
  if (g_timerfd > 0){
	timevalue.it_interval.tv_sec  = 0;
	timevalue.it_interval.tv_usec = 200000;
	timevalue.it_value.tv_sec  = 0;
	timevalue.it_value.tv_usec = 0;
	setitimer(g_timerfd, &timevalue, NULL, timer_handler, NULL, NULL);
  }
};
