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

namespace HTRA_CSharp_Examples
{
    class RTA_GetRealTimeSpectrum_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;              //Specify device number.

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

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

			//If the device 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. If the following errors occur, the device cannot operate normally. It is recommended to follow the instructions and attempt to open the device again.*/
			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.RTA_Profile_TypeDef RTA_ProfileIn = new HtraApi.RTA_Profile_TypeDef();  //RTA input configuration, including center frequency, decimation factor, reference level, etc.
			HtraApi.RTA_Profile_TypeDef RTA_ProfileOut = new HtraApi.RTA_Profile_TypeDef(); //RTA output configuration.
			HtraApi.RTA_FrameInfo_TypeDef FrameInfo = new HtraApi.RTA_FrameInfo_TypeDef();  //RTA data-related information under the current configuration, including start frequency, stop frequency, number of data points, etc.

			HtraApi.RTA_ProfileDeInit(ref Device, ref RTA_ProfileIn); //Initialize the RTA mode configuration parameters.

			RTA_ProfileIn.CenterFreq_Hz = 1e9;									 //Configure the center frequency.
			RTA_ProfileIn.RefLevel_dBm = 0;										 //Configure the reference level.
			RTA_ProfileIn.DecimateFactor = 1;									 //Configure the decimation factor.
			RTA_ProfileIn.TriggerSource = HtraApi.RTA_TriggerSource_TypeDef.Bus; //Set the trigger source to internal bus trigger.

			//Configure trigger mode. FixedPoints mode starts sampling at the rising edge of the trigger signal and stops after collecting TriggerAcqTime duration. 
			//Use Adaptive mode directly, or set #if true to #if false to use FixedPoints mode.
#if true
			RTA_ProfileIn.TriggerMode = HtraApi.TriggerMode_TypeDef.Adaptive;               
#else
			//Configure FixedPoints mode parameters
			RTA_ProfileIn.TriggerMode = HtraApi.TriggerMode_TypeDef.FixedPoints;              
			RTA_ProfileIn.TriggerAcqTime = 0.1; //Set the sampling time after the trigger to 0.1s, effective only in FixedPoints mode.
#endif

			Status = HtraApi.RTA_Configuration(ref Device, ref RTA_ProfileIn, ref RTA_ProfileOut, ref FrameInfo); //Deliver the RTA 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
			byte[] SpectrumTrace = new byte[FrameInfo.PacketValidPoints];                                     //Spectrum array
			System.UInt16[] SpectrumBitmap = new System.UInt16[FrameInfo.FrameHeight * FrameInfo.FrameWidth]; //Spectrum bitmap array
			float[] Spectrum = new float[FrameInfo.FrameWidth];                                               //Spectrum array in dBm units
			HtraApi.RTA_PlotInfo_TypeDef RTA_PlotInfo = new HtraApi.RTA_PlotInfo_TypeDef();                   //Plot information
			HtraApi.RTA_TriggerInfo_TypeDef TriggerInfo = new HtraApi.RTA_TriggerInfo_TypeDef();              //Trigger information
			HtraApi.MeasAuxInfo_TypeDef MeasAuxInfo = new HtraApi.MeasAuxInfo_TypeDef();                      //Auxiliary information of measurement data, including: power peak index, power peak value, device temperature, latitude and longitude, absolute timestamp, etc.

			//Use Adaptive mode directly. If you want to use FixedPoints mode, change #if true to #if false
#if true
			Status = HtraApi.RTA_BusTriggerStart(ref Device); //Trigger the device using RTA_BusTriggerStart.
			while (true)
			{
				Status = HtraApi.RTA_GetRealTimeSpectrum(ref Device, SpectrumTrace, SpectrumBitmap, ref RTA_PlotInfo, ref TriggerInfo, ref MeasAuxInfo); //Get the RTA data and trigger information.

				if (Status == 0)
				{

					//UserCode here
					//Example operation starts, the following is an example of converting the RTA spectrum data into dBm units
					for (int k = 0; k < FrameInfo.FrameWidth; k++)
					{
						Spectrum[k] = (float)SpectrumTrace[k] * RTA_PlotInfo.ScaleTodBm + RTA_PlotInfo.OffsetTodBm;
					}
					for (int j = 0; j < FrameInfo.FrameWidth; j++)
					{
						System.Console.WriteLine(Spectrum[j].ToString());
					}
					//Example operation ends
				}

				/*In case of data retrieval failure, return an error message. If the following errors occur, it is recommended to take actions as prompted.*/
				else
				{
					switch (Status)
					{
						case HtraApi.APIRETVAL_WARNING_ReconfigurationIsRecommended:
							System.Console.WriteLine("Warning - The temperature of the current device varies greatly. It is recommended to reconfigure the temperature");
							break; //If RTA_GetRealTimeSpectrum returns -14, it is recommended to reconfigure the 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 RTA_GetRealTimeSpectrum returns -12, it is recommended to reconfigure the 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;
				}
			}
#else
			while (true)
			{

				Status = HtraApi.RTA_BusTriggerStart(ref Device); //Trigger the device using RTA_BusTriggerStart.

				for (System.UInt32 i = 0; i < FrameInfo.PacketCount; i++)
				{
					Status = HtraApi.RTA_GetRealTimeSpectrum(ref Device, SpectrumTrace, SpectrumBitmap, ref RTA_PlotInfo, ref TriggerInfo, ref MeasAuxInfo); //Get RTA data and trigger information.
					if (Status == 0)
					{

						//UserCode here
						//Operation example begins, the following is an example to convert RTA spectrum data units to dBm.
						for (int k = 0; k < FrameInfo.FrameWidth; k++)
						{
							Spectrum[k] = (float)SpectrumTrace[k] * RTA_PlotInfo.ScaleTodBm + RTA_PlotInfo.OffsetTodBm;
						}
						for (int j = 0; j < FrameInfo.FrameWidth; j++)
						{
							System.Console.WriteLine(Spectrum[j].ToString());
						}
						//Operation example ends
					}

					/*If data retrieval fails, return an error message. In case of the following errors, it is recommended to take actions as prompted.*/
					else
					{
						switch (Status)
						{
							case HtraApi.APIRETVAL_WARNING_ReconfigurationIsRecommended:
								System.Console.WriteLine("Warning - The temperature of the current device varies greatly. It is recommended to reconfigure the temperature");
								break; //If RTA_GetRealTimeSpectrum returns -14, it is recommended to reconfigure the 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 RTA_GetRealTimeSpectrum returns -12, it is recommended to reconfigure the 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;
					}
				}
			}
#endif


			#endregion

			#region 4 Close
			Status = HtraApi.RTA_BusTriggerStop(ref Device); //Call RTA_BusTriggerStop to stop triggering the device.
			HtraApi.Device_Close(ref Device);
			#endregion
		}
	}
}
