/*
    FreeRTOS V7.0.2 - Copyright (C) 2011 Real Time Engineers Ltd.
	

    ***************************************************************************
     *                                                                       *
     *    FreeRTOS tutorial books are available in pdf and paperback.        *
     *    Complete, revised, and edited pdf reference manuals are also       *
     *    available.                                                         *
     *                                                                       *
     *    Purchasing FreeRTOS documentation will not only help you, by       *
     *    ensuring you get running as quickly as possible and with an        *
     *    in-depth knowledge of how to use FreeRTOS, it will also help       *
     *    the FreeRTOS project to continue with its mission of providing     *
     *    professional grade, cross platform, de facto standard solutions    *
     *    for microcontrollers - completely free of charge!                  *
     *                                                                       *
     *    >>> See http://www.FreeRTOS.org/Documentation for details. <<<     *
     *                                                                       *
     *    Thank you for using FreeRTOS, and thank you for your support!      *
     *                                                                       *
    ***************************************************************************


    This file is part of the FreeRTOS distribution.

    FreeRTOS is free software; you can redistribute it and/or modify it under
    the terms of the GNU General Public License (version 2) as published by the
    Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
    >>>NOTE<<< The modification to the GPL is included to allow you to
    distribute a combined work that includes FreeRTOS without being obliged to
    provide the source code for proprietary components outside of the FreeRTOS
    kernel.  FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it
    can be viewed here: http://www.freertos.org/a00114.html and also obtained
    by writing to Richard Barry, contact details for whom are available on the
    FreeRTOS WEB site.

    1 tab == 4 spaces!

    http://www.FreeRTOS.org - Documentation, latest information, license and
    contact details.

    http://www.SafeRTOS.com - A version that is certified for use in safety
    critical systems.

    http://www.OpenRTOS.com - Commercial support, development, porting,
    licensing and training services.
*/

/*
 * Creates all the demo application tasks, then starts the scheduler.  The WEB
 * documentation provides more details of the standard demo application tasks.
 * In addition to the standard demo tasks, the following tasks and tests are
 * defined and/or created within this file:
 *
 * "LCD" task - the LCD task is a 'gatekeeper' task.  It is the only task that
 * is permitted to access the display directly.  Other tasks wishing to write a
 * message to the LCD send the message on a queue to the LCD task instead of
 * accessing the LCD themselves.  The LCD task just blocks on the queue waiting
 * for messages - waking and displaying the messages as they arrive.
 *
 * "Check" task -  This only executes every three seconds but has the highest
 * priority so is guaranteed to get processor time.  Its main function is to 
 * check that all the standard demo tasks are still operational.  Should any 
 * unexpected behaviour within a demo task be discovered the check task will 
 * write an error to the LCD (via the LCD task).  If all the demo tasks are 
 * executing with their expected behaviour then the check task instead writes 
 * a count of the number of times the high frequency interrupt has incremented
 * ulHighFrequencyTimerInterrupts - which is one in every 20,000 interrupts.
 *
 * "Register test" tasks - These tasks are used in part to test the kernel port.
 * They set each processor register to a known value, then check that the 
 * register still contains that value.  Each of the tasks sets the registers
 * to different values, and will get swapping in and out between setting and 
 * then subsequently checking the register values.  Discovery of an incorrect
 * value would be indicative of an error in the task switching mechanism.
 *
 * By way of demonstration, the demo application defines 
 * configMAX_SYSCALL_INTERRUPT_PRIORITY to be 3, configKERNEL_INTERRUPT_PRIORITY 
 * to be 1, and all other interrupts as follows:
 *
 *	+ The UART is allocated a priority of 2. This means it can interrupt the 
 *    RTOS tick, and can also safely use queues.
 *  + Two timers are configured to generate interrupts just to test the nesting 
 *    and queue access mechanisms. These timers are allocated priorities 2 and 3 
 *    respectively. Even though they both access the same two queues, the 
 *    priority 3 interrupt can safely interrupt the priority 2 interrupt. Both 
 *    can interrupt the RTOS tick.
 *  + Finally a high frequency timer interrupt is configured to use priority 4 - 
 *    therefore kernel activity will never prevent the high frequency timer from 
 *    executing immediately that the interrupt is raised (within the limitations 
 *    of the hardware itself). It would not be safe to access a queue from this 
 *    interrupt as it is above configMAX_SYSCALL_INTERRUPT_PRIORITY. 
 *
 * See the online documentation for this demo for more information on interrupt
 * usage.
 */

/* Standard includes. */
#include <stdio.h>

