
/*
 Description:
 This is a template file for standard C header file.
 
 */

/* ************************************************************************** */
/* Revision:
 ### 20120607 JFM
 Original version.
 
 ### 20120607 Initial, Bug Identification
 Change description.
 */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "terminal.h"
#include "define.h"
#include "WiFiCtrl.h"
#include "LedLightCtrl.h"
#include "ChaletPowerRelay.h"
#include "BatteryMonitor.h"
#include "BootloaderInterface.h"

//#include "SDCardMgr.h"
#ifdef TERMINAL_USE_TELNET
#include "TCPIP_Stack/Telnet.h"
#endif

#define TerminalPrint(fmt, ...) \
            do { sprintf(TerminalWorkString, fmt, __VA_ARGS__); \
            TerminalPrintString(TerminalWorkString);} while (0)

char TerminalDataBuf[TERMINAL_STRING_LENGTH];
char TerminalPrevDataBuf[TERMINAL_STRING_LENGTH];
char TerminalWorkString[TERMINAL_STRING_LENGTH];
char *TerminalDataPtr;

int mTerminalPendingAction;
BOOL mTerminalOpened;
int mTerminalTickState;

static BYTE mHelpString[]		= "Here is the list of the available commands:\n\r\n\r"
"help : Shows this window\n\r"	
"\npower [state] Set chalet's 12V Inverter feed power state.  This command controls the main power relay\n"
"    - Available [state] argument are: on\n"
"                                      off\n"
"\nwifi [command] control ChaletDuino's WiFi module state%\n"
"    - Available [command] argument are: on (turns ON module)\n"
"                                        off (turns OFF module)\n"
"                                        status (returns current status)\n"
"\nbattery [sensor] returns current battery sensors readings\n"
"    - Available [sensor] argument are: voltage\n"
"                                       current\n"
"                                       soc (state of charge)\n"
"       Empty [sensor] argument prints all values\n"
"\nstatus : get general system status\n"
"\nbootloader [command] : bootloader mode control\n"
"    - Available [command] argument are: start (enable bootloader and opens port)\n"
"                                        stop (disables bootloader if not busy)\n"
"                                        state (prints actual state of the bootloader)\n"

//"\ndebug : print some real-time stuff..."
"\nHave a good day!\n";

BYTE *mHelpStringPtr;

void InitTerminal(void)
{
	TerminalDataPtr = &TerminalDataBuf[0];
	memset(TerminalDataBuf,0,sizeof(TerminalDataBuf));
	memset(TerminalPrevDataBuf,'\0',sizeof(TerminalPrevDataBuf));
    memset(TerminalWorkString,'\0',sizeof(TerminalWorkString));
    
    mTerminalPendingAction = TERMINAL_ACTION_NONE;
}


void TickTerminal()
{
        switch(mTerminalPendingAction)
    {
        case TERMINAL_ACTION_NONE:
        {
            break;
        }
        case TERMINAL_ACTION_TURN_OFF_WIFI:
        {
            mTerminalPendingAction = TERMINAL_ACTION_NONE;
            TurnOFFWiFi();
            break;
        }
    }
}

void RxTerminalBuf(uint8* DataBuf, int size)
{
    if(DataBuf != 0)
    {
        int i = 0;
        for(i = 0; i < size; i++)
        {
            RxTerminalData(*DataBuf++);
        }
    }
}

