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 打开设备

			int Status = 0;              //函数的返回。
			IntPtr Device = IntPtr.Zero; //当前设备的内存地址。
			int DevNum = 0;              //指定设备号。

			HtraApi.BootProfile_TypeDef BootProfile = new HtraApi.BootProfile_TypeDef(); //启动配置结构体，包括物理接口、供电方式等。
			HtraApi.BootInfo_TypeDef BootInfo = new HtraApi.BootInfo_TypeDef();          //启动信息结构体，包括设备信息、USB速率等。

			BootProfile.DevicePowerSupply = HtraApi.DevicePowerSupply_TypeDef.USBPortAndPowerPort; //使用USB数据端口及独立电源端口双供电。

			//设备数据接口为USB时直接运行，为网口时将 #if true 改为 #if false
#if true
			BootProfile.PhysicalInterface = HtraApi.PhysicalInterface_TypeDef.USB;
#else
			//配置网络相关参数
			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); //打开设备

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

			/*设备打开失败，返回错误提示，发生以下错误时，设备无法正常运行，建议按照提示操作后重新打开设备*/
			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;

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

			#region 2 配置参数
			HtraApi.SWP_Profile_TypeDef SWP_ProfileIn = new HtraApi.SWP_Profile_TypeDef();  //SWP输入配置，包括起始频率、终止频率、RBW、参考电平等。
			HtraApi.SWP_Profile_TypeDef SWP_ProfileOut = new HtraApi.SWP_Profile_TypeDef(); //SWP输出配置。
			HtraApi.SWP_TraceInfo_TypeDef TraceInfo = new HtraApi.SWP_TraceInfo_TypeDef();  //当前配置下的迹线信息，包括迹线点数、跳频点数等。

			HtraApi.SWP_ProfileDeInit(ref Device, ref SWP_ProfileIn); //初始化SWP模式的相关参数。

			SWP_ProfileIn.StartFreq_Hz = 5e8;							//配置起始频率
			SWP_ProfileIn.StopFreq_Hz = 9e9;							//配置终止频率
			SWP_ProfileIn.RBW_Hz = 300e3;								//配置RBW
			SWP_ProfileIn.RBWMode = HtraApi.RBWMode_TypeDef.RBW_Manual; //配置RBW配置方式为手动

			Status = HtraApi.SWP_Configuration(ref Device, ref SWP_ProfileIn, ref SWP_ProfileOut, ref TraceInfo); //下发SWP模式的相关配置。

			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 数据采集
			double[] Frequency = new double[TraceInfo.FullsweepTracePoints];   //创建频率数组。
			float[] PowerSpec_dBm = new float[TraceInfo.FullsweepTracePoints]; //创建功率数组。


			double[] PartialFrequency = new double[TraceInfo.PartialsweepTracePoints];   //局部频率数据数组。
			float[] PartialPowerSpec_dBm = new float[TraceInfo.PartialsweepTracePoints]; //局部功率数据数组。
			int HopIndex = 0;                                                            //当前跳频点索引。
			int FrameIndex = 0;                                                          //当前帧索引。
			HtraApi.MeasAuxInfo_TypeDef MeasAuxInfo = new HtraApi.MeasAuxInfo_TypeDef(); //测量数据的辅助信息，包括：功率最大值索引、功率最大值、设备温度、经纬度、绝对时间戳等。

			while (true)
			{
				for (int i = 0; i < TraceInfo.TotalHops; i++) //TraceInfo.TotalHops代表当前配置下的帧数，因此循环TraceInfo.TotalHops次调用SWP_GetPartialSweep即可得到完整迹线
				{
					//获取部分数据
					Status = HtraApi.SWP_GetPartialSweep(ref Device, PartialFrequency, PartialPowerSpec_dBm, ref HopIndex, ref FrameIndex, ref MeasAuxInfo);

					if (Status == 0)
					{
						//将部分数据复制到整条数据上
						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);

						// 用户代码
						/*

						例如：对部分频谱数据进行处理

						*/
					}

					/*获取数据失败时，返回错误提示，发生以下错误时，建议按照提示进行操作*/
					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;       //SWP_GetPartialSweep返回-8时，建议重新配置参数，再进行获取

							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;       //SWP_GetPartialSweep返回-9时，建议重新配置参数，再进行获取

							case HtraApi.APIRETVAL_WARNING_BusTimeOut:
								System.Console.WriteLine("Warning - Get data timed out, check if the trigger source is triggered normally");
								break;      //SWP_GetPartialSweep返回-10时，建议检查触发源是否正常触发，再进行获取

							case HtraApi.APIRETVAL_WARNING_IFOverflow:
								System.Console.WriteLine("WARNING - IF saturation is recommended to be reconfigured, reference level <= signal power");
								break;      // SWP_GetPartialSweep返回-12时，建议重新配置参数，再进行获取

							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;     //SWP_GetPartialSweep返回-14时，建议重新配置参数，再进行获取

							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;     // SWP_GetPartialSweep返回-15时，建议重新配置参数，再进行获取

							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;
					}
				}
				// 用户代码：例如：打印出每一次第一个点处的频率数据和幅度数据
				//示例开始
				System.Console.WriteLine("Get the full spectrum data  " + Frequency[0].ToString() + "  " + PowerSpec_dBm[0].ToString());

				//示例结束
			}

			#endregion

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