/*
 * Copyright (C) 2015 AggieAir, A Remote Sensing Unmanned Aerial System for Scientific Applications
 * Utah State University, http://aggieair.usu.edu/
 *
 * Michal Podhradsky (michal.podhradsky@aggiemail.usu.edu)
 * Calvin Coopmans (c.r.coopmans@ieee.org)
 *
 * This file is part of paparazzi.
 *
 * paparazzi is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * paparazzi is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with paparazzi; see the file COPYING.  If not, write to
 * the Free Software Foundation, 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/* ChibiOS includes */
#include "ch.h"

/* paparazzi includes */
#include "mcu.h"
#include "led.h"
#include "mcu_periph/sys_time.h"

static inline void main_periodic_1(void);
static inline void main_periodic_15(void);
static inline void main_periodic_05(void);

/*
 * Thread Area Definitions
 */
#define CH_CFG_THREAD_AREA_MAIN_PERIODIC 128

/*
 * Thread Area Initialization
 */
static THD_WORKING_AREA(wa_thd_main_periodic_05, CH_CFG_THREAD_AREA_MAIN_PERIODIC);

/*
 * Static Thread Definitions
 */
static __attribute__((noreturn)) void thd_main_periodic_05(void *arg);

/**
 * Test Thread
 *
 * Replaces main_periodic_05()
 *
 */
static __attribute__((noreturn)) void thd_main_periodic_05(void *arg)
{
  chRegSetThreadName("thd_main_periodic_05");
  (void) arg;
  systime_t time = chVTGetSystemTime();
  while (TRUE)
  {
    time += MS2ST(500);
    main_periodic_05();
    chThdSleepUntil(time);
  }
}

int main(void)
{

  mcu_init();

  /*
   * Init threads
   */
  chThdCreateStatic(wa_thd_main_periodic_05, sizeof(wa_thd_main_periodic_05), NORMALPRIO, thd_main_periodic_05, NULL);


  while (1) {
    /* sleep for 1s */
    sys_time_ssleep(1);
    main_periodic_1();

    /* sleep for 0.42s */
    /*
    * sys_time_usleep(uint32_t us)
    * Use only for up to 2^32/CH_CFG_ST_FREQUENCY-1 usec
    * e.g. if CH_CFG_ST_FREQUENCY=10000 use max for 420000 us
    * or 420ms, otherwise overflow happens
	*/
    sys_time_usleep(420000);
    main_periodic_15();
  }

  return 0;
}

/*
 * Called from main loop polling
 */
static inline void main_periodic_1(void)
{
#ifdef LED_GREEN
  LED_TOGGLE(LED_GREEN);
#endif
}

static inline void main_periodic_15(void)
{
#ifdef SYS_TIME_LED
  LED_TOGGLE(SYS_TIME_LED);
#endif
}

/*
 * Called from the systime interrupt handler
 */
static inline void main_periodic_05(void)
{
#ifdef LED_RED
  LED_TOGGLE(LED_RED);
#endif
}
