/* flaneth - flash and ethernet
   Copyright (C) 2007-2012 Stefan Schuermans <stefan@blinkenarea.org>
   Copyleft: GNU public license V2 - http://www.gnu.org/copyleft/gpl.html
   a BlinkenArea project - http://www.blinkenarea.org/ */

#include <avr/io.h>

#include "macros.h"
#include "status.h"

// IO pins of bus
#define STATUS_DDR (DDRE)
#define STATUS_PORT (PORTE)
#define STATUS_BIT (2)

// status information
char StatusInfoCfPresent = 0;   // presence of working compact flash card
                                // (boolean) (extern)

// number of times to blink status LED
#define StatusBlinkCntIdle (1)
#define StatusBlinkCntIdleWithCf (2)
#define StatusBlinkCntWorking (3)
#define StatusBlinkCntMax (3)
unsigned char StatusBlinkCnt = StatusBlinkCntIdle;

// interval counter for blinking status LED
unsigned char StatusBlinkInterval = 0;

// initialize
void StatusInit(void)
{
  // set up IO pin of status LED as output
  bit_clear(STATUS_PORT, STATUS_BIT);
  bit_set(STATUS_DDR, STATUS_BIT);
}

// tick procedure - call every 200ms
void StatusTick200(void)
{
  // turn on status LED only in even intervals and if not yet blinked
  // StatusBlinkCnt times
  if ((StatusBlinkInterval & 0x01) == 0
      && StatusBlinkInterval >> 1 < StatusBlinkCnt)
    bit_set(STATUS_PORT, STATUS_BIT);
  else
    bit_clear(STATUS_PORT, STATUS_BIT);

  // next interval
  StatusBlinkInterval++;

  // blink cycle finished
  if (StatusBlinkInterval >> 1 > StatusBlinkCntMax) {
    StatusBlinkInterval = 0;

    // set new blink count depending on status information
    if (StatusInfoCfPresent)
      StatusBlinkCnt = StatusBlinkCntIdleWithCf;
    else
      StatusBlinkCnt = StatusBlinkCntIdle;
  }
}
