/*********************************************************************
 *
 *  Main Application Entry Point and TCP/IP Stack Demo
 *  Module for Microchip TCP/IP Stack
 *   -Demonstrates how to call and use the Microchip TCP/IP stack
 *	 -Reference: Microchip TCP/IP Stack Help (TCPIP Stack Help.chm)
 *
 *********************************************************************
 * FileName:        MainDemo.c
 * Dependencies:    TCPIP.h
 * Processor:       PIC18, PIC24F, PIC24H, dsPIC30F, dsPIC33F, PIC32
 * Compiler:        Microchip C32 v1.11b or higher
 *					Microchip C30 v3.24 or higher
 *					Microchip C18 v3.36 or higher
 * Company:         Microchip Technology, Inc.
 *
 * Software License Agreement
 *
 * Copyright (C) 2002-2010 Microchip Technology Inc.  All rights
 * reserved.
 *
 * Microchip licenses to you the right to use, modify, copy, and
 * distribute:
 * (i)  the Software when embedded on a Microchip microcontroller or
 *      digital signal controller product ("Device") which is
 *      integrated into Licensee's product; or
 * (ii) ONLY the Software driver source files ENC28J60.c, ENC28J60.h,
 *		ENCX24J600.c and ENCX24J600.h ported to a non-Microchip device
 *		used in conjunction with a Microchip ethernet controller for
 *		the sole purpose of interfacing with the ethernet controller.
 *
 * You should refer to the license agreement accompanying this
 * Software for additional information regarding your rights and
 * obligations.
 *
 * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
 * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
 * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * MICROCHIP BE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
 * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
 * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
 * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
 * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
 * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
 *
 * File Description:
 * Change History:
 * Rev   Description
 * ----  -----------------------------------------
 * 1.0   Initial release
 * V5.36 ---- STACK_USE_MPFS support has been removed 
 ********************************************************************/
/*
 * This macro uniquely defines this file as the main entry point.
 * There should only be one such definition in the entire project,
 * and this file must define the AppConfig variable as described below.
 */
#define THIS_IS_STACK_APPLICATION

// Include all headers for any enabled TCPIP Stack functions
#include "TCPIP Stack/TCPIP.h"


// Include functions specific to this stack application
#include "prvTaskTCPIP.h"

#include "FreeRTOS.h"
#include "queue.h"
#include "lcd.h"

#include <string.h>

#include "TCPIP Stack/DstarRoomServer.h"

// Declare AppConfig structure and some other supporting stack variables
static unsigned short wOriginalAppConfigChecksum;	// Checksum of the ROM defaults for AppConfig

// Private helper functions.
// These may or may not be present in all applications.
static void InitAppConfig(void);
void	DstarRoomServerUDP(void);
void	ReadMacFromEEPROM(BYTE *SerializedMACAddress);
static	BYTE SerializedMACAddress[6];
BOOL	MACWriteArray(BYTE address, BYTE AppConfig[], WORD length);
void	MACReadArray(BYTE address, BYTE AppConfig[], WORD length);
void	DisplayIPValue(IP_ADDR IPVal, BYTE XLCDText[]);

extern DWORD	RoomServerState;


static BYTE	LCDText[32];
	
//
// Main application entry point.
//
void prvTaskTCPIP (void *pvParameters)
{
	static DWORD dwLastIP;

	// Initialize stack-related hardware components that may be 
	// required by the UART configuration routines
    TickInit();

	MPFSInit();

	// Initialize Stack and application related NV variables into AppConfig.
	InitAppConfig();

	dwLastIP = AppConfig.MyIPAddr.Val;

	// Initialize core stack layers (MAC, ARP, TCP, UDP) and
	// application modules (HTTP, SNMP, etc.)
    StackInit();

	BUTTON0_TRIS = 1;			/* SW1 input */
	BUTTON1_TRIS = 1;			/* SW2 input */
	BUTTON2_TRIS = 1;			/* SW3 input */

	LED1_TRIS = 0;				/* LED1 outout for TCP/IP */
	LED1_IO = 0;

    while(1)
    {

        StackTask();

        // This tasks invokes each of the core stack application tasks
		HTTPServer();
		SNTPClient();
		DstarRoomServerUDP();

		/* check SW1 */
		if (!BUTTON0_IO)
		{
			memset((void*)&AppConfig, 0x00, sizeof(AppConfig));
			MACWriteArray(0x00, (BYTE *)&AppConfig, sizeof(AppConfig));
			Reset();
		}

		/* check SW2 */
		if (!BUTTON1_IO)
		{
			Reset();
		}
		
		/* check SW3 */
		if (!BUTTON2_IO)
		{
			memcpy (LCDText, "Cur. IP Address ",16);
			DisplayIPValue(AppConfig.MyIPAddr, LCDText);
		}

       	// If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the LCD display, UART, and Announce 
        // service
		if(dwLastIP != AppConfig.MyIPAddr.Val)
		{
			dwLastIP = AppConfig.MyIPAddr.Val;
			memcpy (LCDText, "New IP Address  ",16);
			DisplayIPValue(AppConfig.MyIPAddr, LCDText);
			RoomServerState = 0;	// DS_HOME
		}

	}
}