void RxTerminalData(unsigned char Data)
{
    // sTerminalPrint(TerminalWorkString,"%c",Data);
    //  TerminalPrintString(TerminalWorkString);
	if(Data == 0x0D)		//enter
	{
		//TerminalPrint("\n\r");
        TerminalPrintString("\n\r\0");
        
		if(strlen(TerminalDataBuf) != 0)
		{
			strcpy(TerminalPrevDataBuf,TerminalDataBuf);
			ParseNewBuffer();
		}	
		
		TerminalDataPtr = &TerminalDataBuf[0];
		memset(TerminalDataBuf,'\0',sizeof(TerminalDataBuf));
		
	}
	else if(Data == 0x08 || Data == 0x7F)	//backspace
	{
        //		TerminalPrint("%c",Data);
        TerminalPrintChar(Data);
		if(TerminalDataPtr != &TerminalDataBuf[0])
		{
            TerminalDataPtr--;
            *TerminalDataPtr = '\0';
        }
        
	}
    //	else if(Data == 0x1B)	//Up key
    //	{
    //		//memcpy(TerminalDataBuf,TerminalPrevDataBuf,strlen(TerminalPrevDataBuf)-1);
    //		strcpy(TerminalDataBuf,TerminalPrevDataBuf);
    //		TerminalPrint("%s",TerminalDataBuf);
    //	}	
	else
	{
		//TerminalPrint("%c",Data);
        TerminalPrintChar(Data);
		if(TerminalDataPtr < &TerminalDataBuf[TERMINAL_STRING_LENGTH])
        {
			*TerminalDataPtr = Data;
            TerminalDataPtr++;
        }
	}	
}	

