public string query(string cmd) { string resp = null; try { resp = mSession.Query(cmd); } catch (VisaException ex) { //resp = exp.ToString();// string.Empty; throw ex; } return(resp); }
public bool IsConnected() { if (mbSession == null) { return(false); } try { string data = mbSession.Query("*IDN?\n"); return(data.Trim().Length != 0); } catch { return(false); } }
protected bool checkBusyState(MessageBasedSession mbSession, string command) { string OK = "0"; string Command_Line; string responseString = "1"; byte counter = 0; if ((command == "*ESE?") || (command == "*ESR?")) { OK = "0"; } else if ((command == "*OPC?") || (command == ":STAT:SRW:MEAS?")) { OK = "1"; } while ((responseString.Trim() != OK) && (counter < 255)) { Command_Line = ReplaceCommonEscapeSequences(command + "\n"); responseString = mbSession.Query(Command_Line); responseString = responseString.Substring(0, 1); Thread.Sleep(250); counter++; } if (counter == 1) { return(false); } else { return(true); } }
/// <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 string RequestQuery(string query) { lock (sendCommandRequestLocker) lock (receiveDeviceAnswerLocker) lock (requestQueryLocker) { var _Query = query.EndsWith("\n") ? Encoding.ASCII.GetBytes(query) : Encoding.ASCII.GetBytes(string.Format("{0}\n", query)); return(Encoding.ASCII.GetString(mbSession.Query(_Query)).TrimEnd(delim)); } }
/// <summary> /// 初始化设备 /// </summary> /// <param name="Device_Address"></param>设备的GPIB地址 private void Measure_Voltage() { Cursor.Current = Cursors.WaitCursor; try { //Send_Result("0.0"); int Valid_Num = 0; float Sum_Voltage = 0; String responseString = "0.0", textToWrite; for (int i = 0; i < 3; i++) { Print_Log(String.Format("将在{0}秒后开始测量...", 3 - i)); Thread.Sleep(1000); } Print_Log("开始测量..."); for (int i = 0; i < 10; i++) { textToWrite = ReplaceCommonEscapeSequences("MEAS:VOLT:DC? 10V,0.0001V\\n"); responseString = mbSession.Query(textToWrite); if (float.Parse(responseString) < 2) { Print_Log(String.Format("第{0}次测量:无效电压{1:F4}", i, responseString)); } else { Valid_Num++; Sum_Voltage += float.Parse(responseString); Print_Log(String.Format("第{0}次测量:{1:F4}", i, responseString)); } Thread.Sleep(500); } if (Valid_Num != 0) { Print_Log(String.Format("{0}次有效测量平均值:{1:F4}", Valid_Num, Sum_Voltage / Valid_Num)); Send_Result((Sum_Voltage / Valid_Num).ToString()); } else { Send_Result(responseString); } //mbSession.Write(ReplaceCommonEscapeSequences("MEAS:VOLT:DC? \\n")); } catch (ThreadAbortException) { //Print_Log("终止线程!"); } catch (Exception exp) { MessageBox.Show(exp.Message); } finally { Cursor.Current = Cursors.Default; } }
/// <summary> /// /// </summary> /// <param name="query"></param> public void ReadDeviceAnswer(string query) { switch (cbInterfaceType.Text) { case "GPIB": { answer = ""; try { answer = device.ReadString(); txtAnswer.Text = answer; } catch (Exception ex) { ex.ToString(); switch (cbInterfaceType.Text) { default: { txtAnswer.Text = "+0,+1.00000E-00,+1.00000E-00\n"; answer = "+0,+1.00000E-00,+1.00000E-00\n"; break; } } } break; } case "USB": { answer = mbSession.Query(query); break; } case "ETHERNET": break; default: break; } }
private void query_Click(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; try { string textToWrite = ReplaceCommonEscapeSequences(writeTextBox.Text); string responseString = mbSession.Query(textToWrite); readTextBox.Text = InsertCommonEscapeSequences(responseString); if (checkBoxLog.Checked) { Log.WriteLog("Query - " + textToWrite, responseString); } } catch (Exception exp) { MessageBox.Show(exp.Message); } finally { Cursor.Current = Cursors.Default; } }
public object Query(object objCmd) { try { lock (_lock) { return(session.Query(objCmd.ToString())); } } catch (Exception ex) { throw ex; } }
public static void ListAll_TMC_Devices() { //对满足 TMC的设备都支持-ls列出 // (GPIB[0-9]{1,}::[0-9]{1,}::INSTR|TCPIP[0-9]{1,}::.*::INSTR|USB[0-9]{1,}.*::INSTR) USB0::0x0699::0x0415::C022855::INSTR TCPIP0::192.168.1.2::inst0::INSTR GPIB0::2::INSTR https://www.regextester.com/93690 String[] resources = ResourceManager.GetLocalManager().FindResources("?*"); Regex regex = new Regex(@"(GPIB[0-9]{1,}::[0-9]{1,}::INSTR|TCPIP[0-9]{1,}::.*::INSTR|USB[0-9]{1,}.*::INSTR)", RegexOptions.IgnoreCase); //由于该正则表达式在 FindResources("")中不被识别,直接被解析为了 viFindRsrc (0x00001001, "(GPIB[0-9]{1,}::[0-9]{1,}::INSTR|TCPIP[0-9]{1,}::.*::INSTR|USB[0-9]{1,}.*::INSTR)", 0x00000000, 0 (0x0), "") ,因此另用正则表达式匹配 https://www.dotnetperls.com/regex foreach (String res in resources) { if (regex.Match(res).Success) { MessageBasedSession mbs = (MessageBasedSession)ResourceManager.GetLocalManager().Open(res); mbs.Clear(); //it's better send a Device Clear before operation String IDN = mbs.Query("*IDN?"); Console.Write(res.PadRight(20) + " " + IDN); } } //此处不能用return,return后程序继续执行,导致出现 : 指定的资源引用非法。解析出错。 VISA error code -1073807342 (0xBFFF0012), ErrorInvalidResourceName viParseRsrcEx (0x00001001, NULL, 0 (0x0), 0 (0x0), "", "", "") Environment.Exit(0); }
public bool checkBusyState(MessageBasedSession mbSession, string command) //OLD-PANDA { string OK = "0"; string Command_Line; string responseString = "1"; byte counter = 0; if ((command == "*ESE?") || (command == "*ESR?")) { OK = "0"; } else if ((command == "*OPC?") || (command == ":STAT:SRW:MEAS?")) { OK = "1"; } while ((responseString.Trim() != OK) && (counter < 500)) { Command_Line = ReplaceCommonEscapeSequences(command + "\n"); responseString = mbSession.Query(Command_Line); //"trim do not work //trim only trim space but what you have is /n/r //effectively a carriage return that cannot be removed by trime". WeeWen said. responseString = responseString.Substring(0, 1); Thread.Sleep(500); counter++; } if (counter == 1) { return(false); } else { return(true); } }
public void SetLineRate(MessageBasedSession mbSession, int rate) { mbSession.Query("ssf " + rate.ToString() + "\r"); }
public void SetExposureTime(MessageBasedSession mbSession, double time) { mbSession.Query("set " + time.ToString() + "\r"); }
// /*-------Testing for WLAN 802.11n - OFDM Modulation------------------------------------------------*/ /* ------Thực hiện đo WLAN 802.11n SISO---------------------------- * Tham số đầu vào: * - RichTexBox g_logfilePath: Hiển thị ở giao diện chính * - E6640A * - string testItems: Danh sách các thông số cần đo * - string strInAtten: Giá trị suy hao input (--->RF port) * - string strOutAtten: Giá trị suy hao ouput (RF port--->) * Các biến trong hàm: * - Thread.Sleep(timedelay): Đợi một khoảng timedelay [ms] */ //Cấu hình bài test public bool testing_HT20(string testItems) { bool wifiTesting_result = true; try { string result_Value = string.Empty; //-----Thay đổi giá trị Statistic count để lấy được kết quả đo chính xác-------------------------------------------------- //-----Sau khi thay đổi giá trị này, phần mềm phải tạo lại 1 phiên kết nối mới với máy đo để đọc được kết quả đo----------- //Đọc kết quả đo điều chế OFDM //Thread.Sleep(maxEquip_DELAY * 5); //comment on Thusday 26 Novem 2015 checkBusyState(mbSession, "*ESR?"); checkBusyState(mbSession, "*OPC?"); mbSession.Write(":INIT:CONT 0"); checkBusyState(mbSession, "*ESR?"); checkBusyState(mbSession, "*OPC?"); mbSession.Write(":SENSe:POWer:RF:RANGe:OPTimize IMMediate\n"); checkBusyState(mbSession, "*ESR?"); checkBusyState(mbSession, "*OPC?"); result_Value = mbSession.Query("READ:EVM?"); result_Value = InsertCommonEscapeSequences(result_Value); //saveLogfile(g_logfilePath, "READ:EVM? ==>[" + result_Value + "]\n"); if (result_Value.Trim() == "")//Nếu như chuỗi result_Value rỗng thì đưa ra FAIL { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] [FAIL] Giá trị kết quả trả về = null \n"); return(wifiTesting_result); } //---------Hiển thị kết quả đo nếu như kết quả là hợp lệ---------------------- try { string[] MODulation_Value = result_Value.Split(new Char[] { ',' }); Decimal measureResult; //Thông số được lựa chọn trong bài test if (testItems.Contains("AvgPower")) { measureResult = Decimal.Parse(MODulation_Value[19], System.Globalization.NumberStyles.Float); //Hien thi ket qua do duoc saveLogfile(g_logfilePath, "- Average Power = " + measureResult.ToString("0.####") + " dBm"); //Kiểm tra xem nó FAIL hay PASS bằng cách dung hàm check đũng viết từ trên if (check_PassFail_limit(measureResult, AvgPWLow_decimal, AvgPWUp_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_TXPower]\n \n Fail Tai Bai Test 'Average Power' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test if (testItems.Contains("EVMall")) { measureResult = Decimal.Parse(MODulation_Value[1], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- EVM All Carriers = " + measureResult.ToString("0.####") + " dB"); if (check_PassFail_limit(measureResult, -500, EVMallUp_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_EVMAll]\n \n Fail Tai Bai Test 'EVM All Data' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //EVM data carriers if (testItems.Contains("EVMdata")) { measureResult = Decimal.Parse(MODulation_Value[29], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- EVM Data Carriers = " + measureResult.ToString("0.####") + " dB"); if (check_PassFail_limit(measureResult, -500, EVMDataUp_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_EVMData]\n \n Fail Tai Bai Test 'EVM Data Carriers' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //Gia tri EVM pilot carriers if (testItems.Contains("EVMpilot")) { measureResult = Decimal.Parse(MODulation_Value[27], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- EVM Pilot Carriers = " + measureResult.ToString("0.####") + " dB"); if (check_PassFail_limit(measureResult, -500, EVMPilotUp_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_EVMPilot]\n \n Fail Tai Bai Test 'EVM Pilot Carriers' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //FreqError if (testItems.Contains("FreErr")) { measureResult = Decimal.Parse(MODulation_Value[7], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- Center Frequency Error = " + measureResult.ToString("0.####") + " Hz"); if (check_PassFail_limit(measureResult, -MaxFreqErr_decimal, MaxFreqErr_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_Freq]\n \n Fail Tai Bai Test 'Center Frequency Error' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //Gia tri Symbol clock error if (testItems.Contains("SylClkErr")) { measureResult = Decimal.Parse(MODulation_Value[11], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- Symbol clock error = " + measureResult.ToString("0.####") + " ppm"); if (check_PassFail_limit(measureResult, -MaxSymbolCLKErr_decimal, MaxSymbolCLKErr_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_SymbolClock]\n \n Fail Tai Bai Test 'Symbol Clock Error' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //Gia tri LO Leakage (dB)? if (testItems.Contains("IQIm")) { measureResult = Decimal.Parse(MODulation_Value[13], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- IQ Offset = " + measureResult.ToString("0.####") + " dB"); if (check_PassFail_limit(measureResult, -500, MaxIQ_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_IQOffset]\n \n Fail Tai Bai Test 'IQ Offset' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //Gia tri Amplitude imbalance (dB) (GainImbal?) if (testItems.Contains("AmpIm")) { measureResult = Decimal.Parse(MODulation_Value[15], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- Gain Imbalance (Amplitude imbalance) = " + measureResult.ToString("0.####") + " dB"); if (check_PassFail_limit(measureResult, -500, MaxAmpI_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_GainImbal]\n \n Fail Tai Bai Test 'Gain Imbalance' \n"); return(wifiTesting_result); } } //Thông số được lựa chọn trong bài test //Gia tri QuadError (Phase Imbalance?) if (testItems.Contains("PhaseIm")) { measureResult = Decimal.Parse(MODulation_Value[17], System.Globalization.NumberStyles.Float); saveLogfile(g_logfilePath, "- Quadrature Error (Phase Imbalance) = " + measureResult.ToString("0.####") + " Deg"); if (check_PassFail_limit(measureResult, -MaxPhaseI_decimal, MaxPhaseI_decimal)) { saveLogfile(g_logfilePath, " PASS\n"); } else { saveLogfile(g_logfilePath, " FAIL\n"); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_QuadError]\n \n Fail Tai Bai Test 'Quadrature Error' \n"); return(wifiTesting_result); } } } catch { wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] FAIL CODE: [WIFI_Processing] \n \n Loi! xay ra trong qua trinh doc ket qua tu E6640A \n"); return(wifiTesting_result); } return(wifiTesting_result); } catch (Exception Ex) { //MessageBox.Show(Ex.ToString()); wifiTesting_result = false; saveLogfile(g_logfilePath, "[E6640A] ERROR CODE: [WIFI_Testing] \n \n Loi! xay ra tai qua trinh test Wifi \n"); return(wifiTesting_result); } }
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) {} }
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("Нарушение инструкции измерений, повторите попытку поверки по частоте еще раз", "Внимание"); } }
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("Нарушение инструкции измерений, повторите попытку поверки по уровню шумов еще раз", "Внимание"); } }
public string Query(string cmd) { mSession.Write("SYSTem:REMote"); return(mSession.Query(cmd)); }
public string Query(string command) { return(Connector.Query(command + "\r\n")); }
public override bool Init() { try { HardwareCfgManager hardwareCfg = ConfigMgr.HardwareCfgMgr; if (Config.ConnectMode.ToUpper() == @"COMPORT") { foreach (var it in hardwareCfg.Comports) { if (it.PortName == Config.PortName) { comportCfg = it; } } comPort = new System.IO.Ports.SerialPort(); if (comPort != null && comportCfg != null) { GetPortProfileData(comportCfg); comPort.PortName = comportData.Port; comPort.BaudRate = comportData.BaudRate; comPort.Parity = comportData.parity; comPort.StopBits = comportData.stopbits; comPort.DataBits = comportData.DataBits; comPort.ReadTimeout = comportData.Timeout; comPort.WriteTimeout = comportData.Timeout; if (comPort.IsOpen) { comPort.Close(); } comPort.Open(); return(comPort.IsOpen); } return(false); } else if (Config.ConnectMode.ToUpper() == @"NIVISA") { foreach (var it in hardwareCfg.NIVisas) { if (it.PortName == Config.PortName) { nivisaCfg = it; } } if (nivisaCfg != null) { string[] resources = ResourceManager.GetLocalManager().FindResources(nivisaCfg.KeyWord1); foreach (var res in resources) { if (res.Contains(nivisaCfg.KeyWord2)) { session = ResourceManager.GetLocalManager().Open(resources[0].ToString()) as MessageBasedSession; } } string str = session.Query("READ?"); return(session != null); } } return(false); } catch (Exception ex) { return(false); } }