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

namespace HTRA_CSharp_Examples
{
    class DET_GetPowerTrace_Standard
    {
		public void Example()
		{
			#region 1 Open Device

			int Status = 0;              //Function return value.
			IntPtr Device = IntPtr.Zero; //Memory address of the current device.
			int DevNum = 0;              //Specify the 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 info, USB speed, etc.

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

			//If the device data interface is USB, run directly. If it is Ethernet, change #if true to #if false
#if true
			BootProfile.PhysicalInterface = HtraApi.PhysicalInterface_TypeDef.USB;
#else
			//Configure network-related 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 the device fails to open, return an error message. In case of the following errors, the device cannot operate normally. It is recommended to follow the instructions and reattempt to open 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.DET_Profile_TypeDef DET_ProfileIn = new HtraApi.DET_Profile_TypeDef();    //DET input configuration, including center frequency, decimation factor, reference level, etc.
			HtraApi.DET_Profile_TypeDef DET_ProfileOut = new HtraApi.DET_Profile_TypeDef();   //DET output configuration.
			HtraApi.DET_StreamInfo_TypeDef StreamInfo = new HtraApi.DET_StreamInfo_TypeDef(); //DET data information under the current configuration, including DET data points, byte size, etc.

			HtraApi.DET_ProfileDeInit(ref Device, ref DET_ProfileIn); //Initialize the related parameters for DET mode.

			DET_ProfileIn.CenterFreq_Hz = 1e9;									 //Configure center frequency.
			DET_ProfileIn.RefLevel_dBm = 0;										 //Configure reference level.
			DET_ProfileIn.DecimateFactor = 2;									 //Configure decimation factor.
			DET_ProfileIn.TriggerSource = HtraApi.DET_TriggerSource_TypeDef.Bus; //Configure trigger source as internal bus trigger.

			//Configure trigger mode. FixedPoints mode triggers sampling at the rising edge of the signal. Sampling ends after TriggerLength points. Adaptive mode triggers sampling at the rising edge, and ends at the falling edge of the signal.
			//Run directly in Adaptive mode, or change #if true to #if false to use FixedPoints mode.
#if true
			DET_ProfileIn.TriggerMode = HtraApi.TriggerMode_TypeDef.Adaptive;
#else
			//Configure FixedPoints mode-related parameters
			DET_ProfileIn.TriggerMode = HtraApi.TriggerMode_TypeDef.FixedPoints;    
			DET_ProfileIn.TriggerLength = 16242;                                    //Configure the number of points to collect in a single trigger. This is only effective when TriggerMode is set to FixedPoints.
#endif
			Status = HtraApi.DET_Configuration(ref Device, ref DET_ProfileIn, ref DET_ProfileOut, ref StreamInfo); //Apply the related DET 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);
			}

			#endregion

			#region 3 Data Collection
			float[] NormalizedPowerStream = new float[StreamInfo.PacketSamples];				 //Store local amplitude data.
			float ScaleToV = 0;                                                                  //This parameter is the scaling factor for absolute amplitude (in volts).
			HtraApi.DET_TriggerInfo_TypeDef TriggerInfo = new HtraApi.DET_TriggerInfo_TypeDef(); //Trigger information.
			HtraApi.MeasAuxInfo_TypeDef MeasAuxInfo = new HtraApi.MeasAuxInfo_TypeDef();         //Auxiliary measurement data, including: power max index, power max value, device temperature, latitude and longitude, timestamp, etc.

#if true

