C# Example Program

The following C# example demonstrates how to send SCPI commands to the FieldFox using a TCP socket connection over a LAN connection.

Note: You can also send single SCPI commands to the FieldFox using this free Instrument Console program.

Requirements

To connect to the FieldFox and run SCPI programs, you must first download and install the Visual C# Express software from: http://www.microsoft.com/express/download/

Once the program is installed, search the PC hard drive for csc.exe. This file could be in the C:\Windows\Microsoft.NET directory.

NOTE: If more than one folder contains csc.exe, use the folder with the latest revision.

Write the SCPI program

The following procedure uses the example filename MyProgram.cs. You can use any filename that you like.

  1. Copy the text in the shaded are below into a Notepad file and name it MyProgram.cs.

  2. Write your SCPI program between the //Start your program here and //End your program here lines. Several example lines are provided to demonstrate the syntax in which the SCPI commands must be contained. See the SCPI Command Reference and Program Examples for more information.

Run the SCPI Program

Record the dynamically-assigned IP address of the FieldFox.

  1. Shut down the FieldFox.

  2. Connect the FieldFox to the Internet using a LAN connection.

  3. Power ON the FieldFox.

  4. On the FieldFox, press System, then System Configuration, then LAN.

  5. Record the Current IP Address

  6. Compile your program by executing csc.exe MyProgram.cs. This creates a file named MyProgram.exe in the same directory as csc.exe.

  7. Run your SCPI program by executing MyProgram.exe <FieldFox IP Address>. For example: MyProgram.exe 192.121.1.101

To make this process more convenient:

The following steps show how to create shortcuts on your PC desktop to compile and run MyProgram.exe.

  1. Using Windows Explorer, navigate to the folder that contains csc.exe. NOTE: If more than one folder contains csc.exe, use the folder with the latest revision.

  2. Right-click csc.exe then click Create Shortcut.

  3. Drag the shortcut file to the PC desktop.

  4. Right-click on the desktop shortcut, then click Properties.

  5. Append a space, the full path, and filename to the end of the "Target” as in the following image. This example shows MyProgram.cs is saved to the C:\ folder.

  1. After performing a compile, perform the same ‘shortcut’ procedure for MyProgram.exe except, instead of appending the path and filename, append the IP address of the FieldFox.

 

Copy the text in the following shaded area to a Notepad file.

using System;

using System.Collections.Generic;

using System.Text;

using System.Net.Sockets;

using System.IO;

namespace Network.Connect

{

    class Program

    {

        static TelnetConnection tc;

        static int Main(string[] args)

        {

            // defaultHostName is host name to use if one is not specified on the command line.

            string defaultHostName = "192.168.1.1";

            string hostName = defaultHostName;

            if( args.Length == 1 )

            {

                // If command line contains a '?' character, interpret this as help.

                if( args[0].Contains("?"))

                {

                    Console.WriteLine("Usage: N9912A_CS_Example.exe <hostName>\n\n"+

                        "Where optional hostName is an ip address or host name.\n" +

                        "If no hostName is supplied, the default ("+defaultHostName+") is used.\n\n"+

                        "e.g. N9912A_CS_Example.exe 10.10.1.1\n\nor\n\n" +

                        "N9912A_CS_Example.exe A-N9912A-22762");

                    return 0; // exit.

                }

                // Record hostname passed in on command line.

                hostName = args[0];

            }

            try

            {

                tc = new TelnetConnection();

                tc.ReadTimeout = 10000; // 10 sec

                // open socket on hostName, which can be an IP address, or use host name (e.g. "A-N9912A-22762") used in lieu of IP

address

                tc.Open(hostName);

                if( tc.IsOpen )

                {

                    //Start your program here

                    Write("SYST:PRES;*OPC?");

                    Write("*IDN?");

                    Write("SENS:FREQ:STAR?");

                    Write("SENS:FREQ:STAR 3e9");

                    Write("SENS:FREQ:STAR?");

                    Write("SYST:ERR?");

                    Write("SYST:HELP:HEAD?");

                    //End your program here

                    tc.Dispose();

                    Console.WriteLine("Press any key to exit.");

                    Console.ReadKey(); // continue after reading a key from the keyboard.

                }

                else

                {

                    Console.WriteLine("Error opening " + hostName);

                    return -1;

                }

                //FieldFox Programming Guide 5

            }

            catch(Exception e)

            {

                Console.WriteLine(e.ToString());

                return -1;

            }

            // exit normally.

            return 0;

        }

        /// <summary>

        /// Write a SCPI command to the telnet connection.

        /// If the command has a '?', then read back the response and print

        /// it to the Console.

