//#include <proc/p32mx440f256h.h>

#include "HarakiriRelay.h"
#include "BoardCfg.h"
#include "timer.h"
#include "LoraWatchdog.h"

int mLoraSMState;



void InitLoraWatchdog()
{
	mLoraSMState = LORA_WATCHDOG_OK_STATE;
	TimerStart(LORA_WATCHDOG_TIMER,LORA_WATCHDOG_MODULE_RESET_TIMEOUT);
}

void TickLoraWatchdog()
{
	LoraWatchdogStateMachine(LORA_SM_TICK_EVENT);
}

void LoraWatchdogStateMachine(int Event)
{
	switch(mLoraSMState)
	{
		case LORA_WATCHDOG_OK_STATE:
		{
			switch(Event)
			{
				case LORA_SM_TICK_EVENT:
				{
					if(IsTimerExpired(LORA_WATCHDOG_TIMER))
					{
						//We lost the comm...  reset the LoRa module
						LORA_MODULE_RELAY_PIN = 1;	//Turn OFF the LoRa module
						TimerStart(LORA_WATCHDOG_TIMER,LORA_WATCHDOG_MODULE_OFF_TIMEOUT);
						mLoraSMState = LORA_WATCHDOG_RESET_LORA_MODULE_STATE;
					}
					break;
				}
				case LORA_SM_KICK_EVENT:
				{
					//All is well...
					TimerStart(LORA_WATCHDOG_TIMER,LORA_WATCHDOG_MODULE_RESET_TIMEOUT);
					break;
				}
			}
			break;
		}
		case LORA_WATCHDOG_RESET_LORA_MODULE_STATE:
		{
			switch(Event)
			{
				case LORA_SM_TICK_EVENT:
				case LORA_SM_KICK_EVENT://That would be very weird since the LoRa module is OFF!!!
				{
					if(IsTimerExpired(LORA_WATCHDOG_TIMER))
					{
						//Reset is done, turn module back ON.
						LORA_MODULE_RELAY_PIN = 0;	//Turn ON the LoRa module
						TimerStart(LORA_WATCHDOG_TIMER,LORA_WATCHDOG_REBOOT_TIMEOUT);	//If we don't get Comm. back after this delay... reboot the PIC
						mLoraSMState = LORA_WATCHDOG_WAIT_FOR_RECONNECT_STATE;
					}
					break;
				}
			}
			break;
		}
		case LORA_WATCHDOG_WAIT_FOR_RECONNECT_STATE:
		{
			switch(Event)
			{
				case LORA_SM_TICK_EVENT:
				{
					if(IsTimerExpired(LORA_WATCHDOG_TIMER))
					{
						
						TurnOFFWiFi();
						Sleep(100);
						SoftReset();
					}
					break;
				}
				case LORA_SM_KICK_EVENT:
				{
					//Communication is re-established.
					TimerStart(LORA_WATCHDOG_TIMER,LORA_WATCHDOG_MODULE_RESET_TIMEOUT);
					mLoraSMState = LORA_WATCHDOG_OK_STATE;
					break;
				}
			}
			break;
		}
	}
}

void KickLoraWatchdog()
{
	LoraWatchdogStateMachine(LORA_SM_KICK_EVENT);
}
