Example #1
0
 private void disposeDevice()
 {
     if (device != null)
     {
         device.Dispose();
         device = null;
     }
 }
            //Overriding basical device functionality

            /// <summary>
            /// Initializes the device
            /// </summary>
            /// <returns>Returns true, if initialization succeed</returns>
            public bool InitDevice()
            {
                try
                {
                    GPIB_KEITHLEY_2602A_Adderss = new NationalInstruments.NI4882.Address(_primaryAddress, _secondaryAddress);
                    GPIB_KEITHLEY_2602A_Device  = new NationalInstruments.NI4882.Device(_boardNumber, GPIB_KEITHLEY_2602A_Adderss);

                    GPIB_KEITHLEY_2602A_Device.Clear();

                    GPIB_KEITHLEY_2602A_Device.Write("beeper.enable = 1 ");

                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
        /// <summary>
        /// This method should be run after setSettings and setSequence to ensure sane data.
        /// </summary>
        /// <param name="listIterationNumber"></param>
        /// <returns></returns>
        public override BufferGenerationStatus generateBuffers(int listIterationNumber)
        {
            lock (remoteLockObj)
            {
                clientFinishedRun = false;

                lock (taskFinishTimeClicks)
                {
                    taskFinishTimeClicks.Clear();
                }

                expectedNumberOfSamplesGenerated = new Dictionary<string, long>();

                try
                {

                    messageLog(this, new MessageEvent("Stopping and cleaning up old tasks."));
                    if (!stopAndCleanupTasks())
                        return BufferGenerationStatus.Failed_Buffer_Underrun;

                    messageLog(this, new MessageEvent("Generating buffers."));
                    if (settings == null)
                    {
                        messageLog(this, new MessageEvent("Unable to generate buffers. Null settings."));
                        displayError();
                        return BufferGenerationStatus.Failed_Settings_Null;
                    }
                    if (sequence == null)
                    {
                        messageLog(this, new MessageEvent("Unable to generate buffers. Null sequence."));
                        displayError();
                        return BufferGenerationStatus.Failed_Sequence_Null;
                    }

                    // This is redundant.
                    sequence.ListIterationNumber = listIterationNumber;

                    #region Generate variable timebase FPGA task

                    if (serverSettings.UseOpalKellyFPGA)
                    {
                        fpgaTasks = new Dictionary<string, FpgaTimebaseTask>();
                        foreach (DeviceSettings fsettings in myServerSettings.myDevicesSettings.Values)
                        {
                            if (fsettings.IsFPGADevice)
                            {
                                if (fsettings.DeviceEnabled)
                                {
                                    if (fsettings.UsingVariableTimebase)
                                    {
                                        if (opalKellyDeviceNames.Contains(fsettings.DeviceName))
                                        {
                                            messageLog(this, new MessageEvent("Creating Variable Timebase Task on fpga device " + fsettings.DeviceName + "."));
                                            int nSegs = 0;
                                            FpgaTimebaseTask ftask = new FpgaTimebaseTask(fsettings,
                                                opalKellyDevices[opalKellyDeviceNames.IndexOf(fsettings.DeviceName)],
                                                sequence,
                                                Common.getPeriodFromFrequency(fsettings.SampleClockRate),
                                                out nSegs,
                                                myServerSettings.UseFpgaRfModulatedClockOutput,
                                                myServerSettings.UseFpgaAssymetricDutyCycleClocking);
                                            fpgaTasks.Add(fsettings.DeviceName, ftask);
                                            messageLog(this, new MessageEvent("...Done (" + nSegs + " segments total)"));
                                        }
                                        else
                                        {
                                            messageLog(this, new MessageEvent("FPGA device " + fsettings.DeviceName + " is not programmed. Please press the refresh hardware button to program it. Or, if variable timebase on this device is not desired, set DeviceEnabled to false in this device's settings."));
                                            messageLog(this, new MessageEvent("Unable to create variable timebase output on FPGA device. Aborting buffer generation."));
                                            displayError();
                                            return BufferGenerationStatus.Failed_Invalid_Data;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    #endregion

                    #region Generate variable timebase clock output task

                    // If a variable timebase is to be generated by a NI digital output,
                    // then generate the variable timebase output task.
                    if (serverSettings.VariableTimebaseOutputChannel != null && serverSettings.VariableTimebaseOutputChannel != "")
                    {
                        messageLog(this, new MessageEvent("Generating Variable Timebase output clock buffer."));

                        bool otherChannelsOnVariableTimebaseDeviceAlsoUsed = false;
                        foreach (HardwareChannel hc in usedDigitalChannels.Values)
                        {
                            // if the digital channel for the variable timebase is also bound to a logical channel,
                            // complain
                            if (hc.physicalChannelName().ToUpper() == serverSettings.VariableTimebaseOutputChannel)
                            {
                                messageLog(this, new MessageEvent("The variable timebase clock output channel also has a sequence-specified channel bound to it. This is not allowed."));
                                displayError();
                                return BufferGenerationStatus.Failed_Invalid_Data;
                            }

                            // detect if the variable timebase output channel is on a device which also has other
                            // used digital channels.
                            if (hc.DeviceName.ToUpper() == HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(serverSettings.VariableTimebaseOutputChannel).ToUpper())
                            {
                                otherChannelsOnVariableTimebaseDeviceAlsoUsed = true;
                            }
                        }

                        // if the variable timebase output is on the same
                        // device as other digital output channels,
                        // then create the variable timebase task
                        // with the fancy function that can create a shared buffer
                        // for the variable timebase and for the digital output.
                        // Otherwise, use the simpler function which cannot.
                        // NOTE: The above comment is currently incorrect. The variable timebase output
                        // cannot currently exist on the same task as other used channels. Atticus will
                        // complain in a descriptive way if this is attempted.
                        if (otherChannelsOnVariableTimebaseDeviceAlsoUsed)
                        {

                            string variableTimebaseOutputDevice = HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(serverSettings.VariableTimebaseOutputChannel);

                            if (!variableTimebaseOutputDevice.Contains("Dev"))
                            {
                                messageLog(this, new MessageEvent("******* You are using a NI device named " + variableTimebaseOutputDevice + ". This does not follow the convention of naming your devices Dev1, Dev2, Dev3, etc. Unpredictable results are possible! Not recommended! *******"));
                                displayError();
                            }

                            // NOTE! This call will modify useDigitalChannels. Those digital channels which
                            // get their buffers generated within this task will be removed. This is useful,
                            // because we may later in generateBuffers() do another
                            // call to generate another task on this device, but
                            // we want that call to only generate buffers for the remaining digital channels.

                            int nDigitals = usedDigitalChannels.Count;

                            if (myServerSettings.myDevicesSettings.ContainsKey(variableTimebaseOutputDevice))
                            {
                                messageLog(this, new MessageEvent("Variable timebase output device [" + variableTimebaseOutputDevice + "]"));

                                variableTimebaseClockTask = DaqMxTaskGenerator.createDaqMxDigitalOutputAndVariableTimebaseSource(
                                    serverSettings.VariableTimebaseOutputChannel,
                                    null,
                                    serverSettings.VariableTimebaseMasterFrequency,
                                    sequence,
                                    serverSettings.VariableTimebaseType,
                                    variableTimebaseOutputDevice,
                                    serverSettings.myDevicesSettings[variableTimebaseOutputDevice],
                                    settings,
                                    usedDigitalChannels,
                                    serverSettings);
                            }
                            else
                            {
                                messageLog(this, new MessageEvent("***** Server does not contain device named " + variableTimebaseOutputDevice));
                                displayError();
                                return BufferGenerationStatus.Failed_Invalid_Data;
                            }

                            variableTimebaseClockTask.Done += new TaskDoneEventHandler(aTaskFinished);

                            int consumedChannels = nDigitals - usedDigitalChannels.Count;
                            messageLog(this, new MessageEvent(consumedChannels.ToString() + " output buffers also generated. Note, buffer generation on device " + variableTimebaseOutputDevice + " may skip due to no additional channels."));
                        }
                        else
                        {

                            string variableTimebaseOutputDevice = HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(serverSettings.VariableTimebaseOutputChannel);

                            if (myServerSettings.myDevicesSettings.ContainsKey(variableTimebaseOutputDevice))
                            {
                                messageLog(this, new MessageEvent("Variable timebase output device [" + variableTimebaseOutputDevice + "]"));

                                variableTimebaseClockTask = DaqMxTaskGenerator.createDaqMxVariableTimebaseSource(
                                    serverSettings.VariableTimebaseOutputChannel,
                                    serverSettings.VariableTimebaseMasterFrequency,
                                    sequence,
                                    serverSettings.VariableTimebaseType,
                                    serverSettings,
                                    serverSettings.myDevicesSettings[variableTimebaseOutputDevice]);
                            }
                            else
                            {
                                messageLog(this, new MessageEvent("***** Server does not contain device named " + variableTimebaseOutputDevice));
                                displayError();
                                return BufferGenerationStatus.Failed_Invalid_Data;
                            }

                            variableTimebaseClockTask.Done += new TaskDoneEventHandler(aTaskFinished);
                        }

                        try
                        {

                            messageLog(this, new MessageEvent("Variable timebase output clock buffer generated successfully. " + variableTimebaseClockTask.Stream.Buffer.OutputBufferSize + " samples per channel. On board buffer size: " + variableTimebaseClockTask.Stream.Buffer.OutputOnBoardBufferSize + " samples per channel."));
                        }
                        catch (Exception)
                        {
                            messageLog(this, new MessageEvent("Unable to poll task for buffer information. This is probably not a problem."));
                        }
                    }
                    else
                    {
                        variableTimebaseClockTask = null;
                    }

                    #endregion

                    #region Analog and Digital NI device generation (daqMx)

                    /// Is multi-threaded buffer generation enabled?
                    if (!serverSettings.UseMultiThreadedDaqmxBufferGeneration)
                    {
                        // if not, generate each buffer sequentially, in this thread.
                        foreach (string dev in usedDaqMxDevices)
                        {
                            if (!dev.Contains("Dev"))
                            {
                                messageLog(this, new MessageEvent("******* You are using a NI device named " + dev + ". This does not follow the convention of naming your devices Dev1, Dev2, Dev3, etc. Unpredictable results are possible! Not recommended! *******"));
                                displayError();
                            }

                            generateDaqMxTaskOnDevice(dev);
                        }
                    }
                    else
                    {
                        // if yes, generate each buffer in a parallel thread.

                        List<Thread> generateThreads = new List<Thread>();
                        try
                        {

                            messageLog(this, new MessageEvent("Generating buffers in parallel..."));
                            foreach (string dev in usedDaqMxDevices)
                            {
                                if (!dev.Contains("Dev"))
                                {
                                    messageLog(this, new MessageEvent("******* You are using a NI device named " + dev + ". This does not follow the convention of naming your devices Dev1, Dev2, Dev3, etc. Unpredictable results are possible! Not recommended! *******"));
                                    displayError();
                                }
                                Thread thread = new Thread(generateDaqMxTaskOnDevice);
                                generateThreads.Add(thread);

                                thread.Start(dev);
                            }
                            // wait for threads to all complete.

                            foreach (Thread thread in generateThreads)
                            {
                                thread.Join();
                            }
                            messageLog(this, new MessageEvent("...done."));
                        }
                        finally
                        {
                            foreach (Thread thread in generateThreads)
                            {
                                thread.Abort();
                            }
                        }

                    }

                    #endregion

                    // This is where the analog input task is defined
                    #region Analog In Task

                    //First we determine if an analog in task should be created
                    foreach (DeviceSettings ds in AtticusServer.server.serverSettings.myDevicesSettings.Values)
                    {
                        analogInCardDetected |= (ds.DeviceDescription.Contains("6259") || ds.DeviceDescription.Contains("6363")) && ds.AnalogInEnabled; // program will also support PXIe-6363 cards
                    }

                    if (analogInCardDetected)
                    {
                        // Creates the analog in task
                        analogS7ReadTask = new Task();
                        analogS7ReadTask.SynchronizeCallbacks = false;
                        analog_in_names = new List<string>();
                        // bool isUsed; // adareau : now obsolete

                        #region Old Code
                       // // Obtains a list of the analog in channels to be included in the task, and their name
                       // AnalogInChannels the_channels = AtticusServer.server.serverSettings.AIChannels[0];
                       // AnalogInNames the_names = AtticusServer.server.serverSettings.AINames[0];

                       //// We use part of the channels as single ended, and part as differential. He channels are added here. The task is created on Slot 7. This shouldn't be hard coded and will be changed.
                       // #region Single ended
                       // for (int analog_index = 0; analog_index < 10; analog_index++)
                       // {
                       //     PropertyInfo the_channel = the_channels.GetType().GetProperty("AS" + analog_index.ToString());
                       //     isUsed = (bool)the_channel.GetValue(the_channels, null);
                       //     if (isUsed)
                       //     {
                       //         if (analog_index < 5)
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + analog_index.ToString(), "",
                       //                 AITerminalConfiguration.Nrse, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         else
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + (analog_index + 3).ToString(), "",
                       //                 AITerminalConfiguration.Nrse, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         string theName = (string)(the_names.GetType().GetProperty("AS" + analog_index.ToString()).GetValue(the_names, null));
                       //         if (theName == "")
                       //             analog_in_names.Add("AIS" + analog_index.ToString());
                       //         else
                       //             analog_in_names.Add(theName);
                       //     }
                       // }
                       // #endregion

                       // #region Differential
                       // for (int analog_index = 0; analog_index < 11; analog_index++)
                       // {
                       //     PropertyInfo the_channel = the_channels.GetType().GetProperty("AD" + NamingFunctions.number_to_string(analog_index, 2));
                       //     isUsed = (bool)the_channel.GetValue(the_channels, null);

                       //     if (isUsed)
                       //     {
                       //         if (analog_index < 3)
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + (analog_index + 5).ToString(), "",
                       //                 AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         else
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + (analog_index + 13).ToString(), "",
                       //                 AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         string theName = (string)(the_names.GetType().GetProperty("AD" + NamingFunctions.number_to_string(analog_index, 2)).GetValue(the_names, null));
                       //         if (theName == "")
                       //             analog_in_names.Add("AID" + analog_index.ToString());
                       //         else
                       //             analog_in_names.Add(theName);
                       //     }
                       // }
                       // #endregion

                        #endregion

                        #region New Code

                        List<AnalogInChannels> channels_list = AtticusServer.server.serverSettings.AIChannels;

                        foreach (AnalogInChannels aiChannel in channels_list)
                        {
                            if (aiChannel.UseChannel)
                            {
                                if (aiChannel.AnalogInChannelType == AnalogInChannels.AnalogInChannelTypeList.SingleEnded)
                                {
                                    analogS7ReadTask.AIChannels.CreateVoltageChannel(AtticusServer.server.serverSettings.AIDev + "/" + aiChannel.ChannelName, "",
                                      AITerminalConfiguration.Nrse, -10, 10, AIVoltageUnits.Volts);
                                }

                                else if (aiChannel.AnalogInChannelType == AnalogInChannels.AnalogInChannelTypeList.Differential)
                                {
                                    analogS7ReadTask.AIChannels.CreateVoltageChannel(AtticusServer.server.serverSettings.AIDev + "/" + aiChannel.ChannelName, "",
                                     AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                                }

                                string theName = aiChannel.SaveName;
                                analog_in_names.Add(theName);

                            }

                        }

                        #endregion

                        // Configure timing specs of the analog In task. Again these things shouldn't be hard coded and will be changed
                        analogS7ReadTask.Timing.ConfigureSampleClock("", (double)(AtticusServer.server.serverSettings.AIFrequency), SampleClockActiveEdge.Rising,
                            SampleQuantityMode.FiniteSamples, sequence.nSamples(1 / ((double)(AtticusServer.server.serverSettings.AIFrequency))));

                        //analogS7ReadTask.Timing.ReferenceClockSource = "/PXI1Slot7/PXI_Trig7"; // adareau : with my configuration, declaring a ReferenceClockSource was generating errors. I remove this for now...

                        if (AtticusServer.server.serverSettings.UseAITaskTriggering) //AD
                        {

                            DigitalEdgeStartTriggerEdge triggerEdge = DigitalEdgeStartTriggerEdge.Rising;  // AD : see below
                            analogS7ReadTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(AtticusServer.server.serverSettings.AITriggerSource, triggerEdge); // AD : to fix synchronization problem between analog in and output tasks, I trigger
                                                                                                                                                                 //  the analog in task, using the variable timebase source signal (available on PXI_Trig0)
                                                                                                                                                                 // the task starts with the first signal sent by the VT source...
                        }
                        analogS7ReadTask.Timing.ReferenceClockRate = 20000000;
                        analogS7ReadTask.Stream.Timeout = Convert.ToInt32(sequence.SequenceDuration * 1000) + 10000;

                        reader_analog_S7 = new AnalogMultiChannelReader(analogS7ReadTask.Stream);

                    }
                    #endregion

                    #region Watchdog Timer stuff -- NOT FINISHED YET, THUS COMMENTED OUT

                    if (serverSettings.UseWatchdogTimerMonitoringTask)
                    {
                        messageLog(this, new MessageEvent("Watchdog Timer tasks no longer supported. Ignoring serverSettings.UseWatchdogTimerMonitoringTask"));
                        /*
                        if (daqMxTasks.ContainsKey(serverSettings.DeviceToSyncSoftwareTimedTasksTo))
                        {
                            messageLog(this, new MessageEvent("Creating watchdog timer monitoring task"));
                            WatchdogTimerTask wtask = new WatchdogTimerTask(sequence, myServerSettings.myDevicesSettings[serverSettings.DeviceToSyncSoftwareTimedTasksTo].SampleClockRate, daqMxTasks[serverSettings.DeviceToSyncSoftwareTimedTasksTo], .2);
                        }
                        else
                        {
                            messageLog(this, new MessageEvent("Unable to create watchdog timer monitoring task, since the hardware-timed device it was to be synched to is not being used. Continuing without watchdog."));
                        }*/
                    }

                    #endregion

                    #region GPIB device and masquerading gpib channels (like rfsg channels)

                    foreach (int gpibID in usedGpibChannels.Keys)
                    {
                        HardwareChannel gpibChannel = usedGpibChannels[gpibID];
                        if (!gpibChannel.gpibMasquerade)
                        {
                            messageLog(this, new MessageEvent("Generating gpib buffer for gpib ID " + gpibID));

                            NationalInstruments.NI4882.Device gpibDevice = new NationalInstruments.NI4882.Device(
                                gpibChannel.gpibBoardNumber(),
                                new NationalInstruments.NI4882.Address(gpibChannel.GpibAddress.PrimaryAddress, gpibChannel.GpibAddress.SecondaryAddress));
                            GpibTask gpibTask = new GpibTask(gpibDevice);
                            gpibTask.generateBuffer(sequence, myServerSettings.myDevicesSettings[gpibChannel.DeviceName],
                                gpibChannel, gpibID, myServerSettings.GpibRampConverters);
                            gpibTask.Done += new TaskDoneEventHandler(aTaskFinished);
                            gpibTasks.Add(gpibChannel, gpibTask);
                            messageLog(this, new MessageEvent("Done."));

                        }
                        else
                        {
                            switch (gpibChannel.myGpibMasqueradeType)
                            {
                                case HardwareChannel.GpibMasqueradeType.NONE:
                                    messageLog(this, new MessageEvent("********** Error. GPIB channel with ID " + gpibID + " has its masquerading bit set to true, but has its masquerading type set to NONE. **********"));
                                    displayError();
                                    break;
                                case HardwareChannel.GpibMasqueradeType.RFSG:
                                    messageLog(this, new MessageEvent("Generating RFSG buffer for gpib ID " + gpibID));
                                    RfsgTask rftask = new RfsgTask(sequence, settings, gpibID, gpibChannel.DeviceName, serverSettings.myDevicesSettings[gpibChannel.DeviceName]);
                                    rftask.Done += new TaskDoneEventHandler(aTaskFinished);
                                    rfsgTasks.Add(gpibChannel, rftask);
                                    messageLog(this, new MessageEvent("Done."));
                                    break;
                            }
                        }
                    }

                    #endregion

                    #region RS 232 Devices
                    foreach (int rs232ID in usedRS232Channels.Keys)
                    {
                        if (sequence.rs232ChannelUsed(rs232ID))
                        {
                            messageLog(this, new MessageEvent("Generating rs232 buffer for rs232 ID " + rs232ID));
                            HardwareChannel hc = usedRS232Channels[rs232ID];
                            //NationalInstruments.VisaNS.SerialSession device = new NationalInstruments.VisaNS.SerialSession(hc.ChannelName);

                            NationalInstruments.VisaNS.SerialSession device;

                            try
                            {
                                device = getSerialSession(hc);
                            }
                            catch (Exception e)
                            {
                                messageLog(this, new MessageEvent("Caught exception when attempting to open serial device for rs232 channel #" + rs232ID + ". Exception: " + e.Message + e.StackTrace));
                                return BufferGenerationStatus.Failed_Out_Of_Memory;
                            }

                            //                NationalInstruments.VisaNS.RegisterBasedSession device = (NationalInstruments.VisaNS.RegisterBasedSession) NationalInstruments.VisaNS.ResourceManager.GetLocalManager().Open(hc.ChannelName);

                            RS232Task rs232task = new RS232Task(device);
                            rs232task.generateBuffer(sequence, myServerSettings.myDevicesSettings["Serial"], hc, rs232ID);
                            rs232task.Done += new TaskDoneEventHandler(aTaskFinished);
                            rs232Tasks.Add(hc, rs232task);
                            messageLog(this, new MessageEvent("Done."));
                        }
                        else
                        {
                            messageLog(this, new MessageEvent("Skipping rs232 channel ID " + rs232ID + ", that channel is not used in this sequence."));
                        }
                    }

                    #endregion

                    makeTerminalConnections();

                    // Try to clean up as much memory as possible so that there wont be any garbage collection
                    // during the run. Suspect that GCs during the run may be the cause of sporadic buffer underruns.
                    // Note: This is likely wrong. Most of these buffer underruns were eventually fixed with the
                    // data transfer mechanism tweaks described in the user manual. However, no harm in doing some
                    // GC here.
                    System.GC.Collect();
                    System.GC.Collect();
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();

                    messageLog(this, new MessageEvent("Buffers generated succesfully."));

                    return BufferGenerationStatus.Success;

                }
                catch (Exception e)
                {
                    messageLog(this, new MessageEvent("Failed buffer generation due to exception: " + e.Message + "\n" + e.StackTrace));
                    displayError();
                    return BufferGenerationStatus.Failed_Invalid_Data;
                }
            }
        }
        /// <summary>
        /// This method is to be called on the server side, and is not open to use via remoting. Its purpose
        /// is to update the servers internal list of hardware channels by querying the National Instruments drivers.
        /// </summary>
        public void refreshHardwareLists()
        {
            System.Console.WriteLine("Running refreshHardwareLists()...");

            try
            {

                // Set all the devices to disconnected. They will be set back to connected if they are detecter later in this method.
                foreach (DeviceSettings ds in serverSettings.myDevicesSettings.Values)
                    ds.deviceConnected = false;

                myHardwareChannels = new List<HardwareChannel>();

                //List of string identifiers for all devices detected in the process.
                detectedDevices = new List<string>();

                Dictionary<string, string> myDeviceDescriptions = new Dictionary<string, string>();

                // Detect National Instruments analog and digital channels.

                #region detect NI analog and digital  (daqMx)

                System.Console.WriteLine("Accessing DaqSystem devices list...");

                DaqSystem daqSystem = DaqSystem.Local;
                string[] devices = daqSystem.Devices;

                System.Console.WriteLine("...done.");

                System.Console.WriteLine("Found " + devices.Length.ToString() + " devices.");

                bool niDaqDevicesExistThatAreNotNamedDevSomething = false;

                for (int i = 0; i < devices.Length; i++)
                {
                    if (!devices[i].ToUpper().Contains("DEV"))
                    {
                        niDaqDevicesExistThatAreNotNamedDevSomething = true;
                    }

                    System.Console.WriteLine("Querying device " + i + "...");

                    detectedDevices.Add(devices[i]);

                    Device device = daqSystem.LoadDevice(devices[i]);

                    myDeviceDescriptions.Add(devices[i], device.ProductType);
                    string[] analogs = device.AOPhysicalChannels;
                    string[] digitalLines = device.DOLines;

                    if (!serverSettings.myDevicesSettings.ContainsKey(devices[i]))
                    {
                        serverSettings.myDevicesSettings.Add(devices[i], new DeviceSettings(devices[i], myDeviceDescriptions[devices[i]]));
                    }

                    // Special case: 6259 cards use 32-bit wide ports instead of 16 bit wide.
                    if (myDeviceDescriptions[devices[i]].Contains("6259"))
                    {
                        serverSettings.myDevicesSettings[devices[i]].use32BitDigitalPorts = true;
                    }

                    // Add all the analog channels, but only if the device settings say this card is enabled

                    if (serverSettings.myDevicesSettings.ContainsKey(devices[i]) && serverSettings.myDevicesSettings[devices[i]].DeviceEnabled)
                    {

                        if (serverSettings.myDevicesSettings[devices[i]].AnalogChannelsEnabled)
                        {
                            for (int j = 0; j < analogs.Length; j++)
                            {
                                string channelName = justTheChannelName(analogs[j], devices[i]);
                                HardwareChannel hc = new HardwareChannel(this.myServerSettings.ServerName, devices[i], channelName, HardwareChannel.HardwareConstants.ChannelTypes.analog);
                                if (!serverSettings.ExcludedChannels.Contains(hc))
                                {
                                    myHardwareChannels.Add(hc);
                                }
                            }
                        }

                        if (serverSettings.myDevicesSettings[devices[i]].DigitalChannelsEnabled)
                        {
                            for (int j = 0; j < digitalLines.Length; j++)
                            {
                                string channelName = justTheChannelName(digitalLines[j], devices[i]);
                                HardwareChannel hc = new HardwareChannel(this.myServerSettings.ServerName, devices[i], channelName, HardwareChannel.HardwareConstants.ChannelTypes.digital);
                                if (!serverSettings.ExcludedChannels.Contains(hc))
                                {
                                    myHardwareChannels.Add(hc);
                                }
                            }
                        }
                    }

                    System.Console.WriteLine("...done.");

                }

                #endregion

                #region "detect" RFSG cards

                foreach (ServerSettings.rfsgDeviceName rfsgDevName in serverSettings.RfsgDeviceNames)
                {

                    System.Console.WriteLine("Querying RFSG devices...");

                    string devName = rfsgDevName.DeviceName;
                    HardwareChannel hc = new HardwareChannel(serverSettings.ServerName, devName, "rf_out", HardwareChannel.HardwareConstants.ChannelTypes.gpib);
                    hc.gpibMasquerade = true;
                    hc.myGpibMasqueradeType = HardwareChannel.GpibMasqueradeType.RFSG;

                    myHardwareChannels.Add(hc);

                    if (!serverSettings.myDevicesSettings.ContainsKey(devName))
                    {
                        DeviceSettings devSettings = new DeviceSettings(devName, "RFSG driver library signal generator");
                        serverSettings.myDevicesSettings.Add(devName, devSettings);
                    }

                    System.Console.WriteLine("...done.");

                }

                #endregion

                #region detect NI GBIB

                // try a maxumimum of 10 GPIB boards... this is a totally arbitrary number.
                for (int i = 0; i < 10; i++)
                {

                    System.Console.WriteLine("Querying or detecting GPIB Board Number " + i + "...");

                    try
                    {
                        NationalInstruments.NI4882.Board board = new NationalInstruments.NI4882.Board(i);
                        board.SendInterfaceClear();
                        //              board.BecomeActiveController(false);
                        NationalInstruments.NI4882.AddressCollection listeners = board.FindListeners();

                        if (listeners.Count != 0)
                        {
                            foreach (NationalInstruments.NI4882.Address address in listeners)
                            {

                                int wait_delay = 100;

                                try
                                {
                                    NationalInstruments.NI4882.Device dev = new NationalInstruments.NI4882.Device(i, address);
                                    dev.Clear();

                                    // ask the device for its identity
                                    Action<string> writeDelegate = new Action<string>(dev.Write);
                                    IAsyncResult result = writeDelegate.BeginInvoke("*IDN?\n", null, null);
                                    result.AsyncWaitHandle.WaitOne(wait_delay, true);

                                    if (!result.IsCompleted)
                                    {
                                        messageLog(this, new MessageEvent("GPIB device took longer than " + wait_delay + " ms to respond to id request. Aborting."));
                                        dev.AbortAsynchronousIO();
                                        continue;
                                    }

                                    string deviceDescription = dev.ReadString();

                                    string deviceName = "GPIB" + i + "/" + gpibAddressToShortString(address);
                                    detectedDevices.Add(deviceName);

                                    myDeviceDescriptions.Add(deviceName, deviceDescription);

                                    HardwareChannel.HardwareConstants.GPIBDeviceType gpibDeviceType = new HardwareChannel.HardwareConstants.GPIBDeviceType();

                                    // VERY IMPORTANT!!!!!!!!!!
                                    // *******************  THIS IS WHERE YOU ADD DEVICE-DETECTION CODE FOR NEW GPIB DEVICES *********************/
                                    // detect the gpib device type
                                    if (deviceDescription.Contains("ESG-4000B"))
                                    {
                                        gpibDeviceType = HardwareChannel.HardwareConstants.GPIBDeviceType.Agilent_ESG_SIG_Generator;
                                    }
                                    // place any other device type detection code here as else ifs.
                                    else if (deviceDescription.Contains("N5181"))
                                    {
                                        gpibDeviceType = HardwareChannel.HardwareConstants.GPIBDeviceType.Agilent_ESG_SIG_Generator;
                                    }
                                    else
                                    {
                                        gpibDeviceType = HardwareChannel.HardwareConstants.GPIBDeviceType.Unknown;
                                    }

                                    HardwareChannel hc = new HardwareChannel(this.myServerSettings.ServerName,
                                        deviceName,
                                        gpibAddressToShortString(address),
                                        deviceDescription,
                                        HardwareChannel.HardwareConstants.ChannelTypes.gpib, dsAddress(address), gpibDeviceType);
                                    if (!serverSettings.ExcludedChannels.Contains(hc))
                                    {
                                        myHardwareChannels.Add(hc);
                                    }
                                }
                                catch (Exception e)
                                {
                                    messageLog(this, new MessageEvent("Exception when attempting to communicate with GPIB device " + "GPIB" + i + "/" + gpibAddressToShortString(address) + ". " + e.Message + "\n" + e.StackTrace));
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        // throw e;
                    }

                    System.Console.WriteLine("...done.");

                }

                /*
                NationalInstruments.NI4882.Board board = new NationalInstruments.NI4882.Board();
                board.FindListeners(
                */

                #endregion

                #region Detect NI RS232 ports

                System.Console.WriteLine("Querying NI VisaNS Serial Resources...");

                string[] resourceNames = null;
                NationalInstruments.VisaNS.ResourceManager VisaRescources = null;

                System.Console.WriteLine("...done.");

                try
                {
                    VisaRescources = NationalInstruments.VisaNS.ResourceManager.GetLocalManager();
                    resourceNames = VisaRescources.FindResources("/?*");
                }
                catch (Exception e)
                {
                    if (messageLogHandler != null)
                    {
                        messageLogHandler(this, new MessageEvent("Caught exception when attempting to detect serial ports: " + e.Message + e.StackTrace));
                    }
                    else
                    {
                        MessageBox.Show("Caught exception when attempting to detect serial ports: " + e.Message + e.StackTrace);
                    }
                }

                if (resourceNames != null)
                {

                    foreach (string s in resourceNames)
                    {

                        try
                        {

                            System.Console.WriteLine("Querying Resource " + s);

                            NationalInstruments.VisaNS.HardwareInterfaceType hType;
                            short chanNum;
                            VisaRescources.ParseResource(s, out hType, out chanNum);
                            if (hType == NationalInstruments.VisaNS.HardwareInterfaceType.Serial)
                            {
                                NationalInstruments.VisaNS.SerialSession ss = (NationalInstruments.VisaNS.SerialSession)NationalInstruments.VisaNS.ResourceManager.GetLocalManager().Open(s);

                                string description = ss.HardwareInterfaceName;

                                HardwareChannel hc = new HardwareChannel(this.serverSettings.ServerName, "Serial", s, description, HardwareChannel.HardwareConstants.ChannelTypes.rs232);
                                if (!serverSettings.ExcludedChannels.Contains(hc))
                                {
                                    MyHardwareChannels.Add(hc);
                                }
                                if (!detectedDevices.Contains("Serial"))
                                {
                                    detectedDevices.Add("Serial");
                                    myDeviceDescriptions.Add("Serial", "All local RS232 devices.");
                                }

                                ss.Dispose();

                            }
                        }
                        catch (Exception e)
                        {
                            System.Console.WriteLine("Caught exception when attempting to query serial resource named " + s + ". Displaying exception and then skipping this device.");
                            ExceptionViewerDialog ev = new ExceptionViewerDialog(e);
                            ev.ShowDialog();

                        }

                        System.Console.WriteLine("...done.");
                    }
                }

                #endregion

                // If necessary, add DeviceSettings entries for devices.
                foreach (string device in detectedDevices)
                {
                    // If this device does not already have a settings object...
                    if (!myServerSettings.myDevicesSettings.ContainsKey(device))
                    {
                        myServerSettings.myDevicesSettings.Add(device,
                            new DeviceSettings(device, myDeviceDescriptions[device]));
                    }
                    else
                    {
                        myServerSettings.myDevicesSettings[device].deviceConnected = true;
                    }
                }

                #region FPGA Detection and configuration

                if (this.serverSettings.UseOpalKellyFPGA)
                {
                    try
                    {
                        System.Console.WriteLine("Scanning for Opal Kelly FPGA devices...");

                        opalKellyDevices = new List<com.opalkelly.frontpanel.okCFrontPanel>();
                        opalKellyDeviceNames = new List<string>();

                        com.opalkelly.frontpanel.okCFrontPanel ok = new com.opalkelly.frontpanel.okCFrontPanel();
                        int fpgaDeviceCount = ok.GetDeviceCount();

                        System.Console.WriteLine("Found " + fpgaDeviceCount + " fpga device(s).");

                        for (int i = 0; i < fpgaDeviceCount; i++)
                        {
                            string name = ok.GetDeviceListSerial(i);
                            com.opalkelly.frontpanel.okCFrontPanel fpgaDevice = new com.opalkelly.frontpanel.okCFrontPanel();

                            com.opalkelly.frontpanel.okCFrontPanel.ErrorCode errorCode;

                            errorCode = fpgaDevice.OpenBySerial(name);

                            if (errorCode != com.opalkelly.frontpanel.okCFrontPanel.ErrorCode.NoError)
                            {
                                System.Console.WriteLine("Unable to open FPGA device " + name + " due to error code " + errorCode.ToString());
                                continue;
                            }

                            if (!this.detectedDevices.Contains(name))
                            {
                                this.detectedDevices.Add(name);
                            }

                            if (!myServerSettings.myDevicesSettings.ContainsKey(name))
                            {
                                DeviceSettings newSettings = new DeviceSettings(name, "Opal Kelly FPGA Device");
                                newSettings.deviceConnected = true;
                                newSettings.isFPGADevice = true;
                                myServerSettings.myDevicesSettings.Add(name, newSettings);
                            }
                            else
                            {
                                myServerSettings.myDevicesSettings[name].deviceConnected = true;
                            }

                            bool deviceProgrammed = false;

                            if (myServerSettings.myDevicesSettings[name].DeviceEnabled)
                            {
                                if (myServerSettings.myDevicesSettings[name].UsingVariableTimebase)
                                {
                                    deviceProgrammed = true;
                                    if (myServerSettings.myDevicesSettings[name].MySampleClockSource == DeviceSettings.SampleClockSource.DerivedFromMaster)
                                    {
                                        errorCode = fpgaDevice.ConfigureFPGA("variable_timebase_fpga_internal.bit");
                                    }
                                    else
                                    {
                                        errorCode = fpgaDevice.ConfigureFPGA("variable_timebase_fpga_external.bit");
                                    }

                                    if (errorCode == com.opalkelly.frontpanel.okCFrontPanel.ErrorCode.NoError)
                                    {

                                        System.Console.WriteLine("Programmed fpga device " + name + ". Used fpga code version based on sample clock source " + myServerSettings.myDevicesSettings[name].MySampleClockSource.ToString());

                                        opalKellyDeviceNames.Add(name);
                                        opalKellyDevices.Add(fpgaDevice);
                                    }
                                    else
                                    {
                                        System.Console.WriteLine("Error when attempting to program fpga device, error code " + errorCode.ToString());
                                    }
                                }
                            }
                            if (!deviceProgrammed)
                                System.Console.WriteLine("Fpga device " + name + " not programmed, as it is not enable or varible timebase on that device is not enabled.");

                        }
                    }
                    catch (Exception e)
                    {
                        if (e.InnerException != null && e.InnerException.InnerException != null)
                        {
                            Exception innerInner = e.InnerException.InnerException;
                            if (innerInner is System.BadImageFormatException)
                            {
                                MessageBox.Show("You are probably running the wrong build of Atticus. As of version 1.56 Atticus now comes in a 64-bit or 32-bit versions (in the bin\\Release-x64 and bin\\Release-x86 subdirectories respectively). These builds make use of different versions of the Opal Kelly Frontpanel libraries. Please ensure you are using the correct Atticus build. The exception which gave rise to this error will now be displayed.", "Wrong build of Atticus?");
                                DataStructures.ExceptionViewerDialog dial = new ExceptionViewerDialog(e);
                                dial.ShowDialog();
                            }
                            else if (innerInner is System.DllNotFoundException)
                            {
                                MessageBox.Show("As of version 1.56, Atticus is now built to use the 4.0.8 version of the Opal Kelly Frontpanel libraries/drivers. Perhaps you have the wrong version of the libraries installed? You can find a driver-only installer for 4.0.8 in the \\Opal Kelly\\Opal Kelly 4.0.8\\ directory of the Cicero distribution. Please install the newer drivers from there, or contact Opal Kelly to receive a CD with the newest full Frontpanel distribution (or go to the download section of github page for the Cicero Word generator, and download and install Opal-Kelly-CD-4.0.8.zip. You may also need to plug an Opal Kelly device into this computer during installation of the drivers, to insure that the WINUSB windows subsystem gets installed. The exception which gave rise to this error will now be displayed.", "Wrong version of FrontPanel drivers installed?");
                                DataStructures.ExceptionViewerDialog dial = new ExceptionViewerDialog(e);
                                dial.ShowDialog();
                            }
                            else
                            {
                                MessageBox.Show("An unrecognized exception was encountered when scanning for Opal Kelly FPGA devices. The exception will now be displayed.", "Unrecognized exception.");
                                DataStructures.ExceptionViewerDialog dial = new ExceptionViewerDialog(e);
                                dial.ShowDialog();
                            }
                        }
                        else
                        {
                            MessageBox.Show("An unrecognized exception was encountered when scanning for Opal Kelly FPGA devices. The exception will now be displayed.", "Unrecognized exception.");
                            DataStructures.ExceptionViewerDialog dial = new ExceptionViewerDialog(e);
                            dial.ShowDialog();
                        }

                        System.Console.WriteLine("Caught exceptions when attempting to scan for Opal Kelly FPGA devices. Aborted FPGA scan.");
                        opalKellyDevices = null;

                    }
                }
                else
                {
                    System.Console.WriteLine("Opal Kelly FPGA not enabled, so not scanning for them.");
                    opalKellyDevices = null;
                }

                #endregion

                System.Console.WriteLine("...done running refreshHardwareLists().");

                if (niDaqDevicesExistThatAreNotNamedDevSomething)
                {
                    System.Console.WriteLine("!! NOTE !! Some NI devices were detected whose name does not follow the Dev1, Dev2, Dev3, naming convention. This will cause problems.");
                    MessageBox.Show("National Instruments cards were detected whose names do not corresponding to the Dev1, Dev2, Dev3, etc. naming convention. This convention is relied upon by Atticus. Not following this convention will cause problems when attempting to run sequences on these devices. Please use MAX (the NI-supplied program) to rename your NI devices to follow the convention.", "Invalid niDaq Device Names");
                }

            }
            catch (Exception e)
            {
                System.Console.WriteLine("Unhandled exception when scanning connected hardware. Displaying exception, and then continuing to attempt to start Atticus.");
                ExceptionViewerDialog ev = new ExceptionViewerDialog(e);
                ev.ShowDialog();
                MessageBox.Show("Atticus encountered an unhandled exception when scanning for connected hardware. Atticus will continue to run. It is unlikely to function correctly for driving outputs, but will allow you to edit your settings to disable whatever is causing the unhandled exception.");
            }
        }
        public override bool outputGPIBGroup(GPIBGroup gpibGroup, SettingsData settings)
        {
            lock (remoteLockObj)
            {
                try
                {
                    messageLog(this, new MessageEvent("Received an output gpib group request."));

                    if (gpibGroup == null)
                    {
                        messageLog(this, new MessageEvent("Received a null object, unable to comply."));
                        displayError();
                        return false;
                    }

                    if (!stopAndCleanupTasks())
                        return false;

                    if (!setSettings(settings))
                        return false;

                    foreach (int channelID in usedGpibChannels.Keys)
                    {
                        if (gpibGroup.channelEnabled(channelID))
                        {
                            HardwareChannel hc = usedGpibChannels[channelID];
                            GPIBGroupChannelData channelData = gpibGroup.ChannelDatas[channelID];
                            if (channelData.DataType == GPIBGroupChannelData.GpibChannelDataType.raw_string)
                            {
                                NationalInstruments.NI4882.Device gpibDevice = new NationalInstruments.NI4882.Device(hc.gpibBoardNumber(), niAddress(hc.GpibAddress));
                                gpibDevice.Write(
                                    GpibTask.AddNewlineCharacters(channelData.RawString));
                                messageLog(this, new MessageEvent("Wrote GPIB data : " + channelData.RawString));
                            }
                            else if (channelData.DataType == GPIBGroupChannelData.GpibChannelDataType.string_param_string)
                            {
                                NationalInstruments.NI4882.Device gpibDevice = new NationalInstruments.NI4882.Device(hc.gpibBoardNumber(), niAddress(hc.GpibAddress));
                                if (channelData.StringParameterStrings != null)
                                {
                                    foreach (StringParameterString sps in channelData.StringParameterStrings)
                                    {
                                        gpibDevice.Write(
                                            GpibTask.AddNewlineCharacters(sps.ToString()));
                                        messageLog(this, new MessageEvent("Wrote GPIB data : " + sps.ToString()));
                                    }
                                }
                            }
                            else
                            {
                                messageLog(this, new MessageEvent("Skipping channel " + channelID + ", unsupported data type for an Output Now request: " + channelData.DataType.ToString()));
                                displayError();
                            }
                        }
                    }
                    return true;
                }
                catch (Exception e)
                {
                    messageLog(this, new MessageEvent("Caught exception when attempting to output gpib group: " + e.Message + e.StackTrace));
                    displayError();
                    return false;
                }
            }
        }
Example #6
0
 public GpibTask(NationalInstruments.NI4882.Device device)
 {
     this.device = device;
 }
            //Overriding basical device functionality
            /// <summary>
            /// Initializes the device
            /// </summary>
            /// <returns>Returns true, if initialization succeed</returns>
            public bool InitDevice()
            {
                try
                {
                    GPIB_KEITHLEY_2602A_Adderss = new NationalInstruments.NI4882.Address(_primaryAddress, _secondaryAddress);
                    GPIB_KEITHLEY_2602A_Device = new NationalInstruments.NI4882.Device(_boardNumber, GPIB_KEITHLEY_2602A_Adderss);

                    GPIB_KEITHLEY_2602A_Device.Clear();

                    GPIB_KEITHLEY_2602A_Device.Write("beeper.enable = 1 ");

                    return true;
                }
                catch
                {
                    return false;
                }
            }
 public GpibTask(NationalInstruments.NI4882.Device device)
 {
     this.device = device;
 }
 private void disposeDevice()
 {
     if (device != null)
     {
         device.Dispose();
         device = null;
     }
 }