Exemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                using (var res = GlobalResourceManager.Open("TCPIP:localhost::inst0::INSTR"))
                {
                    if (res is IMessageBasedFormattedIO session)
                    {
                        session.WriteLine("*IDN?");
                        var idn = session.ReadLine();
                        Console.WriteLine("Connected to {0}", idn);
                    }
                }
            }
            catch (TypeInitializationException ex)
            {
                if (ex.InnerException != null && ex.InnerException is DllNotFoundException)
                {
                    var VisaNetSharedComponentsVersion = typeof(GlobalResourceManager).Assembly.GetName().Version.ToString();
                    Console.WriteLine("VISA implementation compatible with VISA.NET Shared Components {0} not found. Please install corresponding vendor-specific VISA implementation first.", VisaNetSharedComponentsVersion);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // suppress DllNotFoundException exception in Ivi.Visa dispose
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            // Change this variable to the address of your instrument
            string VISA_ADDRESS = "Your instrument's VISA address goes here!";

            // Create a connection (session) to the RS-232 device.
            // Change VISA_ADDRESS to a serial address, e.g. "ASRL1::INSTR"
            IMessageBasedSession session = GlobalResourceManager.Open(VISA_ADDRESS) as IMessageBasedSession;

            // The first thing you should do with a serial port is enable the Termination Character. Otherwise all of your read's will fail
            session.TerminationCharacterEnabled = true;

            // If you've setup the serial port settings in Connection Expert, you can remove this section.
            // Otherwise, set your connection parameters
            ISerialSession serial = session as ISerialSession;

            serial.BaudRate    = 9600;
            serial.DataBits    = 8;
            serial.Parity      = SerialParity.None;
            serial.FlowControl = SerialFlowControlModes.DtrDsr;

            // Send the *IDN? and read the response as strings
            MessageBasedFormattedIO formattedIO = new MessageBasedFormattedIO(session);

            formattedIO.WriteLine("*IDN?");
            string idnResponse = formattedIO.ReadLine();

            Console.WriteLine("*IDN? returned: {0}", idnResponse);

            // Close the connection to the instrument
            session.Dispose();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 3
0
        private void button3_Click(object sender, EventArgs e)
        {
            string VISA_ADDRESS = listBox1.GetItemText(listBox1.SelectedItem);
            // Create a connection (session) to the instrument
            IMessageBasedSession session;

            session = GlobalResourceManager.Open(VISA_ADDRESS) as IMessageBasedSession;

            // Create a formatted I/O object which will help us format the data we want to send/receive to/from the instrument
            MessageBasedFormattedIO formattedIO = new MessageBasedFormattedIO(session);

            // For Serial and TCP/IP socket connections enable the read Termination Character, or read's will timeout
            if (session.ResourceName.Contains("ASRL") || session.ResourceName.Contains("SOCKET"))
            {
                session.TerminationCharacterEnabled = true;
            }

            formattedIO.WriteLine(":SYSTem:SECurity:ERASeall");
            formattedIO.WriteLine(":SYSTem:SECurity:SANitize");
            formattedIO.WriteLine(":SYSTem:FILesystem:STORage:FSDCard ON|OFF|1|0");
            formattedIO.WriteLine(":SYSTem:PRESet: PERSistent");
            formattedIO.WriteLine(":SYSTem:COMMunicate:LAN:DEFaults");
            formattedIO.WriteLine(":CAL:IQ:DEF");
            session.Dispose();
            MessageBox.Show("Очистка заврешена");
        }
Exemplo n.º 4
0
 protected VISADevice(string visaID)
 {
     this.visaID        = visaID;                                                          // set this visaID to the parameter visaID
     threadLock         = new object();                                                    // each device needs its own locking object.
     manualResetEventIO = new ManualResetEvent(false);                                     // init the manualResetEvent
     mbSession          = GlobalResourceManager.Open(this.visaID) as IMessageBasedSession; // open the message session between the computer and the device.
 }
Exemplo n.º 5
0
        public static string ReadCalibration(string addr)
        {
            string calStr = "";

            using (IGpibSession dev = GlobalResourceManager.Open(addr) as IGpibSession) {
                dev.Clear();
                //dev.RawIO.Write("H0");
                //dev.ReadStatusByte();
                //List<byte> vals = new List<byte>();
                for (int i = 0; i < 256; i++)
                {
                    dev.RawIO.Write(new byte[] { 0x57, (byte)i }); // 0x57 is 'W' in hex
                    calStr = calStr + dev.RawIO.ReadString();
                    if (i % 32 == 31)
                    {
                        calStr = calStr + System.Environment.NewLine;
                    }

                    /*byte[] x = dev.RawIO.Read();
                     * x[0] = (byte)((int)x[0] - 64);
                     * vals.Add(x[0]);*/
                }
            }
            return(calStr);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            // Change this variable to the address of your instrument
            string VISA_ADDRESS = "Your instrument's VISA address goes here!";

            // Create a connection (session) to the TCP/IP socket on the instrument.
            // Change VISA_ADDRESS to a SOCKET address, e.g. "TCPIP::169.254.104.59::5025::SOCKET"
            IMessageBasedSession session = GlobalResourceManager.Open(VISA_ADDRESS) as IMessageBasedSession;

            // The first thing you should do with a SOCKET connection is enable the Termination Character. Otherwise all of your read's will fail
            session.TerminationCharacterEnabled = true;

            // We can find out details of the connection
            ITcpipSocketSession socket = session as ITcpipSocketSession;

            Console.WriteLine("IP: {0}\r\nHostname: {1}\r\nPort: {2}\r\n",
                              socket.Address,
                              socket.HostName,
                              socket.Port);

            // Send the *IDN? and read the response as strings
            MessageBasedFormattedIO formattedIO = new MessageBasedFormattedIO(session);

            formattedIO.WriteLine("*IDN?");
            string idnResponse = formattedIO.ReadLine();

            Console.WriteLine("*IDN? returned: {0}", idnResponse);

            // Close the connection to the instrument
            session.Dispose();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 7
0
 /// <summary>
 /// 使用lvi.Visa库中的类打开与设备的会话(方式1)
 /// </summary>
 /// <param name="resourceName">资源名称,例如"TCPIP0::192.168.0.10::inst0::INSTR"</param>
 private void connectDevice(string resourceName)
 {
     try
     {
         ITcpipSession session = (ITcpipSession)GlobalResourceManager.Open(resourceName);
         ibfIo = session.FormattedIO;
         ShowMsg("*[" + DateTime.Now.ToString() + "] " + "Connect to the device successfully!:lvi.Visa.");
     }
     catch
     {
         lbxReception.Items.Add("*[" + DateTime.Now.ToString() + "] " + "Can't connect to the device!:lvi.Visa.");
     }
 }
Exemplo n.º 8
0
        private void GetVisaChecked(string visa_addr)
        {
            IMessageBasedSession session;

            try
            {
                session           = GlobalResourceManager.Open(visa_addr) as IMessageBasedSession;
                richTextBox1.Text = "Соединение установлено";
            }
            catch (NativeVisaException visaException)
            {
                richTextBox1.Text = "Соединение не установлено";
            }
        }
Exemplo n.º 9
0
 private bool openGPIB()
 {
     try
     {
         session     = GlobalResourceManager.Open(VISA_ADDRESS, AccessModes.None, 5) as IMessageBasedSession;
         formattedIO = new MessageBasedFormattedIO(session);
         MessageBox.Show("The instrument has been successfully connected on GPIB0::25", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
         return(true);
     }
     catch (NativeVisaException visaException)
     {
         //Shell.WriteLine("Error is:\r\n{0}\r\nPress any key to exit...", visaException);
         MessageBox.Show("Please check GPIB conncetion. GPIB port of the instrument should be set as GPIB0::25", "Error: Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return(false);
     }
 }
Exemplo n.º 10
0
 private bool openGPIB()
 {
     try
     {
         sessionLRC         = GlobalResourceManager.Open(LRC_VISA_ADDRESS, AccessModes.None, 50000) as IMessageBasedSession;
         formattedIOLRC     = new MessageBasedFormattedIO(sessionLRC);
         sessionTEMPCON     = GlobalResourceManager.Open(TEMPCON_VISA_ADDRESS, AccessModes.None, 50000) as IMessageBasedSession;
         formattedIOTEMPCON = new MessageBasedFormattedIO(sessionTEMPCON);
         MessageBox.Show("The instruments have been successfully connected on GPIB0::25 and GPIB0::12", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
         return(true);
     }
     catch (NativeVisaException visaException)
     {
         MessageBox.Show("Failed to connect at least one instrument. Please check GPIB conncetion. GPIB port of the LRC Meter and Temperature Controller should be set as GPIB0::25 and GPIB0::12 respectively.", "Error: Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return(false);
     }
 }
Exemplo n.º 11
0
 // attempts to open a VISA resource given the VISA identifier, returns null if the resource does not exist or cannot be opened.
 protected static T TryOpen <T>(string visaID) where T : VISADevice, ITestAndMeasurement
 {
     try
     {
         IMessageBasedSession searcherMBS = GlobalResourceManager.Open(visaID) as IMessageBasedSession; // attempt to open the message session
         searcherMBS.FormattedIO.WriteLine("*IDN?");                                                    // All SCPI compliant devices (and therefore all VISA devices) are required to respon to *IDN?
         string   IDNResponse        = searcherMBS.FormattedIO.ReadLine();
         string[] tokens             = IDNResponse.Split(',');                                          // hopefully this isn't too slow
         string   formattedIDNString = tokens[1];                                                       // we run the IDN command on all connected devices
         T        temp = GetDeviceFromModelString <T>(formattedIDNString, visaID);
         return(temp);
     }
     catch (VisaException)
     {
         return(null);  // if there is an error in the constructor, return null.
         // Yes I know exception handling is expensive and should not be used for control flow purposes, but the VISA functions throw an error instead of returning
         // null or something when a device cannot be opened.
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// Returns a ConnectedDevicestruct that contains information about the VISA devices of device type DeviceType.* connected to the system.
        /// Only devices that can be located by a VISA
        /// library can be found by this function, e.g. something connected using raw sockets over LAN won't work.
        /// NOT THREAD SAFE. This is best used before any regular I/O transfer has started in your program.
        /// </summary>
        /// <remarks>Look at ConnectedDeviceStruct documentation for additional info.</remarks>
        /// <returns>a ConnectedDeviceStruct, containing information about connected Devices of the passed in device type</returns>
        /// <exception cref="System.Runtime.InteropServices.ExternalException">Thrown if the program cannot locate a valid
        /// VISA implementation on the system. There are no checked exceptions in C# but please,
        /// handle this one with a message in ANY application you build with this library.</exception>
        public static ConnectedDeviceStruct <T> GetConnectedDevices <T>() where T : VISADevice, ITestAndMeasurement
        {
            IEnumerable <string> resources;
            IMessageBasedSession searcherMBS;
            List <string>        connectedDeviceModels = new List <string>(); // get a list of connected VISA device model names
            List <string>        rawVISAIDs            = new List <string>(); // get a list of connect VISA devices' returned IDs
            List <T>             toReturn = new List <T>();
            bool unknownDeviceFound       = false;

            try
            {
                resources = GlobalResourceManager.Find("?*");                            // find all connected VISA devices
                foreach (string s in resources)                                          // after this loop, connectedDeviceModels contains a list of connected devices in the form <Model>
                {
                    rawVISAIDs.Add(s);                                                   // we need to add
                    string IDNResponse;
                    searcherMBS = GlobalResourceManager.Open(s) as IMessageBasedSession; // open the message session
                    searcherMBS.FormattedIO.WriteLine("*IDN?");                          // All SCPI compliant devices (and therefore all VISA devices) are required to respon to *IDN?
                    IDNResponse = searcherMBS.FormattedIO.ReadLine();
                    string[] tokens             = IDNResponse.Split(',');                // hopefully this isn't too slow
                    string   formattedIDNString = tokens[1];                             // we run the IDN command on all connected devices
                                                                                         // and then parse the response into the form <Model>
                    connectedDeviceModels.Add(formattedIDNString);
                }
                for (int i = 0; i < connectedDeviceModels.Count; i++)  // connectedDeviceModels.Count() == rawVISAIDs.Count()
                {
                    T temp = GetDeviceFromModelString <T>(connectedDeviceModels[i], rawVISAIDs[i]);
                    if (temp == null)
                    {
                        unknownDeviceFound = true;  // if there's one
                    }
                    else
                    {
                        toReturn.Add(temp);
                    }
                }
                return(new ConnectedDeviceStruct <T>(toReturn.ToArray(), unknownDeviceFound));
            }
            catch (VisaException)  // if no devices are found, return a struct with an array of size 0
            {
                return(new ConnectedDeviceStruct <T>(new T[0], false));
            }
        }
Exemplo n.º 13
0
        public static void WriteCalibration(string addr, string calString)
        {
            calString = Regex.Replace(calString, @"\s+", "");
            if (!IsValidCalString(calString))
            {
                throw new FormatException("Calibration string is not valid.");
            }

            using (IGpibSession dev = GlobalResourceManager.Open(addr) as IGpibSession) {
                dev.Clear();
                //dev.RawIO.Write("H0");
                //dev.ReadStatusByte();
                //List<byte> vals = new List<byte>();
                for (int i = 0; i < 256; i++)
                {
                    dev.RawIO.Write(new byte[] { (byte)'X', (byte)i, (byte)calString[i] });
                }
            }
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            // Change this variable to the address of your instrument
            string VISA_ADDRESS = "Your instrument's VISA address goes here!";

            // Create a connection (session) to the instrument
            IMessageBasedSession session;

            try
            {
                session = GlobalResourceManager.Open(VISA_ADDRESS) as IMessageBasedSession;
            }
            catch (NativeVisaException visaException)
            {
                Console.WriteLine("Couldn't connect. Error is:\r\n{0}\r\nPress any key to exit...", visaException);
                Console.ReadKey();
                return;
            }

            // Create a formatted I/O object which will help us format the data we want to send/receive to/from the instrument
            MessageBasedFormattedIO formattedIO = new MessageBasedFormattedIO(session);

            // For Serial and TCP/IP socket connections enable the read Termination Character, or read's will timeout
            if (session.ResourceName.Contains("ASRL") || session.ResourceName.Contains("SOCKET"))
            {
                session.TerminationCharacterEnabled = true;
            }

            // Send the *IDN? and read the response as strings
            formattedIO.WriteLine("*IDN?");
            string idnResponse = formattedIO.ReadLine();

            Console.WriteLine("*IDN? returned: {0}", idnResponse);

            // Close the connection to the instrument
            session.Dispose();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            try
            {
                var session = GlobalResourceManager.Open("TCPIP:localhost::inst0::INSTR") as IMessageBasedFormattedIO;
                session.WriteLine("*IDN?");
                var idn = session.ReadLine();
                Console.WriteLine(string.Format("Connected to {0}", idn));
            }
            catch (TypeInitializationException ex)
            {
                if (ex.InnerException != null && ex.InnerException is DllNotFoundException)
                {
                    Console.WriteLine("VISA implementation compatible with VISA.NET Shared Components {0} not found. Please install corresponding vendor-specific VISA implementation first.", GlobalResourceManager.ImplementationVersion);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            GetReadyToDie();
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            // Change this variable to the address of your instrument
            string VISA_ADDRESS = "Your instrument's VISA address goes here!";

            // Create a connection (session) to the PXI module
            // Change VISA_ADDRESS to a PXI address, e.g. "PXI0::23-0.0::INSTR"
            IPxiSession session = GlobalResourceManager.Open(VISA_ADDRESS) as IPxiSession;

            Console.WriteLine("Manufacturer: {0}\r\nModel: {1}\r\nChassis: {2}\r\nSlot: {3}\r\nBus-Device.Function: {4}-{5}.{6}\r\n",
                              session.ManufacturerName,
                              session.ModelName,
                              session.ChassisNumber,
                              session.Slot,
                              session.BusNumber,
                              session.DeviceNumber,
                              session.FunctionNumber);

            // Close the connection to the instrument
            session.Dispose();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Search for and then open a device.
        /// </summary>
        /// <remarks>
        /// By default, the first USB device found is opened.
        /// </remarks>
        /// <param name="pattern">string to match in resource names</param>
        /// <param name="index">which of the instruments matching the pattern to open</param>
        public void Open(string pattern = VisaPattern.USB, int index = 0)
        {
            try
            {
                // Find all available instruments.
                string[] resourceStrings = Find(pattern).ToArray();

                // Open a connection to the desired instrument.
                _instrument = GlobalResourceManager.Open(resourceStrings[index]) as IMessageBasedFormattedIO;
            }
            catch (EntryPointNotFoundException ex)
            {
                throw new DevicePortException("The IVI.VISA dll appears to be missing."
                                              + Environment.NewLine + "It must be installed as a separate package."
                                              + Environment.NewLine + "Details:"
                                              + Environment.NewLine + ex.Message);
            }
            catch (IndexOutOfRangeException ex)
            {
                throw new DeviceCommunicationException("Device was not found."
                                                       + Environment.NewLine + "Details:"
                                                       + Environment.NewLine + ex.Message);
            }
        }
        private void cmdStartTest_Click(object sender, EventArgs e)
        {
            System.DateTime CurveTime;
            float           wfmPerSec = 0;

            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            string       temp;
            bool         saveToDisk = cbxSaveToDisk.Checked;
            StreamWriter SaveFile   = null;

            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

            if (saveToDisk)
            {
                // 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 = GlobalResourceManager.Open(txtVisaResourceName.Text.Trim()) as IMessageBasedSession;
                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.FormattedIO.WriteLine("*CLS");
            TekScope.FormattedIO.WriteLine("*CLE");
            TekScope.FormattedIO.WriteLine("DATa:SOUrce CH1");
            TekScope.FormattedIO.WriteLine("DATa:ENCdg RIBinary");
            TekScope.FormattedIO.WriteLine("DATa:STARt 0");
            TekScope.FormattedIO.WriteLine("HORizontal:ACQLENGTH?");
            temp      = TekScope.RawIO.ReadString().Trim();
            AcqLength = Int32.Parse(temp);
            TekScope.FormattedIO.WriteLine(String.Format("DATa:STOP {0}", AcqLength));
            TekScope.FormattedIO.WriteLine("WFMOutpre:ENCdg BINary");
            TekScope.FormattedIO.WriteLine("WFMOutpre:BYT_Nr 1");

            // Get the needed values from the scope to scale the data
            TekScope.FormattedIO.WriteLine("WFMOutpre:PT_Off?");
            temp   = TekScope.RawIO.ReadString().Trim();
            pt_off = Int32.Parse(temp);
            TekScope.FormattedIO.WriteLine("WFMOutpre:XINcr?");
            temp = TekScope.RawIO.ReadString().Trim();
            xinc = Single.Parse(temp);
            TekScope.FormattedIO.WriteLine("WFMOutpre:XZEro?");
            temp  = TekScope.RawIO.ReadString().Trim();
            xzero = Single.Parse(temp);
            TekScope.FormattedIO.WriteLine("WFMOutpre:YMUlt?");
            temp  = TekScope.RawIO.ReadString().Trim();
            ymult = Single.Parse(temp);
            TekScope.FormattedIO.WriteLine("WFMOutpre:YOFf?");
            temp = TekScope.RawIO.ReadString().Trim().TrimEnd('0').TrimEnd('.');
            yoff = Single.Parse(temp);
            TekScope.FormattedIO.WriteLine("WFMOutpre:YZEro?");
            temp  = TekScope.RawIO.ReadString().Trim();
            yzero = Single.Parse(temp);

            // Turn on curve streaming
            TekScope.FormattedIO.WriteLine("CURVEStream?");
            stopWatch.Reset();
            stopWatch.Start();

            // While still collecting curves.  Ends when the user clicks End Test
            while (GatherCurves)
            {
                int    NumBytesCharCount = 0;
                string BlockHeader       = "";

                TekScope.TimeoutMilliseconds = 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.RawIO.ReadString(2);

                        if (BlockHeader == ";\n") // Then it's the terminator from the previous curve so throw it out and try again.
                        {
                            BlockHeader = "";
                        }
                    }
                    catch (IOTimeoutException)
                    {
                    }
                    catch (Exception ex)
                    {
                        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;
                }

                if (saveToDisk)
                {
                    // Create a file with the current date and time as the name
                    CurveTime = 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);
                    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.RawIO.ReadString(NumBytesCharCount);
                DataLength     = int.Parse(temp);
                BytesRemaining = DataLength;

                // Read the back the data, process it and save it to the file
                TekScope.TimeoutMilliseconds = 5000;
                while (BytesRemaining > 0)
                {
                    // Read bytes from scope
                    if (BytesRemaining >= BUFFER_SIZE)
                    {
                        //DataBuffer = TekScope.ReadByteArray(BUFFER_SIZE);
                        DataBuffer      = TekScope.RawIO.Read(BUFFER_SIZE);
                        BytesRemaining -= BUFFER_SIZE;
                    }
                    else
                    {
                        DataBuffer     = TekScope.RawIO.Read(BytesRemaining);
                        BytesRemaining = 0;
                    }

                    // Convert byte values to floating point values then write to .csv file
                    foreach (byte DataPoint in DataBuffer)
                    {
                        yvalue = ((Convert.ToSingle((sbyte)DataPoint) - yoff) * ymult) + yzero;
                        if (saveToDisk)
                        {
                            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;
                    }
                }

                if (saveToDisk)
                {
                    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;
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            // Change this variable to the address of your instrument
            string VISA_ADDRESS = "Your instrument's VISA address goes here!";

            IMessageBasedSession    session = null;
            MessageBasedFormattedIO formattedIO;

            // Part 1:
            //
            // Shows the mechanics of how to catch an exception (an error) in VISA.NET when it occurs.
            // To stimulate an error, the code will try to open a connection t an instrument at an invalid address...
            try
            {
                // First we'll provide an invalid address and see what error we get
                session = GlobalResourceManager.Open("BAD ADDRESS") as IMessageBasedSession;
            }
            catch (Exception ex)
            {
                Console.WriteLine("An exception has occurred!\r\n\r\n{0}\r\n", ex.ToString());

                // To get more specific information about the exception, we can check what kind of exception it is and add specific error handling code
                // In this example, that is done in the ExceptionHandler method
                ExceptionHandler(ex);
            }

            // Part 2:
            //
            // Stimulate another error by sending an invalid query and trying to read its response.
            //
            // Before running this part, don't forget to set your instrument address in the 'VISA_ADDRESS' variable at the top of this method
            session     = GlobalResourceManager.Open(VISA_ADDRESS) as IMessageBasedSession;
            formattedIO = new MessageBasedFormattedIO(session);

            // Misspell the *IDN? query as *IND?
            try
            {
                formattedIO.WriteLine("*IND?");
            }
            catch (Exception ex)
            {
                Console.WriteLine("You'll never get here, because the *IND? data will get sent to the instrument successfully, it's the instrument that won't like it.");
            }

            // Try to read the response (*IND ?)
            try
            {
                string idnResponse = formattedIO.ReadLine();

                Console.WriteLine("*IDN? returned: {0}", idnResponse);
            }
            catch (IOTimeoutException timeoutException)
            {
                Console.WriteLine("The ReadLine call will timeout, because the instrument doesn't know what to do with the command that we sent it.");

                // Check the instrument to see if it has any errors in its queue
                string rawError    = "";
                int    errorCode   = -1;
                string errorString = "";

                while (errorCode != 0)
                {
                    formattedIO.WriteLine("SYST:ERR?");
                    rawError    = formattedIO.ReadLine();
                    errorCode   = int.Parse(rawError.Split(',')[0]);
                    errorString = rawError.Split(',')[1];

                    Console.WriteLine("Error code: {0}, error message: {1}", errorCode, errorString.Trim());
                }
            }

            session.Dispose();

            Console.WriteLine("\r\nPress any key to exit...");
            Console.ReadKey();
        }