Ejemplo n.º 1
0
 public override bool DeInit()
 {
     if (comPort != null)
     {
         comPort.Close();
         comPort.Dispose();
     }
     if (session != null)
     {
         session.Clear();
     }
     return(true);
 }
Ejemplo n.º 2
0
 public void Disconnect()
 {
     try
     {
         session.DisableEvent(EventType.AllEnabled);
         session.Clear();
         io      = null;
         session = null;
     }
     catch (Exception exception)
     {
         throw CreateThrowUpException(exception);
     }
 }
Ejemplo n.º 3
0
        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;
        }
Ejemplo n.º 4
0
        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);
        }
Ejemplo n.º 5
0
        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;
        }
Ejemplo n.º 6
0
 /*--------------Device Clear Operation-----------------update 12/05/2015---------------------------*/
 public void ClearCommand()
 {
     mbSession.Clear();
 }