/// <summary> /// Executes the instrument I/O task. /// </summary> public BK2831E_ReadVoltageResults Run( ) { if (_instrumentSession == null) { throw new ArgumentNullException("_instrumentSession"); } BK2831E_ReadVoltageResults outputs = new BK2831E_ReadVoltageResults(); // Query step // Does a VISA Write _instrumentSession.Write(":FETC?\n"); // Parses out one ASCII number separated by one or more delimiters outputs.Token = _reader.ReadDouble(); _reader.ReadMatch(",;\r\n\t"); // Read and discard the rest of the response _reader.DiscardUnreadData(); // Query step // Does a VISA Write _instrumentSession.Write(":FETC?\n"); // Parses out one ASCII number separated by one or more delimiters outputs.Token2 = _reader.ReadDouble(); _reader.ReadMatch(",;\r\n\t"); // Read and discard the rest of the response _reader.DiscardUnreadData(); return(outputs); }
/// <summary> /// Executes the instrument I/O task. /// </summary> public BK1685B_2_GETDResults Run( ) { if (_instrumentSession == null) { throw new ArgumentNullException("_instrumentSession"); } BK1685B_2_GETDResults outputs = new BK1685B_2_GETDResults(); // Query step // Does a VISA Write _instrumentSession.Write("GETD\r"); // Parses out one ASCII string separated by one or more delimiters outputs.Token = _reader.ReadMismatch(",;\r\n\t"); _reader.ReadMatch(",;\r\n\t"); // Read and discard the rest of the response _reader.DiscardUnreadData(); // Query step // Does a VISA Write _instrumentSession.Write("GETD\r"); // Parses out one ASCII string separated by one or more delimiters outputs.Token2 = _reader.ReadMismatch(",;\r\n\t"); _reader.ReadMatch(",;\r\n\t"); // Read and discard the rest of the response _reader.DiscardUnreadData(); return(outputs); }
/// <summary> /// 根据当前选择的地址返回设备基本信息 /// </summary> private void Query_IDN(String Device_address) { Cursor.Current = Cursors.WaitCursor; try { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(Device_address); Device_Address = list_devices.Text; } catch (InvalidCastException) { MessageBox.Show("Resource selected must be a message-based session"); } catch (Exception exp) { MessageBox.Show(exp.Message); } try { mbSession.Write(ReplaceCommonEscapeSequences("*RST\\n")); mbSession.Write(ReplaceCommonEscapeSequences("*CLS\\n")); string textToWrite = ReplaceCommonEscapeSequences("*IDN?\\n"); string responseString = mbSession.Query(textToWrite); Device_Info.Text = InsertCommonEscapeSequences(responseString); Print_Log("Find device:" + responseString); } catch (Exception exp) { MessageBox.Show(exp.Message); } finally { Cursor.Current = Cursors.Default; } }
public bool Write(string cmd) { try { mbSession.Write(cmd); return(true); } catch { return(false); } }
/// <summary> /// 载入校准档案文件 /// </summary> /// <param name="calFilePath">档案文件路径,相对网分设备</param> /// <param name="msg"></param> /// <returns></returns> public override bool LoadCalFile(string calFilePath, ref string msg) { Connect(); string delAllCalFile = "MEM:DEL:ALL"; string loadCalFile = String.Format("MMEM:LOAD:STAT 1,'{0}'", ReplaceSlash(calFilePath)); mbSession.Write(delAllCalFile); Thread.Sleep(2000); mbSession.Write(loadCalFile); return(true); }
public void write(string cmd) { try { mSession.Write(cmd); } catch (VisaException ex) { throw ex; } }
public void setVoltage(int chn, int mV) { // low level is 0, set high level try { session.Write("SOURce" + chn.ToString() + ":VOLTage:LEVel:IMMediate:LOW " + mV + "mV"); } catch (Exception exp) { MessageBox.Show(exp.Message); } }
public bool Write(string cmd) { if (mbSession == null) { return(false); } try { mbSession.Write(cmd); return(true); } catch { return(false); } }
/// <summary> /// Executes the instrument I/O task. /// </summary> public pingBK2831eResults Run( ) { if (_instrumentSession == null) { throw new ArgumentNullException("_instrumentSession"); } pingBK2831eResults outputs = new pingBK2831eResults(); // Query step // Does a VISA Write _instrumentSession.Write("*IDN?\n"); // Parses out one ASCII string as long as the specified string length outputs.Token = new string(_reader.ReadChars(17)); // Read and discard unparsed response data _reader.ReadMismatch(",;\r\n\t"); _reader.ReadMatch(",;\r\n\t"); // Parses out one ASCII string separated by one or more delimiters outputs.Token2 = _reader.ReadMismatch(",;\r\n\t"); _reader.ReadMatch(",;\r\n\t"); // Parses out one ASCII string separated by one or more delimiters outputs.Token3 = _reader.ReadMismatch(",;\r\n\t"); _reader.ReadMatch(",;\r\n\t"); // Read and discard the rest of the response _reader.DiscardUnreadData(); return(outputs); }
/// <summary> /// Writes the command dev.11 /// </summary> /// <param name="command">The command.</param> /// <returns></returns> public bool WriteCommandDev(string command) { switch (cbInterfaceType.Text) { case "GPIB": { if (device == null) { MessageBox.Show("Check device"); return(false); } device.Write(ReplaceCommonEscapeSequences(command)); return(true); } case "USB": mbSession.Write(ReplaceCommonEscapeSequences(command)); //txtAnswer.AppendText(Environment.NewLine + InsertCommonEscapeSequences(responseString)); return(true); case "ETHERNET": { answer = SendCmdViaEhternet(command, Convert.ToInt32(txtIpPort.Text), txtIpHost.Text); return(true); } default: return(true); } }
private void write_Click(object sender, System.EventArgs e) { try { string textToWrite = ReplaceCommonEscapeSequences(writeTextBox.Text); mbSession.Write(textToWrite); if (checkBoxLog.Checked) { Log.WriteLog("Write - " + textToWrite, ""); } } catch (Exception exp) { MessageBox.Show(exp.Message); } }
public void SendCommandRequest(string request) { lock (requestQueryLocker) lock (receiveDeviceAnswerLocker) lock (sendCommandRequestLocker) { var _Request = request.EndsWith("\n") ? Encoding.ASCII.GetBytes(request) : Encoding.ASCII.GetBytes(request + "\n"); mbSession.Write(_Request); } }
public void Send(string strCommand) { try { myVISA.Write(strCommand); // Write to a Device } catch (Exception e) { throw new Exception(e.Message); } }
public object Excute(object objCmd) { try { lock (_lock) { session.Write(objCmd.ToString()); return(true); } } catch (Exception ex) { throw ex; } }
/// <summary> /// 写命令函数 /// </summary> /// <param name="strCommand"></param> public void Write(string strCommand) { try { if (mbSession != null) { mbSession.Write(strCommand); } } catch (NationalInstruments.VisaNS.VisaException e) { //Global.LogAdd(e.Message); } catch (Exception exp) { throw new Exception("VisaCtrl-VisaOpen\n" + exp.Message); } }
private void button1_Click(object sender, EventArgs e) { // example waveform: sine wave using 12 sample points, integers between 0 to // 16382 (range of AFG). hex notation is easier to verify later // (note: max value of afg3000 is '3FFE' not '3FFF') int[] hexArray = { 0x2000, 0x2FFF, 0x3BB6, 0x3FFE, 0x3BB6, 0x2FFF, 0x2000, 0x1000, 0x0449, 0x0000, 0x0449, 0x1000 }; string[] hexStr1 = new string[hexArray.Length]; string[] hexStr2 = new string[hexArray.Length * 2]; // pre-processing // encode variable 'wave' into binary waveform data for AFG. This is // the same as AWG5000B but marker bits are ignored. see AWG5000B series // programmer manual for bit definitions. for (int i = 0; i < hexArray.Length; i++) { hexStr1[i] = hexArray[i].ToString("X4"); hexStr2[2 * i] = hexStr1[i].Substring(0, 2); hexStr2[(2 * i) + 1] = hexStr1[i].Substring(2, 2); } byte[] Str2Byt = hexStr2.Select(s => Convert.ToByte(s, 16)).ToArray(); string EnCdStr = System.Text.Encoding.ASCII.GetString(Str2Byt); // build binary block header int bytes = Str2Byt.Length; string header = "#" + Convert.ToString(Convert.ToString(bytes).Length) + Convert.ToString(bytes); //Open connection to instrument mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resourceString); mbSession.Write("*RST"); mbSession.Write("*CLS"); mbSession.Write("DATA:DEFine EMEMory, " + hexArray.Length.ToString()); mbSession.Write("DATA EMEMory," + header + EnCdStr); mbSession.Write("SOURce1:FUNCtion EMEMory"); mbSession.Write("OUTPut1 ON"); //Close instrument connection mbSession.Dispose(); }
private void cmdStartTest_Click(object sender, EventArgs e) { System.DateTime CurveTime; float wfmPerSec = 0; System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); string temp; string SaveDirectory = txtSaveDirectory.Text; byte[] DataBuffer; int AcqLength = 0; int CurveCount = 0; int DataLength; int BytesRemaining; // Curve data conversion parameters int pt_off; float xinc; float xzero; float ymult; float yoff; float yzero; float xvalue; float yvalue; cmdStartTest.Enabled = false; lblCurveCount.Text = CurveCount.ToString(); lblWfmPerSec.Text = wfmPerSec.ToString("f"); Application.DoEvents(); // Allow the front panel to redraw // Check that the save directory is valid if (!System.IO.Directory.Exists(SaveDirectory)) { MessageBox.Show("Invalid save directory. Please enter a valid directory then try again.", "Error: Invalid Directory", MessageBoxButtons.OK, MessageBoxIcon.Error); cmdStartTest.Enabled = true; return; } // Prompt the user to prep the scope if (MessageBox.Show("Please setup the scope then press OK to start Curve Streaming. Once Curve Streaming has started you will not be able to control the scope until Curve Streaming is ended.", "Setup Scope", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.Cancel) { cmdStartTest.Enabled = true; return; } // Open a connection to the instrument try { TekScope = new MessageBasedSession(txtVisaResourceName.Text.Trim()); TekScope.Clear(); } catch (Exception ex) { // Show and error message then exit if the connection fails MessageBox.Show(ex.Message, "Error Opening Connection to Instrument", MessageBoxButtons.OK, MessageBoxIcon.Error); TekScope = null; cmdStartTest.Enabled = true; return; } GatherCurves = true; cmdEndTest.Enabled = true; // Setup the waveform transfer TekScope.Write("*CLS"); TekScope.Write("*CLE"); TekScope.Write("DATa:SOUrce CH1"); TekScope.Write("DATa:ENCdg RIBinary"); TekScope.Write("DATa:STARt 0"); TekScope.Write("HORizontal:ACQLENGTH?"); temp = TekScope.ReadString().Trim(); AcqLength = Int32.Parse(temp); TekScope.Write(String.Format("DATa:STOP {0}", AcqLength)); TekScope.Write("WFMOutpre:ENCdg BINary"); TekScope.Write("WFMOutpre:BYT_Nr 1"); // Get the needed values from the scope to scale the data TekScope.Write("WFMOutpre:PT_Off?"); temp = TekScope.ReadString().Trim(); pt_off = Int32.Parse(temp); TekScope.Write("WFMOutpre:XINcr?"); temp = TekScope.ReadString().Trim(); xinc = Single.Parse(temp); TekScope.Write("WFMOutpre:XZEro?"); temp = TekScope.ReadString().Trim(); xzero = Single.Parse(temp); TekScope.Write("WFMOutpre:YMUlt?"); temp = TekScope.ReadString().Trim(); ymult = Single.Parse(temp); TekScope.Write("WFMOutpre:YOFf?"); temp = TekScope.ReadString().Trim().TrimEnd('0').TrimEnd('.'); yoff = Single.Parse(temp); TekScope.Write("WFMOutpre:YZEro?"); temp = TekScope.ReadString().Trim(); yzero = Single.Parse(temp); // Turn on curve streaming TekScope.Write("CURVEStream?"); stopWatch.Reset(); stopWatch.Start(); // While still collecting curves. Ends when the user clicks End Test while (GatherCurves) { int NumBytesCharCount = 0; string BlockHeader = ""; TekScope.Timeout = 200; // Loop until the block header is found while (BlockHeader.Length == 0) { try { // Read the length of the string that contains the length of the data // Note: If this times out it just means that no curve has been sent out yet so need to wait again BlockHeader = TekScope.ReadString(2); if (BlockHeader == ";\n") // Then it's the terminator from the previous curve so throw it out and try again. { BlockHeader = ""; } } catch (VisaException ex) { if (ex.ErrorCode != VisaStatusCode.ErrorTimeout) // Then still waiting on another curve to come in { MessageBox.Show(ex.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } } wfmPerSec = (float)CurveCount / ((float)stopWatch.ElapsedMilliseconds / (float)1000); lblWfmPerSec.Text = wfmPerSec.ToString("f"); Application.DoEvents(); if (!GatherCurves) { break; } } if (!GatherCurves) { break; } // Create a file with the current date and time as the name CurveTime = System.DateTime.Now; string FileName = String.Format("{0}{1}-{2:D2}-{3:D2}_{4:D2}{5:D2}{6:D2}.{7:D3}.csv", txtSaveDirectory.Text, CurveTime.Year, CurveTime.Month, CurveTime.Day, CurveTime.Hour, CurveTime.Minute, CurveTime.Second, CurveTime.Millisecond); StreamWriter SaveFile = new StreamWriter(FileName, false, Encoding.ASCII, BUFFER_SIZE * 10); // Calculate the xvalue for the first point in the record xvalue = (float)(-pt_off * (xinc + xzero)); // Get the number of bytes that make up the data length string NumBytesCharCount = Int32.Parse(BlockHeader.TrimStart('#'), System.Globalization.NumberStyles.HexNumber); // Read the data length string temp = TekScope.ReadString(NumBytesCharCount); DataLength = int.Parse(temp); BytesRemaining = DataLength; // Read the back the data, process it and save it to the file TekScope.Timeout = 5000; while (BytesRemaining > 0) { // Read bytes from scope if (BytesRemaining >= BUFFER_SIZE) { DataBuffer = TekScope.ReadByteArray(BUFFER_SIZE); BytesRemaining -= BUFFER_SIZE; } else { DataBuffer = TekScope.ReadByteArray(BytesRemaining); BytesRemaining = 0; } // Convert byte values to floating point values then write to .csv file foreach (byte DataPoint in DataBuffer) { yvalue = (float)((Convert.ToSingle((sbyte)DataPoint) - yoff) * (ymult + yzero)); SaveFile.WriteLine(xvalue.ToString() + "," + yvalue.ToString()); // Note: Converting to .CSV is very time consuming operation. // Save in a binary format to maximize speed. Highly recommended for waveforms >= 1 Million points. xvalue += xinc; } } SaveFile.Close(); CurveCount++; wfmPerSec = (float)CurveCount / ((float)stopWatch.ElapsedMilliseconds / (float)1000); lblWfmPerSec.Text = wfmPerSec.ToString("f"); lblCurveCount.Text = CurveCount.ToString(); Application.DoEvents(); } // Send Device Clear to stop the curve streaming TekScope.Clear(); TekScope.Dispose(); TekScope = null; cmdStartTest.Enabled = true; cmdEndTest.Enabled = false; }
public void ForceStop() { Connector.Write(ForceStopCommand); }
private void button2_Click(object sender, EventArgs e) { List <float> lista = new List <float>(); List <float> listb = new List <float>(); List <float> listc = new List <float>(); List <float> listd = new List <float>(); try { mbSession.Write("smua.OUTPUT_DCVOLTS"); // mbSession.Write("smua.source.rangev = 5"); for (int i = 1; i < 102; i++) { float levelv = (0.001f * i) - 0.051f; string mbstring = "smua.source.levelv=" + levelv.ToString("0.###"); mbSession.Write(mbstring); mbSession.Write("smua.OUTPUT_ON"); string voltage = mbSession.Query("smua.measure.i()"); mbSession.Write("smua.OUTPUT_OFF"); lista.Add(levelv); listb.Add(Convert.ToSingle(voltage)); } for (int i = 0; i < 101; i++) { float levelv = (i) * 0.02f; string mbstring = "smua.source.levelv=" + levelv.ToString("0.###"); mbSession.Write(mbstring); mbSession.Write("smua.OUTPUT_ON"); string voltage = mbSession.Query("smua.measure.i()"); mbSession.Write("smua.OUTPUT_OFF"); listc.Add(levelv); listd.Add(Convert.ToSingle(voltage)); } float[] aArrayn = lista.ToArray(); float[] bArrayn = listb.ToArray(); float[] cArrayn = listc.ToArray(); float[] dArrayn = listd.ToArray(); Stream myStream; SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Comma separated (*.csv)|*.csv"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { if ((myStream = saveFileDialog1.OpenFile()) != null) { var extension = Path.GetExtension(saveFileDialog1.FileName); switch (extension.ToLower()) { case ".csv": StreamWriter wText = new StreamWriter(myStream); wText.WriteLine(textBox1.Text); for (int i = 0; i <= aArrayn.Length - 1; i++) { wText.WriteLine(Convert.ToString(aArrayn[i], CultureInfo.InvariantCulture) + ',' + Convert.ToString(bArrayn[i], CultureInfo.InvariantCulture) + "," + Convert.ToString(cArrayn[i], CultureInfo.InvariantCulture) + ',' + Convert.ToString(dArrayn[i], CultureInfo.InvariantCulture)); } wText.Flush(); wText.Close(); break; default: throw new ArgumentOutOfRangeException(extension); } } } } catch (Exception ex) {} }
/// <summary> /// 载入校准档案文件 /// </summary> /// <param name="calFilePath">档案文件路径,相对网分设备</param> /// <param name="msg"></param> /// <returns></returns> public override bool LoadCalFile(string calFilePath, ref string msg) { Connect(); string loadCalFile = "MMEM:load '" + calFilePath + "'"; mbSession.Write(loadCalFile); Thread.Sleep(5000); string typeLin = "Format:data ascii;SENSE1:sweep:TYPE LIN"; mbSession.Write(typeLin); return(true); }
public void Write(string command) { connect.Write(command + "\r\n"); }
private void SelectMode(String chosenMode) { try { mbSession.Write(":M:" + chosenMode + " 1 \n"); } catch (VisaException v_exp) { MessageBox.Show(v_exp.Message); } catch (Exception exp) { MessageBox.Show(exp.Message); } }
public void Write(string command) { Connector.Write(command + "\r\n"); }
//// Add them 17/4/2015 public void oneCommand(string command) { try { checkBusyState(mbSession, "*ESR?"); checkBusyState(mbSession, "*OPC?"); mbSession.Write(command); } catch { }; }
public void WriteBufferData(ref byte[] databuff) { if (decivetype == "ATTEN") { var s = "PNSU"; var str2 = searilNo + softNo + s; var pBuff = str2.ToCharArray(); var length = str2.Length; var str3 = Verify_Databuff_Get_VerifyNum(pBuff, length).ToString("X"); s = (str3.Substring(6, 2) + str3.Substring(4, 2)) + str3.Substring(2, 2) + str3.Substring(0, 2); var bytes = Encoding.Default.GetBytes(s); if ((m_connectType == 1) || (m_connectType == 2)) { var num3 = databuff.Length + 8; var destinationArray = new byte[num3]; Array.Copy(bytes, destinationArray, bytes.Length); Array.Copy(databuff, 0, destinationArray, bytes.Length, databuff.Length); try { mbSession.Write(destinationArray); } catch (Exception) { MessageBox.Show("Write setup file data from device has problem,please check the device"); } } else if (m_connectType == 0) { var count = setupfile_len + 8; var buffer3 = new byte[count]; Array.Copy(bytes, buffer3, bytes.Length); Array.Copy(databuff, 0, buffer3, bytes.Length, setupfile_len); try { m_SerialPort.Write(buffer3, 0, count); } catch (Exception) { MessageBox.Show("Write setup file data from device has problem,please check the device"); } } } else if ((m_connectType == 1) || (m_connectType == 2)) { try { mbSession.Write(databuff); } catch (Exception) { MessageBox.Show("Write setup file data from device has problem,please check the device"); } } else if (m_connectType == 0) { try { m_SerialPort.Write(databuff, 0, setupfile_len); } catch (Exception) { MessageBox.Show("Write setup file data from device has problem,please check the device"); } } }
private void Run1() { try { DialogResult dr; try { // Create driver instance VAC = (MessageBasedSession)ResourceManager.GetLocalManager().Open(Form1.addr_zva); } catch { MessageBox.Show("Проверьте физическое и программное подключение анализатора цепей к компьютеру", "Внимание", MessageBoxButtons.OK); m_DrawGraphicOnForm.EndCalculate(); return; } VAC.Timeout = 20000; VAC.Write("*RST"); VAC.Write("SWE:POIN 1000"); VAC.Write("BWID 10"); double[] freqList = { 0.1, 0.7, 2, 13, 24.0 }; int[] dopusk = { -80, -110, -115, -110 }; double[] result_noise = new double[6]; string fileName = Form1.path + "\\" + String.Format("noise_{0}.txt", Form1.date.ToShortTimeString().Replace(":", " ")); StreamWriter sw = new StreamWriter(FileStream.Null); try { sw = new StreamWriter(fileName); } catch { System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); MessageBox.Show("Отсутствуют права на запись файла по указанному пути, обратитесь к администратору", "Внимание", MessageBoxButtons.OK); if (VAC != null) { // Close the driver VAC.Dispose(); } m_DrawGraphicOnForm.EndCalculate(); return; } sw.WriteLine("Определение уровня собственных шумов анализатора"); sw.WriteLine(); sw.WriteLine(String.Format("{0,20}", "f1, ГГц") + "\t" + String.Format("{0,20}", "f2, ГГц, дБм") + "\t" + String.Format("{0,20}", "Шум, дБм") + "\t" + String.Format("{0,20}", "Допуск. (макс), дБм") + "\t" + String.Format("{0,20}", "Соответ.?")); sw.Flush(); double[] data = null; double[] data_X = null; dr = MessageBox.Show(String.Format("Подключите согласованные нагрузки ко всем портам анализатора цепей, после этого нажмите ОК"), "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.Cancel) { if (VAC != null) { // Close the driver VAC.Dispose(); } sw.Close(); m_DrawGraphicOnForm.EndCalculate(); return; } Form1.IsRun = true; for (int ii = 0; ii < Form1.count_port_noise; ii++) { if (!Form1.IsRun) { sw.Close(); Form1.IsRun = false; if (VAC != null) { // Close the driver VAC.Dispose(); } dr = MessageBox.Show("Процедура поверки по частоте закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } m_DrawGraphicOnForm.EndCalculate(); return; } sw.WriteLine(); sw.WriteLine("Порт {0}", Form1.number_port_noise[ii]); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); switch (Form1.number_port_noise[ii]) { case (1): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S21'"); break; case (2): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S12'"); break; case (3): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S43'"); break; case (4): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S34'"); break; } Thread.Sleep((int)(1.1 * Convert.ToDouble(VAC.Query("SWE:TIME?").Replace("\n", ""), provider) * 1000)); string[] str_data = VAC.Query("CALC1:DATA? FDAT").Split(','); data = new double[str_data.Length]; data_X = new double[str_data.Length]; for (int iii = 0; iii < str_data.Length; iii++) { data[iii] = Convert.ToDouble(str_data[iii], provider); data_X[iii] = freqList[0] + iii * (freqList[freqList.Length - 1] - freqList[0]) / 1000.0; } int number = 0; double mean = 0; int cout_mean = 0; string results = "Нет"; for (int ll = 1; ll < freqList.Length; ll++) { mean = 0; cout_mean = 0; for (int l = number + 1; l < data_X.Length; l++) { if (data_X[l] >= freqList[ll - 1]) { for (int j = number; j <= l; j++) { mean += data[j]; cout_mean++; } mean = mean / cout_mean; mean -= 10; number = l; if (mean <= dopusk[ll - 1]) { results = "Да"; } else { results = "Нет"; } break; } } sw.WriteLine(String.Format("{0,20}", freqList[ll - 1].ToString()) + "\t" + String.Format("{0,20}", freqList[ll].ToString()) + "\t" + String.Format("{0,20}", (mean).ToString()) + "\t" + String.Format("{0,20}", (dopusk[ll - 1]).ToString()) + "\t" + String.Format("{0,20}", results)); } sw.Flush(); m_DrawGraphicOnForm.DrawGraphic(false); } Form1.IsRun = false; sw.Close(); //Освобождаем ресурсы m_DrawGraphicOnForm.DrawGraphic(true); m_DrawGraphicOnForm.EndCalculate(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); dr = MessageBox.Show("Процедура поверки по уровню шумов закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } } catch (Exception ex) { //Освобождаем ресурсы m_DrawGraphicOnForm.DrawGraphic(true); m_DrawGraphicOnForm.EndCalculate(); Form1.IsRun = false; System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); MessageBox.Show("Нарушение инструкции измерений, повторите попытку поверки по уровню шумов еще раз", "Внимание"); } }
private void Run() { try { DialogResult dr; try { // Create driver instance CNT = (MessageBasedSession)ResourceManager.GetLocalManager().Open(Form1.addr_CNT); } catch { MessageBox.Show("Проверьте физическое и программное подключение частотомера к компьютеру", "Внимание", MessageBoxButtons.OK); m_DrawGraphicOnForm.EndCalculate(); return; } try { // Create driver instance VAC = (MessageBasedSession)ResourceManager.GetLocalManager().Open(Form1.addr_zva); } catch { MessageBox.Show("Проверьте физическое и программное подключение анализатора цепей к компьютеру", "Внимание", MessageBoxButtons.OK); m_DrawGraphicOnForm.EndCalculate(); return; } CNT.Timeout = 20000; VAC.Timeout = 20000; CNT.Write("*RST"); VAC.Write("*RST"); VAC.Write($"SENS:SWE:TYPE CW"); CNT.Write($"SENS:ACQ:APER 300ms"); VAC.Write("SOUR1:POW 3"); string str1; string result; bool IsCanalA = false; bool IsCanalB = false; if (Form1.freqList_freq[0] <= 0.00001) { MessageBox.Show("Некорректно задана измеряемая частота (за нижним пределом диапазона частот стенда)", "Внимание"); if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } m_DrawGraphicOnForm.EndCalculate(); return; } if (Form1.freqList_freq[0] <= 0.3) { IsCanalA = true; } else if (Form1.freqList_freq[0] <= 40) { IsCanalB = true; } else { MessageBox.Show("Некорректно задана измеряемая частота (за верхним пределом диапазона частот стенда)", "Внимание"); if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } m_DrawGraphicOnForm.EndCalculate(); return; } string fileName = Form1.path + "\\" + String.Format("freq_{0}.txt", Form1.date.ToShortTimeString().Replace(":", " ")); StreamWriter sw = new StreamWriter(FileStream.Null); try { sw = new StreamWriter(fileName); } catch { System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); MessageBox.Show("Отсутствуют права на запись файла по указанному пути, обратитесь к администратору", "Внимание", MessageBoxButtons.OK); if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } m_DrawGraphicOnForm.EndCalculate(); return; } sw.WriteLine("Определение диапазона рабочих частот и относительной погрешности установки частоты источника выходного сигнала"); sw.WriteLine(); sw.WriteLine(String.Format("{0,20}", "f_уст, ГГц") + "\t" + String.Format("{0,20}", "f_изм, ГГц") + "\t" + String.Format("{0,20}", "Погрешн., отн.ед.") + "\t" + String.Format("{0,20}", "Доп.знач., отн.ед (±)") + "\t" + String.Format("{0,20}", "Соответ.?")); sw.Flush(); Form1.IsRun = true; sw.WriteLine(); for (int ii = 0; ii < Form1.count_port_freq; ii++) { IsCanalA = false; IsCanalB = false; sw.WriteLine(); sw.WriteLine("Порт {0}", Form1.number_port_freq[ii]); if (Form1.freqList_freq[0] <= 0.3) { dr = MessageBox.Show(String.Format("Подключите ПОРТ_{0} анализатора цепей к входу А частотомера, после этого нажмите ОК", Form1.number_port_freq[ii]), "Внимание", MessageBoxButtons.OKCancel); IsCanalA = true; } else { dr = MessageBox.Show(String.Format("Подключите ПОРТ_{0} анализатора цепей к входу C частотомера, после этого нажмите ОК", Form1.number_port_freq[ii]), "Внимание", MessageBoxButtons.OKCancel); IsCanalB = true; } if (dr == DialogResult.Cancel) { sw.Close(); Form1.IsRun = false; if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } dr = MessageBox.Show("Процедура поверки по частоте закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } m_DrawGraphicOnForm.EndCalculate(); return; } for (int i = 0; i < Form1.freqList_freq.Length; i++) { if (!Form1.IsRun) { sw.Close(); Form1.IsRun = false; if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } dr = MessageBox.Show("Процедура поверки по частоте закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } m_DrawGraphicOnForm.EndCalculate(); return; } if (i != 0) { if (Form1.freqList_freq[i] <= 0.3) { } else if (Form1.freqList_freq[i] > 0.3 && Form1.freqList_freq[i] <= 40) { if (!IsCanalB) { dr = MessageBox.Show(String.Format("Подключите ПОРТ_{0} анализатора цепей к входу C частотомера, после этого нажмите ОК", Form1.number_port_freq[ii]), "Внимание", MessageBoxButtons.OKCancel); IsCanalB = true; if (dr == DialogResult.Cancel) { if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } sw.Close(); Form1.IsRun = false; dr = MessageBox.Show("Процедура поверки по частоте закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } m_DrawGraphicOnForm.EndCalculate(); return; } } } else { MessageBox.Show("Некорректно задана измеряемая частота или измеряемая мощность (за диапазоном частот стенда)", "Внимание"); sw.Close(); Form1.IsRun = false; dr = MessageBox.Show("Процедура поверки по частоте закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } if (CNT != null) { // Close the driver CNT.Dispose(); } if (VAC != null) { // Close the driver VAC.Dispose(); } m_DrawGraphicOnForm.EndCalculate(); return; } } switch (Form1.number_port_freq[ii]) { case (1): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S11'"); break; case (2): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S22'"); break; case (3): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S33'"); break; case (4): VAC.Write(@"CALC1:PAR:MEAS 'Trc1', 'S44'"); break; } VAC.Write($"SENS:FREQ {Form1.freqList_freq[i] * Math.Pow(10, 9)}"); Thread.Sleep(100); if (Form1.freqList_freq[i] <= 0.3) { str1 = CNT.Query("MEAS:FREQ? (@1)n").Replace("\n", "").Replace(".", ","); CNT.Write($"SENS:ACQ:APER 100ms"); str1 = CNT.Query("READ:FREQ? (@1)n").Replace("\n", "").Replace(".", ","); } else { str1 = CNT.Query("MEAS:FREQ? (@3)n").Replace("\n", "").Replace(".", ","); CNT.Write($"SENS:ACQ:APER 100ms"); str1 = CNT.Query("READ:FREQ? (@3)n").Replace("\n", "").Replace(".", ","); } str1 = (Convert.ToDouble(str1) * Math.Pow(10, -9)).ToString(); if (Math.Abs(((Form1.freqList_freq[i] - Convert.ToDouble(str1)) / (Form1.freqList_freq[i]))) <= 8 * Math.Pow(10, -6)) { result = "Да"; } else { result = "Нет"; } sw.WriteLine(String.Format("{0,20}", (Form1.freqList_freq[i]).ToString()) + "\t" + String.Format("{0,20}", str1) + "\t" + String.Format(CultureInfo.InvariantCulture, "{0,20:0.###E+00}", (Form1.freqList_freq[i] - Convert.ToDouble(str1)) / (Form1.freqList_freq[i])) + "\t" + String.Format("{0,20}", "8E-06") + "\t" + String.Format("{0,20}", result)); m_DrawGraphicOnForm.DrawGraphic(false); } } Form1.IsRun = false; sw.Close(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); dr = MessageBox.Show("Процедура поверки по частоте закончена. Просмотреть результаты?", "Внимание", MessageBoxButtons.OKCancel); if (dr == DialogResult.OK) { Process.Start(fileName); } //Освобождаем ресурсы m_DrawGraphicOnForm.DrawGraphic(true); m_DrawGraphicOnForm.EndCalculate(); sw.Close(); } catch (Exception ex) { //Освобождаем ресурсы m_DrawGraphicOnForm.DrawGraphic(true); m_DrawGraphicOnForm.EndCalculate(); Form1.IsRun = false; System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); System.Media.SystemSounds.Beep.Play(); MessageBox.Show("Нарушение инструкции измерений, повторите попытку поверки по частоте еще раз", "Внимание"); } }
/// <summary> /// 载入校准档案文件 /// </summary> /// <param name="calFilePath">档案文件路径,相对网分设备</param> /// <param name="msg"></param> /// <returns></returns> public override bool LoadCalFile(string calFilePath, ref string msg) { Connect(); string loadCalFile = "MMEM:load '" + calFilePath + "'"; _mbSession.Write(loadCalFile); Thread.Sleep(5000); string typeLin = ":SENS1:SWE:TYPE LINear"; _mbSession.Write(typeLin); return(true); }
public bool SetFreq(int chNum, float freq) { afg3022Session.Write("SOURce" + (chNum + 1) + ":FREQuency:FIXed " + freq); return(true); }
public void FMSignal(int SourceNum, float carrier, float low, float offset, float ampl) { session.Write("SOURce" + SourceNum + ":FUNCtion:SHAPe SIN"); session.Write("SOURce" + SourceNum + ":FREQuency:FIXed " + carrier); session.Write("SOURce" + SourceNum + ":VOLTage:UNIT VRMS"); session.Write("SOURce" + SourceNum + ":VOLTage:LEVel:IMMediate:AMPLitude " + ampl); session.Write("SOURce" + SourceNum + ":FM:INTernal:FUNCtion SQUare"); session.Write("SOURce" + SourceNum + ":FM:INTernal:FREQuency " + low); session.Write("SOURce" + SourceNum + ":FM:DEViation " + offset); session.Write("SOURce" + SourceNum + ":FM:STATe ON"); }