Exemplo n.º 1
0
        private void ImageGrabber_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Style = ProgressBarStyle.Continuous;
            toolStripProgressBar1.Value = 0;

            if (e.Result == null)
            {
                FailCount++;
                if (FailCount > 5)
                {
                    SetupControlState(false);
                    lock (mbSession)
                    {
                        mbSession.Dispose();
                    }
                    SetMessage("Disconnected!");
                    MessageBox.Show("There was a problem while grabbbing an image, please reconnect to the Scope");
                }
                return;
            }
            PictureBox pb = (e.Result as PictureBox);

            if (pb.Image != null)
            {
                pb.Image.Dispose();
            }
            pb.Image  = model;
            FailCount = 0;
            SetMessage("Connected to " + textBox1.Text);
        }
Exemplo n.º 2
0
        //---- Helper DMM property
        // --- properties

        // +++ Constructors
        /// <summary>
        /// Starts a new scope instance but does not attempt to open the scope for use.
        /// <para>Call OpenScope to start communications.</para>
        /// </summary>
        //     public static TekScope()
        //    {

        //  assignDMMchannels();
        //         OpenScope(scopeName);
        //     }

        /// <summary>
        /// Starts a new scope instance and attempts to open the scope for use.
        /// <para>If connection is a success then OnConnectedStateChanged will assert with arg isConnected = true;</para>
        /// <para>Otherwise, isConnected may be tested for connection state.</para>
        /// </summary>
        /// <param name="scopeName">A nickname for this scope instance</param>
        /// <param name="lastResourceString">Optional. If blank, a dialog will allow the user to select a scope from the available scope resources.
        /// <para>if used, this is a tektronix scope resource string identifying a specific scope that is known to be connected.</para>
        /// </param>

        /*    public TekScope(string scopeName, string lastResourceString = null)
         *  {
         *      //  assignDMMchannels();
         *      OpenScope(scopeName, lastResourceString);
         *  }*/
        // --- Constructors

        public static void Dispose()
        {
            if (mbSession != null)
            {
                mbSession.Dispose();
            }
        }
Exemplo n.º 3
0
 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     serial.Close();
     if (mbSession != null && !mbSession.IsDisposed)
     {
         mbSession.Dispose();
     }
     this.Dispose();
 }
Exemplo n.º 4
0
        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;
            }
        }
        // ============================================================================================================

        private void disconnectVna()
        {
            // is there a connection to the vna?
            if (isVnaConnected == true)
            {
                // yes...
                visaMessageBasedSession.Dispose();

                // update vna connected flag
                isVnaConnected = false;

                // log the event
                appendToTextBoxLog("Disconnected from VNA" + Environment.NewLine);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Clean up any resources being used.
 /// </summary>
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (mbSession != null)
         {
             mbSession.Dispose();
         }
         if (components != null)
         {
             components.Dispose();
         }
     }
     base.Dispose(disposing);
 }
Exemplo n.º 7
0
        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;
        }
Exemplo n.º 8
0
 /// <summary>
 /// 释放会话
 /// </summary>
 public void Release()
 {
     if (mbSession != null)
     {
         mbSession.Dispose();
     }
 }
Exemplo n.º 9
0
 public int CloseSession()
 {
     if (m_connectType == 1)
     {
         try
         {
             mbSession.Terminate();
             mbSession.Dispose();
         }
         catch (Exception)
         {
             return(-1);
         }
         bsessionopen     = false;
         m_ConnectManager = null;
     }
     else if (m_connectType == 0)
     {
         bsessionopen = false;
         try
         {
             m_SerialPort.Close();
         }
         catch (Exception)
         {
             return(-1);
         }
         m_SerialPort = null;
     }
     return(0);
 }
Exemplo n.º 10
0
 private void frmMain_Load(object sender, EventArgs e)
 {
     if (TekScope != null)
     {
         TekScope.Dispose();
         TekScope = null;
     }
 }
Exemplo n.º 11
0
 public bool XstageRelease()
 {
     if (Connector != null)
     {
         Connector.Dispose();
         return(true);
     }
     return(false);
 }