			Status = HtraApi.DET_BusTriggerStart(ref Device); //Call DET_BusTriggerStart to trigger the device. If the trigger source is external, this function is not required.
			while (true)
			{
				Status = HtraApi.DET_GetPowerStream(ref Device, NormalizedPowerStream, ref ScaleToV, ref TriggerInfo, ref MeasAuxInfo); //Get DET data and trigger information.
				if (Status == 0)
				{
					//UserCode here

					//Example: Convert DET data to dBm
					//Example start
					for (int i = 0; i < StreamInfo.PacketSamples; i++)
					{
						NormalizedPowerStream[i] = (float)(10 * Math.Log10(20 * Math.Pow(NormalizedPowerStream[i] * ScaleToV, 2)));
					}
					//Example end
				}

				/*If data retrieval fails, return an error message. In case of the following errors, it is recommended to follow the instructions and reattempt to retrieve the data */
				else
				{
					switch (Status)
					{
						case HtraApi.APIRETVAL_WARNING_BusTimeOut:
							System.Console.WriteLine("Warning - Get data timed out, check if the trigger source is triggered normally");
							break;      //If DET_GetPowerStream returns -14, it is recommended to reconfigure parameters before retrieving again.

						case HtraApi.APIRETVAL_WARNING_IFOverflow:
							System.Console.WriteLine("WARNING - IF saturation is recommended to be reconfigured, reference level <= signal power");
							break;      // If DET_GetPowerStream returns -12, it is recommended to reconfigure parameters before retrieving again.
						default:
							System.Console.WriteLine("If the status of the get function is incorrect, check the process of getting data");
							break;
					}
					System.Console.WriteLine("Status = " + Status);
					break;

				}
				for (int k = 0; k < (int)StreamInfo.PacketSamples; k++)
				{
					System.Console.WriteLine(NormalizedPowerStream[k].ToString());
				}
			}


#else
			while (true)
			{
				Status = HtraApi.DET_BusTriggerStart(ref Device); //Call DET_BusTriggerStart to trigger the device. If the trigger source is external, this function is not required.
				for (int j = 0; j < (int)StreamInfo.PacketCount; j++)
				{
					Status = HtraApi.DET_GetPowerStream(ref Device, NormalizedPowerStream, ref ScaleToV, ref TriggerInfo, ref MeasAuxInfo); //Get DET data and trigger information.
					if (Status == 0)
					{
						//UserCode here

						//Example: Convert DET data to dBm
						//Example start
						UInt32 points = StreamInfo.PacketSamples; //Number of data points per packet
						if (j == (int)StreamInfo.PacketCount - 1 && StreamInfo.StreamSamples % StreamInfo.PacketSamples != 0)
						{       //Last packet check, if it's the last packet and not full
							points = (UInt32)StreamInfo.StreamSamples % StreamInfo.PacketSamples; //Calculate number of data points in the last packet
						}
						for (int i = 0; i < points; i++)
						{
							NormalizedPowerStream[i + StreamInfo.PacketSamples * j] = (float)(10 * Math.Log10(20 * Math.Pow(NormalizedPowerStream[i] * ScaleToV, 2)));
						}
						//Example end
					}

					/*If data retrieval fails, return an error message. In case of the following errors, it is recommended to follow the instructions and reattempt to retrieve the data*/
					else
					{
						switch (Status)
						{
							case HtraApi.APIRETVAL_WARNING_BusTimeOut:
								System.Console.WriteLine("Warning - Get data timed out, check if the trigger source is triggered normally");
								break;      //If DET_GetPowerStream returns -14, it is recommended to reconfigure parameters before retrieving again.

							case HtraApi.APIRETVAL_WARNING_IFOverflow:
								System.Console.WriteLine("WARNING - IF saturation is recommended to be reconfigured, reference level <= signal power");
								break;      // If DET_GetPowerStream returns -12, it is recommended to reconfigure parameters before retrieving again.
							default:
								System.Console.WriteLine("If the status of the get function is incorrect, check the process of getting data");
								break;
						}
						System.Console.WriteLine("Status = " + Status);
						break;

					}
					for (int k = 0; k < (int)DET_ProfileIn.TriggerLength; k++)
					{
						System.Console.WriteLine(NormalizedPowerStream[k].ToString());
					}
				}
			}
#endif

			#endregion

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