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

namespace HTRA_CSharp_Examples
{
    class DSP_IQSToSpectrum
    {
		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.IQS_Profile_TypeDef IQS_ProfileIn = new HtraApi.IQS_Profile_TypeDef();    //IQS input configuration, including start frequency, stop frequency, RBW, reference level, etc.
			HtraApi.IQS_Profile_TypeDef IQS_ProfileOut = new HtraApi.IQS_Profile_TypeDef();   //IQS output configuration.
			HtraApi.IQS_StreamInfo_TypeDef StreamInfo = new HtraApi.IQS_StreamInfo_TypeDef(); //IQ data information under current configuration, including bandwidth, single-channel sample rate, etc.
			HtraApi.IQStream_TypeDef IQStream = new HtraApi.IQStream_TypeDef();               //Store IQ data packets, including IQ data and configuration information.

			HtraApi.IQS_ProfileDeInit(ref Device, ref IQS_ProfileIn); //Initialize related parameters for IQS mode configuration.

			IQS_ProfileIn.CenterFreq_Hz = 1e9;                                   //Configure center frequency
			IQS_ProfileIn.RefLevel_dBm = 0;                                      //Configure reference level
			IQS_ProfileIn.DecimateFactor = 2;                                    //Configure decimation factor
			IQS_ProfileIn.DataFormat = HtraApi.DataFormat_TypeDef.Complex16bit;  //Configure IQ data format
			IQS_ProfileIn.TriggerMode = HtraApi.TriggerMode_TypeDef.FixedPoints; //Configure trigger mode.
			IQS_ProfileIn.TriggerSource = HtraApi.IQS_TriggerSource_TypeDef.Bus; //Configure trigger source as internal bus trigger.
			IQS_ProfileIn.BusTimeout_ms = 5000;                                  //Configure bus timeout.
			IQS_ProfileIn.TriggerLength = 16242;                                 //Configure sample points.

			Status = HtraApi.IQS_Configuration(ref Device, ref IQS_ProfileIn, ref IQS_ProfileOut, ref StreamInfo);  //Apply the IQS mode configuration by calling this function.
			if (Status == 0)
			{
				System.Console.WriteLine("configuration delievery succeeded");
			}
			else
			{
				System.Console.WriteLine("SWP_Configuration call is incorrect,Status = " + Status);
				HtraApi.Device_Close(ref Device);
			}

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

			IntPtr DSP = IntPtr.Zero;  
			HtraApi.DSP_Open(ref DSP); //Open DSP functionality.

			HtraApi.DSP_FFT_TypeDef IQToSpectrumIn = new HtraApi.DSP_FFT_TypeDef();  //Configure FFT mode parameters.
			HtraApi.DSP_FFT_TypeDef IQToSpectrumOut = new HtraApi.DSP_FFT_TypeDef(); //Feedback actual FFT mode parameters.
			UInt32 TracePoints = 0;                                                  //Number of spectrum points after FFT.

			HtraApi.DSP_FFT_DeInit(ref IQToSpectrumIn); //Initialize related parameters for FFT mode configuration.

			IQToSpectrumIn.Calibration = false;                                                 //Configure whether to enable calibration, 0 means no calibration, other values enable calibration.
			IQToSpectrumIn.DetectionRatio = 1;                                                  //Configure detection ratio.
			IQToSpectrumIn.TraceDetector = HtraApi.TraceDetector_TypeDef.TraceDetector_PosPeak; //Configure detection method.
			IQToSpectrumIn.FFTSize = (UInt32)StreamInfo.StreamSamples;                          //Configure FFT points.
			IQToSpectrumIn.Intercept = 1;                                                       //Configure intercept rate.
			IQToSpectrumIn.SamplePts = (UInt32)StreamInfo.StreamSamples;                        //Configure sample points.
			IQToSpectrumIn.WindowType = HtraApi.Window_TypeDef.FlatTop;                         //Configure window type.

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

			HtraApi.DSP_FFT_Configuration(ref DSP, ref IQToSpectrumIn, ref IQToSpectrumOut, ref TracePoints, ref RBWRatio); //Apply the FFT mode configuration by calling this function.

			double[] Frequency = new double[TracePoints]; //Frequency array.
			float[] Spectrum = new float[TracePoints];    //Amplitude array.
			#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 required.

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


					else
					{
						/*When data retrieval fails, return an error message. If the following errors occur, it is recommended to follow the suggested actions:*/
						switch (Status)
						{
							case HtraApi.APIRETVAL_ERROR_BusError:  //When IQS_GetIQStream returns -8, it is recommended to reconfigure the parameters and try retrieving again
								System.Console.WriteLine("Error - Bus communication error");
								Status = HtraApi.IQS_Configuration(ref Device, ref IQS_ProfileIn, ref IQS_ProfileOut, ref StreamInfo);
								break;

							case HtraApi.APIRETVAL_ERROR_BusDataError: //When IQS_GetIQStream returns -9, it is recommended to reconfigure the parameters and try retrieving again.
								System.Console.WriteLine("Error - The data content is incorrect");
								Status = HtraApi.IQS_Configuration(ref Device, ref IQS_ProfileIn, ref IQS_ProfileOut, ref StreamInfo);
								break;

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

							case HtraApi.APIRETVAL_WARNING_IFOverflow: //When IQS_GetIQStream returns -12, it is recommended to reconfigure the parameters and try retrieving again.
								System.Console.WriteLine("WARNING - IF saturation is recommended to be reconfigured, reference level <= signal power");
								break;

							case HtraApi.APIRETVAL_WARNING_ReconfigurationIsRecommended: //When IQS_GetIQStream returns -14, it is recommended to reconfigure the parameters and try retrieving again.
								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: //When IQS_GetIQStream returns -15, it is recommended to reconfigure the parameters and try retrieving again.
								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;
                        HtraApi.DSP_FFT_IQSToSpectrum(ref DSP, ref IQStream, Frequency, Spectrum); //Execute IQ to spectrum function.
                    }
                }
			}
			#endregion

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