/*
 * detector.c
 *
 *  Created on: Dec 22, 2014
 *      Author: hutch
 */

#include "supportFiles/interrupts.h"
#include <stdint.h>
#include "filter.h"
#include "queue.h"
#include "isr.h"
#include "stdio.h"

#define TRANSMITTER_TICK_MULTIPLIER 3	// Call the tick function this many times for each ADC interrupt.

// Only has one "state" as the filtering process has to run slightly faster than the 100 kHz rate because it falls slightly behind
// at the beginning because filter_computePower() requires more time when starting up (has to perform all mult-accs).
// After testing, it was found that it was not possible to efficiently run the timer ISR faster than 100 kHz. As such,
// you can't affort to have any states as everything has to complete in a single tick.
void detector_tick() {
	static uint16_t sampleCount = 0;
	queue_size_t elementCount = isr_adcQueueElementCount();
	for (queue_size_t i=0; i<elementCount; i++) {		// Always drain the ADC queue.
		interrupts_disableArmInts();									// Disable interrupts while accessing the ADC queue.
		filter_addNewInput(isr_popAdcQueueData());	// Copy the input into the main filter input queue.
		interrupts_enableArmInts();										// Enable the interrupts as soon as possible.
		sampleCount++;																// Keep track of how many samples you have acquired.
		if (sampleCount == FILTER_FIR_DECIMATION_FACTOR) {	// Only invoke the filters after every DECIMATION_FACTOR times.
			sampleCount = 0;																	// Reset the sample count when you run the filters.
			filter_firFilter();																// Runs the FIR filter on the accumulated input and places the output in the y-queue.
			for (int filterNumber=0; filterNumber<FILTER_IIR_FILTER_COUNT; filterNumber++) {	// Run all of the IIR filters.
				filter_iirFilter(filterNumber);			// Run each of the IIR filters.
				filter_computePower(filterNumber);	// Compute the power for each of the filters.
			}
		}
	}
}




