#include "delay.h"
#include "CommandsDefine.h"
#include "AnalogChannelCtrl_Dictionary.h"
#include "ProjectConfig.h"
#include "Probe_MSO7000X_2d5g.h"
#include "AnalogChannelCtrl_2d5g_base.h"
#include "Helper.h"
//////////////////////////////////////////////////////////////////////////////
// 			2203/5/X GHz_ljw 合并版
//////////////////////////////////////////////////////////////////////////////
 
u32 GetDACConfigWord(struct ParasDAC params,u8* dac_index)
{
	u32 ConfigWord = 0x10300000;
	u8 dataType = refCtrl;
	if(params.isBias == 0) //hardware move
	{
		dataType = params.high_low == 0 ? move_hz : move_lz;
	}
	else if(params.isBias == 1) //bias, hardware offset
	{
		dataType = params.high_low == 0 ? offset_hz : offset_lz;
	}
	
	dac_index[0] = dacPortInfoTable[params.channelId-1][dataType][0] - 5;
	u8 dac_indexEx = dacPortInfoTable[params.channelId-1][dataType][2];
	u8 port = dacPortInfoTable[params.channelId-1][dataType][1];
	ConfigWord |= dac_indexEx << 24;
	ConfigWord |= port << 16;
	ConfigWord |= params.data;

	return ConfigWord;
}

void ChannelOffsetSet(u8 *pData,u8 channelId){
	//if(channelId!=1) return;
	u32 ConfigWord_dac;	 
	u8 dac_index;
	u8 isBias = pData[0];
	u8 high_low = pData[1];
	u16 dac = pData[2] + (pData[3]<<8);
	if(isBias==0)
	{
		isBias=1;
	}
	else
	{
		isBias=0;
	}
	 
	//控制字
	struct ParasDAC paramsDAC;
	//bias
	paramsDAC.high_low = high_low;
	paramsDAC.channelId = channelId;
	paramsDAC.data = dac;
	paramsDAC.isBias = isBias;
	ConfigWord_dac = GetDACConfigWord(paramsDAC,&dac_index);
	
	DAC_AD5628(ConfigWord_dac,dac_index);
		//if(channelId==1){
		//	channelId=channelId; //test point
		//}
		//if(channelId==2){
		//	channelId=channelId; //test point
		//}
		//	if(channelId==3){
		//	channelId=channelId; //test point
		//}
		//		if(channelId==4){
		//	channelId=channelId; //test point
		//}
	
	//delay_ms(10);
	delay_ms(1);
	
}
void CMD0x40_Request_AnalogChannelCalcOffset_process(u8 *pData,u16 dataLen,u8 bIsContentBitInverted_Recv,u8 bIsContentBitInverted_SendBack)
{
#ifdef RUNNING_WHERE_AT_BOOT	
	Command_SendbackErrorMessage(Error0x02_CannotRunAtBoot,1);
#else
	u8 bDataOK=1;
	u8 validDataLength=dataLen;
	if (bIsContentBitInverted_Recv)
	{
		validDataLength=dataLen/2;
		if (!Helper_CheckInvertBytesIsRegist(pData,dataLen))
			bDataOK=0;
	}
	if (validDataLength<5)
		bDataOK=0;
	if (bDataOK)
	{
		u8 channelId = pData[0];
		IsChannelSetting = 1;	
		for(int i=0; i<MAX_CHANNEL_NUM; i++)
		{
			if(((channelId>>i) & 0x01) == 1){
					ChannelOffsetSet(pData + 1,i+1);
					delay_us(10);
			}
		}		
	}
	else
		Command_SendbackErrorMessage(Error0x05_CMD_ParaLentghError,1);			
#endif		
}
