/**** Includes ****/
#include "../utils/utils.h"
#include "fuse.h"

using namespace hw;

/**** Private definitions ****/
/**** Private constants ****/
/**** Private variables ****/
/**** Private function declarations ****/

/**** Public function definitions ****/
hw::Fuse::Fuse(bsp::AnalogIn* ain_ch)
{
	this->hold_current = 0;
	this->trip_cycles = 0;
	this->warning = 0;
	this->fault = 0;
	this->cooldown_counter = 0;
	this->cooldown_cycles = 0;
	this->retry_cnt = 0;
}

hw::Fuse::~Fuse(void)
{
	return;
}

void hw::Fuse::update(void)
{
	// Under threshold
	if(this->ain_ch->last_read <= this->hold_current)
	{
		// Clear warning flag
		this->warning = 0;
		
		// OC energy counter
		if(this->oc_counter > 0) this->oc_counter--;
		
		// Cool down fuse
		if(this->cooldown_counter > 0) this->cooldown_counter--;
		
		// Auto reset logic
		if((this->fault)&&(this->cooldown_counter==0))
		{
			this->fault = 0;
			this->retry_cnt = util::sat_add(this->retry_cnt, 1);
		};
		return;
	};

	// Over current condition
	this->warning = 1;
		
	// PC energy counter
	this->oc_counter = util::sat_add(this->oc_counter, 1);
		
	// Check for trip threshold
	if(this->oc_counter < this->trip_cycles) return;
		
	// Trip fuse
	this->fault = 1;
	this->cooldown_counter = this->cooldown_cycles;
}

/**** Private function definitions ****/