        /// </summary>

        /// <remarks>

        /// Note the '?' detection is naive, as a ? could occur in the middle

        /// of a SCPI string argument, and not actually signify a SCPI query.

        /// </remarks>

        /// <param name="s"></param>

        static void Write(string s)

        {

            Console.WriteLine(s);

            tc.WriteLine(s);

            if (s.IndexOf('?') >= 0)

                Read();

        }

        /// <summary>

        /// Read the telnet connection for a response, and print the response to the

        /// Console.

        /// </summary>

        static void Read()

        {

            Console.WriteLine(tc.Read());

        }

    }

#region TelnetConnection - no need to edit

    /// <summary>

    /// Telnet Connection on port 5025 to an instrument

    /// </summary>

    public class TelnetConnection : IDisposable

    {

        TcpClient m_Client;

        NetworkStream m_Stream;

        bool m_IsOpen = false;

        string m_Hostname;

        int m_ReadTimeout = 1000; // ms

        public delegate void ConnectionDelegate();

        public event ConnectionDelegate Opened;

        public event ConnectionDelegate Closed;

        public bool IsOpen { get { return m_IsOpen; } }

        public TelnetConnection() { }

        public TelnetConnection(bool open) : this("localhost", true) { }

        public TelnetConnection(string host, bool open)

        {

            if (open)

                Open(host);

        }

        void CheckOpen()

        {

            if (!IsOpen)

                throw new Exception("Connection not open.");

        }

        public string Hostname

        {

            get { return m_Hostname; }

        }

        public int ReadTimeout

        {

            set { m_ReadTimeout = value; if (IsOpen) m_Stream.ReadTimeout = value; }

            get { return m_ReadTimeout; }

        }

        public void Write(string str)

        {

            //FieldFox Programming Guide 6

            CheckOpen();

            byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(str);

            m_Stream.Write(bytes, 0, bytes.Length);

            m_Stream.Flush();

        }

        public void WriteLine(string str)

        {

            CheckOpen();

            byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(str);

            m_Stream.Write(bytes, 0, bytes.Length);

            WriteTerminator();

        }

        void WriteTerminator()

        {

            byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes("\r\n\0");

            m_Stream.Write(bytes, 0, bytes.Length);

            m_Stream.Flush();

        }

        public string Read()

        {

            CheckOpen();

            return System.Text.ASCIIEncoding.ASCII.GetString(ReadBytes());

        }

        /// <summary>

        /// Reads bytes from the socket and returns them as a byte[].

        /// </summary>

        /// <returns></returns>

        public byte[] ReadBytes()

        {

            int i = m_Stream.ReadByte();

            byte b = (byte)i;

            int bytesToRead = 0;

            var bytes = new List<byte>();

            if ((char)b == '#')

            {

                bytesToRead = ReadLengthHeader();

                if (bytesToRead > 0)

                {

                    i = m_Stream.ReadByte();

                    if ((char)i != '\n') // discard carriage return after length header.

                        bytes.Add((byte)i);

                }

            }

            if (bytesToRead == 0)

            {

                while (i != -1 && b != (byte)'\n')

                {

                    bytes.Add(b);

                    i = m_Stream.ReadByte();

                    b = (byte)i;

                }

            }

            else

            {

                int bytesRead = 0;

                while (bytesRead < bytesToRead && i != -1)

                {

                    i = m_Stream.ReadByte();

                    if (i != -1)

                    {

                        bytesRead++;

                        // record all bytes except \n if it is the last char.

                        if (bytesRead < bytesToRead || (char)i != '\n')

                            bytes.Add((byte)i);

                    }

                }

            }

            return bytes.ToArray();

        }

        int ReadLengthHeader()

        {

            int numDigits = Convert.ToInt32(new string(new char[] { (char)m_Stream.ReadByte() }));

            string bytes = "";

            for (int i = 0; i < numDigits; ++i)

                bytes = bytes + (char)m_Stream.ReadByte();

            return Convert.ToInt32(bytes);

        }

        public void Open(string hostname)

        {

            if (IsOpen)

                Close();

            m_Hostname = hostname;

            m_Client = new TcpClient(hostname, 5025);

            m_Stream = m_Client.GetStream();

            m_Stream.ReadTimeout = ReadTimeout;

            m_IsOpen = true;

            if (Opened != null)

                Opened();

        }

        public void Close()

        {

            if (!m_IsOpen)

                //FieldFox Programming Guide 7

                return;

            m_Stream.Close();

            m_Client.Close();

            m_IsOpen = false;

            if (Closed != null)

                Closed();

        }

        public void Dispose()

        {

            Close();

        }

    }

#endregion

}