// Copyright (c) 2004 Rowley Associates Limited.
//
// This file may be distributed under the terms of the License Agreement
// provided with this software.
//
// THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// test8
// Check that timeouts work on wait calls

#include <string.h>
#include <ctl_api.h>

CTL_TASK_t mainTask,other1Task,other2Task;
int other1count, other2count;

#define CALLSTACKSIZE 16 // this is only required for AVR builds
#define STACKSIZE 64
unsigned other1Stack[1+STACKSIZE+1], other2Stack[1+STACKSIZE+1]; // allocate 1 word before and after to aid debugging stack space problems

void 
other1(void *p)
{
  while (1)
    {
      other1count++;          
      ctl_board_set_leds(0);
    }  
}

void 
other2(void *p)
{
  while (1)
    {
      other2count++;   
      ctl_board_set_leds(0xFFFFFFFF);        
    }  
}

void
ctl_handle_error(CTL_ERROR_CODE_t e)
{
  while (1);
}

CTL_EVENT_SET_t e1; // set to zero to cause wait
CTL_SEMAPHORE_t s1; // set to zero to cause wait
CTL_MESSAGE_QUEUE_t mq;
#define QSIZE 1
void *queue[QSIZE];

int
main(void)
{  
  unsigned result, v;
  ctl_board_init();  
  ctl_task_init(&mainTask, 255, "main");
  ctl_start_timer(ctl_increment_tick_from_isr);
  ctl_timeslice_period = ctl_get_ticks_per_second();  
  memset(other1Stack, 0xcd, sizeof(other1Stack));
  memset(other2Stack, 0xcd, sizeof(other2Stack));
  other1Stack[0]=other1Stack[1+STACKSIZE]=other2Stack[0]=other2Stack[1+STACKSIZE]=0xfacefeed;
  ctl_task_run(&other1Task, 1, other1, 0, "other1", STACKSIZE, other1Stack+1, CALLSTACKSIZE);
  ctl_task_run(&other2Task, 1, other2, 0, "other2", STACKSIZE, other2Stack+1, CALLSTACKSIZE);
  ctl_task_set_priority(&mainTask, 1);
  result = ctl_events_wait(CTL_EVENT_WAIT_ANY_EVENTS_WITH_AUTO_CLEAR, &e1, 1, 1, ctl_get_current_time()+1);
  result = ctl_semaphore_wait(&s1, 1, ctl_get_current_time()+1);
  ctl_message_queue_init(&mq, queue, QSIZE);
  result = (int)ctl_message_queue_receive(&mq, (void **)&v, 1, ctl_get_current_time()+1);
  while (1)
    {
      ;
    }
}