/* Scheduler includes. */
#include "TCPIP Stack/TCPIP.h"
#include "TCPIP Stack/StackTsk.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

#include "TCPIP Stack/TCPIP.h"
#include "TCPIP Stack/BerkeleyAPI.h"
#include "MDD File System/FSIO.h"

//#include "partest.h"
#include "blocktim.h"
#include "flash.h"
#include "semtest.h"
#include "GenQTest.h"
#include "QPeek.h"
#include "lcd.h"
#include "IntQueue.h"

#pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1, FWDTEN = OFF
#pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_2, FSOSCEN = ON
#pragma config FSRSSEL = PRIORITY_7  
#pragma config UPLLIDIV = DIV_2         // USB PLL Input Divider
#pragma config UPLLEN   = ON            // USB PLL Enabled
#pragma config FMIIEN = OFF, FETHIO = OFF	// external PHY in RMII/alternate configuration
#pragma interrupt _USB1Interrupt ipl4 vector 45



#define ROOM_SERVER_PORT			(39999)
#define ROOM_CLIENT_PORT			(39998)


/*-----------------------------------------------------------*/

BYTE header[41],voice[12];
xQueueHandle xDstarSndQueue, xDstarRcvQueue;
WORD	SSN;
WORD	left_byte;
WORD	DefaultVid  = 0x04D8;
WORD	DefaultPid = 0x0300;

WORD	seq;
BYTE	PicVer[2];
DWORD	dwServerIP;
BOOL	PTT_On;
BOOL	COS_On;
WORD	voice_pnt;
BOOL	headerRead;
BYTE	rig_buffer[32];

/* semi local variables*/
static	BYTE	LCDText[32];

/* The rate at which the LED controlled by the 'check' task will flash when no
errors have been detected. */
#define mainNO_ERROR_PERIOD	( 3000 / portTICK_RATE_MS )

/* The rate at which the LED controlled by the 'check' task will flash when an
error has been detected. */
#define mainERROR_PERIOD 	( 500 / portTICK_RATE_MS )

/* The priorities of the various demo application tasks. */
#define mainCHECK_TASK_PRIORITY				( tskIDLE_PRIORITY + 4 )
#define mainSEM_TEST_PRIORITY				( tskIDLE_PRIORITY + 1 )
#define mainBLOCK_Q_PRIORITY				( tskIDLE_PRIORITY + 2 )
#define mainCOM_TEST_PRIORITY				( tskIDLE_PRIORITY + 2 )
#define mainINTEGER_TASK_PRIORITY           ( tskIDLE_PRIORITY )
#define mainGEN_QUEUE_TASK_PRIORITY			( tskIDLE_PRIORITY )

/* The LED controlled by the 'check' task. */
//#define mainCHECK_LED						( 7 )

/* The LED used by the comtest tasks.  mainCOM_TEST_LED + 1 is also used.
See the comtest.c file for more information. */
//#define mainCOM_TEST_LED					( 4 )

/* Baud rate used by the comtest tasks. */
//#define mainCOM_TEST_BAUD_RATE				( 115200 )

/* Misc. */
#define mainDONT_WAIT						( 0 )

/* Dimension the buffer used to hold the value of the high frequency timer 
count when it is converted to a string. */
#define mainMAX_STRING_LENGTH				( 20 )

/* The frequency at which the "fast interrupt test" interrupt will occur. */
#define mainTEST_INTERRUPT_FREQUENCY		( 20000 )

/* The number of timer clocks we expect to occur between each "fast
interrupt test" interrupt. */
#define mainEXPECTED_CLOCKS_BETWEEN_INTERRUPTS ( ( configCPU_CLOCK_HZ >> 1 ) / mainTEST_INTERRUPT_FREQUENCY )

/* The number of nano seconds between each core clock. */
#define mainNS_PER_CLOCK ( ( unsigned long ) ( ( 1.0 / ( double ) ( configCPU_CLOCK_HZ >> 1 ) ) * 1000000000.0 ) )

/*-----------------------------------------------------------*/

/*
 * Setup the processor ready for the demo.
 */
static void prvSetupHardware( void );
void MACreadInit(void);
//static WORD	FSInit(void);

/*
 * Implements the 'TCPIP' task functionality as described at the top of this 
 * file. 
 */
extern void prvTaskTCPIP( void *pvParameters );

/*
 * Implements the 'USB' task functionality as described at the top of this 
 * file. 
 */
extern void prvTaskUSB( void *pvParameters );

static void prvTaskDateTime( void *pvParameters );

/*-----------------------------------------------------------*/

