//选择设备之后进行打开 private void button2_Click(object sender, EventArgs e) { SelectResource f = new SelectResource(); f.StartPosition = FormStartPosition.CenterParent; DialogResult r = f.ShowDialog(this); if (r == DialogResult.OK) { device_name = f.ResourceName; Cursor.Current = Cursors.WaitCursor; using (var rmSession = new ResourceManager()) { try { mbSession = (MessageBasedSession)rmSession.Open(f.ResourceName); button2.Enabled = false; button3.Enabled = true; } catch (InvalidCastException) { System.Windows.Forms.MessageBox.Show("Resource selected must be a message-based session"); } catch (Exception exp) { System.Windows.Forms.MessageBox.Show(exp.Message); } finally { Cursor.Current = Cursors.Default; } } } }
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); } }
private void openSession_Click(object sender, System.EventArgs e) { using (SelectResource sr = new SelectResource()) { if (lastResourceString != null) { sr.ResourceName = lastResourceString; } DialogResult result = sr.ShowDialog(this); if (result == DialogResult.OK) { lastResourceString = sr.ResourceName; Cursor.Current = Cursors.WaitCursor; try { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(sr.ResourceName); SetupControlState(true); } catch (InvalidCastException) { MessageBox.Show("Resource selected must be a message-based session"); } catch (Exception exp) { MessageBox.Show(exp.Message); } finally { Cursor.Current = Cursors.Default; } } } }
static void instrument_write(MessageBasedSession instrument_control_object, string command) { /* * Purpose: Used to send commands to the instrument. * * Parameters: * instrument_control_object - The reference to the instrument object created external to this function. It is passed * in by reference so that it retains all values upon exiting this function, making it * consumable to all other calling functions. * * command - The command string issued to the instrument in order to perform an action. * * Returns: * None * * Revisions: * 2019-06-04 JJB Initial revision. */ if (echo_command == true) { Console.WriteLine("{0}", command); } instrument_control_object.RawIO.Write(command); //instrument_control_object.WriteString(command + "\n"); return; }
private void SelRes() { if ((string)availableResourcesListBox.SelectedItem != null) { string selectedString = (string)availableResourcesListBox.SelectedItem; ResourceName = selectedString; using (var rmSession = new ResourceManager()) { try { mbSession = (MessageBasedSession)rmSession.Open(ResourceName); mbSession.RawIO.Write("*OPT?"); string cardInSlot = mbSession.RawIO.ReadString(); //if (cardInSlot.Contains("7708")) //{ this.DialogResult = DialogResult.OK; this.Close(); ////} //else //{ // MessageBox.Show(adRes.brd7708notfound); //} } catch (Exception e) { MessageBox.Show(e.Message); } } } }
/// <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 static void SetUSBRawAttribute(ref MessageBasedSession mbs) { UsbRaw usbRaw = (UsbRaw)mbs; usbRaw.InterruptInPipe = -1; // Disable the interrupt pointer usbRaw.BulkInPipe = 129; // Re-define the bulk-in pipe }
public virtual int Connect(int gpibAddress, bool remote, string serverName) { int status = 0; string remoteServer = $"visa://{serverName}"; string instrumentID; if (remote) { instrumentID = $"{remoteServer}/GPIB0::{gpibAddress}::INSTR"; } else { instrumentID = $"GPIB0::{gpibAddress}::INSTR"; } try { session = (MessageBasedSession)ResourceManager.GetLocalManager().Open(instrumentID); if (Convert.ToBoolean(VerifyInstrument())) { //if the instrument is not of the correct type, close the session. session.Dispose(); status = -1; } } catch (Exception ex) { Logger.ReportException($"Failed to open gpib device {instrumentID}.", ex); status = -1; } return status; }
public static void SetSerialAttribute(ref MessageBasedSession mbs) { SerialSession ser = (SerialSession)mbs; ser.BaudRate = GlobalVars.VISA_CLI_Option_SerialBaudRate; //设置速率 ser.DataBits = GlobalVars.VISA_CLI_Option_SerialDataBits; //数据位 ser.StopBits = GlobalVars.VISA_CLI_Option_SerialStopBits; //停止位 ser.Parity = GlobalVars.VISA_CLI_Option_SerialParity; //校验 NONE 0 Odd 1 Even 2 Mark 3 Space 4 ser.FlowControl = GlobalVars.VISA_CLI_Option_SerialFlowControl; //Flow Control NONE 0 XON/XOFF 1 使用 NI I/O Trace 监视 VISA Test Panel 设置时得到 ser.TerminationCharacter = GlobalVars.theReadTerminationCharactersOfRS232; //结束符,针对每个串口只能设置唯一的结束符,此处留给 Read操作,Write操作直接手动在命令末尾加指定的结束符 ser.ReadTermination = GlobalVars.VISA_CLI_Option_SerialTerminationMethodWhenRead; // 读回结束符选择 //VI_ATTR_ASRL_END_IN indicates the method used to terminate read operations ser.WriteTermination = GlobalVars.VISA_CLI_Option_SerialTerminationMethodWhenWrite; // 写入结束符选择(ser.TerminationCharacter 定义的终止符优先给读回终止符, 写入终止符由 --stmW=2 和 --terminateW="0x0A" 共同指定,若--terminateW不指定,默认使用0x0aA) // VI_ATTR_ASRL_END_OUT indicates the method used to terminate write operations if (GlobalVars.VISA_CLI_Option_PrintDebugMessage) { Console.WriteLine("当前正使用COM通信,当前设置为:\n速率 : " + GlobalVars.VISA_CLI_Option_SerialBaudRate.ToString() + " bps" + "\n数据位 : " + GlobalVars.VISA_CLI_Option_SerialDataBits.ToString() + "\n停止位 : " + (((int)GlobalVars.VISA_CLI_Option_SerialStopBits) / 10).ToString() + "\n校验方式(Parity) : " + GlobalVars.VISA_CLI_Option_SerialParityEnumList[((int)GlobalVars.VISA_CLI_Option_SerialParity)] + "\nFlowControl : " + GlobalVars.VISA_CLI_Option_SerialFlowControlEnumList[((int)GlobalVars.VISA_CLI_Option_SerialFlowControl)] + "\nTerminationCharacter : 0x" + GlobalVars.theReadTerminationCharactersOfRS232.ToString("X2") //https://stackoverflow.com/questions/5426582/turn-byte-into-two-digit-hexadecimal-number-just-using-tostring/5426587#5426587 + "\nTerminationCharactersOfRead : 0x" + GlobalVars.theReadTerminationCharactersOfRS232.ToString("X2") + "\nTerminationCharactersOfWrite : 0x" + GlobalVars.theWriteTerminationCharactersOfRS232.ToString("X2") + "\nSerialTerminationMethodOfRead : " + GlobalVars.VISA_CLI_Option_SerialTerminationMethodEnumList[((int)GlobalVars.VISA_CLI_Option_SerialTerminationMethodWhenRead)] + "\nSerialTerminationMethodOfWrite : " + GlobalVars.VISA_CLI_Option_SerialTerminationMethodEnumList[((int)GlobalVars.VISA_CLI_Option_SerialTerminationMethodWhenWrite)] + "\n\n请确保仪器设置与本设置相符" ); } }
private void frmMain_Load(object sender, EventArgs e) { if (TekScope != null) { TekScope.Dispose(); TekScope = null; } }
private void openMySession() { closeMySession(); //open a Session to the VNA mySession = ResourceManager.GetLocalManager().Open(sAddress); //cast this to a message based session mbSession = (MessageBasedSession)mySession; }
private AFG3022() { string[] resources = ResourceManager.GetLocalManager().FindResources("USB?*INSTR"); if (resources != null && resources.Length > 0) { session = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resources[0]); } }
private string readFRES(MessageBasedSession mbSession, Channel prevChan) { try { mbSession.RawIO.Write($"ROUT:OPEN:ALL"); Thread.Sleep(20); mbSession.RawIO.Write($"ROUT:MULT:CLOS (@{portAddr},{Pair},141,142,143)"); Thread.Sleep(20); if (this.Function != prevChan.Function) { mbSession.RawIO.Write($"SENS:FUNC 'FRES'"); } if (this.range != prevChan.range) { string rangeDyn = range.Replace("k", "000"); rangeDyn = range.Replace("M", "000000"); mbSession.RawIO.Write($":SENS:FRES:RANG{rangeDyn}"); } if (this.NPLC != prevChan.NPLC) { mbSession.RawIO.Write($":SENS:FRES:NPLC {NPLC}"); } if (this.FILT != prevChan.FILT) { mbSession.RawIO.Write($":SENS:FRES:AVER:STAT {FILT}"); } for (int i = 0; i < 2; i++) { mbSession.RawIO.Write("DATA:FRESH?"); //-6.26574010E-02VDC,+900.272SECS,+69495RDNG# пример возвращаемой строки string readStr = mbSession.RawIO.ReadString(); //string readStr = "-6.26574010E-02VDC,+900.272SECS,+69495RDNG#"; string[] separator = { "," }; string[] nameAr = readStr.Split(separator, StringSplitOptions.RemoveEmptyEntries); string[] separator2 = { "OHM4W" }; nameAr = nameAr[0].Split(separator2, StringSplitOptions.RemoveEmptyEntries); nameAr[0] = nameAr[0].Replace(".", ","); double result = 0; if (double.TryParse(nameAr[0], out result) && nameAr[0] != "+9,9E37" && nameAr[0] != "-9,9E37") { return(nameAr[0]); } ; } return("OVRFLW"); } catch (IOTimeoutException exp) { MessageBox.Show("Failed to read value. Reason: " + exp.Message); } catch (NativeVisaException exp) { MessageBox.Show("Failed to read value. Reason: " + exp.Message); } return(null); }
/// <summary> /// Close the session (if opened) /// </summary> public void close() { lock (mbSession) { if (mbSession != null) { mbSession.Dispose(); mbSession = null; } } }
/// <summary> /// Open a sesion to a specified resource. If an existing session is open it will be closed first. /// </summary> /// <param name="resourceName"></param> public void open(string resourceName) { if (isOpen()) { close(); } using (var rmSession = new ResourceManager()) { mbSession = (MessageBasedSession)rmSession.Open(resourceName); } }
public bool Open(string visaaddress) { try { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(visaaddress); return(true); } catch { return(false); } }
/// <summary> /// /// </summary> /// <returns></returns> public bool Connection(ref string message) { try { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(MeasureEquip_IP); return(true); }catch (Exception ex) { message = ex.ToString(); return(false); } }
public bool Open(out string message) { message = ""; try { mbSession = (MessageBasedSession)NationalInstruments.VisaNS.ResourceManager.GetLocalManager().Open(this.GPIBAddress); //att_handle là địa chỉ GPIB của máy Attenuation return(true); } catch (Exception ex) { message = ex.ToString(); return(false); } }
private async void openSession_Click(object sender, EventArgs e) { if (openSession.Text == adRes.openSession) { using (SelectResource sr = new SelectResource()) { if (lastResourceString != null) { sr.ResourceName = lastResourceString; } DialogResult result = sr.ShowDialog(this); if (result == DialogResult.OK) { lastResourceString = sr.ResourceName; Cursor = Cursors.WaitCursor; using (var rmSession = new ResourceManager()) { try { mbSession = sr.mbSession; mbSession.TimeoutMilliseconds = 20000; SetupControlState(true); } catch (InvalidCastException) { MessageBox.Show("Resource selected must be a message-based session"); } catch (Exception exp) { MessageBox.Show(exp.Message); } finally { Cursor = Cursors.Default; } } openSession.Text = adRes.closeSession; } } } else if (openSession.Text == adRes.closeSession) { await Task.Run(() => waitWriteEnds()); DeinitializeTimer(); createTimerBtn.Enabled = false; createTimerBtn.Text = adRes.strRecord; channels = null; SetupControlState(false); mbSession.Dispose(); openSession.Text = adRes.openSession; } }
public FunGen() { if (desc != null) { // afg3022.Descriptor = desc; return; } if (GetDevDescList() != null && deviceList.Count != 0) { afg3022Session = (MessageBasedSession)ResourceManager.GetLocalManager().Open(deviceList[0]); } }
public void Dispose() { if (_handleSessionLifetime) { if (_instrumentSession != null) { ((IDisposable)(_instrumentSession)).Dispose(); _instrumentSession = null; } } GC.SuppressFinalize(this); }
public SetupForm(List <Channel> channel, MessageBasedSession mbSeesion) { InitializeComponent(); session = mbSeesion; channels = new List <Channel>(); if (channel != null) { channels.Clear(); channels.AddRange(channel); saveSetsBtn.Enabled = true; } refrashLists(); }
/// <summary> /// Makes sure message based session has been and is still opened. Throws an exception if not. /// </summary> protected void preCheck() { if (!isOpen()) { throw new Exception("No session opened."); } // If disposed and not set to null it was not closed here. Closed due to loss of communication if (mbSession.IsDisposed && isOpen()) { mbSession = null; throw new Exception("Communication with the device was lost."); } }
/*----------------------------------------------------------*/ public E6640A_VISA(string MeasureEquip_IP) { try { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(MeasureEquip_IP); //Hàm dùng để vào máy đo, để thực hiện cấu hình } catch { //Nếu vòng try sai thì báo lỗi ở đây MessageBox.Show("[E6640A_VISA]Không kết nối được với máy đo IP= " + MeasureEquip_IP); saveLogfile(g_logfilePath, "[E6640A_VISA]Không kết nối được với máy đo IP= " + MeasureEquip_IP + " \n"); }; }
public void Disconnect() { try { session.DisableEvent(EventType.AllEnabled); session.Clear(); io = null; session = null; } catch (Exception exception) { throw CreateThrowUpException(exception); } }
public MBSession(string resourceString) { if (resourceString != null) { try { MbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resourceString); } catch (Exception exc) { MessageBox.Show(exc.Message, exc.GetType().ToString()); } } else { MessageBox.Show("Empty resource string"); } }
public void readTime(MessageBasedSession mbSession, Channel prevChan) { mbSession.RawIO.Write("DISP:TEXT:DATA 'TEST'"); mbSession.RawIO.Write("DISP:TEXT:STAT ON"); DateTime dateTimeStart; DateTime dateTimeEnd; dateTimeStart = DateTime.Now; //string readValue = await Task.Run(() => this.readValue(mbSession)); //Считывание значения через класс readValueBool(mbSession, prevChan); dateTimeEnd = DateTime.Now; timeToRead = dateTimeEnd - dateTimeStart; mbSession.RawIO.Write("DISP:TEXT:STAT OFF"); }
static void instrument_connect(ref ResourceManager resource_manager, ref MessageBasedSession instrument_control_object, string instrument_id_string, Int16 timeout) { /* * Purpose: Open an instance of an instrument object for remote communication and establish the communication attributes. * * Parameters: * resource_manager - The reference to the resource manager object created external to this function. It is passed in * by reference so that any internal attributes that are updated when using to connect to the * instrument are updated to the caller. * * instrument_control_object - The reference to the instrument object created external to this function. It is passed * in by reference so that it retains all values upon exiting this function, making it * consumable to all other calling functions. * * instrument_id_string - The instrument VISA resource string used to identify the equipment at the underlying driver * level. This string can be obtained per making a call to Find_Resources() VISA function and * extracted from the reported list. * * timeout - This is used to define the duration of wait time that will transpire with respect to VISA read/query calls * prior to an error being reported. * * Returns: * None * * Revisions: * 2019-06-04 JJB Initial revision. */ instrument_control_object = (MessageBasedSession)(resource_manager.Open(instrument_id_string, Ivi.Visa.AccessModes.None, 2000)); // Instrument ID String examples... // LAN -> TCPIP0::134.63.71.209::inst0::INSTR // USB -> USB0::0x05E6::0x2450::01419962::INSTR // GPIB -> GPIB0::16::INSTR // Serial -> ASRL4::INSTR instrument_control_object.Clear(); instrument_control_object.TimeoutMilliseconds = timeout; if (instrument_id_string.Contains("ASRL")) { instrument_control_object.TerminationCharacterEnabled = true; instrument_control_object.TerminationCharacter = 0x0A; } else if (instrument_id_string.Contains("SOCKET")) { instrument_control_object.TerminationCharacterEnabled = true; instrument_control_object.TerminationCharacter = 0x0A; } return; }
private void Connect() { try { if (!_connected) { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(_visaAddress); _connected = true; } } catch (Exception e) { throw new VnaException("Connect N5224A fail via Visa Command", e); } }
public bool XStageConnect(string port) { try { Connector = (MessageBasedSession)ResourceManager.GetLocalManager().Open("COM" + port); //Connector = (MessageBasedSession)ResourceManager.GetLocalManager().Open("ASRL5::INSTR"); Connector.Timeout = 5000; } catch (Exception e) { Console.WriteLine(e.Message); return(false); } return(true); }
/// <summary> /// This task will use the MessageBasedSession passed in. This task can either the MessageBasedSession or leave it open for the caller to close. /// </summary> /// <param name="session">MessageBasedSession used by this task.</param> /// <param name="taskHandlesSessionLifetime">If true, the task will close session when the task is disposed. If false, the caller is responsible for closing session.</param> public BK2831E_2_INIT(MessageBasedSession session, bool taskHandlesSessionLifetime) { if (session == null) { throw new ArgumentNullException("session"); } _instrumentSession = session; _instrumentSession.Timeout = 2000; _instrumentSession.TerminationCharacterEnabled = false; _instrumentSession.TerminationCharacter = 0; // The caller can control the VISA session lifetime by passing in false for taskHandlesSessionLifetime. If taskHandlesSessionLifetime // is true, then the VISA session will be closed when the caller disposes this task. _handleSessionLifetime = taskHandlesSessionLifetime; }
public override ERROR_CODES ConnectToDevice() { ERROR_CODES status = ERROR_CODES.AA_OK; UpdateErrorBuffers("", ""); try { msgbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(DeviceID); msgbSession.DefaultBufferSize = 128000; } catch (Exception e) { status = ERROR_CODES.INSTRUMENT_CONNECTION_FAILED; UpdateErrorBuffers(e.Message, String.Format("Failed to connect to device {0}.", ModelName)); } return status; }
private void initButton_Click(object sender, EventArgs e) { try { mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(sessionListBox.Text); } catch (InvalidCastException) { MessageBox.Show("Resource selected must be a message-based session"); } catch (Exception exp) { MessageBox.Show(exp.Message); } finally { Cursor.Current = Cursors.Default; } }
internal void Connect() { try { ResourceManager manager = ResourceManager.GetLocalManager(); m_session = (MessageBasedSession)manager.Open(ResourceName); } catch (ArgumentException ex) { throw new SBJException("Error occured while trying to connect to instrument", ex); } catch (VisaException ex) { throw new SBJException("Error occured while trying to connect to instrument", ex); } catch (DllNotFoundException ex) { throw new SBJException("Error occured while trying to connect to instrument", ex); } catch (EntryPointNotFoundException ex) { throw new SBJException("Error occured while trying to connect to instrument", ex); } }
/// <summary> /// Initialize the VISA communication /// </summary> /// <param name="resourceName">VISA resource name</param> public virtual void initVISASession(string resourceName,bool developmentMode=false) { if (developmentMode == false) { try { VISAResourceName = resourceName; deviceSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resourceName); sessionCommType = commType.VISA; sessionInitialised = true; } catch (InvalidCastException) { Debug.WriteLine("Resource selected must be a message-based session"); sessionInitialised = false; sessionCommType = commType.none; } catch (Exception exp) { Debug.WriteLine(exp.Message); System.Windows.Forms.MessageBox.Show(VISAResourceName + " initialization fails"); System.Windows.Forms.MessageBox.Show(exp.Message); sessionInitialised = false; sessionCommType = commType.none; } finally { //Cursor.Current = Cursors.Default; } } else { sessionInitialised = false; sessionCommType = commType.none; } }
public bool SCPIconnect() { if (scpitalker == null) { try { scpitalker = new MessageBasedSession("TCPIP::" + signalIP); functiongenerator = new SCPI(scpitalker); } catch (System.ArgumentException) { if (Global.AskError("Check your signal generator connection settings") == DialogResult.Retry) SCPIconnect(); } } return scpitalker != null; }
public Arb_33522A_USB(string VISA_Address_String) { AWG_33522A_USB = (MessageBasedSession)ResourceManager.GetLocalManager().Open(VISA_Address_String); }
private bool WaitDevRdy(int waitTime) { int i = 0; while (afg3022Session == null || deviceList.Count == 0) { Thread.Sleep(100); if (GetDevDescList() != null && deviceList.Count != 0) { afg3022Session = (MessageBasedSession)ResourceManager.GetLocalManager().Open(deviceList[0]); } if (i > waitTime) { return false; } i++; } return true; }
public VisaDevice(string resourceString) { VisaID = resourceString; mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resourceString); mbSession.Timeout = int.MaxValue; }
public override ERROR_CODES DisconnectFromDevice() { UpdateErrorBuffers("", ""); if (IsOpen) { msgbSession.Dispose(); msgbSession = null; } return ERROR_CODES.AA_OK; }
public VISA(string VISA_Address_String) { if (is_Init) { throw new Exception(); } try { myVISA = (MessageBasedSession)ResourceManager.GetLocalManager().Open(VISA_Address_String); is_Init = true; } catch (Exception e) { strErr = e.Message.ToString(); } }