/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

 /* Set some one-shot timers and a periodic timer.
  * Create a reader thread that loops and receives messages from
  * expiring timers and prints them.
  */

#include <stdio.h> /* For printf */

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>

#define MSGQ_SIZE 8
#define STACK_SIZE 16*1024
#define NUM_TIMER 5

IOSMessage msgQ[MSGQ_SIZE];
IOSMessageQueueId qid = -1;

static void
rdr_thread(u32 x)
{
  char *msg;
  unsigned count = 0; 
  printf("Reader thread starts running\n");
  while (1) {
      IOS_ReceiveMessage(qid, (IOSMessage *) &msg, IOS_MESSAGE_BLOCK);
      if ( NULL == msg) {
          printf("Received null message\n");
          goto out;
      }
      count++;
      printf("Read timer msg[%d]: %s\n", count, msg);
  }
out:
  IOS_DestroyMessageQueue(qid);
  IOS_ThreadExit(0);
}

static u32
create_rdr()
{
  u32 *progStack = (void *) IOS_Alloc(STACK_SIZE/IOS_DDR_PAGE_SIZE);
  u32 id = IOS_CreateThread(rdr_thread, 0, progStack, STACK_SIZE, IOS_GetThreadPriority(0) - 1, IOS_THREAD_CREATE_DETACHED);
  IOS_StartThread(id);
  return id;
}

void
timer(u32 x)
{
    char msg[NUM_TIMER][32];
    char periodic_msg[32];
    int period = 1;
    int t[]= {6, 9, 5, 2, 4}; /* NUM_TIMER # of times for timers */
    u32 id;
    int i;
    if ( 0 > (qid = IOS_CreateMessageQueue(msgQ, MSGQ_SIZE)))
            goto done;
    id = create_rdr();
    for ( i = 0; i < NUM_TIMER; ++i ) {
        sprintf(msg[i], "timer-period: %ds expired", t[i]);
        IOS_CreateTimer(t[i]*1000, 0, qid, (u32)msg[i]);
    } 
    sprintf(periodic_msg,"periodic timer: %ds expired", period);
        IOS_CreateTimer(0, period*1000, qid, (u32)periodic_msg);
    IOS_YieldThread();
done:
    IOS_ThreadExit(0);
}
