/**************************************************************************************************/
/* LOW VOLTAGE LOAD SWITCHER BOARD																  */
/* Copyright 2012 MBARI.                                                    					  */
/* MBARI Proprietary Information. All rights reserved.                      					  */
/* FILENAME:		breaker.c																	  */
/* DESCRIPTION:		This file contains functions relating to the operation of the				  */
/*					board's circuit breakers.													  */
/* FUNCTION LIST:	brkrReset(int channel)														  */
/*					brkrState(int channel)														  */
/**************************************************************************************************/
#include <p24fxxxx.h>
#include <stdio.h>

#include "dig_io.h"
#include "sys_defs.h"
#include "spi2.h"
#include "expander.h"
#include "actions.h"
#include "breaker.h"
#include "sys_timer.h"
#include "potentiometer.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
//	NAME:			brkrReset(int channel)
//	DESCRIPTION:	Resets the circuit breaker on channel n. 		
////////////////////////////////////////////////////////////////////////////////////////////////////
void brkrReset(int channel)
{
	int prev_state1, prev_state2, dummy;

	prev_state1 = potReadWrite(POT_01_CS, READ, WIPER_2, 0x00);
	prev_state2 = potReadWrite(POT_02_CS, READ, WIPER_2, 0x00);
			
	switch(channel)
	{
		case 1:
		{
			//RESET CKT_BRKR_01

			dummy = potReadWrite(POT_01_CS, WRITE, WIPER_2, 0);			//prevent UV condition

			expSetLow(DIO_01_CS, GPIOB, GP4);	//SET CKT_BRKR_01_RST LOW
			tmrDelayMs(1);						//reset time
			expSetHigh(DIO_01_CS, GPIOB, GP4);	//TURN BACK ON
			tmrDelayMs(50);
			dummy = potReadWrite(POT_01_CS, WRITE, WIPER_2, prev_state1);	
			break;
		}
		case 2:
		{
			//RESET CKT_BRKR_02

			dummy = potReadWrite(POT_02_CS, WRITE, WIPER_2, 0);			//prevent UV condition

			expSetLow(DIO_01_CS, GPIOA, GP4);	//SET CKT_BRKR_02_RST LOW
			tmrDelayMs(1);						//reset time
			expSetHigh(DIO_01_CS, GPIOA, GP4);	//TURN BACK ON
			tmrDelayMs(50);
			dummy = potReadWrite(POT_02_CS, WRITE, WIPER_2, prev_state2);
			break;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////
//	NAME:			brkrState(int channel)
//	DESCRIPTION:	Checks the state of the circuit breaker on channel n. 		
////////////////////////////////////////////////////////////////////////////////////////////////////
int brkrState(int channel)
{
	int state;
	
	switch(channel)
	{
		case 1:
		{
			state = expReadBit(DIO_01_CS, GPIOB, GP3);		//READ CKT_BRKR_01_STATE
			break;
		}
		case 2:
		{
			state = expReadBit(DIO_01_CS, GPIOA, GP3);		//READ CKT_BRKR_02_STATE
		}
	}

	return state;
}