void ParseNewBuffer(void)
{
	char mCmdString[30], mDataString1[30], mDataString2[30], mDataString3[30],mDataString4[30];
	memset(mCmdString,'\0',sizeof(mCmdString));
	memset(mDataString1,'\0',sizeof(mDataString1));
	memset(mDataString2,'\0',sizeof(mDataString2));
	memset(mDataString3,'\0',sizeof(mDataString3));
	memset(mDataString4,'\0',sizeof(mDataString4));
	
	sscanf(TerminalDataBuf,"%s %s %s %s %s",mCmdString, mDataString1, mDataString2, mDataString3,mDataString4);
    
	if(strncmp(mCmdString,"help",strlen("help")) == 0)
	{
        mHelpStringPtr = mHelpString;
        static BYTE* Ptr= mHelpString;
        
        SendTerminalData(mHelpString,strlen(mHelpString));
        
        Ptr = mHelpStringPtr;
	}
    
	else if(strncmp(mCmdString,"power",strlen("power")) == 0)
	{
		if(strlen(mDataString1) == 0)
		{
			TerminalPrintString("\n[state] parameter is invalid.  Type 'help' for more info\n");
			return;
		}
        
        
		if(strncmp(mDataString1,"on",strlen("on")) == 0)
		{
            TerminalPrintString("Turning chalet's inverter ON\n");
//            ChaletPowerRelayTurnOn();
		}
		else if(strncmp(mDataString1,"off",strlen("off")) == 0)
		{
            TerminalPrintString("Turning chalet's inverter OFF\n");
//            ChaletPowerRelayTurnOff();
		}
		else
		{
			TerminalPrintString("\n[state] parameter is invalid.  Type 'help' for valid values\n");
		}	
        
		TerminalPrintString("\n");
	}
    else if(strncmp(mCmdString,"wifi",strlen("wifi")) == 0)
	{
		if(strlen(mDataString1) == 0)
		{
			TerminalPrintString("\n[value] parameter is invalid.  Type 'help' for more info\n");
			return;
		}
        
        if(strncmp(mDataString1,"on",strlen("on")) == 0)
		{
            if(GetWiFiSate() != WIFI_CONNECTED_STATE)
            {
                TerminalPrintString("Turning WiFi module ON\n");
                InitWiFi();
            }
            else
            {
                 TerminalPrintString("WiFi already connected...\n");
            }
 		}
        else if(strncmp(mDataString1,"off",strlen("off")) == 0) 
		{
            if(GetWiFiSate() != WIFI_MODULE_OFF_STATE)
            {
                TerminalPrintString("Turning WiFi module OFF... Goodbye!\n");
                //TurnOFFWiFi();
                mTerminalPendingAction = TERMINAL_ACTION_TURN_OFF_WIFI;
            }
            else
            {
                TerminalPrintString("WiFi module already OFF... that's weird!\n");
            }
		}	
        else if(strncmp(mDataString1,"status",strlen("status")) == 0) 
		{
            switch (GetWiFiSate())
            {
                case WIFI_MODULE_OFF_STATE:
                {
                    TerminalPrintString("WiFi module OFF\n");
                    break;
                }
                case WIFI_CONNECTED_STATE:
                {
                    TerminalPrintString("WiFi Connected\n");
                    break;
                }
                case WIFI_DISCONNECTED_STATE:
                {
                    TerminalPrintString("WiFi Disconnected\n");
                    break;
                }
                case WIFI_INIT_ERROR_STATE:
                {
                    TerminalPrintString("WiFi ERROR\n");
                    break;
                }
                case WIFI_UNKNOWN_STATE:
                {
                    TerminalPrintString("WiFi state Unknown!\n");
                    break;
                }
            }
            
		}	
        
		TerminalPrintString("\n");
	}
    else if(strncmp(mCmdString,"battery",strlen("battery")) == 0)
	{
		if(strlen(mDataString1) == 0)
		{
			char voltage[15];
            sprintf(voltage,"%f",GetBatteryVoltage(0));
            TerminalPrintString("Battery Voltage: ");
            TerminalPrintString(voltage);
            TerminalPrintString("\n");
            char current[15];
            sprintf(current,"%d",GetSolarPanelCurrent());
            TerminalPrintString("Battery charge current: ");
            TerminalPrintString(current);
            TerminalPrintString("mA\n");
			return;
		}

        if(strncmp(mDataString1,"voltage",strlen("voltage")) == 0)
		{
            char voltage[15];
            sprintf(voltage,"%f",GetBatteryVoltage(0));
            TerminalPrintString("Battery Voltage: ");
            TerminalPrintString(voltage);
            TerminalPrintString("\n");
 		}
        else if(strncmp(mDataString1,"current",strlen("current")) == 0) 
		{
            char current[15];
            sprintf(current,"%d",GetSolarPanelCurrent());
            TerminalPrintString("Battery charge current: ");
            TerminalPrintString(current);
            TerminalPrintString("mA\n");
		}	
        else if(strncmp(mDataString1,"soc",strlen("soc")) == 0) 
		{
            char SOC[15];
            sprintf(SOC,"%d",GetBatterySOC());
            TerminalPrintString("Battery SOC: ");
        //    TerminalPrintString(SOC);
            TerminalPrintString("%\n");
		}	        
		TerminalPrintString("\n");
	}	
	else if(strncmp(mCmdString,"status",strlen("status")) == 0)
	{
       // TerminalPrintString("General status:\nBattery: TBD \nWiFi: TBD\nOther Stuff: TBD\n");
        TerminalPrintString("General status:\n");
        
//        if(GetChaletPowerRelayState() == CHALET_POWER_RELAY_OFF_STATE)
        {
//           TerminalPrintString("Inverter power relay: OFF\n"); 
        }
//        else if(GetChaletPowerRelayState() == CHALET_POWER_RELAY_ON_STATE)
        {
 //          TerminalPrintString("Inverter power relay: ON\n"); 
        }
  //      else
        {
//           TerminalPrintString("Inverter power relay: UNKNOWN\n");  
        }
        
        switch(GetWiFiSate())
        {
            case WIFI_MODULE_OFF_STATE:
            {
                TerminalPrintString("WiFi: Module is turned OFF\n"); 
                break;
            }
            case WIFI_CONNECTED_STATE:
            {
                TerminalPrintString("WiFi: Connected to AP\n"); 
                break;
            }
            case WIFI_DISCONNECTED_STATE:
            {
                TerminalPrintString("WiFi: Disconnected from AP\n"); 
                break;
            }
            case WIFI_INIT_ERROR_STATE:
            {
                TerminalPrintString("WiFi: Module initialization error\n"); 
                break;
            }
            case WIFI_UNKNOWN_STATE:
            default:
            {
               TerminalPrintString("WiFi: Unknown state\n"); 
                break;
            }
        }
        
        char voltage[15];
        memset(voltage,0,15);
        sprintf(voltage,"%.2f",GetBatteryVoltage(0));
        TerminalPrintString("Battery Voltage: ");
        TerminalPrintString(voltage);
        TerminalPrintString("V\n");
        
        char current[15];
        memset(current,0,15);
        sprintf(current,"%dmA\n",GetSolarPanelCurrent());
        TerminalPrintString("Battery charge current: ");
        TerminalPrintString(current);
        //TerminalPrintString("mA\n");
        
        Sleep(100);
        char SOC[15];
        memset(SOC,0,15);
        sprintf(SOC,"%d%%\n",GetBatterySOC());
        TerminalPrintString("Battery SOC: ");
        TerminalPrintString(SOC);
      //  TerminalPrintString("\n");
 
		
        TerminalPrintString("\n");
	}
	else if(strncmp(mCmdString,"bootloader",strlen("bootloader")) == 0)
	{
		if(strlen(mDataString1) == 0)
		{
			TerminalPrintString("\n[command] parameter is invalid.  Type 'help' for more info\n");
			return;
		}
        
        if(strncmp(mDataString1,"start",strlen("start")) == 0)
		{
            //start bootloader server
//			OpenBootloaderServer();
			BootloaderActivateBootloader();
			TerminalPrintString("Activating bootloader\n");
 		}
        else if(strncmp(mDataString1,"stop",strlen("stop")) == 0) 
		{
			//CloseBootloaderServer();
			TerminalPrintString("Deactivating bootloader\n");
				BootloaderDeactivateBootloader();
		}
		else if(strncmp(mDataString1,"status",strlen("status")) == 0) 
		{
			if(IsBootloaderClientConnected())
			{
				TerminalPrintString("\nBootloader client connected\n");
				return;
			}
			else
			if(IsBootloaderClientConnected())
			{
				TerminalPrintString("\nBootloader client not connected\n");
				return;
			}
		}
	
	}
	else if(strncmp(mCmdString,"debug",strlen(mCmdString)) == 0)
	{
        //		if(strlen(mDataString1) == 0)
        //		{
        //			TerminalPrintString("\n[subsystem] parameter is invalid.  Type 'help' for more info\n");
        //			return;
        //		}
        //        if(strlen(mDataString2) == 0)
        //		{
        //			TerminalPrintString("\n[timeout] parameter is invalid.  Type 'help' for more info\n");
        //			return;
        //		}
        //        
        //        unsigned int timeout = atoi(mDataString2);
        //        if(timeout != 0 && timeout < 100 && timeout > 5000)
        //        {
        //            TerminalPrint("[timeout] value must be between 100 & 5000.  Current value: %d",timeout);
        //            return;
        //        }
        //        
        //		if(strncmp(mDataString1,"valve",strlen("valve")) == 0)
        //		{
        //          //  TerminalPrintValveStatus();
        //            TerminalPrintString("Debug valve not implemented\n");
        //		}
        //        else if(strncmp(mDataString1,"flow",strlen("flow")) == 0)
        //		{
        //            if(timeout == 0)
        //            {
        //                TerminalPrintString("Flow debugging stopped\n");
        //                StopDebugFlowMeter();
        //            }
        //            else
        //            {
        //                TerminalPrintString("OK\n");
        //                StartDebugFlowMeter(timeout);
        //            }
        //		}
        //		else if(strncmp(mDataString1,"hygro",strlen("hygro")) == 0)
        //		{
        //            TerminalPrintString("Debug hygro not implemented\n");
        //		}
    }
    
    else
		TerminalPrintString("Unknown command\n\n");
}	

void TerminalPrintString(char *str)
{
#ifdef USE_WINC1500  
    SendTerminalData(str,strlen(str));
#else
#ifdef TERMINAL_USE_TCP_SERVER
    TCPPutString(mTerminalSocket, str);
#endif
#endif
}

void TerminalPrintChar(char byte)
{
#ifdef USE_WINC1500
    SentTerminalByte(byte);
#else
#ifdef TERMINAL_USE_TCP_SERVER
    TCPPut(mTerminalSocket,byte);
#endif
#endif
}

void TerminalStateMachine(void)
{
    
}	

//
//void TerminalPrintValveStatus()
//{
//    if(GetValveState() == VALVE_ON)
//    {
//        TerminalPrintString("The valve is ON\n");
//    }
//    else
//    {
//        TerminalPrintString("The valve is OFF\n");
//    }
//}
//
//void TerminalPrintFlowStatus()
//{
//    unsigned int Flow = GetCurrentFlow();
//    TerminalPrint("Flow: %d\n",Flow);;
//}
//
//void TerminalPrintHygroStatus(int unit)
//{
//    TerminalPrint("Hygro %d: ?\n",unit);
//}
//

//EOf

