using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HTRA_CSharp_Examples
{
    class DSP_DDC
    {
		public void Example()
		{
			#region 1 Open device

			int Status = 0;              //Function return value.
			IntPtr Device = IntPtr.Zero; //Current device memory address.
			int DevNum = 0;              //Specify device number.

			HtraApi.BootProfile_TypeDef BootProfile = new HtraApi.BootProfile_TypeDef(); //Boot configuration structure, including physical interface, power supply, etc.
			HtraApi.BootInfo_TypeDef BootInfo = new HtraApi.BootInfo_TypeDef();          //Boot info structure, including device information, USB speed, etc.

			BootProfile.DevicePowerSupply = HtraApi.DevicePowerSupply_TypeDef.USBPortAndPowerPort; //Use both USB data port and independent power port for dual power supply.

			//If the device data interface is USB, run directly. If it's Ethernet, change #if true to #if false
#if true
			BootProfile.PhysicalInterface = HtraApi.PhysicalInterface_TypeDef.USB;
#else
			//Configure network parameters
			BootProfile.PhysicalInterface = HtraApi.PhysicalInterface_TypeDef.ETH;
			BootProfile.ETH_IPVersion = HtraApi.IPVersion_TypeDef.IPv4;
			BootProfile.ETH_RemotePort = 5000;
			BootProfile.ETH_ReadTimeOut = 5000;
			BootProfile.ETH_IPAddress = new byte[16];
			BootProfile.ETH_IPAddress[0] = 192;
			BootProfile.ETH_IPAddress[1] = 168;
			BootProfile.ETH_IPAddress[2] = 1;
			BootProfile.ETH_IPAddress[3] = 100;
#endif

			Status = HtraApi.Device_Open(ref Device, DevNum, ref BootProfile, ref BootInfo); //Open the device

			if (Status == 0)
			{
				System.Console.WriteLine("Device is opened successfully");
			}

			/*If device opening fails, return an error message. If the following errors occur, the device will not operate normally. It is recommended to follow the prompts and try reopening the device.*/
			else
			{
				switch (Status)
				{
					case HtraApi.APIRETVAL_ERROR_BusOpenFailed:
						System.Console.WriteLine("Error - Check the device power supply, data cable connection and driver installation");
						return;

					case HtraApi.APIRETVAL_ERROR_RFACalFileIsMissing:
						System.Console.WriteLine("Error - RF calibration file is missing");
						return;

					case HtraApi.APIRETVAL_ERROR_IFACalFileIsMissing:
						System.Console.WriteLine("Error - IF calibration file is missing");
						return;

					case HtraApi.APIRETVAL_ERROR_DeviceConfigFileIsMissing:
						System.Console.WriteLine("Error - Configuration file missing");
						return;

					case HtraApi.APIRETVAL_ERROR_DeviceSpecFileIsMissing:
						System.Console.WriteLine("Error - Device specification file is missing");
						return;

					case HtraApi.APIRETVAL_ERROR_FirmwareVersionMismatch:
						System.Console.WriteLine("Error - Firmware Version Mismatch");
						break;

					default:
						System.Console.WriteLine("Return other errors! Status = " + Status);
						return;
				}
			}
			#endregion

			#region 2 Configure Parameters
			HtraApi.IQStream_TypeDef IQStream = new HtraApi.IQStream_TypeDef();               //Parameters related to IQ data acquisition under the current configuration, including IQ data, ScaleToV, I_MaxValue, etc.
			HtraApi.IQS_Profile_TypeDef IQSIn = new HtraApi.IQS_Profile_TypeDef();            //IQS mode input configuration, including center frequency, decimation factor, reference level, etc.
			HtraApi.IQS_Profile_TypeDef IQSOut = new HtraApi.IQS_Profile_TypeDef();           //IQS mode output configuration.
			HtraApi.IQS_StreamInfo_TypeDef StreamInfo = new HtraApi.IQS_StreamInfo_TypeDef(); //IQ data stream-related information under the current configuration.

			IQSIn.CenterFreq_Hz = 1e9;                                   //Set center frequency.
			IQSIn.RefLevel_dBm = 0;                                      //Set reference level.
			IQSIn.DataFormat = HtraApi.DataFormat_TypeDef.Complex16bit;  //Set IQ data format.
			IQSIn.TriggerMode = HtraApi.TriggerMode_TypeDef.FixedPoints; //Set trigger mode.
			IQSIn.TriggerSource = HtraApi.IQS_TriggerSource_TypeDef.Bus; //Set trigger source to internal bus trigger.
			IQSIn.DecimateFactor = 2;                                    //Set decimation factor.
			IQSIn.BusTimeout_ms = 5000;                                  //Set bus timeout duration.
			IQSIn.TriggerLength = 16242;                                 //Set number of sampling points.

			Status = HtraApi.IQS_Configuration(ref Device, ref IQSIn, ref IQSOut, ref StreamInfo); //Call this function to apply the IQS mode configuration.

			Int16[] AlternIQStream = new Int16[StreamInfo.StreamSamples * 2]; //Create an array to store IQ data, in the format IQIQIQ...

			//Enable DSP functionality
			IntPtr DSP = IntPtr.Zero;  //Allocate memory for digital signal processing
			HtraApi.DSP_Open(ref DSP); //Start signal processing functionality

			//DDC Mode Configuration
			HtraApi.IQStream_TypeDef IQStreamOut = new HtraApi.IQStream_TypeDef();  //DDC input configuration, including frequency offset for mixing, sampling rate, number of samples, etc.
			HtraApi.DSP_DDC_TypeDef DDC_ProfileIn = new HtraApi.DSP_DDC_TypeDef();  //DDC output configuration.
			HtraApi.DSP_DDC_TypeDef DDC_ProfileOut = new HtraApi.DSP_DDC_TypeDef(); //IQ data after DDC processing (configuration, returned info, and temporary data).

			Status = HtraApi.DSP_DDC_DeInit(ref DDC_ProfileIn);    //Call this function to initialize DDC mode configuration
			DDC_ProfileIn.DDCOffsetFrequency = 10e6;               //Set DDC frequency offset
			DDC_ProfileIn.DecimateFactor = 2;                      //Set DDC decimation factor
			DDC_ProfileIn.SamplePoints = StreamInfo.PacketSamples; //Set number of samples
			DDC_ProfileIn.SampleRate = StreamInfo.IQSampleRate;    //Set sampling rate
			Status = HtraApi.DSP_DDC_Configuration(ref DSP, ref DDC_ProfileIn, ref DDC_ProfileOut); //Apply DDC mode configuration

			//FFT Mode Configuration
			HtraApi.DSP_FFT_TypeDef IQToSpectrumIn = new HtraApi.DSP_FFT_TypeDef();  //FFT mode input configuration, including FFT points, detection method, etc.
			HtraApi.DSP_FFT_TypeDef IQToSpectrumOut = new HtraApi.DSP_FFT_TypeDef(); //FFT mode output configuration.
			UInt32 TracePoints = 0;													 //FFT mode output configuration.

			HtraApi.DSP_FFT_DeInit(ref IQToSpectrumIn); //Call this function to initialize FFT mode configuration.

			IQToSpectrumIn.Calibration = false;													//Set whether to enable calibration. Set 0 to disable calibration, other values to enable.
			IQToSpectrumIn.DetectionRatio = 1;													//Set detection ratio
			IQToSpectrumIn.TraceDetector = HtraApi.TraceDetector_TypeDef.TraceDetector_PosPeak; //Set detection method
			IQToSpectrumIn.FFTSize = (UInt32)DDC_ProfileOut.SamplePoints;						//Set FFT points
			IQToSpectrumIn.Intercept = 1;														//Set intercept ratio
			IQToSpectrumIn.SamplePts = (UInt32)DDC_ProfileOut.SamplePoints;						//Set number of samples
			IQToSpectrumIn.WindowType = HtraApi.Window_TypeDef.FlatTop;							//Set window type

			double RBWRatio = 0; //This parameter returns the RBW ratio, RBW = RBWRatio * StreamInfo.IQSampleRate.

			HtraApi.DSP_FFT_Configuration(ref DSP, ref IQToSpectrumIn, ref IQToSpectrumOut, ref TracePoints, ref RBWRatio); //Apply FFT mode configuration.

			double[] Frequency = new double[TracePoints]; //Array to store frequency values.
			float[] Spectrum = new float[TracePoints];    //Array to store power values.
			#endregion

			#region 3 Data Collection
			while (true)
			{
				Status = HtraApi.IQS_BusTriggerStart(ref Device); //Call IQS_BusTriggerStart to trigger the device. If the trigger source is external, this function is not needed.

				for (UInt64 i = 0; i < StreamInfo.PacketCount; i++)
				{
					Status = HtraApi.IQS_GetIQStream_PM1(ref Device, ref IQStream); //Get IQ data packet, trigger information, I channel max value, and max value index.
					if (Status == 0)
					{
						unsafe
						{
							System.Int16* IQ = (System.Int16*)IQStream.AlternIQStream; //Used to retrieve IQ data
							UInt32 points = StreamInfo.PacketSamples;                  //Number of data points in a packet
							if (i == StreamInfo.PacketCount - 1 && StreamInfo.StreamSamples % StreamInfo.PacketSamples != 0) //Check for the last packet and if it's not full
							{
								points = (UInt32)StreamInfo.StreamSamples % StreamInfo.PacketSamples; //Calculate the number of data points in the last packet
							}
							for (int j = 0; j < points; j++) //Write IQ data into the array
							{
								AlternIQStream[j + StreamInfo.PacketSamples * (int)i] = IQ[j];
							}
						}
					}

					else
					{
						/*If data retrieval fails, return error message. When the following errors occur, it's recommended to follow the prompts to reattempt.*/
						switch (Status)
						{
							case HtraApi.APIRETVAL_ERROR_BusError:  //IQS_GetIQStream returns -8, suggests reconfiguring parameters and retrying
								System.Console.WriteLine("Error - Bus communication error");
								Status = HtraApi.IQS_Configuration(ref Device, ref IQSIn, ref IQSOut, ref StreamInfo);
								break;

							case HtraApi.APIRETVAL_ERROR_BusDataError: //IQS_GetIQStream returns -9, suggests reconfiguring parameters and retrying
								System.Console.WriteLine("Error - The data content is incorrect");
								Status = HtraApi.IQS_Configuration(ref Device, ref IQSIn, ref IQSOut, ref StreamInfo);
								break;

							case HtraApi.APIRETVAL_WARNING_BusTimeOut: //IQS_GetIQStream returns -10, suggests checking if the trigger source is normal before retrying
								System.Console.WriteLine("Warning - Get data timed out, check if the trigger source is triggered normally");
								break;

							case HtraApi.APIRETVAL_WARNING_IFOverflow: //IQS_GetIQStream returns -12, suggests reconfiguring parameters and retrying
								System.Console.WriteLine("WARNING - IF saturation is recommended to be reconfigured, reference level <= signal power");
								break;

							case HtraApi.APIRETVAL_WARNING_ReconfigurationIsRecommended: //IQS_GetIQStream returns -14, suggests reconfiguring parameters and retrying
								System.Console.WriteLine("Warning - The current device temperature has changed significantly relative to the configured temperature, and it is recommended to reconfigure \n");
								break;

							case HtraApi.APIRETVAL_WARNING_ClockUnlocked_SYSCLK: //IQS_GetIQStream returns -15, suggests reconfiguring parameters and retrying
								System.Console.WriteLine("Warning - There may be an anomaly in the hardware status of the device and reconfiguration is recommended\n");
								break;
							default:
								break;
						}
						System.Console.WriteLine("Status = " + Status);
					}

				}

				unsafe
				{
					fixed (Int16* ptr = AlternIQStream)
					{
						IQStream.AlternIQStream = (IntPtr)ptr;												   //Point the AlternIQStream pointer to the actual address where IQ data exists.
						Status = HtraApi.DSP_DDC_Execute(ref DSP, ref IQStream, ref IQStreamOut);              //Execute DDC (Digital Down-Conversion).
						Status = HtraApi.DSP_FFT_IQSToSpectrum(ref DSP, ref IQStreamOut, Frequency, Spectrum); //Execute IQ to Spectrum function.
					}
				}

				for (int i = 0; i < TracePoints; i++)
				{
					System.Console.WriteLine("Frequency:" + Frequency[i].ToString() + ",  " + "Spectrum:" + Spectrum[i].ToString());
				}
			}
			#endregion

			#region 4 Close
			Status = HtraApi.IQS_BusTriggerStop(ref Device); //Call IQS_BusTriggerStop to stop triggering the device. If the trigger source is external, this function is not needed.
			HtraApi.DSP_Close(ref DSP);
			HtraApi.Device_Close(ref Device);
			#endregion
		}
	}
}
