/*
 * an_gen.c
 *
 *  Created on: 19-07-2017
 *      Author: KJ
 */


#include "tdefs.h"
#include "misc.h"
#include <math.h>

#include "an_gen.h"
#include "analog_in.h"
#include "dev_ctrl.h"
#include "elements.h"
#include "config.h"
#include <ti/sysbios/hal/Hwi.h>

//u16 bus_an_samples_buf_force[MAX_AN_CARDS][4][4];

#define SAMPLE_STEP	(50.0f/(SAMPLES_PER_MS*1000.0f))

struct an_gen_force_params genpar;
u8 an_gen_buf_ready = 0;

int an_gen_initlog(void *arguments, void *logic)
{
	return 0;
}

void an_gen(void *arguments, void *logic)
{
	int i,j;
	u8 an_gen_sample_num;

	if(!(dev_ctrl_state & DEV_CTRL_STATE_TEST_AN) || !genpar.an_force_mask)
	{
		an_gen_buf_ready=0;
		return;
	}

	UInt key = Hwi_disable();

	an_gen_sample_num=bus_an_cur_sample_num+(SAMPLES_PER_MS*LOOP_CYCLE_MS);
	an_gen_sample_num%=(SAMPLES_PER_MS*MAIN_FREQ_PERIOD_MS*2);

	for(j=0;j<(SAMPLES_PER_MS*LOOP_CYCLE_MS);j++)
	{
		for(i=0;i<=(MAX_AN_CARDS/2 * 4);i++)
			if(genpar.an_force_mask & (1<<i))
				bus_an_samples_buf[i>>2][i%4][an_gen_sample_num] = (u16)(genpar.an_force_amp[i/4][i%4] * sinf(2 * PI * SAMPLE_STEP * (bus_an_cur_timestamp+(SAMPLES_PER_MS*LOOP_CYCLE_MS)+j) + genpar.an_force_ph[i/4][i%4]) + 32768);

		an_gen_sample_num++;
		an_gen_sample_num%=(SAMPLES_PER_MS*MAIN_FREQ_PERIOD_MS*2);
	}

	an_gen_buf_ready=1;
	Hwi_restore(key);
}