Exemplo n.º 12
0
        public bool Close()
        {
            if (session == null)
            {
                return(true);
            }

            session.Dispose();
            return(session.IsDisposed);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Close the session (if opened)
 /// </summary>
 public void close()
 {
     lock (mbSession) {
         if (mbSession != null)
         {
             mbSession.Dispose();
             mbSession = null;
         }
     }
 }
        public void Dispose()
        {
            lock (disposeLocker)
            {
                if (mbSession != null)
                {
                    mbSession.Dispose();
                }

                GC.Collect();
            }
        }
Exemplo n.º 15
0
 public bool Close()
 {
     try {
         if (mbSession != null)
         {
             mbSession.Dispose();
         }
         return(true);
     }
     catch {
         return(false);
     }
 }
Exemplo n.º 16
0
 public bool RstageRelease( )
 {
     try
     {
         //connect.CloseSession();
         connect.Dispose();
         return(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         return(false);
     }
 }
Exemplo n.º 17
0
        private void closeMySession()
        {
            if (mbSession == null)
            {
                return;
            }

            // Toggle the hardware GPIB REN line. Return to Local.
            GpibSession gpib = (GpibSession)mySession;

            gpib.ControlRen(RenMode.DeassertAfterGtl);

            //Close the Session
            mbSession.Dispose();
            mbSession = null;
        }
Exemplo n.º 18
0
        private void button1_Click(object sender, EventArgs e)
        {
            // example waveform: sine wave using 12 sample points, integers between 0 to
            // 16382 (range of AFG).  hex notation is easier to verify later
            // (note: max value of afg3000 is '3FFE' not '3FFF')

            int[]    hexArray = { 0x2000, 0x2FFF, 0x3BB6, 0x3FFE, 0x3BB6, 0x2FFF, 0x2000, 0x1000, 0x0449, 0x0000, 0x0449, 0x1000 };
            string[] hexStr1  = new string[hexArray.Length];
            string[] hexStr2  = new string[hexArray.Length * 2];


            // pre-processing
            // encode variable 'wave' into binary waveform data for AFG.  This is
            // the same as AWG5000B but marker bits are ignored.  see AWG5000B series
            // programmer manual for bit definitions.
            for (int i = 0; i < hexArray.Length; i++)
            {
                hexStr1[i]           = hexArray[i].ToString("X4");
                hexStr2[2 * i]       = hexStr1[i].Substring(0, 2);
                hexStr2[(2 * i) + 1] = hexStr1[i].Substring(2, 2);
            }
            byte[] Str2Byt = hexStr2.Select(s => Convert.ToByte(s, 16)).ToArray();
            string EnCdStr = System.Text.Encoding.ASCII.GetString(Str2Byt);


            // build binary block header
            int    bytes  = Str2Byt.Length;
            string header = "#" + Convert.ToString(Convert.ToString(bytes).Length) + Convert.ToString(bytes);


            //Open connection to instrument
            mbSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resourceString);
            mbSession.Write("*RST");
            mbSession.Write("*CLS");
            mbSession.Write("DATA:DEFine EMEMory, " + hexArray.Length.ToString());
            mbSession.Write("DATA EMEMory," + header + EnCdStr);
            mbSession.Write("SOURce1:FUNCtion EMEMory");
            mbSession.Write("OUTPut1 ON");


            //Close instrument connection
            mbSession.Dispose();
        }
Exemplo n.º 19
0
 static void instrument_disconnect(ref MessageBasedSession instrument_control_object)
 {
     /*
      *  Purpose: Closes an instance of and instrument object previously opened for remote communication.
      *
      *  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.
      *
      *  Returns:
      *      None
      *
      *  Revisions:
      *      2019-06-04      JJB     Initial revision.
      */
     instrument_control_object.Dispose();
     return;
 }
Exemplo n.º 20
0
 public bool RStageConnect(string port)
 {
     try
     {
         connect = (MessageBasedSession)ResourceManager.GetLocalManager().Open("COM" + port);
         connect.SetAttributeInt32(NationalInstruments.VisaNS.AttributeType.AsrlBaud, 38400);
         connect.Timeout = 1000;
         Thread.Sleep(100);
         connect.Dispose();
         connect = (MessageBasedSession)ResourceManager.GetLocalManager().Open("COM" + port);
         connect.SetAttributeInt32(NationalInstruments.VisaNS.AttributeType.AsrlBaud, 38400);
         connect.Timeout = 1000;
         //connect = new SerialCom();
         //connect.OpenSession( port );
         return(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         return(false);
     }
 }
Exemplo n.º 21
0
 /*----------------------------------------------------------*/
 /*----------------------------------------------------------*/
 public void Close()
 {
     mbSession.Dispose();
 }
Exemplo n.º 22
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;
        }
Exemplo n.º 23
0
        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("Нарушение инструкции измерений, повторите попытку поверки по уровню шумов еще раз", "Внимание");
            }
        }
Exemplo n.º 24
0
        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("Нарушение инструкции измерений, повторите попытку поверки по частоте еще раз", "Внимание");
            }
        }
 /**
  * closes the instrument
  * */
 override public void closeInstrument()
 {
     mbSession.Dispose();
 }
Exemplo n.º 26
0
 public void close()
 {
     mSession.Dispose();
 }
Exemplo n.º 27
0
 public void Close()
 {
     session.Dispose();
 }