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

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

			int Status = 0;              //Return value of the function.
			IntPtr Device = IntPtr.Zero; //Memory address of the current device.
			int DevNum = 0;              //Specifies the device number.

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

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

			//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");
			}

			/*Device open failed, error message is returned. The following errors indicate that the device cannot operate normally. It is recommended to follow the prompts to resolve the issue and then reopen 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.SWP_Profile_TypeDef SWP_ProfileIn = new HtraApi.SWP_Profile_TypeDef();  //SWP input configuration, including start frequency, stop frequency, RBW, reference level, etc.
			HtraApi.SWP_Profile_TypeDef SWP_ProfileOut = new HtraApi.SWP_Profile_TypeDef(); //SWP output configuration.
			HtraApi.SWP_TraceInfo_TypeDef TraceInfo = new HtraApi.SWP_TraceInfo_TypeDef();  //Trace information under current configuration, including trace points, hop points, etc.

			HtraApi.SWP_ProfileDeInit(ref Device, ref SWP_ProfileIn); //Initialize related parameters for SWP mode.

			SWP_ProfileIn.StartFreq_Hz = 5e8;							//Configure start frequency.
			SWP_ProfileIn.StopFreq_Hz = 9e9;							//Configure stop frequency.
			SWP_ProfileIn.RBW_Hz = 300e3;								//Configure RBW.
			SWP_ProfileIn.RBWMode = HtraApi.RBWMode_TypeDef.RBW_Manual; //Set RBW mode to manual.

			Status = HtraApi.SWP_Configuration(ref Device, ref SWP_ProfileIn, ref SWP_ProfileOut, ref TraceInfo); //Send SWP mode configuration.

			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
			double[] Frequency = new double[TraceInfo.FullsweepTracePoints];   //Create frequency array.
			float[] PowerSpec_dBm = new float[TraceInfo.FullsweepTracePoints]; //Create power array.


			double[] PartialFrequency = new double[TraceInfo.PartialsweepTracePoints];   //Partial frequency data array.
			float[] PartialPowerSpec_dBm = new float[TraceInfo.PartialsweepTracePoints]; //Partial power data array.
			int HopIndex = 0;                                                            //Current hop point index.
			int FrameIndex = 0;                                                          //Current frame index.
			HtraApi.MeasAuxInfo_TypeDef MeasAuxInfo = new HtraApi.MeasAuxInfo_TypeDef(); //Measurement auxiliary info, including: maximum power index, maximum power, device temperature, latitude/longitude, timestamp, etc.

			while (true)
			{
				for (int i = 0; i < TraceInfo.TotalHops; i++) //TraceInfo.TotalHops represents the number of frames under the current configuration. Looping TraceInfo.TotalHops times to call SWP_GetPartialSweep will gather the full trace.
				{
					//Get partial data
					Status = HtraApi.SWP_GetPartialSweep(ref Device, PartialFrequency, PartialPowerSpec_dBm, ref HopIndex, ref FrameIndex, ref MeasAuxInfo);

					if (Status == 0)
					{
						//Copy partial data to the full data array
						int DestIndex = HopIndex * TraceInfo.PartialsweepTracePoints;
						int Len = TraceInfo.PartialsweepTracePoints;
						if ((HopIndex + 1) * TraceInfo.PartialsweepTracePoints > TraceInfo.FullsweepTracePoints)
						{
							Len = TraceInfo.FullsweepTracePoints - HopIndex * TraceInfo.PartialsweepTracePoints;
						}
						Array.Copy(PartialFrequency, 0, Frequency, DestIndex, Len);
						Array.Copy(PartialPowerSpec_dBm, 0, PowerSpec_dBm, DestIndex, Len);

						// User code
						/*

						For example: Process partial spectrum data

						*/
					}

					/*If data retrieval fails, return error message. In case of the following errors, it is recommended to follow the prompts for resolution. */
					else
					{
						switch (Status)
						{
							case HtraApi.APIRETVAL_ERROR_BusError:
								System.Console.WriteLine("Error - Bus communication error");
								Status = HtraApi.SWP_Configuration(ref Device, ref SWP_ProfileIn, ref SWP_ProfileOut, ref TraceInfo);
								break;       //If SWP_GetPartialSweep returns -8, it is recommended to reconfigure the parameters and try retrieving the data again.

							case HtraApi.APIRETVAL_ERROR_BusDataError:
								System.Console.WriteLine("Error - The data content is incorrect");
								Status = HtraApi.SWP_Configuration(ref Device, ref SWP_ProfileIn, ref SWP_ProfileOut, ref TraceInfo);
								break;       //If SWP_GetPartialSweep returns -9, it is recommended to reconfigure the parameters and try retrieving the data again.

							case HtraApi.APIRETVAL_WARNING_BusTimeOut:
								System.Console.WriteLine("Warning - Get data timed out, check if the trigger source is triggered normally");
								break;      //If SWP_GetPartialSweep returns -10, check whether the trigger source is working correctly, and then retry retrieving the data.

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

							case HtraApi.APIRETVAL_WARNING_ReconfigurationIsRecommended:
								System.Console.WriteLine("Warning - The current device temperature has changed significantly relative to the configured temperature, and it is recommended to reconfigure");
								break;     //If SWP_GetPartialSweep returns -14, it is recommended to reconfigure the parameters and try retrieving the data again.

							case HtraApi.APIRETVAL_WARNING_ClockUnlocked_SYSCLK:
								System.Console.WriteLine("Warning - There may be an anomaly in the hardware status of the device and reconfiguration is recommended");
								break;     // If SWP_GetPartialSweep returns -15, it is recommended to reconfigure the parameters and try retrieving the data 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;
					}
				}
				// User code: For example, print the frequency data and amplitude data at the first point each time
				//Example begins
				System.Console.WriteLine("Get the full spectrum data  " + Frequency[0].ToString() + "  " + PowerSpec_dBm[0].ToString());

				//Example ends
			}

			#endregion

			#region 4 Close
			HtraApi.Device_Close(ref Device);
			#endregion
		}
	}
}
