/*
   Copyright (c) 2015, Digi International Inc.

   Permission to use, copy, modify, and/or distribute this software for any
   purpose with or without fee is hereby granted, provided that the above
   copyright notice and this permission notice appear in all copies.

   THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
   WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
   MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
   ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
   OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*******************************************************************************************************

      uCOSDemo1.c

This program has a startup task which creates 10 other tasks, each of which
displays the character passed to it during initialization at a random x,y
location in the stdio window.  The startup task continues to run and updates
system statistics every 5 seconds.

See Newv251.pdf and Relv251.pdf in the samples/ucos-II directory for
information from Jean J. Labrosse pertaining to version 2.51 of uCOS-II.

*******************************************************************************************************/
#class auto 			// Change default storage class for local variables: on the stack

/*
*********************************************************************************************************
*                                                uC/OS-II
*                                          The Real-Time Kernel
*
*                           (c) Copyright 1992-1999, Jean J. Labrosse, Weston, FL
*                                           All Rights Reserved
*
*                                                 V2.51
*
*                                               EXAMPLE #1
*********************************************************************************************************
*/

/*
*********************************************************************************************************
*                                               CONSTANTS
*********************************************************************************************************
*/

#define  TASK_STK_SIZE       512       // Size of each task's stacks (# of bytes)
#define  N_TASKS              10       // Number of identical tasks

/*
*********************************************************************************************************
*                                               CONFIGURATION
*********************************************************************************************************
*/

// Redefine uC/OS-II configuration constants as necessary
#define OS_MAX_EVENTS          2       // Maximum number of events (semaphores, queues, mailboxes)
#define OS_MAX_TASKS          11  		// Maximum number of tasks system can create (less stat and idle tasks)
#define OS_TASK_STAT_EN			 1       // Enable statistics task creation
#define OS_SEM_EN					 1			// Enable semaphore usage
#define STACK_CNT_512         13       // number of 512 byte stacks (application tasks + stat task + prog stacks)

#use "ucos2.lib"

/*
*********************************************************************************************************
*                                               VARIABLES
*********************************************************************************************************
*/

char             TaskData[N_TASKS];    // Parameters to pass to each task
OS_EVENT        *RandomSem;
OS_EVENT			 *PrintSem;

/*
*********************************************************************************************************
*                                           FUNCTION PROTOTYPES
*********************************************************************************************************
*/

void   Task(void *data);               // Function prototypes of tasks
void   TaskStart(void *data);          // Function prototypes of Startup task
void   ClearScreen();
void   DispStr(int x, int y, char *s);

/*
*********************************************************************************************************
*                                                MAIN
*********************************************************************************************************
*/

void main (void)
{
    ClearScreen();
    OSInit();                                              // Initialize uC/OS-II
    RandomSem = OSSemCreate(1);                            // Random number semaphore
    PrintSem = OSSemCreate(1);
    OSTaskCreate(TaskStart, (void *)0, TASK_STK_SIZE, 10);
    OSStart();                                             // Start multitasking
}

/*
*********************************************************************************************************
*                                              STARTUP TASK
*********************************************************************************************************
*/
void TaskStart (void *data)
{
    auto UBYTE  i, err;
    static char   s[100];
    auto WORD   key;

    data = data;                                           // Prevent compiler warning

	 DispStr(26, 0, "uC/OS-II, The Real-Time Kernel");
	 DispStr(33, 1, "Jean J. Labrosse");
	 DispStr(36, 3, "EXAMPLE #1");

	 DispStr(0, 12, "Determining  CPU's capacity ...");
    OSStatInit();                                          // Initialize uC/OS-II's statistics
	 DispStr(0, 12, "                               ");

    for (i = 0; i < N_TASKS; i++) {                        // Create N_TASKS identical tasks
        TaskData[i] = '0' + i;                             // Each task will display its own letter
        OSTaskCreate(Task, (void *)&TaskData[i], TASK_STK_SIZE, i + 11);
    }

	 DispStr(0, 12, "#Tasks          : xxxxx  CPU Usage: xxx %");
	 DispStr(0, 13, "#Task switch/sec: xxxxx");
	 DispStr(28, 14, "<-PRESS 'Q' TO QUIT->");
    for (;;) {
        sprintf(s, "%5d", OSTaskCtr);                     // Display #tasks running
		  DispStr(18, 12, s);
#if OS_TASK_STAT_EN
        sprintf(s, "%3d", OSCPUUsage);                    // Display CPU usage in %
		  DispStr(36, 12, s);
#endif
        sprintf(s, "%5d", OSCtxSwCtr);                // Display avg #context switches per 5 seconds
		  DispStr(18, 13, s);
        OSCtxSwCtr = 0;

        sprintf(s, "V%1d.%02d", OSVersion() / 100, OSVersion() % 100);
		  DispStr(75, 14, s);

        if (kbhit()) {                                       // See if key has been pressed
            key = getchar();
				if (key == 0x71 || key == 0x51) {                // Yes, see if it's the q or Q key
                exit(0);
            }
        }
        OSTimeDly(OS_TICKS_PER_SEC);                         // Wait one second
    }
}

/*
*********************************************************************************************************
*                                                  TASKS
*********************************************************************************************************
*/

nodebug void Task (void *data)
{
	 auto UBYTE x;
    auto UBYTE y;
    auto UBYTE err;
	 auto UBYTE num[2];

    for (;;) {
        OSSemPend(RandomSem, 0, &err);           // Acquire semaphore to perform random numbers
        x = (int)(rand() * 5);                   // Find X position where task number will appear
        y = (int)(rand() * 5);                   // Find Y position where task number will appear
        OSSemPost(RandomSem);                    // Release semaphore

        sprintf(num, "%c", *((char *)data));
		  DispStr(x + 39, y + 5, num);	          // Display the task number on the screen
		  OSTimeDly(25);
    }
}

/*
*********************************************************************************************************
*                                      HELPER FUNCTIONS
*********************************************************************************************************
*/

nodebug void
ClearScreen()
{
   printf ( "\x1Bt" );            	// Space Opens Window
}

nodebug void
DispStr (int x, int y, char *s)
{
   x += 0x20;
   y += 0x20;
   printf ("\x1B=%c%c%s", x, y, s);
}