#include "StdAfx.h"
#include <string>
#include "NI_DAQ.h"

//TaskHandle NI_DAQ::taskHandle = 0; //inicilalizace staticke, kdyz budu pridavat, dalsi task tak se bude zvetsovat
NI_DAQ::NI_DAQ(void)
{

}

NI_DAQ::NI_DAQ(char IO, char* Dev, char* channel)
{
	char *auxarray;
	int arrsize;
	AOtaskHandle = 0;
	AItaskHandle = 0;
	error = 0;
	/*DAQmxCreateTask("",&AOtaskHandle);
	DAQmxCreateAOVoltageChan(AOtaskHandle,"Dev1/ao0","",0.0,5.0,DAQmx_Val_Volts,NULL);
	DAQmxStartTask(AOtaskHandle);*/

	arrsize = sizeof(Dev)+sizeof(channel)+1;
	auxarray = (char*)malloc(arrsize);
	strcpy_s(auxarray, arrsize, Dev);
	strcat_s(auxarray, arrsize, "/");
	strcat_s(auxarray, arrsize, channel);

	switch (IO)
	{
	case 'O':
		if((error = DAQmxCreateTask("",&AOtaskHandle))==0)
		{	
			
			if((error = DAQmxCreateAOVoltageChan(AOtaskHandle,auxarray,"",0,5.0,DAQmx_Val_Volts,NULL))==0)
				error = DAQmxStartTask(AOtaskHandle);
		}
		break;
	case 'I':
		if((error = DAQmxCreateTask("",&AItaskHandle))==0)
			if((error = DAQmxCreateAIVoltageChan(AItaskHandle,auxarray,"",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,NULL))==0) //DAQmx_Val_RSE
				error = DAQmxStartTask(AItaskHandle);
		break;
	}

	if( DAQmxFailed(error) )
		DAQmxGetExtendedErrorInfo(errBuff,2048);
}

int NI_DAQ::change_channel(char IO, char* Dev, char* channel)
{
	char *auxarray;
	int arrsize;

	arrsize = sizeof(Dev)+sizeof(channel)+1;
	auxarray = (char*)malloc(arrsize);
	strcpy_s(auxarray, arrsize, Dev);
	strcat_s(auxarray, arrsize, "/");
	strcat_s(auxarray, arrsize, channel);

	switch (IO)
	{
	case 'O':
		if( AOtaskHandle!=0 ) 
		{
			DAQmxStopTask(AOtaskHandle);
			DAQmxClearTask(AOtaskHandle);
		}
		if((error = DAQmxCreateTask("",&AOtaskHandle))==0)
		{	
			
			if((error = DAQmxCreateAOVoltageChan(AOtaskHandle,auxarray,"",0,5.0,DAQmx_Val_Volts,NULL))==0)
				error = DAQmxStartTask(AOtaskHandle);
		}
		break;
	case 'I':
		if( AItaskHandle!=0 ) 
		{
			DAQmxStopTask(AItaskHandle);
			DAQmxClearTask(AItaskHandle);
		}
		if((error = DAQmxCreateTask("",&AItaskHandle))==0)
			if((error = DAQmxCreateAIVoltageChan(AItaskHandle,auxarray,"",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,NULL))==0) //DAQmx_Val_RSE
				error = DAQmxStartTask(AItaskHandle);
		break;
	}

	if( DAQmxFailed(error) )
		DAQmxGetExtendedErrorInfo(errBuff,2048);
	return error;
}
int NI_DAQ::write(double _data)
{
	if (error == 0)
		error = DAQmxWriteAnalogScalarF64(AOtaskHandle,1,0.1,_data,NULL);
	return error;
}

int NI_DAQ::read(double* _data)
{
	if (error == 0)
		error = DAQmxReadAnalogScalarF64(AItaskHandle,0.1,_data,NULL);
	return error;
}

NI_DAQ::~NI_DAQ(void)
{
	if( AOtaskHandle!=0 ) 
	{
		DAQmxStopTask(AOtaskHandle);
		DAQmxClearTask(AOtaskHandle);
	}
	if( AItaskHandle!=0 ) 
	{
		DAQmxStopTask(AItaskHandle);
		DAQmxClearTask(AItaskHandle);
	}
}
