/* 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/interrupt.h>
#include <avr/wdt.h>

#include "apps.h"
#include "arp.h"
#include "bus.h"
#include "cf.h"
#include "debug.h"
#include "eeprom.h"
#include "http.h"
#include "random.h"
#include "rtl8019.h"
#include "ser115200.h"
#include "status.h"
#include "tasks.h"
#include "tcp.h"
#include "timing.h"
#include "uart.h"

// try to work with CF card
static void mainWorkCf(void)
{
  unsigned long sectors;

  // reset card
  if (CfReset() != 0)
    return;

  // identify card
  if (CfIdentify(&sectors) != 0)
    return;

  // run applications
  AppsRun();
}

// wait for CF card and work with it
static void mainWaitCf(void)
{
  // wait for new card
  while (!CfIsPresent())
    Tasks();

  // work with card
  mainWorkCf();

  // wait for failing card to be removed
  while (CfIsPresent())
    Tasks();
}

// main code entry point
int main(void)
{
  wdt_reset();
#ifdef DEBUG
  wdt_disable();
#else
  wdt_enable(WDTO_60MS);
#endif
  wdt_reset();

  // initialize uart to be able to use stdio
  UartInit();

  debug_printf("");
  debug_printf("flaneth");

  debug_init_printf("init");

  // initialize low level modules
  BusInit();

  // initialize middle level modules
  CfInit();
  RtlInit();
  StatusInit();
  Ser115200Init();
  TimingInit();

  // initialize high level modules
  ArpInit();
  HttpInit();
  TcpInit();

  // use entropy collected during initialization
  RandomTask();

  debug_init_printf("config");

  // get configuration from EEPROM
  EepromGetConfig();

  // enable interrupts
  sei();

  debug_init_printf("start");

  // main loop
  while (1)
    mainWaitCf();

  return 0;
}