// Writes an IP address to the LCD display and the UART as available
void DisplayIPValue(IP_ADDR IPVal, BYTE XLCDText[])
{
    static	BYTE IPDigit[4];
	static	BYTE i;
	static	BYTE j;
	static	BYTE LCDPos;

	LCDPos = 16;
	for(i = 0; i < sizeof(IP_ADDR); i++)
	{
	    uitoa((WORD)IPVal.v[i], IPDigit);


			for(j = 0; j < strlen((char*)IPDigit); j++)
			{
				XLCDText[LCDPos++] = IPDigit[j];
			}
			if(i == sizeof(IP_ADDR)-1)
				break;
			XLCDText[LCDPos++] = '.';

	}
		XLCDText[LCDPos] = 0x00;

		if(LCDPos < 32u)
			LCDText[LCDPos] = 0;
			xMessage.pcMessage = (char *)XLCDText;
 			xMessage.xMinDisplayTime = 1000 / portTICK_RATE_MS;
			xQueueSend( xLCDQueue, &xMessage, 0 );

}


/*********************************************************************
 * Function:        void InitAppConfig(void)
 *
 * PreCondition:    MPFSInit() is already called.
 *
 * Input:           None
 *
 * Output:          Write/Read non-volatile config variables.
 *
 * Side Effects:    None
 *
 * Overview:        None
 *
 * Note:            None
 ********************************************************************/

static void InitAppConfig(void)
{
	extern	MAC_ADDR	MyMACAddr;              // Application MAC address

		MACReadArray (0x00,(BYTE *)&AppConfig, sizeof(AppConfig));
		wOriginalAppConfigChecksum = CalcIPChecksum((BYTE*)&AppConfig, sizeof(AppConfig)-2);
		if (wOriginalAppConfigChecksum != AppConfig.CheckSum)
		{
			memset((void*)&AppConfig, 0x00, sizeof(AppConfig));
			AppConfig.Flags.bIsDHCPEnabled = TRUE;
			AppConfig.Flags.bInConfigMode = TRUE;
			AppConfig.Flags.RepeaterAcc = FALSE;
			memcpypgm2ram((void*)&MyMACAddr, (ROM void*)SerializedMACAddress, sizeof(MyMACAddr));
			AppConfig.MyIPAddr.Val = MY_DEFAULT_IP_ADDR_BYTE1 | MY_DEFAULT_IP_ADDR_BYTE2<<8ul | MY_DEFAULT_IP_ADDR_BYTE3<<16ul | MY_DEFAULT_IP_ADDR_BYTE4<<24ul;
			AppConfig.DefaultIPAddr.Val = AppConfig.MyIPAddr.Val;
			AppConfig.MyMask.Val = MY_DEFAULT_MASK_BYTE1 | MY_DEFAULT_MASK_BYTE2<<8ul | MY_DEFAULT_MASK_BYTE3<<16ul | MY_DEFAULT_MASK_BYTE4<<24ul;
			AppConfig.DefaultMask.Val = AppConfig.MyMask.Val;
			AppConfig.MyGateway.Val = MY_DEFAULT_GATE_BYTE1 | MY_DEFAULT_GATE_BYTE2<<8ul | MY_DEFAULT_GATE_BYTE3<<16ul | MY_DEFAULT_GATE_BYTE4<<24ul;
			AppConfig.PrimaryDNSServer.Val = MY_DEFAULT_PRIMARY_DNS_BYTE1 | MY_DEFAULT_PRIMARY_DNS_BYTE2<<8ul  | MY_DEFAULT_PRIMARY_DNS_BYTE3<<16ul  | MY_DEFAULT_PRIMARY_DNS_BYTE4<<24ul;
			AppConfig.SecondaryDNSServer.Val = MY_DEFAULT_SECONDARY_DNS_BYTE1 | MY_DEFAULT_SECONDARY_DNS_BYTE2<<8ul  | MY_DEFAULT_SECONDARY_DNS_BYTE3<<16ul  | MY_DEFAULT_SECONDARY_DNS_BYTE4<<24ul;
			AppConfig.DefaultOutPort = ROOM_SERVER_OUT_PORT;
			AppConfig.DefaultInPort = ROOM_SERVER_IN_PORT;
			AppConfig.DefaultLogPort = ROOM_SERVER_LOG_PORT;
			strncpy ((char *)AppConfig.LogServerName, "www.jk1zrw.org", 32);;
			strncpy ((char *)AppConfig.DefaultRoomName, "TST000  ", 8);
			strncpy ((char *)AppConfig.NTPserver, "pool.ntp.org", 32);
			strncpy ((char *)AppConfig.UserID, "admin",16);
			strncpy ((char *)AppConfig.PASSWORD, "microchip", 16);
			AppConfig.TmZone = 0x09;
			AppConfig.TmZoneMinutes = 0x00;
			AppConfig.CheckSum = CalcIPChecksum((BYTE*)&AppConfig, sizeof(AppConfig)-2);
			MACWriteArray(0x00, (BYTE *)&AppConfig, sizeof(AppConfig));
		}

		ReadMacFromEEPROM(SerializedMACAddress);
		memcpy (&MyMACAddr, &SerializedMACAddress, 6);
}