/* The queue used to send messages to the LCD task. */
static xQueueHandle xLCDQueue;



/*-----------------------------------------------------------*/

/*
 * Create the demo tasks then start the scheduler.
 */
int main( void )
{
	/* Configure any hardware required for this demo. */
	prvSetupHardware();

	/* Create the LCD task - this returns the queue to use when writing 
	messages to the LCD. */
	xLCDQueue = xStartLCDTask();

	FSInit();				/* SPI file system initialize */
	MACreadInit();			/* 25AA02E48 initialize */
 
	xDstarSndQueue = xQueueCreate (32, 56);
	xDstarRcvQueue = xQueueCreate (32, 56);

	seq = 0;
	PTT_On = FALSE;
	COS_On = FALSE;
	voice_pnt = 0;
	headerRead = FALSE;

	/* Create all the other standard demo tasks. */
    vCreateBlockTimeTasks();
    vStartQueuePeekTasks();
	vStartInterruptQueueTasks();

	/* Create the tasks defined within this file. */
	xTaskCreate( prvTaskTCPIP, ( const signed char * const ) "TCPIP", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY+1, NULL );

	/* Create the tasks defined within this file. */
	xTaskCreate( prvTaskUSB, ( const signed char * const ) "USB", 1024 /*configMINIMAL_STACK_SIZE*/ , NULL, tskIDLE_PRIORITY+1, NULL );

	/* Create the tasks defined within this file. */
	xTaskCreate( prvTaskDateTime, ( const signed char * const ) "TIME", configMINIMAL_STACK_SIZE , NULL, tskIDLE_PRIORITY+1, NULL );
	
	/* Finally start the scheduler. */
	vTaskStartScheduler();

	/* Will only reach here if there is insufficient heap available to start
	the scheduler. */
	return 0;
}

/*-----------------------------------------------------------*/

static void prvSetupHardware( void )
{
	/* Set the system and peripheral bus speeds and enable the program cache*/
    SYSTEMConfigPerformance( configCPU_CLOCK_HZ - 1 );
	mOSCSetPBDIV( OSC_PB_DIV_2 );

	/* Setup to use the external interrupt controller. */
    INTEnableSystemMultiVectoredInt();

	portDISABLE_INTERRUPTS();

   //Initialize the RTCC
   RtccInit();
   while(RtccGetClkStat()!=RTCC_CLK_ON);// wait for the SOSC to be actually running and RTCC to have its clock source
							            // could wait here at most 32ms
   RtccOpen(0x00000000, 0x11010106, 0); /* 2011 01/01 00:00:00 */

}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook( void )
{
	/* Look at pxCurrentTCB to see which task overflowed its stack. */
	for( ;; );
}
/*-----------------------------------------------------------*/

void _general_exception_handler( unsigned long ulCause, unsigned long ulStatus )
{
	/* This overrides the definition provided by the kernel.  Other exceptions 
	should be handled here. */
	for( ;; );
}
/*-----------------------------------------------------------*/

static void prvTaskDateTime( void *pvParameters )
{
	rtccTime tm;
	rtccDate dt;

	vTaskDelay (10000 / portTICK_RATE_MS);

	while (1)
	{
		RtccGetTimeDate (&tm, &dt); 
		memset (LCDText, 0x20, 32);
		LCDText[6] = '2';
		LCDText[7] = '0';
		LCDText[8] = (dt.year>> 4) + 0x30;
		LCDText[9] = (dt.year & 0x0f) + 0x30;
		LCDText[10] = '/';
		LCDText[11] = (dt.mon>> 4) + 0x30;
		LCDText[12] = (dt.mon & 0x0f) + 0x30;
		LCDText[13] = '/';
		LCDText[14] = (dt.mday>> 4) + 0x30;
		LCDText[15] = (dt.mday & 0x0f) + 0x30;


		LCDText[24] = (tm.hour>> 4) + 0x30;
		LCDText[25] = (tm.hour & 0x0f) + 0x30;
		LCDText[26] = ':';
		LCDText[27] = (tm.min>> 4) + 0x30;
		LCDText[28] = (tm.min & 0x0f) + 0x30;
		LCDText[29] = ':';
		LCDText[30] = (tm.sec >> 4) + 0x30;
		LCDText[31] = (tm.sec & 0x0f) + 0x30;

		xMessage.pcMessage = LCDText;
 		xMessage.xMinDisplayTime = 500 / portTICK_RATE_MS;
		xQueueSend( xLCDQueue, &xMessage, 0 );
		vTaskDelay (60000 / portTICK_RATE_MS);
	}
}
