/*
   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.
*/
/*******************************************************************************************************

      uCOSDemo4.c

This program does the following:

Start up task: Sets up stdio window, creates 5 tasks, updates system statistics in
					the stdio window every every 5 seconds.
each task:    	Determines angle based on initial parameters passed to the task during
					task creation.  Then, determines sin and cos of angle and displays results
					in stdio window.

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-1998, Jean J. Labrosse, Plantation, FL
*                                           All Rights Reserved
*
*                                                 V2.51
*
*                                               EXAMPLE #4
*********************************************************************************************************
*/

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

// Redefine uC/OS-II configuration constants as necessary
#define OS_MAX_TASKS           6  		// Maximum number of tasks system can create (less stat and idle tasks)
#define OS_TASK_CREATE_EN		 0       // Disable normal task creation
#define OS_TASK_CREATE_EXT_EN	 1       // Enable extended task creation
#define OS_TASK_STAT_EN			 1       // Enable statistics task creation

#define STACK_CNT_512	       8       // number of 512 byte stacks (application tasks + stat task + prog stack)

#use "ucos2.lib"

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

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

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

INT8U            TaskData[N_TASKS];              // Parameters to pass to each task

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

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

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

void main (void)
{
    ClearScreen();                               // Clear the screen

    OSInit();                                    // Initialize uC/OS-II

    OSTaskCreateExt(TaskStart,
                    (void *)0,
                    0,
                    0,
                    TASK_STK_SIZE,
                    (void *)0,
                    0);
    OSStart();                                   // Start multitasking
}

/*
*********************************************************************************************************
*                                              STARTUP TASK
*********************************************************************************************************
*/
void TaskStart (void *data)
{
    auto INT8U  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(28,  2, "Rabbit with Floating-Point");
	 DispStr( 0, 22, "Determining  CPU's capacity ...");

    OSStatInit();                                          // Initialize uC/OS-II's statistics

	 DispStr( 0, 22, "                               ");

    for (i = 0; i < N_TASKS; i++) {                        // Create N_TASKS identical tasks
        TaskData[i] = i;
        OSTaskCreateExt(Task,
                        (void *)&TaskData[i],
                        i + 1,
                        0,
                        TASK_STK_SIZE,
                        (void *)0,
                        0);
    }
    DispStr( 0,  5, "TaskPrio      Angle   cos(Angle)   sin(Angle)");
    DispStr( 0,  6, "--------      -----   ----------   ----------");
    DispStr( 0, 22, "#Tasks          : xxxxx  CPU Usage: xxx %");
    DispStr( 0, 23, "#Task switch sec: xxxxx");
    DispStr(28, 24, "<-PRESS 'Q' TO QUIT->");

    for (;;) {
        sprintf(s, "%5d", OSTaskCtr);                     // Display #tasks running
        DispStr(18, 22, s);

        sprintf(s, "%3d", OSCPUUsage);                    // Display CPU usage in %
        DispStr(36, 22, s);

        sprintf(s, "%5d", OSCtxSwCtr / 5);                // Display #context switches per second
        DispStr(18, 23, s);

        OSCtxSwCtr = 0;

        sprintf(s, "V%1d.%02d", OSVersion() / 100, OSVersion() % 100);
        DispStr(75, 24, 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 five seconds
    }
}

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

void Task (void *data)
{
    auto float  x;
    auto float  y;
    auto float  angle;
    auto float  radians;
    auto char  s[81];
    auto INT8U ypos, err;


    ypos  = *(INT8U *)data + 8;
    angle = (float)(*(INT8U *)data * 36.0);
    for (;;) {
        radians = 2.0 * 3.141592 * angle / 360.0;
        x       = cos(radians);
        y       = sin(radians);
        sprintf(s, "    %d      %8.3f     %8.3f     %8.3f", *(INT8U *)data, angle, x, y);
		  DispStr(0, ypos, s);
        if (angle >= 360.0) {
            angle /= 360.0;
        } else {
            angle +=   0.01;
        }
        OSTimeDly(18);
    }
}

/*
*********************************************************************************************************
*                                      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);
}